UNPKG

308 kBJavaScriptView Raw
1/*! @name @videojs/http-streaming @version 3.0.0-2 @license Apache-2.0 */
2!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("video.js"),require("@xmldom/xmldom")):"function"==typeof define&&define.amd?define(["exports","video.js","@xmldom/xmldom"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).httpStreaming={},e.videojs,e.window)}(this,(function(e,t,i){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=n(t),r={exports:{}};!function(e,t){!function(t){var i=/^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#[^]*)?$/,n=/^([^\/?#]*)([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var s=a.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");return s.path=a.normalizePath(s.path),a.buildURLFromParts(s)}var r=a.parseURL(t);if(!r)throw new Error("Error trying to parse relative URL.");if(r.scheme)return i.alwaysNormalize?(r.path=a.normalizePath(r.path),a.buildURLFromParts(r)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var d=n.exec(o.path);o.netLoc=d[1],o.path=d[2]}o.netLoc&&!o.path&&(o.path="/");var u={scheme:o.scheme,netLoc:r.netLoc,path:null,params:r.params,query:r.query,fragment:r.fragment};if(!r.netLoc&&(u.netLoc=o.netLoc,"/"!==r.path[0]))if(r.path){var l=o.path,h=l.substring(0,l.lastIndexOf("/")+1)+r.path;u.path=a.normalizePath(h)}else u.path=o.path,r.params||(u.params=o.params,r.query||(u.query=o.query));return null===u.path&&(u.path=i.alwaysNormalize?a.normalizePath(r.path):r.path),a.buildURLFromParts(u)},parseURL:function(e){var t=i.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(s,"");e.length!==(e=e.replace(r,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=a}()}(r);var a=r.exports,o="http://example.com",d=function(e,t){if(/^[a-z]+:/i.test(t))return t;/^data:/.test(e)&&(e=window.location&&window.location.href||"");var i="function"==typeof window.URL,n=/^\/\//.test(e),s=!window.location&&!/\/\//i.test(e);if(i?e=new window.URL(e,window.location||o):/\/\//i.test(e)||(e=a.buildAbsoluteURL(window.location&&window.location.href||"",e)),i){var r=new URL(t,e);return s?r.href.slice(o.length):n?r.href.slice(r.protocol.length):r.href}return a.buildAbsoluteURL(e,t)};const u=d,l=(e,t)=>t&&t.responseURL&&e!==t.responseURL?t.responseURL:e,h=e=>s.default.log.debug?s.default.log.debug.bind(s.default,"VHS:",`${e} >`):function(){};function c(){return c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n])}return e},c.apply(this,arguments)}var p=function(){function e(){this.listeners={}}var t=e.prototype;return t.on=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)},t.off=function(e,t){if(!this.listeners[e])return!1;var i=this.listeners[e].indexOf(t);return this.listeners[e]=this.listeners[e].slice(0),this.listeners[e].splice(i,1),i>-1},t.trigger=function(e){var t=this.listeners[e];if(t)if(2===arguments.length)for(var i=t.length,n=0;n<i;++n)t[n].call(this,arguments[1]);else for(var s=Array.prototype.slice.call(arguments,1),r=t.length,a=0;a<r;++a)t[a].apply(this,s)},t.dispose=function(){this.listeners={}},t.pipe=function(e){this.on("data",(function(t){e.push(t)}))},e}();function m(e){for(var t,i=(t=e,window.atob?window.atob(t):Buffer.from(t,"base64").toString("binary")),n=new Uint8Array(i.length),s=0;s<i.length;s++)n[s]=i.charCodeAt(s);return n}
3/*! @name m3u8-parser @version 6.0.0 @license Apache-2.0 */class f extends p{constructor(){super(),this.buffer=""}push(e){let t;for(this.buffer+=e,t=this.buffer.indexOf("\n");t>-1;t=this.buffer.indexOf("\n"))this.trigger("data",this.buffer.substring(0,t)),this.buffer=this.buffer.substring(t+1)}}const g=String.fromCharCode(9),y=function(e){const t=/([0-9.]*)?@?([0-9.]*)?/.exec(e||""),i={};return t[1]&&(i.length=parseInt(t[1],10)),t[2]&&(i.offset=parseInt(t[2],10)),i},_=function(e){const t={};if(!e)return t;const i=e.split(new RegExp('(?:^|,)((?:[^=]*)=(?:"[^"]*"|[^,]*))'));let n,s=i.length;for(;s--;)""!==i[s]&&(n=/([^=]*)=(.*)/.exec(i[s]).slice(1),n[0]=n[0].replace(/^\s+|\s+$/g,""),n[1]=n[1].replace(/^\s+|\s+$/g,""),n[1]=n[1].replace(/^['"](.*)['"]$/g,"$1"),t[n[0]]=n[1]);return t};class T extends p{constructor(){super(),this.customParsers=[],this.tagMappers=[]}push(e){let t,i;0!==(e=e.trim()).length&&("#"===e[0]?this.tagMappers.reduce(((t,i)=>{const n=i(e);return n===e?t:t.concat([n])}),[e]).forEach((e=>{for(let t=0;t<this.customParsers.length;t++)if(this.customParsers[t].call(this,e))return;if(0===e.indexOf("#EXT"))if(e=e.replace("\r",""),t=/^#EXTM3U/.exec(e),t)this.trigger("data",{type:"tag",tagType:"m3u"});else{if(t=/^#EXTINF:([0-9\.]*)?,?(.*)?$/.exec(e),t)return i={type:"tag",tagType:"inf"},t[1]&&(i.duration=parseFloat(t[1])),t[2]&&(i.title=t[2]),void this.trigger("data",i);if(t=/^#EXT-X-TARGETDURATION:([0-9.]*)?/.exec(e),t)return i={type:"tag",tagType:"targetduration"},t[1]&&(i.duration=parseInt(t[1],10)),void this.trigger("data",i);if(t=/^#EXT-X-VERSION:([0-9.]*)?/.exec(e),t)return i={type:"tag",tagType:"version"},t[1]&&(i.version=parseInt(t[1],10)),void this.trigger("data",i);if(t=/^#EXT-X-MEDIA-SEQUENCE:(\-?[0-9.]*)?/.exec(e),t)return i={type:"tag",tagType:"media-sequence"},t[1]&&(i.number=parseInt(t[1],10)),void this.trigger("data",i);if(t=/^#EXT-X-DISCONTINUITY-SEQUENCE:(\-?[0-9.]*)?/.exec(e),t)return i={type:"tag",tagType:"discontinuity-sequence"},t[1]&&(i.number=parseInt(t[1],10)),void this.trigger("data",i);if(t=/^#EXT-X-PLAYLIST-TYPE:(.*)?$/.exec(e),t)return i={type:"tag",tagType:"playlist-type"},t[1]&&(i.playlistType=t[1]),void this.trigger("data",i);if(t=/^#EXT-X-BYTERANGE:(.*)?$/.exec(e),t)return i=c(y(t[1]),{type:"tag",tagType:"byterange"}),void this.trigger("data",i);if(t=/^#EXT-X-ALLOW-CACHE:(YES|NO)?/.exec(e),t)return i={type:"tag",tagType:"allow-cache"},t[1]&&(i.allowed=!/NO/.test(t[1])),void this.trigger("data",i);if(t=/^#EXT-X-MAP:(.*)$/.exec(e),t){if(i={type:"tag",tagType:"map"},t[1]){const e=_(t[1]);e.URI&&(i.uri=e.URI),e.BYTERANGE&&(i.byterange=y(e.BYTERANGE))}this.trigger("data",i)}else if(t=/^#EXT-X-STREAM-INF:(.*)$/.exec(e),t){if(i={type:"tag",tagType:"stream-inf"},t[1]){if(i.attributes=_(t[1]),i.attributes.RESOLUTION){const e=i.attributes.RESOLUTION.split("x"),t={};e[0]&&(t.width=parseInt(e[0],10)),e[1]&&(t.height=parseInt(e[1],10)),i.attributes.RESOLUTION=t}i.attributes.BANDWIDTH&&(i.attributes.BANDWIDTH=parseInt(i.attributes.BANDWIDTH,10)),i.attributes["FRAME-RATE"]&&(i.attributes["FRAME-RATE"]=parseFloat(i.attributes["FRAME-RATE"])),i.attributes["PROGRAM-ID"]&&(i.attributes["PROGRAM-ID"]=parseInt(i.attributes["PROGRAM-ID"],10))}this.trigger("data",i)}else{if(t=/^#EXT-X-MEDIA:(.*)$/.exec(e),t)return i={type:"tag",tagType:"media"},t[1]&&(i.attributes=_(t[1])),void this.trigger("data",i);if(t=/^#EXT-X-ENDLIST/.exec(e),t)this.trigger("data",{type:"tag",tagType:"endlist"});else if(t=/^#EXT-X-DISCONTINUITY/.exec(e),t)this.trigger("data",{type:"tag",tagType:"discontinuity"});else{if(t=/^#EXT-X-PROGRAM-DATE-TIME:(.*)$/.exec(e),t)return i={type:"tag",tagType:"program-date-time"},t[1]&&(i.dateTimeString=t[1],i.dateTimeObject=new Date(t[1])),void this.trigger("data",i);if(t=/^#EXT-X-KEY:(.*)$/.exec(e),t)return i={type:"tag",tagType:"key"},t[1]&&(i.attributes=_(t[1]),i.attributes.IV&&("0x"===i.attributes.IV.substring(0,2).toLowerCase()&&(i.attributes.IV=i.attributes.IV.substring(2)),i.attributes.IV=i.attributes.IV.match(/.{8}/g),i.attributes.IV[0]=parseInt(i.attributes.IV[0],16),i.attributes.IV[1]=parseInt(i.attributes.IV[1],16),i.attributes.IV[2]=parseInt(i.attributes.IV[2],16),i.attributes.IV[3]=parseInt(i.attributes.IV[3],16),i.attributes.IV=new Uint32Array(i.attributes.IV))),void this.trigger("data",i);if(t=/^#EXT-X-START:(.*)$/.exec(e),t)return i={type:"tag",tagType:"start"},t[1]&&(i.attributes=_(t[1]),i.attributes["TIME-OFFSET"]=parseFloat(i.attributes["TIME-OFFSET"]),i.attributes.PRECISE=/YES/.test(i.attributes.PRECISE)),void this.trigger("data",i);if(t=/^#EXT-X-CUE-OUT-CONT:(.*)?$/.exec(e),t)return i={type:"tag",tagType:"cue-out-cont"},t[1]?i.data=t[1]:i.data="",void this.trigger("data",i);if(t=/^#EXT-X-CUE-OUT:(.*)?$/.exec(e),t)return i={type:"tag",tagType:"cue-out"},t[1]?i.data=t[1]:i.data="",void this.trigger("data",i);if(t=/^#EXT-X-CUE-IN:(.*)?$/.exec(e),t)return i={type:"tag",tagType:"cue-in"},t[1]?i.data=t[1]:i.data="",void this.trigger("data",i);if(t=/^#EXT-X-SKIP:(.*)$/.exec(e),t&&t[1])return i={type:"tag",tagType:"skip"},i.attributes=_(t[1]),i.attributes.hasOwnProperty("SKIPPED-SEGMENTS")&&(i.attributes["SKIPPED-SEGMENTS"]=parseInt(i.attributes["SKIPPED-SEGMENTS"],10)),i.attributes.hasOwnProperty("RECENTLY-REMOVED-DATERANGES")&&(i.attributes["RECENTLY-REMOVED-DATERANGES"]=i.attributes["RECENTLY-REMOVED-DATERANGES"].split(g)),void this.trigger("data",i);if(t=/^#EXT-X-PART:(.*)$/.exec(e),t&&t[1])return i={type:"tag",tagType:"part"},i.attributes=_(t[1]),["DURATION"].forEach((function(e){i.attributes.hasOwnProperty(e)&&(i.attributes[e]=parseFloat(i.attributes[e]))})),["INDEPENDENT","GAP"].forEach((function(e){i.attributes.hasOwnProperty(e)&&(i.attributes[e]=/YES/.test(i.attributes[e]))})),i.attributes.hasOwnProperty("BYTERANGE")&&(i.attributes.byterange=y(i.attributes.BYTERANGE)),void this.trigger("data",i);if(t=/^#EXT-X-SERVER-CONTROL:(.*)$/.exec(e),t&&t[1])return i={type:"tag",tagType:"server-control"},i.attributes=_(t[1]),["CAN-SKIP-UNTIL","PART-HOLD-BACK","HOLD-BACK"].forEach((function(e){i.attributes.hasOwnProperty(e)&&(i.attributes[e]=parseFloat(i.attributes[e]))})),["CAN-SKIP-DATERANGES","CAN-BLOCK-RELOAD"].forEach((function(e){i.attributes.hasOwnProperty(e)&&(i.attributes[e]=/YES/.test(i.attributes[e]))})),void this.trigger("data",i);if(t=/^#EXT-X-PART-INF:(.*)$/.exec(e),t&&t[1])return i={type:"tag",tagType:"part-inf"},i.attributes=_(t[1]),["PART-TARGET"].forEach((function(e){i.attributes.hasOwnProperty(e)&&(i.attributes[e]=parseFloat(i.attributes[e]))})),void this.trigger("data",i);if(t=/^#EXT-X-PRELOAD-HINT:(.*)$/.exec(e),t&&t[1])return i={type:"tag",tagType:"preload-hint"},i.attributes=_(t[1]),["BYTERANGE-START","BYTERANGE-LENGTH"].forEach((function(e){if(i.attributes.hasOwnProperty(e)){i.attributes[e]=parseInt(i.attributes[e],10);const t="BYTERANGE-LENGTH"===e?"length":"offset";i.attributes.byterange=i.attributes.byterange||{},i.attributes.byterange[t]=i.attributes[e],delete i.attributes[e]}})),void this.trigger("data",i);if(t=/^#EXT-X-RENDITION-REPORT:(.*)$/.exec(e),t&&t[1])return i={type:"tag",tagType:"rendition-report"},i.attributes=_(t[1]),["LAST-MSN","LAST-PART"].forEach((function(e){i.attributes.hasOwnProperty(e)&&(i.attributes[e]=parseInt(i.attributes[e],10))})),void this.trigger("data",i);this.trigger("data",{type:"tag",data:e.slice(4)})}}}else this.trigger("data",{type:"comment",text:e.slice(1)})})):this.trigger("data",{type:"uri",uri:e}))}addParser({expression:e,customType:t,dataParser:i,segment:n}){"function"!=typeof i&&(i=e=>e),this.customParsers.push((s=>{if(e.exec(s))return this.trigger("data",{type:"custom",data:i(s),customType:t,segment:n}),!0}))}addTagMapper({expression:e,map:t}){this.tagMappers.push((i=>e.test(i)?t(i):i))}}const b=function(e){const t={};return Object.keys(e).forEach((function(i){var n;t[(n=i,n.toLowerCase().replace(/-(\w)/g,(e=>e[1].toUpperCase())))]=e[i]})),t},S=function(e){const{serverControl:t,targetDuration:i,partTargetDuration:n}=e;if(!t)return;const s="#EXT-X-SERVER-CONTROL",r="holdBack",a="partHoldBack",o=i&&3*i,d=n&&2*n;i&&!t.hasOwnProperty(r)&&(t[r]=o,this.trigger("info",{message:`${s} defaulting HOLD-BACK to targetDuration * 3 (${o}).`})),o&&t[r]<o&&(this.trigger("warn",{message:`${s} clamping HOLD-BACK (${t[r]}) to targetDuration * 3 (${o})`}),t[r]=o),n&&!t.hasOwnProperty(a)&&(t[a]=3*n,this.trigger("info",{message:`${s} defaulting PART-HOLD-BACK to partTargetDuration * 3 (${t[a]}).`})),n&&t[a]<d&&(this.trigger("warn",{message:`${s} clamping PART-HOLD-BACK (${t[a]}) to partTargetDuration * 2 (${d}).`}),t[a]=d)};class v extends p{constructor(){super(),this.lineStream=new f,this.parseStream=new T,this.lineStream.pipe(this.parseStream);const e=this,t=[];let i,n,s={},r=!1;const a=function(){},o={AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}};let d=0;this.manifest={allowCache:!0,discontinuityStarts:[],segments:[]};let u=0,l=0;this.on("end",(()=>{s.uri||!s.parts&&!s.preloadHints||(!s.map&&i&&(s.map=i),!s.key&&n&&(s.key=n),s.timeline||"number"!=typeof d||(s.timeline=d),this.manifest.preloadSegment=s)})),this.parseStream.on("data",(function(h){let p,f;({tag(){({version(){h.version&&(this.manifest.version=h.version)},"allow-cache"(){this.manifest.allowCache=h.allowed,"allowed"in h||(this.trigger("info",{message:"defaulting allowCache to YES"}),this.manifest.allowCache=!0)},byterange(){const e={};"length"in h&&(s.byterange=e,e.length=h.length,"offset"in h||(h.offset=u)),"offset"in h&&(s.byterange=e,e.offset=h.offset),u=e.offset+e.length},endlist(){this.manifest.endList=!0},inf(){"mediaSequence"in this.manifest||(this.manifest.mediaSequence=0,this.trigger("info",{message:"defaulting media sequence to zero"})),"discontinuitySequence"in this.manifest||(this.manifest.discontinuitySequence=0,this.trigger("info",{message:"defaulting discontinuity sequence to zero"})),h.duration>0&&(s.duration=h.duration),0===h.duration&&(s.duration=.01,this.trigger("info",{message:"updating zero segment duration to a small value"})),this.manifest.segments=t},key(){if(h.attributes)if("NONE"!==h.attributes.METHOD)if(h.attributes.URI){if("com.apple.streamingkeydelivery"===h.attributes.KEYFORMAT)return this.manifest.contentProtection=this.manifest.contentProtection||{},void(this.manifest.contentProtection["com.apple.fps.1_0"]={attributes:h.attributes});if("com.microsoft.playready"===h.attributes.KEYFORMAT)return this.manifest.contentProtection=this.manifest.contentProtection||{},void(this.manifest.contentProtection["com.microsoft.playready"]={uri:h.attributes.URI});if("urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"===h.attributes.KEYFORMAT)return-1===["SAMPLE-AES","SAMPLE-AES-CTR","SAMPLE-AES-CENC"].indexOf(h.attributes.METHOD)?void this.trigger("warn",{message:"invalid key method provided for Widevine"}):("SAMPLE-AES-CENC"===h.attributes.METHOD&&this.trigger("warn",{message:"SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead"}),"data:text/plain;base64,"!==h.attributes.URI.substring(0,23)?void this.trigger("warn",{message:"invalid key URI provided for Widevine"}):h.attributes.KEYID&&"0x"===h.attributes.KEYID.substring(0,2)?(this.manifest.contentProtection=this.manifest.contentProtection||{},void(this.manifest.contentProtection["com.widevine.alpha"]={attributes:{schemeIdUri:h.attributes.KEYFORMAT,keyId:h.attributes.KEYID.substring(2)},pssh:m(h.attributes.URI.split(",")[1])})):void this.trigger("warn",{message:"invalid key ID provided for Widevine"}));h.attributes.METHOD||this.trigger("warn",{message:"defaulting key method to AES-128"}),n={method:h.attributes.METHOD||"AES-128",uri:h.attributes.URI},void 0!==h.attributes.IV&&(n.iv=h.attributes.IV)}else this.trigger("warn",{message:"ignoring key declaration without URI"});else n=null;else this.trigger("warn",{message:"ignoring key declaration without attribute list"})},"media-sequence"(){isFinite(h.number)?this.manifest.mediaSequence=h.number:this.trigger("warn",{message:"ignoring invalid media sequence: "+h.number})},"discontinuity-sequence"(){isFinite(h.number)?(this.manifest.discontinuitySequence=h.number,d=h.number):this.trigger("warn",{message:"ignoring invalid discontinuity sequence: "+h.number})},"playlist-type"(){/VOD|EVENT/.test(h.playlistType)?this.manifest.playlistType=h.playlistType:this.trigger("warn",{message:"ignoring unknown playlist type: "+h.playlist})},map(){i={},h.uri&&(i.uri=h.uri),h.byterange&&(i.byterange=h.byterange),n&&(i.key=n)},"stream-inf"(){this.manifest.playlists=t,this.manifest.mediaGroups=this.manifest.mediaGroups||o,h.attributes?(s.attributes||(s.attributes={}),c(s.attributes,h.attributes)):this.trigger("warn",{message:"ignoring empty stream-inf attributes"})},media(){if(this.manifest.mediaGroups=this.manifest.mediaGroups||o,!(h.attributes&&h.attributes.TYPE&&h.attributes["GROUP-ID"]&&h.attributes.NAME))return void this.trigger("warn",{message:"ignoring incomplete or missing media group"});const e=this.manifest.mediaGroups[h.attributes.TYPE];e[h.attributes["GROUP-ID"]]=e[h.attributes["GROUP-ID"]]||{},p=e[h.attributes["GROUP-ID"]],f={default:/yes/i.test(h.attributes.DEFAULT)},f.default?f.autoselect=!0:f.autoselect=/yes/i.test(h.attributes.AUTOSELECT),h.attributes.LANGUAGE&&(f.language=h.attributes.LANGUAGE),h.attributes.URI&&(f.uri=h.attributes.URI),h.attributes["INSTREAM-ID"]&&(f.instreamId=h.attributes["INSTREAM-ID"]),h.attributes.CHARACTERISTICS&&(f.characteristics=h.attributes.CHARACTERISTICS),h.attributes.FORCED&&(f.forced=/yes/i.test(h.attributes.FORCED)),p[h.attributes.NAME]=f},discontinuity(){d+=1,s.discontinuity=!0,this.manifest.discontinuityStarts.push(t.length)},"program-date-time"(){void 0===this.manifest.dateTimeString&&(this.manifest.dateTimeString=h.dateTimeString,this.manifest.dateTimeObject=h.dateTimeObject),s.dateTimeString=h.dateTimeString,s.dateTimeObject=h.dateTimeObject},targetduration(){!isFinite(h.duration)||h.duration<0?this.trigger("warn",{message:"ignoring invalid target duration: "+h.duration}):(this.manifest.targetDuration=h.duration,S.call(this,this.manifest))},start(){h.attributes&&!isNaN(h.attributes["TIME-OFFSET"])?this.manifest.start={timeOffset:h.attributes["TIME-OFFSET"],precise:h.attributes.PRECISE}:this.trigger("warn",{message:"ignoring start declaration without appropriate attribute list"})},"cue-out"(){s.cueOut=h.data},"cue-out-cont"(){s.cueOutCont=h.data},"cue-in"(){s.cueIn=h.data},skip(){this.manifest.skip=b(h.attributes),this.warnOnMissingAttributes_("#EXT-X-SKIP",h.attributes,["SKIPPED-SEGMENTS"])},part(){r=!0;const e=this.manifest.segments.length,t=b(h.attributes);s.parts=s.parts||[],s.parts.push(t),t.byterange&&(t.byterange.hasOwnProperty("offset")||(t.byterange.offset=l),l=t.byterange.offset+t.byterange.length);const i=s.parts.length-1;this.warnOnMissingAttributes_(`#EXT-X-PART #${i} for segment #${e}`,h.attributes,["URI","DURATION"]),this.manifest.renditionReports&&this.manifest.renditionReports.forEach(((e,t)=>{e.hasOwnProperty("lastPart")||this.trigger("warn",{message:`#EXT-X-RENDITION-REPORT #${t} lacks required attribute(s): LAST-PART`})}))},"server-control"(){const e=this.manifest.serverControl=b(h.attributes);e.hasOwnProperty("canBlockReload")||(e.canBlockReload=!1,this.trigger("info",{message:"#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false"})),S.call(this,this.manifest),e.canSkipDateranges&&!e.hasOwnProperty("canSkipUntil")&&this.trigger("warn",{message:"#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set"})},"preload-hint"(){const e=this.manifest.segments.length,t=b(h.attributes),i=t.type&&"PART"===t.type;s.preloadHints=s.preloadHints||[],s.preloadHints.push(t),t.byterange&&(t.byterange.hasOwnProperty("offset")||(t.byterange.offset=i?l:0,i&&(l=t.byterange.offset+t.byterange.length)));const n=s.preloadHints.length-1;if(this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${n} for segment #${e}`,h.attributes,["TYPE","URI"]),t.type)for(let i=0;i<s.preloadHints.length-1;i++){const r=s.preloadHints[i];r.type&&r.type===t.type&&this.trigger("warn",{message:`#EXT-X-PRELOAD-HINT #${n} for segment #${e} has the same TYPE ${t.type} as preload hint #${i}`})}},"rendition-report"(){const e=b(h.attributes);this.manifest.renditionReports=this.manifest.renditionReports||[],this.manifest.renditionReports.push(e);const t=this.manifest.renditionReports.length-1,i=["LAST-MSN","URI"];r&&i.push("LAST-PART"),this.warnOnMissingAttributes_(`#EXT-X-RENDITION-REPORT #${t}`,h.attributes,i)},"part-inf"(){this.manifest.partInf=b(h.attributes),this.warnOnMissingAttributes_("#EXT-X-PART-INF",h.attributes,["PART-TARGET"]),this.manifest.partInf.partTarget&&(this.manifest.partTargetDuration=this.manifest.partInf.partTarget),S.call(this,this.manifest)}}[h.tagType]||a).call(e)},uri(){s.uri=h.uri,t.push(s),this.manifest.targetDuration&&!("duration"in s)&&(this.trigger("warn",{message:"defaulting segment duration to the target duration"}),s.duration=this.manifest.targetDuration),n&&(s.key=n),s.timeline=d,i&&(s.map=i),l=0,s={}},comment(){},custom(){h.segment?(s.custom=s.custom||{},s.custom[h.customType]=h.data):(this.manifest.custom=this.manifest.custom||{},this.manifest.custom[h.customType]=h.data)}})[h.type].call(e)}))}warnOnMissingAttributes_(e,t,i){const n=[];i.forEach((function(e){t.hasOwnProperty(e)||n.push(e)})),n.length&&this.trigger("warn",{message:`${e} lacks required attribute(s): ${n.join(", ")}`})}push(e){this.lineStream.push(e)}end(){this.lineStream.push("\n"),this.trigger("end")}addParser(e){this.parseStream.addParser(e)}addTagMapper(e){this.parseStream.addTagMapper(e)}}var w={mp4:/^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,webm:/^(vp0?[89]|av0?1|opus|vorbis)/,ogg:/^(vp0?[89]|theora|flac|opus|vorbis)/,video:/^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,audio:/^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,text:/^(stpp.ttml.im1t)/,muxerVideo:/^(avc0?1)/,muxerAudio:/^(mp4a)/,muxerText:/a^/},I=["video","audio","text"],E=["Video","Audio","Text"],A=function(e){return e?e.replace(/avc1\.(\d+)\.(\d+)/i,(function(e,t,i){return"avc1."+("00"+Number(t).toString(16)).slice(-2)+"00"+("00"+Number(i).toString(16)).slice(-2)})):e},L=function(e){void 0===e&&(e="");var t=e.split(","),i=[];return t.forEach((function(e){var t;e=e.trim(),I.forEach((function(n){var s=w[n].exec(e.toLowerCase());if(s&&!(s.length<=1)){t=n;var r=e.substring(0,s[1].length),a=e.replace(r,"");i.push({type:r,details:a,mediaType:n})}})),t||i.push({type:e,details:"",mediaType:"unknown"})})),i},x=function(e){return void 0===e&&(e=""),w.audio.test(e.trim().toLowerCase())},D=function(e){if(e&&"string"==typeof e){var t,i=e.toLowerCase().split(",").map((function(e){return A(e.trim())})),n="video";1===i.length&&x(i[0])?n="audio":1===i.length&&(void 0===(t=i[0])&&(t=""),w.text.test(t.trim().toLowerCase()))&&(n="application");var s="mp4";return i.every((function(e){return w.mp4.test(e)}))?s="mp4":i.every((function(e){return w.webm.test(e)}))?s="webm":i.every((function(e){return w.ogg.test(e)}))&&(s="ogg"),n+"/"+s+';codecs="'+e+'"'}},k=function(e){return void 0===e&&(e=""),window.MediaSource&&window.MediaSource.isTypeSupported&&window.MediaSource.isTypeSupported(D(e))||!1},O=function(e){return void 0===e&&(e=""),e.toLowerCase().split(",").every((function(e){e=e.trim();for(var t=0;t<E.length;t++)if(w["muxer"+E[t]].test(e))return!0;return!1}))},P="mp4a.40.2";function U(...e){const t=s.default.obj||s.default;return(t.merge||t.mergeOptions).apply(t,e)}function C(...e){const t=s.default.time||s.default;return(t.createTimeRanges||t.createTimeRanges).apply(t,e)}const R=1/30,M=.1,B=function(e,t){const i=[];let n;if(e&&e.length)for(n=0;n<e.length;n++)t(e.start(n),e.end(n))&&i.push([e.start(n),e.end(n)]);return C(i)},N=function(e,t){return B(e,(function(e,i){return e-M<=t&&i+M>=t}))},F=function(e,t){return B(e,(function(e){return e-R>=t}))},$=e=>{const t=[];if(!e||!e.length)return"";for(let i=0;i<e.length;i++)t.push(e.start(i)+" => "+e.end(i));return t.join(", ")},q=e=>{const t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t},W=function(e){if(e&&e.length&&e.end)return e.end(e.length-1)},G=function(e,t){let i=0;if(!e||!e.length)return i;for(let n=0;n<e.length;n++){const s=e.start(n),r=e.end(n);t>r||(i+=t>s&&t<=r?r-t:r-s)}return i},V=(e,t)=>{if(!t.preload)return t.duration;let i=0;return(t.parts||[]).forEach((function(e){i+=e.duration})),(t.preloadHints||[]).forEach((function(t){"PART"===t.type&&(i+=e.partTargetDuration)})),i},H=e=>(e.segments||[]).reduce(((e,t,i)=>(t.parts?t.parts.forEach((function(n,s){e.push({duration:n.duration,segmentIndex:i,partIndex:s,part:n,segment:t})})):e.push({duration:t.duration,segmentIndex:i,partIndex:null,segment:t,part:null}),e)),[]),j=e=>{const t=e.segments&&e.segments.length&&e.segments[e.segments.length-1];return t&&t.parts||[]},X=({preloadSegment:e})=>{if(!e)return;const{parts:t,preloadHints:i}=e;let n=(i||[]).reduce(((e,t)=>e+("PART"===t.type?1:0)),0);return n+=t&&t.length?t.length:0,n},z=(e,t)=>{if(t.endList)return 0;if(e&&e.suggestedPresentationDelay)return e.suggestedPresentationDelay;const i=j(t).length>0;return i&&t.serverControl&&t.serverControl.partHoldBack?t.serverControl.partHoldBack:i&&t.partTargetDuration?3*t.partTargetDuration:t.serverControl&&t.serverControl.holdBack?t.serverControl.holdBack:t.targetDuration?3*t.targetDuration:0},Q=function(e,t,i){if(void 0===t&&(t=e.mediaSequence+e.segments.length),t<e.mediaSequence)return 0;const n=function(e,t){let i=0,n=t-e.mediaSequence,s=e.segments[n];if(s){if(void 0!==s.start)return{result:s.start,precise:!0};if(void 0!==s.end)return{result:s.end-s.duration,precise:!0}}for(;n--;){if(s=e.segments[n],void 0!==s.end)return{result:i+s.end,precise:!0};if(i+=V(e,s),void 0!==s.start)return{result:i+s.start,precise:!0}}return{result:i,precise:!1}}(e,t);if(n.precise)return n.result;const s=function(e,t){let i,n=0,s=t-e.mediaSequence;for(;s<e.segments.length;s++){if(i=e.segments[s],void 0!==i.start)return{result:i.start-n,precise:!0};if(n+=V(e,i),void 0!==i.end)return{result:i.end-n,precise:!0}}return{result:-1,precise:!1}}(e,t);return s.precise?s.result:n.result+i},Y=function(e,t,i){if(!e)return 0;if("number"!=typeof i&&(i=0),void 0===t){if(e.totalDuration)return e.totalDuration;if(!e.endList)return window.Infinity}return Q(e,t,i)},K=function({defaultDuration:e,durationList:t,startIndex:i,endIndex:n}){let s=0;if(i>n&&([i,n]=[n,i]),i<0){for(let t=i;t<Math.min(0,n);t++)s+=e;i=0}for(let e=i;e<n;e++)s+=t[e].duration;return s},J=function(e,t,i,n){if(!e||!e.segments)return null;if(e.endList)return Y(e);if(null===t)return null;t=t||0;let s=Q(e,e.mediaSequence+e.segments.length,t);return i&&(s-=n="number"==typeof n?n:z(null,e)),Math.max(0,s)},Z=function(e){return e.excludeUntil&&e.excludeUntil>Date.now()},ee=function(e){return e.excludeUntil&&e.excludeUntil===1/0},te=function(e){const t=Z(e);return!e.disabled&&!t},ie=function(e,t){return t.attributes&&t.attributes[e]},ne=(e,t)=>{if(1===e.playlists.length)return!0;const i=t.attributes.BANDWIDTH||Number.MAX_VALUE;return 0===e.playlists.filter((e=>!!te(e)&&(e.attributes.BANDWIDTH||0)<i)).length},se=(e,t)=>!(!e&&!t||!e&&t||e&&!t||e!==t&&(!e.id||!t.id||e.id!==t.id)&&(!e.resolvedUri||!t.resolvedUri||e.resolvedUri!==t.resolvedUri)&&(!e.uri||!t.uri||e.uri!==t.uri)),re=function(e,t){const i=e&&e.mediaGroups&&e.mediaGroups.AUDIO||{};let n=!1;for(const e in i){for(const s in i[e])if(n=t(i[e][s]),n)break;if(n)break}return!!n},ae=e=>{if(!e||!e.playlists||!e.playlists.length)return re(e,(e=>e.playlists&&e.playlists.length||e.uri));for(let t=0;t<e.playlists.length;t++){const i=e.playlists[t],n=i.attributes&&i.attributes.CODECS;if((!n||!n.split(",").every((e=>x(e))))&&!re(e,(e=>se(i,e))))return!1}return!0};var oe={liveEdgeDelay:z,duration:Y,seekable:function(e,t,i){const n=t||0,s=J(e,t,!0,i);return null===s?C():C(n,s)},getMediaInfoForTime:function({playlist:e,currentTime:t,startingSegmentIndex:i,startingPartIndex:n,startTime:s,exactManifestTimings:r}){let a=t-s;const o=H(e);let d=0;for(let e=0;e<o.length;e++){const t=o[e];if(i===t.segmentIndex&&("number"!=typeof n||"number"!=typeof t.partIndex||n===t.partIndex)){d=e;break}}if(a<0){if(d>0)for(let t=d-1;t>=0;t--){const i=o[t];if(a+=i.duration,r){if(a<0)continue}else if(a+R<=0)continue;return{partIndex:i.partIndex,segmentIndex:i.segmentIndex,startTime:s-K({defaultDuration:e.targetDuration,durationList:o,startIndex:d,endIndex:t})}}return{partIndex:o[0]&&o[0].partIndex||null,segmentIndex:o[0]&&o[0].segmentIndex||0,startTime:t}}if(d<0){for(let i=d;i<0;i++)if(a-=e.targetDuration,a<0)return{partIndex:o[0]&&o[0].partIndex||null,segmentIndex:o[0]&&o[0].segmentIndex||0,startTime:t};d=0}for(let t=d;t<o.length;t++){const i=o[t];if(a-=i.duration,r){if(a>0)continue}else if(a-R>=0)continue;return{partIndex:i.partIndex,segmentIndex:i.segmentIndex,startTime:s+K({defaultDuration:e.targetDuration,durationList:o,startIndex:d,endIndex:t})}}return{segmentIndex:o[o.length-1].segmentIndex,partIndex:o[o.length-1].partIndex,startTime:t}},isEnabled:te,isDisabled:function(e){return e.disabled},isExcluded:Z,isIncompatible:ee,playlistEnd:J,isAes:function(e){for(let t=0;t<e.segments.length;t++)if(e.segments[t].key)return!0;return!1},hasAttribute:ie,estimateSegmentRequestTime:function(e,t,i,n=0){return ie("BANDWIDTH",i)?(e*i.attributes.BANDWIDTH-8*n)/t:NaN},isLowestEnabledRendition:ne,isAudioOnly:ae,playlistMatch:se,segmentDurationWithParts:V};const{log:de}=s.default,ue=(e,t)=>`${e}-${t}`,le=(e,t)=>{e.mediaGroups&&["AUDIO","SUBTITLES"].forEach((i=>{if(e.mediaGroups[i])for(const n in e.mediaGroups[i])for(const s in e.mediaGroups[i][n]){const r=e.mediaGroups[i][n][s];t(r,i,n,s)}}))},he=({playlist:e,uri:t,id:i})=>{e.id=i,e.playlistErrors_=0,t&&(e.uri=t),e.attributes=e.attributes||{}},ce=(e,t)=>{e.uri=t;for(let t=0;t<e.playlists.length;t++)if(!e.playlists[t].uri){const i=`placeholder-uri-${t}`;e.playlists[t].uri=i}const i=ae(e);le(e,((t,n,s,r)=>{const a=`placeholder-uri-${n}-${s}-${r}`;if(!t.playlists||!t.playlists.length){if(i&&"AUDIO"===n&&!t.uri)for(let t=0;t<e.playlists.length;t++){const i=e.playlists[t];if(i.attributes&&i.attributes.AUDIO&&i.attributes.AUDIO===s)return}t.playlists=[c({},t)]}t.playlists.forEach((function(t,i){const n=ue(i,a);t.uri?t.resolvedUri=t.resolvedUri||u(e.uri,t.uri):(t.uri=0===i?a:n,t.resolvedUri=t.uri),t.id=t.id||n,t.attributes=t.attributes||{},e.playlists[t.id]=t,e.playlists[t.uri]=t}))})),(e=>{let t=e.playlists.length;for(;t--;){const i=e.playlists[t];he({playlist:i,id:ue(t,i.uri)}),i.resolvedUri=u(e.uri,i.uri),e.playlists[i.id]=i,e.playlists[i.uri]=i,i.attributes.BANDWIDTH||de.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.")}})(e),(e=>{le(e,(t=>{t.uri&&(t.resolvedUri=u(e.uri,t.uri))}))})(e)},{EventTarget:pe}=s.default,me=(e,t)=>{if(!e)return t;const i=U(e,t);if(e.preloadHints&&!t.preloadHints&&delete i.preloadHints,e.parts&&!t.parts)delete i.parts;else if(e.parts&&t.parts)for(let n=0;n<t.parts.length;n++)e.parts&&e.parts[n]&&(i.parts[n]=U(e.parts[n],t.parts[n]));return!e.skipped&&t.skipped&&(i.skipped=!1),e.preload&&!t.preload&&(i.preload=!1),i},fe=(e,t)=>{!e.resolvedUri&&e.uri&&(e.resolvedUri=u(t,e.uri)),e.key&&!e.key.resolvedUri&&(e.key.resolvedUri=u(t,e.key.uri)),e.map&&!e.map.resolvedUri&&(e.map.resolvedUri=u(t,e.map.uri)),e.map&&e.map.key&&!e.map.key.resolvedUri&&(e.map.key.resolvedUri=u(t,e.map.key.uri)),e.parts&&e.parts.length&&e.parts.forEach((e=>{e.resolvedUri||(e.resolvedUri=u(t,e.uri))})),e.preloadHints&&e.preloadHints.length&&e.preloadHints.forEach((e=>{e.resolvedUri||(e.resolvedUri=u(t,e.uri))}))},ge=function(e){const t=e.segments||[],i=e.preloadSegment;if(i&&i.parts&&i.parts.length){if(i.preloadHints)for(let e=0;e<i.preloadHints.length;e++)if("MAP"===i.preloadHints[e].type)return t;i.duration=e.targetDuration,i.preload=!0,t.push(i)}return t},ye=(e,t)=>e===t||e.segments&&t.segments&&e.segments.length===t.segments.length&&e.endList===t.endList&&e.mediaSequence===t.mediaSequence&&e.preloadSegment===t.preloadSegment,_e=(e,t,i=ye)=>{const n=U(e,{}),s=n.playlists[t.id];if(!s)return null;if(i(s,t))return null;t.segments=ge(t);const r=U(s,t);if(r.preloadSegment&&!t.preloadSegment&&delete r.preloadSegment,s.segments){if(t.skip){t.segments=t.segments||[];for(let e=0;e<t.skip.skippedSegments;e++)t.segments.unshift({skipped:!0})}r.segments=((e,t,i)=>{const n=e.slice(),s=t.slice();i=i||0;const r=[];let a;for(let e=0;e<s.length;e++){const t=n[e+i],o=s[e];t?(a=t.map||a,r.push(me(t,o))):(a&&!o.map&&(o.map=a),r.push(o))}return r})(s.segments,t.segments,t.mediaSequence-s.mediaSequence)}r.segments.forEach((e=>{fe(e,r.resolvedUri)}));for(let e=0;e<n.playlists.length;e++)n.playlists[e].id===t.id&&(n.playlists[e]=r);return n.playlists[t.id]=r,n.playlists[t.uri]=r,le(e,((e,i,n,s)=>{if(e.playlists)for(let i=0;i<e.playlists.length;i++)t.id===e.playlists[i].id&&(e.playlists[i]=r)})),n},Te=(e,t)=>{const i=e.segments||[],n=i[i.length-1],s=n&&n.parts&&n.parts[n.parts.length-1],r=s&&s.duration||n&&n.duration;return t&&r?1e3*r:500*(e.partTargetDuration||e.targetDuration||10)};class be extends pe{constructor(e,t,i={}){if(super(),!e)throw new Error("A non-empty playlist URL or object is required");this.logger_=h("PlaylistLoader");const{withCredentials:n=!1}=i;this.src=e,this.vhs_=t,this.withCredentials=n;const s=t.options_;this.customTagParsers=s&&s.customTagParsers||[],this.customTagMappers=s&&s.customTagMappers||[],this.llhls=s&&s.llhls,this.state="HAVE_NOTHING",this.handleMediaupdatetimeout_=this.handleMediaupdatetimeout_.bind(this),this.on("mediaupdatetimeout",this.handleMediaupdatetimeout_)}handleMediaupdatetimeout_(){if("HAVE_METADATA"!==this.state)return;const e=this.media();let t=u(this.main.uri,e.uri);this.llhls&&(t=((e,t)=>{if(t.endList||!t.serverControl)return e;const i={};if(t.serverControl.canBlockReload){const{preloadSegment:e}=t;let n=t.mediaSequence+t.segments.length;if(e){const s=e.parts||[],r=X(t)-1;r>-1&&r!==s.length-1&&(i._HLS_part=r),(r>-1||s.length)&&n--}i._HLS_msn=n}if(t.serverControl&&t.serverControl.canSkipUntil&&(i._HLS_skip=t.serverControl.canSkipDateranges?"v2":"YES"),Object.keys(i).length){const t=new window.URL(e);["_HLS_skip","_HLS_msn","_HLS_part"].forEach((function(e){i.hasOwnProperty(e)&&t.searchParams.set(e,i[e])})),e=t.toString()}return e})(t,e)),this.state="HAVE_CURRENT_METADATA",this.request=this.vhs_.xhr({uri:t,withCredentials:this.withCredentials},((e,t)=>{if(this.request)return e?this.playlistRequestError(this.request,this.media(),"HAVE_METADATA"):void this.haveMetadata({playlistString:this.request.responseText,url:this.media().uri,id:this.media().id})}))}playlistRequestError(e,t,i){const{uri:n,id:s}=t;this.request=null,i&&(this.state=i),this.error={playlist:this.main.playlists[s],status:e.status,message:`HLS playlist request error at URL: ${n}.`,responseText:e.responseText,code:e.status>=500?4:2},this.trigger("error")}parseManifest_({url:e,manifestString:t}){return(({onwarn:e,oninfo:t,manifestString:i,customTagParsers:n=[],customTagMappers:s=[],llhls:r})=>{const a=new v;e&&a.on("warn",e),t&&a.on("info",t),n.forEach((e=>a.addParser(e))),s.forEach((e=>a.addTagMapper(e))),a.push(i),a.end();const o=a.manifest;if(r||(["preloadSegment","skip","serverControl","renditionReports","partInf","partTargetDuration"].forEach((function(e){o.hasOwnProperty(e)&&delete o[e]})),o.segments&&o.segments.forEach((function(e){["parts","preloadHints"].forEach((function(t){e.hasOwnProperty(t)&&delete e[t]}))}))),!o.targetDuration){let t=10;o.segments&&o.segments.length&&(t=o.segments.reduce(((e,t)=>Math.max(e,t.duration)),0)),e&&e(`manifest has no targetDuration defaulting to ${t}`),o.targetDuration=t}const d=j(o);if(d.length&&!o.partTargetDuration){const t=d.reduce(((e,t)=>Math.max(e,t.duration)),0);e&&(e(`manifest has no partTargetDuration defaulting to ${t}`),de.error("LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.")),o.partTargetDuration=t}return o})({onwarn:({message:t})=>this.logger_(`m3u8-parser warn for ${e}: ${t}`),oninfo:({message:t})=>this.logger_(`m3u8-parser info for ${e}: ${t}`),manifestString:t,customTagParsers:this.customTagParsers,customTagMappers:this.customTagMappers,llhls:this.llhls})}haveMetadata({playlistString:e,playlistObject:t,url:i,id:n}){this.request=null,this.state="HAVE_METADATA";const s=t||this.parseManifest_({url:i,manifestString:e});s.lastRequest=Date.now(),he({playlist:s,uri:i,id:n});const r=_e(this.main,s);this.targetDuration=s.partTargetDuration||s.targetDuration,this.pendingMedia_=null,r?(this.main=r,this.media_=this.main.playlists[n]):this.trigger("playlistunchanged"),this.updateMediaUpdateTimeout_(Te(this.media(),!!r)),this.trigger("loadedplaylist")}dispose(){this.trigger("dispose"),this.stopRequest(),window.clearTimeout(this.mediaUpdateTimeout),window.clearTimeout(this.finalRenditionTimeout),this.off()}stopRequest(){if(this.request){const e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e,t){if(!e)return this.media_;if("HAVE_NOTHING"===this.state)throw new Error("Cannot switch media playlist from "+this.state);if("string"==typeof e){if(!this.main.playlists[e])throw new Error("Unknown playlist URI: "+e);e=this.main.playlists[e]}if(window.clearTimeout(this.finalRenditionTimeout),t){const t=(e.partTargetDuration||e.targetDuration)/2*1e3||5e3;return void(this.finalRenditionTimeout=window.setTimeout(this.media.bind(this,e,!1),t))}const i=this.state,n=!this.media_||e.id!==this.media_.id,s=this.main.playlists[e.id];if(s&&s.endList||e.endList&&e.segments.length)return this.request&&(this.request.onreadystatechange=null,this.request.abort(),this.request=null),this.state="HAVE_METADATA",this.media_=e,void(n&&(this.trigger("mediachanging"),"HAVE_MAIN_MANIFEST"===i?this.trigger("loadedmetadata"):this.trigger("mediachange")));if(this.updateMediaUpdateTimeout_(Te(e,!0)),n){if(this.state="SWITCHING_MEDIA",this.request){if(e.resolvedUri===this.request.url)return;this.request.onreadystatechange=null,this.request.abort(),this.request=null}this.media_&&this.trigger("mediachanging"),this.pendingMedia_=e,this.request=this.vhs_.xhr({uri:e.resolvedUri,withCredentials:this.withCredentials},((t,n)=>{if(this.request){if(e.lastRequest=Date.now(),e.resolvedUri=l(e.resolvedUri,n),t)return this.playlistRequestError(this.request,e,i);this.haveMetadata({playlistString:n.responseText,url:e.uri,id:e.id}),"HAVE_MAIN_MANIFEST"===i?this.trigger("loadedmetadata"):this.trigger("mediachange")}}))}}pause(){this.mediaUpdateTimeout&&(window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),this.stopRequest(),"HAVE_NOTHING"===this.state&&(this.started=!1),"SWITCHING_MEDIA"===this.state?this.media_?this.state="HAVE_METADATA":this.state="HAVE_MAIN_MANIFEST":"HAVE_CURRENT_METADATA"===this.state&&(this.state="HAVE_METADATA")}load(e){this.mediaUpdateTimeout&&(window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);const t=this.media();if(e){const e=t?(t.partTargetDuration||t.targetDuration)/2*1e3:5e3;this.mediaUpdateTimeout=window.setTimeout((()=>{this.mediaUpdateTimeout=null,this.load()}),e)}else this.started?t&&!t.endList?this.trigger("mediaupdatetimeout"):this.trigger("loadedplaylist"):this.start()}updateMediaUpdateTimeout_(e){this.mediaUpdateTimeout&&(window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),this.media()&&!this.media().endList&&(this.mediaUpdateTimeout=window.setTimeout((()=>{this.mediaUpdateTimeout=null,this.trigger("mediaupdatetimeout"),this.updateMediaUpdateTimeout_(e)}),e))}start(){if(this.started=!0,"object"==typeof this.src)return this.src.uri||(this.src.uri=window.location.href),this.src.resolvedUri=this.src.uri,void setTimeout((()=>{this.setupInitialPlaylist(this.src)}),0);this.request=this.vhs_.xhr({uri:this.src,withCredentials:this.withCredentials},((e,t)=>{if(!this.request)return;if(this.request=null,e)return this.error={status:t.status,message:`HLS playlist request error at URL: ${this.src}.`,responseText:t.responseText,code:2},"HAVE_NOTHING"===this.state&&(this.started=!1),this.trigger("error");this.src=l(this.src,t);const i=this.parseManifest_({manifestString:t.responseText,url:this.src});this.setupInitialPlaylist(i)}))}srcUri(){return"string"==typeof this.src?this.src:this.src.uri}setupInitialPlaylist(e){if(this.state="HAVE_MAIN_MANIFEST",e.playlists)return this.main=e,ce(this.main,this.srcUri()),e.playlists.forEach((e=>{e.segments=ge(e),e.segments.forEach((t=>{fe(t,e.resolvedUri)}))})),this.trigger("loadedplaylist"),void(this.request||this.media(this.main.playlists[0]));const t=this.srcUri()||window.location.href;this.main=((e,t)=>{const i=ue(0,t),n={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:window.location.href,resolvedUri:window.location.href,playlists:[{uri:t,id:i,resolvedUri:t,attributes:{}}]};return n.playlists[i]=n.playlists[0],n.playlists[t]=n.playlists[0],n})(0,t),this.haveMetadata({playlistObject:e,url:t,id:this.main.playlists[0].id}),this.trigger("loadedmetadata")}}const{xhr:Se}=s.default,ve=function(e,t,i,n){const s="arraybuffer"===e.responseType?e.response:e.responseText;!t&&s&&(e.responseTime=Date.now(),e.roundTripTime=e.responseTime-e.requestTime,e.bytesReceived=s.byteLength||s.length,e.bandwidth||(e.bandwidth=Math.floor(e.bytesReceived/e.roundTripTime*8*1e3))),i.headers&&(e.responseHeaders=i.headers),t&&"ETIMEDOUT"===t.code&&(e.timedout=!0),t||e.aborted||200===i.statusCode||206===i.statusCode||0===i.statusCode||(t=new Error("XHR Failed with a response of: "+(e&&(s||e.responseText)))),n(t,e)},we=function(){const e=function e(t,i){t=U({timeout:45e3},t);const n=e.beforeRequest||s.default.Vhs.xhr.beforeRequest;if(n&&"function"==typeof n){const e=n(t);e&&(t=e)}const r=(!0===s.default.Vhs.xhr.original?Se:s.default.Vhs.xhr)(t,(function(e,t){return ve(r,e,t,i)})),a=r.abort;return r.abort=function(){return r.aborted=!0,a.apply(r,arguments)},r.uri=t.uri,r.requestTime=Date.now(),r};return e.original=!0,e},Ie=function(e){const t={};return e.byterange&&(t.Range=function(e){let t;const i=e.offset;return t="bigint"==typeof e.offset||"bigint"==typeof e.length?window.BigInt(e.offset)+window.BigInt(e.length)-window.BigInt(1):e.offset+e.length-1,"bytes="+i+"-"+t}(e.byterange)),t};var Ee,Ae,Le=/^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i,xe=/^application\/dash\+xml/i,De=function(e){return Le.test(e)?"hls":xe.test(e)?"dash":"application/vnd.videojs.vhs+json"===e?"vhs-json":null},ke=function(e){return"function"===ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer},Oe=function(e){return e instanceof Uint8Array?e:(Array.isArray(e)||ke(e)||e instanceof ArrayBuffer||(e="number"!=typeof e||"number"==typeof e&&e!=e?0:[e]),new Uint8Array(e&&e.buffer||e,e&&e.byteOffset||0,e&&e.byteLength||0))},Pe=window.BigInt||Number,Ue=[Pe("0x1"),Pe("0x100"),Pe("0x10000"),Pe("0x1000000"),Pe("0x100000000"),Pe("0x10000000000"),Pe("0x1000000000000"),Pe("0x100000000000000"),Pe("0x10000000000000000")];Ee=new Uint16Array([65484]),255===(Ae=new Uint8Array(Ee.buffer,Ee.byteOffset,Ee.byteLength))[0]||Ae[0];var Ce=function(e,t){var i=void 0===t?{}:t,n=i.signed,s=void 0!==n&&n,r=i.le,a=void 0!==r&&r;e=Oe(e);var o=a?"reduce":"reduceRight",d=(e[o]?e[o]:Array.prototype[o]).call(e,(function(t,i,n){var s=a?n:Math.abs(n+1-e.length);return t+Pe(i)*Ue[s]}),Pe(0));if(s){var u=Ue[e.length]/Pe(2)-Pe(1);(d=Pe(d))>u&&(d-=u,d-=u,d-=Pe(2))}return Number(d)},Re=function(e,t){if("string"!=typeof e&&e&&"function"==typeof e.toString&&(e=e.toString()),"string"!=typeof e)return new Uint8Array;t||(e=unescape(encodeURIComponent(e)));for(var i=new Uint8Array(e.length),n=0;n<e.length;n++)i[n]=e.charCodeAt(n);return i},Me=function(e,t,i){var n=void 0===i?{}:i,s=n.offset,r=void 0===s?0:s,a=n.mask,o=void 0===a?[]:a;e=Oe(e);var d=(t=Oe(t)).every?t.every:Array.prototype.every;return t.length&&e.length-r>=t.length&&d.call(t,(function(t,i){return t===(o[i]?o[i]&e[r+i]:e[r+i])}))};const Be=function(e,t){return e.start(t)+"-"+e.end(t)},Ne=function(e,t){const i=e.toString(16);return"00".substring(0,2-i.length)+i+(t%2?" ":"")},Fe=function(e){return e>=32&&e<126?String.fromCharCode(e):"."},$e=function(e){const t={};return Object.keys(e).forEach((i=>{const n=e[i];ke(n)?t[i]={bytes:n.buffer,byteOffset:n.byteOffset,byteLength:n.byteLength}:t[i]=n})),t},qe=function(e){const t=e.byterange||{length:1/0,offset:0};return[t.length,t.offset,e.resolvedUri].join(",")},We=function(e){return e.resolvedUri},Ge=e=>{const t=Array.prototype.slice.call(e),i=16;let n,s,r="";for(let e=0;e<t.length/i;e++)n=t.slice(e*i,e*i+i).map(Ne).join(""),s=t.slice(e*i,e*i+i).map(Fe).join(""),r+=n+" "+s+"\n";return r};var Ve=Object.freeze({__proto__:null,createTransferableMessage:$e,initSegmentId:qe,segmentKeyId:We,hexDump:Ge,tagDump:({bytes:e})=>Ge(e),textRanges:e=>{let t,i="";for(t=0;t<e.length;t++)i+=Be(e,t)+" ";return i}});const He=({programTime:e,playlist:t,retryCount:i=2,seekTo:n,pauseAfterSeek:s=!0,tech:r,callback:a})=>{if(!a)throw new Error("seekToProgramTime: callback must be provided");if(void 0===e||!t||!n)return a({message:"seekToProgramTime: programTime, seekTo and playlist must be provided"});if(!t.endList&&!r.hasStarted_)return a({message:"player must be playing a live stream to start buffering"});if(!(e=>{if(!e.segments||0===e.segments.length)return!1;for(let t=0;t<e.segments.length;t++)if(!e.segments[t].dateTimeObject)return!1;return!0})(t))return a({message:"programDateTime tags must be provided in the manifest "+t.resolvedUri});const o=((e,t)=>{let i;try{i=new Date(e)}catch(e){return null}if(!t||!t.segments||0===t.segments.length)return null;let n=t.segments[0];if(i<n.dateTimeObject)return null;for(let e=0;e<t.segments.length-1&&(n=t.segments[e],!(i<t.segments[e+1].dateTimeObject));e++);const s=t.segments[t.segments.length-1],r=s.dateTimeObject,a=s.videoTimingInfo?(o=s.videoTimingInfo).transmuxedPresentationEnd-o.transmuxedPresentationStart-o.transmuxerPrependedSeconds:s.duration+.25*s.duration;var o;return i>new Date(r.getTime()+1e3*a)?null:(i>r&&(n=s),{segment:n,estimatedStart:n.videoTimingInfo?n.videoTimingInfo.transmuxedPresentationStart:oe.duration(t,t.mediaSequence+t.segments.indexOf(n)),type:n.videoTimingInfo?"accurate":"estimate"})})(e,t);if(!o)return a({message:`${e} was not found in the stream`});const d=o.segment,u=((e,t)=>{let i,n;try{i=new Date(e),n=new Date(t)}catch(e){}const s=i.getTime();return(n.getTime()-s)/1e3})(d.dateTimeObject,e);if("estimate"===o.type)return 0===i?a({message:`${e} is not buffered yet. Try again`}):(n(o.estimatedStart+u),void r.one("seeked",(()=>{He({programTime:e,playlist:t,retryCount:i-1,seekTo:n,pauseAfterSeek:s,tech:r,callback:a})})));const l=d.start+u;r.one("seeked",(()=>a(null,r.currentTime()))),s&&r.pause(),n(l)},je=e=>!!e&&"object"==typeof e,Xe=(...e)=>e.reduce(((e,t)=>("object"!=typeof t||Object.keys(t).forEach((i=>{Array.isArray(e[i])&&Array.isArray(t[i])?e[i]=e[i].concat(t[i]):je(e[i])&&je(t[i])?e[i]=Xe(e[i],t[i]):e[i]=t[i]})),e)),{}),ze=e=>Object.keys(e).map((t=>e[t])),Qe=e=>e.reduce(((e,t)=>e.concat(t)),[]),Ye=e=>{if(!e.length)return[];const t=[];for(let i=0;i<e.length;i++)t.push(e[i]);return t};const Ke=({baseUrl:e="",source:t="",range:i="",indexRange:n=""})=>{const s={uri:t,resolvedUri:d(e||"",t)};if(i||n){const e=(i||n).split("-");let t,r=window.BigInt?window.BigInt(e[0]):parseInt(e[0],10),a=window.BigInt?window.BigInt(e[1]):parseInt(e[1],10);r<Number.MAX_SAFE_INTEGER&&"bigint"==typeof r&&(r=Number(r)),a<Number.MAX_SAFE_INTEGER&&"bigint"==typeof a&&(a=Number(a)),t="bigint"==typeof a||"bigint"==typeof r?window.BigInt(a)-window.BigInt(r)+window.BigInt(1):a-r+1,"bigint"==typeof t&&t<Number.MAX_SAFE_INTEGER&&(t=Number(t)),s.byterange={length:t,offset:r}}return s},Je=e=>(e&&"number"!=typeof e&&(e=parseInt(e,10)),isNaN(e)?null:e),Ze={static(e){const{duration:t,timescale:i=1,sourceDuration:n,periodDuration:s}=e,r=Je(e.endNumber),a=t/i;return"number"==typeof r?{start:0,end:r}:"number"==typeof s?{start:0,end:s/a}:{start:0,end:n/a}},dynamic(e){const{NOW:t,clientOffset:i,availabilityStartTime:n,timescale:s=1,duration:r,periodStart:a=0,minimumUpdatePeriod:o=0,timeShiftBufferDepth:d=1/0}=e,u=Je(e.endNumber),l=(t+i)/1e3,h=n+a,c=l+o-h,p=Math.ceil(c*s/r),m=Math.floor((l-h-d)*s/r),f=Math.floor((l-h)*s/r);return{start:Math.max(0,m),end:"number"==typeof u?u:Math.min(p,f)}}},et=e=>{const{type:t,duration:i,timescale:n=1,periodDuration:s,sourceDuration:r}=e,{start:a,end:o}=Ze[t](e),d=((e,t)=>{const i=[];for(let n=e;n<t;n++)i.push(n);return i})(a,o).map((e=>t=>{const{duration:i,timescale:n=1,periodStart:s,startNumber:r=1}=e;return{number:r+t,duration:i/n,timeline:s,time:t*i}})(e));if("static"===t){const e=d.length-1,t="number"==typeof s?s:r;d[e].duration=t-i/n*e}return d},tt=e=>{const{baseUrl:t,initialization:i={},sourceDuration:n,indexRange:s="",periodStart:r,presentationTime:a,number:o=0,duration:d}=e;if(!t)throw new Error("NO_BASE_URL");const u=Ke({baseUrl:t,source:i.sourceURL,range:i.range}),l=Ke({baseUrl:t,source:t,indexRange:s});if(l.map=u,d){const t=et(e);t.length&&(l.duration=t[0].duration,l.timeline=t[0].timeline)}else n&&(l.duration=n,l.timeline=r);return l.presentationTime=a||r,l.number=o,[l]},it=(e,t,i)=>{const n=e.sidx.map?e.sidx.map:null,s=e.sidx.duration,r=e.timeline||0,a=e.sidx.byterange,o=a.offset+a.length,d=t.timescale,u=t.references.filter((e=>1!==e.referenceType)),l=[],h=e.endList?"static":"dynamic",c=e.sidx.timeline;let p,m=c,f=e.mediaSequence||0;p="bigint"==typeof t.firstOffset?window.BigInt(o)+t.firstOffset:o+t.firstOffset;for(let e=0;e<u.length;e++){const a=t.references[e],o=a.referencedSize,u=a.subsegmentDuration;let g;g="bigint"==typeof p?p+window.BigInt(o)-window.BigInt(1):p+o-1;const y=tt({baseUrl:i,timescale:d,timeline:r,periodStart:c,presentationTime:m,number:f,duration:u,sourceDuration:s,indexRange:`${p}-${g}`,type:h})[0];n&&(y.map=n),l.push(y),p+="bigint"==typeof p?window.BigInt(o):o,m+=u/d,f++}return e.segments=l,e},nt=["AUDIO","SUBTITLES"],st=e=>{return(t=e,i=({timeline:e})=>e,ze(t.reduce(((e,t)=>(t.forEach((t=>{e[i(t)]=t})),e)),{}))).sort(((e,t)=>e.timeline>t.timeline?1:-1));var t,i},rt=e=>{let t=[];var i,n;return i=e,n=(e,i,n,s)=>{t=t.concat(e.playlists||[])},nt.forEach((function(e){for(var t in i.mediaGroups[e])for(var s in i.mediaGroups[e][t]){var r=i.mediaGroups[e][t][s];n(r)}})),t},at=({playlist:e,mediaSequence:t})=>{e.mediaSequence=t,e.segments.forEach(((t,i)=>{t.number=e.mediaSequence+i}))},ot=e=>e&&e.uri+"-"+(e=>{let t;return t="bigint"==typeof e.offset||"bigint"==typeof e.length?window.BigInt(e.offset)+window.BigInt(e.length)-window.BigInt(1):e.offset+e.length-1,`${e.offset}-${t}`})(e.byterange),dt=e=>ze(e.reduce(((e,t)=>{const i=t.attributes.id+(t.attributes.lang||"");return e[i]?(t.segments&&(t.segments[0]&&(t.segments[0].discontinuity=!0),e[i].segments.push(...t.segments)),t.attributes.contentProtection&&(e[i].attributes.contentProtection=t.attributes.contentProtection)):(e[i]=t,e[i].attributes.timelineStarts=[]),e[i].attributes.timelineStarts.push({start:t.attributes.periodStart,timeline:t.attributes.periodStart}),e}),{})).map((e=>{var t;return e.discontinuityStarts=(t=e.segments||[],"discontinuity",t.reduce(((e,t,i)=>(t.discontinuity&&e.push(i),e)),[])),e})),ut=(e,t)=>{const i=ot(e.sidx),n=i&&t[i]&&t[i].sidx;return n&&it(e,n,e.sidx.resolvedUri),e},lt=(e,t={})=>{if(!Object.keys(t).length)return e;for(const i in e)e[i]=ut(e[i],t);return e},ht=({attributes:e,segments:t,sidx:i,discontinuityStarts:n})=>{const s={attributes:{NAME:e.id,AUDIO:"audio",SUBTITLES:"subs",RESOLUTION:{width:e.width,height:e.height},CODECS:e.codecs,BANDWIDTH:e.bandwidth,"PROGRAM-ID":1},uri:"",endList:"static"===e.type,timeline:e.periodStart,resolvedUri:"",targetDuration:e.duration,discontinuityStarts:n,timelineStarts:e.timelineStarts,segments:t};return e.frameRate&&(s.attributes["FRAME-RATE"]=e.frameRate),e.contentProtection&&(s.contentProtection=e.contentProtection),i&&(s.sidx=i),s},ct=({attributes:e})=>"video/mp4"===e.mimeType||"video/webm"===e.mimeType||"video"===e.contentType,pt=({attributes:e})=>"audio/mp4"===e.mimeType||"audio/webm"===e.mimeType||"audio"===e.contentType,mt=({attributes:e})=>"text/vtt"===e.mimeType||"text"===e.contentType,ft=e=>e?Object.keys(e).reduce(((t,i)=>{const n=e[i];return t.concat(n.playlists)}),[]):[],gt=({dashPlaylists:e,locations:t,sidxMapping:i={},previousManifest:n})=>{if(!e.length)return{};const{sourceDuration:s,type:r,suggestedPresentationDelay:a,minimumUpdatePeriod:o}=e[0].attributes,d=dt(e.filter(ct)).map(ht),u=dt(e.filter(pt)),l=dt(e.filter(mt)),h=e.map((e=>e.attributes.captionServices)).filter(Boolean),c={allowCache:!0,discontinuityStarts:[],segments:[],endList:!0,mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:"",duration:s,playlists:lt(d,i)};o>=0&&(c.minimumUpdatePeriod=1e3*o),t&&(c.locations=t),"dynamic"===r&&(c.suggestedPresentationDelay=a);const p=0===c.playlists.length,m=u.length?((e,t={},i=!1)=>{let n;const s=e.reduce(((e,s)=>{const r=s.attributes.role&&s.attributes.role.value||"",a=s.attributes.lang||"";let o=s.attributes.label||"main";if(a&&!s.attributes.label){const e=r?` (${r})`:"";o=`${s.attributes.lang}${e}`}e[o]||(e[o]={language:a,autoselect:!0,default:"main"===r,playlists:[],uri:""});const d=ut((({attributes:e,segments:t,sidx:i,mediaSequence:n,discontinuitySequence:s,discontinuityStarts:r},a)=>{const o={attributes:{NAME:e.id,BANDWIDTH:e.bandwidth,CODECS:e.codecs,"PROGRAM-ID":1},uri:"",endList:"static"===e.type,timeline:e.periodStart,resolvedUri:"",targetDuration:e.duration,discontinuitySequence:s,discontinuityStarts:r,timelineStarts:e.timelineStarts,mediaSequence:n,segments:t};return e.contentProtection&&(o.contentProtection=e.contentProtection),i&&(o.sidx=i),a&&(o.attributes.AUDIO="audio",o.attributes.SUBTITLES="subs"),o})(s,i),t);return e[o].playlists.push(d),void 0===n&&"main"===r&&(n=s,n.default=!0),e}),{});return n||(s[Object.keys(s)[0]].default=!0),s})(u,i,p):null,f=l.length?((e,t={})=>e.reduce(((e,i)=>{const n=i.attributes.lang||"text";return e[n]||(e[n]={language:n,default:!1,autoselect:!1,playlists:[],uri:""}),e[n].playlists.push(ut((({attributes:e,segments:t,mediaSequence:i,discontinuityStarts:n,discontinuitySequence:s})=>{void 0===t&&(t=[{uri:e.baseUrl,timeline:e.periodStart,resolvedUri:e.baseUrl||"",duration:e.sourceDuration,number:0}],e.duration=e.sourceDuration);const r={NAME:e.id,BANDWIDTH:e.bandwidth,"PROGRAM-ID":1};return e.codecs&&(r.CODECS=e.codecs),{attributes:r,uri:"",endList:"static"===e.type,timeline:e.periodStart,resolvedUri:e.baseUrl||"",targetDuration:e.duration,timelineStarts:e.timelineStarts,discontinuityStarts:n,discontinuitySequence:s,mediaSequence:i,segments:t}})(i),t)),e}),{}))(l,i):null,g=d.concat(ft(m),ft(f)),y=g.map((({timelineStarts:e})=>e));var _,T;return c.timelineStarts=st(y),_=g,T=c.timelineStarts,_.forEach((e=>{e.mediaSequence=0,e.discontinuitySequence=T.findIndex((function({timeline:t}){return t===e.timeline})),e.segments&&e.segments.forEach(((e,t)=>{e.number=t}))})),m&&(c.mediaGroups.AUDIO.audio=m),f&&(c.mediaGroups.SUBTITLES.subs=f),h.length&&(c.mediaGroups["CLOSED-CAPTIONS"].cc=h.reduce(((e,t)=>t?(t.forEach((t=>{const{channel:i,language:n}=t;e[n]={autoselect:!1,default:!1,instreamId:i,language:n},t.hasOwnProperty("aspectRatio")&&(e[n].aspectRatio=t.aspectRatio),t.hasOwnProperty("easyReader")&&(e[n].easyReader=t.easyReader),t.hasOwnProperty("3D")&&(e[n]["3D"]=t["3D"])})),e):e),{})),n?(({oldManifest:e,newManifest:t})=>{const i=e.playlists.concat(rt(e)),n=t.playlists.concat(rt(t));return t.timelineStarts=st([e.timelineStarts,t.timelineStarts]),(({oldPlaylists:e,newPlaylists:t,timelineStarts:i})=>{t.forEach((t=>{t.discontinuitySequence=i.findIndex((function({timeline:e}){return e===t.timeline}));const n=((e,t)=>{for(let i=0;i<e.length;i++)if(e[i].attributes.NAME===t)return e[i];return null})(e,t.attributes.NAME);if(!n)return;if(t.sidx)return;const s=t.segments[0],r=n.segments.findIndex((function(e){return Math.abs(e.presentationTime-s.presentationTime)<.016666666666666666}));if(-1===r)return at({playlist:t,mediaSequence:n.mediaSequence+n.segments.length}),t.segments[0].discontinuity=!0,t.discontinuityStarts.unshift(0),void((!n.segments.length&&t.timeline>n.timeline||n.segments.length&&t.timeline>n.segments[n.segments.length-1].timeline)&&t.discontinuitySequence--);n.segments[r].discontinuity&&!s.discontinuity&&(s.discontinuity=!0,t.discontinuityStarts.unshift(0),t.discontinuitySequence--),at({playlist:t,mediaSequence:n.segments[r].number})}))})({oldPlaylists:i,newPlaylists:n,timelineStarts:t.timelineStarts}),t})({oldManifest:n,newManifest:c}):c},yt=(e,t,i)=>{const{NOW:n,clientOffset:s,availabilityStartTime:r,timescale:a=1,periodStart:o=0,minimumUpdatePeriod:d=0}=e,u=(n+s)/1e3+d-(r+o);return Math.ceil((u*a-t)/i)},_t=(e,t)=>{const{type:i,minimumUpdatePeriod:n=0,media:s="",sourceDuration:r,timescale:a=1,startNumber:o=1,periodStart:d}=e,u=[];let l=-1;for(let h=0;h<t.length;h++){const c=t[h],p=c.d,m=c.r||0,f=c.t||0;let g;if(l<0&&(l=f),f&&f>l&&(l=f),m<0){const o=h+1;g=o===t.length?"dynamic"===i&&n>0&&s.indexOf("$Number$")>0?yt(e,l,p):(r*a-l)/p:(t[o].t-l)/p}else g=m+1;const y=o+u.length+g;let _=o+u.length;for(;_<y;)u.push({number:_,duration:p/a,time:l,timeline:d}),l+=p,_++}return u},Tt=/\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g,bt=(e,t)=>e.replace(Tt,(e=>(t,i,n,s)=>{if("$$"===t)return"$";if(void 0===e[i])return t;const r=""+e[i];return"RepresentationID"===i?r:(s=n?parseInt(s,10):1,r.length>=s?r:`${new Array(s-r.length+1).join("0")}${r}`)})(t)),St=(e,t)=>{const i={RepresentationID:e.id,Bandwidth:e.bandwidth||0},{initialization:n={sourceURL:"",range:""}}=e,s=Ke({baseUrl:e.baseUrl,source:bt(n.sourceURL,i),range:n.range}),r=((e,t)=>e.duration||t?e.duration?et(e):_t(e,t):[{number:e.startNumber||1,duration:e.sourceDuration,time:0,timeline:e.periodStart}])(e,t);return r.map((t=>{i.Number=t.number,i.Time=t.time;const n=bt(e.media||"",i),r=e.timescale||1,a=e.presentationTimeOffset||0,o=e.periodStart+(t.time-a)/r;return{uri:n,timeline:t.timeline,duration:t.duration,resolvedUri:d(e.baseUrl||"",n),map:s,number:t.number,presentationTime:o}}))},vt=(e,t)=>{const{duration:i,segmentUrls:n=[],periodStart:s}=e;if(!i&&!t||i&&t)throw new Error("SEGMENT_TIME_UNSPECIFIED");const r=n.map((t=>((e,t)=>{const{baseUrl:i,initialization:n={}}=e,s=Ke({baseUrl:i,source:n.sourceURL,range:n.range}),r=Ke({baseUrl:i,source:t.media,range:t.mediaRange});return r.map=s,r})(e,t)));let a;return i&&(a=et(e)),t&&(a=_t(e,t)),a.map(((t,i)=>{if(r[i]){const n=r[i],a=e.timescale||1,o=e.presentationTimeOffset||0;return n.timeline=t.timeline,n.duration=t.duration,n.number=t.number,n.presentationTime=s+(t.time-o)/a,n}})).filter((e=>e))},wt=({attributes:e,segmentInfo:t})=>{let i,n;t.template?(n=St,i=Xe(e,t.template)):t.base?(n=tt,i=Xe(e,t.base)):t.list&&(n=vt,i=Xe(e,t.list));const s={attributes:e};if(!n)return s;const r=n(i,t.segmentTimeline);if(i.duration){const{duration:e,timescale:t=1}=i;i.duration=e/t}else r.length?i.duration=r.reduce(((e,t)=>Math.max(e,Math.ceil(t.duration))),0):i.duration=0;return s.attributes=i,s.segments=r,t.base&&i.indexRange&&(s.sidx=r[0],s.segments=[]),s},It=(e,t)=>Ye(e.childNodes).filter((({tagName:e})=>e===t)),Et=e=>e.textContent.trim(),At=e=>{const t=/P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/.exec(e);if(!t)return 0;const[i,n,s,r,a,o]=t.slice(1);return 31536e3*parseFloat(i||0)+2592e3*parseFloat(n||0)+86400*parseFloat(s||0)+3600*parseFloat(r||0)+60*parseFloat(a||0)+parseFloat(o||0)},Lt={mediaPresentationDuration:e=>At(e),availabilityStartTime(e){return/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(t=e)&&(t+="Z"),Date.parse(t)/1e3;var t},minimumUpdatePeriod:e=>At(e),suggestedPresentationDelay:e=>At(e),type:e=>e,timeShiftBufferDepth:e=>At(e),start:e=>At(e),width:e=>parseInt(e,10),height:e=>parseInt(e,10),bandwidth:e=>parseInt(e,10),frameRate:e=>(e=>parseFloat(e.split("/").reduce(((e,t)=>e/t))))(e),startNumber:e=>parseInt(e,10),timescale:e=>parseInt(e,10),presentationTimeOffset:e=>parseInt(e,10),duration(e){const t=parseInt(e,10);return isNaN(t)?At(e):t},d:e=>parseInt(e,10),t:e=>parseInt(e,10),r:e=>parseInt(e,10),DEFAULT:e=>e},xt=e=>e&&e.attributes?Ye(e.attributes).reduce(((e,t)=>{const i=Lt[t.name]||Lt.DEFAULT;return e[t.name]=i(t.value),e}),{}):{},Dt={"urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b":"org.w3.clearkey","urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed":"com.widevine.alpha","urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95":"com.microsoft.playready","urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb":"com.adobe.primetime"},kt=(e,t)=>t.length?Qe(e.map((function(e){return t.map((function(t){return d(e,Et(t))}))}))):e,Ot=e=>{const t=It(e,"SegmentTemplate")[0],i=It(e,"SegmentList")[0],n=i&&It(i,"SegmentURL").map((e=>Xe({tag:"SegmentURL"},xt(e)))),s=It(e,"SegmentBase")[0],r=i||t,a=r&&It(r,"SegmentTimeline")[0],o=i||s||t,d=o&&It(o,"Initialization")[0],u=t&&xt(t);u&&d?u.initialization=d&&xt(d):u&&u.initialization&&(u.initialization={sourceURL:u.initialization});const l={template:u,segmentTimeline:a&&It(a,"S").map((e=>xt(e))),list:i&&Xe(xt(i),{segmentUrls:n,initialization:xt(d)}),base:s&&Xe(xt(s),{initialization:xt(d)})};return Object.keys(l).forEach((e=>{l[e]||delete l[e]})),l},Pt=(e,t)=>(i,n)=>{const s=kt(t,It(i.node,"BaseURL")),r=Xe(e,{periodStart:i.attributes.start});"number"==typeof i.attributes.duration&&(r.periodDuration=i.attributes.duration);const a=It(i.node,"AdaptationSet"),o=Ot(i.node);return Qe(a.map(((e,t,i)=>n=>{const s=xt(n),r=kt(t,It(n,"BaseURL")),a=It(n,"Role")[0],o={role:xt(a)};let d=Xe(e,s,o);const u=It(n,"Accessibility")[0],l="urn:scte:dash:cc:cea-608:2015"===(h=xt(u)).schemeIdUri?("string"!=typeof h.value?[]:h.value.split(";")).map((e=>{let t,i;return i=e,/^CC\d=/.test(e)?[t,i]=e.split("="):/^CC\d$/.test(e)&&(t=e),{channel:t,language:i}})):"urn:scte:dash:cc:cea-708:2015"===h.schemeIdUri?("string"!=typeof h.value?[]:h.value.split(";")).map((e=>{const t={channel:void 0,language:void 0,aspectRatio:1,easyReader:0,"3D":0};if(/=/.test(e)){const[i,n=""]=e.split("=");t.channel=i,t.language=e,n.split(",").forEach((e=>{const[i,n]=e.split(":");"lang"===i?t.language=n:"er"===i?t.easyReader=Number(n):"war"===i?t.aspectRatio=Number(n):"3D"===i&&(t["3D"]=Number(n))}))}else t.language=e;return t.channel&&(t.channel="SERVICE"+t.channel),t})):void 0;var h;l&&(d=Xe(d,{captionServices:l}));const c=It(n,"Label")[0];if(c&&c.childNodes.length){const e=c.childNodes[0].nodeValue.trim();d=Xe(d,{label:e})}const p=It(n,"ContentProtection").reduce(((e,t)=>{const i=xt(t);i.schemeIdUri&&(i.schemeIdUri=i.schemeIdUri.toLowerCase());const n=Dt[i.schemeIdUri];if(n){e[n]={attributes:i};const s=It(t,"cenc:pssh")[0];if(s){const t=Et(s);e[n].pssh=t&&m(t)}}return e}),{});Object.keys(p).length&&(d=Xe(d,{contentProtection:p}));const f=Ot(n),g=It(n,"Representation"),y=Xe(i,f);return Qe(g.map(((e,t,i)=>n=>{const s=It(n,"BaseURL"),r=kt(t,s),a=Xe(e,xt(n)),o=Ot(n);return r.map((e=>({segmentInfo:Xe(i,o),attributes:Xe(a,{baseUrl:e})})))})(d,r,y)))})(r,s,o)))},Ut=e=>{if(""===e)throw new Error("DASH_EMPTY_MANIFEST");const t=new i.DOMParser;let n,s;try{n=t.parseFromString(e,"application/xml"),s=n&&"MPD"===n.documentElement.tagName?n.documentElement:null}catch(e){}if(!s||s&&s.getElementsByTagName("parsererror").length>0)throw new Error("DASH_INVALID_XML");return s};var Ct=Math.pow(2,32),Rt=function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength);return i.getBigUint64?(t=i.getBigUint64(0))<Number.MAX_SAFE_INTEGER?Number(t):t:i.getUint32(0)*Ct+i.getUint32(4)},Mt=Oe([73,68,51]),Bt=function e(t,i){return void 0===i&&(i=0),(t=Oe(t)).length-i<10||!Me(t,Mt,{offset:i})?i:(i+=function(e,t){void 0===t&&(t=0);var i=(e=Oe(e))[t+5],n=e[t+6]<<21|e[t+7]<<14|e[t+8]<<7|e[t+9];return(16&i)>>4?n+20:n+10}(t,i),e(t,i))},Nt=function(e){return"string"==typeof e?Re(e):e},Ft=function e(t,i,n){void 0===n&&(n=!1),i=function(e){return Array.isArray(e)?e.map((function(e){return Nt(e)})):[Nt(e)]}(i),t=Oe(t);var s=[];if(!i.length)return s;for(var r=0;r<t.length;){var a=(t[r]<<24|t[r+1]<<16|t[r+2]<<8|t[r+3])>>>0,o=t.subarray(r+4,r+8);if(0===a)break;var d=r+a;if(d>t.length){if(n)break;d=t.length}var u=t.subarray(r+8,d);Me(o,i[0])&&(1===i.length?s.push(u):s.push.apply(s,e(u,i.slice(1),n))),r=d}return s},$t={EBML:Oe([26,69,223,163]),DocType:Oe([66,130]),Segment:Oe([24,83,128,103]),SegmentInfo:Oe([21,73,169,102]),Tracks:Oe([22,84,174,107]),Track:Oe([174]),TrackNumber:Oe([215]),DefaultDuration:Oe([35,227,131]),TrackEntry:Oe([174]),TrackType:Oe([131]),FlagDefault:Oe([136]),CodecID:Oe([134]),CodecPrivate:Oe([99,162]),VideoTrack:Oe([224]),AudioTrack:Oe([225]),Cluster:Oe([31,67,182,117]),Timestamp:Oe([231]),TimestampScale:Oe([42,215,177]),BlockGroup:Oe([160]),BlockDuration:Oe([155]),Block:Oe([161]),SimpleBlock:Oe([163])},qt=[128,64,32,16,8,4,2,1],Wt=function(e,t,i,n){void 0===i&&(i=!0),void 0===n&&(n=!1);var s=function(e){for(var t=1,i=0;i<qt.length&&!(e&qt[i]);i++)t++;return t}(e[t]),r=e.subarray(t,t+s);return i&&((r=Array.prototype.slice.call(e,t,t+s))[0]^=qt[s-1]),{length:s,value:Ce(r,{signed:n}),bytes:r}},Gt=function e(t){return"string"==typeof t?t.match(/.{1,2}/g).map((function(t){return e(t)})):"number"==typeof t?function(e,t){var i=(void 0===t?{}:t).le,n=void 0!==i&&i;("bigint"!=typeof e&&"number"!=typeof e||"number"==typeof e&&e!=e)&&(e=0);for(var s,r=(s=e=Pe(e),Math.ceil(function(e){return e.toString(2).length}(s)/8)),a=new Uint8Array(new ArrayBuffer(r)),o=0;o<r;o++){var d=n?o:Math.abs(o+1-a.length);a[d]=Number(e/Ue[o]&Pe(255)),e<0&&(a[d]=Math.abs(~a[d]),a[d]-=0===o?1:2)}return a}(t):t},Vt=function e(t,i,n){if(n>=i.length)return i.length;var s=Wt(i,n,!1);if(Me(t.bytes,s.bytes))return n;var r=Wt(i,n+s.length);return e(t,i,n+r.length+r.value+s.length)},Ht=function e(t,i){i=function(e){return Array.isArray(e)?e.map((function(e){return Gt(e)})):[Gt(e)]}(i),t=Oe(t);var n=[];if(!i.length)return n;for(var s=0;s<t.length;){var r=Wt(t,s,!1),a=Wt(t,s+r.length),o=s+r.length+a.length;127===a.value&&(a.value=Vt(r,t,o),a.value!==t.length&&(a.value-=o));var d=o+a.value>t.length?t.length:o+a.value,u=t.subarray(o,d);Me(i[0],r.bytes)&&(1===i.length?n.push(u):n=n.concat(e(u,i.slice(1)))),s+=r.length+a.length+u.length}return n},jt=Oe([0,0,0,1]),Xt=Oe([0,0,1]),zt=Oe([0,0,3]),Qt=function(e){for(var t=[],i=1;i<e.length-2;)Me(e.subarray(i,i+3),zt)&&(t.push(i+2),i++),i++;if(0===t.length)return e;var n=e.length-t.length,s=new Uint8Array(n),r=0;for(i=0;i<n;r++,i++)r===t[0]&&(r++,t.shift()),s[i]=e[r];return s},Yt=function(e,t,i,n){void 0===n&&(n=1/0),e=Oe(e),i=[].concat(i);for(var s,r=0,a=0;r<e.length&&(a<n||s);){var o=void 0;if(Me(e.subarray(r),jt)?o=4:Me(e.subarray(r),Xt)&&(o=3),o){if(a++,s)return Qt(e.subarray(s,r));var d=void 0;"h264"===t?d=31&e[r+o]:"h265"===t&&(d=e[r+o]>>1&63),-1!==i.indexOf(d)&&(s=r+o),r+=o+("h264"===t?1:2)}else r++}return e.subarray(0,0)},Kt={webm:Oe([119,101,98,109]),matroska:Oe([109,97,116,114,111,115,107,97]),flac:Oe([102,76,97,67]),ogg:Oe([79,103,103,83]),ac3:Oe([11,119]),riff:Oe([82,73,70,70]),avi:Oe([65,86,73]),wav:Oe([87,65,86,69]),"3gp":Oe([102,116,121,112,51,103]),mp4:Oe([102,116,121,112]),fmp4:Oe([115,116,121,112]),mov:Oe([102,116,121,112,113,116]),moov:Oe([109,111,111,118]),moof:Oe([109,111,111,102])},Jt={aac:function(e){var t=Bt(e);return Me(e,[255,16],{offset:t,mask:[255,22]})},mp3:function(e){var t=Bt(e);return Me(e,[255,2],{offset:t,mask:[255,6]})},webm:function(e){var t=Ht(e,[$t.EBML,$t.DocType])[0];return Me(t,Kt.webm)},mkv:function(e){var t=Ht(e,[$t.EBML,$t.DocType])[0];return Me(t,Kt.matroska)},mp4:function(e){return!Jt["3gp"](e)&&!Jt.mov(e)&&(!(!Me(e,Kt.mp4,{offset:4})&&!Me(e,Kt.fmp4,{offset:4}))||!(!Me(e,Kt.moof,{offset:4})&&!Me(e,Kt.moov,{offset:4}))||void 0)},mov:function(e){return Me(e,Kt.mov,{offset:4})},"3gp":function(e){return Me(e,Kt["3gp"],{offset:4})},ac3:function(e){var t=Bt(e);return Me(e,Kt.ac3,{offset:t})},ts:function(e){if(e.length<189&&e.length>=1)return 71===e[0];for(var t=0;t+188<e.length&&t<188;){if(71===e[t]&&71===e[t+188])return!0;t+=1}return!1},flac:function(e){var t=Bt(e);return Me(e,Kt.flac,{offset:t})},ogg:function(e){return Me(e,Kt.ogg)},avi:function(e){return Me(e,Kt.riff)&&Me(e,Kt.avi,{offset:8})},wav:function(e){return Me(e,Kt.riff)&&Me(e,Kt.wav,{offset:8})},h264:function(e){return function(e,t,i){return Yt(e,"h264",7,3)}(e).length},h265:function(e){return function(e,t,i){return Yt(e,"h265",[32,33],3)}(e).length}},Zt=Object.keys(Jt).filter((function(e){return"ts"!==e&&"h264"!==e&&"h265"!==e})).concat(["ts","h264","h265"]);Zt.forEach((function(e){var t=Jt[e];Jt[e]=function(e){return t(Oe(e))}}));var ei=Jt,ti=function(e){e=Oe(e);for(var t=0;t<Zt.length;t++){var i=Zt[t];if(ei[i](e))return i}return""};const ii=(e,t)=>{if(4===e.readyState)return t()},{EventTarget:ni}=s.default,si=function(e,t){if(!ye(e,t))return!1;if(e.sidx&&t.sidx&&(e.sidx.offset!==t.sidx.offset||e.sidx.length!==t.sidx.length))return!1;if(!e.sidx&&t.sidx||e.sidx&&!t.sidx)return!1;if(e.segments&&!t.segments||!e.segments&&t.segments)return!1;if(!e.segments&&!t.segments)return!0;for(let i=0;i<e.segments.length;i++){const n=e.segments[i],s=t.segments[i];if(n.uri!==s.uri)return!1;if(!n.byterange&&!s.byterange)continue;const r=n.byterange,a=s.byterange;if(r&&!a||!r&&a)return!1;if(r.offset!==a.offset||r.length!==a.length)return!1}return!0},ri=(e,t)=>(Boolean(!e.map&&!t.map)||Boolean(e.map&&t.map&&e.map.byterange.offset===t.map.byterange.offset&&e.map.byterange.length===t.map.byterange.length))&&e.uri===t.uri&&e.byterange.offset===t.byterange.offset&&e.byterange.length===t.byterange.length,ai=(e,t)=>{const i={};for(const n in e){const s=e[n].sidx;if(s){const e=ot(s);if(!t[e])break;const n=t[e].sidxInfo;ri(n,s)&&(i[e]=t[e])}}return i};class oi extends ni{constructor(e,t,i={},n){super(),this.mainPlaylistLoader_=n||this,n||(this.isMain_=!0);const{withCredentials:s=!1}=i;if(this.vhs_=t,this.withCredentials=s,!e)throw new Error("A non-empty playlist URL or object is required");this.on("minimumUpdatePeriod",(()=>{this.refreshXml_()})),this.on("mediaupdatetimeout",(()=>{this.refreshMedia_(this.media().id)})),this.state="HAVE_NOTHING",this.loadedPlaylists_={},this.logger_=h("DashPlaylistLoader"),this.isMain_?(this.mainPlaylistLoader_.srcUrl=e,this.mainPlaylistLoader_.sidxMapping_={}):this.childPlaylist_=e}requestErrored_(e,t,i){return!this.request||(this.request=null,e?(this.error="object"!=typeof e||e instanceof Error?{status:t.status,message:"DASH request error at URL: "+t.uri,response:t.response,code:2}:e,i&&(this.state=i),this.trigger("error"),!0):void 0)}addSidxSegments_(e,t,i){const n=e.sidx&&ot(e.sidx);if(!e.sidx||!n||this.mainPlaylistLoader_.sidxMapping_[n])return void(this.mediaRequest_=window.setTimeout((()=>i(!1)),0));const s=l(e.sidx.resolvedUri),r=(s,r)=>{if(this.requestErrored_(s,r,t))return;const a=this.mainPlaylistLoader_.sidxMapping_;let o;try{o=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),i={version:e[0],flags:new Uint8Array(e.subarray(1,4)),references:[],referenceId:t.getUint32(4),timescale:t.getUint32(8)},n=12;0===i.version?(i.earliestPresentationTime=t.getUint32(n),i.firstOffset=t.getUint32(n+4),n+=8):(i.earliestPresentationTime=Rt(e.subarray(n)),i.firstOffset=Rt(e.subarray(n+8)),n+=16),n+=2;var s=t.getUint16(n);for(n+=2;s>0;n+=12,s--)i.references.push({referenceType:(128&e[n])>>>7,referencedSize:2147483647&t.getUint32(n),subsegmentDuration:t.getUint32(n+4),startsWithSap:!!(128&e[n+8]),sapType:(112&e[n+8])>>>4,sapDeltaTime:268435455&t.getUint32(n+8)});return i}(Oe(r.response).subarray(8))}catch(e){return void this.requestErrored_(e,r,t)}return a[n]={sidxInfo:e.sidx,sidx:o},it(e,o,e.sidx.resolvedUri),i(!0)};this.request=((e,t,i)=>{let n,s=[],r=!1;const a=function(e,t,n,s){return t.abort(),r=!0,i(e,t,n,s)},o=function(e,t){if(r)return;if(e)return a(e,t,"",s);const i=t.responseText.substring(s&&s.byteLength||0,t.responseText.length);if(s=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];if(t=t.filter((function(e){return e&&(e.byteLength||e.length)&&"string"!=typeof e})),t.length<=1)return Oe(t[0]);var n=t.reduce((function(e,t,i){return e+(t.byteLength||t.length)}),0),s=new Uint8Array(n),r=0;return t.forEach((function(e){e=Oe(e),s.set(e,r),r+=e.byteLength})),s}(s,Re(i,!0)),n=n||Bt(s),s.length<10||n&&s.length<n+2)return ii(t,(()=>a(e,t,"",s)));const o=ti(s);return"ts"===o&&s.length<188||!o&&s.length<376?ii(t,(()=>a(e,t,"",s))):a(null,t,o,s)},d={uri:e,beforeSend(e){e.overrideMimeType("text/plain; charset=x-user-defined"),e.addEventListener("progress",(function({total:t,loaded:i}){return ve(e,null,{statusCode:e.status},o)}))}},u=t(d,(function(e,t){return ve(u,e,t,o)}));return u})(s,this.vhs_.xhr,((t,i,n,a)=>{if(t)return r(t,i);if(!n||"mp4"!==n)return r({status:i.status,message:`Unsupported ${n||"unknown"} container type for sidx segment at URL: ${s}`,response:"",playlist:e,internal:!0,playlistExclusionDuration:1/0,code:2},i);const{offset:o,length:d}=e.sidx.byterange;if(a.length>=d+o)return r(t,{response:a.subarray(o,o+d),status:i.status,uri:i.uri});this.request=this.vhs_.xhr({uri:s,responseType:"arraybuffer",headers:Ie({byterange:e.sidx.byterange})},r)}))}dispose(){this.trigger("dispose"),this.stopRequest(),this.loadedPlaylists_={},window.clearTimeout(this.minimumUpdatePeriodTimeout_),window.clearTimeout(this.mediaRequest_),window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.mediaRequest_=null,this.minimumUpdatePeriodTimeout_=null,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.off()}hasPendingRequest(){return this.request||this.mediaRequest_}stopRequest(){if(this.request){const e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e){if(!e)return this.media_;if("HAVE_NOTHING"===this.state)throw new Error("Cannot switch media playlist from "+this.state);const t=this.state;if("string"==typeof e){if(!this.mainPlaylistLoader_.main.playlists[e])throw new Error("Unknown playlist URI: "+e);e=this.mainPlaylistLoader_.main.playlists[e]}const i=!this.media_||e.id!==this.media_.id;if(i&&this.loadedPlaylists_[e.id]&&this.loadedPlaylists_[e.id].endList)return this.state="HAVE_METADATA",this.media_=e,void(i&&(this.trigger("mediachanging"),this.trigger("mediachange")));i&&(this.media_&&this.trigger("mediachanging"),this.addSidxSegments_(e,t,(i=>{this.haveMetadata({startingState:t,playlist:e})})))}haveMetadata({startingState:e,playlist:t}){this.state="HAVE_METADATA",this.loadedPlaylists_[t.id]=t,this.mediaRequest_=null,this.refreshMedia_(t.id),"HAVE_MAIN_MANIFEST"===e?this.trigger("loadedmetadata"):this.trigger("mediachange")}pause(){this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.stopRequest(),window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.isMain_&&(window.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_),this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_=null),"HAVE_NOTHING"===this.state&&(this.started=!1)}load(e){window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null;const t=this.media();if(e){const e=t?t.targetDuration/2*1e3:5e3;this.mediaUpdateTimeout=window.setTimeout((()=>this.load()),e)}else this.started?t&&!t.endList?(this.isMain_&&!this.minimumUpdatePeriodTimeout_&&(this.trigger("minimumUpdatePeriod"),this.updateMinimumUpdatePeriodTimeout_()),this.trigger("mediaupdatetimeout")):this.trigger("loadedplaylist"):this.start()}start(){this.started=!0,this.isMain_?this.requestMain_(((e,t)=>{this.haveMain_(),this.hasPendingRequest()||this.media_||this.media(this.mainPlaylistLoader_.main.playlists[0])})):this.mediaRequest_=window.setTimeout((()=>this.haveMain_()),0)}requestMain_(e){this.request=this.vhs_.xhr({uri:this.mainPlaylistLoader_.srcUrl,withCredentials:this.withCredentials},((t,i)=>{if(this.requestErrored_(t,i))return void("HAVE_NOTHING"===this.state&&(this.started=!1));const n=i.responseText!==this.mainPlaylistLoader_.mainXml_;return this.mainPlaylistLoader_.mainXml_=i.responseText,i.responseHeaders&&i.responseHeaders.date?this.mainLoaded_=Date.parse(i.responseHeaders.date):this.mainLoaded_=Date.now(),this.mainPlaylistLoader_.srcUrl=l(this.mainPlaylistLoader_.srcUrl,i),n?(this.handleMain_(),void this.syncClientServerClock_((()=>e(i,n)))):e(i,n)}))}syncClientServerClock_(e){const t=(i=this.mainPlaylistLoader_.mainXml_,(e=>{const t=It(e,"UTCTiming")[0];if(!t)return null;const i=xt(t);switch(i.schemeIdUri){case"urn:mpeg:dash:utc:http-head:2014":case"urn:mpeg:dash:utc:http-head:2012":i.method="HEAD";break;case"urn:mpeg:dash:utc:http-xsdate:2014":case"urn:mpeg:dash:utc:http-iso:2014":case"urn:mpeg:dash:utc:http-xsdate:2012":case"urn:mpeg:dash:utc:http-iso:2012":i.method="GET";break;case"urn:mpeg:dash:utc:direct:2014":case"urn:mpeg:dash:utc:direct:2012":i.method="DIRECT",i.value=Date.parse(i.value);break;default:throw new Error("UNSUPPORTED_UTC_TIMING_SCHEME")}return i})(Ut(i)));var i;return null===t?(this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e()):"DIRECT"===t.method?(this.mainPlaylistLoader_.clientOffset_=t.value-Date.now(),e()):void(this.request=this.vhs_.xhr({uri:u(this.mainPlaylistLoader_.srcUrl,t.value),method:t.method,withCredentials:this.withCredentials},((i,n)=>{if(!this.request)return;if(i)return this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e();let s;s="HEAD"===t.method?n.responseHeaders&&n.responseHeaders.date?Date.parse(n.responseHeaders.date):this.mainLoaded_:Date.parse(n.responseText),this.mainPlaylistLoader_.clientOffset_=s-Date.now(),e()})))}haveMain_(){this.state="HAVE_MAIN_MANIFEST",this.isMain_?this.trigger("loadedplaylist"):this.media_||this.media(this.childPlaylist_)}handleMain_(){this.mediaRequest_=null;const e=this.mainPlaylistLoader_.main;let t=(({mainXml:e,srcUrl:t,clientOffset:i,sidxMapping:n,previousManifest:s})=>{const r=((e,t={})=>{const i=((e,t={})=>{const{manifestUri:i="",NOW:n=Date.now(),clientOffset:s=0}=t,r=It(e,"Period");if(!r.length)throw new Error("INVALID_NUMBER_OF_PERIOD");const a=It(e,"Location"),o=xt(e),d=kt([i],It(e,"BaseURL"));o.type=o.type||"static",o.sourceDuration=o.mediaPresentationDuration||0,o.NOW=n,o.clientOffset=s,a.length&&(o.locations=a.map(Et));const u=[];return r.forEach(((e,t)=>{const i=xt(e),n=u[t-1];i.start=(({attributes:e,priorPeriodAttributes:t,mpdType:i})=>"number"==typeof e.start?e.start:t&&"number"==typeof t.start&&"number"==typeof t.duration?t.start+t.duration:t||"static"!==i?null:0)({attributes:i,priorPeriodAttributes:n?n.attributes:null,mpdType:o.type}),u.push({node:e,attributes:i})})),{locations:o.locations,representationInfo:Qe(u.map(Pt(o,d)))}})(Ut(e),t),n=i.representationInfo.map(wt);return gt({dashPlaylists:n,locations:i.locations,sidxMapping:t.sidxMapping,previousManifest:t.previousManifest})})(e,{manifestUri:t,clientOffset:i,sidxMapping:n,previousManifest:s});return ce(r,t),r})({mainXml:this.mainPlaylistLoader_.mainXml_,srcUrl:this.mainPlaylistLoader_.srcUrl,clientOffset:this.mainPlaylistLoader_.clientOffset_,sidxMapping:this.mainPlaylistLoader_.sidxMapping_,previousManifest:e});e&&(t=((e,t,i)=>{let n=!0,s=U(e,{duration:t.duration,minimumUpdatePeriod:t.minimumUpdatePeriod,timelineStarts:t.timelineStarts});for(let e=0;e<t.playlists.length;e++){const r=t.playlists[e];if(r.sidx){const e=ot(r.sidx);i&&i[e]&&i[e].sidx&&it(r,i[e].sidx,r.sidx.resolvedUri)}const a=_e(s,r,si);a&&(s=a,n=!1)}return le(t,((e,t,i,r)=>{if(e.playlists&&e.playlists.length){const a=e.playlists[0].id,o=_e(s,e.playlists[0],si);o&&(s=o,s.mediaGroups[t][i][r].playlists[0]=s.playlists[a],n=!1)}})),t.minimumUpdatePeriod!==e.minimumUpdatePeriod&&(n=!1),n?null:s})(e,t,this.mainPlaylistLoader_.sidxMapping_)),this.mainPlaylistLoader_.main=t||e;const i=this.mainPlaylistLoader_.main.locations&&this.mainPlaylistLoader_.main.locations[0];return i&&i!==this.mainPlaylistLoader_.srcUrl&&(this.mainPlaylistLoader_.srcUrl=i),(!e||t&&t.minimumUpdatePeriod!==e.minimumUpdatePeriod)&&this.updateMinimumUpdatePeriodTimeout_(),Boolean(t)}updateMinimumUpdatePeriodTimeout_(){const e=this.mainPlaylistLoader_;e.createMupOnMedia_&&(e.off("loadedmetadata",e.createMupOnMedia_),e.createMupOnMedia_=null),e.minimumUpdatePeriodTimeout_&&(window.clearTimeout(e.minimumUpdatePeriodTimeout_),e.minimumUpdatePeriodTimeout_=null);let t=e.main&&e.main.minimumUpdatePeriod;0===t&&(e.media()?t=1e3*e.media().targetDuration:(e.createMupOnMedia_=e.updateMinimumUpdatePeriodTimeout_,e.one("loadedmetadata",e.createMupOnMedia_))),"number"!=typeof t||t<=0?t<0&&this.logger_(`found invalid minimumUpdatePeriod of ${t}, not setting a timeout`):this.createMUPTimeout_(t)}createMUPTimeout_(e){const t=this.mainPlaylistLoader_;t.minimumUpdatePeriodTimeout_=window.setTimeout((()=>{t.minimumUpdatePeriodTimeout_=null,t.trigger("minimumUpdatePeriod"),t.createMUPTimeout_(e)}),e)}refreshXml_(){this.requestMain_(((e,t)=>{t&&(this.media_&&(this.media_=this.mainPlaylistLoader_.main.playlists[this.media_.id]),this.mainPlaylistLoader_.sidxMapping_=((e,t)=>{let i=ai(e.playlists,t);return le(e,((e,n,s,r)=>{if(e.playlists&&e.playlists.length){const n=e.playlists;i=U(i,ai(n,t))}})),i})(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.sidxMapping_),this.addSidxSegments_(this.media(),this.state,(e=>{this.refreshMedia_(this.media().id)})))}))}refreshMedia_(e){if(!e)throw new Error("refreshMedia_ must take a media id");this.media_&&this.isMain_&&this.handleMain_();const t=this.mainPlaylistLoader_.main.playlists,i=!this.media_||this.media_!==t[e];if(i?this.media_=t[e]:this.trigger("playlistunchanged"),!this.mediaUpdateTimeout){const e=()=>{this.media().endList||(this.mediaUpdateTimeout=window.setTimeout((()=>{this.trigger("mediaupdatetimeout"),e()}),Te(this.media(),Boolean(i))))};e()}this.trigger("loadedplaylist")}}var di={GOAL_BUFFER_LENGTH:30,MAX_GOAL_BUFFER_LENGTH:60,BACK_BUFFER_LENGTH:30,GOAL_BUFFER_LENGTH_RATE:1,INITIAL_BANDWIDTH:4194304,BANDWIDTH_VARIANCE:1.2,BUFFER_LOW_WATER_LINE:0,MAX_BUFFER_LOW_WATER_LINE:30,EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:16,BUFFER_LOW_WATER_LINE_RATE:1,BUFFER_HIGH_WATER_LINE:30};const ui=function(e){return e.on=e.addEventListener,e.off=e.removeEventListener,e},li=function(e){return function(){const t=function(e){try{return URL.createObjectURL(new Blob([e],{type:"application/javascript"}))}catch(t){const i=new BlobBuilder;return i.append(e),URL.createObjectURL(i.getBlob())}}(e),i=ui(new Worker(t));i.objURL=t;const n=i.terminate;return i.on=i.addEventListener,i.off=i.removeEventListener,i.terminate=function(){return URL.revokeObjectURL(t),n.call(this)},i}},hi=function(e){return`var browserWorkerPolyFill = ${ui.toString()};\nbrowserWorkerPolyFill(self);\n`+e},ci=function(e){return e.toString().replace(/^function.+?{/,"").slice(0,-1)},pi=hi(ci((function(){var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},t=function(){this.init=function(){var e={};this.on=function(t,i){e[t]||(e[t]=[]),e[t]=e[t].concat(i)},this.off=function(t,i){var n;return!!e[t]&&(n=e[t].indexOf(i),e[t]=e[t].slice(),e[t].splice(n,1),n>-1)},this.trigger=function(t){var i,n,s,r;if(i=e[t])if(2===arguments.length)for(s=i.length,n=0;n<s;++n)i[n].call(this,arguments[1]);else{for(r=[],n=arguments.length,n=1;n<arguments.length;++n)r.push(arguments[n]);for(s=i.length,n=0;n<s;++n)i[n].apply(this,r)}},this.dispose=function(){e={}}}};t.prototype.pipe=function(e){return this.on("data",(function(t){e.push(t)})),this.on("done",(function(t){e.flush(t)})),this.on("partialdone",(function(t){e.partialFlush(t)})),this.on("endedtimeline",(function(t){e.endTimeline(t)})),this.on("reset",(function(t){e.reset(t)})),e},t.prototype.push=function(e){this.trigger("data",e)},t.prototype.flush=function(e){this.trigger("done",e)},t.prototype.partialFlush=function(e){this.trigger("partialdone",e)},t.prototype.endTimeline=function(e){this.trigger("endedtimeline",e)},t.prototype.reset=function(e){this.trigger("reset",e)};var i,n,s,r,a,o,d,u,l,h,c,p,m,f,g,y,_,T,b,S,v,w,I,E,A,L,x,D,k,O,P,U,C,R,M,B,N,F,$,q,W=t,G=Math.pow(2,32),V={getUint64:function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength);return i.getBigUint64?(t=i.getBigUint64(0))<Number.MAX_SAFE_INTEGER?Number(t):t:i.getUint32(0)*G+i.getUint32(4)},MAX_UINT32:G},H=V.MAX_UINT32;!function(){var e;if(w={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],mvex:[],mvhd:[],pasp:[],sdtp:[],smhd:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],styp:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[]},"undefined"!=typeof Uint8Array){for(e in w)w.hasOwnProperty(e)&&(w[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);I=new Uint8Array(["i".charCodeAt(0),"s".charCodeAt(0),"o".charCodeAt(0),"m".charCodeAt(0)]),A=new Uint8Array(["a".charCodeAt(0),"v".charCodeAt(0),"c".charCodeAt(0),"1".charCodeAt(0)]),E=new Uint8Array([0,0,0,1]),L=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),x=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]),D={video:L,audio:x},P=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),O=new Uint8Array([0,0,0,0,0,0,0,0]),U=new Uint8Array([0,0,0,0,0,0,0,0]),C=U,R=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),M=U,k=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}}(),i=function(e){var t,i,n=[],s=0;for(t=1;t<arguments.length;t++)n.push(arguments[t]);for(t=n.length;t--;)s+=n[t].byteLength;for(i=new Uint8Array(s+8),new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,i.byteLength),i.set(e,4),t=0,s=8;t<n.length;t++)i.set(n[t],s),s+=n[t].byteLength;return i},n=function(){return i(w.dinf,i(w.dref,P))},s=function(e){return i(w.esds,new Uint8Array([0,0,0,0,3,25,0,0,0,4,17,64,21,0,6,0,0,0,218,192,0,0,218,192,5,2,e.audioobjecttype<<3|e.samplingfrequencyindex>>>1,e.samplingfrequencyindex<<7|e.channelcount<<3,6,1,2]))},g=function(e){return i(w.hdlr,D[e])},f=function(e){var t=new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,e.duration>>>24&255,e.duration>>>16&255,e.duration>>>8&255,255&e.duration,85,196,0,0]);return e.samplerate&&(t[12]=e.samplerate>>>24&255,t[13]=e.samplerate>>>16&255,t[14]=e.samplerate>>>8&255,t[15]=255&e.samplerate),i(w.mdhd,t)},m=function(e){return i(w.mdia,f(e),g(e.type),o(e))},a=function(e){return i(w.mfhd,new Uint8Array([0,0,0,0,(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e]))},o=function(e){return i(w.minf,"video"===e.type?i(w.vmhd,k):i(w.smhd,O),n(),_(e))},d=function(e,t){for(var n=[],s=t.length;s--;)n[s]=b(t[s]);return i.apply(null,[w.moof,a(e)].concat(n))},u=function(e){for(var t=e.length,n=[];t--;)n[t]=c(e[t]);return i.apply(null,[w.moov,h(4294967295)].concat(n).concat(l(e)))},l=function(e){for(var t=e.length,n=[];t--;)n[t]=S(e[t]);return i.apply(null,[w.mvex].concat(n))},h=function(e){var t=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return i(w.mvhd,t)},y=function(e){var t,n,s=e.samples||[],r=new Uint8Array(4+s.length);for(n=0;n<s.length;n++)t=s[n].flags,r[n+4]=t.dependsOn<<4|t.isDependedOn<<2|t.hasRedundancy;return i(w.sdtp,r)},_=function(e){return i(w.stbl,T(e),i(w.stts,M),i(w.stsc,C),i(w.stsz,R),i(w.stco,U))},T=function(e){return i(w.stsd,new Uint8Array([0,0,0,0,0,0,0,1]),"video"===e.type?B(e):N(e))},B=function(e){var t,n,s=e.sps||[],r=e.pps||[],a=[],o=[];for(t=0;t<s.length;t++)a.push((65280&s[t].byteLength)>>>8),a.push(255&s[t].byteLength),a=a.concat(Array.prototype.slice.call(s[t]));for(t=0;t<r.length;t++)o.push((65280&r[t].byteLength)>>>8),o.push(255&r[t].byteLength),o=o.concat(Array.prototype.slice.call(r[t]));if(n=[w.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,(65280&e.width)>>8,255&e.width,(65280&e.height)>>8,255&e.height,0,72,0,0,0,72,0,0,0,0,0,0,0,1,19,118,105,100,101,111,106,115,45,99,111,110,116,114,105,98,45,104,108,115,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),i(w.avcC,new Uint8Array([1,e.profileIdc,e.profileCompatibility,e.levelIdc,255].concat([s.length],a,[r.length],o))),i(w.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))],e.sarRatio){var d=e.sarRatio[0],u=e.sarRatio[1];n.push(i(w.pasp,new Uint8Array([(4278190080&d)>>24,(16711680&d)>>16,(65280&d)>>8,255&d,(4278190080&u)>>24,(16711680&u)>>16,(65280&u)>>8,255&u])))}return i.apply(null,n)},N=function(e){return i(w.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(65280&e.channelcount)>>8,255&e.channelcount,(65280&e.samplesize)>>8,255&e.samplesize,0,0,0,0,(65280&e.samplerate)>>8,255&e.samplerate,0,0]),s(e))},p=function(e){var t=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(4278190080&e.id)>>24,(16711680&e.id)>>16,(65280&e.id)>>8,255&e.id,0,0,0,0,(4278190080&e.duration)>>24,(16711680&e.duration)>>16,(65280&e.duration)>>8,255&e.duration,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,(65280&e.width)>>8,255&e.width,0,0,(65280&e.height)>>8,255&e.height,0,0]);return i(w.tkhd,t)},b=function(e){var t,n,s,r,a,o;return t=i(w.tfhd,new Uint8Array([0,0,0,58,(4278190080&e.id)>>24,(16711680&e.id)>>16,(65280&e.id)>>8,255&e.id,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0])),a=Math.floor(e.baseMediaDecodeTime/H),o=Math.floor(e.baseMediaDecodeTime%H),n=i(w.tfdt,new Uint8Array([1,0,0,0,a>>>24&255,a>>>16&255,a>>>8&255,255&a,o>>>24&255,o>>>16&255,o>>>8&255,255&o])),"audio"===e.type?(s=v(e,92),i(w.traf,t,n,s)):(r=y(e),s=v(e,r.length+92),i(w.traf,t,n,s,r))},c=function(e){return e.duration=e.duration||4294967295,i(w.trak,p(e),m(e))},S=function(e){var t=new Uint8Array([0,0,0,0,(4278190080&e.id)>>24,(16711680&e.id)>>16,(65280&e.id)>>8,255&e.id,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return"video"!==e.type&&(t[t.length-1]=0),i(w.trex,t)},q=function(e,t){var i=0,n=0,s=0,r=0;return e.length&&(void 0!==e[0].duration&&(i=1),void 0!==e[0].size&&(n=2),void 0!==e[0].flags&&(s=4),void 0!==e[0].compositionTimeOffset&&(r=8)),[0,0,i|n|s|r,1,(4278190080&e.length)>>>24,(16711680&e.length)>>>16,(65280&e.length)>>>8,255&e.length,(4278190080&t)>>>24,(16711680&t)>>>16,(65280&t)>>>8,255&t]},$=function(e,t){var n,s,r,a,o,d;for(t+=20+16*(a=e.samples||[]).length,r=q(a,t),(s=new Uint8Array(r.length+16*a.length)).set(r),n=r.length,d=0;d<a.length;d++)o=a[d],s[n++]=(4278190080&o.duration)>>>24,s[n++]=(16711680&o.duration)>>>16,s[n++]=(65280&o.duration)>>>8,s[n++]=255&o.duration,s[n++]=(4278190080&o.size)>>>24,s[n++]=(16711680&o.size)>>>16,s[n++]=(65280&o.size)>>>8,s[n++]=255&o.size,s[n++]=o.flags.isLeading<<2|o.flags.dependsOn,s[n++]=o.flags.isDependedOn<<6|o.flags.hasRedundancy<<4|o.flags.paddingValue<<1|o.flags.isNonSyncSample,s[n++]=61440&o.flags.degradationPriority,s[n++]=15&o.flags.degradationPriority,s[n++]=(4278190080&o.compositionTimeOffset)>>>24,s[n++]=(16711680&o.compositionTimeOffset)>>>16,s[n++]=(65280&o.compositionTimeOffset)>>>8,s[n++]=255&o.compositionTimeOffset;return i(w.trun,s)},F=function(e,t){var n,s,r,a,o,d;for(t+=20+8*(a=e.samples||[]).length,r=q(a,t),(n=new Uint8Array(r.length+8*a.length)).set(r),s=r.length,d=0;d<a.length;d++)o=a[d],n[s++]=(4278190080&o.duration)>>>24,n[s++]=(16711680&o.duration)>>>16,n[s++]=(65280&o.duration)>>>8,n[s++]=255&o.duration,n[s++]=(4278190080&o.size)>>>24,n[s++]=(16711680&o.size)>>>16,n[s++]=(65280&o.size)>>>8,n[s++]=255&o.size;return i(w.trun,n)},v=function(e,t){return"audio"===e.type?F(e,t):$(e,t)};var j,X,z,Q,Y,K,J,Z,ee={ftyp:r=function(){return i(w.ftyp,I,E,I,A)},mdat:function(e){return i(w.mdat,e)},moof:d,moov:u,initSegment:function(e){var t,i=r(),n=u(e);return(t=new Uint8Array(i.byteLength+n.byteLength)).set(i),t.set(n,i.byteLength),t}},te=function(e,t){var i={size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}};return i.dataOffset=t,i.compositionTimeOffset=e.pts-e.dts,i.duration=e.duration,i.size=4*e.length,i.size+=e.byteLength,e.keyFrame&&(i.flags.dependsOn=2,i.flags.isNonSyncSample=0),i},ie={groupNalsIntoFrames:function(e){var t,i,n=[],s=[];for(s.byteLength=0,s.nalCount=0,s.duration=0,n.byteLength=0,t=0;t<e.length;t++)"access_unit_delimiter_rbsp"===(i=e[t]).nalUnitType?(n.length&&(n.duration=i.dts-n.dts,s.byteLength+=n.byteLength,s.nalCount+=n.length,s.duration+=n.duration,s.push(n)),(n=[i]).byteLength=i.data.byteLength,n.pts=i.pts,n.dts=i.dts):("slice_layer_without_partitioning_rbsp_idr"===i.nalUnitType&&(n.keyFrame=!0),n.duration=i.dts-n.dts,n.byteLength+=i.data.byteLength,n.push(i));return s.length&&(!n.duration||n.duration<=0)&&(n.duration=s[s.length-1].duration),s.byteLength+=n.byteLength,s.nalCount+=n.length,s.duration+=n.duration,s.push(n),s},groupFramesIntoGops:function(e){var t,i,n=[],s=[];for(n.byteLength=0,n.nalCount=0,n.duration=0,n.pts=e[0].pts,n.dts=e[0].dts,s.byteLength=0,s.nalCount=0,s.duration=0,s.pts=e[0].pts,s.dts=e[0].dts,t=0;t<e.length;t++)(i=e[t]).keyFrame?(n.length&&(s.push(n),s.byteLength+=n.byteLength,s.nalCount+=n.nalCount,s.duration+=n.duration),(n=[i]).nalCount=i.length,n.byteLength=i.byteLength,n.pts=i.pts,n.dts=i.dts,n.duration=i.duration):(n.duration+=i.duration,n.nalCount+=i.length,n.byteLength+=i.byteLength,n.push(i));return s.length&&n.duration<=0&&(n.duration=s[s.length-1].duration),s.byteLength+=n.byteLength,s.nalCount+=n.nalCount,s.duration+=n.duration,s.push(n),s},extendFirstKeyFrame:function(e){var t;return!e[0][0].keyFrame&&e.length>1&&(t=e.shift(),e.byteLength-=t.byteLength,e.nalCount-=t.nalCount,e[0][0].dts=t.dts,e[0][0].pts=t.pts,e[0][0].duration+=t.duration),e},generateSampleTable:function(e,t){var i,n,s,r,a,o=t||0,d=[];for(i=0;i<e.length;i++)for(r=e[i],n=0;n<r.length;n++)a=r[n],o+=(s=te(a,o)).size,d.push(s);return d},concatenateNalData:function(e){var t,i,n,s,r,a,o=0,d=e.byteLength,u=e.nalCount,l=new Uint8Array(d+4*u),h=new DataView(l.buffer);for(t=0;t<e.length;t++)for(s=e[t],i=0;i<s.length;i++)for(r=s[i],n=0;n<r.length;n++)a=r[n],h.setUint32(o,a.data.byteLength),o+=4,l.set(a.data,o),o+=a.data.byteLength;return l},generateSampleTableForFrame:function(e,t){var i,n=[];return i=te(e,t||0),n.push(i),n},concatenateNalDataForFrame:function(e){var t,i,n=0,s=e.byteLength,r=e.length,a=new Uint8Array(s+4*r),o=new DataView(a.buffer);for(t=0;t<e.length;t++)i=e[t],o.setUint32(n,i.data.byteLength),n+=4,a.set(i.data,n),n+=i.data.byteLength;return a}},ne=[33,16,5,32,164,27],se=[33,65,108,84,1,2,4,8,168,2,4,8,17,191,252],re=function(e){for(var t=[];e--;)t.push(0);return t},ae=9e4;K=function(e,t){return X(Y(e,t))},J=function(e,t){return z(Q(e),t)},Z=function(e,t,i){return Q(i?e:e-t)};var oe={ONE_SECOND_IN_TS:ae,secondsToVideoTs:X=function(e){return e*ae},secondsToAudioTs:z=function(e,t){return e*t},videoTsToSeconds:Q=function(e){return e/ae},audioTsToSeconds:Y=function(e,t){return e/t},audioTsToVideoTs:K,videoTsToAudioTs:J,metadataTsToSeconds:Z},de=oe,ue={prefixWithSilence:function(e,t,i,n){var s,r,a,o,d,u=0,l=0,h=0;if(t.length&&(s=de.audioTsToVideoTs(e.baseMediaDecodeTime,e.samplerate),r=Math.ceil(de.ONE_SECOND_IN_TS/(e.samplerate/1024)),i&&n&&(u=s-Math.max(i,n),h=(l=Math.floor(u/r))*r),!(l<1||h>de.ONE_SECOND_IN_TS/2))){for((a=function(){if(!j){var e={96e3:[ne,[227,64],re(154),[56]],88200:[ne,[231],re(170),[56]],64e3:[ne,[248,192],re(240),[56]],48e3:[ne,[255,192],re(268),[55,148,128],re(54),[112]],44100:[ne,[255,192],re(268),[55,163,128],re(84),[112]],32e3:[ne,[255,192],re(268),[55,234],re(226),[112]],24e3:[ne,[255,192],re(268),[55,255,128],re(268),[111,112],re(126),[224]],16e3:[ne,[255,192],re(268),[55,255,128],re(268),[111,255],re(269),[223,108],re(195),[1,192]],12e3:[se,re(268),[3,127,248],re(268),[6,255,240],re(268),[13,255,224],re(268),[27,253,128],re(259),[56]],11025:[se,re(268),[3,127,248],re(268),[6,255,240],re(268),[13,255,224],re(268),[27,255,192],re(268),[55,175,128],re(108),[112]],8e3:[se,re(268),[3,121,16],re(47),[7]]};t=e,j=Object.keys(t).reduce((function(e,i){return e[i]=new Uint8Array(t[i].reduce((function(e,t){return e.concat(t)}),[])),e}),{})}var t;return j}()[e.samplerate])||(a=t[0].data),o=0;o<l;o++)d=t[0],t.splice(0,0,{data:a,dts:d.dts-r,pts:d.pts-r});return e.baseMediaDecodeTime-=Math.floor(de.videoTsToAudioTs(h,e.samplerate)),h}},trimAdtsFramesByEarliestDts:function(e,t,i){return t.minSegmentDts>=i?e:(t.minSegmentDts=1/0,e.filter((function(e){return e.dts>=i&&(t.minSegmentDts=Math.min(t.minSegmentDts,e.dts),t.minSegmentPts=t.minSegmentDts,!0)})))},generateSampleTable:function(e){var t,i,n=[];for(t=0;t<e.length;t++)i=e[t],n.push({size:i.data.byteLength,duration:1024});return n},concatenateFrameData:function(e){var t,i,n=0,s=new Uint8Array(function(e){var t,i=0;for(t=0;t<e.length;t++)i+=e[t].data.byteLength;return i}(e));for(t=0;t<e.length;t++)i=e[t],s.set(i.data,n),n+=i.data.byteLength;return s}},le=oe.ONE_SECOND_IN_TS,he={clearDtsInfo:function(e){delete e.minSegmentDts,delete e.maxSegmentDts,delete e.minSegmentPts,delete e.maxSegmentPts},calculateTrackBaseMediaDecodeTime:function(e,t){var i,n=e.minSegmentDts;return t||(n-=e.timelineStartInfo.dts),i=e.timelineStartInfo.baseMediaDecodeTime,i+=n,i=Math.max(0,i),"audio"===e.type&&(i*=e.samplerate/le,i=Math.floor(i)),i},collectDtsInfo:function(e,t){"number"==typeof t.pts&&(void 0===e.timelineStartInfo.pts&&(e.timelineStartInfo.pts=t.pts),void 0===e.minSegmentPts?e.minSegmentPts=t.pts:e.minSegmentPts=Math.min(e.minSegmentPts,t.pts),void 0===e.maxSegmentPts?e.maxSegmentPts=t.pts:e.maxSegmentPts=Math.max(e.maxSegmentPts,t.pts)),"number"==typeof t.dts&&(void 0===e.timelineStartInfo.dts&&(e.timelineStartInfo.dts=t.dts),void 0===e.minSegmentDts?e.minSegmentDts=t.dts:e.minSegmentDts=Math.min(e.minSegmentDts,t.dts),void 0===e.maxSegmentDts?e.maxSegmentDts=t.dts:e.maxSegmentDts=Math.max(e.maxSegmentDts,t.dts))}},ce={parseSei:function(e){for(var t=0,i={payloadType:-1,payloadSize:0},n=0,s=0;t<e.byteLength&&128!==e[t];){for(;255===e[t];)n+=255,t++;for(n+=e[t++];255===e[t];)s+=255,t++;if(s+=e[t++],!i.payload&&4===n){if("GA94"===String.fromCharCode(e[t+3],e[t+4],e[t+5],e[t+6])){i.payloadType=n,i.payloadSize=s,i.payload=e.subarray(t,t+s);break}i.payload=void 0}t+=s,n=0,s=0}return i},parseUserData:function(e){return 181!==e.payload[0]||49!=(e.payload[1]<<8|e.payload[2])||"GA94"!==String.fromCharCode(e.payload[3],e.payload[4],e.payload[5],e.payload[6])||3!==e.payload[7]?null:e.payload.subarray(8,e.payload.length-1)},parseCaptionPackets:function(e,t){var i,n,s,r,a=[];if(!(64&t[0]))return a;for(n=31&t[0],i=0;i<n;i++)r={type:3&t[2+(s=3*i)],pts:e},4&t[s+2]&&(r.ccData=t[s+3]<<8|t[s+4],a.push(r));return a},discardEmulationPreventionBytes:function(e){for(var t,i,n=e.byteLength,s=[],r=1;r<n-2;)0===e[r]&&0===e[r+1]&&3===e[r+2]?(s.push(r+2),r+=2):r++;if(0===s.length)return e;t=n-s.length,i=new Uint8Array(t);var a=0;for(r=0;r<t;a++,r++)a===s[0]&&(a++,s.shift()),i[r]=e[a];return i},USER_DATA_REGISTERED_ITU_T_T35:4},pe=W,me=ce,fe=function(e){e=e||{},fe.prototype.init.call(this),this.parse708captions_="boolean"!=typeof e.parse708captions||e.parse708captions,this.captionPackets_=[],this.ccStreams_=[new Ee(0,0),new Ee(0,1),new Ee(1,0),new Ee(1,1)],this.parse708captions_&&(this.cc708Stream_=new be({captionServices:e.captionServices})),this.reset(),this.ccStreams_.forEach((function(e){e.on("data",this.trigger.bind(this,"data")),e.on("partialdone",this.trigger.bind(this,"partialdone")),e.on("done",this.trigger.bind(this,"done"))}),this),this.parse708captions_&&(this.cc708Stream_.on("data",this.trigger.bind(this,"data")),this.cc708Stream_.on("partialdone",this.trigger.bind(this,"partialdone")),this.cc708Stream_.on("done",this.trigger.bind(this,"done")))};fe.prototype=new pe,fe.prototype.push=function(e){var t,i,n;if("sei_rbsp"===e.nalUnitType&&(t=me.parseSei(e.escapedRBSP)).payload&&t.payloadType===me.USER_DATA_REGISTERED_ITU_T_T35&&(i=me.parseUserData(t)))if(e.dts<this.latestDts_)this.ignoreNextEqualDts_=!0;else{if(e.dts===this.latestDts_&&this.ignoreNextEqualDts_)return this.numSameDts_--,void(this.numSameDts_||(this.ignoreNextEqualDts_=!1));n=me.parseCaptionPackets(e.pts,i),this.captionPackets_=this.captionPackets_.concat(n),this.latestDts_!==e.dts&&(this.numSameDts_=0),this.numSameDts_++,this.latestDts_=e.dts}},fe.prototype.flushCCStreams=function(e){this.ccStreams_.forEach((function(t){return"flush"===e?t.flush():t.partialFlush()}),this)},fe.prototype.flushStream=function(e){this.captionPackets_.length?(this.captionPackets_.forEach((function(e,t){e.presortIndex=t})),this.captionPackets_.sort((function(e,t){return e.pts===t.pts?e.presortIndex-t.presortIndex:e.pts-t.pts})),this.captionPackets_.forEach((function(e){e.type<2?this.dispatchCea608Packet(e):this.dispatchCea708Packet(e)}),this),this.captionPackets_.length=0,this.flushCCStreams(e)):this.flushCCStreams(e)},fe.prototype.flush=function(){return this.flushStream("flush")},fe.prototype.partialFlush=function(){return this.flushStream("partialFlush")},fe.prototype.reset=function(){this.latestDts_=null,this.ignoreNextEqualDts_=!1,this.numSameDts_=0,this.activeCea608Channel_=[null,null],this.ccStreams_.forEach((function(e){e.reset()}))},fe.prototype.dispatchCea608Packet=function(e){this.setsTextOrXDSActive(e)?this.activeCea608Channel_[e.type]=null:this.setsChannel1Active(e)?this.activeCea608Channel_[e.type]=0:this.setsChannel2Active(e)&&(this.activeCea608Channel_[e.type]=1),null!==this.activeCea608Channel_[e.type]&&this.ccStreams_[(e.type<<1)+this.activeCea608Channel_[e.type]].push(e)},fe.prototype.setsChannel1Active=function(e){return 4096==(30720&e.ccData)},fe.prototype.setsChannel2Active=function(e){return 6144==(30720&e.ccData)},fe.prototype.setsTextOrXDSActive=function(e){return 256==(28928&e.ccData)||4138==(30974&e.ccData)||6186==(30974&e.ccData)},fe.prototype.dispatchCea708Packet=function(e){this.parse708captions_&&this.cc708Stream_.push(e)};var ge={127:9834,4128:32,4129:160,4133:8230,4138:352,4140:338,4144:9608,4145:8216,4146:8217,4147:8220,4148:8221,4149:8226,4153:8482,4154:353,4156:339,4157:8480,4159:376,4214:8539,4215:8540,4216:8541,4217:8542,4218:9168,4219:9124,4220:9123,4221:9135,4222:9126,4223:9121,4256:12600},ye=function(e){return 32<=e&&e<=127||160<=e&&e<=255},_e=function(e){this.windowNum=e,this.reset()};_e.prototype.reset=function(){this.clearText(),this.pendingNewLine=!1,this.winAttr={},this.penAttr={},this.penLoc={},this.penColor={},this.visible=0,this.rowLock=0,this.columnLock=0,this.priority=0,this.relativePositioning=0,this.anchorVertical=0,this.anchorHorizontal=0,this.anchorPoint=0,this.rowCount=1,this.virtualRowCount=this.rowCount+1,this.columnCount=41,this.windowStyle=0,this.penStyle=0},_e.prototype.getText=function(){return this.rows.join("\n")},_e.prototype.clearText=function(){this.rows=[""],this.rowIdx=0},_e.prototype.newLine=function(e){for(this.rows.length>=this.virtualRowCount&&"function"==typeof this.beforeRowOverflow&&this.beforeRowOverflow(e),this.rows.length>0&&(this.rows.push(""),this.rowIdx++);this.rows.length>this.virtualRowCount;)this.rows.shift(),this.rowIdx--},_e.prototype.isEmpty=function(){return 0===this.rows.length||1===this.rows.length&&""===this.rows[0]},_e.prototype.addText=function(e){this.rows[this.rowIdx]+=e},_e.prototype.backspace=function(){if(!this.isEmpty()){var e=this.rows[this.rowIdx];this.rows[this.rowIdx]=e.substr(0,e.length-1)}};var Te=function(e,t,i){this.serviceNum=e,this.text="",this.currentWindow=new _e(-1),this.windows=[],this.stream=i,"string"==typeof t&&this.createTextDecoder(t)};Te.prototype.init=function(e,t){this.startPts=e;for(var i=0;i<8;i++)this.windows[i]=new _e(i),"function"==typeof t&&(this.windows[i].beforeRowOverflow=t)},Te.prototype.setCurrentWindow=function(e){this.currentWindow=this.windows[e]},Te.prototype.createTextDecoder=function(e){if("undefined"==typeof TextDecoder)this.stream.trigger("log",{level:"warn",message:"The `encoding` option is unsupported without TextDecoder support"});else try{this.textDecoder_=new TextDecoder(e)}catch(t){this.stream.trigger("log",{level:"warn",message:"TextDecoder could not be created with "+e+" encoding. "+t})}};var be=function(e){e=e||{},be.prototype.init.call(this);var t,i=this,n=e.captionServices||{},s={};Object.keys(n).forEach((e=>{t=n[e],/^SERVICE/.test(e)&&(s[e]=t.encoding)})),this.serviceEncodings=s,this.current708Packet=null,this.services={},this.push=function(e){3===e.type?(i.new708Packet(),i.add708Bytes(e)):(null===i.current708Packet&&i.new708Packet(),i.add708Bytes(e))}};be.prototype=new pe,be.prototype.new708Packet=function(){null!==this.current708Packet&&this.push708Packet(),this.current708Packet={data:[],ptsVals:[]}},be.prototype.add708Bytes=function(e){var t=e.ccData,i=t>>>8,n=255&t;this.current708Packet.ptsVals.push(e.pts),this.current708Packet.data.push(i),this.current708Packet.data.push(n)},be.prototype.push708Packet=function(){var e=this.current708Packet,t=e.data,i=null,n=null,s=0,r=t[s++];for(e.seq=r>>6,e.sizeCode=63&r;s<t.length;s++)n=31&(r=t[s++]),7==(i=r>>5)&&n>0&&(i=r=t[s++]),this.pushServiceBlock(i,s,n),n>0&&(s+=n-1)},be.prototype.pushServiceBlock=function(e,t,i){var n,s=t,r=this.current708Packet.data,a=this.services[e];for(a||(a=this.initService(e,s));s<t+i&&s<r.length;s++)n=r[s],ye(n)?s=this.handleText(s,a):24===n?s=this.multiByteCharacter(s,a):16===n?s=this.extendedCommands(s,a):128<=n&&n<=135?s=this.setCurrentWindow(s,a):152<=n&&n<=159?s=this.defineWindow(s,a):136===n?s=this.clearWindows(s,a):140===n?s=this.deleteWindows(s,a):137===n?s=this.displayWindows(s,a):138===n?s=this.hideWindows(s,a):139===n?s=this.toggleWindows(s,a):151===n?s=this.setWindowAttributes(s,a):144===n?s=this.setPenAttributes(s,a):145===n?s=this.setPenColor(s,a):146===n?s=this.setPenLocation(s,a):143===n?a=this.reset(s,a):8===n?a.currentWindow.backspace():12===n?a.currentWindow.clearText():13===n?a.currentWindow.pendingNewLine=!0:14===n?a.currentWindow.clearText():141===n&&s++},be.prototype.extendedCommands=function(e,t){var i=this.current708Packet.data[++e];return ye(i)&&(e=this.handleText(e,t,{isExtended:!0})),e},be.prototype.getPts=function(e){return this.current708Packet.ptsVals[Math.floor(e/2)]},be.prototype.initService=function(e,t){var i,n,s=this;return(i="SERVICE"+e)in this.serviceEncodings&&(n=this.serviceEncodings[i]),this.services[e]=new Te(e,n,s),this.services[e].init(this.getPts(t),(function(t){s.flushDisplayed(t,s.services[e])})),this.services[e]},be.prototype.handleText=function(e,t,i){var n,s,r,a,o=i&&i.isExtended,d=i&&i.isMultiByte,u=this.current708Packet.data,l=o?4096:0,h=u[e],c=u[e+1],p=t.currentWindow;return t.textDecoder_&&!o?(d?(s=[h,c],e++):s=[h],n=t.textDecoder_.decode(new Uint8Array(s))):(a=ge[r=l|h]||r,n=4096&r&&r===a?"":String.fromCharCode(a)),p.pendingNewLine&&!p.isEmpty()&&p.newLine(this.getPts(e)),p.pendingNewLine=!1,p.addText(n),e},be.prototype.multiByteCharacter=function(e,t){var i=this.current708Packet.data,n=i[e+1],s=i[e+2];return ye(n)&&ye(s)&&(e=this.handleText(++e,t,{isMultiByte:!0})),e},be.prototype.setCurrentWindow=function(e,t){var i=7&this.current708Packet.data[e];return t.setCurrentWindow(i),e},be.prototype.defineWindow=function(e,t){var i=this.current708Packet.data,n=i[e],s=7&n;t.setCurrentWindow(s);var r=t.currentWindow;return n=i[++e],r.visible=(32&n)>>5,r.rowLock=(16&n)>>4,r.columnLock=(8&n)>>3,r.priority=7&n,n=i[++e],r.relativePositioning=(128&n)>>7,r.anchorVertical=127&n,n=i[++e],r.anchorHorizontal=n,n=i[++e],r.anchorPoint=(240&n)>>4,r.rowCount=15&n,n=i[++e],r.columnCount=63&n,n=i[++e],r.windowStyle=(56&n)>>3,r.penStyle=7&n,r.virtualRowCount=r.rowCount+1,e},be.prototype.setWindowAttributes=function(e,t){var i=this.current708Packet.data,n=i[e],s=t.currentWindow.winAttr;return n=i[++e],s.fillOpacity=(192&n)>>6,s.fillRed=(48&n)>>4,s.fillGreen=(12&n)>>2,s.fillBlue=3&n,n=i[++e],s.borderType=(192&n)>>6,s.borderRed=(48&n)>>4,s.borderGreen=(12&n)>>2,s.borderBlue=3&n,n=i[++e],s.borderType+=(128&n)>>5,s.wordWrap=(64&n)>>6,s.printDirection=(48&n)>>4,s.scrollDirection=(12&n)>>2,s.justify=3&n,n=i[++e],s.effectSpeed=(240&n)>>4,s.effectDirection=(12&n)>>2,s.displayEffect=3&n,e},be.prototype.flushDisplayed=function(e,t){for(var i=[],n=0;n<8;n++)t.windows[n].visible&&!t.windows[n].isEmpty()&&i.push(t.windows[n].getText());t.endPts=e,t.text=i.join("\n\n"),this.pushCaption(t),t.startPts=e},be.prototype.pushCaption=function(e){""!==e.text&&(this.trigger("data",{startPts:e.startPts,endPts:e.endPts,text:e.text,stream:"cc708_"+e.serviceNum}),e.text="",e.startPts=e.endPts)},be.prototype.displayWindows=function(e,t){var i=this.current708Packet.data[++e],n=this.getPts(e);this.flushDisplayed(n,t);for(var s=0;s<8;s++)i&1<<s&&(t.windows[s].visible=1);return e},be.prototype.hideWindows=function(e,t){var i=this.current708Packet.data[++e],n=this.getPts(e);this.flushDisplayed(n,t);for(var s=0;s<8;s++)i&1<<s&&(t.windows[s].visible=0);return e},be.prototype.toggleWindows=function(e,t){var i=this.current708Packet.data[++e],n=this.getPts(e);this.flushDisplayed(n,t);for(var s=0;s<8;s++)i&1<<s&&(t.windows[s].visible^=1);return e},be.prototype.clearWindows=function(e,t){var i=this.current708Packet.data[++e],n=this.getPts(e);this.flushDisplayed(n,t);for(var s=0;s<8;s++)i&1<<s&&t.windows[s].clearText();return e},be.prototype.deleteWindows=function(e,t){var i=this.current708Packet.data[++e],n=this.getPts(e);this.flushDisplayed(n,t);for(var s=0;s<8;s++)i&1<<s&&t.windows[s].reset();return e},be.prototype.setPenAttributes=function(e,t){var i=this.current708Packet.data,n=i[e],s=t.currentWindow.penAttr;return n=i[++e],s.textTag=(240&n)>>4,s.offset=(12&n)>>2,s.penSize=3&n,n=i[++e],s.italics=(128&n)>>7,s.underline=(64&n)>>6,s.edgeType=(56&n)>>3,s.fontStyle=7&n,e},be.prototype.setPenColor=function(e,t){var i=this.current708Packet.data,n=i[e],s=t.currentWindow.penColor;return n=i[++e],s.fgOpacity=(192&n)>>6,s.fgRed=(48&n)>>4,s.fgGreen=(12&n)>>2,s.fgBlue=3&n,n=i[++e],s.bgOpacity=(192&n)>>6,s.bgRed=(48&n)>>4,s.bgGreen=(12&n)>>2,s.bgBlue=3&n,n=i[++e],s.edgeRed=(48&n)>>4,s.edgeGreen=(12&n)>>2,s.edgeBlue=3&n,e},be.prototype.setPenLocation=function(e,t){var i=this.current708Packet.data,n=i[e],s=t.currentWindow.penLoc;return t.currentWindow.pendingNewLine=!0,n=i[++e],s.row=15&n,n=i[++e],s.column=63&n,e},be.prototype.reset=function(e,t){var i=this.getPts(e);return this.flushDisplayed(i,t),this.initService(t.serviceNum,e)};var Se={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,304:174,305:176,306:189,307:191,308:8482,309:162,310:163,311:9834,312:224,313:160,314:232,315:226,316:234,317:238,318:244,319:251,544:193,545:201,546:211,547:218,548:220,549:252,550:8216,551:161,552:42,553:39,554:8212,555:169,556:8480,557:8226,558:8220,559:8221,560:192,561:194,562:199,563:200,564:202,565:203,566:235,567:206,568:207,569:239,570:212,571:217,572:249,573:219,574:171,575:187,800:195,801:227,802:205,803:204,804:236,805:210,806:242,807:213,808:245,809:123,810:125,811:92,812:94,813:95,814:124,815:126,816:196,817:228,818:214,819:246,820:223,821:165,822:164,823:9474,824:197,825:229,826:216,827:248,828:9484,829:9488,830:9492,831:9496},ve=function(e){return null===e?"":(e=Se[e]||e,String.fromCharCode(e))},we=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],Ie=function(){for(var e=[],t=15;t--;)e.push("");return e},Ee=function(e,t){Ee.prototype.init.call(this),this.field_=e||0,this.dataChannel_=t||0,this.name_="CC"+(1+(this.field_<<1|this.dataChannel_)),this.setConstants(),this.reset(),this.push=function(e){var t,i,n,s,r;if((t=32639&e.ccData)!==this.lastControlCode_){if(4096==(61440&t)?this.lastControlCode_=t:t!==this.PADDING_&&(this.lastControlCode_=null),n=t>>>8,s=255&t,t!==this.PADDING_)if(t===this.RESUME_CAPTION_LOADING_)this.mode_="popOn";else if(t===this.END_OF_CAPTION_)this.mode_="popOn",this.clearFormatting(e.pts),this.flushDisplayed(e.pts),i=this.displayed_,this.displayed_=this.nonDisplayed_,this.nonDisplayed_=i,this.startPts_=e.pts;else if(t===this.ROLL_UP_2_ROWS_)this.rollUpRows_=2,this.setRollUp(e.pts);else if(t===this.ROLL_UP_3_ROWS_)this.rollUpRows_=3,this.setRollUp(e.pts);else if(t===this.ROLL_UP_4_ROWS_)this.rollUpRows_=4,this.setRollUp(e.pts);else if(t===this.CARRIAGE_RETURN_)this.clearFormatting(e.pts),this.flushDisplayed(e.pts),this.shiftRowsUp_(),this.startPts_=e.pts;else if(t===this.BACKSPACE_)"popOn"===this.mode_?this.nonDisplayed_[this.row_]=this.nonDisplayed_[this.row_].slice(0,-1):this.displayed_[this.row_]=this.displayed_[this.row_].slice(0,-1);else if(t===this.ERASE_DISPLAYED_MEMORY_)this.flushDisplayed(e.pts),this.displayed_=Ie();else if(t===this.ERASE_NON_DISPLAYED_MEMORY_)this.nonDisplayed_=Ie();else if(t===this.RESUME_DIRECT_CAPTIONING_)"paintOn"!==this.mode_&&(this.flushDisplayed(e.pts),this.displayed_=Ie()),this.mode_="paintOn",this.startPts_=e.pts;else if(this.isSpecialCharacter(n,s))r=ve((n=(3&n)<<8)|s),this[this.mode_](e.pts,r),this.column_++;else if(this.isExtCharacter(n,s))"popOn"===this.mode_?this.nonDisplayed_[this.row_]=this.nonDisplayed_[this.row_].slice(0,-1):this.displayed_[this.row_]=this.displayed_[this.row_].slice(0,-1),r=ve((n=(3&n)<<8)|s),this[this.mode_](e.pts,r),this.column_++;else if(this.isMidRowCode(n,s))this.clearFormatting(e.pts),this[this.mode_](e.pts," "),this.column_++,14==(14&s)&&this.addFormatting(e.pts,["i"]),1==(1&s)&&this.addFormatting(e.pts,["u"]);else if(this.isOffsetControlCode(n,s))this.column_+=3&s;else if(this.isPAC(n,s)){var a=we.indexOf(7968&t);"rollUp"===this.mode_&&(a-this.rollUpRows_+1<0&&(a=this.rollUpRows_-1),this.setRollUp(e.pts,a)),a!==this.row_&&(this.clearFormatting(e.pts),this.row_=a),1&s&&-1===this.formatting_.indexOf("u")&&this.addFormatting(e.pts,["u"]),16==(16&t)&&(this.column_=4*((14&t)>>1)),this.isColorPAC(s)&&14==(14&s)&&this.addFormatting(e.pts,["i"])}else this.isNormalChar(n)&&(0===s&&(s=null),r=ve(n),r+=ve(s),this[this.mode_](e.pts,r),this.column_+=r.length)}else this.lastControlCode_=null}};Ee.prototype=new pe,Ee.prototype.flushDisplayed=function(e){var t=this.displayed_.map((function(e,t){try{return e.trim()}catch(e){return this.trigger("log",{level:"warn",message:"Skipping a malformed 608 caption at index "+t+"."}),""}}),this).join("\n").replace(/^\n+|\n+$/g,"");t.length&&this.trigger("data",{startPts:this.startPts_,endPts:e,text:t,stream:this.name_})},Ee.prototype.reset=function(){this.mode_="popOn",this.topRow_=0,this.startPts_=0,this.displayed_=Ie(),this.nonDisplayed_=Ie(),this.lastControlCode_=null,this.column_=0,this.row_=14,this.rollUpRows_=2,this.formatting_=[]},Ee.prototype.setConstants=function(){0===this.dataChannel_?(this.BASE_=16,this.EXT_=17,this.CONTROL_=(20|this.field_)<<8,this.OFFSET_=23):1===this.dataChannel_&&(this.BASE_=24,this.EXT_=25,this.CONTROL_=(28|this.field_)<<8,this.OFFSET_=31),this.PADDING_=0,this.RESUME_CAPTION_LOADING_=32|this.CONTROL_,this.END_OF_CAPTION_=47|this.CONTROL_,this.ROLL_UP_2_ROWS_=37|this.CONTROL_,this.ROLL_UP_3_ROWS_=38|this.CONTROL_,this.ROLL_UP_4_ROWS_=39|this.CONTROL_,this.CARRIAGE_RETURN_=45|this.CONTROL_,this.RESUME_DIRECT_CAPTIONING_=41|this.CONTROL_,this.BACKSPACE_=33|this.CONTROL_,this.ERASE_DISPLAYED_MEMORY_=44|this.CONTROL_,this.ERASE_NON_DISPLAYED_MEMORY_=46|this.CONTROL_},Ee.prototype.isSpecialCharacter=function(e,t){return e===this.EXT_&&t>=48&&t<=63},Ee.prototype.isExtCharacter=function(e,t){return(e===this.EXT_+1||e===this.EXT_+2)&&t>=32&&t<=63},Ee.prototype.isMidRowCode=function(e,t){return e===this.EXT_&&t>=32&&t<=47},Ee.prototype.isOffsetControlCode=function(e,t){return e===this.OFFSET_&&t>=33&&t<=35},Ee.prototype.isPAC=function(e,t){return e>=this.BASE_&&e<this.BASE_+8&&t>=64&&t<=127},Ee.prototype.isColorPAC=function(e){return e>=64&&e<=79||e>=96&&e<=127},Ee.prototype.isNormalChar=function(e){return e>=32&&e<=127},Ee.prototype.setRollUp=function(e,t){if("rollUp"!==this.mode_&&(this.row_=14,this.mode_="rollUp",this.flushDisplayed(e),this.nonDisplayed_=Ie(),this.displayed_=Ie()),void 0!==t&&t!==this.row_)for(var i=0;i<this.rollUpRows_;i++)this.displayed_[t-i]=this.displayed_[this.row_-i],this.displayed_[this.row_-i]="";void 0===t&&(t=this.row_),this.topRow_=t-this.rollUpRows_+1},Ee.prototype.addFormatting=function(e,t){this.formatting_=this.formatting_.concat(t);var i=t.reduce((function(e,t){return e+"<"+t+">"}),"");this[this.mode_](e,i)},Ee.prototype.clearFormatting=function(e){if(this.formatting_.length){var t=this.formatting_.reverse().reduce((function(e,t){return e+"</"+t+">"}),"");this.formatting_=[],this[this.mode_](e,t)}},Ee.prototype.popOn=function(e,t){var i=this.nonDisplayed_[this.row_];i+=t,this.nonDisplayed_[this.row_]=i},Ee.prototype.rollUp=function(e,t){var i=this.displayed_[this.row_];i+=t,this.displayed_[this.row_]=i},Ee.prototype.shiftRowsUp_=function(){var e;for(e=0;e<this.topRow_;e++)this.displayed_[e]="";for(e=this.row_+1;e<15;e++)this.displayed_[e]="";for(e=this.topRow_;e<this.row_;e++)this.displayed_[e]=this.displayed_[e+1];this.displayed_[this.row_]=""},Ee.prototype.paintOn=function(e,t){var i=this.displayed_[this.row_];i+=t,this.displayed_[this.row_]=i};var Ae={CaptionStream:fe,Cea608Stream:Ee,Cea708Stream:be},Le={H264_STREAM_TYPE:27,ADTS_STREAM_TYPE:15,METADATA_STREAM_TYPE:21},xe=W,De="shared",ke=function(e,t){var i=1;for(e>t&&(i=-1);Math.abs(t-e)>4294967296;)e+=8589934592*i;return e},Oe=function(e){var t,i;Oe.prototype.init.call(this),this.type_=e||De,this.push=function(e){this.type_!==De&&e.type!==this.type_||(void 0===i&&(i=e.dts),e.dts=ke(e.dts,i),e.pts=ke(e.pts,i),t=e.dts,this.trigger("data",e))},this.flush=function(){i=t,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.discontinuity=function(){i=void 0,t=void 0},this.reset=function(){this.discontinuity(),this.trigger("reset")}};Oe.prototype=new xe;var Pe,Ue={TimestampRolloverStream:Oe,handleRollover:ke},Ce=Le,Re=(e,t,i)=>{if(!e)return-1;for(var n=i;n<e.length;n++)if(e[n]===t)return n;return-1},Me=function(e,t,i){var n,s="";for(n=t;n<i;n++)s+="%"+("00"+e[n].toString(16)).slice(-2);return s},Be=function(e,t,i){return decodeURIComponent(Me(e,t,i))},Ne=function(e,t,i){return unescape(Me(e,t,i))},Fe=function(e){return e[0]<<21|e[1]<<14|e[2]<<7|e[3]},$e={APIC:function(e){var t,i,n=1;3===e.data[0]&&((t=Re(e.data,0,n))<0||(e.mimeType=Ne(e.data,n,t),n=t+1,e.pictureType=e.data[n],n++,(i=Re(e.data,0,n))<0||(e.description=Be(e.data,n,i),n=i+1,"--\x3e"===e.mimeType?e.url=Ne(e.data,n,e.data.length):e.pictureData=e.data.subarray(n,e.data.length))))},"T*":function(e){3===e.data[0]&&(e.value=Be(e.data,1,e.data.length).replace(/\0*$/,""),e.values=e.value.split("\0"))},TXXX:function(e){var t;3===e.data[0]&&-1!==(t=Re(e.data,0,1))&&(e.description=Be(e.data,1,t),e.value=Be(e.data,t+1,e.data.length).replace(/\0*$/,""),e.data=e.value)},"W*":function(e){e.url=Ne(e.data,0,e.data.length).replace(/\0.*$/,"")},WXXX:function(e){var t;3===e.data[0]&&-1!==(t=Re(e.data,0,1))&&(e.description=Be(e.data,1,t),e.url=Ne(e.data,t+1,e.data.length).replace(/\0.*$/,""))},PRIV:function(e){var t;for(t=0;t<e.data.length;t++)if(0===e.data[t]){e.owner=Ne(e.data,0,t);break}e.privateData=e.data.subarray(t+1),e.data=e.privateData}};(Pe=function(e){var t,i={descriptor:e&&e.descriptor},n=0,s=[],r=0;if(Pe.prototype.init.call(this),this.dispatchType=Ce.METADATA_STREAM_TYPE.toString(16),i.descriptor)for(t=0;t<i.descriptor.length;t++)this.dispatchType+=("00"+i.descriptor[t].toString(16)).slice(-2);this.push=function(e){var t,i,a,o,d;if("timed-metadata"===e.type)if(e.dataAlignmentIndicator&&(r=0,s.length=0),0===s.length&&(e.data.length<10||e.data[0]!=="I".charCodeAt(0)||e.data[1]!=="D".charCodeAt(0)||e.data[2]!=="3".charCodeAt(0)))this.trigger("log",{level:"warn",message:"Skipping unrecognized metadata packet"});else if(s.push(e),r+=e.data.byteLength,1===s.length&&(n=Fe(e.data.subarray(6,10)),n+=10),!(r<n)){for(t={data:new Uint8Array(n),frames:[],pts:s[0].pts,dts:s[0].dts},d=0;d<n;)t.data.set(s[0].data.subarray(0,n-d),d),d+=s[0].data.byteLength,r-=s[0].data.byteLength,s.shift();i=10,64&t.data[5]&&(i+=4,i+=Fe(t.data.subarray(10,14)),n-=Fe(t.data.subarray(16,20)));do{if((a=Fe(t.data.subarray(i+4,i+8)))<1){this.trigger("log",{level:"warn",message:"Malformed ID3 frame encountered. Skipping remaining metadata parsing."});break}if((o={id:String.fromCharCode(t.data[i],t.data[i+1],t.data[i+2],t.data[i+3]),data:t.data.subarray(i+10,i+a+10)}).key=o.id,$e[o.id]?$e[o.id](o):"T"===o.id[0]?$e["T*"](o):"W"===o.id[0]&&$e["W*"](o),"com.apple.streaming.transportStreamTimestamp"===o.owner){var u=o.data,l=(1&u[3])<<30|u[4]<<22|u[5]<<14|u[6]<<6|u[7]>>>2;l*=4,l+=3&u[7],o.timeStamp=l,void 0===t.pts&&void 0===t.dts&&(t.pts=o.timeStamp,t.dts=o.timeStamp),this.trigger("timestamp",o)}t.frames.push(o),i+=10,i+=a}while(i<n);this.trigger("data",t)}}}).prototype=new W;var qe,We,Ge,Ve=Pe,He=W,je=Ae,Xe=Le,ze=Ue.TimestampRolloverStream,Qe=188;(qe=function(){var e=new Uint8Array(Qe),t=0;qe.prototype.init.call(this),this.push=function(i){var n,s=0,r=Qe;for(t?((n=new Uint8Array(i.byteLength+t)).set(e.subarray(0,t)),n.set(i,t),t=0):n=i;r<n.byteLength;)71!==n[s]||71!==n[r]?(s++,r++):(this.trigger("data",n.subarray(s,r)),s+=Qe,r+=Qe);s<n.byteLength&&(e.set(n.subarray(s),0),t=n.byteLength-s)},this.flush=function(){t===Qe&&71===e[0]&&(this.trigger("data",e),t=0),this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.reset=function(){t=0,this.trigger("reset")}}).prototype=new He,(We=function(){var e,t,i,n;We.prototype.init.call(this),n=this,this.packetsWaitingForPmt=[],this.programMapTable=void 0,e=function(e,n){var s=0;n.payloadUnitStartIndicator&&(s+=e[s]+1),"pat"===n.type?t(e.subarray(s),n):i(e.subarray(s),n)},t=function(e,t){t.section_number=e[7],t.last_section_number=e[8],n.pmtPid=(31&e[10])<<8|e[11],t.pmtPid=n.pmtPid},i=function(e,t){var i,s;if(1&e[5]){for(n.programMapTable={video:null,audio:null,"timed-metadata":{}},i=3+((15&e[1])<<8|e[2])-4,s=12+((15&e[10])<<8|e[11]);s<i;){var r=e[s],a=(31&e[s+1])<<8|e[s+2];r===Xe.H264_STREAM_TYPE&&null===n.programMapTable.video?n.programMapTable.video=a:r===Xe.ADTS_STREAM_TYPE&&null===n.programMapTable.audio?n.programMapTable.audio=a:r===Xe.METADATA_STREAM_TYPE&&(n.programMapTable["timed-metadata"][a]=r),s+=5+((15&e[s+3])<<8|e[s+4])}t.programMapTable=n.programMapTable}},this.push=function(t){var i={},n=4;if(i.payloadUnitStartIndicator=!!(64&t[1]),i.pid=31&t[1],i.pid<<=8,i.pid|=t[2],(48&t[3])>>>4>1&&(n+=t[n]+1),0===i.pid)i.type="pat",e(t.subarray(n),i),this.trigger("data",i);else if(i.pid===this.pmtPid)for(i.type="pmt",e(t.subarray(n),i),this.trigger("data",i);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else void 0===this.programMapTable?this.packetsWaitingForPmt.push([t,n,i]):this.processPes_(t,n,i)},this.processPes_=function(e,t,i){i.pid===this.programMapTable.video?i.streamType=Xe.H264_STREAM_TYPE:i.pid===this.programMapTable.audio?i.streamType=Xe.ADTS_STREAM_TYPE:i.streamType=this.programMapTable["timed-metadata"][i.pid],i.type="pes",i.data=e.subarray(t),this.trigger("data",i)}}).prototype=new He,We.STREAM_TYPES={h264:27,adts:15},Ge=function(){var e,t=this,i=!1,n={data:[],size:0},s={data:[],size:0},r={data:[],size:0},a=function(e,i,n){var s,r,a=new Uint8Array(e.size),o={type:i},d=0,u=0;if(e.data.length&&!(e.size<9)){for(o.trackId=e.data[0].pid,d=0;d<e.data.length;d++)r=e.data[d],a.set(r.data,u),u+=r.data.byteLength;!function(e,t){var i;const n=e[0]<<16|e[1]<<8|e[2];t.data=new Uint8Array,1===n&&(t.packetLength=6+(e[4]<<8|e[5]),t.dataAlignmentIndicator=0!=(4&e[6]),192&(i=e[7])&&(t.pts=(14&e[9])<<27|(255&e[10])<<20|(254&e[11])<<12|(255&e[12])<<5|(254&e[13])>>>3,t.pts*=4,t.pts+=(6&e[13])>>>1,t.dts=t.pts,64&i&&(t.dts=(14&e[14])<<27|(255&e[15])<<20|(254&e[16])<<12|(255&e[17])<<5|(254&e[18])>>>3,t.dts*=4,t.dts+=(6&e[18])>>>1)),t.data=e.subarray(9+e[8]))}(a,o),s="video"===i||o.packetLength<=e.size,(n||s)&&(e.size=0,e.data.length=0),s&&t.trigger("data",o)}};Ge.prototype.init.call(this),this.push=function(o){({pat:function(){},pes:function(){var e,t;switch(o.streamType){case Xe.H264_STREAM_TYPE:e=n,t="video";break;case Xe.ADTS_STREAM_TYPE:e=s,t="audio";break;case Xe.METADATA_STREAM_TYPE:e=r,t="timed-metadata";break;default:return}o.payloadUnitStartIndicator&&a(e,t,!0),e.data.push(o),e.size+=o.data.byteLength},pmt:function(){var n={type:"metadata",tracks:[]};null!==(e=o.programMapTable).video&&n.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+e.video,codec:"avc",type:"video"}),null!==e.audio&&n.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+e.audio,codec:"adts",type:"audio"}),i=!0,t.trigger("data",n)}})[o.type]()},this.reset=function(){n.size=0,n.data.length=0,s.size=0,s.data.length=0,this.trigger("reset")},this.flushStreams_=function(){a(n,"video"),a(s,"audio"),a(r,"timed-metadata")},this.flush=function(){if(!i&&e){var n={type:"metadata",tracks:[]};null!==e.video&&n.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+e.video,codec:"avc",type:"video"}),null!==e.audio&&n.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+e.audio,codec:"adts",type:"audio"}),t.trigger("data",n)}i=!1,this.flushStreams_(),this.trigger("done")}},Ge.prototype=new He;var Ye={PAT_PID:0,MP2T_PACKET_LENGTH:Qe,TransportPacketStream:qe,TransportParseStream:We,ElementaryStream:Ge,TimestampRolloverStream:ze,CaptionStream:je.CaptionStream,Cea608Stream:je.Cea608Stream,Cea708Stream:je.Cea708Stream,MetadataStream:Ve};for(var Ke in Xe)Xe.hasOwnProperty(Ke)&&(Ye[Ke]=Xe[Ke]);var Je,Ze=Ye,et=oe.ONE_SECOND_IN_TS,tt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];(Je=function(e){var t,i=0;Je.prototype.init.call(this),this.skipWarn_=function(e,t){this.trigger("log",{level:"warn",message:`adts skiping bytes ${e} to ${t} in frame ${i} outside syncword`})},this.push=function(n){var s,r,a,o,d,u=0;if(e||(i=0),"audio"===n.type){var l;for(t&&t.length?(a=t,(t=new Uint8Array(a.byteLength+n.data.byteLength)).set(a),t.set(n.data,a.byteLength)):t=n.data;u+7<t.length;)if(255===t[u]&&240==(246&t[u+1])){if("number"==typeof l&&(this.skipWarn_(l,u),l=null),r=2*(1&~t[u+1]),s=(3&t[u+3])<<11|t[u+4]<<3|(224&t[u+5])>>5,d=(o=1024*(1+(3&t[u+6])))*et/tt[(60&t[u+2])>>>2],t.byteLength-u<s)break;this.trigger("data",{pts:n.pts+i*d,dts:n.dts+i*d,sampleCount:o,audioobjecttype:1+(t[u+2]>>>6&3),channelcount:(1&t[u+2])<<2|(192&t[u+3])>>>6,samplerate:tt[(60&t[u+2])>>>2],samplingfrequencyindex:(60&t[u+2])>>>2,samplesize:16,data:t.subarray(u+7+r,u+s)}),i++,u+=s}else"number"!=typeof l&&(l=u),u++;"number"==typeof l&&(this.skipWarn_(l,u),l=null),t=t.subarray(u)}},this.flush=function(){i=0,this.trigger("done")},this.reset=function(){t=void 0,this.trigger("reset")},this.endTimeline=function(){t=void 0,this.trigger("endedtimeline")}}).prototype=new W;var it,nt,st,rt=Je,at=W,ot=function(e){var t=e.byteLength,i=0,n=0;this.length=function(){return 8*t},this.bitsAvailable=function(){return 8*t+n},this.loadWord=function(){var s=e.byteLength-t,r=new Uint8Array(4),a=Math.min(4,t);if(0===a)throw new Error("no bytes available");r.set(e.subarray(s,s+a)),i=new DataView(r.buffer).getUint32(0),n=8*a,t-=a},this.skipBits=function(e){var s;n>e?(i<<=e,n-=e):(e-=n,e-=8*(s=Math.floor(e/8)),t-=s,this.loadWord(),i<<=e,n-=e)},this.readBits=function(e){var s=Math.min(n,e),r=i>>>32-s;return(n-=s)>0?i<<=s:t>0&&this.loadWord(),(s=e-s)>0?r<<s|this.readBits(s):r},this.skipLeadingZeros=function(){var e;for(e=0;e<n;++e)if(0!=(i&2147483648>>>e))return i<<=e,n-=e,e;return this.loadWord(),e+this.skipLeadingZeros()},this.skipUnsignedExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.readUnsignedExpGolomb=function(){var e=this.skipLeadingZeros();return this.readBits(e+1)-1},this.readExpGolomb=function(){var e=this.readUnsignedExpGolomb();return 1&e?1+e>>>1:-1*(e>>>1)},this.readBoolean=function(){return 1===this.readBits(1)},this.readUnsignedByte=function(){return this.readBits(8)},this.loadWord()};(nt=function(){var e,t,i=0;nt.prototype.init.call(this),this.push=function(n){var s;t?((s=new Uint8Array(t.byteLength+n.data.byteLength)).set(t),s.set(n.data,t.byteLength),t=s):t=n.data;for(var r=t.byteLength;i<r-3;i++)if(1===t[i+2]){e=i+5;break}for(;e<r;)switch(t[e]){case 0:if(0!==t[e-1]){e+=2;break}if(0!==t[e-2]){e++;break}i+3!==e-2&&this.trigger("data",t.subarray(i+3,e-2));do{e++}while(1!==t[e]&&e<r);i=e-2,e+=3;break;case 1:if(0!==t[e-1]||0!==t[e-2]){e+=3;break}this.trigger("data",t.subarray(i+3,e-2)),i=e-2,e+=3;break;default:e+=3}t=t.subarray(i),e-=i,i=0},this.reset=function(){t=null,i=0,this.trigger("reset")},this.flush=function(){t&&t.byteLength>3&&this.trigger("data",t.subarray(i+3)),t=null,i=0,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")}}).prototype=new at,st={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},it=function(){var e,t,i,n,s,r,a,o=new nt;it.prototype.init.call(this),e=this,this.push=function(e){"video"===e.type&&(t=e.trackId,i=e.pts,n=e.dts,o.push(e))},o.on("data",(function(a){var o={trackId:t,pts:i,dts:n,data:a,nalUnitTypeCode:31&a[0]};switch(o.nalUnitTypeCode){case 5:o.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:o.nalUnitType="sei_rbsp",o.escapedRBSP=s(a.subarray(1));break;case 7:o.nalUnitType="seq_parameter_set_rbsp",o.escapedRBSP=s(a.subarray(1)),o.config=r(o.escapedRBSP);break;case 8:o.nalUnitType="pic_parameter_set_rbsp";break;case 9:o.nalUnitType="access_unit_delimiter_rbsp"}e.trigger("data",o)})),o.on("done",(function(){e.trigger("done")})),o.on("partialdone",(function(){e.trigger("partialdone")})),o.on("reset",(function(){e.trigger("reset")})),o.on("endedtimeline",(function(){e.trigger("endedtimeline")})),this.flush=function(){o.flush()},this.partialFlush=function(){o.partialFlush()},this.reset=function(){o.reset()},this.endTimeline=function(){o.endTimeline()},a=function(e,t){var i,n=8,s=8;for(i=0;i<e;i++)0!==s&&(s=(n+t.readExpGolomb()+256)%256),n=0===s?n:s},s=function(e){for(var t,i,n=e.byteLength,s=[],r=1;r<n-2;)0===e[r]&&0===e[r+1]&&3===e[r+2]?(s.push(r+2),r+=2):r++;if(0===s.length)return e;t=n-s.length,i=new Uint8Array(t);var a=0;for(r=0;r<t;a++,r++)a===s[0]&&(a++,s.shift()),i[r]=e[a];return i},r=function(e){var t,i,n,s,r,o,d,u,l,h,c,p,m=0,f=0,g=0,y=0,_=[1,1];if(i=(t=new ot(e)).readUnsignedByte(),s=t.readUnsignedByte(),n=t.readUnsignedByte(),t.skipUnsignedExpGolomb(),st[i]&&(3===(r=t.readUnsignedExpGolomb())&&t.skipBits(1),t.skipUnsignedExpGolomb(),t.skipUnsignedExpGolomb(),t.skipBits(1),t.readBoolean()))for(c=3!==r?8:12,p=0;p<c;p++)t.readBoolean()&&a(p<6?16:64,t);if(t.skipUnsignedExpGolomb(),0===(o=t.readUnsignedExpGolomb()))t.readUnsignedExpGolomb();else if(1===o)for(t.skipBits(1),t.skipExpGolomb(),t.skipExpGolomb(),d=t.readUnsignedExpGolomb(),p=0;p<d;p++)t.skipExpGolomb();if(t.skipUnsignedExpGolomb(),t.skipBits(1),u=t.readUnsignedExpGolomb(),l=t.readUnsignedExpGolomb(),0===(h=t.readBits(1))&&t.skipBits(1),t.skipBits(1),t.readBoolean()&&(m=t.readUnsignedExpGolomb(),f=t.readUnsignedExpGolomb(),g=t.readUnsignedExpGolomb(),y=t.readUnsignedExpGolomb()),t.readBoolean()&&t.readBoolean()){switch(t.readUnsignedByte()){case 1:_=[1,1];break;case 2:_=[12,11];break;case 3:_=[10,11];break;case 4:_=[16,11];break;case 5:_=[40,33];break;case 6:_=[24,11];break;case 7:_=[20,11];break;case 8:_=[32,11];break;case 9:_=[80,33];break;case 10:_=[18,11];break;case 11:_=[15,11];break;case 12:_=[64,33];break;case 13:_=[160,99];break;case 14:_=[4,3];break;case 15:_=[3,2];break;case 16:_=[2,1];break;case 255:_=[t.readUnsignedByte()<<8|t.readUnsignedByte(),t.readUnsignedByte()<<8|t.readUnsignedByte()]}_&&(_[0],_[1])}return{profileIdc:i,levelIdc:n,profileCompatibility:s,width:16*(u+1)-2*m-2*f,height:(2-h)*(l+1)*16-2*g-2*y,sarRatio:_}}},it.prototype=new at;var dt,ut={H264Stream:it,NalByteStream:nt},lt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],ht=function(e,t){var i=e[t+6]<<21|e[t+7]<<14|e[t+8]<<7|e[t+9];return i=i>=0?i:0,(16&e[t+5])>>4?i+20:i+10},ct=function(e,t){return e.length-t<10||e[t]!=="I".charCodeAt(0)||e[t+1]!=="D".charCodeAt(0)||e[t+2]!=="3".charCodeAt(0)?t:(t+=ht(e,t),ct(e,t))},pt=function(e){return e[0]<<21|e[1]<<14|e[2]<<7|e[3]},mt={isLikelyAacData:function(e){var t=ct(e,0);return e.length>=t+2&&255==(255&e[t])&&240==(240&e[t+1])&&16==(22&e[t+1])},parseId3TagSize:ht,parseAdtsSize:function(e,t){var i=(224&e[t+5])>>5,n=e[t+4]<<3;return 6144&e[t+3]|n|i},parseType:function(e,t){return e[t]==="I".charCodeAt(0)&&e[t+1]==="D".charCodeAt(0)&&e[t+2]==="3".charCodeAt(0)?"timed-metadata":!0&e[t]&&240==(240&e[t+1])?"audio":null},parseSampleRate:function(e){for(var t=0;t+5<e.length;){if(255===e[t]&&240==(246&e[t+1]))return lt[(60&e[t+2])>>>2];t++}return null},parseAacTimestamp:function(e){var t,i,n;t=10,64&e[5]&&(t+=4,t+=pt(e.subarray(10,14)));do{if((i=pt(e.subarray(t+4,t+8)))<1)return null;if("PRIV"===String.fromCharCode(e[t],e[t+1],e[t+2],e[t+3])){n=e.subarray(t+10,t+i+10);for(var s=0;s<n.byteLength;s++)if(0===n[s]){var r=unescape(function(e,t,i){var n,s="";for(n=0;n<i;n++)s+="%"+("00"+e[n].toString(16)).slice(-2);return s}(n,0,s));if("com.apple.streaming.transportStreamTimestamp"===r){var a=n.subarray(s+1),o=(1&a[3])<<30|a[4]<<22|a[5]<<14|a[6]<<6|a[7]>>>2;return(o*=4)+(3&a[7])}break}}t+=10,t+=i}while(t<e.byteLength);return null}},ft=mt;(dt=function(){var e=new Uint8Array,t=0;dt.prototype.init.call(this),this.setTimestamp=function(e){t=e},this.push=function(i){var n,s,r,a,o=0,d=0;for(e.length?(a=e.length,(e=new Uint8Array(i.byteLength+a)).set(e.subarray(0,a)),e.set(i,a)):e=i;e.length-d>=3;)if(e[d]!=="I".charCodeAt(0)||e[d+1]!=="D".charCodeAt(0)||e[d+2]!=="3".charCodeAt(0))if(255!=(255&e[d])||240!=(240&e[d+1]))d++;else{if(e.length-d<7)break;if(d+(o=ft.parseAdtsSize(e,d))>e.length)break;r={type:"audio",data:e.subarray(d,d+o),pts:t,dts:t},this.trigger("data",r),d+=o}else{if(e.length-d<10)break;if(d+(o=ft.parseId3TagSize(e,d))>e.length)break;s={type:"timed-metadata",data:e.subarray(d,d+o)},this.trigger("data",s),d+=o}n=e.length-d,e=n>0?e.subarray(d):new Uint8Array},this.reset=function(){e=new Uint8Array,this.trigger("reset")},this.endTimeline=function(){e=new Uint8Array,this.trigger("endedtimeline")}}).prototype=new W;var gt,yt,_t,Tt,bt=W,St=ee,vt=ie,wt=ue,It=he,Et=Ze,At=oe,Lt=rt,xt=ut.H264Stream,Dt=dt,kt=mt.isLikelyAacData,Ot=oe.ONE_SECOND_IN_TS,Pt=["audioobjecttype","channelcount","samplerate","samplingfrequencyindex","samplesize"],Ut=["width","height","profileIdc","levelIdc","profileCompatibility","sarRatio"],Ct=function(e,t){t.stream=e,this.trigger("log",t)},Rt=function(e,t){for(var i=Object.keys(t),n=0;n<i.length;n++){var s=i[n];"headOfPipeline"!==s&&t[s].on&&t[s].on("log",Ct.bind(e,s))}},Mt=function(e,t){var i;if(e.length!==t.length)return!1;for(i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0},Bt=function(e,t,i,n,s,r){return{start:{dts:e,pts:e+(i-t)},end:{dts:e+(n-t),pts:e+(s-i)},prependedContentDuration:r,baseMediaDecodeTime:e}};yt=function(e,t){var i,n=[],s=0,r=0,a=1/0;i=(t=t||{}).firstSequenceNumber||0,yt.prototype.init.call(this),this.push=function(t){It.collectDtsInfo(e,t),e&&Pt.forEach((function(i){e[i]=t[i]})),n.push(t)},this.setEarliestDts=function(e){s=e},this.setVideoBaseMediaDecodeTime=function(e){a=e},this.setAudioAppendStart=function(e){r=e},this.flush=function(){var o,d,u,l,h,c,p;0!==n.length?(o=wt.trimAdtsFramesByEarliestDts(n,e,s),e.baseMediaDecodeTime=It.calculateTrackBaseMediaDecodeTime(e,t.keepOriginalTimestamps),p=wt.prefixWithSilence(e,o,r,a),e.samples=wt.generateSampleTable(o),u=St.mdat(wt.concatenateFrameData(o)),n=[],d=St.moof(i,[e]),l=new Uint8Array(d.byteLength+u.byteLength),i++,l.set(d),l.set(u,d.byteLength),It.clearDtsInfo(e),h=Math.ceil(1024*Ot/e.samplerate),o.length&&(c=o.length*h,this.trigger("segmentTimingInfo",Bt(At.audioTsToVideoTs(e.baseMediaDecodeTime,e.samplerate),o[0].dts,o[0].pts,o[0].dts+c,o[0].pts+c,p||0)),this.trigger("timingInfo",{start:o[0].pts,end:o[0].pts+c})),this.trigger("data",{track:e,boxes:l}),this.trigger("done","AudioSegmentStream")):this.trigger("done","AudioSegmentStream")},this.reset=function(){It.clearDtsInfo(e),n=[],this.trigger("reset")}},yt.prototype=new bt,gt=function(e,t){var i,n,s,r=[],a=[];i=(t=t||{}).firstSequenceNumber||0,gt.prototype.init.call(this),delete e.minPTS,this.gopCache_=[],this.push=function(t){It.collectDtsInfo(e,t),"seq_parameter_set_rbsp"!==t.nalUnitType||n||(n=t.config,e.sps=[t.data],Ut.forEach((function(t){e[t]=n[t]}),this)),"pic_parameter_set_rbsp"!==t.nalUnitType||s||(s=t.data,e.pps=[t.data]),r.push(t)},this.flush=function(){for(var n,s,o,d,u,l,h,c,p=0;r.length&&"access_unit_delimiter_rbsp"!==r[0].nalUnitType;)r.shift();if(0===r.length)return this.resetStream_(),void this.trigger("done","VideoSegmentStream");if(n=vt.groupNalsIntoFrames(r),(o=vt.groupFramesIntoGops(n))[0][0].keyFrame||((s=this.getGopForFusion_(r[0],e))?(p=s.duration,o.unshift(s),o.byteLength+=s.byteLength,o.nalCount+=s.nalCount,o.pts=s.pts,o.dts=s.dts,o.duration+=s.duration):o=vt.extendFirstKeyFrame(o)),a.length){var m;if(!(m=t.alignGopsAtEnd?this.alignGopsAtEnd_(o):this.alignGopsAtStart_(o)))return this.gopCache_.unshift({gop:o.pop(),pps:e.pps,sps:e.sps}),this.gopCache_.length=Math.min(6,this.gopCache_.length),r=[],this.resetStream_(),void this.trigger("done","VideoSegmentStream");It.clearDtsInfo(e),o=m}It.collectDtsInfo(e,o),e.samples=vt.generateSampleTable(o),u=St.mdat(vt.concatenateNalData(o)),e.baseMediaDecodeTime=It.calculateTrackBaseMediaDecodeTime(e,t.keepOriginalTimestamps),this.trigger("processedGopsInfo",o.map((function(e){return{pts:e.pts,dts:e.dts,byteLength:e.byteLength}}))),h=o[0],c=o[o.length-1],this.trigger("segmentTimingInfo",Bt(e.baseMediaDecodeTime,h.dts,h.pts,c.dts+c.duration,c.pts+c.duration,p)),this.trigger("timingInfo",{start:o[0].pts,end:o[o.length-1].pts+o[o.length-1].duration}),this.gopCache_.unshift({gop:o.pop(),pps:e.pps,sps:e.sps}),this.gopCache_.length=Math.min(6,this.gopCache_.length),r=[],this.trigger("baseMediaDecodeTime",e.baseMediaDecodeTime),this.trigger("timelineStartInfo",e.timelineStartInfo),d=St.moof(i,[e]),l=new Uint8Array(d.byteLength+u.byteLength),i++,l.set(d),l.set(u,d.byteLength),this.trigger("data",{track:e,boxes:l}),this.resetStream_(),this.trigger("done","VideoSegmentStream")},this.reset=function(){this.resetStream_(),r=[],this.gopCache_.length=0,a.length=0,this.trigger("reset")},this.resetStream_=function(){It.clearDtsInfo(e),n=void 0,s=void 0},this.getGopForFusion_=function(t){var i,n,s,r,a,o=1/0;for(a=0;a<this.gopCache_.length;a++)s=(r=this.gopCache_[a]).gop,e.pps&&Mt(e.pps[0],r.pps[0])&&e.sps&&Mt(e.sps[0],r.sps[0])&&(s.dts<e.timelineStartInfo.dts||(i=t.dts-s.dts-s.duration)>=-1e4&&i<=45e3&&(!n||o>i)&&(n=r,o=i));return n?n.gop:null},this.alignGopsAtStart_=function(e){var t,i,n,s,r,o,d,u;for(r=e.byteLength,o=e.nalCount,d=e.duration,t=i=0;t<a.length&&i<e.length&&(n=a[t],s=e[i],n.pts!==s.pts);)s.pts>n.pts?t++:(i++,r-=s.byteLength,o-=s.nalCount,d-=s.duration);return 0===i?e:i===e.length?null:((u=e.slice(i)).byteLength=r,u.duration=d,u.nalCount=o,u.pts=u[0].pts,u.dts=u[0].dts,u)},this.alignGopsAtEnd_=function(e){var t,i,n,s,r,o,d;for(t=a.length-1,i=e.length-1,r=null,o=!1;t>=0&&i>=0;){if(n=a[t],s=e[i],n.pts===s.pts){o=!0;break}n.pts>s.pts?t--:(t===a.length-1&&(r=i),i--)}if(!o&&null===r)return null;if(0===(d=o?i:r))return e;var u=e.slice(d),l=u.reduce((function(e,t){return e.byteLength+=t.byteLength,e.duration+=t.duration,e.nalCount+=t.nalCount,e}),{byteLength:0,duration:0,nalCount:0});return u.byteLength=l.byteLength,u.duration=l.duration,u.nalCount=l.nalCount,u.pts=u[0].pts,u.dts=u[0].dts,u},this.alignGopsWith=function(e){a=e}},gt.prototype=new bt,Tt=function(e,t){this.numberOfTracks=0,this.metadataStream=t,void 0!==(e=e||{}).remux?this.remuxTracks=!!e.remux:this.remuxTracks=!0,"boolean"==typeof e.keepOriginalTimestamps?this.keepOriginalTimestamps=e.keepOriginalTimestamps:this.keepOriginalTimestamps=!1,this.pendingTracks=[],this.videoTrack=null,this.pendingBoxes=[],this.pendingCaptions=[],this.pendingMetadata=[],this.pendingBytes=0,this.emittedTracks=0,Tt.prototype.init.call(this),this.push=function(e){return e.text?this.pendingCaptions.push(e):e.frames?this.pendingMetadata.push(e):(this.pendingTracks.push(e.track),this.pendingBytes+=e.boxes.byteLength,"video"===e.track.type&&(this.videoTrack=e.track,this.pendingBoxes.push(e.boxes)),void("audio"===e.track.type&&(this.audioTrack=e.track,this.pendingBoxes.unshift(e.boxes))))}},Tt.prototype=new bt,Tt.prototype.flush=function(e){var t,i,n,s,r=0,a={captions:[],captionStreams:{},metadata:[],info:{}},o=0;if(this.pendingTracks.length<this.numberOfTracks){if("VideoSegmentStream"!==e&&"AudioSegmentStream"!==e)return;if(this.remuxTracks)return;if(0===this.pendingTracks.length)return this.emittedTracks++,void(this.emittedTracks>=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0))}if(this.videoTrack?(o=this.videoTrack.timelineStartInfo.pts,Ut.forEach((function(e){a.info[e]=this.videoTrack[e]}),this)):this.audioTrack&&(o=this.audioTrack.timelineStartInfo.pts,Pt.forEach((function(e){a.info[e]=this.audioTrack[e]}),this)),this.videoTrack||this.audioTrack){for(1===this.pendingTracks.length?a.type=this.pendingTracks[0].type:a.type="combined",this.emittedTracks+=this.pendingTracks.length,n=St.initSegment(this.pendingTracks),a.initSegment=new Uint8Array(n.byteLength),a.initSegment.set(n),a.data=new Uint8Array(this.pendingBytes),s=0;s<this.pendingBoxes.length;s++)a.data.set(this.pendingBoxes[s],r),r+=this.pendingBoxes[s].byteLength;for(s=0;s<this.pendingCaptions.length;s++)(t=this.pendingCaptions[s]).startTime=At.metadataTsToSeconds(t.startPts,o,this.keepOriginalTimestamps),t.endTime=At.metadataTsToSeconds(t.endPts,o,this.keepOriginalTimestamps),a.captionStreams[t.stream]=!0,a.captions.push(t);for(s=0;s<this.pendingMetadata.length;s++)(i=this.pendingMetadata[s]).cueTime=At.metadataTsToSeconds(i.pts,o,this.keepOriginalTimestamps),a.metadata.push(i);for(a.metadata.dispatchType=this.metadataStream.dispatchType,this.pendingTracks.length=0,this.videoTrack=null,this.pendingBoxes.length=0,this.pendingCaptions.length=0,this.pendingBytes=0,this.pendingMetadata.length=0,this.trigger("data",a),s=0;s<a.captions.length;s++)t=a.captions[s],this.trigger("caption",t);for(s=0;s<a.metadata.length;s++)i=a.metadata[s],this.trigger("id3Frame",i)}this.emittedTracks>=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0)},Tt.prototype.setRemux=function(e){this.remuxTracks=e},(_t=function(e){var t,i,n=this,s=!0;_t.prototype.init.call(this),e=e||{},this.baseMediaDecodeTime=e.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var s={};this.transmuxPipeline_=s,s.type="aac",s.metadataStream=new Et.MetadataStream,s.aacStream=new Dt,s.audioTimestampRolloverStream=new Et.TimestampRolloverStream("audio"),s.timedMetadataTimestampRolloverStream=new Et.TimestampRolloverStream("timed-metadata"),s.adtsStream=new Lt,s.coalesceStream=new Tt(e,s.metadataStream),s.headOfPipeline=s.aacStream,s.aacStream.pipe(s.audioTimestampRolloverStream).pipe(s.adtsStream),s.aacStream.pipe(s.timedMetadataTimestampRolloverStream).pipe(s.metadataStream).pipe(s.coalesceStream),s.metadataStream.on("timestamp",(function(e){s.aacStream.setTimestamp(e.timeStamp)})),s.aacStream.on("data",(function(r){"timed-metadata"!==r.type&&"audio"!==r.type||s.audioSegmentStream||(i=i||{timelineStartInfo:{baseMediaDecodeTime:n.baseMediaDecodeTime},codec:"adts",type:"audio"},s.coalesceStream.numberOfTracks++,s.audioSegmentStream=new yt(i,e),s.audioSegmentStream.on("log",n.getLogTrigger_("audioSegmentStream")),s.audioSegmentStream.on("timingInfo",n.trigger.bind(n,"audioTimingInfo")),s.adtsStream.pipe(s.audioSegmentStream).pipe(s.coalesceStream),n.trigger("trackinfo",{hasAudio:!!i,hasVideo:!!t}))})),s.coalesceStream.on("data",this.trigger.bind(this,"data")),s.coalesceStream.on("done",this.trigger.bind(this,"done")),Rt(this,s)},this.setupTsPipeline=function(){var s={};this.transmuxPipeline_=s,s.type="ts",s.metadataStream=new Et.MetadataStream,s.packetStream=new Et.TransportPacketStream,s.parseStream=new Et.TransportParseStream,s.elementaryStream=new Et.ElementaryStream,s.timestampRolloverStream=new Et.TimestampRolloverStream,s.adtsStream=new Lt,s.h264Stream=new xt,s.captionStream=new Et.CaptionStream(e),s.coalesceStream=new Tt(e,s.metadataStream),s.headOfPipeline=s.packetStream,s.packetStream.pipe(s.parseStream).pipe(s.elementaryStream).pipe(s.timestampRolloverStream),s.timestampRolloverStream.pipe(s.h264Stream),s.timestampRolloverStream.pipe(s.adtsStream),s.timestampRolloverStream.pipe(s.metadataStream).pipe(s.coalesceStream),s.h264Stream.pipe(s.captionStream).pipe(s.coalesceStream),s.elementaryStream.on("data",(function(r){var a;if("metadata"===r.type){for(a=r.tracks.length;a--;)t||"video"!==r.tracks[a].type?i||"audio"!==r.tracks[a].type||((i=r.tracks[a]).timelineStartInfo.baseMediaDecodeTime=n.baseMediaDecodeTime):(t=r.tracks[a]).timelineStartInfo.baseMediaDecodeTime=n.baseMediaDecodeTime;t&&!s.videoSegmentStream&&(s.coalesceStream.numberOfTracks++,s.videoSegmentStream=new gt(t,e),s.videoSegmentStream.on("log",n.getLogTrigger_("videoSegmentStream")),s.videoSegmentStream.on("timelineStartInfo",(function(t){i&&!e.keepOriginalTimestamps&&(i.timelineStartInfo=t,s.audioSegmentStream.setEarliestDts(t.dts-n.baseMediaDecodeTime))})),s.videoSegmentStream.on("processedGopsInfo",n.trigger.bind(n,"gopInfo")),s.videoSegmentStream.on("segmentTimingInfo",n.trigger.bind(n,"videoSegmentTimingInfo")),s.videoSegmentStream.on("baseMediaDecodeTime",(function(e){i&&s.audioSegmentStream.setVideoBaseMediaDecodeTime(e)})),s.videoSegmentStream.on("timingInfo",n.trigger.bind(n,"videoTimingInfo")),s.h264Stream.pipe(s.videoSegmentStream).pipe(s.coalesceStream)),i&&!s.audioSegmentStream&&(s.coalesceStream.numberOfTracks++,s.audioSegmentStream=new yt(i,e),s.audioSegmentStream.on("log",n.getLogTrigger_("audioSegmentStream")),s.audioSegmentStream.on("timingInfo",n.trigger.bind(n,"audioTimingInfo")),s.audioSegmentStream.on("segmentTimingInfo",n.trigger.bind(n,"audioSegmentTimingInfo")),s.adtsStream.pipe(s.audioSegmentStream).pipe(s.coalesceStream)),n.trigger("trackinfo",{hasAudio:!!i,hasVideo:!!t})}})),s.coalesceStream.on("data",this.trigger.bind(this,"data")),s.coalesceStream.on("id3Frame",(function(e){e.dispatchType=s.metadataStream.dispatchType,n.trigger("id3Frame",e)})),s.coalesceStream.on("caption",this.trigger.bind(this,"caption")),s.coalesceStream.on("done",this.trigger.bind(this,"done")),Rt(this,s)},this.setBaseMediaDecodeTime=function(n){var s=this.transmuxPipeline_;e.keepOriginalTimestamps||(this.baseMediaDecodeTime=n),i&&(i.timelineStartInfo.dts=void 0,i.timelineStartInfo.pts=void 0,It.clearDtsInfo(i),s.audioTimestampRolloverStream&&s.audioTimestampRolloverStream.discontinuity()),t&&(s.videoSegmentStream&&(s.videoSegmentStream.gopCache_=[]),t.timelineStartInfo.dts=void 0,t.timelineStartInfo.pts=void 0,It.clearDtsInfo(t),s.captionStream.reset()),s.timestampRolloverStream&&s.timestampRolloverStream.discontinuity()},this.setAudioAppendStart=function(e){i&&this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(e)},this.setRemux=function(t){var i=this.transmuxPipeline_;e.remux=t,i&&i.coalesceStream&&i.coalesceStream.setRemux(t)},this.alignGopsWith=function(e){t&&this.transmuxPipeline_.videoSegmentStream&&this.transmuxPipeline_.videoSegmentStream.alignGopsWith(e)},this.getLogTrigger_=function(e){var t=this;return function(i){i.stream=e,t.trigger("log",i)}},this.push=function(e){if(s){var t=kt(e);t&&"aac"!==this.transmuxPipeline_.type?this.setupAacPipeline():t||"ts"===this.transmuxPipeline_.type||this.setupTsPipeline(),s=!1}this.transmuxPipeline_.headOfPipeline.push(e)},this.flush=function(){s=!0,this.transmuxPipeline_.headOfPipeline.flush()},this.endTimeline=function(){this.transmuxPipeline_.headOfPipeline.endTimeline()},this.reset=function(){this.transmuxPipeline_.headOfPipeline&&this.transmuxPipeline_.headOfPipeline.reset()},this.resetCaptions=function(){this.transmuxPipeline_.captionStream&&this.transmuxPipeline_.captionStream.reset()}}).prototype=new bt;var Nt,Ft,$t,qt,Wt={Transmuxer:_t,VideoSegmentStream:gt,AudioSegmentStream:yt,AUDIO_PROPERTIES:Pt,VIDEO_PROPERTIES:Ut,generateSegmentTimingInfo:Bt},Gt=function(e){return e>>>0},Vt=function(e){var t="";return t+=String.fromCharCode(e[0]),t+=String.fromCharCode(e[1]),(t+=String.fromCharCode(e[2]))+String.fromCharCode(e[3])},Ht=Gt,jt=Vt,Xt=function(e,t){var i,n,s,r,a,o=[];if(!t.length)return null;for(i=0;i<e.byteLength;)n=Ht(e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]),s=jt(e.subarray(i+4,i+8)),r=n>1?i+n:e.byteLength,s===t[0]&&(1===t.length?o.push(e.subarray(i+8,r)):(a=Xt(e.subarray(i+8,r),t.slice(1))).length&&(o=o.concat(a))),i=r;return o},zt=Gt,Qt=V.getUint64,Yt=function(e){var t={version:e[0],flags:new Uint8Array(e.subarray(1,4))};return 1===t.version?t.baseMediaDecodeTime=Qt(e.subarray(4)):t.baseMediaDecodeTime=zt(e[4]<<24|e[5]<<16|e[6]<<8|e[7]),t},Kt=function(e){return{isLeading:(12&e[0])>>>2,dependsOn:3&e[0],isDependedOn:(192&e[1])>>>6,hasRedundancy:(48&e[1])>>>4,paddingValue:(14&e[1])>>>1,isNonSyncSample:1&e[1],degradationPriority:e[2]<<8|e[3]}},Jt=function(e){var t,i={version:e[0],flags:new Uint8Array(e.subarray(1,4)),samples:[]},n=new DataView(e.buffer,e.byteOffset,e.byteLength),s=1&i.flags[2],r=4&i.flags[2],a=1&i.flags[1],o=2&i.flags[1],d=4&i.flags[1],u=8&i.flags[1],l=n.getUint32(4),h=8;for(s&&(i.dataOffset=n.getInt32(h),h+=4),r&&l&&(t={flags:Kt(e.subarray(h,h+4))},h+=4,a&&(t.duration=n.getUint32(h),h+=4),o&&(t.size=n.getUint32(h),h+=4),u&&(1===i.version?t.compositionTimeOffset=n.getInt32(h):t.compositionTimeOffset=n.getUint32(h),h+=4),i.samples.push(t),l--);l--;)t={},a&&(t.duration=n.getUint32(h),h+=4),o&&(t.size=n.getUint32(h),h+=4),d&&(t.flags=Kt(e.subarray(h,h+4)),h+=4),u&&(1===i.version?t.compositionTimeOffset=n.getInt32(h):t.compositionTimeOffset=n.getUint32(h),h+=4),i.samples.push(t);return i},Zt=function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength),n={version:e[0],flags:new Uint8Array(e.subarray(1,4)),trackId:i.getUint32(4)},s=1&n.flags[2],r=2&n.flags[2],a=8&n.flags[2],o=16&n.flags[2],d=32&n.flags[2],u=65536&n.flags[0],l=131072&n.flags[0];return t=8,s&&(t+=4,n.baseDataOffset=i.getUint32(12),t+=4),r&&(n.sampleDescriptionIndex=i.getUint32(t),t+=4),a&&(n.defaultSampleDuration=i.getUint32(t),t+=4),o&&(n.defaultSampleSize=i.getUint32(t),t+=4),d&&(n.defaultSampleFlags=i.getUint32(t)),u&&(n.durationIsEmpty=!0),!s&&l&&(n.baseDataOffsetIsMoof=!0),n},ei=(Nt="undefined"!=typeof window?window:void 0!==e?e:"undefined"!=typeof self?self:{},ce.discardEmulationPreventionBytes),ti=Ae.CaptionStream,ii=Xt,ni=Yt,si=Jt,ri=Zt,ai=Nt,oi=function(e,t){for(var i=e,n=0;n<t.length;n++){var s=t[n];if(i<s.size)return s;i-=s.size}return null},di=function(){var e,t,i,n,s,r,a=!1;this.isInitialized=function(){return a},this.init=function(t){e=new ti,a=!0,r=!!t&&t.isPartial,e.on("data",(function(e){e.startTime=e.startPts/n,e.endTime=e.endPts/n,s.captions.push(e),s.captionStreams[e.stream]=!0})),e.on("log",(function(e){s.logs.push(e)}))},this.isNewInit=function(e,t){return!(e&&0===e.length||t&&"object"==typeof t&&0===Object.keys(t).length||i===e[0]&&n===t[i])},this.parse=function(e,r,a){var o;if(!this.isInitialized())return null;if(!r||!a)return null;if(this.isNewInit(r,a))i=r[0],n=a[i];else if(null===i||!n)return t.push(e),null;for(;t.length>0;){var d=t.shift();this.parse(d,r,a)}return o=function(e,t,i){if(null===t)return null;var n=function(e,t){var i=ii(e,["moof","traf"]),n=ii(e,["mdat"]),s={},r=[];return n.forEach((function(e,t){var n=i[t];r.push({mdat:e,traf:n})})),r.forEach((function(e){var i,n,r=e.mdat,a=e.traf,o=ii(a,["tfhd"]),d=ri(o[0]),u=d.trackId,l=ii(a,["tfdt"]),h=l.length>0?ni(l[0]).baseMediaDecodeTime:0,c=ii(a,["trun"]);t===u&&c.length>0&&(i=function(e,t,i){var n=t,s=i.defaultSampleDuration||0,r=i.defaultSampleSize||0,a=i.trackId,o=[];return e.forEach((function(e){var t=si(e).samples;t.forEach((function(e){void 0===e.duration&&(e.duration=s),void 0===e.size&&(e.size=r),e.trackId=a,e.dts=n,void 0===e.compositionTimeOffset&&(e.compositionTimeOffset=0),"bigint"==typeof n?(e.pts=n+ai.BigInt(e.compositionTimeOffset),n+=ai.BigInt(e.duration)):(e.pts=n+e.compositionTimeOffset,n+=e.duration)})),o=o.concat(t)})),o}(c,h,d),n=function(e,t,i){var n,s,r,a,o=new DataView(e.buffer,e.byteOffset,e.byteLength),d={logs:[],seiNals:[]};for(s=0;s+4<e.length;s+=r)if(r=o.getUint32(s),s+=4,!(r<=0))switch(31&e[s]){case 6:var u=e.subarray(s+1,s+1+r),l=oi(s,t);if(n={nalUnitType:"sei_rbsp",size:r,data:u,escapedRBSP:ei(u),trackId:i},l)n.pts=l.pts,n.dts=l.dts,a=l;else{if(!a){d.logs.push({level:"warn",message:"We've encountered a nal unit without data at "+s+" for trackId "+i+". See mux.js#223."});break}n.pts=a.pts,n.dts=a.dts}d.seiNals.push(n)}return d}(r,i,u),s[u]||(s[u]={seiNals:[],logs:[]}),s[u].seiNals=s[u].seiNals.concat(n.seiNals),s[u].logs=s[u].logs.concat(n.logs))})),s}(e,t)[t]||{};return{seiNals:n.seiNals,logs:n.logs,timescale:i}}(e,i,n),o&&o.logs&&(s.logs=s.logs.concat(o.logs)),null!==o&&o.seiNals?(this.pushNals(o.seiNals),this.flushStream(),s):s.logs.length?{logs:s.logs,captions:[],captionStreams:[]}:null},this.pushNals=function(t){if(!this.isInitialized()||!t||0===t.length)return null;t.forEach((function(t){e.push(t)}))},this.flushStream=function(){if(!this.isInitialized())return null;r?e.partialFlush():e.flush()},this.clearParsedCaptions=function(){s.captions=[],s.captionStreams={},s.logs=[]},this.resetCaptionStream=function(){if(!this.isInitialized())return null;e.reset()},this.clearAllCaptions=function(){this.clearParsedCaptions(),this.resetCaptionStream()},this.reset=function(){t=[],i=null,n=null,s?this.clearParsedCaptions():s={captions:[],captionStreams:{},logs:[]},this.resetCaptionStream()},this.reset()},ui=Gt,li=function(e){return("00"+e.toString(16)).slice(-2)},hi=Xt,ci=Vt,pi=V.getUint64,mi=Nt;Ft=function(e,t){var i=hi(t,["moof","traf"]).reduce((function(t,i){var n,s=hi(i,["tfhd"])[0],r=ui(s[4]<<24|s[5]<<16|s[6]<<8|s[7]),a=e[r]||9e4,o=hi(i,["tfdt"])[0],d=new DataView(o.buffer,o.byteOffset,o.byteLength);let u;return"bigint"==typeof(n=1===o[0]?pi(o.subarray(4,12)):d.getUint32(4))?u=n/mi.BigInt(a):"number"!=typeof n||isNaN(n)||(u=n/a),u<Number.MAX_SAFE_INTEGER&&(u=Number(u)),u<t&&(t=u),t}),1/0);return"bigint"==typeof i||isFinite(i)?i:0},qt=function(e){var t=0===e[0]?12:20;return ui(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])},$t=function(e){var t=hi(e,["moov","trak"]),i=[];return t.forEach((function(e){var t,n,s={},r=hi(e,["tkhd"])[0];r&&(n=(t=new DataView(r.buffer,r.byteOffset,r.byteLength)).getUint8(0),s.id=0===n?t.getUint32(12):t.getUint32(20));var a=hi(e,["mdia","hdlr"])[0];if(a){var o=ci(a.subarray(8,12));s.type="vide"===o?"video":"soun"===o?"audio":o}var d=hi(e,["mdia","minf","stbl","stsd"])[0];if(d){var u=d.subarray(8);s.codec=ci(u.subarray(4,8));var l,h=hi(u,[s.codec])[0];h&&(/^[asm]vc[1-9]$/i.test(s.codec)?(l=h.subarray(78),"avcC"===ci(l.subarray(4,8))&&l.length>11?(s.codec+=".",s.codec+=li(l[9]),s.codec+=li(l[10]),s.codec+=li(l[11])):s.codec="avc1.4d400d"):/^mp4[a,v]$/i.test(s.codec)?(l=h.subarray(28),"esds"===ci(l.subarray(4,8))&&l.length>20&&0!==l[19]?(s.codec+="."+li(l[19]),s.codec+="."+li(l[20]>>>2&63).replace(/^0/,"")):s.codec="mp4a.40.2"):s.codec=s.codec.toLowerCase())}var c=hi(e,["mdia","mdhd"])[0];c&&(s.timescale=qt(c)),i.push(s)})),i};var fi=Ft,gi=$t,yi=Le,_i=function(e){var t=31&e[1];return(t<<=8)|e[2]},Ti=function(e){return!!(64&e[1])},bi=function(e){var t=0;return(48&e[3])>>>4>1&&(t+=e[4]+1),t},Si=function(e){switch(e){case 5:return"slice_layer_without_partitioning_rbsp_idr";case 6:return"sei_rbsp";case 7:return"seq_parameter_set_rbsp";case 8:return"pic_parameter_set_rbsp";case 9:return"access_unit_delimiter_rbsp";default:return null}},vi={parseType:function(e,t){var i=_i(e);return 0===i?"pat":i===t?"pmt":t?"pes":null},parsePat:function(e){var t=Ti(e),i=4+bi(e);return t&&(i+=e[i]+1),(31&e[i+10])<<8|e[i+11]},parsePmt:function(e){var t={},i=Ti(e),n=4+bi(e);if(i&&(n+=e[n]+1),1&e[n+5]){var s;s=3+((15&e[n+1])<<8|e[n+2])-4;for(var r=12+((15&e[n+10])<<8|e[n+11]);r<s;){var a=n+r;t[(31&e[a+1])<<8|e[a+2]]=e[a],r+=5+((15&e[a+3])<<8|e[a+4])}return t}},parsePayloadUnitStartIndicator:Ti,parsePesType:function(e,t){switch(t[_i(e)]){case yi.H264_STREAM_TYPE:return"video";case yi.ADTS_STREAM_TYPE:return"audio";case yi.METADATA_STREAM_TYPE:return"timed-metadata";default:return null}},parsePesTime:function(e){if(!Ti(e))return null;var t=4+bi(e);if(t>=e.byteLength)return null;var i,n=null;return 192&(i=e[t+7])&&((n={}).pts=(14&e[t+9])<<27|(255&e[t+10])<<20|(254&e[t+11])<<12|(255&e[t+12])<<5|(254&e[t+13])>>>3,n.pts*=4,n.pts+=(6&e[t+13])>>>1,n.dts=n.pts,64&i&&(n.dts=(14&e[t+14])<<27|(255&e[t+15])<<20|(254&e[t+16])<<12|(255&e[t+17])<<5|(254&e[t+18])>>>3,n.dts*=4,n.dts+=(6&e[t+18])>>>1)),n},videoPacketContainsKeyFrame:function(e){for(var t=4+bi(e),i=e.subarray(t),n=0,s=0,r=!1;s<i.byteLength-3;s++)if(1===i[s+2]){n=s+5;break}for(;n<i.byteLength;)switch(i[n]){case 0:if(0!==i[n-1]){n+=2;break}if(0!==i[n-2]){n++;break}s+3!==n-2&&"slice_layer_without_partitioning_rbsp_idr"===Si(31&i[s+3])&&(r=!0);do{n++}while(1!==i[n]&&n<i.length);s=n-2,n+=3;break;case 1:if(0!==i[n-1]||0!==i[n-2]){n+=3;break}"slice_layer_without_partitioning_rbsp_idr"===Si(31&i[s+3])&&(r=!0),s=n-2,n+=3;break;default:n+=3}return i=i.subarray(s),n-=s,s=0,i&&i.byteLength>3&&"slice_layer_without_partitioning_rbsp_idr"===Si(31&i[s+3])&&(r=!0),r}},wi=Le,Ii=Ue.handleRollover,Ei={};Ei.ts=vi,Ei.aac=mt;var Ai=oe.ONE_SECOND_IN_TS,Li=188,xi=71,Di=function(e,t,i){for(var n,s,r,a,o=0,d=Li,u=!1;d<=e.byteLength;)if(e[o]!==xi||e[d]!==xi&&d!==e.byteLength)o++,d++;else{if(n=e.subarray(o,d),"pes"===Ei.ts.parseType(n,t.pid)&&(s=Ei.ts.parsePesType(n,t.table),r=Ei.ts.parsePayloadUnitStartIndicator(n),"audio"===s&&r&&(a=Ei.ts.parsePesTime(n))&&(a.type="audio",i.audio.push(a),u=!0)),u)break;o+=Li,d+=Li}for(o=(d=e.byteLength)-Li,u=!1;o>=0;)if(e[o]!==xi||e[d]!==xi&&d!==e.byteLength)o--,d--;else{if(n=e.subarray(o,d),"pes"===Ei.ts.parseType(n,t.pid)&&(s=Ei.ts.parsePesType(n,t.table),r=Ei.ts.parsePayloadUnitStartIndicator(n),"audio"===s&&r&&(a=Ei.ts.parsePesTime(n))&&(a.type="audio",i.audio.push(a),u=!0)),u)break;o-=Li,d-=Li}},ki=function(e,t,i){for(var n,s,r,a,o,d,u,l=0,h=Li,c=!1,p={data:[],size:0};h<e.byteLength;)if(e[l]!==xi||e[h]!==xi)l++,h++;else{if(n=e.subarray(l,h),"pes"===Ei.ts.parseType(n,t.pid)&&(s=Ei.ts.parsePesType(n,t.table),r=Ei.ts.parsePayloadUnitStartIndicator(n),"video"===s&&(r&&!c&&(a=Ei.ts.parsePesTime(n))&&(a.type="video",i.video.push(a),c=!0),!i.firstKeyFrame))){if(r&&0!==p.size){for(o=new Uint8Array(p.size),d=0;p.data.length;)u=p.data.shift(),o.set(u,d),d+=u.byteLength;if(Ei.ts.videoPacketContainsKeyFrame(o)){var m=Ei.ts.parsePesTime(o);m?(i.firstKeyFrame=m,i.firstKeyFrame.type="video"):console.warn("Failed to extract PTS/DTS from PES at first keyframe. This could be an unusual TS segment, or else mux.js did not parse your TS segment correctly. If you know your TS segments do contain PTS/DTS on keyframes please file a bug report! You can try ffprobe to double check for yourself.")}p.size=0}p.data.push(n),p.size+=n.byteLength}if(c&&i.firstKeyFrame)break;l+=Li,h+=Li}for(l=(h=e.byteLength)-Li,c=!1;l>=0;)if(e[l]!==xi||e[h]!==xi)l--,h--;else{if(n=e.subarray(l,h),"pes"===Ei.ts.parseType(n,t.pid)&&(s=Ei.ts.parsePesType(n,t.table),r=Ei.ts.parsePayloadUnitStartIndicator(n),"video"===s&&r&&(a=Ei.ts.parsePesTime(n))&&(a.type="video",i.video.push(a),c=!0)),c)break;l-=Li,h-=Li}},Oi=function(e,t){var i;return i=Ei.aac.isLikelyAacData(e)?function(e){for(var t,i=!1,n=0,s=null,r=null,a=0,o=0;e.length-o>=3;){switch(Ei.aac.parseType(e,o)){case"timed-metadata":if(e.length-o<10){i=!0;break}if((a=Ei.aac.parseId3TagSize(e,o))>e.length){i=!0;break}null===r&&(t=e.subarray(o,o+a),r=Ei.aac.parseAacTimestamp(t)),o+=a;break;case"audio":if(e.length-o<7){i=!0;break}if((a=Ei.aac.parseAdtsSize(e,o))>e.length){i=!0;break}null===s&&(t=e.subarray(o,o+a),s=Ei.aac.parseSampleRate(t)),n++,o+=a;break;default:o++}if(i)return null}if(null===s||null===r)return null;var d=Ai/s;return{audio:[{type:"audio",dts:r,pts:r},{type:"audio",dts:r+1024*n*d,pts:r+1024*n*d}]}}(e):function(e){var t={pid:null,table:null},i={};for(var n in function(e,t){for(var i,n=0,s=Li;s<e.byteLength;)if(e[n]!==xi||e[s]!==xi)n++,s++;else{switch(i=e.subarray(n,s),Ei.ts.parseType(i,t.pid)){case"pat":t.pid=Ei.ts.parsePat(i);break;case"pmt":var r=Ei.ts.parsePmt(i);t.table=t.table||{},Object.keys(r).forEach((function(e){t.table[e]=r[e]}))}n+=Li,s+=Li}}(e,t),t.table)if(t.table.hasOwnProperty(n))switch(t.table[n]){case wi.H264_STREAM_TYPE:i.video=[],ki(e,t,i),0===i.video.length&&delete i.video;break;case wi.ADTS_STREAM_TYPE:i.audio=[],Di(e,t,i),0===i.audio.length&&delete i.audio}return i}(e),i&&(i.audio||i.video)?(function(e,t){if(e.audio&&e.audio.length){var i=t;(void 0===i||isNaN(i))&&(i=e.audio[0].dts),e.audio.forEach((function(e){e.dts=Ii(e.dts,i),e.pts=Ii(e.pts,i),e.dtsTime=e.dts/Ai,e.ptsTime=e.pts/Ai}))}if(e.video&&e.video.length){var n=t;if((void 0===n||isNaN(n))&&(n=e.video[0].dts),e.video.forEach((function(e){e.dts=Ii(e.dts,n),e.pts=Ii(e.pts,n),e.dtsTime=e.dts/Ai,e.ptsTime=e.pts/Ai})),e.firstKeyFrame){var s=e.firstKeyFrame;s.dts=Ii(s.dts,n),s.pts=Ii(s.pts,n),s.dtsTime=s.dts/Ai,s.ptsTime=s.pts/Ai}}}(i,t),i):null};class Pi{constructor(e,t){this.options=t||{},this.self=e,this.init()}init(){this.transmuxer&&this.transmuxer.dispose(),this.transmuxer=new Wt.Transmuxer(this.options),function(e,t){t.on("data",(function(t){const i=t.initSegment;t.initSegment={data:i.buffer,byteOffset:i.byteOffset,byteLength:i.byteLength};const n=t.data;t.data=n.buffer,e.postMessage({action:"data",segment:t,byteOffset:n.byteOffset,byteLength:n.byteLength},[t.data])})),t.on("done",(function(t){e.postMessage({action:"done"})})),t.on("gopInfo",(function(t){e.postMessage({action:"gopInfo",gopInfo:t})})),t.on("videoSegmentTimingInfo",(function(t){const i={start:{decode:oe.videoTsToSeconds(t.start.dts),presentation:oe.videoTsToSeconds(t.start.pts)},end:{decode:oe.videoTsToSeconds(t.end.dts),presentation:oe.videoTsToSeconds(t.end.pts)},baseMediaDecodeTime:oe.videoTsToSeconds(t.baseMediaDecodeTime)};t.prependedContentDuration&&(i.prependedContentDuration=oe.videoTsToSeconds(t.prependedContentDuration)),e.postMessage({action:"videoSegmentTimingInfo",videoSegmentTimingInfo:i})})),t.on("audioSegmentTimingInfo",(function(t){const i={start:{decode:oe.videoTsToSeconds(t.start.dts),presentation:oe.videoTsToSeconds(t.start.pts)},end:{decode:oe.videoTsToSeconds(t.end.dts),presentation:oe.videoTsToSeconds(t.end.pts)},baseMediaDecodeTime:oe.videoTsToSeconds(t.baseMediaDecodeTime)};t.prependedContentDuration&&(i.prependedContentDuration=oe.videoTsToSeconds(t.prependedContentDuration)),e.postMessage({action:"audioSegmentTimingInfo",audioSegmentTimingInfo:i})})),t.on("id3Frame",(function(t){e.postMessage({action:"id3Frame",id3Frame:t})})),t.on("caption",(function(t){e.postMessage({action:"caption",caption:t})})),t.on("trackinfo",(function(t){e.postMessage({action:"trackinfo",trackInfo:t})})),t.on("audioTimingInfo",(function(t){e.postMessage({action:"audioTimingInfo",audioTimingInfo:{start:oe.videoTsToSeconds(t.start),end:oe.videoTsToSeconds(t.end)}})})),t.on("videoTimingInfo",(function(t){e.postMessage({action:"videoTimingInfo",videoTimingInfo:{start:oe.videoTsToSeconds(t.start),end:oe.videoTsToSeconds(t.end)}})})),t.on("log",(function(t){e.postMessage({action:"log",log:t})}))}(this.self,this.transmuxer)}pushMp4Captions(e){this.captionParser||(this.captionParser=new di,this.captionParser.init());const t=new Uint8Array(e.data,e.byteOffset,e.byteLength),i=this.captionParser.parse(t,e.trackIds,e.timescales);this.self.postMessage({action:"mp4Captions",captions:i&&i.captions||[],logs:i&&i.logs||[],data:t.buffer},[t.buffer])}probeMp4StartTime({timescales:e,data:t}){const i=fi(e,t);this.self.postMessage({action:"probeMp4StartTime",startTime:i,data:t},[t.buffer])}probeMp4Tracks({data:e}){const t=gi(e);this.self.postMessage({action:"probeMp4Tracks",tracks:t,data:e},[e.buffer])}probeTs({data:e,baseStartTime:t}){const i="number"!=typeof t||isNaN(t)?void 0:t*oe.ONE_SECOND_IN_TS,n=Oi(e,i);let s=null;n&&(s={hasVideo:n.video&&2===n.video.length||!1,hasAudio:n.audio&&2===n.audio.length||!1},s.hasVideo&&(s.videoStart=n.video[0].ptsTime),s.hasAudio&&(s.audioStart=n.audio[0].ptsTime)),this.self.postMessage({action:"probeTs",result:s,data:e},[e.buffer])}clearAllMp4Captions(){this.captionParser&&this.captionParser.clearAllCaptions()}clearParsedMp4Captions(){this.captionParser&&this.captionParser.clearParsedCaptions()}push(e){const t=new Uint8Array(e.data,e.byteOffset,e.byteLength);this.transmuxer.push(t)}reset(){this.transmuxer.reset()}setTimestampOffset(e){const t=e.timestampOffset||0;this.transmuxer.setBaseMediaDecodeTime(Math.round(oe.secondsToVideoTs(t)))}setAudioAppendStart(e){this.transmuxer.setAudioAppendStart(Math.ceil(oe.secondsToVideoTs(e.appendStart)))}setRemux(e){this.transmuxer.setRemux(e.remux)}flush(e){this.transmuxer.flush(),self.postMessage({action:"done",type:"transmuxed"})}endTimeline(){this.transmuxer.endTimeline(),self.postMessage({action:"endedtimeline",type:"transmuxed"})}alignGopsWith(e){this.transmuxer.alignGopsWith(e.gopsToAlignWith.slice())}}self.onmessage=function(e){"init"===e.data.action&&e.data.options?this.messageHandlers=new Pi(self,e.data.options):(this.messageHandlers||(this.messageHandlers=new Pi(self)),e.data&&e.data.action&&"init"!==e.data.action&&this.messageHandlers[e.data.action]&&this.messageHandlers[e.data.action](e.data))}})));var mi=li(pi);const fi=e=>{const{transmuxer:t,bytes:i,audioAppendStart:n,gopsToAlignWith:s,remux:r,onData:a,onTrackInfo:o,onAudioTimingInfo:d,onVideoTimingInfo:u,onVideoSegmentTimingInfo:l,onAudioSegmentTimingInfo:h,onId3:c,onCaptions:p,onDone:m,onEndedTimeline:f,onTransmuxerLog:g,isEndOfTimeline:y}=e,_={buffer:[]};let T=y;if(t.onmessage=i=>{t.currentTransmux===e&&("data"===i.data.action&&((e,t,i)=>{const{type:n,initSegment:s,captions:r,captionStreams:a,metadata:o,videoFrameDtsTime:d,videoFramePtsTime:u}=e.data.segment;t.buffer.push({captions:r,captionStreams:a,metadata:o});const l=e.data.segment.boxes||{data:e.data.segment.data},h={type:n,data:new Uint8Array(l.data,l.data.byteOffset,l.data.byteLength),initSegment:new Uint8Array(s.data,s.byteOffset,s.byteLength)};void 0!==d&&(h.videoFrameDtsTime=d),void 0!==u&&(h.videoFramePtsTime=u),i(h)})(i,_,a),"trackinfo"===i.data.action&&o(i.data.trackInfo),"gopInfo"===i.data.action&&((e,t)=>{t.gopInfo=e.data.gopInfo})(i,_),"audioTimingInfo"===i.data.action&&d(i.data.audioTimingInfo),"videoTimingInfo"===i.data.action&&u(i.data.videoTimingInfo),"videoSegmentTimingInfo"===i.data.action&&l(i.data.videoSegmentTimingInfo),"audioSegmentTimingInfo"===i.data.action&&h(i.data.audioSegmentTimingInfo),"id3Frame"===i.data.action&&c([i.data.id3Frame],i.data.id3Frame.dispatchType),"caption"===i.data.action&&p(i.data.caption),"endedtimeline"===i.data.action&&(T=!1,f()),"log"===i.data.action&&g(i.data.log),"transmuxed"===i.data.type&&(T||(t.onmessage=null,(({transmuxedData:e,callback:t})=>{e.buffer=[],t(e)})({transmuxedData:_,callback:m}),gi(t))))},n&&t.postMessage({action:"setAudioAppendStart",appendStart:n}),Array.isArray(s)&&t.postMessage({action:"alignGopsWith",gopsToAlignWith:s}),void 0!==r&&t.postMessage({action:"setRemux",remux:r}),i.byteLength){const e=i instanceof ArrayBuffer?i:i.buffer,n=i instanceof ArrayBuffer?0:i.byteOffset;t.postMessage({action:"push",data:e,byteOffset:n,byteLength:i.byteLength},[e])}y&&t.postMessage({action:"endTimeline"}),t.postMessage({action:"flush"})},gi=e=>{e.currentTransmux=null,e.transmuxQueue.length&&(e.currentTransmux=e.transmuxQueue.shift(),"function"==typeof e.currentTransmux?e.currentTransmux():fi(e.currentTransmux))},yi=(e,t)=>{e.postMessage({action:t}),gi(e)};var _i=e=>{((e,t)=>{if(!t.currentTransmux)return t.currentTransmux=e,void yi(t,e);t.transmuxQueue.push(yi.bind(null,t,e))})("reset",e)};const Ti=function(e){const t=e.transmuxer,i=e.endAction||e.action,n=e.callback,s=c({},e,{endAction:null,transmuxer:null,callback:null}),r=s=>{s.data.action===i&&(t.removeEventListener("message",r),s.data.data&&(s.data.data=new Uint8Array(s.data.data,e.byteOffset||0,e.byteLength||s.data.data.byteLength),e.data&&(e.data=s.data.data)),n(s.data))};if(t.addEventListener("message",r),e.data){const i=e.data instanceof ArrayBuffer;s.byteOffset=i?0:e.data.byteOffset,s.byteLength=e.data.byteLength;const n=[i?e.data:e.data.buffer];t.postMessage(s,n)}else t.postMessage(s)},bi=-101,Si=-102,vi=e=>{e.forEach((e=>{e.abort()}))},wi=(e,t)=>t.timedout?{status:t.status,message:"HLS request timed-out at URL: "+t.uri,code:bi,xhr:t}:t.aborted?{status:t.status,message:"HLS request aborted at URL: "+t.uri,code:Si,xhr:t}:e?{status:t.status,message:"HLS request errored at URL: "+t.uri,code:2,xhr:t}:"arraybuffer"===t.responseType&&0===t.response.byteLength?{status:t.status,message:"Empty HLS response at URL: "+t.uri,code:2,xhr:t}:null,Ii=(e,t,i)=>(n,s)=>{const r=s.response,a=wi(n,s);if(a)return i(a,e);if(16!==r.byteLength)return i({status:s.status,message:"Invalid HLS key at URL: "+s.uri,code:2,xhr:s},e);const o=new DataView(r),d=new Uint32Array([o.getUint32(0),o.getUint32(4),o.getUint32(8),o.getUint32(12)]);for(let e=0;e<t.length;e++)t[e].bytes=d;return i(null,e)},Ei=(e,t)=>{const i=ti(e.map.bytes);if("mp4"!==i){const n=e.map.resolvedUri||e.map.uri;return t({internal:!0,message:`Found unsupported ${i||"unknown"} container for initialization segment at URL: ${n}`,code:2})}Ti({action:"probeMp4Tracks",data:e.map.bytes,transmuxer:e.transmuxer,callback:({tracks:i,data:n})=>(e.map.bytes=n,i.forEach((function(t){e.map.tracks=e.map.tracks||{},e.map.tracks[t.type]||(e.map.tracks[t.type]=t,"number"==typeof t.id&&t.timescale&&(e.map.timescales=e.map.timescales||{},e.map.timescales[t.id]=t.timescale))})),t(null))})},Ai=({segment:e,bytes:t,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l,doneFn:h,onTransmuxerLog:c})=>{const p=e.map&&e.map.tracks||{},m=Boolean(p.audio&&p.video);let f=n.bind(null,e,"audio","start");const g=n.bind(null,e,"audio","end");let y=n.bind(null,e,"video","start");const _=n.bind(null,e,"video","end");Ti({action:"probeTs",transmuxer:e.transmuxer,data:t,baseStartTime:e.baseStartTime,callback:n=>{e.bytes=t=n.data;const p=n.result;p&&(i(e,{hasAudio:p.hasAudio,hasVideo:p.hasVideo,isMuxed:m}),i=null,p.hasAudio&&!m&&f(p.audioStart),p.hasVideo&&y(p.videoStart),f=null,y=null),(e=>{if(!e.transmuxer.currentTransmux)return e.transmuxer.currentTransmux=e,void fi(e);e.transmuxer.transmuxQueue.push(e)})({bytes:t,transmuxer:e.transmuxer,audioAppendStart:e.audioAppendStart,gopsToAlignWith:e.gopsToAlignWith,remux:m,onData:t=>{t.type="combined"===t.type?"video":t.type,l(e,t)},onTrackInfo:t=>{i&&(m&&(t.isMuxed=!0),i(e,t))},onAudioTimingInfo:e=>{f&&void 0!==e.start&&(f(e.start),f=null),g&&void 0!==e.end&&g(e.end)},onVideoTimingInfo:e=>{y&&void 0!==e.start&&(y(e.start),y=null),_&&void 0!==e.end&&_(e.end)},onVideoSegmentTimingInfo:e=>{s(e)},onAudioSegmentTimingInfo:e=>{r(e)},onId3:(t,i)=>{a(e,t,i)},onCaptions:t=>{o(e,[t])},isEndOfTimeline:d,onEndedTimeline:()=>{u()},onTransmuxerLog:c,onDone:t=>{h&&(t.type="combined"===t.type?"video":t.type,h(null,e,t))}})}})},Li=({segment:e,bytes:t,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l,doneFn:h,onTransmuxerLog:c})=>{let p=new Uint8Array(t);if(function(e){return Ft(e,["moof"]).length>0}(p)){e.isFmp4=!0;const{tracks:s}=e.map,r={isFmp4:!0,hasVideo:!!s.video,hasAudio:!!s.audio};s.audio&&s.audio.codec&&"enca"!==s.audio.codec&&(r.audioCodec=s.audio.codec),s.video&&s.video.codec&&"encv"!==s.video.codec&&(r.videoCodec=s.video.codec),s.video&&s.audio&&(r.isMuxed=!0),i(e,r);const a=t=>{l(e,{data:p,type:r.hasAudio&&!r.isMuxed?"audio":"video"}),t&&t.length&&o(e,t),h(null,e,{})};Ti({action:"probeMp4StartTime",timescales:e.map.timescales,data:p,transmuxer:e.transmuxer,callback:({data:i,startTime:o})=>{t=i.buffer,e.bytes=p=i,r.hasAudio&&!r.isMuxed&&n(e,"audio","start",o),r.hasVideo&&n(e,"video","start",o),s.video&&i.byteLength&&e.transmuxer?Ti({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:e.transmuxer,data:p,timescales:e.map.timescales,trackIds:[s.video.id],callback:i=>{t=i.data.buffer,e.bytes=p=i.data,i.logs.forEach((function(e){c(U(e,{stream:"mp4CaptionParser"}))})),a(i.captions)}}):a()}})}else if(e.transmuxer){if(void 0===e.container&&(e.container=ti(p)),"ts"!==e.container&&"aac"!==e.container)return i(e,{hasAudio:!1,hasVideo:!1}),void h(null,e,{});Ai({segment:e,bytes:t,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l,doneFn:h,onTransmuxerLog:c})}else h(null,e,{})},xi=function({id:e,key:t,encryptedBytes:i,decryptionWorker:n},s){const r=t=>{if(t.data.source===e){n.removeEventListener("message",r);const e=t.data.decrypted;s(new Uint8Array(e.bytes,e.byteOffset,e.byteLength))}};let a;n.addEventListener("message",r),a=t.bytes.slice?t.bytes.slice():new Uint32Array(Array.prototype.slice.call(t.bytes)),n.postMessage($e({source:e,encrypted:i,key:a,iv:t.iv}),[i.buffer,a.buffer])},Di=({xhr:e,xhrOptions:t,decryptionWorker:i,segment:n,abortFn:s,progressFn:r,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:d,audioSegmentTimingInfoFn:u,id3Fn:l,captionsFn:h,isEndOfTimeline:c,endedTimelineFn:p,dataFn:m,doneFn:f,onTransmuxerLog:g})=>{const y=[],_=(({activeXhrs:e,decryptionWorker:t,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l,doneFn:h,onTransmuxerLog:c})=>{let p=0,m=!1;return(f,g)=>{if(!m){if(f)return m=!0,vi(e),h(f,g);if(p+=1,p===e.length){const p=function(){if(g.encryptedBytes)return(({decryptionWorker:e,segment:t,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l,doneFn:h,onTransmuxerLog:c})=>{xi({id:t.requestId,key:t.key,encryptedBytes:t.encryptedBytes,decryptionWorker:e},(e=>{t.bytes=e,Li({segment:t,bytes:t.bytes,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l,doneFn:h,onTransmuxerLog:c})}))})({decryptionWorker:t,segment:g,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l,doneFn:h,onTransmuxerLog:c});Li({segment:g,bytes:g.bytes,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l,doneFn:h,onTransmuxerLog:c})};if(g.endOfAllRequests=Date.now(),g.map&&g.map.encryptedBytes&&!g.map.bytes)return xi({decryptionWorker:t,id:g.requestId+"-init",encryptedBytes:g.map.encryptedBytes,key:g.map.key},(t=>{g.map.bytes=t,Ei(g,(t=>{if(t)return vi(e),h(t,g);p()}))}));p()}}}})({activeXhrs:y,decryptionWorker:i,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:d,audioSegmentTimingInfoFn:u,id3Fn:l,captionsFn:h,isEndOfTimeline:c,endedTimelineFn:p,dataFn:m,doneFn:f,onTransmuxerLog:g});if(n.key&&!n.key.bytes){const i=[n.key];n.map&&!n.map.bytes&&n.map.key&&n.map.key.resolvedUri===n.key.resolvedUri&&i.push(n.map.key);const s=e(U(t,{uri:n.key.resolvedUri,responseType:"arraybuffer"}),Ii(n,i,_));y.push(s)}if(n.map&&!n.map.bytes){if(n.map.key&&(!n.key||n.key.resolvedUri!==n.map.key.resolvedUri)){const i=e(U(t,{uri:n.map.key.resolvedUri,responseType:"arraybuffer"}),Ii(n,[n.map.key],_));y.push(i)}const i=U(t,{uri:n.map.resolvedUri,responseType:"arraybuffer",headers:Ie(n.map)}),s=(({segment:e,finishProcessingFn:t})=>(i,n)=>{const s=wi(i,n);if(s)return t(s,e);const r=new Uint8Array(n.response);if(e.map.key)return e.map.encryptedBytes=r,t(null,e);e.map.bytes=r,Ei(e,(function(i){if(i)return i.xhr=n,i.status=n.status,t(i,e);t(null,e)}))})({segment:n,finishProcessingFn:_}),r=e(i,s);y.push(r)}const T=U(t,{uri:n.part&&n.part.resolvedUri||n.resolvedUri,responseType:"arraybuffer",headers:Ie(n)}),b=e(T,(({segment:e,finishProcessingFn:t,responseType:i})=>(n,s)=>{const r=wi(n,s);if(r)return t(r,e);const a="arraybuffer"!==i&&s.responseText?(e=>{const t=new Uint8Array(new ArrayBuffer(e.length));for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t.buffer})(s.responseText.substring(e.lastReachedChar||0)):s.response;return e.stats=(e=>({bandwidth:e.bandwidth,bytesReceived:e.bytesReceived||0,roundTripTime:e.roundTripTime||0}))(s),e.key?e.encryptedBytes=new Uint8Array(a):e.bytes=new Uint8Array(a),t(null,e)})({segment:n,finishProcessingFn:_,responseType:T.responseType}));b.addEventListener("progress",(({segment:e,progressFn:t,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:r,id3Fn:a,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l})=>i=>{if(!i.target.aborted)return e.stats=U(e.stats,(e=>{const t=e.target,i={bandwidth:1/0,bytesReceived:0,roundTripTime:Date.now()-t.requestTime||0};return i.bytesReceived=e.loaded,i.bandwidth=Math.floor(i.bytesReceived/i.roundTripTime*8*1e3),i})(i)),!e.stats.firstBytesReceivedAt&&e.stats.bytesReceived&&(e.stats.firstBytesReceivedAt=Date.now()),t(i,e)})({segment:n,progressFn:r,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:d,audioSegmentTimingInfoFn:u,id3Fn:l,captionsFn:h,isEndOfTimeline:c,endedTimelineFn:p,dataFn:m})),y.push(b);const S={};return y.forEach((e=>{e.addEventListener("loadend",(({loadendState:e,abortFn:t})=>i=>{i.target.aborted&&t&&!e.calledAbortFn&&(t(),e.calledAbortFn=!0)})({loadendState:S,abortFn:s}))})),()=>vi(y)},ki=h("CodecUtils"),Oi=(e,t)=>{const i=t.attributes||{};return e&&e.mediaGroups&&e.mediaGroups.AUDIO&&i.AUDIO&&e.mediaGroups.AUDIO[i.AUDIO]},Pi=function(e){const t={};return e.forEach((({mediaType:e,type:i,details:n})=>{t[e]=t[e]||[],t[e].push(A(`${i}${n}`))})),Object.keys(t).forEach((function(e){if(t[e].length>1)return ki(`multiple ${e} codecs found as attributes: ${t[e].join(", ")}. Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.`),void(t[e]=null);t[e]=t[e][0]})),t},Ui=function(e){let t=0;return e.audio&&t++,e.video&&t++,t},Ci=function(e,t){const i=t.attributes||{},n=Pi(function(e){const t=e.attributes||{};if(t.CODECS)return L(t.CODECS)}(t)||[]);if(Oi(e,t)&&!n.audio&&!((e,t)=>{if(!Oi(e,t))return!0;const i=t.attributes||{},n=e.mediaGroups.AUDIO[i.AUDIO];for(const e in n)if(!n[e].uri&&!n[e].playlists)return!0;return!1})(e,t)){const t=Pi(function(e,t){if(!e.mediaGroups.AUDIO||!t)return null;var i=e.mediaGroups.AUDIO[t];if(!i)return null;for(var n in i){var s=i[n];if(s.default&&s.playlists)return L(s.playlists[0].attributes.CODECS)}return null}(e,i.AUDIO)||[]);t.audio&&(n.audio=t.audio)}return n},Ri=h("PlaylistSelector"),Mi=function(e){if(!e||!e.playlist)return;const t=e.playlist;return JSON.stringify({id:t.id,bandwidth:e.bandwidth,width:e.width,height:e.height,codecs:t.attributes&&t.attributes.CODECS||""})},Bi=function(e,t){if(!e)return"";const i=window.getComputedStyle(e);return i?i[t]:""},Ni=function(e,t){const i=e.slice();e.sort((function(e,n){const s=t(e,n);return 0===s?i.indexOf(e)-i.indexOf(n):s}))},Fi=function(e,t){let i,n;return e.attributes.BANDWIDTH&&(i=e.attributes.BANDWIDTH),i=i||window.Number.MAX_VALUE,t.attributes.BANDWIDTH&&(n=t.attributes.BANDWIDTH),n=n||window.Number.MAX_VALUE,i-n};let $i=function(e,t,i,n,s,r){if(!e)return;const a={bandwidth:t,width:i,height:n,limitRenditionByPlayerDimensions:s};let o=e.playlists;oe.isAudioOnly(e)&&(o=r.getAudioTrackPlaylists_(),a.audioOnly=!0);let d=o.map((e=>{let t;const i=e.attributes&&e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width,n=e.attributes&&e.attributes.RESOLUTION&&e.attributes.RESOLUTION.height;return t=e.attributes&&e.attributes.BANDWIDTH,t=t||window.Number.MAX_VALUE,{bandwidth:t,width:i,height:n,playlist:e}}));Ni(d,((e,t)=>e.bandwidth-t.bandwidth)),d=d.filter((e=>!oe.isIncompatible(e.playlist)));let u=d.filter((e=>oe.isEnabled(e.playlist)));u.length||(u=d.filter((e=>!oe.isDisabled(e.playlist))));const l=u.filter((e=>e.bandwidth*di.BANDWIDTH_VARIANCE<t));let h=l[l.length-1];const c=l.filter((e=>e.bandwidth===h.bandwidth))[0];if(!1===s){const e=c||u[0]||d[0];if(e&&e.playlist){let t="sortedPlaylistReps";return c&&(t="bandwidthBestRep"),u[0]&&(t="enabledPlaylistReps"),Ri(`choosing ${Mi(e)} using ${t} with options`,a),e.playlist}return Ri("could not choose a playlist with options",a),null}const p=l.filter((e=>e.width&&e.height));Ni(p,((e,t)=>e.width-t.width));const m=p.filter((e=>e.width===i&&e.height===n));h=m[m.length-1];const f=m.filter((e=>e.bandwidth===h.bandwidth))[0];let g,y,_,T;if(f||(g=p.filter((e=>e.width>i||e.height>n)),y=g.filter((e=>e.width===g[0].width&&e.height===g[0].height)),h=y[y.length-1],_=y.filter((e=>e.bandwidth===h.bandwidth))[0]),r.leastPixelDiffSelector){const e=p.map((e=>(e.pixelDiff=Math.abs(e.width-i)+Math.abs(e.height-n),e)));Ni(e,((e,t)=>e.pixelDiff===t.pixelDiff?t.bandwidth-e.bandwidth:e.pixelDiff-t.pixelDiff)),T=e[0]}const b=T||_||f||c||u[0]||d[0];if(b&&b.playlist){let e="sortedPlaylistReps";return T?e="leastPixelDiffRep":_?e="resolutionPlusOneRep":f?e="resolutionBestRep":c?e="bandwidthBestRep":u[0]&&(e="enabledPlaylistReps"),Ri(`choosing ${Mi(b)} using ${e} with options`,a),b.playlist}return Ri("could not choose a playlist with options",a),null};const qi=function(){const e=this.useDevicePixelRatio&&window.devicePixelRatio||1;return $i(this.playlists.main,this.systemBandwidth,parseInt(Bi(this.tech_.el(),"width"),10)*e,parseInt(Bi(this.tech_.el(),"height"),10)*e,this.limitRenditionByPlayerDimensions,this.playlistController_)},Wi=function(e,t,i){let n,s;if(i&&i.cues)for(n=i.cues.length;n--;)s=i.cues[n],s.startTime>=e&&s.endTime<=t&&i.removeCue(s)};var Gi=9e4,Vi=Gi;const Hi=e=>"number"==typeof e&&isFinite(e),ji=1/60,Xi=e=>{const{startOfSegment:t,duration:i,segment:n,part:s,playlist:{mediaSequence:r,id:a,segments:o=[]},mediaIndex:d,partIndex:u,timeline:l}=e,h=o.length-1;let c="mediaIndex/partIndex increment";e.getMediaInfoForTime?c=`getMediaInfoForTime (${e.getMediaInfoForTime})`:e.isSyncRequest&&(c="getSyncSegmentCandidate (isSyncRequest)"),e.independent&&(c+=` with independent ${e.independent}`);const p="number"==typeof u,m=e.segment.uri?"segment":"pre-segment",f=p?X({preloadSegment:n})-1:0;return`${m} [${r+d}/${r+h}]`+(p?` part [${u}/${f}]`:"")+` segment start/end [${n.start} => ${n.end}]`+(p?` part start/end [${s.start} => ${s.end}]`:"")+` startOfSegment [${t}]`+` duration [${i}]`+` timeline [${l}]`+` selected by [${c}]`+` playlist [${a}]`},zi=e=>`${e}TimingInfo`,Qi=({timelineChangeController:e,currentTimeline:t,segmentTimeline:i,loaderType:n,audioDisabled:s})=>{if(t===i)return!1;if("audio"===n){const t=e.lastTimelineChange({type:"main"});return!t||t.to!==i}if("main"===n&&s){const t=e.pendingTimelineChange({type:"audio"});return!t||t.to!==i}return!1},Yi=({segmentDuration:e,maxDuration:t})=>!!e&&Math.round(e)>t+R;class Ki extends s.default.EventTarget{constructor(e,t={}){if(super(),!e)throw new TypeError("Initialization settings are required");if("function"!=typeof e.currentTime)throw new TypeError("No currentTime getter specified");if(!e.mediaSource)throw new TypeError("No MediaSource specified");this.bandwidth=e.bandwidth,this.throughput={rate:0,count:0},this.roundTrip=NaN,this.resetStats_(),this.mediaIndex=null,this.partIndex=null,this.hasPlayed_=e.hasPlayed,this.currentTime_=e.currentTime,this.seekable_=e.seekable,this.seeking_=e.seeking,this.duration_=e.duration,this.mediaSource_=e.mediaSource,this.vhs_=e.vhs,this.loaderType_=e.loaderType,this.currentMediaInfo_=void 0,this.startingMediaInfo_=void 0,this.segmentMetadataTrack_=e.segmentMetadataTrack,this.goalBufferLength_=e.goalBufferLength,this.sourceType_=e.sourceType,this.sourceUpdater_=e.sourceUpdater,this.inbandTextTracks_=e.inbandTextTracks,this.state_="INIT",this.timelineChangeController_=e.timelineChangeController,this.shouldSaveSegmentTimingInfo_=!0,this.parse708captions_=e.parse708captions,this.useDtsForTimestampOffset_=e.useDtsForTimestampOffset,this.captionServices_=e.captionServices,this.exactManifestTimings=e.exactManifestTimings,this.checkBufferTimeout_=null,this.error_=void 0,this.currentTimeline_=-1,this.pendingSegment_=null,this.xhrOptions_=null,this.pendingSegments_=[],this.audioDisabled_=!1,this.isPendingTimestampOffset_=!1,this.gopBuffer_=[],this.timeMapping_=0,this.safeAppend_=s.default.browser.IE_VERSION>=11,this.appendInitSegment_={audio:!0,video:!0},this.playlistOfLastInitSegment_={audio:null,video:null},this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_={id3:[],caption:[]},this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=null,this.activeInitSegmentId_=null,this.initSegments_={},this.cacheEncryptionKeys_=e.cacheEncryptionKeys,this.keyCache_={},this.decrypter_=e.decrypter,this.syncController_=e.syncController,this.syncPoint_={segmentIndex:0,time:0},this.transmuxer_=this.createTransmuxer_(),this.triggerSyncInfoUpdate_=()=>this.trigger("syncinfoupdate"),this.syncController_.on("syncinfoupdate",this.triggerSyncInfoUpdate_),this.mediaSource_.addEventListener("sourceopen",(()=>{this.isEndOfStream_()||(this.ended_=!1)})),this.fetchAtBuffer_=!1,this.logger_=h(`SegmentLoader[${this.loaderType_}]`),Object.defineProperty(this,"state",{get(){return this.state_},set(e){e!==this.state_&&(this.logger_(`${this.state_} -> ${e}`),this.state_=e,this.trigger("statechange"))}}),this.sourceUpdater_.on("ready",(()=>{this.hasEnoughInfoToAppend_()&&this.processCallQueue_()})),"main"===this.loaderType_&&this.timelineChangeController_.on("pendingtimelinechange",(()=>{this.hasEnoughInfoToAppend_()&&this.processCallQueue_()})),"audio"===this.loaderType_&&this.timelineChangeController_.on("timelinechange",(()=>{this.hasEnoughInfoToLoad_()&&this.processLoadQueue_(),this.hasEnoughInfoToAppend_()&&this.processCallQueue_()}))}createTransmuxer_(){return(e=>{const t=new mi;t.currentTransmux=null,t.transmuxQueue=[];const i=t.terminate;return t.terminate=()=>(t.currentTransmux=null,t.transmuxQueue.length=0,i.call(t)),t.postMessage({action:"init",options:e}),t})({remux:!1,alignGopsAtEnd:this.safeAppend_,keepOriginalTimestamps:!0,parse708captions:this.parse708captions_,captionServices:this.captionServices_})}resetStats_(){this.mediaBytesTransferred=0,this.mediaRequests=0,this.mediaRequestsAborted=0,this.mediaRequestsTimedout=0,this.mediaRequestsErrored=0,this.mediaTransferDuration=0,this.mediaSecondsLoaded=0,this.mediaAppends=0}dispose(){this.trigger("dispose"),this.state="DISPOSED",this.pause(),this.abort_(),this.transmuxer_&&this.transmuxer_.terminate(),this.resetStats_(),this.checkBufferTimeout_&&window.clearTimeout(this.checkBufferTimeout_),this.syncController_&&this.triggerSyncInfoUpdate_&&this.syncController_.off("syncinfoupdate",this.triggerSyncInfoUpdate_),this.off()}setAudio(e){this.audioDisabled_=!e,e?this.appendInitSegment_.audio=!0:this.sourceUpdater_.removeAudio(0,this.duration_())}abort(){"WAITING"===this.state?(this.abort_(),this.state="READY",this.paused()||this.monitorBuffer_()):this.pendingSegment_&&(this.pendingSegment_=null)}abort_(){this.pendingSegment_&&this.pendingSegment_.abortRequests&&this.pendingSegment_.abortRequests(),this.pendingSegment_=null,this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_),this.waitingOnRemove_=!1,window.clearTimeout(this.quotaExceededErrorRetryTimeout_),this.quotaExceededErrorRetryTimeout_=null}checkForAbort_(e){return"APPENDING"!==this.state||this.pendingSegment_?!this.pendingSegment_||this.pendingSegment_.requestId!==e:(this.state="READY",!0)}error(e){return void 0!==e&&(this.logger_("error occurred:",e),this.error_=e),this.pendingSegment_=null,this.error_}endOfStream(){this.ended_=!0,this.transmuxer_&&_i(this.transmuxer_),this.gopBuffer_.length=0,this.pause(),this.trigger("ended")}buffered_(){const e=this.getMediaInfo_();if(!this.sourceUpdater_||!e)return C();if("main"===this.loaderType_){const{hasAudio:t,hasVideo:i,isMuxed:n}=e;if(i&&t&&!this.audioDisabled_&&!n)return this.sourceUpdater_.buffered();if(i)return this.sourceUpdater_.videoBuffered()}return this.sourceUpdater_.audioBuffered()}initSegmentForMap(e,t=!1){if(!e)return null;const i=qe(e);let n=this.initSegments_[i];return t&&!n&&e.bytes&&(this.initSegments_[i]=n={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:e.bytes,tracks:e.tracks,timescales:e.timescales}),n||e}segmentKey(e,t=!1){if(!e)return null;const i=We(e);let n=this.keyCache_[i];this.cacheEncryptionKeys_&&t&&!n&&e.bytes&&(this.keyCache_[i]=n={resolvedUri:e.resolvedUri,bytes:e.bytes});const s={resolvedUri:(n||e).resolvedUri};return n&&(s.bytes=n.bytes),s}couldBeginLoading_(){return this.playlist_&&!this.paused()}load(){if(this.monitorBuffer_(),this.playlist_)return"INIT"===this.state&&this.couldBeginLoading_()?this.init_():void(!this.couldBeginLoading_()||"READY"!==this.state&&"INIT"!==this.state||(this.state="READY"))}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}playlist(e,t={}){if(!e)return;const i=this.playlist_,n=this.pendingSegment_;this.playlist_=e,this.xhrOptions_=t,"INIT"===this.state&&(e.syncInfo={mediaSequence:e.mediaSequence,time:0},"main"===this.loaderType_&&this.syncController_.setDateTimeMappingForStart(e));let s=null;if(i&&(i.id?s=i.id:i.uri&&(s=i.uri)),this.logger_(`playlist update [${s} => ${e.id||e.uri}]`),this.trigger("syncinfoupdate"),"INIT"===this.state&&this.couldBeginLoading_())return this.init_();if(!i||i.uri!==e.uri)return null!==this.mediaIndex&&(e.endList?this.resyncLoader():this.resetLoader()),this.currentMediaInfo_=void 0,void this.trigger("playlistupdate");const r=e.mediaSequence-i.mediaSequence;if(this.logger_(`live window shift [${r}]`),null!==this.mediaIndex)if(this.mediaIndex-=r,this.mediaIndex<0)this.mediaIndex=null,this.partIndex=null;else{const e=this.playlist_.segments[this.mediaIndex];if(this.partIndex&&(!e.parts||!e.parts.length||!e.parts[this.partIndex])){const e=this.mediaIndex;this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`),this.resetLoader(),this.mediaIndex=e}}n&&(n.mediaIndex-=r,n.mediaIndex<0?(n.mediaIndex=null,n.partIndex=null):(n.mediaIndex>=0&&(n.segment=e.segments[n.mediaIndex]),n.partIndex>=0&&n.segment.parts&&(n.part=n.segment.parts[n.partIndex]))),this.syncController_.saveExpiredSegmentInfo(i,e)}pause(){this.checkBufferTimeout_&&(window.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=null)}paused(){return null===this.checkBufferTimeout_}resetEverything(e){this.ended_=!1,this.appendInitSegment_={audio:!0,video:!0},this.resetLoader(),this.remove(0,1/0,e),this.transmuxer_&&(this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),this.transmuxer_.postMessage({action:"reset"}))}resetLoader(){this.fetchAtBuffer_=!1,this.resyncLoader()}resyncLoader(){this.transmuxer_&&_i(this.transmuxer_),this.mediaIndex=null,this.partIndex=null,this.syncPoint_=null,this.isPendingTimestampOffset_=!1,this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.abort(),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}remove(e,t,i=(()=>{}),n=!1){if(t===1/0&&(t=this.duration_()),t<=e)return void this.logger_("skipping remove because end ${end} is <= start ${start}");if(!this.sourceUpdater_||!this.getMediaInfo_())return void this.logger_("skipping remove because no source updater or starting media info");let s=1;const r=()=>{s--,0===s&&i()};!n&&this.audioDisabled_||(s++,this.sourceUpdater_.removeAudio(e,t,r)),(n||"main"===this.loaderType_)&&(this.gopBuffer_=((e,t,i,n)=>{const s=Math.ceil((t-n)*Vi),r=Math.ceil((i-n)*Vi),a=e.slice();let o=e.length;for(;o--&&!(e[o].pts<=r););if(-1===o)return a;let d=o+1;for(;d--&&!(e[d].pts<=s););return d=Math.max(d,0),a.splice(d,o-d+1),a})(this.gopBuffer_,e,t,this.timeMapping_),s++,this.sourceUpdater_.removeVideo(e,t,r));for(const i in this.inbandTextTracks_)Wi(e,t,this.inbandTextTracks_[i]);Wi(e,t,this.segmentMetadataTrack_),r()}monitorBuffer_(){this.checkBufferTimeout_&&window.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=window.setTimeout(this.monitorBufferTick_.bind(this),1)}monitorBufferTick_(){"READY"===this.state&&this.fillBuffer_(),this.checkBufferTimeout_&&window.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=window.setTimeout(this.monitorBufferTick_.bind(this),500)}fillBuffer_(){if(this.sourceUpdater_.updating())return;const e=this.chooseNextRequest_();e&&("number"==typeof e.timestampOffset&&(this.isPendingTimestampOffset_=!1,this.timelineChangeController_.pendingTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline})),this.loadSegment_(e))}isEndOfStream_(e=this.mediaIndex,t=this.playlist_,i=this.partIndex){if(!t||!this.mediaSource_)return!1;const n="number"==typeof e&&t.segments[e],s=e+1===t.segments.length,r=!n||!n.parts||i+1===n.parts.length;return t.endList&&"open"===this.mediaSource_.readyState&&s&&r}chooseNextRequest_(){const e=this.buffered_(),t=W(e)||0,i=G(e,this.currentTime_()),n=!this.hasPlayed_()&&i>=1,s=i>=this.goalBufferLength_(),r=this.playlist_.segments;if(!r.length||n||s)return null;this.syncPoint_=this.syncPoint_||this.syncController_.getSyncPoint(this.playlist_,this.duration_(),this.currentTimeline_,this.currentTime_());const a={partIndex:null,mediaIndex:null,startOfSegment:null,playlist:this.playlist_,isSyncRequest:Boolean(!this.syncPoint_)};if(a.isSyncRequest)a.mediaIndex=function(e,t,i){t=t||[];const n=[];let s=0;for(let r=0;r<t.length;r++){const a=t[r];if(e===a.timeline&&(n.push(r),s+=a.duration,s>i))return r}return 0===n.length?0:n[n.length-1]}(this.currentTimeline_,r,t);else if(null!==this.mediaIndex){const e=r[this.mediaIndex],i="number"==typeof this.partIndex?this.partIndex:-1;a.startOfSegment=e.end?e.end:t,e.parts&&e.parts[i+1]?(a.mediaIndex=this.mediaIndex,a.partIndex=i+1):a.mediaIndex=this.mediaIndex+1}else{const{segmentIndex:e,startTime:i,partIndex:n}=oe.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,playlist:this.playlist_,currentTime:this.fetchAtBuffer_?t:this.currentTime_(),startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time});a.getMediaInfoForTime=this.fetchAtBuffer_?`bufferedEnd ${t}`:`currentTime ${this.currentTime_()}`,a.mediaIndex=e,a.startOfSegment=i,a.partIndex=n}const o=r[a.mediaIndex];let d=o&&"number"==typeof a.partIndex&&o.parts&&o.parts[a.partIndex];if(!o||"number"==typeof a.partIndex&&!d)return null;if("number"!=typeof a.partIndex&&o.parts&&(a.partIndex=0,d=o.parts[0]),!i&&d&&!d.independent)if(0===a.partIndex){const e=r[a.mediaIndex-1],t=e.parts&&e.parts.length&&e.parts[e.parts.length-1];t&&t.independent&&(a.mediaIndex-=1,a.partIndex=e.parts.length-1,a.independent="previous segment")}else o.parts[a.partIndex-1].independent&&(a.partIndex-=1,a.independent="previous part");const u=this.mediaSource_&&"ended"===this.mediaSource_.readyState;return a.mediaIndex>=r.length-1&&u&&!this.seeking_()?null:this.generateSegmentInfo_(a)}generateSegmentInfo_(e){const{independent:t,playlist:i,mediaIndex:n,startOfSegment:s,isSyncRequest:r,partIndex:a,forceTimestampOffset:o,getMediaInfoForTime:d}=e,u=i.segments[n],l="number"==typeof a&&u.parts[a],h={requestId:"segment-loader-"+Math.random(),uri:l&&l.resolvedUri||u.resolvedUri,mediaIndex:n,partIndex:l?a:null,isSyncRequest:r,startOfSegment:s,playlist:i,bytes:null,encryptedBytes:null,timestampOffset:null,timeline:u.timeline,duration:l&&l.duration||u.duration,segment:u,part:l,byteLength:0,transmuxer:this.transmuxer_,getMediaInfoForTime:d,independent:t},c=void 0!==o?o:this.isPendingTimestampOffset_;h.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:u.timeline,currentTimeline:this.currentTimeline_,startOfSegment:s,buffered:this.buffered_(),overrideCheck:c});const p=W(this.sourceUpdater_.audioBuffered());return"number"==typeof p&&(h.audioAppendStart=p-this.sourceUpdater_.audioTimestampOffset()),this.sourceUpdater_.videoBuffered().length&&(h.gopsToAlignWith=((e,t,i)=>{if(null==t||!e.length)return[];const n=Math.ceil((t-i+3)*Vi);let s;for(s=0;s<e.length&&!(e[s].pts>n);s++);return e.slice(s)})(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_)),h}timestampOffsetForSegment_(e){return(({segmentTimeline:e,currentTimeline:t,startOfSegment:i,buffered:n,overrideCheck:s})=>s||e!==t?e<t?i:n.length?n.end(n.length-1):i:null)(e)}earlyAbortWhenNeeded_(e){if(this.vhs_.tech_.paused()||!this.xhrOptions_.timeout||!this.playlist_.attributes.BANDWIDTH)return;if(Date.now()-(e.firstBytesReceivedAt||Date.now())<1e3)return;const t=this.currentTime_(),i=e.bandwidth,n=this.pendingSegment_.duration,s=oe.estimateSegmentRequestTime(n,i,this.playlist_,e.bytesReceived),r=function(e,t,i=1){return((e.length?e.end(e.length-1):0)-t)/i}(this.buffered_(),t,this.vhs_.tech_.playbackRate())-1;if(s<=r)return;const a=function(e){const{main:t,currentTime:i,bandwidth:n,duration:s,segmentDuration:r,timeUntilRebuffer:a,currentTimeline:o,syncController:d}=e,u=t.playlists.filter((e=>!oe.isIncompatible(e)));let l=u.filter(oe.isEnabled);l.length||(l=u.filter((e=>!oe.isDisabled(e))));const h=l.filter(oe.hasAttribute.bind(null,"BANDWIDTH")).map((e=>{const t=d.getSyncPoint(e,s,o,i)?1:2;return{playlist:e,rebufferingImpact:oe.estimateSegmentRequestTime(r,n,e)*t-a}})),c=h.filter((e=>e.rebufferingImpact<=0));return Ni(c,((e,t)=>Fi(t.playlist,e.playlist))),c.length?c[0]:(Ni(h,((e,t)=>e.rebufferingImpact-t.rebufferingImpact)),h[0]||null)}({main:this.vhs_.playlists.main,currentTime:t,bandwidth:i,duration:this.duration_(),segmentDuration:n,timeUntilRebuffer:r,currentTimeline:this.currentTimeline_,syncController:this.syncController_});if(!a)return;const o=s-r-a.rebufferingImpact;let d=.5;r<=R&&(d=1),!a.playlist||a.playlist.uri===this.playlist_.uri||o<d||(this.bandwidth=a.playlist.attributes.BANDWIDTH*di.BANDWIDTH_VARIANCE+1,this.trigger("earlyabort"))}handleAbort_(e){this.logger_(`Aborting ${Xi(e)}`),this.mediaRequestsAborted+=1}handleProgress_(e,t){this.earlyAbortWhenNeeded_(t.stats),this.checkForAbort_(t.requestId)||this.trigger("progress")}handleTrackInfo_(e,t){this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId)||this.checkForIllegalMediaSwitch(t)||(t=t||{},function(e,t){if(!e&&!t||!e&&t||e&&!t)return!1;if(e===t)return!0;const i=Object.keys(e).sort(),n=Object.keys(t).sort();if(i.length!==n.length)return!1;for(let s=0;s<i.length;s++){const r=i[s];if(r!==n[s])return!1;if(e[r]!==t[r])return!1}return!0}(this.currentMediaInfo_,t)||(this.appendInitSegment_={audio:!0,video:!0},this.startingMediaInfo_=t,this.currentMediaInfo_=t,this.logger_("trackinfo update",t),this.trigger("trackinfo")),this.checkForAbort_(e.requestId)||(this.pendingSegment_.trackInfo=t,this.hasEnoughInfoToAppend_()&&this.processCallQueue_()))}handleTimingInfo_(e,t,i,n){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;const s=this.pendingSegment_,r=zi(t);s[r]=s[r]||{},s[r][i]=n,this.logger_(`timinginfo: ${t} - ${i} - ${n}`),this.hasEnoughInfoToAppend_()&&this.processCallQueue_()}handleCaptions_(e,t){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(0===t.length)return void this.logger_("SegmentLoader received no captions from a caption event");if(!this.pendingSegment_.hasAppendedData_)return void this.metadataQueue_.caption.push(this.handleCaptions_.bind(this,e,t));const i=null===this.sourceUpdater_.videoTimestampOffset()?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset(),n={};t.forEach((e=>{n[e.stream]=n[e.stream]||{startTime:1/0,captions:[],endTime:0};const t=n[e.stream];t.startTime=Math.min(t.startTime,e.startTime+i),t.endTime=Math.max(t.endTime,e.endTime+i),t.captions.push(e)})),Object.keys(n).forEach((e=>{const{startTime:t,endTime:s,captions:r}=n[e],a=this.inbandTextTracks_;this.logger_(`adding cues from ${t} -> ${s} for ${e}`),function(e,t,i){if(!e[i]){t.trigger({type:"usage",name:"vhs-608"});let n=i;/^cc708_/.test(i)&&(n="SERVICE"+i.split("_")[1]);const s=t.textTracks().getTrackById(n);if(s)e[i]=s;else{let s=i,r=i,a=!1;const o=(t.options_.vhs&&t.options_.vhs.captionServices||{})[n];o&&(s=o.label,r=o.language,a=o.default),e[i]=t.addRemoteTextTrack({kind:"captions",id:n,default:a,label:s,language:r},!1).track}}}(a,this.vhs_.tech_,e),Wi(t,s,a[e]),function({inbandTextTracks:e,captionArray:t,timestampOffset:i}){if(!t)return;const n=window.WebKitDataCue||window.VTTCue;t.forEach((t=>{const s=t.stream;e[s].addCue(new n(t.startTime+i,t.endTime+i,t.text))}))}({captionArray:r,inbandTextTracks:a,timestampOffset:i})})),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}handleId3_(e,t,i){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(!this.pendingSegment_.hasAppendedData_)return void this.metadataQueue_.id3.push(this.handleId3_.bind(this,e,t,i));const n=null===this.sourceUpdater_.videoTimestampOffset()?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset();((e,t,i)=>{e.metadataTrack_||(e.metadataTrack_=i.addRemoteTextTrack({kind:"metadata",label:"Timed Metadata"},!1).track,e.metadataTrack_.inBandMetadataTrackDispatchType=t)})(this.inbandTextTracks_,i,this.vhs_.tech_),(({inbandTextTracks:e,metadataArray:t,timestampOffset:i,videoDuration:n})=>{if(!t)return;const r=window.WebKitDataCue||window.VTTCue,a=e.metadataTrack_;if(!a)return;if(t.forEach((e=>{const t=e.cueTime+i;!("number"!=typeof t||window.isNaN(t)||t<0)&&t<1/0&&e.frames.forEach((e=>{const i=new r(t,t,e.value||e.url||e.data||"");i.frame=e,i.value=e,function(e){Object.defineProperties(e.frame,{id:{get:()=>(s.default.log.warn("cue.frame.id is deprecated. Use cue.value.key instead."),e.value.key)},value:{get:()=>(s.default.log.warn("cue.frame.value is deprecated. Use cue.value.data instead."),e.value.data)},privateData:{get:()=>(s.default.log.warn("cue.frame.privateData is deprecated. Use cue.value.data instead."),e.value.data)}})}(i),a.addCue(i)}))})),!a.cues||!a.cues.length)return;const o=a.cues,d=[];for(let e=0;e<o.length;e++)o[e]&&d.push(o[e]);const u=d.reduce(((e,t)=>{const i=e[t.startTime]||[];return i.push(t),e[t.startTime]=i,e}),{}),l=Object.keys(u).sort(((e,t)=>Number(e)-Number(t)));l.forEach(((e,t)=>{const i=u[e],s=Number(l[t+1])||n;i.forEach((e=>{e.endTime=s}))}))})({inbandTextTracks:this.inbandTextTracks_,metadataArray:t,timestampOffset:n,videoDuration:this.duration_()})}processMetadataQueue_(){this.metadataQueue_.id3.forEach((e=>e())),this.metadataQueue_.caption.forEach((e=>e())),this.metadataQueue_.id3=[],this.metadataQueue_.caption=[]}processCallQueue_(){const e=this.callQueue_;this.callQueue_=[],e.forEach((e=>e()))}processLoadQueue_(){const e=this.loadQueue_;this.loadQueue_=[],e.forEach((e=>e()))}hasEnoughInfoToLoad_(){if("audio"!==this.loaderType_)return!0;const e=this.pendingSegment_;return!(!e||this.getCurrentMediaInfo_()&&Qi({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}))}getCurrentMediaInfo_(e=this.pendingSegment_){return e&&e.trackInfo||this.currentMediaInfo_}getMediaInfo_(e=this.pendingSegment_){return this.getCurrentMediaInfo_(e)||this.startingMediaInfo_}hasEnoughInfoToAppend_(){if(!this.sourceUpdater_.ready())return!1;if(this.waitingOnRemove_||this.quotaExceededErrorRetryTimeout_)return!1;const e=this.pendingSegment_,t=this.getCurrentMediaInfo_();if(!e||!t)return!1;const{hasAudio:i,hasVideo:n,isMuxed:s}=t;return!(n&&!e.videoTimingInfo||i&&!this.audioDisabled_&&!s&&!e.audioTimingInfo||Qi({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}))}handleData_(e,t){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(this.callQueue_.length||!this.hasEnoughInfoToAppend_())return void this.callQueue_.push(this.handleData_.bind(this,e,t));const i=this.pendingSegment_;if(this.setTimeMapping_(i.timeline),this.updateMediaSecondsLoaded_(i.part||i.segment),"closed"!==this.mediaSource_.readyState){if(e.map&&(e.map=this.initSegmentForMap(e.map,!0),i.segment.map=e.map),e.key&&this.segmentKey(e.key,!0),i.isFmp4=e.isFmp4,i.timingInfo=i.timingInfo||{},i.isFmp4)this.trigger("fmp4"),i.timingInfo.start=i[zi(t.type)].start;else{const e=this.getCurrentMediaInfo_(),t="main"===this.loaderType_&&e&&e.hasVideo;let n;t&&(n=i.videoTimingInfo.start),i.timingInfo.start=this.trueSegmentStart_({currentStart:i.timingInfo.start,playlist:i.playlist,mediaIndex:i.mediaIndex,currentVideoTimestampOffset:this.sourceUpdater_.videoTimestampOffset(),useVideoTimingInfo:t,firstVideoFrameTimeForData:n,videoTimingInfo:i.videoTimingInfo,audioTimingInfo:i.audioTimingInfo})}if(this.updateAppendInitSegmentStatus(i,t.type),this.updateSourceBufferTimestampOffset_(i),i.isSyncRequest){this.updateTimingInfoEnd_(i),this.syncController_.saveSegmentTimingInfo({segmentInfo:i,shouldSaveTimelineMapping:"main"===this.loaderType_});const e=this.chooseNextRequest_();if(e.mediaIndex!==i.mediaIndex||e.partIndex!==i.partIndex)return void this.logger_("sync segment was incorrect, not appending");this.logger_("sync segment was correct, appending")}i.hasAppendedData_=!0,this.processMetadataQueue_(),this.appendData_(i,t)}}updateAppendInitSegmentStatus(e,t){"main"!==this.loaderType_||"number"!=typeof e.timestampOffset||e.changedTimestampOffset||(this.appendInitSegment_={audio:!0,video:!0}),this.playlistOfLastInitSegment_[t]!==e.playlist&&(this.appendInitSegment_[t]=!0)}getInitSegmentAndUpdateState_({type:e,initSegment:t,map:i,playlist:n}){if(i){const e=qe(i);if(this.activeInitSegmentId_===e)return null;t=this.initSegmentForMap(i,!0).bytes,this.activeInitSegmentId_=e}return t&&this.appendInitSegment_[e]?(this.playlistOfLastInitSegment_[e]=n,this.appendInitSegment_[e]=!1,this.activeInitSegmentId_=null,t):null}handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i},n){const s=this.sourceUpdater_.audioBuffered(),r=this.sourceUpdater_.videoBuffered();s.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: "+q(s).join(", ")),r.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: "+q(r).join(", "));const a=s.length?s.start(0):0,o=s.length?s.end(s.length-1):0,d=r.length?r.start(0):0,u=r.length?r.end(r.length-1):0;if(o-a<=1&&u-d<=1)return this.logger_(`On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. Appended byte length: ${i.byteLength}, audio buffer: ${q(s).join(", ")}, video buffer: ${q(r).join(", ")}, `),this.error({message:"Quota exceeded error with append of a single segment of content",excludeUntil:1/0}),void this.trigger("error");this.waitingOnRemove_=!0,this.callQueue_.push(this.appendToSourceBuffer_.bind(this,{segmentInfo:e,type:t,bytes:i}));const l=this.currentTime_()-1;this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${l}`),this.remove(0,l,(()=>{this.logger_("On QUOTA_EXCEEDED_ERR, retrying append in 1s"),this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=window.setTimeout((()=>{this.logger_("On QUOTA_EXCEEDED_ERR, re-processing call queue"),this.quotaExceededErrorRetryTimeout_=null,this.processCallQueue_()}),1e3)}),!0)}handleAppendError_({segmentInfo:e,type:t,bytes:i},n){n&&(22!==n.code?(this.logger_("Received non QUOTA_EXCEEDED_ERR on append",n),this.error(`${t} append of ${i.length}b failed for segment #${e.mediaIndex} in playlist ${e.playlist.id}`),this.trigger("appenderror")):this.handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i}))}appendToSourceBuffer_({segmentInfo:e,type:t,initSegment:i,data:n,bytes:s}){if(!s){const e=[n];let t=n.byteLength;i&&(e.unshift(i),t+=i.byteLength),s=(e=>{let t,i=0;return e.bytes&&(t=new Uint8Array(e.bytes),e.segments.forEach((e=>{t.set(e,i),i+=e.byteLength}))),t})({bytes:t,segments:e})}this.sourceUpdater_.appendBuffer({segmentInfo:e,type:t,bytes:s},this.handleAppendError_.bind(this,{segmentInfo:e,type:t,bytes:s}))}handleSegmentTimingInfo_(e,t,i){if(!this.pendingSegment_||t!==this.pendingSegment_.requestId)return;const n=this.pendingSegment_.segment,s=`${e}TimingInfo`;n[s]||(n[s]={}),n[s].transmuxerPrependedSeconds=i.prependedContentDuration||0,n[s].transmuxedPresentationStart=i.start.presentation,n[s].transmuxedDecodeStart=i.start.decode,n[s].transmuxedPresentationEnd=i.end.presentation,n[s].transmuxedDecodeEnd=i.end.decode,n[s].baseMediaDecodeTime=i.baseMediaDecodeTime}appendData_(e,t){const{type:i,data:n}=t;if(!n||!n.byteLength)return;if("audio"===i&&this.audioDisabled_)return;const s=this.getInitSegmentAndUpdateState_({type:i,initSegment:t.initSegment,playlist:e.playlist,map:e.isFmp4?e.segment.map:null});this.appendToSourceBuffer_({segmentInfo:e,type:i,initSegment:s,data:n})}loadSegment_(e){this.state="WAITING",this.pendingSegment_=e,this.trimBackBuffer_(e),"number"==typeof e.timestampOffset&&this.transmuxer_&&this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),this.hasEnoughInfoToLoad_()?this.updateTransmuxerAndRequestSegment_(e):this.loadQueue_.push((()=>{const t=c({},e,{forceTimestampOffset:!0});c(e,this.generateSegmentInfo_(t)),this.isPendingTimestampOffset_=!1,this.updateTransmuxerAndRequestSegment_(e)}))}updateTransmuxerAndRequestSegment_(e){this.shouldUpdateTransmuxerTimestampOffset_(e.timestampOffset)&&(this.gopBuffer_.length=0,e.gopsToAlignWith=[],this.timeMapping_=0,this.transmuxer_.postMessage({action:"reset"}),this.transmuxer_.postMessage({action:"setTimestampOffset",timestampOffset:e.timestampOffset}));const t=this.createSimplifiedSegmentObj_(e),i=this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex),n=null!==this.mediaIndex,s=e.timeline!==this.currentTimeline_&&e.timeline>0,r=i||n&&s;this.logger_(`Requesting ${Xi(e)}`),t.map&&!t.map.bytes&&(this.logger_("going to request init segment."),this.appendInitSegment_={video:!0,audio:!0}),e.abortRequests=Di({xhr:this.vhs_.xhr,xhrOptions:this.xhrOptions_,decryptionWorker:this.decrypter_,segment:t,abortFn:this.handleAbort_.bind(this,e),progressFn:this.handleProgress_.bind(this),trackInfoFn:this.handleTrackInfo_.bind(this),timingInfoFn:this.handleTimingInfo_.bind(this),videoSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"video",e.requestId),audioSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"audio",e.requestId),captionsFn:this.handleCaptions_.bind(this),isEndOfTimeline:r,endedTimelineFn:()=>{this.logger_("received endedtimeline callback")},id3Fn:this.handleId3_.bind(this),dataFn:this.handleData_.bind(this),doneFn:this.segmentRequestFinished_.bind(this),onTransmuxerLog:({message:t,level:i,stream:n})=>{this.logger_(`${Xi(e)} logged from transmuxer stream ${n} as a ${i}: ${t}`)}})}trimBackBuffer_(e){const t=((e,t,i)=>{let n=t-di.BACK_BUFFER_LENGTH;e.length&&(n=Math.max(n,e.start(0)));const s=t-i;return Math.min(s,n)})(this.seekable_(),this.currentTime_(),this.playlist_.targetDuration||10);t>0&&this.remove(0,t)}createSimplifiedSegmentObj_(e){const t=e.segment,i=e.part,n={resolvedUri:i?i.resolvedUri:t.resolvedUri,byterange:i?i.byterange:t.byterange,requestId:e.requestId,transmuxer:e.transmuxer,audioAppendStart:e.audioAppendStart,gopsToAlignWith:e.gopsToAlignWith,part:e.part},s=e.playlist.segments[e.mediaIndex-1];if(s&&s.timeline===t.timeline&&(s.videoTimingInfo?n.baseStartTime=s.videoTimingInfo.transmuxedDecodeEnd:s.audioTimingInfo&&(n.baseStartTime=s.audioTimingInfo.transmuxedDecodeEnd)),t.key){const i=t.key.iv||new Uint32Array([0,0,0,e.mediaIndex+e.playlist.mediaSequence]);n.key=this.segmentKey(t.key),n.key.iv=i}return t.map&&(n.map=this.initSegmentForMap(t.map)),n}saveTransferStats_(e){this.mediaRequests+=1,e&&(this.mediaBytesTransferred+=e.bytesReceived,this.mediaTransferDuration+=e.roundTripTime)}saveBandwidthRelatedStats_(e,t){this.pendingSegment_.byteLength=t.bytesReceived,e<ji?this.logger_(`Ignoring segment's bandwidth because its duration of ${e} is less than the min to record 0.016666666666666666`):(this.bandwidth=t.bandwidth,this.roundTrip=t.roundTripTime)}handleTimeout_(){this.mediaRequestsTimedout+=1,this.bandwidth=1,this.roundTrip=NaN,this.trigger("bandwidthupdate")}segmentRequestFinished_(e,t,i){if(this.callQueue_.length)return void this.callQueue_.push(this.segmentRequestFinished_.bind(this,e,t,i));if(this.saveTransferStats_(t.stats),!this.pendingSegment_)return;if(t.requestId!==this.pendingSegment_.requestId)return;if(e){if(this.pendingSegment_=null,this.state="READY",e.code===Si)return;return this.pause(),e.code===bi?void this.handleTimeout_():(this.mediaRequestsErrored+=1,this.error(e),void this.trigger("error"))}const n=this.pendingSegment_;this.saveBandwidthRelatedStats_(n.duration,t.stats),n.endOfAllRequests=t.endOfAllRequests,i.gopInfo&&(this.gopBuffer_=((e,t,i)=>{if(!t.length)return e;if(i)return t.slice();const n=t[0].pts;let s=0;for(;s<e.length&&!(e[s].pts>=n);s++);return e.slice(0,s).concat(t)})(this.gopBuffer_,i.gopInfo,this.safeAppend_)),this.state="APPENDING",this.trigger("appending"),this.waitForAppendsToComplete_(n)}setTimeMapping_(e){const t=this.syncController_.mappingForTimeline(e);null!==t&&(this.timeMapping_=t)}updateMediaSecondsLoaded_(e){"number"==typeof e.start&&"number"==typeof e.end?this.mediaSecondsLoaded+=e.end-e.start:this.mediaSecondsLoaded+=e.duration}shouldUpdateTransmuxerTimestampOffset_(e){return null!==e&&("main"===this.loaderType_&&e!==this.sourceUpdater_.videoTimestampOffset()||!this.audioDisabled_&&e!==this.sourceUpdater_.audioTimestampOffset())}trueSegmentStart_({currentStart:e,playlist:t,mediaIndex:i,firstVideoFrameTimeForData:n,currentVideoTimestampOffset:s,useVideoTimingInfo:r,videoTimingInfo:a,audioTimingInfo:o}){if(void 0!==e)return e;if(!r)return o.start;const d=t.segments[i-1];return 0!==i&&d&&void 0!==d.start&&d.end===n+s?a.start:n}waitForAppendsToComplete_(e){const t=this.getCurrentMediaInfo_(e);if(!t)return this.error({message:"No starting media returned, likely due to an unsupported media format.",playlistExclusionDuration:1/0}),void this.trigger("error");const{hasAudio:i,hasVideo:n,isMuxed:s}=t,r="main"===this.loaderType_&&n,a=!this.audioDisabled_&&i&&!s;if(e.waitingOnAppends=0,!e.hasAppendedData_)return e.timingInfo||"number"!=typeof e.timestampOffset||(this.isPendingTimestampOffset_=!0),e.timingInfo={start:0},e.waitingOnAppends++,this.isPendingTimestampOffset_||(this.updateSourceBufferTimestampOffset_(e),this.processMetadataQueue_()),void this.checkAppendsDone_(e);r&&e.waitingOnAppends++,a&&e.waitingOnAppends++,r&&this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this,e)),a&&this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this,e))}checkAppendsDone_(e){this.checkForAbort_(e.requestId)||(e.waitingOnAppends--,0===e.waitingOnAppends&&this.handleAppendsDone_())}checkForIllegalMediaSwitch(e){const t=((e,t,i)=>"main"===e&&t&&i?i.hasAudio||i.hasVideo?t.hasVideo&&!i.hasVideo?"Only audio found in segment when we expected video. We can't switch to audio only from a stream that had video. To get rid of this message, please add codec information to the manifest.":!t.hasVideo&&i.hasVideo?"Video found in segment when we expected only audio. We can't switch to a stream with video from an audio only stream. To get rid of this message, please add codec information to the manifest.":null:"Neither audio nor video found in segment.":null)(this.loaderType_,this.getCurrentMediaInfo_(),e);return!!t&&(this.error({message:t,playlistExclusionDuration:1/0}),this.trigger("error"),!0)}updateSourceBufferTimestampOffset_(e){if(null===e.timestampOffset||"number"!=typeof e.timingInfo.start||e.changedTimestampOffset||"main"!==this.loaderType_)return;let t=!1;e.timestampOffset-=this.getSegmentStartTimeForTimestampOffsetCalculation_({videoTimingInfo:e.segment.videoTimingInfo,audioTimingInfo:e.segment.audioTimingInfo,timingInfo:e.timingInfo}),e.changedTimestampOffset=!0,e.timestampOffset!==this.sourceUpdater_.videoTimestampOffset()&&(this.sourceUpdater_.videoTimestampOffset(e.timestampOffset),t=!0),e.timestampOffset!==this.sourceUpdater_.audioTimestampOffset()&&(this.sourceUpdater_.audioTimestampOffset(e.timestampOffset),t=!0),t&&this.trigger("timestampoffset")}getSegmentStartTimeForTimestampOffsetCalculation_({videoTimingInfo:e,audioTimingInfo:t,timingInfo:i}){return this.useDtsForTimestampOffset_?e&&"number"==typeof e.transmuxedDecodeStart?e.transmuxedDecodeStart:t&&"number"==typeof t.transmuxedDecodeStart?t.transmuxedDecodeStart:i.start:i.start}updateTimingInfoEnd_(e){e.timingInfo=e.timingInfo||{};const t=this.getMediaInfo_(),i="main"===this.loaderType_&&t&&t.hasVideo&&e.videoTimingInfo?e.videoTimingInfo:e.audioTimingInfo;i&&(e.timingInfo.end="number"==typeof i.end?i.end:i.start+e.duration)}handleAppendsDone_(){if(this.pendingSegment_&&this.trigger("appendsdone"),!this.pendingSegment_)return this.state="READY",void(this.paused()||this.monitorBuffer_());const e=this.pendingSegment_;this.updateTimingInfoEnd_(e),this.shouldSaveSegmentTimingInfo_&&this.syncController_.saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:"main"===this.loaderType_});const t=((e,t)=>{if("hls"!==t)return null;const i=(e=>{let t=0;return["video","audio"].forEach((function(i){const n=e[`${i}TimingInfo`];if(!n)return;const{start:s,end:r}=n;let a;"bigint"==typeof s||"bigint"==typeof r?a=window.BigInt(r)-window.BigInt(s):"number"==typeof s&&"number"==typeof r&&(a=r-s),void 0!==a&&a>t&&(t=a)})),"bigint"==typeof t&&t<Number.MAX_SAFE_INTEGER&&(t=Number(t)),t})({audioTimingInfo:e.audioTimingInfo,videoTimingInfo:e.videoTimingInfo});if(!i)return null;const n=e.playlist.targetDuration,s=Yi({segmentDuration:i,maxDuration:2*n}),r=Yi({segmentDuration:i,maxDuration:n}),a=`Segment with index ${e.mediaIndex} from playlist ${e.playlist.id} has a duration of ${i} when the reported duration is ${e.duration} and the target duration is ${n}. For HLS content, a duration in excess of the target duration may result in playback issues. See the HLS specification section on EXT-X-TARGETDURATION for more details: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1`;return s||r?{severity:s?"warn":"info",message:a}:null})(e,this.sourceType_);if(t&&("warn"===t.severity?s.default.log.warn(t.message):this.logger_(t.message)),this.recordThroughput_(e),this.pendingSegment_=null,this.state="READY",e.isSyncRequest&&(this.trigger("syncinfoupdate"),!e.hasAppendedData_))return void this.logger_(`Throwing away un-appended sync request ${Xi(e)}`);this.logger_(`Appended ${Xi(e)}`),this.addSegmentMetadataCue_(e),this.fetchAtBuffer_=!0,this.currentTimeline_!==e.timeline&&(this.timelineChangeController_.lastTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline}),"main"!==this.loaderType_||this.audioDisabled_||this.timelineChangeController_.lastTimelineChange({type:"audio",from:this.currentTimeline_,to:e.timeline})),this.currentTimeline_=e.timeline,this.trigger("syncinfoupdate");const i=e.segment,n=e.part,r=i.end&&this.currentTime_()-i.end>3*e.playlist.targetDuration,a=n&&n.end&&this.currentTime_()-n.end>3*e.playlist.partTargetDuration;if(r||a)return this.logger_(`bad ${r?"segment":"part"} ${Xi(e)}`),void this.resetEverything();null!==this.mediaIndex&&this.trigger("bandwidthupdate"),this.trigger("progress"),this.mediaIndex=e.mediaIndex,this.partIndex=e.partIndex,this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex)&&this.endOfStream(),this.trigger("appended"),e.hasAppendedData_&&this.mediaAppends++,this.paused()||this.monitorBuffer_()}recordThroughput_(e){if(e.duration<ji)return void this.logger_(`Ignoring segment's throughput because its duration of ${e.duration} is less than the min to record 0.016666666666666666`);const t=this.throughput.rate,i=Date.now()-e.endOfAllRequests+1,n=Math.floor(e.byteLength/i*8*1e3);this.throughput.rate+=(n-t)/++this.throughput.count}addSegmentMetadataCue_(e){if(!this.segmentMetadataTrack_)return;const t=e.segment,i=t.start,n=t.end;if(!Hi(i)||!Hi(n))return;Wi(i,n,this.segmentMetadataTrack_);const s=window.WebKitDataCue||window.VTTCue,r={custom:t.custom,dateTimeObject:t.dateTimeObject,dateTimeString:t.dateTimeString,bandwidth:e.playlist.attributes.BANDWIDTH,resolution:e.playlist.attributes.RESOLUTION,codecs:e.playlist.attributes.CODECS,byteLength:e.byteLength,uri:e.uri,timeline:e.timeline,playlist:e.playlist.id,start:i,end:n},a=new s(i,n,JSON.stringify(r));a.value=r,this.segmentMetadataTrack_.addCue(a)}}function Ji(){}const Zi=function(e){return"string"!=typeof e?e:e.replace(/./,(e=>e.toUpperCase()))},en=["video","audio"],tn=(e,t)=>{const i=t[`${e}Buffer`];return i&&i.updating||t.queuePending[e]},nn=(e,t)=>{if(0===t.queue.length)return;let i=0,n=t.queue[i];if("mediaSource"!==n.type){if("mediaSource"!==e&&t.ready()&&"closed"!==t.mediaSource.readyState&&!tn(e,t)){if(n.type!==e){if(i=((e,t)=>{for(let i=0;i<t.length;i++){const n=t[i];if("mediaSource"===n.type)return null;if(n.type===e)return i}return null})(e,t.queue),null===i)return;n=t.queue[i]}return t.queue.splice(i,1),t.queuePending[e]=n,n.action(e,t),n.doneFn?void 0:(t.queuePending[e]=null,void nn(e,t))}}else t.updating()||"closed"===t.mediaSource.readyState||(t.queue.shift(),n.action(t),n.doneFn&&n.doneFn(),nn("audio",t),nn("video",t))},sn=(e,t)=>{const i=t[`${e}Buffer`],n=Zi(e);i&&(i.removeEventListener("updateend",t[`on${n}UpdateEnd_`]),i.removeEventListener("error",t[`on${n}Error_`]),t.codecs[e]=null,t[`${e}Buffer`]=null)},rn=(e,t)=>e&&t&&-1!==Array.prototype.indexOf.call(e.sourceBuffers,t),an=(e,t,i)=>(n,s)=>{const r=s[`${n}Buffer`];if(rn(s.mediaSource,r)){s.logger_(`Appending segment ${t.mediaIndex}'s ${e.length} bytes to ${n}Buffer`);try{r.appendBuffer(e)}catch(e){s.logger_(`Error with code ${e.code} `+(22===e.code?"(QUOTA_EXCEEDED_ERR) ":"")+`when appending segment ${t.mediaIndex} to ${n}Buffer`),s.queuePending[n]=null,i(e)}}},on=(e,t)=>(i,n)=>{const s=n[`${i}Buffer`];if(rn(n.mediaSource,s)){n.logger_(`Removing ${e} to ${t} from ${i}Buffer`);try{s.remove(e,t)}catch(s){n.logger_(`Remove ${e} to ${t} from ${i}Buffer failed`)}}},dn=e=>(t,i)=>{const n=i[`${t}Buffer`];rn(i.mediaSource,n)&&(i.logger_(`Setting ${t}timestampOffset to ${e}`),n.timestampOffset=e)},un=e=>(t,i)=>{e()},ln=e=>t=>{if("open"===t.mediaSource.readyState){t.logger_(`Calling mediaSource endOfStream(${e||""})`);try{t.mediaSource.endOfStream(e)}catch(e){s.default.log.warn("Failed to call media source endOfStream",e)}}},hn=e=>t=>{t.logger_(`Setting mediaSource duration to ${e}`);try{t.mediaSource.duration=e}catch(e){s.default.log.warn("Failed to set media source duration",e)}},cn=(e,t)=>i=>{const n=Zi(e),s=D(t);i.logger_(`Adding ${e}Buffer with codec ${t} to mediaSource`);const r=i.mediaSource.addSourceBuffer(s);r.addEventListener("updateend",i[`on${n}UpdateEnd_`]),r.addEventListener("error",i[`on${n}Error_`]),i.codecs[e]=t,i[`${e}Buffer`]=r},pn=e=>t=>{const i=t[`${e}Buffer`];if(sn(e,t),rn(t.mediaSource,i)){t.logger_(`Removing ${e}Buffer with codec ${t.codecs[e]} from mediaSource`);try{t.mediaSource.removeSourceBuffer(i)}catch(t){s.default.log.warn(`Failed to removeSourceBuffer ${e}Buffer`,t)}}},mn=e=>(t,i)=>{const n=i[`${t}Buffer`],s=D(e);rn(i.mediaSource,n)&&i.codecs[t]!==e&&(i.logger_(`changing ${t}Buffer codec from ${i.codecs[t]} to ${e}`),n.changeType(s),i.codecs[t]=e)},fn=({type:e,sourceUpdater:t,action:i,doneFn:n,name:s})=>{t.queue.push({type:e,action:i,doneFn:n,name:s}),nn(e,t)},gn=(e,t)=>i=>{if(t.queuePending[e]){const i=t.queuePending[e].doneFn;t.queuePending[e]=null,i&&i(t[`${e}Error_`])}nn(e,t)};class yn extends s.default.EventTarget{constructor(e){super(),this.mediaSource=e,this.sourceopenListener_=()=>nn("mediaSource",this),this.mediaSource.addEventListener("sourceopen",this.sourceopenListener_),this.logger_=h("SourceUpdater"),this.audioTimestampOffset_=0,this.videoTimestampOffset_=0,this.queue=[],this.queuePending={audio:null,video:null},this.delayedAudioAppendQueue_=[],this.videoAppendQueued_=!1,this.codecs={},this.onVideoUpdateEnd_=gn("video",this),this.onAudioUpdateEnd_=gn("audio",this),this.onVideoError_=e=>{this.videoError_=e},this.onAudioError_=e=>{this.audioError_=e},this.createdSourceBuffers_=!1,this.initializedEme_=!1,this.triggeredReady_=!1}initializedEme(){this.initializedEme_=!0,this.triggerReady()}hasCreatedSourceBuffers(){return this.createdSourceBuffers_}hasInitializedAnyEme(){return this.initializedEme_}ready(){return this.hasCreatedSourceBuffers()&&this.hasInitializedAnyEme()}createSourceBuffers(e){this.hasCreatedSourceBuffers()||(this.addOrChangeSourceBuffers(e),this.createdSourceBuffers_=!0,this.trigger("createdsourcebuffers"),this.triggerReady())}triggerReady(){this.ready()&&!this.triggeredReady_&&(this.triggeredReady_=!0,this.trigger("ready"))}addSourceBuffer(e,t){fn({type:"mediaSource",sourceUpdater:this,action:cn(e,t),name:"addSourceBuffer"})}abort(e){fn({type:e,sourceUpdater:this,action:(e,t)=>{if("open"!==t.mediaSource.readyState)return;const i=t[`${e}Buffer`];if(rn(t.mediaSource,i)){t.logger_(`calling abort on ${e}Buffer`);try{i.abort()}catch(t){s.default.log.warn(`Failed to abort on ${e}Buffer`,t)}}},name:"abort"})}removeSourceBuffer(e){this.canRemoveSourceBuffer()?fn({type:"mediaSource",sourceUpdater:this,action:pn(e),name:"removeSourceBuffer"}):s.default.log.error("removeSourceBuffer is not supported!")}canRemoveSourceBuffer(){return!s.default.browser.IE_VERSION&&!s.default.browser.IS_FIREFOX&&window.MediaSource&&window.MediaSource.prototype&&"function"==typeof window.MediaSource.prototype.removeSourceBuffer}static canChangeType(){return window.SourceBuffer&&window.SourceBuffer.prototype&&"function"==typeof window.SourceBuffer.prototype.changeType}canChangeType(){return this.constructor.canChangeType()}changeType(e,t){this.canChangeType()?fn({type:e,sourceUpdater:this,action:mn(t),name:"changeType"}):s.default.log.error("changeType is not supported!")}addOrChangeSourceBuffers(e){if(!e||"object"!=typeof e||0===Object.keys(e).length)throw new Error("Cannot addOrChangeSourceBuffers to undefined codecs");Object.keys(e).forEach((t=>{const i=e[t];if(!this.hasCreatedSourceBuffers())return this.addSourceBuffer(t,i);this.canChangeType()&&this.changeType(t,i)}))}appendBuffer(e,t){const{segmentInfo:i,type:n,bytes:s}=e;if(this.processedAppend_=!0,"audio"===n&&this.videoBuffer&&!this.videoAppendQueued_)return this.delayedAudioAppendQueue_.push([e,t]),void this.logger_(`delayed audio append of ${s.length} until video append`);if(fn({type:n,sourceUpdater:this,action:an(s,i||{mediaIndex:-1},t),doneFn:t,name:"appendBuffer"}),"video"===n){if(this.videoAppendQueued_=!0,!this.delayedAudioAppendQueue_.length)return;const e=this.delayedAudioAppendQueue_.slice();this.logger_(`queuing delayed audio ${e.length} appendBuffers`),this.delayedAudioAppendQueue_.length=0,e.forEach((e=>{this.appendBuffer.apply(this,e)}))}}audioBuffered(){return rn(this.mediaSource,this.audioBuffer)&&this.audioBuffer.buffered?this.audioBuffer.buffered:C()}videoBuffered(){return rn(this.mediaSource,this.videoBuffer)&&this.videoBuffer.buffered?this.videoBuffer.buffered:C()}buffered(){const e=rn(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,t=rn(this.mediaSource,this.audioBuffer)?this.audioBuffer:null;return t&&!e?this.audioBuffered():e&&!t?this.videoBuffered():function(e,t){let i=null,n=null,s=0;const r=[],a=[];if(!(e&&e.length&&t&&t.length))return C();let o=e.length;for(;o--;)r.push({time:e.start(o),type:"start"}),r.push({time:e.end(o),type:"end"});for(o=t.length;o--;)r.push({time:t.start(o),type:"start"}),r.push({time:t.end(o),type:"end"});for(r.sort((function(e,t){return e.time-t.time})),o=0;o<r.length;o++)"start"===r[o].type?(s++,2===s&&(i=r[o].time)):"end"===r[o].type&&(s--,1===s&&(n=r[o].time)),null!==i&&null!==n&&(a.push([i,n]),i=null,n=null);return C(a)}(this.audioBuffered(),this.videoBuffered())}setDuration(e,t=Ji){fn({type:"mediaSource",sourceUpdater:this,action:hn(e),name:"duration",doneFn:t})}endOfStream(e=null,t=Ji){"string"!=typeof e&&(e=void 0),fn({type:"mediaSource",sourceUpdater:this,action:ln(e),name:"endOfStream",doneFn:t})}removeAudio(e,t,i=Ji){this.audioBuffered().length&&0!==this.audioBuffered().end(0)?fn({type:"audio",sourceUpdater:this,action:on(e,t),doneFn:i,name:"remove"}):i()}removeVideo(e,t,i=Ji){this.videoBuffered().length&&0!==this.videoBuffered().end(0)?fn({type:"video",sourceUpdater:this,action:on(e,t),doneFn:i,name:"remove"}):i()}updating(){return!(!tn("audio",this)&&!tn("video",this))}audioTimestampOffset(e){return void 0!==e&&this.audioBuffer&&this.audioTimestampOffset_!==e&&(fn({type:"audio",sourceUpdater:this,action:dn(e),name:"timestampOffset"}),this.audioTimestampOffset_=e),this.audioTimestampOffset_}videoTimestampOffset(e){return void 0!==e&&this.videoBuffer&&this.videoTimestampOffset!==e&&(fn({type:"video",sourceUpdater:this,action:dn(e),name:"timestampOffset"}),this.videoTimestampOffset_=e),this.videoTimestampOffset_}audioQueueCallback(e){this.audioBuffer&&fn({type:"audio",sourceUpdater:this,action:un(e),name:"callback"})}videoQueueCallback(e){this.videoBuffer&&fn({type:"video",sourceUpdater:this,action:un(e),name:"callback"})}dispose(){this.trigger("dispose"),en.forEach((e=>{this.abort(e),this.canRemoveSourceBuffer()?this.removeSourceBuffer(e):this[`${e}QueueCallback`]((()=>sn(e,this)))})),this.videoAppendQueued_=!1,this.delayedAudioAppendQueue_.length=0,this.sourceopenListener_&&this.mediaSource.removeEventListener("sourceopen",this.sourceopenListener_),this.off()}}const _n=e=>decodeURIComponent(escape(String.fromCharCode.apply(null,e))),Tn=new Uint8Array("\n\n".split("").map((e=>e.charCodeAt(0))));class bn extends Ki{constructor(e,t={}){super(e,t),this.mediaSource_=null,this.subtitlesTrack_=null,this.loaderType_="subtitle",this.featuresNativeTextTracks_=e.featuresNativeTextTracks,this.shouldSaveSegmentTimingInfo_=!1}createTransmuxer_(){return null}buffered_(){if(!this.subtitlesTrack_||!this.subtitlesTrack_.cues||!this.subtitlesTrack_.cues.length)return C();const e=this.subtitlesTrack_.cues;return C([[e[0].startTime,e[e.length-1].startTime]])}initSegmentForMap(e,t=!1){if(!e)return null;const i=qe(e);let n=this.initSegments_[i];if(t&&!n&&e.bytes){const t=Tn.byteLength+e.bytes.byteLength,s=new Uint8Array(t);s.set(e.bytes),s.set(Tn,e.bytes.byteLength),this.initSegments_[i]=n={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:s}}return n||e}couldBeginLoading_(){return this.playlist_&&this.subtitlesTrack_&&!this.paused()}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}track(e){return void 0===e||(this.subtitlesTrack_=e,"INIT"===this.state&&this.couldBeginLoading_()&&this.init_()),this.subtitlesTrack_}remove(e,t){Wi(e,t,this.subtitlesTrack_)}fillBuffer_(){const e=this.chooseNextRequest_();if(e){if(null===this.syncController_.timestampOffsetForTimeline(e.timeline)){const e=()=>{this.state="READY",this.paused()||this.monitorBuffer_()};return this.syncController_.one("timestampoffset",e),void(this.state="WAITING_ON_TIMELINE")}this.loadSegment_(e)}}timestampOffsetForSegment_(){return null}chooseNextRequest_(){return this.skipEmptySegments_(super.chooseNextRequest_())}skipEmptySegments_(e){for(;e&&e.segment.empty;){if(e.mediaIndex+1>=e.playlist.segments.length){e=null;break}e=this.generateSegmentInfo_({playlist:e.playlist,mediaIndex:e.mediaIndex+1,startOfSegment:e.startOfSegment+e.duration,isSyncRequest:e.isSyncRequest})}return e}stopForError(e){this.error(e),this.state="READY",this.pause(),this.trigger("error")}segmentRequestFinished_(e,t,i){if(!this.subtitlesTrack_)return void(this.state="READY");if(this.saveTransferStats_(t.stats),!this.pendingSegment_)return this.state="READY",void(this.mediaRequestsAborted+=1);if(e)return e.code===bi&&this.handleTimeout_(),e.code===Si?this.mediaRequestsAborted+=1:this.mediaRequestsErrored+=1,void this.stopForError(e);const n=this.pendingSegment_;this.saveBandwidthRelatedStats_(n.duration,t.stats),t.key&&this.segmentKey(t.key,!0),this.state="APPENDING",this.trigger("appending");const s=n.segment;if(s.map&&(s.map.bytes=t.map.bytes),n.bytes=t.bytes,"function"!=typeof window.WebVTT&&this.subtitlesTrack_&&this.subtitlesTrack_.tech_){let n;const s=()=>{this.subtitlesTrack_.tech_.off("vttjsloaded",n),this.stopForError({message:"Error loading vtt.js"})};return n=()=>{this.subtitlesTrack_.tech_.off("vttjserror",s),this.segmentRequestFinished_(e,t,i)},this.state="WAITING_ON_VTTJS",this.subtitlesTrack_.tech_.one("vttjsloaded",n),void this.subtitlesTrack_.tech_.one("vttjserror",s)}s.requested=!0;try{this.parseVTTCues_(n)}catch(e){return void this.stopForError({message:e.message})}if(this.updateTimeMapping_(n,this.syncController_.timelines[n.timeline],this.playlist_),n.cues.length?n.timingInfo={start:n.cues[0].startTime,end:n.cues[n.cues.length-1].endTime}:n.timingInfo={start:n.startOfSegment,end:n.startOfSegment+n.duration},n.isSyncRequest)return this.trigger("syncinfoupdate"),this.pendingSegment_=null,void(this.state="READY");n.byteLength=n.bytes.byteLength,this.mediaSecondsLoaded+=s.duration,n.cues.forEach((e=>{this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_?new window.VTTCue(e.startTime,e.endTime,e.text):e)})),function(e){const t=e.cues;if(t)for(let i=0;i<t.length;i++){const n=[];let s=0;for(let e=0;e<t.length;e++)t[i].startTime===t[e].startTime&&t[i].endTime===t[e].endTime&&t[i].text===t[e].text&&(s++,s>1&&n.push(t[e]));n.length&&n.forEach((t=>e.removeCue(t)))}}(this.subtitlesTrack_),this.handleAppendsDone_()}handleData_(){}updateTimingInfoEnd_(){}parseVTTCues_(e){let t,i=!1;"function"==typeof window.TextDecoder?t=new window.TextDecoder("utf8"):(t=window.WebVTT.StringDecoder(),i=!0);const n=new window.WebVTT.Parser(window,window.vttjs,t);if(e.cues=[],e.timestampmap={MPEGTS:0,LOCAL:0},n.oncue=e.cues.push.bind(e.cues),n.ontimestampmap=t=>{e.timestampmap=t},n.onparsingerror=e=>{s.default.log.warn("Error encountered when parsing cues: "+e.message)},e.segment.map){let t=e.segment.map.bytes;i&&(t=_n(t)),n.parse(t)}let r=e.bytes;i&&(r=_n(r)),n.parse(r),n.flush()}updateTimeMapping_(e,t,i){const n=e.segment;if(!t)return;if(!e.cues.length)return void(n.empty=!0);const s=e.timestampmap,r=s.MPEGTS/Vi-s.LOCAL+t.mapping;if(e.cues.forEach((e=>{e.startTime+=r,e.endTime+=r})),!i.syncInfo){const t=e.cues[0].startTime,s=e.cues[e.cues.length-1].startTime;i.syncInfo={mediaSequence:i.mediaSequence+e.mediaIndex,time:Math.min(t,s-n.duration)}}}}const Sn=function(e,t){const i=e.cues;for(let e=0;e<i.length;e++){const n=i[e];if(t>=n.adStartTime&&t<=n.adEndTime)return n}return null},vn=[{name:"VOD",run:(e,t,i,n,s)=>i!==1/0?{time:0,segmentIndex:0,partIndex:null}:null},{name:"ProgramDateTime",run:(e,t,i,n,s)=>{if(!Object.keys(e.timelineToDatetimeMappings).length)return null;let r=null,a=null;const o=H(t);s=s||0;for(let i=0;i<o.length;i++){const n=o[t.endList||0===s?i:o.length-(i+1)],d=n.segment,u=e.timelineToDatetimeMappings[d.timeline];if(!u||!d.dateTimeObject)continue;let l=d.dateTimeObject.getTime()/1e3+u;if(d.parts&&"number"==typeof n.partIndex)for(let e=0;e<n.partIndex;e++)l+=d.parts[e].duration;const h=Math.abs(s-l);if(null!==a&&(0===h||a<h))break;a=h,r={time:l,segmentIndex:n.segmentIndex,partIndex:n.partIndex}}return r}},{name:"Segment",run:(e,t,i,n,s)=>{let r=null,a=null;s=s||0;const o=H(t);for(let e=0;e<o.length;e++){const i=o[t.endList||0===s?e:o.length-(e+1)],d=i.segment,u=i.part&&i.part.start||d&&d.start;if(d.timeline===n&&void 0!==u){const e=Math.abs(s-u);if(null!==a&&a<e)break;(!r||null===a||a>=e)&&(a=e,r={time:u,segmentIndex:i.segmentIndex,partIndex:i.partIndex})}}return r}},{name:"Discontinuity",run:(e,t,i,n,s)=>{let r=null;if(s=s||0,t.discontinuityStarts&&t.discontinuityStarts.length){let i=null;for(let n=0;n<t.discontinuityStarts.length;n++){const a=t.discontinuityStarts[n],o=t.discontinuitySequence+n+1,d=e.discontinuities[o];if(d){const e=Math.abs(s-d.time);if(null!==i&&i<e)break;(!r||null===i||i>=e)&&(i=e,r={time:d.time,segmentIndex:a,partIndex:null})}}}return r}},{name:"Playlist",run:(e,t,i,n,s)=>t.syncInfo?{time:t.syncInfo.time,segmentIndex:t.syncInfo.mediaSequence-t.mediaSequence,partIndex:null}:null}];class wn extends s.default.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={},this.logger_=h("SyncController")}getSyncPoint(e,t,i,n){const s=this.runStrategies_(e,t,i,n);return s.length?this.selectSyncPoint_(s,{key:"time",value:n}):null}getExpiredTime(e,t){if(!e||!e.segments)return null;const i=this.runStrategies_(e,t,e.discontinuitySequence,0);if(!i.length)return null;const n=this.selectSyncPoint_(i,{key:"segmentIndex",value:0});return n.segmentIndex>0&&(n.time*=-1),Math.abs(n.time+K({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:n.segmentIndex,endIndex:0}))}runStrategies_(e,t,i,n){const s=[];for(let r=0;r<vn.length;r++){const a=vn[r],o=a.run(this,e,t,i,n);o&&(o.strategy=a.name,s.push({strategy:a.name,syncPoint:o}))}return s}selectSyncPoint_(e,t){let i=e[0].syncPoint,n=Math.abs(e[0].syncPoint[t.key]-t.value),s=e[0].strategy;for(let r=1;r<e.length;r++){const a=Math.abs(e[r].syncPoint[t.key]-t.value);a<n&&(n=a,i=e[r].syncPoint,s=e[r].strategy)}return this.logger_(`syncPoint for [${t.key}: ${t.value}] chosen with strategy [${s}]: [time:${i.time}, segmentIndex:${i.segmentIndex}`+("number"==typeof i.partIndex?`,partIndex:${i.partIndex}`:"")+"]"),i}saveExpiredSegmentInfo(e,t){const i=t.mediaSequence-e.mediaSequence;if(i>86400)s.default.log.warn(`Not saving expired segment info. Media sequence gap ${i} is too large.`);else for(let n=i-1;n>=0;n--){const i=e.segments[n];if(i&&void 0!==i.start){t.syncInfo={mediaSequence:e.mediaSequence+n,time:i.start},this.logger_(`playlist refresh sync: [time:${t.syncInfo.time}, mediaSequence: ${t.syncInfo.mediaSequence}]`),this.trigger("syncinfoupdate");break}}}setDateTimeMappingForStart(e){if(this.timelineToDatetimeMappings={},e.segments&&e.segments.length&&e.segments[0].dateTimeObject){const t=e.segments[0],i=t.dateTimeObject.getTime()/1e3;this.timelineToDatetimeMappings[t.timeline]=-i}}saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:t}){const i=this.calculateSegmentTimeMapping_(e,e.timingInfo,t),n=e.segment;i&&(this.saveDiscontinuitySyncInfo_(e),e.playlist.syncInfo||(e.playlist.syncInfo={mediaSequence:e.playlist.mediaSequence+e.mediaIndex,time:n.start}));const s=n.dateTimeObject;n.discontinuity&&t&&s&&(this.timelineToDatetimeMappings[n.timeline]=-s.getTime()/1e3)}timestampOffsetForTimeline(e){return void 0===this.timelines[e]?null:this.timelines[e].time}mappingForTimeline(e){return void 0===this.timelines[e]?null:this.timelines[e].mapping}calculateSegmentTimeMapping_(e,t,i){const n=e.segment,s=e.part;let r,a,o=this.timelines[e.timeline];if("number"==typeof e.timestampOffset)o={time:e.startOfSegment,mapping:e.startOfSegment-t.start},i&&(this.timelines[e.timeline]=o,this.trigger("timestampoffset"),this.logger_(`time mapping for timeline ${e.timeline}: [time: ${o.time}] [mapping: ${o.mapping}]`)),r=e.startOfSegment,a=t.end+o.mapping;else{if(!o)return!1;r=t.start+o.mapping,a=t.end+o.mapping}return s&&(s.start=r,s.end=a),(!n.start||r<n.start)&&(n.start=r),n.end=a,!0}saveDiscontinuitySyncInfo_(e){const t=e.playlist,i=e.segment;if(i.discontinuity)this.discontinuities[i.timeline]={time:i.start,accuracy:0};else if(t.discontinuityStarts&&t.discontinuityStarts.length)for(let n=0;n<t.discontinuityStarts.length;n++){const s=t.discontinuityStarts[n],r=t.discontinuitySequence+n+1,a=s-e.mediaIndex,o=Math.abs(a);if(!this.discontinuities[r]||this.discontinuities[r].accuracy>o){let n;n=a<0?i.start-K({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:s}):i.end+K({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:s}),this.discontinuities[r]={time:n,accuracy:o}}}}dispose(){this.trigger("dispose"),this.off()}}class In extends s.default.EventTarget{constructor(){super(),this.pendingTimelineChanges_={},this.lastTimelineChanges_={}}clearPendingTimelineChange(e){this.pendingTimelineChanges_[e]=null,this.trigger("pendingtimelinechange")}pendingTimelineChange({type:e,from:t,to:i}){return"number"==typeof t&&"number"==typeof i&&(this.pendingTimelineChanges_[e]={type:e,from:t,to:i},this.trigger("pendingtimelinechange")),this.pendingTimelineChanges_[e]}lastTimelineChange({type:e,from:t,to:i}){return"number"==typeof t&&"number"==typeof i&&(this.lastTimelineChanges_[e]={type:e,from:t,to:i},delete this.pendingTimelineChanges_[e],this.trigger("timelinechange")),this.lastTimelineChanges_[e]}dispose(){this.trigger("dispose"),this.pendingTimelineChanges_={},this.lastTimelineChanges_={},this.off()}}const En=hi(ci((function(){var e=function(){function e(){this.listeners={}}var t=e.prototype;return t.on=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)},t.off=function(e,t){if(!this.listeners[e])return!1;var i=this.listeners[e].indexOf(t);return this.listeners[e]=this.listeners[e].slice(0),this.listeners[e].splice(i,1),i>-1},t.trigger=function(e){var t=this.listeners[e];if(t)if(2===arguments.length)for(var i=t.length,n=0;n<i;++n)t[n].call(this,arguments[1]);else for(var s=Array.prototype.slice.call(arguments,1),r=t.length,a=0;a<r;++a)t[a].apply(this,s)},t.dispose=function(){this.listeners={}},t.pipe=function(e){this.on("data",(function(t){e.push(t)}))},e}();
4/*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */let t=null;class i{constructor(e){let i,n,s;t||(t=function(){const e=[[[],[],[],[],[]],[[],[],[],[],[]]],t=e[0],i=e[1],n=t[4],s=i[4];let r,a,o;const d=[],u=[];let l,h,c,p,m,f;for(r=0;r<256;r++)u[(d[r]=r<<1^283*(r>>7))^r]=r;for(a=o=0;!n[a];a^=l||1,o=u[o]||1)for(p=o^o<<1^o<<2^o<<3^o<<4,p=p>>8^255&p^99,n[a]=p,s[p]=a,c=d[h=d[l=d[a]]],f=16843009*c^65537*h^257*l^16843008*a,m=257*d[p]^16843008*p,r=0;r<4;r++)t[r][a]=m=m<<24^m>>>8,i[r][p]=f=f<<24^f>>>8;for(r=0;r<5;r++)t[r]=t[r].slice(0),i[r]=i[r].slice(0);return e}()),this._tables=[[t[0][0].slice(),t[0][1].slice(),t[0][2].slice(),t[0][3].slice(),t[0][4].slice()],[t[1][0].slice(),t[1][1].slice(),t[1][2].slice(),t[1][3].slice(),t[1][4].slice()]];const r=this._tables[0][4],a=this._tables[1],o=e.length;let d=1;if(4!==o&&6!==o&&8!==o)throw new Error("Invalid aes key size");const u=e.slice(0),l=[];for(this._key=[u,l],i=o;i<4*o+28;i++)s=u[i-1],(i%o==0||8===o&&i%o==4)&&(s=r[s>>>24]<<24^r[s>>16&255]<<16^r[s>>8&255]<<8^r[255&s],i%o==0&&(s=s<<8^s>>>24^d<<24,d=d<<1^283*(d>>7))),u[i]=u[i-o]^s;for(n=0;i;n++,i--)s=u[3&n?i:i-4],l[n]=i<=4||n<4?s:a[0][r[s>>>24]]^a[1][r[s>>16&255]]^a[2][r[s>>8&255]]^a[3][r[255&s]]}decrypt(e,t,i,n,s,r){const a=this._key[1];let o,d,u,l=e^a[0],h=n^a[1],c=i^a[2],p=t^a[3];const m=a.length/4-2;let f,g=4;const y=this._tables[1],_=y[0],T=y[1],b=y[2],S=y[3],v=y[4];for(f=0;f<m;f++)o=_[l>>>24]^T[h>>16&255]^b[c>>8&255]^S[255&p]^a[g],d=_[h>>>24]^T[c>>16&255]^b[p>>8&255]^S[255&l]^a[g+1],u=_[c>>>24]^T[p>>16&255]^b[l>>8&255]^S[255&h]^a[g+2],p=_[p>>>24]^T[l>>16&255]^b[h>>8&255]^S[255&c]^a[g+3],g+=4,l=o,h=d,c=u;for(f=0;f<4;f++)s[(3&-f)+r]=v[l>>>24]<<24^v[h>>16&255]<<16^v[c>>8&255]<<8^v[255&p]^a[g++],o=l,l=h,h=c,c=p,p=o}}class n extends e{constructor(){super(e),this.jobs=[],this.delay=1,this.timeout_=null}processJob_(){this.jobs.shift()(),this.jobs.length?this.timeout_=setTimeout(this.processJob_.bind(this),this.delay):this.timeout_=null}push(e){this.jobs.push(e),this.timeout_||(this.timeout_=setTimeout(this.processJob_.bind(this),this.delay))}}const s=function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24};class r{constructor(e,t,i,a){const o=r.STEP,d=new Int32Array(e.buffer),u=new Uint8Array(e.byteLength);let l=0;for(this.asyncStream_=new n,this.asyncStream_.push(this.decryptChunk_(d.subarray(l,l+o),t,i,u)),l=o;l<d.length;l+=o)i=new Uint32Array([s(d[l-4]),s(d[l-3]),s(d[l-2]),s(d[l-1])]),this.asyncStream_.push(this.decryptChunk_(d.subarray(l,l+o),t,i,u));this.asyncStream_.push((function(){var e;
5/*! @name aes-decrypter @version 4.0.1 @license Apache-2.0 */a(null,(e=u).subarray(0,e.byteLength-e[e.byteLength-1]))}))}static get STEP(){return 32e3}decryptChunk_(e,t,n,r){return function(){const a=function(e,t,n){const r=new Int32Array(e.buffer,e.byteOffset,e.byteLength>>2),a=new i(Array.prototype.slice.call(t)),o=new Uint8Array(e.byteLength),d=new Int32Array(o.buffer);let u,l,h,c,p,m,f,g,y;for(u=n[0],l=n[1],h=n[2],c=n[3],y=0;y<r.length;y+=4)p=s(r[y]),m=s(r[y+1]),f=s(r[y+2]),g=s(r[y+3]),a.decrypt(p,m,f,g,d,y),d[y]=s(d[y]^u),d[y+1]=s(d[y+1]^l),d[y+2]=s(d[y+2]^h),d[y+3]=s(d[y+3]^c),u=p,l=m,h=f,c=g;return o}(e,t,n);r.set(a,e.byteOffset)}}}var a="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},o=("undefined"!=typeof window?window:void 0!==a?a:"undefined"!=typeof self?self:{}).BigInt||Number;o("0x1"),o("0x100"),o("0x10000"),o("0x1000000"),o("0x100000000"),o("0x10000000000"),o("0x1000000000000"),o("0x100000000000000"),o("0x10000000000000000"),function(){var e=new Uint16Array([65484]),t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);255===t[0]||t[0]}();self.onmessage=function(e){const t=e.data,i=new Uint8Array(t.encrypted.bytes,t.encrypted.byteOffset,t.encrypted.byteLength),n=new Uint32Array(t.key.bytes,t.key.byteOffset,t.key.byteLength/4),s=new Uint32Array(t.iv.bytes,t.iv.byteOffset,t.iv.byteLength/4);new r(i,n,s,(function(e,i){self.postMessage(function(e){const t={};return Object.keys(e).forEach((i=>{const n=e[i];var s;s=n,("function"===ArrayBuffer.isView?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer)?t[i]={bytes:n.buffer,byteOffset:n.byteOffset,byteLength:n.byteLength}:t[i]=n})),t}({source:t.source,decrypted:i}),[i.buffer])}))}})));var An=li(En);const Ln=e=>{let t=e.default?"main":"alternative";return e.characteristics&&e.characteristics.indexOf("public.accessibility.describes-video")>=0&&(t="main-desc"),t},xn=(e,t)=>{e.abort(),e.pause(),t&&t.activePlaylistLoader&&(t.activePlaylistLoader.pause(),t.activePlaylistLoader=null)},Dn=(e,t)=>{t.activePlaylistLoader=e,e.load()},kn={AUDIO:(e,t)=>()=>{const{segmentLoaders:{[e]:i},mediaTypes:{[e]:n},excludePlaylist:r}=t;xn(i,n);const a=n.activeTrack(),o=n.activeGroup(),d=(o.filter((e=>e.default))[0]||o[0]).id,u=n.tracks[d];if(a!==u){s.default.log.warn("Problem encountered loading the alternate audio track.Switching back to default.");for(const e in n.tracks)n.tracks[e].enabled=n.tracks[e]===u;n.onTrackChanged()}else r({error:{message:"Problem encountered loading the default audio track."}})},SUBTITLES:(e,t)=>()=>{const{segmentLoaders:{[e]:i},mediaTypes:{[e]:n}}=t;s.default.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track."),xn(i,n);const r=n.activeTrack();r&&(r.mode="disabled"),n.onTrackChanged()}},On={AUDIO:(e,t,i)=>{if(!t)return;const{tech:n,requestOptions:s,segmentLoaders:{[e]:r}}=i;t.on("loadedmetadata",(()=>{const e=t.media();r.playlist(e,s),(!n.paused()||e.endList&&"none"!==n.preload())&&r.load()})),t.on("loadedplaylist",(()=>{r.playlist(t.media(),s),n.paused()||r.load()})),t.on("error",kn[e](e,i))},SUBTITLES:(e,t,i)=>{const{tech:n,requestOptions:s,segmentLoaders:{[e]:r},mediaTypes:{[e]:a}}=i;t.on("loadedmetadata",(()=>{const e=t.media();r.playlist(e,s),r.track(a.activeTrack()),(!n.paused()||e.endList&&"none"!==n.preload())&&r.load()})),t.on("loadedplaylist",(()=>{r.playlist(t.media(),s),n.paused()||r.load()})),t.on("error",kn[e](e,i))}},Pn={AUDIO:(e,t)=>{const{vhs:i,sourceType:n,segmentLoaders:{[e]:r},requestOptions:a,main:{mediaGroups:o},mediaTypes:{[e]:{groups:d,tracks:u,logger_:l}},mainPlaylistLoader:h}=t,c=ae(h.main);o[e]&&0!==Object.keys(o[e]).length||(o[e]={main:{default:{default:!0}}},c&&(o[e].main.default.playlists=h.main.playlists));for(const r in o[e]){d[r]||(d[r]=[]);for(const p in o[e][r]){let m,f=o[e][r][p];if(c?(l(`AUDIO group '${r}' label '${p}' is a main playlist`),f.isMainPlaylist=!0,m=null):m="vhs-json"===n&&f.playlists?new be(f.playlists[0],i,a):f.resolvedUri?new be(f.resolvedUri,i,a):f.playlists&&"dash"===n?new oi(f.playlists[0],i,a,h):null,f=U({id:p,playlistLoader:m},f),On[e](e,f.playlistLoader,t),d[r].push(f),void 0===u[p]){const e=new s.default.AudioTrack({id:p,kind:Ln(f),enabled:!1,language:f.language,default:f.default,label:p});u[p]=e}}}r.on("error",kn[e](e,t))},SUBTITLES:(e,t)=>{const{tech:i,vhs:n,sourceType:s,segmentLoaders:{[e]:r},requestOptions:a,main:{mediaGroups:o},mediaTypes:{[e]:{groups:d,tracks:u}},mainPlaylistLoader:l}=t;for(const r in o[e]){d[r]||(d[r]=[]);for(const h in o[e][r]){if(o[e][r][h].forced)continue;let c,p=o[e][r][h];if("hls"===s)c=new be(p.resolvedUri,n,a);else if("dash"===s){if(!p.playlists.filter((e=>e.excludeUntil!==1/0)).length)return;c=new oi(p.playlists[0],n,a,l)}else"vhs-json"===s&&(c=new be(p.playlists?p.playlists[0]:p.resolvedUri,n,a));if(p=U({id:h,playlistLoader:c},p),On[e](e,p.playlistLoader,t),d[r].push(p),void 0===u[h]){const e=i.addRemoteTextTrack({id:h,kind:"subtitles",default:p.default&&p.autoselect,language:p.language,label:h},!1).track;u[h]=e}}}r.on("error",kn[e](e,t))},"CLOSED-CAPTIONS":(e,t)=>{const{tech:i,main:{mediaGroups:n},mediaTypes:{[e]:{groups:s,tracks:r}}}=t;for(const t in n[e]){s[t]||(s[t]=[]);for(const a in n[e][t]){const o=n[e][t][a];if(!/^(?:CC|SERVICE)/.test(o.instreamId))continue;const d=i.options_.vhs&&i.options_.vhs.captionServices||{};let u={label:a,language:o.language,instreamId:o.instreamId,default:o.default&&o.autoselect};if(d[u.instreamId]&&(u=U(u,d[u.instreamId])),void 0===u.default&&delete u.default,s[t].push(U({id:a},o)),void 0===r[a]){const e=i.addRemoteTextTrack({id:u.instreamId,kind:"captions",default:u.default,language:u.language,label:u.label},!1).track;r[a]=e}}}}},Un=(e,t)=>{for(let i=0;i<e.length;i++){if(se(t,e[i]))return!0;if(e[i].playlists&&Un(e[i].playlists,t))return!0}return!1},Cn={AUDIO:(e,t)=>()=>{const{mediaTypes:{[e]:{tracks:i}}}=t;for(const e in i)if(i[e].enabled)return i[e];return null},SUBTITLES:(e,t)=>()=>{const{mediaTypes:{[e]:{tracks:i}}}=t;for(const e in i)if("showing"===i[e].mode||"hidden"===i[e].mode)return i[e];return null}};let Rn;const Mn=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],Bn=function(e){return this.audioSegmentLoader_[e]+this.mainSegmentLoader_[e]};class Nn extends s.default.EventTarget{constructor(e){super();const{src:t,withCredentials:i,tech:n,bandwidth:s,externVhs:r,useCueTags:a,playlistExclusionDuration:o,enableLowInitialPlaylist:d,sourceType:u,cacheEncryptionKeys:l,bufferBasedABR:c,leastPixelDiffSelector:p,captionServices:m}=e;if(!t)throw new Error("A non-empty playlist URL or JSON manifest string is required");let{maxPlaylistRetries:f}=e;null==f&&(f=1/0),Rn=r,this.bufferBasedABR=Boolean(c),this.leastPixelDiffSelector=Boolean(p),this.withCredentials=i,this.tech_=n,this.vhs_=n.vhs,this.sourceType_=u,this.useCueTags_=a,this.playlistExclusionDuration=o,this.maxPlaylistRetries=f,this.enableLowInitialPlaylist=d,this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack("metadata","ad-cues"),this.cueTagsTrack_.inBandMetadataTrackDispatchType=""),this.requestOptions_={withCredentials:i,maxPlaylistRetries:f,timeout:null},this.on("error",this.pauseLoading),this.mediaTypes_=(()=>{const e={};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((t=>{e[t]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:Ji,activeTrack:Ji,getActiveGroup:Ji,onGroupChanged:Ji,onTrackChanged:Ji,lastTrack_:null,logger_:h(`MediaGroups[${t}]`)}})),e})(),this.mediaSource=new window.MediaSource,this.handleDurationChange_=this.handleDurationChange_.bind(this),this.handleSourceOpen_=this.handleSourceOpen_.bind(this),this.handleSourceEnded_=this.handleSourceEnded_.bind(this),this.mediaSource.addEventListener("durationchange",this.handleDurationChange_),this.mediaSource.addEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.addEventListener("sourceended",this.handleSourceEnded_),this.seekable_=C(),this.hasPlayed_=!1,this.syncController_=new wn(e),this.segmentMetadataTrack_=n.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.decrypter_=new An,this.sourceUpdater_=new yn(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new In;const g={vhs:this.vhs_,parse708captions:e.parse708captions,useDtsForTimestampOffset:e.useDtsForTimestampOffset,captionServices:m,mediaSource:this.mediaSource,currentTime:this.tech_.currentTime.bind(this.tech_),seekable:()=>this.seekable(),seeking:()=>this.tech_.seeking(),duration:()=>this.duration(),hasPlayed:()=>this.hasPlayed_,goalBufferLength:()=>this.goalBufferLength(),bandwidth:s,syncController:this.syncController_,decrypter:this.decrypter_,sourceType:this.sourceType_,inbandTextTracks:this.inbandTextTracks_,cacheEncryptionKeys:l,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:e.exactManifestTimings};this.mainPlaylistLoader_="dash"===this.sourceType_?new oi(t,this.vhs_,this.requestOptions_):new be(t,this.vhs_,this.requestOptions_),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new Ki(U(g,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),e),this.audioSegmentLoader_=new Ki(U(g,{loaderType:"audio"}),e),this.subtitleSegmentLoader_=new bn(U(g,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks}),e),this.setupSegmentLoaderListeners_(),this.bufferBasedABR&&(this.mainPlaylistLoader_.one("loadedplaylist",(()=>this.startABRTimer_())),this.tech_.on("pause",(()=>this.stopABRTimer_())),this.tech_.on("play",(()=>this.startABRTimer_()))),Mn.forEach((e=>{this[e+"_"]=Bn.bind(this,e)})),this.logger_=h("pc"),this.triggeredFmp4Usage=!1,"none"===this.tech_.preload()?(this.loadOnPlay_=()=>{this.loadOnPlay_=null,this.mainPlaylistLoader_.load()},this.tech_.one("play",this.loadOnPlay_)):this.mainPlaylistLoader_.load(),this.timeToLoadedData__=-1,this.mainAppendsToLoadedData__=-1,this.audioAppendsToLoadedData__=-1;const y="none"===this.tech_.preload()?"play":"loadstart";this.tech_.one(y,(()=>{const e=Date.now();this.tech_.one("loadeddata",(()=>{this.timeToLoadedData__=Date.now()-e,this.mainAppendsToLoadedData__=this.mainSegmentLoader_.mediaAppends,this.audioAppendsToLoadedData__=this.audioSegmentLoader_.mediaAppends}))}))}mainAppendsToLoadedData_(){return this.mainAppendsToLoadedData__}audioAppendsToLoadedData_(){return this.audioAppendsToLoadedData__}appendsToLoadedData_(){const e=this.mainAppendsToLoadedData_(),t=this.audioAppendsToLoadedData_();return-1===e||-1===t?-1:e+t}timeToLoadedData_(){return this.timeToLoadedData__}checkABR_(){const e=this.selectPlaylist();e&&this.shouldSwitchToMedia_(e)&&this.switchMedia_(e,"abr")}switchMedia_(e,t,i){const n=this.media(),s=n&&(n.id||n.uri),r=e.id||e.uri;s&&s!==r&&(this.logger_(`switch media ${s} -> ${r} from ${t}`),this.tech_.trigger({type:"usage",name:`vhs-rendition-change-${t}`})),this.mainPlaylistLoader_.media(e,i)}startABRTimer_(){this.stopABRTimer_(),this.abrTimer_=window.setInterval((()=>this.checkABR_()),250)}stopABRTimer_(){this.tech_.scrubbing&&this.tech_.scrubbing()||(window.clearInterval(this.abrTimer_),this.abrTimer_=null)}getAudioTrackPlaylists_(){const e=this.main(),t=e&&e.playlists||[];if(!e||!e.mediaGroups||!e.mediaGroups.AUDIO)return t;const i=e.mediaGroups.AUDIO,n=Object.keys(i);let s;if(Object.keys(this.mediaTypes_.AUDIO.groups).length)s=this.mediaTypes_.AUDIO.activeTrack();else{const e=i.main||n.length&&i[n[0]];for(const t in e)if(e[t].default){s={label:t};break}}if(!s)return t;const r=[];for(const t in i)if(i[t][s.label]){const n=i[t][s.label];if(n.playlists&&n.playlists.length)r.push.apply(r,n.playlists);else if(n.uri)r.push(n);else if(e.playlists.length)for(let i=0;i<e.playlists.length;i++){const n=e.playlists[i];n.attributes&&n.attributes.AUDIO&&n.attributes.AUDIO===t&&r.push(n)}}return r.length?r:t}setupMainPlaylistLoaderListeners_(){this.mainPlaylistLoader_.on("loadedmetadata",(()=>{const e=this.mainPlaylistLoader_.media(),t=1.5*e.targetDuration*1e3;ne(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=t,e.endList&&"none"!==this.tech_.preload()&&(this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.mainSegmentLoader_.load()),(e=>{["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((t=>{Pn[t](t,e)}));const{mediaTypes:t,mainPlaylistLoader:i,tech:n,vhs:s,segmentLoaders:{AUDIO:r,main:a}}=e;["AUDIO","SUBTITLES"].forEach((i=>{t[i].activeGroup=((e,t)=>i=>{const{mainPlaylistLoader:n,mediaTypes:{[e]:{groups:s}}}=t,r=n.media();if(!r)return null;let a=null;r.attributes[e]&&(a=s[r.attributes[e]]);const o=Object.keys(s);if(!a)if("AUDIO"===e&&o.length>1&&ae(t.main))for(let e=0;e<o.length;e++){const t=s[o[e]];if(Un(t,r)){a=t;break}}else s.main?a=s.main:1===o.length&&(a=s[o[0]]);return void 0===i?a:null!==i&&a&&a.filter((e=>e.id===i.id))[0]||null})(i,e),t[i].activeTrack=Cn[i](i,e),t[i].onGroupChanged=((e,t)=>()=>{const{segmentLoaders:{[e]:i,main:n},mediaTypes:{[e]:s}}=t,r=s.activeTrack(),a=s.getActiveGroup(),o=s.activePlaylistLoader,d=s.lastGroup_;a&&d&&a.id===d.id||(s.lastGroup_=a,s.lastTrack_=r,xn(i,s),a&&!a.isMainPlaylist&&(a.playlistLoader?(i.resyncLoader(),Dn(a.playlistLoader,s)):o&&n.resetEverything()))})(i,e),t[i].onGroupChanging=((e,t)=>()=>{const{segmentLoaders:{[e]:i},mediaTypes:{[e]:n}}=t;n.lastGroup_=null,i.abort(),i.pause()})(i,e),t[i].onTrackChanged=((e,t)=>()=>{const{mainPlaylistLoader:i,segmentLoaders:{[e]:n,main:s},mediaTypes:{[e]:r}}=t,a=r.activeTrack(),o=r.getActiveGroup(),d=r.activePlaylistLoader,u=r.lastTrack_;if((!u||!a||u.id!==a.id)&&(r.lastGroup_=o,r.lastTrack_=a,xn(n,r),o)){if(o.isMainPlaylist){if(!a||!u||a.id===u.id)return;const e=t.vhs.playlistController_,n=e.selectPlaylist();if(e.media()===n)return;return r.logger_(`track change. Switching main audio from ${u.id} to ${a.id}`),i.pause(),s.resetEverything(),void e.fastQualityChange_(n)}if("AUDIO"===e){if(!o.playlistLoader)return s.setAudio(!0),void s.resetEverything();n.setAudio(!0),s.setAudio(!1)}d!==o.playlistLoader?(n.track&&n.track(a),n.resetEverything(),Dn(o.playlistLoader,r)):Dn(o.playlistLoader,r)}})(i,e),t[i].getActiveGroup=((e,{mediaTypes:t})=>()=>{const i=t[e].activeTrack();return i?t[e].activeGroup(i):null})(i,e)}));const o=t.AUDIO.activeGroup();if(o){const e=(o.filter((e=>e.default))[0]||o[0]).id;t.AUDIO.tracks[e].enabled=!0,t.AUDIO.onGroupChanged(),t.AUDIO.onTrackChanged(),t.AUDIO.getActiveGroup().playlistLoader?(a.setAudio(!1),r.setAudio(!0)):a.setAudio(!0)}i.on("mediachange",(()=>{["AUDIO","SUBTITLES"].forEach((e=>t[e].onGroupChanged()))})),i.on("mediachanging",(()=>{["AUDIO","SUBTITLES"].forEach((e=>t[e].onGroupChanging()))}));const d=()=>{t.AUDIO.onTrackChanged(),n.trigger({type:"usage",name:"vhs-audio-change"})};n.audioTracks().addEventListener("change",d),n.remoteTextTracks().addEventListener("change",t.SUBTITLES.onTrackChanged),s.on("dispose",(()=>{n.audioTracks().removeEventListener("change",d),n.remoteTextTracks().removeEventListener("change",t.SUBTITLES.onTrackChanged)})),n.clearTracks("audio");for(const e in t.AUDIO.tracks)n.audioTracks().addTrack(t.AUDIO.tracks[e])})({sourceType:this.sourceType_,segmentLoaders:{AUDIO:this.audioSegmentLoader_,SUBTITLES:this.subtitleSegmentLoader_,main:this.mainSegmentLoader_},tech:this.tech_,requestOptions:this.requestOptions_,mainPlaylistLoader:this.mainPlaylistLoader_,vhs:this.vhs_,main:this.main(),mediaTypes:this.mediaTypes_,excludePlaylist:this.excludePlaylist.bind(this)}),this.triggerPresenceUsage_(this.main(),e),this.setupFirstPlay(),!this.mediaTypes_.AUDIO.activePlaylistLoader||this.mediaTypes_.AUDIO.activePlaylistLoader.media()?this.trigger("selectedinitialmedia"):this.mediaTypes_.AUDIO.activePlaylistLoader.one("loadedmetadata",(()=>{this.trigger("selectedinitialmedia")}))})),this.mainPlaylistLoader_.on("loadedplaylist",(()=>{this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_);let e=this.mainPlaylistLoader_.media();if(!e){let t;if(this.excludeUnsupportedVariants_(),this.enableLowInitialPlaylist&&(t=this.selectInitialPlaylist()),t||(t=this.selectPlaylist()),!t||!this.shouldSwitchToMedia_(t))return;if(this.initialMedia_=t,this.switchMedia_(this.initialMedia_,"initial"),"vhs-json"!==this.sourceType_||!this.initialMedia_.segments)return;e=this.initialMedia_}this.handleUpdatedMediaPlaylist(e)})),this.mainPlaylistLoader_.on("error",(()=>{const e=this.mainPlaylistLoader_.error;this.excludePlaylist({playlistToExclude:e.playlist,error:e})})),this.mainPlaylistLoader_.on("mediachanging",(()=>{this.mainSegmentLoader_.abort(),this.mainSegmentLoader_.pause()})),this.mainPlaylistLoader_.on("mediachange",(()=>{const e=this.mainPlaylistLoader_.media(),t=1.5*e.targetDuration*1e3;ne(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=t,this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.mainSegmentLoader_.load(),this.tech_.trigger({type:"mediachange",bubbles:!0})})),this.mainPlaylistLoader_.on("playlistunchanged",(()=>{const e=this.mainPlaylistLoader_.media();"playlist-unchanged"!==e.lastExcludeReason_&&this.stuckAtPlaylistEnd_(e)&&(this.excludePlaylist({error:{message:"Playlist no longer updating.",reason:"playlist-unchanged"}}),this.tech_.trigger("playliststuck"))})),this.mainPlaylistLoader_.on("renditiondisabled",(()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-disabled"})})),this.mainPlaylistLoader_.on("renditionenabled",(()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-enabled"})}))}handleUpdatedMediaPlaylist(e){this.useCueTags_&&this.updateAdCues_(e),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.updateDuration(!e.endList),this.tech_.paused()||(this.mainSegmentLoader_.load(),this.audioSegmentLoader_&&this.audioSegmentLoader_.load())}triggerPresenceUsage_(e,t){const i=e.mediaGroups||{};let n=!0;const s=Object.keys(i.AUDIO);for(const e in i.AUDIO)for(const t in i.AUDIO[e])i.AUDIO[e][t].uri||(n=!1);n&&this.tech_.trigger({type:"usage",name:"vhs-demuxed"}),Object.keys(i.SUBTITLES).length&&this.tech_.trigger({type:"usage",name:"vhs-webvtt"}),Rn.Playlist.isAes(t)&&this.tech_.trigger({type:"usage",name:"vhs-aes"}),s.length&&Object.keys(i.AUDIO[s[0]]).length>1&&this.tech_.trigger({type:"usage",name:"vhs-alternate-audio"}),this.useCueTags_&&this.tech_.trigger({type:"usage",name:"vhs-playlist-cue-tags"})}shouldSwitchToMedia_(e){const t=this.mainPlaylistLoader_.media()||this.mainPlaylistLoader_.pendingMedia_,i=this.tech_.currentTime(),n=this.bufferLowWaterLine(),r=this.bufferHighWaterLine();return function({currentPlaylist:e,buffered:t,currentTime:i,nextPlaylist:n,bufferLowWaterLine:r,bufferHighWaterLine:a,duration:o,bufferBasedABR:d,log:u}){if(!n)return s.default.log.warn("We received no playlist to switch to. Please check your stream."),!1;const l=`allowing switch ${e&&e.id||"null"} -> ${n.id}`;if(!e)return u(`${l} as current playlist is not set`),!0;if(n.id===e.id)return!1;const h=Boolean(N(t,i).length);if(!e.endList)return h||"number"!=typeof e.partTargetDuration?(u(`${l} as current playlist is live`),!0):(u(`not ${l} as current playlist is live llhls, but currentTime isn't in buffered.`),!1);const c=G(t,i),p=d?di.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:di.MAX_BUFFER_LOW_WATER_LINE;if(o<p)return u(`${l} as duration < max low water line (${o} < ${p})`),!0;const m=n.attributes.BANDWIDTH,f=e.attributes.BANDWIDTH;if(m<f&&(!d||c<a)){let e=`${l} as next bandwidth < current bandwidth (${m} < ${f})`;return d&&(e+=` and forwardBuffer < bufferHighWaterLine (${c} < ${a})`),u(e),!0}if((!d||m>f)&&c>=r){let e=`${l} as forwardBuffer >= bufferLowWaterLine (${c} >= ${r})`;return d&&(e+=` and next bandwidth > current bandwidth (${m} > ${f})`),u(e),!0}return u(`not ${l} as no switching criteria met`),!1}({buffered:this.tech_.buffered(),currentTime:i,currentPlaylist:t,nextPlaylist:e,bufferLowWaterLine:n,bufferHighWaterLine:r,duration:this.duration(),bufferBasedABR:this.bufferBasedABR,log:this.logger_})}setupSegmentLoaderListeners_(){this.bufferBasedABR||(this.mainSegmentLoader_.on("bandwidthupdate",(()=>{const e=this.selectPlaylist();this.shouldSwitchToMedia_(e)&&this.switchMedia_(e,"bandwidthupdate"),this.tech_.trigger("bandwidthupdate")})),this.mainSegmentLoader_.on("progress",(()=>{this.trigger("progress")}))),this.mainSegmentLoader_.on("error",(()=>{const e=this.mainSegmentLoader_.error();this.excludePlaylist({playlistToExclude:e.playlist,error:e})})),this.mainSegmentLoader_.on("appenderror",(()=>{this.error=this.mainSegmentLoader_.error_,this.trigger("error")})),this.mainSegmentLoader_.on("syncinfoupdate",(()=>{this.onSyncInfoUpdate_()})),this.mainSegmentLoader_.on("timestampoffset",(()=>{this.tech_.trigger({type:"usage",name:"vhs-timestamp-offset"})})),this.audioSegmentLoader_.on("syncinfoupdate",(()=>{this.onSyncInfoUpdate_()})),this.audioSegmentLoader_.on("appenderror",(()=>{this.error=this.audioSegmentLoader_.error_,this.trigger("error")})),this.mainSegmentLoader_.on("ended",(()=>{this.logger_("main segment loader ended"),this.onEndOfStream()})),this.mainSegmentLoader_.on("earlyabort",(e=>{this.bufferBasedABR||(this.delegateLoaders_("all",["abort"]),this.excludePlaylist({error:{message:"Aborted early because there isn't enough bandwidth to complete the request without rebuffering."},playlistExclusionDuration:120}))}));const e=()=>{if(!this.sourceUpdater_.hasCreatedSourceBuffers())return this.tryToCreateSourceBuffers_();const e=this.getCodecsOrExclude_();e&&this.sourceUpdater_.addOrChangeSourceBuffers(e)};this.mainSegmentLoader_.on("trackinfo",e),this.audioSegmentLoader_.on("trackinfo",e),this.mainSegmentLoader_.on("fmp4",(()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)})),this.audioSegmentLoader_.on("fmp4",(()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)})),this.audioSegmentLoader_.on("ended",(()=>{this.logger_("audioSegmentLoader ended"),this.onEndOfStream()}))}mediaSecondsLoaded_(){return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded+this.mainSegmentLoader_.mediaSecondsLoaded)}load(){this.mainSegmentLoader_.load(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.load(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.load()}fastQualityChange_(e=this.selectPlaylist()){e!==this.mainPlaylistLoader_.media()?(this.switchMedia_(e,"fast-quality"),this.mainSegmentLoader_.resetEverything((()=>{s.default.browser.IE_VERSION||s.default.browser.IS_EDGE?this.tech_.setCurrentTime(this.tech_.currentTime()+.04):this.tech_.setCurrentTime(this.tech_.currentTime())}))):this.logger_("skipping fastQualityChange because new media is same as old")}play(){if(this.setupFirstPlay())return;this.tech_.ended()&&this.tech_.setCurrentTime(0),this.hasPlayed_&&this.load();const e=this.tech_.seekable();return this.tech_.duration()===1/0&&this.tech_.currentTime()<e.start(0)?this.tech_.setCurrentTime(e.end(e.length-1)):void 0}setupFirstPlay(){const e=this.mainPlaylistLoader_.media();if(!e||this.tech_.paused()||this.hasPlayed_)return!1;if(!e.endList){const e=this.seekable();if(!e.length)return!1;if(s.default.browser.IE_VERSION&&0===this.tech_.readyState())return this.tech_.one("loadedmetadata",(()=>{this.trigger("firstplay"),this.tech_.setCurrentTime(e.end(0)),this.hasPlayed_=!0})),!1;this.trigger("firstplay"),this.tech_.setCurrentTime(e.end(0))}return this.hasPlayed_=!0,this.load(),!0}handleSourceOpen_(){if(this.tryToCreateSourceBuffers_(),this.tech_.autoplay()){const e=this.tech_.play();void 0!==e&&"function"==typeof e.then&&e.then(null,(e=>{}))}this.trigger("sourceopen")}handleSourceEnded_(){if(!this.inbandTextTracks_.metadataTrack_)return;const e=this.inbandTextTracks_.metadataTrack_.cues;if(!e||!e.length)return;const t=this.duration();e[e.length-1].endTime=isNaN(t)||Math.abs(t)===1/0?Number.MAX_VALUE:t}handleDurationChange_(){this.tech_.trigger("durationchange")}onEndOfStream(){let e=this.mainSegmentLoader_.ended_;if(this.mediaTypes_.AUDIO.activePlaylistLoader){const t=this.mainSegmentLoader_.getCurrentMediaInfo_();e=!t||t.hasVideo?e&&this.audioSegmentLoader_.ended_:this.audioSegmentLoader_.ended_}e&&(this.stopABRTimer_(),this.sourceUpdater_.endOfStream())}stuckAtPlaylistEnd_(e){if(!this.seekable().length)return!1;const t=this.syncController_.getExpiredTime(e,this.duration());if(null===t)return!1;const i=Rn.Playlist.playlistEnd(e,t),n=this.tech_.currentTime(),s=this.tech_.buffered();if(!s.length)return i-n<=M;const r=s.end(s.length-1);return r-n<=M&&i-r<=M}excludePlaylist({playlistToExclude:e=this.mainPlaylistLoader_.media(),error:t={},playlistExclusionDuration:i}){if(e=e||this.mainPlaylistLoader_.media(),i=i||t.playlistExclusionDuration||this.playlistExclusionDuration,!e)return this.error=t,void("open"!==this.mediaSource.readyState?this.trigger("error"):this.sourceUpdater_.endOfStream("network"));e.playlistErrors_++;const n=this.mainPlaylistLoader_.main.playlists,r=n.filter(te),a=1===r.length&&r[0]===e;if(1===n.length&&i!==1/0)return s.default.log.warn(`Problem encountered with playlist ${e.id}. Trying again since it is the only playlist.`),this.tech_.trigger("retryplaylist"),this.mainPlaylistLoader_.load(a);if(a){let t=!1;n.forEach((i=>{if(i===e)return;const n=i.excludeUntil;void 0!==n&&n!==1/0&&(t=!0,delete i.excludeUntil)})),t&&(s.default.log.warn("Removing other playlists from the exclusion list because the last rendition is about to be excluded."),this.tech_.trigger("retryplaylist"))}let o;o=e.playlistErrors_>this.maxPlaylistRetries?1/0:Date.now()+1e3*i,e.excludeUntil=o,t.reason&&(e.lastExcludeReason_=t.reason),this.tech_.trigger("excludeplaylist"),this.tech_.trigger({type:"usage",name:"vhs-rendition-excluded"});const d=this.selectPlaylist();if(!d)return this.error="Playback cannot continue. No available working or supported playlists.",void this.trigger("error");const u=t.internal?this.logger_:s.default.log.warn,l=t.message?" "+t.message:"";u(`${t.internal?"Internal problem":"Problem"} encountered with playlist ${e.id}.${l} Switching to playlist ${d.id}.`),d.attributes.AUDIO!==e.attributes.AUDIO&&this.delegateLoaders_("audio",["abort","pause"]),d.attributes.SUBTITLES!==e.attributes.SUBTITLES&&this.delegateLoaders_("subtitle",["abort","pause"]),this.delegateLoaders_("main",["abort","pause"]);const h=d.targetDuration/2*1e3||5e3,c="number"==typeof d.lastRequest&&Date.now()-d.lastRequest<=h;return this.switchMedia_(d,"exclude",a||c)}pauseLoading(){this.delegateLoaders_("all",["abort","pause"]),this.stopABRTimer_()}delegateLoaders_(e,t){const i=[],n="all"===e;(n||"main"===e)&&i.push(this.mainPlaylistLoader_);const s=[];(n||"audio"===e)&&s.push("AUDIO"),(n||"subtitle"===e)&&(s.push("CLOSED-CAPTIONS"),s.push("SUBTITLES")),s.forEach((e=>{const t=this.mediaTypes_[e]&&this.mediaTypes_[e].activePlaylistLoader;t&&i.push(t)})),["main","audio","subtitle"].forEach((t=>{const n=this[`${t}SegmentLoader_`];!n||e!==t&&"all"!==e||i.push(n)})),i.forEach((e=>t.forEach((t=>{"function"==typeof e[t]&&e[t]()}))))}setCurrentTime(e){const t=N(this.tech_.buffered(),e);return this.mainPlaylistLoader_&&this.mainPlaylistLoader_.media()&&this.mainPlaylistLoader_.media().segments?t&&t.length?e:(this.mainSegmentLoader_.resetEverything(),this.mainSegmentLoader_.abort(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.resetEverything(),this.audioSegmentLoader_.abort()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.resetEverything(),this.subtitleSegmentLoader_.abort()),void this.load()):0}duration(){if(!this.mainPlaylistLoader_)return 0;const e=this.mainPlaylistLoader_.media();return e?e.endList?this.mediaSource?this.mediaSource.duration:Rn.Playlist.duration(e):1/0:0}seekable(){return this.seekable_}onSyncInfoUpdate_(){let e;if(!this.mainPlaylistLoader_)return;let t=this.mainPlaylistLoader_.media();if(!t)return;let i=this.syncController_.getExpiredTime(t,this.duration());if(null===i)return;const n=this.mainPlaylistLoader_.main,s=Rn.Playlist.seekable(t,i,Rn.Playlist.liveEdgeDelay(n,t));if(0===s.length)return;if(this.mediaTypes_.AUDIO.activePlaylistLoader){if(t=this.mediaTypes_.AUDIO.activePlaylistLoader.media(),i=this.syncController_.getExpiredTime(t,this.duration()),null===i)return;if(e=Rn.Playlist.seekable(t,i,Rn.Playlist.liveEdgeDelay(n,t)),0===e.length)return}let r,a;this.seekable_&&this.seekable_.length&&(r=this.seekable_.end(0),a=this.seekable_.start(0)),e?e.start(0)>s.end(0)||s.start(0)>e.end(0)?this.seekable_=s:this.seekable_=C([[e.start(0)>s.start(0)?e.start(0):s.start(0),e.end(0)<s.end(0)?e.end(0):s.end(0)]]):this.seekable_=s,this.seekable_&&this.seekable_.length&&this.seekable_.end(0)===r&&this.seekable_.start(0)===a||(this.logger_(`seekable updated [${$(this.seekable_)}]`),this.tech_.trigger("seekablechanged"))}updateDuration(e){if(this.updateDuration_&&(this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.updateDuration_=null),"open"!==this.mediaSource.readyState)return this.updateDuration_=this.updateDuration.bind(this,e),void this.mediaSource.addEventListener("sourceopen",this.updateDuration_);if(e){const e=this.seekable();if(!e.length)return;return void((isNaN(this.mediaSource.duration)||this.mediaSource.duration<e.end(e.length-1))&&this.sourceUpdater_.setDuration(e.end(e.length-1)))}const t=this.tech_.buffered();let i=Rn.Playlist.duration(this.mainPlaylistLoader_.media());t.length>0&&(i=Math.max(i,t.end(t.length-1))),this.mediaSource.duration!==i&&this.sourceUpdater_.setDuration(i)}dispose(){this.trigger("dispose"),this.decrypter_.terminate(),this.mainPlaylistLoader_.dispose(),this.mainSegmentLoader_.dispose(),this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_),["AUDIO","SUBTITLES"].forEach((e=>{const t=this.mediaTypes_[e].groups;for(const e in t)t[e].forEach((e=>{e.playlistLoader&&e.playlistLoader.dispose()}))})),this.audioSegmentLoader_.dispose(),this.subtitleSegmentLoader_.dispose(),this.sourceUpdater_.dispose(),this.timelineChangeController_.dispose(),this.stopABRTimer_(),this.updateDuration_&&this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.mediaSource.removeEventListener("durationchange",this.handleDurationChange_),this.mediaSource.removeEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.removeEventListener("sourceended",this.handleSourceEnded_),this.off()}main(){return this.mainPlaylistLoader_.main}media(){return this.mainPlaylistLoader_.media()||this.initialMedia_}areMediaTypesKnown_(){const e=!!this.mediaTypes_.AUDIO.activePlaylistLoader,t=!!this.mainSegmentLoader_.getCurrentMediaInfo_(),i=!e||!!this.audioSegmentLoader_.getCurrentMediaInfo_();return!(!t||!i)}getCodecsOrExclude_(){const e={main:this.mainSegmentLoader_.getCurrentMediaInfo_()||{},audio:this.audioSegmentLoader_.getCurrentMediaInfo_()||{}};e.video=e.main;const t=Ci(this.main(),this.media()),i={},n=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(e.main.hasVideo&&(i.video=t.video||e.main.videoCodec||"avc1.4d400d"),e.main.isMuxed&&(i.video+=`,${t.audio||e.main.audioCodec||P}`),(e.main.hasAudio&&!e.main.isMuxed||e.audio.hasAudio||n)&&(i.audio=t.audio||e.main.audioCodec||e.audio.audioCodec||P,e.audio.isFmp4=e.main.hasAudio&&!e.main.isMuxed?e.main.isFmp4:e.audio.isFmp4),!i.audio&&!i.video)return void this.excludePlaylist({playlistToExclude:this.media(),error:{message:"Could not determine codecs for playlist."},playlistExclusionDuration:1/0});const s={};let r;if(["video","audio"].forEach((function(t){if(i.hasOwnProperty(t)&&(n=e[t].isFmp4,a=i[t],!(n?k(a):O(a)))){const n=e[t].isFmp4?"browser":"muxer";s[n]=s[n]||[],s[n].push(i[t]),"audio"===t&&(r=n)}var n,a})),n&&r&&this.media().attributes.AUDIO){const e=this.media().attributes.AUDIO;this.main().playlists.forEach((t=>{(t.attributes&&t.attributes.AUDIO)===e&&t!==this.media()&&(t.excludeUntil=1/0)})),this.logger_(`excluding audio group ${e} as ${r} does not support codec(s): "${i.audio}"`)}if(!Object.keys(s).length){if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){const e=[];if(["video","audio"].forEach((t=>{const n=(L(this.sourceUpdater_.codecs[t]||"")[0]||{}).type,s=(L(i[t]||"")[0]||{}).type;n&&s&&n.toLowerCase()!==s.toLowerCase()&&e.push(`"${this.sourceUpdater_.codecs[t]}" -> "${i[t]}"`)})),e.length)return void this.excludePlaylist({playlistToExclude:this.media(),error:{message:`Codec switching not supported: ${e.join(", ")}.`,internal:!0},playlistExclusionDuration:1/0})}return i}{const e=Object.keys(s).reduce(((e,t)=>(e&&(e+=", "),e+`${t} does not support codec(s): "${s[t].join(",")}"`)),"")+".";this.excludePlaylist({playlistToExclude:this.media(),error:{internal:!0,message:e},playlistExclusionDuration:1/0})}}tryToCreateSourceBuffers_(){if("open"!==this.mediaSource.readyState||this.sourceUpdater_.hasCreatedSourceBuffers())return;if(!this.areMediaTypesKnown_())return;const e=this.getCodecsOrExclude_();if(!e)return;this.sourceUpdater_.createSourceBuffers(e);const t=[e.video,e.audio].filter(Boolean).join(",");this.excludeIncompatibleVariants_(t)}excludeUnsupportedVariants_(){const e=this.main().playlists,t=[];Object.keys(e).forEach((i=>{const n=e[i];if(-1!==t.indexOf(n.id))return;t.push(n.id);const s=Ci(this.main,n),r=[];!s.audio||O(s.audio)||k(s.audio)||r.push(`audio codec ${s.audio}`),!s.video||O(s.video)||k(s.video)||r.push(`video codec ${s.video}`),s.text&&"stpp.ttml.im1t"===s.text&&r.push(`text codec ${s.text}`),r.length&&(n.excludeUntil=1/0,this.logger_(`excluding ${n.id} for unsupported: ${r.join(", ")}`))}))}excludeIncompatibleVariants_(e){const t=[],i=this.main().playlists,n=Pi(L(e)),s=Ui(n),r=n.video&&L(n.video)[0]||null,a=n.audio&&L(n.audio)[0]||null;Object.keys(i).forEach((e=>{const n=i[e];if(-1!==t.indexOf(n.id)||n.excludeUntil===1/0)return;t.push(n.id);const o=[],d=Ci(this.mainPlaylistLoader_.main,n),u=Ui(d);if(d.audio||d.video){if(u!==s&&o.push(`codec count "${u}" !== "${s}"`),!this.sourceUpdater_.canChangeType()){const e=d.video&&L(d.video)[0]||null,t=d.audio&&L(d.audio)[0]||null;e&&r&&e.type.toLowerCase()!==r.type.toLowerCase()&&o.push(`video codec "${e.type}" !== "${r.type}"`),t&&a&&t.type.toLowerCase()!==a.type.toLowerCase()&&o.push(`audio codec "${t.type}" !== "${a.type}"`)}o.length&&(n.excludeUntil=1/0,this.logger_(`excluding ${n.id}: ${o.join(" && ")}`))}}))}updateAdCues_(e){let t=0;const i=this.seekable();i.length&&(t=i.start(0)),function(e,t,i=0){if(!e.segments)return;let n,s=i;for(let i=0;i<e.segments.length;i++){const r=e.segments[i];if(n||(n=Sn(t,s+r.duration/2)),n){if("cueIn"in r){n.endTime=s,n.adEndTime=s,s+=r.duration,n=null;continue}if(s<n.endTime){s+=r.duration;continue}n.endTime+=r.duration}else if("cueOut"in r&&(n=new window.VTTCue(s,s+r.duration,r.cueOut),n.adStartTime=s,n.adEndTime=s+parseFloat(r.cueOut),t.addCue(n)),"cueOutCont"in r){const[e,i]=r.cueOutCont.split("/").map(parseFloat);n=new window.VTTCue(s,s+r.duration,""),n.adStartTime=s-e,n.adEndTime=n.adStartTime+i,t.addCue(n)}s+=r.duration}}(e,this.cueTagsTrack_,t)}goalBufferLength(){const e=this.tech_.currentTime(),t=di.GOAL_BUFFER_LENGTH,i=di.GOAL_BUFFER_LENGTH_RATE,n=Math.max(t,di.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*i,n)}bufferLowWaterLine(){const e=this.tech_.currentTime(),t=di.BUFFER_LOW_WATER_LINE,i=di.BUFFER_LOW_WATER_LINE_RATE,n=Math.max(t,di.MAX_BUFFER_LOW_WATER_LINE),s=Math.max(t,di.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*i,this.bufferBasedABR?s:n)}bufferHighWaterLine(){return di.BUFFER_HIGH_WATER_LINE}}class Fn{constructor(e,t,i){const{playlistController_:n}=e,s=n.fastQualityChange_.bind(n);if(t.attributes){const e=t.attributes.RESOLUTION;this.width=e&&e.width,this.height=e&&e.height,this.bandwidth=t.attributes.BANDWIDTH,this.frameRate=t.attributes["FRAME-RATE"]}var r,a,o;this.codecs=Ci(n.main(),t),this.playlist=t,this.id=i,this.enabled=(r=e.playlists,a=t.id,o=s,e=>{const t=r.main.playlists[a],i=ee(t),n=te(t);return void 0===e?n:(e?delete t.disabled:t.disabled=!0,e===n||i||(o(),e?r.trigger("renditionenabled"):r.trigger("renditiondisabled")),e)})}}const $n=["seeking","seeked","pause","playing","error"];class qn{constructor(e){this.playlistController_=e.playlistController,this.tech_=e.tech,this.seekable=e.seekable,this.allowSeeksWithinUnsafeLiveWindow=e.allowSeeksWithinUnsafeLiveWindow,this.liveRangeSafeTimeDelta=e.liveRangeSafeTimeDelta,this.media=e.media,this.consecutiveUpdates=0,this.lastRecordedTime=null,this.checkCurrentTimeTimeout_=null,this.logger_=h("PlaybackWatcher"),this.logger_("initialize");const t=()=>this.monitorCurrentTime_(),i=()=>this.monitorCurrentTime_(),n=()=>this.techWaiting_(),s=()=>this.resetTimeUpdate_(),r=this.playlistController_,a=["main","subtitle","audio"],o={};a.forEach((e=>{o[e]={reset:()=>this.resetSegmentDownloads_(e),updateend:()=>this.checkSegmentDownloads_(e)},r[`${e}SegmentLoader_`].on("appendsdone",o[e].updateend),r[`${e}SegmentLoader_`].on("playlistupdate",o[e].reset),this.tech_.on(["seeked","seeking"],o[e].reset)}));const d=e=>{["main","audio"].forEach((t=>{r[`${t}SegmentLoader_`][e]("appended",this.seekingAppendCheck_)}))};this.seekingAppendCheck_=()=>{this.fixesBadSeeks_()&&(this.consecutiveUpdates=0,this.lastRecordedTime=this.tech_.currentTime(),d("off"))},this.clearSeekingAppendCheck_=()=>d("off"),this.watchForBadSeeking_=()=>{this.clearSeekingAppendCheck_(),d("on")},this.tech_.on("seeked",this.clearSeekingAppendCheck_),this.tech_.on("seeking",this.watchForBadSeeking_),this.tech_.on("waiting",n),this.tech_.on($n,s),this.tech_.on("canplay",i),this.tech_.one("play",t),this.dispose=()=>{this.clearSeekingAppendCheck_(),this.logger_("dispose"),this.tech_.off("waiting",n),this.tech_.off($n,s),this.tech_.off("canplay",i),this.tech_.off("play",t),this.tech_.off("seeking",this.watchForBadSeeking_),this.tech_.off("seeked",this.clearSeekingAppendCheck_),a.forEach((e=>{r[`${e}SegmentLoader_`].off("appendsdone",o[e].updateend),r[`${e}SegmentLoader_`].off("playlistupdate",o[e].reset),this.tech_.off(["seeked","seeking"],o[e].reset)})),this.checkCurrentTimeTimeout_&&window.clearTimeout(this.checkCurrentTimeTimeout_),this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_(),this.checkCurrentTimeTimeout_&&window.clearTimeout(this.checkCurrentTimeTimeout_),this.checkCurrentTimeTimeout_=window.setTimeout(this.monitorCurrentTime_.bind(this),250)}resetSegmentDownloads_(e){const t=this.playlistController_[`${e}SegmentLoader_`];this[`${e}StalledDownloads_`]>0&&this.logger_(`resetting possible stalled download count for ${e} loader`),this[`${e}StalledDownloads_`]=0,this[`${e}Buffered_`]=t.buffered_()}checkSegmentDownloads_(e){const t=this.playlistController_,i=t[`${e}SegmentLoader_`],n=i.buffered_(),s=function(e,t){if(e===t)return!1;if(!e&&t||!t&&e)return!0;if(e.length!==t.length)return!0;for(let i=0;i<e.length;i++)if(e.start(i)!==t.start(i)||e.end(i)!==t.end(i))return!0;return!1}(this[`${e}Buffered_`],n);this[`${e}Buffered_`]=n,s?this.resetSegmentDownloads_(e):(this[`${e}StalledDownloads_`]++,this.logger_(`found #${this[`${e}StalledDownloads_`]} ${e} appends that did not increase buffer (possible stalled download)`,{playlistId:i.playlist_&&i.playlist_.id,buffered:q(n)}),this[`${e}StalledDownloads_`]<10||(this.logger_(`${e} loader stalled download exclusion`),this.resetSegmentDownloads_(e),this.tech_.trigger({type:"usage",name:`vhs-${e}-download-exclusion`}),"subtitle"!==e&&t.excludePlaylist({error:{message:`Excessive ${e} segment downloading detected.`},playlistExclusionDuration:1/0})))}checkCurrentTime_(){if(this.tech_.paused()||this.tech_.seeking())return;const e=this.tech_.currentTime(),t=this.tech_.buffered();if(this.lastRecordedTime===e&&(!t.length||e+M>=t.end(t.length-1)))return this.techWaiting_();this.consecutiveUpdates>=5&&e===this.lastRecordedTime?(this.consecutiveUpdates++,this.waiting_()):e===this.lastRecordedTime?this.consecutiveUpdates++:(this.consecutiveUpdates=0,this.lastRecordedTime=e)}resetTimeUpdate_(){this.consecutiveUpdates=0}fixesBadSeeks_(){if(!this.tech_.seeking())return!1;const e=this.seekable(),t=this.tech_.currentTime();let i;if(this.afterSeekableWindow_(e,t,this.media(),this.allowSeeksWithinUnsafeLiveWindow)&&(i=e.end(e.length-1)),this.beforeSeekableWindow_(e,t)){const t=e.start(0);i=t+(t===e.end(0)?0:M)}if(void 0!==i)return this.logger_(`Trying to seek outside of seekable at time ${t} with seekable range ${$(e)}. Seeking to ${i}.`),this.tech_.setCurrentTime(i),!0;const n=this.playlistController_.sourceUpdater_,s=this.tech_.buffered(),r=n.audioBuffer?n.audioBuffered():null,a=n.videoBuffer?n.videoBuffered():null,o=this.media(),d=o.partTargetDuration?o.partTargetDuration:2*(o.targetDuration-R),u=[r,a];for(let e=0;e<u.length;e++)if(u[e]&&G(u[e],t)<d)return!1;const l=F(s,t);return 0!==l.length&&(i=l.start(0)+M,this.logger_(`Buffered region starts (${l.start(0)}) just beyond seek point (${t}). Seeking to ${i}.`),this.tech_.setCurrentTime(i),!0)}waiting_(){if(this.techWaiting_())return;const e=this.tech_.currentTime(),t=this.tech_.buffered(),i=N(t,e);return i.length&&e+3<=i.end(0)?(this.resetTimeUpdate_(),this.tech_.setCurrentTime(e),this.logger_(`Stopped at ${e} while inside a buffered region [${i.start(0)} -> ${i.end(0)}]. Attempting to resume playback by seeking to the current time.`),void this.tech_.trigger({type:"usage",name:"vhs-unknown-waiting"})):void 0}techWaiting_(){const e=this.seekable(),t=this.tech_.currentTime();if(this.tech_.seeking())return!0;if(this.beforeSeekableWindow_(e,t)){const i=e.end(e.length-1);return this.logger_(`Fell out of live window at time ${t}. Seeking to live point (seekable end) ${i}`),this.resetTimeUpdate_(),this.tech_.setCurrentTime(i),this.tech_.trigger({type:"usage",name:"vhs-live-resync"}),!0}const i=this.tech_.vhs.playlistController_.sourceUpdater_,n=this.tech_.buffered();if(this.videoUnderflow_({audioBuffered:i.audioBuffered(),videoBuffered:i.videoBuffered(),currentTime:t}))return this.resetTimeUpdate_(),this.tech_.setCurrentTime(t),this.tech_.trigger({type:"usage",name:"vhs-video-underflow"}),!0;const s=F(n,t);return s.length>0&&(this.logger_(`Stopped at ${t} and seeking to ${s.start(0)}`),this.resetTimeUpdate_(),this.skipTheGap_(t),!0)}afterSeekableWindow_(e,t,i,n=!1){if(!e.length)return!1;let s=e.end(e.length-1)+M;return!i.endList&&n&&(s=e.end(e.length-1)+3*i.targetDuration),t>s}beforeSeekableWindow_(e,t){return!!(e.length&&e.start(0)>0&&t<e.start(0)-this.liveRangeSafeTimeDelta)}videoUnderflow_({videoBuffered:e,audioBuffered:t,currentTime:i}){if(!e)return;let n;if(e.length&&t.length){const s=N(e,i-3),r=N(e,i),a=N(t,i);a.length&&!r.length&&s.length&&(n={start:s.end(0),end:a.end(0)})}else F(e,i).length||(n=this.gapFromVideoUnderflow_(e,i));return!!n&&(this.logger_(`Encountered a gap in video from ${n.start} to ${n.end}. Seeking to current time ${i}`),!0)}skipTheGap_(e){const t=this.tech_.buffered(),i=this.tech_.currentTime(),n=F(t,i);this.resetTimeUpdate_(),0!==n.length&&i===e&&(this.logger_("skipTheGap_:","currentTime:",i,"scheduled currentTime:",e,"nextRange start:",n.start(0)),this.tech_.setCurrentTime(n.start(0)+R),this.tech_.trigger({type:"usage",name:"vhs-gap-skip"}))}gapFromVideoUnderflow_(e,t){const i=function(e){if(e.length<2)return C();const t=[];for(let i=1;i<e.length;i++){const n=e.end(i-1),s=e.start(i);t.push([n,s])}return C(t)}(e);for(let e=0;e<i.length;e++){const n=i.start(e),s=i.end(e);if(t-n<4&&t-n>2)return{start:n,end:s}}return null}}const Wn={errorInterval:30,getSource(e){return e(this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource())}},Gn=function(e,t){let i=0,n=0;const r=U(Wn,t);e.ready((()=>{e.trigger({type:"usage",name:"vhs-error-reload-initialized"})}));const a=function(){n&&e.currentTime(n)},o=function(t){null!=t&&(n=e.duration()!==1/0&&e.currentTime()||0,e.one("loadedmetadata",a),e.src(t),e.trigger({type:"usage",name:"vhs-error-reload"}),e.play())},d=function(){if(Date.now()-i<1e3*r.errorInterval)e.trigger({type:"usage",name:"vhs-error-reload-canceled"});else{if(r.getSource&&"function"==typeof r.getSource)return i=Date.now(),r.getSource.call(e,o);s.default.log.error("ERROR: reloadSourceOnError - The option getSource must be a function!")}},u=function(){e.off("loadedmetadata",a),e.off("error",d),e.off("dispose",u)};e.on("error",d),e.on("dispose",u),e.reloadSourceOnError=function(t){u(),Gn(e,t)}};var Vn="3.0.0-2";const Hn={PlaylistLoader:be,Playlist:oe,utils:Ve,STANDARD_PLAYLIST_SELECTOR:qi,INITIAL_PLAYLIST_SELECTOR:function(){const e=this.playlists.main.playlists.filter(oe.isEnabled);return Ni(e,((e,t)=>Fi(e,t))),e.filter((e=>!!Ci(this.playlists.main,e).video))[0]||null},lastBandwidthSelector:qi,movingAverageBandwidthSelector:function(e){let t=-1,i=-1;if(e<0||e>1)throw new Error("Moving average bandwidth decay must be between 0 and 1.");return function(){const n=this.useDevicePixelRatio&&window.devicePixelRatio||1;return t<0&&(t=this.systemBandwidth,i=this.systemBandwidth),this.systemBandwidth>0&&this.systemBandwidth!==i&&(t=e*this.systemBandwidth+(1-e)*t,i=this.systemBandwidth),$i(this.playlists.main,t,parseInt(Bi(this.tech_.el(),"width"),10)*n,parseInt(Bi(this.tech_.el(),"height"),10)*n,this.limitRenditionByPlayerDimensions,this.playlistController_)}},comparePlaylistBandwidth:Fi,comparePlaylistResolution:function(e,t){let i,n;return e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width&&(i=e.attributes.RESOLUTION.width),i=i||window.Number.MAX_VALUE,t.attributes.RESOLUTION&&t.attributes.RESOLUTION.width&&(n=t.attributes.RESOLUTION.width),n=n||window.Number.MAX_VALUE,i===n&&e.attributes.BANDWIDTH&&t.attributes.BANDWIDTH?e.attributes.BANDWIDTH-t.attributes.BANDWIDTH:i-n},xhr:we()};Object.keys(di).forEach((e=>{Object.defineProperty(Hn,e,{get:()=>(s.default.log.warn(`using Vhs.${e} is UNSAFE be sure you know what you are doing`),di[e]),set(t){s.default.log.warn(`using Vhs.${e} is UNSAFE be sure you know what you are doing`),"number"!=typeof t||t<0?s.default.log.warn(`value of Vhs.${e} must be greater than or equal to 0`):di[e]=t}})}));const jn="videojs-vhs",Xn=function(e,t){const i=t.media();let n=-1;for(let t=0;t<e.length;t++)if(e[t].id===i.id){n=t;break}e.selectedIndex_=n,e.trigger({selectedIndex:n,type:"change"})};Hn.canPlaySource=function(){return s.default.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const zn=(e,t,i)=>{if(!e)return e;let n={};t&&t.attributes&&t.attributes.CODECS&&(n=Pi(L(t.attributes.CODECS))),i&&i.attributes&&i.attributes.CODECS&&(n.audio=i.attributes.CODECS);const s=D(n.video),r=D(n.audio),a={};for(const i in e)a[i]={},r&&(a[i].audioContentType=r),s&&(a[i].videoContentType=s),t.contentProtection&&t.contentProtection[i]&&t.contentProtection[i].pssh&&(a[i].pssh=t.contentProtection[i].pssh),"string"==typeof e[i]&&(a[i].url=e[i]);return U(e,a)},Qn=(e,t)=>e.reduce(((e,i)=>{if(!i.contentProtection)return e;const n=t.reduce(((e,t)=>{const n=i.contentProtection[t];return n&&n.pssh&&(e[t]={pssh:n.pssh}),e}),{});return Object.keys(n).length&&e.push(n),e}),[]),Yn=({player:e,sourceKeySystems:t,audioMedia:i,mainPlaylists:n})=>{if(!e.eme.initializeMediaKeys)return Promise.resolve();const s=i?n.concat([i]):n,r=Qn(s,Object.keys(t)),a=[],o=[];return r.forEach((t=>{o.push(new Promise(((t,i)=>{e.tech_.one("keysessioncreated",t)}))),a.push(new Promise(((i,n)=>{e.eme.initializeMediaKeys({keySystems:t},(e=>{e?n(e):i()}))})))})),Promise.race([Promise.all(a),Promise.race(o)])},Kn=({player:e,sourceKeySystems:t,media:i,audioMedia:n})=>{const r=zn(t,i,n);return!(!r||(e.currentSource().keySystems=r,r&&!e.eme&&(s.default.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),1)))},Jn=()=>{if(!window.localStorage)return null;const e=window.localStorage.getItem(jn);if(!e)return null;try{return JSON.parse(e)}catch(e){return null}},Zn=e=>0===e.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")?JSON.parse(e.substring(e.indexOf(",")+1)):e;Hn.supportsNativeHls=function(){if(!document||!document.createElement)return!1;const e=document.createElement("video");return!!s.default.getTech("Html5").isSupported()&&["application/vnd.apple.mpegurl","audio/mpegurl","audio/x-mpegurl","application/x-mpegurl","video/x-mpegurl","video/mpegurl","application/mpegurl"].some((function(t){return/maybe|probably/i.test(e.canPlayType(t))}))}(),Hn.supportsNativeDash=!!(document&&document.createElement&&s.default.getTech("Html5").isSupported())&&/maybe|probably/i.test(document.createElement("video").canPlayType("application/dash+xml")),Hn.supportsTypeNatively=e=>"hls"===e?Hn.supportsNativeHls:"dash"===e&&Hn.supportsNativeDash,Hn.isSupported=function(){return s.default.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const es=s.default.getComponent("Component");class ts extends es{constructor(e,t,i){if(super(t,i.vhs),"number"==typeof i.initialBandwidth&&(this.options_.bandwidth=i.initialBandwidth),this.logger_=h("VhsHandler"),t.options_&&t.options_.playerId){const e=s.default.getPlayer(t.options_.playerId);this.player_=e}if(this.tech_=t,this.source_=e,this.stats={},this.ignoreNextSeekingEvent_=!1,this.setOptions_(),this.options_.overrideNative&&t.overrideNativeAudioTracks&&t.overrideNativeVideoTracks)t.overrideNativeAudioTracks(!0),t.overrideNativeVideoTracks(!0);else if(this.options_.overrideNative&&(t.featuresNativeVideoTracks||t.featuresNativeAudioTracks))throw new Error("Overriding native VHS requires emulated tracks. See https://git.io/vMpjB");this.on(document,["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],(e=>{const t=document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement;t&&t.contains(this.tech_.el())?this.playlistController_.fastQualityChange_():this.playlistController_.checkABR_()})),this.on(this.tech_,"seeking",(function(){this.ignoreNextSeekingEvent_?this.ignoreNextSeekingEvent_=!1:this.setCurrentTime(this.tech_.currentTime())})),this.on(this.tech_,"error",(function(){this.tech_.error()&&this.playlistController_&&this.playlistController_.pauseLoading()})),this.on(this.tech_,"play",this.play)}setOptions_(){if(this.options_.withCredentials=this.options_.withCredentials||!1,this.options_.limitRenditionByPlayerDimensions=!1!==this.options_.limitRenditionByPlayerDimensions,this.options_.useDevicePixelRatio=this.options_.useDevicePixelRatio||!1,this.options_.useBandwidthFromLocalStorage=void 0!==this.source_.useBandwidthFromLocalStorage?this.source_.useBandwidthFromLocalStorage:this.options_.useBandwidthFromLocalStorage||!1,this.options_.useNetworkInformationApi=this.options_.useNetworkInformationApi||!1,this.options_.useDtsForTimestampOffset=this.options_.useDtsForTimestampOffset||!1,this.options_.customTagParsers=this.options_.customTagParsers||[],this.options_.customTagMappers=this.options_.customTagMappers||[],this.options_.cacheEncryptionKeys=this.options_.cacheEncryptionKeys||!1,this.options_.llhls=!1!==this.options_.llhls,this.options_.bufferBasedABR=this.options_.bufferBasedABR||!1,"number"!=typeof this.options_.playlistExclusionDuration&&(this.options_.playlistExclusionDuration=300),"number"!=typeof this.options_.bandwidth&&this.options_.useBandwidthFromLocalStorage){const e=Jn();e&&e.bandwidth&&(this.options_.bandwidth=e.bandwidth,this.tech_.trigger({type:"usage",name:"vhs-bandwidth-from-local-storage"})),e&&e.throughput&&(this.options_.throughput=e.throughput,this.tech_.trigger({type:"usage",name:"vhs-throughput-from-local-storage"}))}"number"!=typeof this.options_.bandwidth&&(this.options_.bandwidth=di.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===di.INITIAL_BANDWIDTH,["withCredentials","useDevicePixelRatio","limitRenditionByPlayerDimensions","bandwidth","customTagParsers","customTagMappers","cacheEncryptionKeys","playlistSelector","initialPlaylistSelector","bufferBasedABR","liveRangeSafeTimeDelta","llhls","useNetworkInformationApi","useDtsForTimestampOffset","exactManifestTimings","leastPixelDiffSelector"].forEach((e=>{void 0!==this.source_[e]&&(this.options_[e]=this.source_[e])})),this.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions,this.useDevicePixelRatio=this.options_.useDevicePixelRatio}src(e,t){if(!e)return;this.setOptions_(),this.options_.src=Zn(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=Hn,this.options_.sourceType=De(t),this.options_.seekTo=e=>{this.tech_.setCurrentTime(e)},this.playlistController_=new Nn(this.options_);const i=U({liveRangeSafeTimeDelta:M},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new qn(i),this.playlistController_.on("error",(()=>{const e=s.default.players[this.tech_.options_.playerId];let t=this.playlistController_.error;"object"!=typeof t||t.code?"string"==typeof t&&(t={message:t,code:3}):t.code=3,e.error(t)}));const n=this.options_.bufferBasedABR?Hn.movingAverageBandwidthSelector(.55):Hn.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):n.bind(this),this.playlistController_.selectInitialPlaylist=Hn.INITIAL_PLAYLIST_SELECTOR.bind(this),this.playlists=this.playlistController_.mainPlaylistLoader_,this.mediaSource=this.playlistController_.mediaSource,Object.defineProperties(this,{selectPlaylist:{get(){return this.playlistController_.selectPlaylist},set(e){this.playlistController_.selectPlaylist=e.bind(this)}},throughput:{get(){return this.playlistController_.mainSegmentLoader_.throughput.rate},set(e){this.playlistController_.mainSegmentLoader_.throughput.rate=e,this.playlistController_.mainSegmentLoader_.throughput.count=1}},bandwidth:{get(){let e=this.playlistController_.mainSegmentLoader_.bandwidth;const t=window.navigator.connection||window.navigator.mozConnection||window.navigator.webkitConnection,i=1e7;if(this.options_.useNetworkInformationApi&&t){const n=1e3*t.downlink*1e3;e=n>=i&&e>=i?Math.max(e,n):n}return e},set(e){this.playlistController_.mainSegmentLoader_.bandwidth=e,this.playlistController_.mainSegmentLoader_.throughput={rate:0,count:0}}},systemBandwidth:{get(){const e=1/(this.bandwidth||1);let t;return t=this.throughput>0?1/this.throughput:0,Math.floor(1/(e+t))},set(){s.default.log.error('The "systemBandwidth" property is read-only')}}}),this.options_.bandwidth&&(this.bandwidth=this.options_.bandwidth),this.options_.throughput&&(this.throughput=this.options_.throughput),Object.defineProperties(this.stats,{bandwidth:{get:()=>this.bandwidth||0,enumerable:!0},mediaRequests:{get:()=>this.playlistController_.mediaRequests_()||0,enumerable:!0},mediaRequestsAborted:{get:()=>this.playlistController_.mediaRequestsAborted_()||0,enumerable:!0},mediaRequestsTimedout:{get:()=>this.playlistController_.mediaRequestsTimedout_()||0,enumerable:!0},mediaRequestsErrored:{get:()=>this.playlistController_.mediaRequestsErrored_()||0,enumerable:!0},mediaTransferDuration:{get:()=>this.playlistController_.mediaTransferDuration_()||0,enumerable:!0},mediaBytesTransferred:{get:()=>this.playlistController_.mediaBytesTransferred_()||0,enumerable:!0},mediaSecondsLoaded:{get:()=>this.playlistController_.mediaSecondsLoaded_()||0,enumerable:!0},mediaAppends:{get:()=>this.playlistController_.mediaAppends_()||0,enumerable:!0},mainAppendsToLoadedData:{get:()=>this.playlistController_.mainAppendsToLoadedData_()||0,enumerable:!0},audioAppendsToLoadedData:{get:()=>this.playlistController_.audioAppendsToLoadedData_()||0,enumerable:!0},appendsToLoadedData:{get:()=>this.playlistController_.appendsToLoadedData_()||0,enumerable:!0},timeToLoadedData:{get:()=>this.playlistController_.timeToLoadedData_()||0,enumerable:!0},buffered:{get:()=>q(this.tech_.buffered()),enumerable:!0},currentTime:{get:()=>this.tech_.currentTime(),enumerable:!0},currentSource:{get:()=>this.tech_.currentSource_,enumerable:!0},currentTech:{get:()=>this.tech_.name_,enumerable:!0},duration:{get:()=>this.tech_.duration(),enumerable:!0},main:{get:()=>this.playlists.main,enumerable:!0},playerDimensions:{get:()=>this.tech_.currentDimensions(),enumerable:!0},seekable:{get:()=>q(this.tech_.seekable()),enumerable:!0},timestamp:{get:()=>Date.now(),enumerable:!0},videoPlaybackQuality:{get:()=>this.tech_.getVideoPlaybackQuality(),enumerable:!0}}),this.tech_.one("canplay",this.playlistController_.setupFirstPlay.bind(this.playlistController_)),this.tech_.on("bandwidthupdate",(()=>{this.options_.useBandwidthFromLocalStorage&&(e=>{if(!window.localStorage)return!1;let t=Jn();t=t?U(t,e):e;try{window.localStorage.setItem(jn,JSON.stringify(t))}catch(e){return!1}})({bandwidth:this.bandwidth,throughput:Math.round(this.throughput)})})),this.playlistController_.on("selectedinitialmedia",(()=>{var e;(e=this).representations=()=>{const t=e.playlistController_.main(),i=ae(t)?e.playlistController_.getAudioTrackPlaylists_():t.playlists;return i?i.filter((e=>!ee(e))).map(((t,i)=>new Fn(e,t,t.id))):[]}})),this.playlistController_.sourceUpdater_.on("createdsourcebuffers",(()=>{this.setupEme_()})),this.on(this.playlistController_,"progress",(function(){this.tech_.trigger("progress")})),this.on(this.playlistController_,"firstplay",(function(){this.ignoreNextSeekingEvent_=!0})),this.setupQualityLevels_(),this.tech_.el()&&(this.mediaSourceUrl_=window.URL.createObjectURL(this.playlistController_.mediaSource),this.tech_.src(this.mediaSourceUrl_))}createKeySessions_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;this.logger_("waiting for EME key session creation"),Yn({player:this.player_,sourceKeySystems:this.source_.keySystems,audioMedia:e&&e.media(),mainPlaylists:this.playlists.main.playlists}).then((()=>{this.logger_("created EME key session"),this.playlistController_.sourceUpdater_.initializedEme()})).catch((e=>{this.logger_("error while creating EME key session",e),this.player_.error({message:"Failed to initialize media keys for EME",code:3})}))}handleWaitingForKey_(){this.logger_("waitingforkey fired, attempting to create any new key sessions"),this.createKeySessions_()}setupEme_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader,t=Kn({player:this.player_,sourceKeySystems:this.source_.keySystems,media:this.playlists.media(),audioMedia:e&&e.media()});this.player_.tech_.on("keystatuschange",(e=>{if("output-restricted"!==e.status)return;const t=this.playlistController_.main();if(!t||!t.playlists)return;const i=[];t.playlists.forEach((e=>{e&&e.attributes&&e.attributes.RESOLUTION&&e.attributes.RESOLUTION.height>=720&&(!e.excludeUntil||e.excludeUntil<1/0)&&(e.excludeUntil=1/0,i.push(e))})),i.length&&(s.default.log.warn('DRM keystatus changed to "output-restricted." Removing the following HD playlists that will most likely fail to play and clearing the buffer. This may be due to HDCP restrictions on the stream and the capabilities of the current device.',...i),this.playlistController_.fastQualityChange_())})),this.handleWaitingForKey_=this.handleWaitingForKey_.bind(this),this.player_.tech_.on("waitingforkey",this.handleWaitingForKey_),11!==s.default.browser.IE_VERSION&&t?this.createKeySessions_():this.playlistController_.sourceUpdater_.initializedEme()}setupQualityLevels_(){const e=s.default.players[this.tech_.options_.playerId];e&&e.qualityLevels&&!this.qualityLevels_&&(this.qualityLevels_=e.qualityLevels(),this.playlistController_.on("selectedinitialmedia",(()=>{var e,t;e=this.qualityLevels_,(t=this).representations().forEach((t=>{e.addQualityLevel(t)})),Xn(e,t.playlists)})),this.playlists.on("mediachange",(()=>{Xn(this.qualityLevels_,this.playlists)})))}static version(){return{"@videojs/http-streaming":Vn,"mux.js":"6.2.0","mpd-parser":"1.0.0","m3u8-parser":"6.0.0","aes-decrypter":"4.0.1"}}version(){return this.constructor.version()}canChangeType(){return yn.canChangeType()}play(){this.playlistController_.play()}setCurrentTime(e){this.playlistController_.setCurrentTime(e)}duration(){return this.playlistController_.duration()}seekable(){return this.playlistController_.seekable()}dispose(){this.playbackWatcher_&&this.playbackWatcher_.dispose(),this.playlistController_&&this.playlistController_.dispose(),this.qualityLevels_&&this.qualityLevels_.dispose(),this.tech_&&this.tech_.vhs&&delete this.tech_.vhs,this.mediaSourceUrl_&&window.URL.revokeObjectURL&&(window.URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null),this.tech_&&this.tech_.off("waitingforkey",this.handleWaitingForKey_),super.dispose()}convertToProgramTime(e,t){return(({playlist:e,time:t,callback:i})=>{if(!i)throw new Error("getProgramTime: callback must be provided");if(!e||void 0===t)return i({message:"getProgramTime: playlist and time must be provided"});const n=((e,t)=>{if(!t||!t.segments||0===t.segments.length)return null;let i,n=0;for(let s=0;s<t.segments.length&&(i=t.segments[s],n=i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationEnd:n+i.duration,!(e<=n));s++);const s=t.segments[t.segments.length-1];if(s.videoTimingInfo&&s.videoTimingInfo.transmuxedPresentationEnd<e)return null;if(e>n){if(e>n+.25*s.duration)return null;i=s}return{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:n-i.duration,type:i.videoTimingInfo?"accurate":"estimate"}})(t,e);if(!n)return i({message:"valid programTime was not found"});if("estimate"===n.type)return i({message:"Accurate programTime could not be determined. Please seek to e.seekTime and try again",seekTime:n.estimatedStart});const s={mediaSeconds:t},r=((e,t)=>{if(!t.dateTimeObject)return null;const i=t.videoTimingInfo.transmuxerPrependedSeconds,n=e-(t.videoTimingInfo.transmuxedPresentationStart+i);return new Date(t.dateTimeObject.getTime()+1e3*n)})(t,n.segment);return r&&(s.programDateTime=r.toISOString()),i(null,s)})({playlist:this.playlistController_.media(),time:e,callback:t})}seekToProgramTime(e,t,i=!0,n=2){return He({programTime:e,playlist:this.playlistController_.media(),retryCount:n,pauseAfterSeek:i,seekTo:this.options_.seekTo,tech:this.options_.tech,callback:t})}}const is={name:"videojs-http-streaming",VERSION:Vn,canHandleSource(e,t={}){const i=U(s.default.options,t);return is.canPlayType(e.type,i)},handleSource(e,t,i={}){const n=U(s.default.options,i);return t.vhs=new ts(e,t,n),t.vhs.xhr=we(),t.vhs.src(e.src,e.type),t.vhs},canPlayType(e,t={}){const{vhs:{overrideNative:i=!s.default.browser.IS_ANY_SAFARI}={}}=U(s.default.options,t),n=De(e);return!n||Hn.supportsTypeNatively(n)&&!i?"":"maybe"}};k("avc1.4d400d,mp4a.40.2")&&s.default.getTech("Html5").registerSourceHandler(is,0),s.default.VhsHandler=ts,s.default.VhsSourceHandler=is,s.default.Vhs=Hn,s.default.use||s.default.registerComponent("Vhs",Hn),s.default.options.vhs=s.default.options.vhs||{},s.default.getPlugin&&s.default.getPlugin("reloadSourceOnError")||s.default.registerPlugin("reloadSourceOnError",(function(e){Gn(this,e)})),e.LOCAL_STORAGE_KEY=jn,e.Vhs=Hn,e.VhsHandler=ts,e.VhsSourceHandler=is,e.emeKeySystems=zn,e.expandDataUri=Zn,e.getAllPsshKeySystemsOptions=Qn,e.setupEmeOptions=Kn,e.simpleTypeFromSourceType=De,e.waitForKeySessionCreation=Yn,Object.defineProperty(e,"__esModule",{value:!0})}));