6 lines
365 KiB
JavaScript
6 lines
365 KiB
JavaScript
/*! @name @videojs/http-streaming @version 3.17.0 @license Apache-2.0 */
|
|
!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);function a(){return a=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},a.apply(this,arguments)}var r="https://example.com",o=function(e,t){if(/^[a-z]+:/i.test(t))return t;/^data:/.test(e)&&(e=window.location&&window.location.href||"");var i=/^\/\//.test(e),n=!window.location&&!/\/\//i.test(e);e=new window.URL(e,window.location||r);var s=new URL(t,e);return n?s.href.slice(r.length):i?s.href.slice(s.protocol.length):s.href};const d=o,u=(e,t)=>t&&t.responseURL&&e!==t.responseURL?t.responseURL:e,l=e=>s.default.log.debug?s.default.log.debug.bind(s.default,"VHS:",`${e} >`):function(){};var h=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),a=t.length,r=0;r<a;++r)t[r].apply(this,s)},t.dispose=function(){this.listeners={}},t.pipe=function(e){this.on("data",(function(t){e.push(t)}))},e}();function c(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}
|
|
/*! @name m3u8-parser @version 7.2.0 @license Apache-2.0 */class p extends h{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 m=String.fromCharCode(9),g=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},f=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},y=e=>{const t=e.split("x"),i={};return t[0]&&(i.width=parseInt(t[0],10)),t[1]&&(i.height=parseInt(t[1],10)),i};class _ extends h{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=a(g(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=f(t[1]);e.URI&&(i.uri=e.URI),e.BYTERANGE&&(i.byterange=g(e.BYTERANGE))}this.trigger("data",i)}else{if(t=/^#EXT-X-STREAM-INF:(.*)$/.exec(e),t)return i={type:"tag",tagType:"stream-inf"},t[1]&&(i.attributes=f(t[1]),i.attributes.RESOLUTION&&(i.attributes.RESOLUTION=y(i.attributes.RESOLUTION)),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))),void this.trigger("data",i);if(t=/^#EXT-X-MEDIA:(.*)$/.exec(e),t)return i={type:"tag",tagType:"media"},t[1]&&(i.attributes=f(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=f(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=f(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=f(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(m)),void this.trigger("data",i);if(t=/^#EXT-X-PART:(.*)$/.exec(e),t&&t[1])return i={type:"tag",tagType:"part"},i.attributes=f(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=g(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=f(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=f(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=f(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=f(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);if(t=/^#EXT-X-DATERANGE:(.*)$/.exec(e),t&&t[1]){i={type:"tag",tagType:"daterange"},i.attributes=f(t[1]),["ID","CLASS"].forEach((function(e){i.attributes.hasOwnProperty(e)&&(i.attributes[e]=String(i.attributes[e]))})),["START-DATE","END-DATE"].forEach((function(e){i.attributes.hasOwnProperty(e)&&(i.attributes[e]=new Date(i.attributes[e]))})),["DURATION","PLANNED-DURATION"].forEach((function(e){i.attributes.hasOwnProperty(e)&&(i.attributes[e]=parseFloat(i.attributes[e]))})),["END-ON-NEXT"].forEach((function(e){i.attributes.hasOwnProperty(e)&&(i.attributes[e]=/YES/i.test(i.attributes[e]))})),["SCTE35-CMD"," SCTE35-OUT","SCTE35-IN"].forEach((function(e){i.attributes.hasOwnProperty(e)&&(i.attributes[e]=i.attributes[e].toString(16))}));const e=/^X-([A-Z]+-)+[A-Z]+$/;for(const t in i.attributes){if(!e.test(t))continue;const n=/[0-9A-Fa-f]{6}/g.test(i.attributes[t]),s=/^\d+(\.\d+)?$/.test(i.attributes[t]);i.attributes[t]=n?i.attributes[t].toString(16):s?parseFloat(i.attributes[t]):String(i.attributes[t])}this.trigger("data",i)}else if(t=/^#EXT-X-INDEPENDENT-SEGMENTS/.exec(e),t)this.trigger("data",{type:"tag",tagType:"independent-segments"});else if(t=/^#EXT-X-I-FRAMES-ONLY/.exec(e),t)this.trigger("data",{type:"tag",tagType:"i-frames-only"});else{if(t=/^#EXT-X-CONTENT-STEERING:(.*)$/.exec(e),t)return i={type:"tag",tagType:"content-steering"},i.attributes=f(t[1]),void this.trigger("data",i);if(t=/^#EXT-X-I-FRAME-STREAM-INF:(.*)$/.exec(e),t)return i={type:"tag",tagType:"i-frame-playlist"},i.attributes=f(t[1]),i.attributes.URI&&(i.uri=i.attributes.URI),i.attributes.BANDWIDTH&&(i.attributes.BANDWIDTH=parseInt(i.attributes.BANDWIDTH,10)),i.attributes.RESOLUTION&&(i.attributes.RESOLUTION=y(i.attributes.RESOLUTION)),i.attributes["AVERAGE-BANDWIDTH"]&&(i.attributes["AVERAGE-BANDWIDTH"]=parseInt(i.attributes["AVERAGE-BANDWIDTH"],10)),i.attributes["FRAME-RATE"]&&(i.attributes["FRAME-RATE"]=parseFloat(i.attributes["FRAME-RATE"])),void this.trigger("data",i);if(t=/^#EXT-X-DEFINE:(.*)$/.exec(e),t)return i={type:"tag",tagType:"define"},i.attributes=f(t[1]),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 T=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},b=function(e){const{serverControl:t,targetDuration:i,partTargetDuration:n}=e;if(!t)return;const s="#EXT-X-SERVER-CONTROL",a="holdBack",r="partHoldBack",o=i&&3*i,d=n&&2*n;i&&!t.hasOwnProperty(a)&&(t[a]=o,this.trigger("info",{message:`${s} defaulting HOLD-BACK to targetDuration * 3 (${o}).`})),o&&t[a]<o&&(this.trigger("warn",{message:`${s} clamping HOLD-BACK (${t[a]}) to targetDuration * 3 (${o})`}),t[a]=o),n&&!t.hasOwnProperty(r)&&(t[r]=3*n,this.trigger("info",{message:`${s} defaulting PART-HOLD-BACK to partTargetDuration * 3 (${t[r]}).`})),n&&t[r]<d&&(this.trigger("warn",{message:`${s} clamping PART-HOLD-BACK (${t[r]}) to partTargetDuration * 2 (${d}).`}),t[r]=d)};class S extends h{constructor(e={}){super(),this.lineStream=new p,this.parseStream=new _,this.lineStream.pipe(this.parseStream),this.mainDefinitions=e.mainDefinitions||{},this.params=new URL(e.uri,"https://a.com").searchParams,this.lastProgramDateTime=null;const t=this,i=[];let n,s,r={},o=!1;const d=function(){},u={AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}};let l=0;this.manifest={allowCache:!0,discontinuityStarts:[],dateRanges:[],iFramePlaylists:[],segments:[]};let h=0,m=0;const g={};this.on("end",(()=>{r.uri||!r.parts&&!r.preloadHints||(!r.map&&n&&(r.map=n),!r.key&&s&&(r.key=s),r.timeline||"number"!=typeof l||(r.timeline=l),this.manifest.preloadSegment=r)})),this.parseStream.on("data",(function(e){let p,f;if(t.manifest.definitions)for(const i in t.manifest.definitions)if(e.uri&&(e.uri=e.uri.replace(`{$${i}}`,t.manifest.definitions[i])),e.attributes)for(const n in e.attributes)"string"==typeof e.attributes[n]&&(e.attributes[n]=e.attributes[n].replace(`{$${i}}`,t.manifest.definitions[i]));({tag(){({version(){e.version&&(this.manifest.version=e.version)},"allow-cache"(){this.manifest.allowCache=e.allowed,"allowed"in e||(this.trigger("info",{message:"defaulting allowCache to YES"}),this.manifest.allowCache=!0)},byterange(){const t={};"length"in e&&(r.byterange=t,t.length=e.length,"offset"in e||(e.offset=h)),"offset"in e&&(r.byterange=t,t.offset=e.offset),h=t.offset+t.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"})),e.title&&(r.title=e.title),e.duration>0&&(r.duration=e.duration),0===e.duration&&(r.duration=.01,this.trigger("info",{message:"updating zero segment duration to a small value"})),this.manifest.segments=i},key(){if(e.attributes)if("NONE"!==e.attributes.METHOD)if(e.attributes.URI){if("com.apple.streamingkeydelivery"===e.attributes.KEYFORMAT)return this.manifest.contentProtection=this.manifest.contentProtection||{},void(this.manifest.contentProtection["com.apple.fps.1_0"]={attributes:e.attributes});if("com.microsoft.playready"===e.attributes.KEYFORMAT)return this.manifest.contentProtection=this.manifest.contentProtection||{},void(this.manifest.contentProtection["com.microsoft.playready"]={uri:e.attributes.URI});if("urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"===e.attributes.KEYFORMAT)return-1===["SAMPLE-AES","SAMPLE-AES-CTR","SAMPLE-AES-CENC"].indexOf(e.attributes.METHOD)?void this.trigger("warn",{message:"invalid key method provided for Widevine"}):("SAMPLE-AES-CENC"===e.attributes.METHOD&&this.trigger("warn",{message:"SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead"}),"data:text/plain;base64,"!==e.attributes.URI.substring(0,23)?void this.trigger("warn",{message:"invalid key URI provided for Widevine"}):e.attributes.KEYID&&"0x"===e.attributes.KEYID.substring(0,2)?(this.manifest.contentProtection=this.manifest.contentProtection||{},void(this.manifest.contentProtection["com.widevine.alpha"]={attributes:{schemeIdUri:e.attributes.KEYFORMAT,keyId:e.attributes.KEYID.substring(2)},pssh:c(e.attributes.URI.split(",")[1])})):void this.trigger("warn",{message:"invalid key ID provided for Widevine"}));e.attributes.METHOD||this.trigger("warn",{message:"defaulting key method to AES-128"}),s={method:e.attributes.METHOD||"AES-128",uri:e.attributes.URI},void 0!==e.attributes.IV&&(s.iv=e.attributes.IV)}else this.trigger("warn",{message:"ignoring key declaration without URI"});else s=null;else this.trigger("warn",{message:"ignoring key declaration without attribute list"})},"media-sequence"(){isFinite(e.number)?this.manifest.mediaSequence=e.number:this.trigger("warn",{message:"ignoring invalid media sequence: "+e.number})},"discontinuity-sequence"(){isFinite(e.number)?(this.manifest.discontinuitySequence=e.number,l=e.number):this.trigger("warn",{message:"ignoring invalid discontinuity sequence: "+e.number})},"playlist-type"(){/VOD|EVENT/.test(e.playlistType)?this.manifest.playlistType=e.playlistType:this.trigger("warn",{message:"ignoring unknown playlist type: "+e.playlist})},map(){n={},e.uri&&(n.uri=e.uri),e.byterange&&(n.byterange=e.byterange),s&&(n.key=s)},"stream-inf"(){this.manifest.playlists=i,this.manifest.mediaGroups=this.manifest.mediaGroups||u,e.attributes?(r.attributes||(r.attributes={}),a(r.attributes,e.attributes)):this.trigger("warn",{message:"ignoring empty stream-inf attributes"})},media(){if(this.manifest.mediaGroups=this.manifest.mediaGroups||u,!(e.attributes&&e.attributes.TYPE&&e.attributes["GROUP-ID"]&&e.attributes.NAME))return void this.trigger("warn",{message:"ignoring incomplete or missing media group"});const t=this.manifest.mediaGroups[e.attributes.TYPE];t[e.attributes["GROUP-ID"]]=t[e.attributes["GROUP-ID"]]||{},p=t[e.attributes["GROUP-ID"]],f={default:/yes/i.test(e.attributes.DEFAULT)},f.default?f.autoselect=!0:f.autoselect=/yes/i.test(e.attributes.AUTOSELECT),e.attributes.LANGUAGE&&(f.language=e.attributes.LANGUAGE),e.attributes.URI&&(f.uri=e.attributes.URI),e.attributes["INSTREAM-ID"]&&(f.instreamId=e.attributes["INSTREAM-ID"]),e.attributes.CHARACTERISTICS&&(f.characteristics=e.attributes.CHARACTERISTICS),e.attributes.FORCED&&(f.forced=/yes/i.test(e.attributes.FORCED)),p[e.attributes.NAME]=f},discontinuity(){l+=1,r.discontinuity=!0,this.manifest.discontinuityStarts.push(i.length)},"program-date-time"(){void 0===this.manifest.dateTimeString&&(this.manifest.dateTimeString=e.dateTimeString,this.manifest.dateTimeObject=e.dateTimeObject),r.dateTimeString=e.dateTimeString,r.dateTimeObject=e.dateTimeObject;const{lastProgramDateTime:t}=this;this.lastProgramDateTime=new Date(e.dateTimeString).getTime(),null===t&&this.manifest.segments.reduceRight(((e,t)=>(t.programDateTime=e-1e3*t.duration,t.programDateTime)),this.lastProgramDateTime)},targetduration(){!isFinite(e.duration)||e.duration<0?this.trigger("warn",{message:"ignoring invalid target duration: "+e.duration}):(this.manifest.targetDuration=e.duration,b.call(this,this.manifest))},start(){e.attributes&&!isNaN(e.attributes["TIME-OFFSET"])?this.manifest.start={timeOffset:e.attributes["TIME-OFFSET"],precise:e.attributes.PRECISE}:this.trigger("warn",{message:"ignoring start declaration without appropriate attribute list"})},"cue-out"(){r.cueOut=e.data},"cue-out-cont"(){r.cueOutCont=e.data},"cue-in"(){r.cueIn=e.data},skip(){this.manifest.skip=T(e.attributes),this.warnOnMissingAttributes_("#EXT-X-SKIP",e.attributes,["SKIPPED-SEGMENTS"])},part(){o=!0;const t=this.manifest.segments.length,i=T(e.attributes);r.parts=r.parts||[],r.parts.push(i),i.byterange&&(i.byterange.hasOwnProperty("offset")||(i.byterange.offset=m),m=i.byterange.offset+i.byterange.length);const n=r.parts.length-1;this.warnOnMissingAttributes_(`#EXT-X-PART #${n} for segment #${t}`,e.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 t=this.manifest.serverControl=T(e.attributes);t.hasOwnProperty("canBlockReload")||(t.canBlockReload=!1,this.trigger("info",{message:"#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false"})),b.call(this,this.manifest),t.canSkipDateranges&&!t.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 t=this.manifest.segments.length,i=T(e.attributes),n=i.type&&"PART"===i.type;r.preloadHints=r.preloadHints||[],r.preloadHints.push(i),i.byterange&&(i.byterange.hasOwnProperty("offset")||(i.byterange.offset=n?m:0,n&&(m=i.byterange.offset+i.byterange.length)));const s=r.preloadHints.length-1;if(this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${s} for segment #${t}`,e.attributes,["TYPE","URI"]),i.type)for(let e=0;e<r.preloadHints.length-1;e++){const n=r.preloadHints[e];n.type&&n.type===i.type&&this.trigger("warn",{message:`#EXT-X-PRELOAD-HINT #${s} for segment #${t} has the same TYPE ${i.type} as preload hint #${e}`})}},"rendition-report"(){const t=T(e.attributes);this.manifest.renditionReports=this.manifest.renditionReports||[],this.manifest.renditionReports.push(t);const i=this.manifest.renditionReports.length-1,n=["LAST-MSN","URI"];o&&n.push("LAST-PART"),this.warnOnMissingAttributes_(`#EXT-X-RENDITION-REPORT #${i}`,e.attributes,n)},"part-inf"(){this.manifest.partInf=T(e.attributes),this.warnOnMissingAttributes_("#EXT-X-PART-INF",e.attributes,["PART-TARGET"]),this.manifest.partInf.partTarget&&(this.manifest.partTargetDuration=this.manifest.partInf.partTarget),b.call(this,this.manifest)},daterange(){this.manifest.dateRanges.push(T(e.attributes));const t=this.manifest.dateRanges.length-1;this.warnOnMissingAttributes_(`#EXT-X-DATERANGE #${t}`,e.attributes,["ID","START-DATE"]);const i=this.manifest.dateRanges[t];i.endDate&&i.startDate&&new Date(i.endDate)<new Date(i.startDate)&&this.trigger("warn",{message:"EXT-X-DATERANGE END-DATE must be equal to or later than the value of the START-DATE"}),i.duration&&i.duration<0&&this.trigger("warn",{message:"EXT-X-DATERANGE DURATION must not be negative"}),i.plannedDuration&&i.plannedDuration<0&&this.trigger("warn",{message:"EXT-X-DATERANGE PLANNED-DURATION must not be negative"});const n=!!i.endOnNext;if(n&&!i.class&&this.trigger("warn",{message:"EXT-X-DATERANGE with an END-ON-NEXT=YES attribute must have a CLASS attribute"}),n&&(i.duration||i.endDate)&&this.trigger("warn",{message:"EXT-X-DATERANGE with an END-ON-NEXT=YES attribute must not contain DURATION or END-DATE attributes"}),i.duration&&i.endDate){const e=i.startDate.getTime()+1e3*i.duration;this.manifest.dateRanges[t].endDate=new Date(e)}if(g[i.id]){for(const e in g[i.id])if(i[e]&&JSON.stringify(g[i.id][e])!==JSON.stringify(i[e])){this.trigger("warn",{message:"EXT-X-DATERANGE tags with the same ID in a playlist must have the same attributes values"});break}const e=this.manifest.dateRanges.findIndex((e=>e.id===i.id));this.manifest.dateRanges[e]=a(this.manifest.dateRanges[e],i),g[i.id]=a(g[i.id],i),this.manifest.dateRanges.pop()}else g[i.id]=i},"independent-segments"(){this.manifest.independentSegments=!0},"i-frames-only"(){this.manifest.iFramesOnly=!0,this.requiredCompatibilityversion(this.manifest.version,4)},"content-steering"(){this.manifest.contentSteering=T(e.attributes),this.warnOnMissingAttributes_("#EXT-X-CONTENT-STEERING",e.attributes,["SERVER-URI"])},define(){this.manifest.definitions=this.manifest.definitions||{};const t=(e,t)=>{e in this.manifest.definitions?this.trigger("error",{message:`EXT-X-DEFINE: Duplicate name ${e}`}):this.manifest.definitions[e]=t};if("QUERYPARAM"in e.attributes){if("NAME"in e.attributes||"IMPORT"in e.attributes)return void this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"});const i=this.params.get(e.attributes.QUERYPARAM);return i?void t(e.attributes.QUERYPARAM,decodeURIComponent(i)):void this.trigger("error",{message:`EXT-X-DEFINE: No query param ${e.attributes.QUERYPARAM}`})}return"NAME"in e.attributes?"IMPORT"in e.attributes?void this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"}):"VALUE"in e.attributes&&"string"==typeof e.attributes.VALUE?void t(e.attributes.NAME,e.attributes.VALUE):void this.trigger("error",{message:`EXT-X-DEFINE: No value for ${e.attributes.NAME}`}):"IMPORT"in e.attributes?this.mainDefinitions[e.attributes.IMPORT]?void t(e.attributes.IMPORT,this.mainDefinitions[e.attributes.IMPORT]):void this.trigger("error",{message:`EXT-X-DEFINE: No value ${e.attributes.IMPORT} to import, or IMPORT used on main playlist`}):void this.trigger("error",{message:"EXT-X-DEFINE: No attribute"})},"i-frame-playlist"(){this.manifest.iFramePlaylists.push({attributes:e.attributes,uri:e.uri,timeline:l}),this.warnOnMissingAttributes_("#EXT-X-I-FRAME-STREAM-INF",e.attributes,["BANDWIDTH","URI"])}}[e.tagType]||d).call(t)},uri(){r.uri=e.uri,i.push(r),this.manifest.targetDuration&&!("duration"in r)&&(this.trigger("warn",{message:"defaulting segment duration to the target duration"}),r.duration=this.manifest.targetDuration),s&&(r.key=s),r.timeline=l,n&&(r.map=n),m=0,null!==this.lastProgramDateTime&&(r.programDateTime=this.lastProgramDateTime,this.lastProgramDateTime+=1e3*r.duration),r={}},comment(){},custom(){e.segment?(r.custom=r.custom||{},r.custom[e.customType]=e.data):(this.manifest.custom=this.manifest.custom||{},this.manifest.custom[e.customType]=e.data)}})[e.type].call(t)}))}requiredCompatibilityversion(e,t){(e<t||!e)&&this.trigger("warn",{message:`manifest must be at least version ${t}`})}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.manifest.dateRanges.length&&null===this.lastProgramDateTime&&this.trigger("warn",{message:"A playlist with EXT-X-DATERANGE tag must contain atleast one EXT-X-PROGRAM-DATE-TIME tag"}),this.lastProgramDateTime=null,this.trigger("end")}addParser(e){this.parseStream.addParser(e)}addTagMapper(e){this.parseStream.addTagMapper(e)}}var v={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^/},w=["video","audio","text"],I=["Video","Audio","Text"],E=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},A=function(e){void 0===e&&(e="");var t=e.split(","),i=[];return t.forEach((function(e){var t;e=e.trim(),w.forEach((function(n){var s=v[n].exec(e.toLowerCase());if(s&&!(s.length<=1)){t=n;var a=e.substring(0,s[1].length),r=e.replace(a,"");i.push({type:a,details:r,mediaType:n})}})),t||i.push({type:e,details:"",mediaType:"unknown"})})),i},D=function(e){return void 0===e&&(e=""),v.audio.test(e.trim().toLowerCase())},x=function(e){if(e&&"string"==typeof e){var t,i=e.toLowerCase().split(",").map((function(e){return E(e.trim())})),n="video";1===i.length&&D(i[0])?n="audio":1===i.length&&(void 0===(t=i[0])&&(t=""),v.text.test(t.trim().toLowerCase()))&&(n="application");var s="mp4";return i.every((function(e){return v.mp4.test(e)}))?s="mp4":i.every((function(e){return v.webm.test(e)}))?s="webm":i.every((function(e){return v.ogg.test(e)}))&&(s="ogg"),n+"/"+s+';codecs="'+e+'"'}},U=function(e,t){return void 0===e&&(e=""),void 0===t&&(t=!1),window.MediaSource&&window.MediaSource.isTypeSupported&&window.MediaSource.isTypeSupported(x(e))||t&&window.ManagedMediaSource&&window.ManagedMediaSource.isTypeSupported&&window.ManagedMediaSource.isTypeSupported(x(e))||!1},L=function(e){return void 0===e&&(e=""),e.toLowerCase().split(",").every((function(e){e=e.trim();for(var t=0;t<I.length;t++)if(v["muxer"+I[t]].test(e))return!0;return!1}))},P="mp4a.40.2";function C(...e){const t=s.default.obj||s.default;return(t.merge||t.mergeOptions).apply(t,e)}function O(...e){const t=s.default.time||s.default;return(t.createTimeRanges||t.createTimeRanges).apply(t,e)}const k=1/30,R=.1,M=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 O(i)},N=function(e,t){return M(e,(function(e,i){return e-R<=t&&i+R>=t}))},B=function(e,t){return M(e,(function(e){return e-k>=t}))},F=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},$=function(e){if(e&&e.length&&e.end)return e.end(e.length-1)},V=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),a=e.end(n);t>a||(i+=t>s&&t<=a?a-t:a-s)}return i},G=(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},W=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)),[]),H=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},j=(e,t)=>{if(t.endList)return 0;if(e&&e.suggestedPresentationDelay)return e.suggestedPresentationDelay;const i=H(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},z=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+=G(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+=G(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 z(e,t,i)},Q=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},K=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=z(e,e.mediaSequence+e.segments.length,t);return i&&(s-=n="number"==typeof n?n:j(null,e)),Math.max(0,s)},J=function(e){return e.excludeUntil&&e.excludeUntil>Date.now()},Z=function(e){return e.excludeUntil&&e.excludeUntil===1/0},ee=function(e){const t=J(e);return!e.disabled&&!t},te=function(e,t){return t.attributes&&t.attributes[e]},ie=(e,t)=>{if(1===e.playlists.length)return!0;const i=t.attributes.BANDWIDTH||Number.MAX_VALUE;return 0===e.playlists.filter((e=>!!ee(e)&&(e.attributes.BANDWIDTH||0)<i)).length},ne=(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)),se=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 se(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=>D(e))))&&!se(e,(e=>ne(i,e))))return!1}return!0};var re={liveEdgeDelay:j,duration:Y,seekable:function(e,t,i){const n=t||0;let s=K(e,t,!0,i);return null===s?O():(s<n&&(s=n),O(n,s))},getMediaInfoForTime:function({playlist:e,currentTime:t,startingSegmentIndex:i,startingPartIndex:n,startTime:s,exactManifestTimings:a}){let r=t-s;const o=W(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(r<0){if(d>0)for(let t=d-1;t>=0;t--){const i=o[t];if(r+=i.duration,a){if(r<0)continue}else if(r+k<=0)continue;return{partIndex:i.partIndex,segmentIndex:i.segmentIndex,startTime:s-Q({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(r-=e.targetDuration,r<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];r-=i.duration;const n=i.duration>k&&r+k>=0;if(0!==r&&!n||t===o.length-1){if(a){if(r>0)continue}else if(r-k>=0)continue;return{partIndex:i.partIndex,segmentIndex:i.segmentIndex,startTime:s+Q({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:ee,isDisabled:function(e){return e.disabled},isExcluded:J,isIncompatible:Z,playlistEnd:K,isAes:function(e){for(let t=0;t<e.segments.length;t++)if(e.segments[t].key)return!0;return!1},hasAttribute:te,estimateSegmentRequestTime:function(e,t,i,n=0){return te("BANDWIDTH",i)?(e*i.attributes.BANDWIDTH-8*n)/t:NaN},isLowestEnabledRendition:ie,isAudioOnly:ae,playlistMatch:ne,segmentDurationWithParts:G};const{log:oe}=s.default,de=(e,t)=>`${e}-${t}`,ue=(e,t,i)=>`placeholder-uri-${e}-${t}-${i}`,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 a=e.mediaGroups[i][n][s];t(a,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,i=ue)=>{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 n=ae(e);le(e,((t,s,r,o)=>{if(!t.playlists||!t.playlists.length){if(n&&"AUDIO"===s&&!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===r)return}t.playlists=[a({},t)]}t.playlists.forEach((function(t,n){const a=i(s,r,o,t),u=de(n,a);t.uri?t.resolvedUri=t.resolvedUri||d(e.uri,t.uri):(t.uri=0===n?a:u,t.resolvedUri=t.uri),t.id=t.id||u,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:de(t,i.uri)}),i.resolvedUri=d(e.uri,i.uri),e.playlists[i.id]=i,e.playlists[i.uri]=i,i.attributes.BANDWIDTH||oe.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.")}})(e),(e=>{le(e,(t=>{t.uri&&(t.resolvedUri=d(e.uri,t.uri))}))})(e)};class pe{constructor(){this.offset_=null,this.pendingDateRanges_=new Map,this.processedDateRanges_=new Map}setOffset(e=[]){if(null!==this.offset_)return;if(!e.length)return;const[t]=e;void 0!==t.programDateTime&&(this.offset_=t.programDateTime/1e3)}setPendingDateRanges(e=[]){if(!e.length)return;const[t]=e,i=t.startDate.getTime();this.trimProcessedDateRanges_(i),this.pendingDateRanges_=e.reduce(((e,t)=>(e.set(t.id,t),e)),new Map)}processDateRange(e){this.pendingDateRanges_.delete(e.id),this.processedDateRanges_.set(e.id,e)}getDateRangesToProcess(){if(null===this.offset_)return[];const e={},t=[];this.pendingDateRanges_.forEach(((i,n)=>{if(!this.processedDateRanges_.has(n)&&(i.startTime=i.startDate.getTime()/1e3-this.offset_,i.processDateRange=()=>this.processDateRange(i),t.push(i),i.class))if(e[i.class]){const t=e[i.class].push(i);i.classListIndex=t-1}else e[i.class]=[i],i.classListIndex=0}));for(const i of t){const t=e[i.class]||[];i.endDate?i.endTime=i.endDate.getTime()/1e3-this.offset_:i.endOnNext&&t[i.classListIndex+1]?i.endTime=t[i.classListIndex+1].startTime:i.duration?i.endTime=i.startTime+i.duration:i.plannedDuration?i.endTime=i.startTime+i.plannedDuration:i.endTime=i.startTime}return t}trimProcessedDateRanges_(e){new Map(this.processedDateRanges_).forEach(((t,i)=>{t.startDate.getTime()<e&&this.processedDateRanges_.delete(i)}))}}const me=({requestType:e,request:t,error:i,parseFailure:n})=>{const r=t.status<200||t.status>299,o=t.status>=400&&t.status<=499,d={uri:t.uri,requestType:e},u=r&&!o||n;if(i&&o)d.error=a({},i),d.errorType=s.default.Error.NetworkRequestFailed;else if(t.aborted)d.errorType=s.default.Error.NetworkRequestAborted;else if(t.timedout)d.erroType=s.default.Error.NetworkRequestTimeout;else if(u){const e=n?s.default.Error.NetworkBodyParserFailed:s.default.Error.NetworkBadStatus;d.errorType=e,d.status=t.status,d.headers=t.headers}return d},ge=l("CodecUtils"),fe=function(e){const t=e.attributes||{};if(t.CODECS)return A(t.CODECS)},ye=(e,t)=>{const i=t.attributes||{};return e&&e.mediaGroups&&e.mediaGroups.AUDIO&&i.AUDIO&&e.mediaGroups.AUDIO[i.AUDIO]},_e=function(e){const t={};return e.forEach((({mediaType:e,type:i,details:n})=>{t[e]=t[e]||[],t[e].push(E(`${i}${n}`))})),Object.keys(t).forEach((function(e){if(t[e].length>1)return ge(`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},Te=function(e){let t=0;return e.audio&&t++,e.video&&t++,t},be=function(e,t){const i=t.attributes||{},n=_e(fe(t)||[]);if(ye(e,t)&&!n.audio&&!((e,t)=>{if(!ye(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=_e(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 A(s.playlists[0].attributes.CODECS)}return null}(e,i.AUDIO)||[]);t.audio&&(n.audio=t.audio)}return n},{EventTarget:Se}=s.default,ve=(e,t)=>{if(!e)return t;const i=C(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]=C(e.parts[n],t.parts[n]));return!e.skipped&&t.skipped&&(i.skipped=!1),e.preload&&!t.preload&&(i.preload=!1),i},we=(e,t)=>{!e.resolvedUri&&e.uri&&(e.resolvedUri=d(t,e.uri)),e.key&&!e.key.resolvedUri&&(e.key.resolvedUri=d(t,e.key.uri)),e.map&&!e.map.resolvedUri&&(e.map.resolvedUri=d(t,e.map.uri)),e.map&&e.map.key&&!e.map.key.resolvedUri&&(e.map.key.resolvedUri=d(t,e.map.key.uri)),e.parts&&e.parts.length&&e.parts.forEach((e=>{e.resolvedUri||(e.resolvedUri=d(t,e.uri))})),e.preloadHints&&e.preloadHints.length&&e.preloadHints.forEach((e=>{e.resolvedUri||(e.resolvedUri=d(t,e.uri))}))},Ie=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},Ee=(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,Ae=(e,t,i=Ee)=>{const n=C(e,{}),s=n.playlists[t.id];if(!s)return null;if(i(s,t))return null;t.segments=Ie(t);const a=C(s,t);if(a.preloadSegment&&!t.preloadSegment&&delete a.preloadSegment,s.segments){if(t.skip){t.segments=t.segments||[];for(let e=0;e<t.skip.skippedSegments;e++)t.segments.unshift({skipped:!0})}a.segments=((e,t,i)=>{const n=e.slice(),s=t.slice();i=i||0;const a=[];let r;for(let e=0;e<s.length;e++){const t=n[e+i],o=s[e];t?(r=t.map||r,a.push(ve(t,o))):(r&&!o.map&&(o.map=r),a.push(o))}return a})(s.segments,t.segments,t.mediaSequence-s.mediaSequence)}a.segments.forEach((e=>{we(e,a.resolvedUri)}));for(let e=0;e<n.playlists.length;e++)n.playlists[e].id===t.id&&(n.playlists[e]=a);return n.playlists[t.id]=a,n.playlists[t.uri]=a,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]=a)})),n},De=(e,t)=>{const i=e.segments||[],n=i[i.length-1],s=n&&n.parts&&n.parts[n.parts.length-1],a=s&&s.duration||n&&n.duration;return t&&a?1e3*a:500*(e.partTargetDuration||e.targetDuration||10)},xe=(e,t,i)=>{if(!e)return;const n=[];return e.forEach((e=>{if(!e.attributes)return;const{BANDWIDTH:t,RESOLUTION:i,CODECS:s}=e.attributes;n.push({id:e.id,bandwidth:t,resolution:i,codecs:s})})),{type:t,isLive:i,renditions:n}};class Ue extends Se{constructor(e,t,i={}){if(super(),!e)throw new Error("A non-empty playlist URL or object is required");this.logger_=l("PlaylistLoader");const{withCredentials:n=!1}=i;this.src=e,this.vhs_=t,this.withCredentials=n,this.addDateRangesToTextTrack_=i.addDateRangesToTextTrack;const s=t.options_;this.customTagParsers=s&&s.customTagParsers||[],this.customTagMappers=s&&s.customTagMappers||[],this.llhls=s&&s.llhls,this.dateRangesStorage_=new pe,this.state="HAVE_NOTHING",this.handleMediaupdatetimeout_=this.handleMediaupdatetimeout_.bind(this),this.on("mediaupdatetimeout",this.handleMediaupdatetimeout_),this.on("loadedplaylist",this.handleLoadedPlaylist_.bind(this))}handleLoadedPlaylist_(){const e=this.media();if(!e)return;this.dateRangesStorage_.setOffset(e.segments),this.dateRangesStorage_.setPendingDateRanges(e.dateRanges);const t=this.dateRangesStorage_.getDateRangesToProcess();t.length&&this.addDateRangesToTextTrack_&&this.addDateRangesToTextTrack_(t)}handleMediaupdatetimeout_(){if("HAVE_METADATA"!==this.state)return;const e=this.media();let t=d(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||[],a=X(t)-1;a>-1&&a!==s.length-1&&(i._HLS_part=a),(a>-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,requestType:"hls-playlist"},((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,metadata:me({requestType:e.requestType,request:e,error:e.error})},this.trigger("error")}parseManifest_({url:e,manifestString:t}){try{const i=(({onwarn:e,oninfo:t,manifestString:i,customTagParsers:n=[],customTagMappers:s=[],llhls:a})=>{const r=new S;e&&r.on("warn",e),t&&r.on("info",t),n.forEach((e=>r.addParser(e))),s.forEach((e=>r.addTagMapper(e))),r.push(i),r.end();const o=r.manifest;if(a||(["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({message:`manifest has no targetDuration defaulting to ${t}`}),o.targetDuration=t}const d=H(o);if(d.length&&!o.partTargetDuration){const t=d.reduce(((e,t)=>Math.max(e,t.duration)),0);e&&(e({message:`manifest has no partTargetDuration defaulting to ${t}`}),oe.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});return i.playlists&&i.playlists.length?(this.excludeAudioOnlyVariants(i.playlists),i):i}catch(e){this.error=e,this.error.metadata={errorType:s.default.Error.StreamingHlsPlaylistParserError,error:e}}}excludeAudioOnlyVariants(e){const t=e=>{const t=e.attributes||{},{width:i,height:n}=t.RESOLUTION||{};if(i&&n)return!0;const s=fe(e)||[],a=_e(s);return Boolean(a.video)};e.some(t)&&e.forEach((e=>{t(e)||(e.excludeUntil=1/0)}))}haveMetadata({playlistString:e,playlistObject:t,url:i,id:n}){this.request=null,this.state="HAVE_METADATA";const s={playlistInfo:{type:"media",uri:i}};this.trigger({type:"playlistparsestart",metadata:s});const a=t||this.parseManifest_({url:i,manifestString:e});a.lastRequest=Date.now(),he({playlist:a,uri:i,id:n});const r=Ae(this.main,a);this.targetDuration=a.partTargetDuration||a.targetDuration,this.pendingMedia_=null,r?(this.main=r,this.media_=this.main.playlists[n]):this.trigger("playlistunchanged"),this.updateMediaUpdateTimeout_(De(this.media(),!!r)),s.parsedPlaylist=xe(this.main.playlists,s.playlistInfo.type,!this.media_.endList),this.trigger({type:"playlistparsecomplete",metadata:s}),this.trigger("loadedplaylist")}dispose(){this.trigger("dispose"),this.stopRequest(),window.clearTimeout(this.mediaUpdateTimeout),window.clearTimeout(this.finalRenditionTimeout),this.dateRangesStorage_=new pe,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_(De(e,!0)),!n)return;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;const a={playlistInfo:{type:"media",uri:e.uri}};this.trigger({type:"playlistrequeststart",metadata:a}),this.request=this.vhs_.xhr({uri:e.resolvedUri,withCredentials:this.withCredentials,requestType:"hls-playlist"},((t,n)=>{if(this.request){if(e.lastRequest=Date.now(),e.resolvedUri=u(e.resolvedUri,n),t)return this.playlistRequestError(this.request,e,i);this.trigger({type:"playlistrequestcomplete",metadata:a}),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);const e={playlistInfo:{type:"multivariant",uri:this.src}};this.trigger({type:"playlistrequeststart",metadata:e}),this.request=this.vhs_.xhr({uri:this.src,withCredentials:this.withCredentials,requestType:"hls-playlist"},((t,i)=>{if(!this.request)return;if(this.request=null,t)return this.error={status:i.status,message:`HLS playlist request error at URL: ${this.src}.`,responseText:i.responseText,code:2,metadata:me({requestType:i.requestType,request:i,error:t})},"HAVE_NOTHING"===this.state&&(this.started=!1),this.trigger("error");this.trigger({type:"playlistrequestcomplete",metadata:e}),this.src=u(this.src,i),this.trigger({type:"playlistparsestart",metadata:e});const n=this.parseManifest_({manifestString:i.responseText,url:this.src});e.parsedPlaylist=xe(n.playlists,e.playlistInfo.type,!1),this.trigger({type:"playlistparsecomplete",metadata:e}),this.setupInitialPlaylist(n)}))}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=Ie(e),e.segments.forEach((t=>{we(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=de(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")}updateOrDeleteClone(e,t){const i=this.main,n=e.ID;let s=i.playlists.length;for(;s--;){const a=i.playlists[s];if(a.attributes["PATHWAY-ID"]===n){const r=a.resolvedUri,o=a.id;if(t){const t=this.createCloneURI_(a.resolvedUri,e),r=de(n,t),o=this.createCloneAttributes_(n,a.attributes),d=this.createClonePlaylist_(a,r,e,o);i.playlists[s]=d,i.playlists[r]=d,i.playlists[t]=d}else i.playlists.splice(s,1);delete i.playlists[o],delete i.playlists[r]}}this.updateOrDeleteCloneMedia(e,t)}updateOrDeleteCloneMedia(e,t){const i=this.main,n=e.ID;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((e=>{if(i.mediaGroups[e]&&i.mediaGroups[e][n])for(const t in i.mediaGroups[e])if(t===n){for(const n in i.mediaGroups[e][t])i.mediaGroups[e][t][n].playlists.forEach(((e,t)=>{const n=i.playlists[e.id],s=n.id,a=n.resolvedUri;delete i.playlists[s],delete i.playlists[a]}));delete i.mediaGroups[e][t]}})),t&&this.createClonedMediaGroups_(e)}addClonePathway(e,t={}){const i=this.main,n=i.playlists.length,s=this.createCloneURI_(t.resolvedUri,e),a=de(e.ID,s),r=this.createCloneAttributes_(e.ID,t.attributes),o=this.createClonePlaylist_(t,a,e,r);i.playlists[n]=o,i.playlists[a]=o,i.playlists[s]=o,this.createClonedMediaGroups_(e)}createClonedMediaGroups_(e){const t=e.ID,i=e["BASE-ID"],n=this.main;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((s=>{if(n.mediaGroups[s]&&!n.mediaGroups[s][t])for(const r in n.mediaGroups[s])if(r===i){n.mediaGroups[s][t]={};for(const i in n.mediaGroups[s][r]){const o=n.mediaGroups[s][r][i];n.mediaGroups[s][t][i]=a({},o);const d=n.mediaGroups[s][t][i],u=this.createCloneURI_(o.resolvedUri,e);d.resolvedUri=u,d.uri=u,d.playlists=[],o.playlists.forEach(((a,r)=>{const o=n.playlists[a.id],u=ue(s,t,i),l=de(t,u);if(o&&!n.playlists[l]){const t=this.createClonePlaylist_(o,l,e),i=t.resolvedUri;n.playlists[l]=t,n.playlists[i]=t}d.playlists[r]=this.createClonePlaylist_(a,l,e)}))}}}))}createClonePlaylist_(e,t,i,n){const s=this.createCloneURI_(e.resolvedUri,i),a={resolvedUri:s,uri:s,id:t};return e.segments&&(a.segments=[]),n&&(a.attributes=n),C(e,a)}createCloneURI_(e,t){const i=new URL(e);i.hostname=t["URI-REPLACEMENT"].HOST;const n=t["URI-REPLACEMENT"].PARAMS;for(const e of Object.keys(n))i.searchParams.set(e,n[e]);return i.href}createCloneAttributes_(e,t){const i={"PATHWAY-ID":e};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((n=>{t[n]&&(i[n]=e)})),i}getKeyIdSet(e){if(e.contentProtection){const t=new Set;for(const i in e.contentProtection){const n=e.contentProtection[i].attributes.keyId;n&&t.add(n.toLowerCase())}return t}}}const Le=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)},Pe=function(){const e=function e(t,i){t=C({timeout:45e3},t);const n=e.beforeRequest||s.default.Vhs.xhr.beforeRequest,a=e._requestCallbackSet||s.default.Vhs.xhr._requestCallbackSet||new Set,r=e._responseCallbackSet||s.default.Vhs.xhr._responseCallbackSet;n&&"function"==typeof n&&(s.default.log.warn("beforeRequest is deprecated, use onRequest instead."),a.add(n));const o=!0===s.default.Vhs.xhr.original?s.default.xhr:s.default.Vhs.xhr,d=((e,t)=>{if(!e||!e.size)return;let i=t;return e.forEach((e=>{i=e(i)})),i})(a,t);a.delete(n);const u=o(d||t,(function(e,t){return((e,t,i,n)=>{e&&e.size&&e.forEach((e=>{e(t,i,n)}))})(r,u,e,t),Le(u,e,t,i)})),l=u.abort;return u.abort=function(){return u.aborted=!0,l.apply(u,arguments)},u.uri=t.uri,u.requestType=t.requestType,u.requestTime=Date.now(),u};return e.original=!0,e},Ce=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 Oe,ke,Re=/^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i,Me=/^application\/dash\+xml/i,Ne=function(e){return Re.test(e)?"hls":Me.test(e)?"dash":"application/vnd.videojs.vhs+json"===e?"vhs-json":null},Be=function(e){return"function"===ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer},Fe=function(e){return e instanceof Uint8Array?e:(Array.isArray(e)||Be(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))},qe=window.BigInt||Number,$e=[qe("0x1"),qe("0x100"),qe("0x10000"),qe("0x1000000"),qe("0x100000000"),qe("0x10000000000"),qe("0x1000000000000"),qe("0x100000000000000"),qe("0x10000000000000000")];Oe=new Uint16Array([65484]),255===(ke=new Uint8Array(Oe.buffer,Oe.byteOffset,Oe.byteLength))[0]||ke[0];var Ve=function(e,t){var i=void 0===t?{}:t,n=i.signed,s=void 0!==n&&n,a=i.le,r=void 0!==a&&a;e=Fe(e);var o=r?"reduce":"reduceRight",d=(e[o]?e[o]:Array.prototype[o]).call(e,(function(t,i,n){var s=r?n:Math.abs(n+1-e.length);return t+qe(i)*$e[s]}),qe(0));if(s){var u=$e[e.length]/qe(2)-qe(1);(d=qe(d))>u&&(d-=u,d-=u,d-=qe(2))}return Number(d)},Ge=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},We=function(e,t,i){var n=void 0===i?{}:i,s=n.offset,a=void 0===s?0:s,r=n.mask,o=void 0===r?[]:r;e=Fe(e);var d=(t=Fe(t)).every?t.every:Array.prototype.every;return t.length&&e.length-a>=t.length&&d.call(t,(function(t,i){return t===(o[i]?o[i]&e[a+i]:e[a+i])}))};const He=function(e,t){return e.start(t)+"-"+e.end(t)},Xe=function(e,t){const i=e.toString(16);return"00".substring(0,2-i.length)+i+(t%2?" ":"")},je=function(e){return e>=32&&e<126?String.fromCharCode(e):"."},ze=function(e){const t={};return Object.keys(e).forEach((i=>{const n=e[i];Be(n)?t[i]={bytes:n.buffer,byteOffset:n.byteOffset,byteLength:n.byteLength}:t[i]=n})),t},Ye=function(e){const t=e.byterange||{length:1/0,offset:0};return[t.length,t.offset,e.resolvedUri].join(",")},Qe=function(e){return e.resolvedUri},Ke=e=>{const t=Array.prototype.slice.call(e),i=16;let n,s,a="";for(let e=0;e<t.length/i;e++)n=t.slice(e*i,e*i+i).map(Xe).join(""),s=t.slice(e*i,e*i+i).map(je).join(""),a+=n+" "+s+"\n";return a};var Je=Object.freeze({__proto__:null,createTransferableMessage:ze,initSegmentId:Ye,segmentKeyId:Qe,hexDump:Ke,tagDump:({bytes:e})=>Ke(e),textRanges:e=>{let t,i="";for(t=0;t<e.length;t++)i+=He(e,t)+" ";return i}});const Ze=({programTime:e,playlist:t,retryCount:i=2,seekTo:n,pauseAfterSeek:s=!0,tech:a,callback:r})=>{if(!r)throw new Error("seekToProgramTime: callback must be provided");if(void 0===e||!t||!n)return r({message:"seekToProgramTime: programTime, seekTo and playlist must be provided"});if(!t.endList&&!a.hasStarted_)return r({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 r({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<new Date(n.dateTimeObject))return null;for(let e=0;e<t.segments.length-1&&(n=t.segments[e],!(i<new Date(t.segments[e+1].dateTimeObject)));e++);const s=t.segments[t.segments.length-1],a=s.dateTimeObject,r=s.videoTimingInfo?(o=s.videoTimingInfo).transmuxedPresentationEnd-o.transmuxedPresentationStart-o.transmuxerPrependedSeconds:s.duration+.25*s.duration;var o;return i>new Date(a.getTime()+1e3*r)?null:(i>new Date(a)&&(n=s),{segment:n,estimatedStart:n.videoTimingInfo?n.videoTimingInfo.transmuxedPresentationStart:re.duration(t,t.mediaSequence+t.segments.indexOf(n)),type:n.videoTimingInfo?"accurate":"estimate"})})(e,t);if(!o)return r({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?r({message:`${e} is not buffered yet. Try again`}):(n(o.estimatedStart+u),void a.one("seeked",(()=>{Ze({programTime:e,playlist:t,retryCount:i-1,seekTo:n,pauseAfterSeek:s,tech:a,callback:r})})));const l=d.start+u;a.one("seeked",(()=>r(null,a.currentTime()))),s&&a.pause(),n(l)},et=e=>!!e&&"object"==typeof e,tt=(...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]):et(e[i])&&et(t[i])?e[i]=tt(e[i],t[i]):e[i]=t[i]})),e)),{}),it=e=>Object.keys(e).map((t=>e[t])),nt=e=>e.reduce(((e,t)=>e.concat(t)),[]),st=e=>{if(!e.length)return[];const t=[];for(let i=0;i<e.length;i++)t.push(e[i]);return t};const at=({baseUrl:e="",source:t="",range:i="",indexRange:n=""})=>{const s={uri:t,resolvedUri:o(e||"",t)};if(i||n){const e=(i||n).split("-");let t,a=window.BigInt?window.BigInt(e[0]):parseInt(e[0],10),r=window.BigInt?window.BigInt(e[1]):parseInt(e[1],10);a<Number.MAX_SAFE_INTEGER&&"bigint"==typeof a&&(a=Number(a)),r<Number.MAX_SAFE_INTEGER&&"bigint"==typeof r&&(r=Number(r)),t="bigint"==typeof r||"bigint"==typeof a?window.BigInt(r)-window.BigInt(a)+window.BigInt(1):r-a+1,"bigint"==typeof t&&t<Number.MAX_SAFE_INTEGER&&(t=Number(t)),s.byterange={length:t,offset:a}}return s},rt=e=>(e&&"number"!=typeof e&&(e=parseInt(e,10)),isNaN(e)?null:e),ot={static(e){const{duration:t,timescale:i=1,sourceDuration:n,periodDuration:s}=e,a=rt(e.endNumber),r=t/i;return"number"==typeof a?{start:0,end:a}:"number"==typeof s?{start:0,end:s/r}:{start:0,end:n/r}},dynamic(e){const{NOW:t,clientOffset:i,availabilityStartTime:n,timescale:s=1,duration:a,periodStart:r=0,minimumUpdatePeriod:o=0,timeShiftBufferDepth:d=1/0}=e,u=rt(e.endNumber),l=(t+i)/1e3,h=n+r,c=l+o-h,p=Math.ceil(c*s/a),m=Math.floor((l-h-d)*s/a),g=Math.floor((l-h)*s/a);return{start:Math.max(0,m),end:"number"==typeof u?u:Math.min(p,g)}}},dt=e=>{const{type:t,duration:i,timescale:n=1,periodDuration:s,sourceDuration:a}=e,{start:r,end:o}=ot[t](e),d=((e,t)=>{const i=[];for(let n=e;n<t;n++)i.push(n);return i})(r,o).map((e=>t=>{const{duration:i,timescale:n=1,periodStart:s,startNumber:a=1}=e;return{number:a+t,duration:i/n,timeline:s,time:t*i}})(e));if("static"===t){const e=d.length-1,t="number"==typeof s?s:a;d[e].duration=t-i/n*e}return d},ut=e=>{const{baseUrl:t,initialization:i={},sourceDuration:n,indexRange:s="",periodStart:a,presentationTime:r,number:o=0,duration:d}=e;if(!t)throw new Error("NO_BASE_URL");const u=at({baseUrl:t,source:i.sourceURL,range:i.range}),l=at({baseUrl:t,source:t,indexRange:s});if(l.map=u,d){const t=dt(e);t.length&&(l.duration=t[0].duration,l.timeline=t[0].timeline)}else n&&(l.duration=n,l.timeline=a);return l.presentationTime=r||a,l.number=o,[l]},lt=(e,t,i)=>{const n=e.sidx.map?e.sidx.map:null,s=e.sidx.duration,a=e.timeline||0,r=e.sidx.byterange,o=r.offset+r.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,g=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 r=t.references[e],o=r.referencedSize,u=r.subsegmentDuration;let f;f="bigint"==typeof p?p+window.BigInt(o)-window.BigInt(1):p+o-1;const y=ut({baseUrl:i,timescale:d,timeline:a,periodStart:c,presentationTime:m,number:g,duration:u,sourceDuration:s,indexRange:`${p}-${f}`,type:h})[0];n&&(y.map=n),l.push(y),p+="bigint"==typeof p?window.BigInt(o):o,m+=u/d,g++}return e.segments=l,e},ht=["AUDIO","SUBTITLES"],ct=e=>{return(t=e,i=({timeline:e})=>e,it(t.reduce(((e,t)=>(t.forEach((t=>{e[i(t)]=t})),e)),{}))).sort(((e,t)=>e.timeline>t.timeline?1:-1));var t,i},pt=e=>{let t=[];var i,n;return i=e,n=(e,i,n,s)=>{t=t.concat(e.playlists||[])},ht.forEach((function(e){for(var t in i.mediaGroups[e])for(var s in i.mediaGroups[e][t]){var a=i.mediaGroups[e][t][s];n(a)}})),t},mt=({playlist:e,mediaSequence:t})=>{e.mediaSequence=t,e.segments.forEach(((t,i)=>{t.number=e.mediaSequence+i}))},gt=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),ft=e=>{const t=e.reduce((function(e,t){return e[t.attributes.baseUrl]||(e[t.attributes.baseUrl]=[]),e[t.attributes.baseUrl].push(t),e}),{});let i=[];return Object.values(t).forEach((e=>{const t=it(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}),{}));i=i.concat(t)})),i.map((e=>{var t;return e.discontinuityStarts=(t=e.segments||[],"discontinuity",t.reduce(((e,t,i)=>(t.discontinuity&&e.push(i),e)),[])),e}))},yt=(e,t)=>{const i=gt(e.sidx),n=i&&t[i]&&t[i].sidx;return n&<(e,n,e.sidx.resolvedUri),e},_t=(e,t={})=>{if(!Object.keys(t).length)return e;for(const i in e)e[i]=yt(e[i],t);return e},Tt=({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:e.baseUrl||"",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),e.serviceLocation&&(s.attributes.serviceLocation=e.serviceLocation),i&&(s.sidx=i),s},bt=({attributes:e})=>"video/mp4"===e.mimeType||"video/webm"===e.mimeType||"video"===e.contentType,St=({attributes:e})=>"audio/mp4"===e.mimeType||"audio/webm"===e.mimeType||"audio"===e.contentType,vt=({attributes:e})=>"text/vtt"===e.mimeType||"text"===e.contentType,wt=e=>e?Object.keys(e).reduce(((t,i)=>{const n=e[i];return t.concat(n.playlists)}),[]):[],It=({dashPlaylists:e,locations:t,contentSteering:i,sidxMapping:n={},previousManifest:s,eventStream:a})=>{if(!e.length)return{};const{sourceDuration:r,type:o,suggestedPresentationDelay:d,minimumUpdatePeriod:u}=e[0].attributes,l=ft(e.filter(bt)).map(Tt),h=ft(e.filter(St)),c=ft(e.filter(vt)),p=e.map((e=>e.attributes.captionServices)).filter(Boolean),m={allowCache:!0,discontinuityStarts:[],segments:[],endList:!0,mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:"",duration:r,playlists:_t(l,n)};u>=0&&(m.minimumUpdatePeriod=1e3*u),t&&(m.locations=t),i&&(m.contentSteering=i),"dynamic"===o&&(m.suggestedPresentationDelay=d),a&&a.length>0&&(m.eventStream=a);const g=0===m.playlists.length,f=h.length?((e,t={},i=!1)=>{let n;const s=e.reduce(((e,s)=>{const a=s.attributes.role&&s.attributes.role.value||"",r=s.attributes.lang||"";let o=s.attributes.label||"main";if(r&&!s.attributes.label){const e=a?` (${a})`:"";o=`${s.attributes.lang}${e}`}e[o]||(e[o]={language:r,autoselect:!0,default:"main"===a,playlists:[],uri:""});const d=yt((({attributes:e,segments:t,sidx:i,mediaSequence:n,discontinuitySequence:s,discontinuityStarts:a},r)=>{const o={attributes:{NAME:e.id,BANDWIDTH:e.bandwidth,CODECS:e.codecs,"PROGRAM-ID":1},uri:"",endList:"static"===e.type,timeline:e.periodStart,resolvedUri:e.baseUrl||"",targetDuration:e.duration,discontinuitySequence:s,discontinuityStarts:a,timelineStarts:e.timelineStarts,mediaSequence:n,segments:t};return e.contentProtection&&(o.contentProtection=e.contentProtection),e.serviceLocation&&(o.attributes.serviceLocation=e.serviceLocation),i&&(o.sidx=i),r&&(o.attributes.AUDIO="audio",o.attributes.SUBTITLES="subs"),o})(s,i),t);return e[o].playlists.push(d),void 0===n&&"main"===a&&(n=s,n.default=!0),e}),{});return n||(s[Object.keys(s)[0]].default=!0),s})(h,n,g):null,y=c.length?((e,t={})=>e.reduce(((e,i)=>{const n=i.attributes.label||i.attributes.lang||"text",s=i.attributes.lang||"und";return e[n]||(e[n]={language:s,default:!1,autoselect:!1,playlists:[],uri:""}),e[n].playlists.push(yt((({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 a={NAME:e.id,BANDWIDTH:e.bandwidth,"PROGRAM-ID":1};e.codecs&&(a.CODECS=e.codecs);const r={attributes:a,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};return e.serviceLocation&&(r.attributes.serviceLocation=e.serviceLocation),r})(i),t)),e}),{}))(c,n):null,_=l.concat(wt(f),wt(y)),T=_.map((({timelineStarts:e})=>e));var b,S;return m.timelineStarts=ct(T),b=_,S=m.timelineStarts,b.forEach((e=>{e.mediaSequence=0,e.discontinuitySequence=S.findIndex((function({timeline:t}){return t===e.timeline})),e.segments&&e.segments.forEach(((e,t)=>{e.number=t}))})),f&&(m.mediaGroups.AUDIO.audio=f),y&&(m.mediaGroups.SUBTITLES.subs=y),p.length&&(m.mediaGroups["CLOSED-CAPTIONS"].cc=p.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),{})),s?(({oldManifest:e,newManifest:t})=>{const i=e.playlists.concat(pt(e)),n=t.playlists.concat(pt(t));return t.timelineStarts=ct([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],a=n.segments.findIndex((function(e){return Math.abs(e.presentationTime-s.presentationTime)<.016666666666666666}));if(-1===a)return mt({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[a].discontinuity&&!s.discontinuity&&(s.discontinuity=!0,t.discontinuityStarts.unshift(0),t.discontinuitySequence--),mt({playlist:t,mediaSequence:n.segments[a].number})}))})({oldPlaylists:i,newPlaylists:n,timelineStarts:t.timelineStarts}),t})({oldManifest:s,newManifest:m}):m},Et=(e,t,i)=>{const{NOW:n,clientOffset:s,availabilityStartTime:a,timescale:r=1,periodStart:o=0,minimumUpdatePeriod:d=0}=e,u=(n+s)/1e3+d-(a+o);return Math.ceil((u*r-t)/i)},At=(e,t)=>{const{type:i,minimumUpdatePeriod:n=0,media:s="",sourceDuration:a,timescale:r=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,g=c.t||0;let f;if(l<0&&(l=g),g&&g>l&&(l=g),m<0){const o=h+1;f=o===t.length?"dynamic"===i&&n>0&&s.indexOf("$Number$")>0?Et(e,l,p):(a*r-l)/p:(t[o].t-l)/p}else f=m+1;const y=o+u.length+f;let _=o+u.length;for(;_<y;)u.push({number:_,duration:p/r,time:l,timeline:d}),l+=p,_++}return u},Dt=/\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g,xt=(e,t)=>e.replace(Dt,(e=>(t,i,n,s)=>{if("$$"===t)return"$";if(void 0===e[i])return t;const a=""+e[i];return"RepresentationID"===i?a:(s=n?parseInt(s,10):1,a.length>=s?a:`${new Array(s-a.length+1).join("0")}${a}`)})(t)),Ut=(e,t)=>{const i={RepresentationID:e.id,Bandwidth:e.bandwidth||0},{initialization:n={sourceURL:"",range:""}}=e,s=at({baseUrl:e.baseUrl,source:xt(n.sourceURL,i),range:n.range}),a=((e,t)=>e.duration||t?e.duration?dt(e):At(e,t):[{number:e.startNumber||1,duration:e.sourceDuration,time:0,timeline:e.periodStart}])(e,t);return a.map((t=>{i.Number=t.number,i.Time=t.time;const n=xt(e.media||"",i),a=e.timescale||1,r=e.presentationTimeOffset||0,d=e.periodStart+(t.time-r)/a;return{uri:n,timeline:t.timeline,duration:t.duration,resolvedUri:o(e.baseUrl||"",n),map:s,number:t.number,presentationTime:d}}))},Lt=(e,t)=>{const{duration:i,segmentUrls:n=[],periodStart:s}=e;if(!i&&!t||i&&t)throw new Error("SEGMENT_TIME_UNSPECIFIED");const a=n.map((t=>((e,t)=>{const{baseUrl:i,initialization:n={}}=e,s=at({baseUrl:i,source:n.sourceURL,range:n.range}),a=at({baseUrl:i,source:t.media,range:t.mediaRange});return a.map=s,a})(e,t)));let r;return i&&(r=dt(e)),t&&(r=At(e,t)),r.map(((t,i)=>{if(a[i]){const n=a[i],r=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)/r,n}})).filter((e=>e))},Pt=({attributes:e,segmentInfo:t})=>{let i,n;t.template?(n=Ut,i=tt(e,t.template)):t.base?(n=ut,i=tt(e,t.base)):t.list&&(n=Lt,i=tt(e,t.list));const s={attributes:e};if(!n)return s;const a=n(i,t.segmentTimeline);if(i.duration){const{duration:e,timescale:t=1}=i;i.duration=e/t}else a.length?i.duration=a.reduce(((e,t)=>Math.max(e,Math.ceil(t.duration))),0):i.duration=0;return s.attributes=i,s.segments=a,t.base&&i.indexRange&&(s.sidx=a[0],s.segments=[]),s},Ct=(e,t)=>st(e.childNodes).filter((({tagName:e})=>e===t)),Ot=e=>e.textContent.trim(),kt=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,a,r,o]=t.slice(1);return 31536e3*parseFloat(i||0)+2592e3*parseFloat(n||0)+86400*parseFloat(s||0)+3600*parseFloat(a||0)+60*parseFloat(r||0)+parseFloat(o||0)},Rt={mediaPresentationDuration:e=>kt(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=>kt(e),suggestedPresentationDelay:e=>kt(e),type:e=>e,timeShiftBufferDepth:e=>kt(e),start:e=>kt(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)?kt(e):t},d:e=>parseInt(e,10),t:e=>parseInt(e,10),r:e=>parseInt(e,10),presentationTime:e=>parseInt(e,10),DEFAULT:e=>e},Mt=e=>e&&e.attributes?st(e.attributes).reduce(((e,t)=>{const i=Rt[t.name]||Rt.DEFAULT;return e[t.name]=i(t.value),e}),{}):{},Nt={"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","urn:mpeg:dash:mp4protection:2011":"mp4protection"},Bt=(e,t)=>t.length?nt(e.map((function(e){return t.map((function(t){const i=Ot(t),n=o(e.baseUrl,i),s=tt(Mt(t),{baseUrl:n});return n!==i&&!s.serviceLocation&&e.serviceLocation&&(s.serviceLocation=e.serviceLocation),s}))}))):e,Ft=e=>{const t=Ct(e,"SegmentTemplate")[0],i=Ct(e,"SegmentList")[0],n=i&&Ct(i,"SegmentURL").map((e=>tt({tag:"SegmentURL"},Mt(e)))),s=Ct(e,"SegmentBase")[0],a=i||t,r=a&&Ct(a,"SegmentTimeline")[0],o=i||s||t,d=o&&Ct(o,"Initialization")[0],u=t&&Mt(t);u&&d?u.initialization=d&&Mt(d):u&&u.initialization&&(u.initialization={sourceURL:u.initialization});const l={template:u,segmentTimeline:r&&Ct(r,"S").map((e=>Mt(e))),list:i&&tt(Mt(i),{segmentUrls:n,initialization:Mt(d)}),base:s&&tt(Mt(s),{initialization:Mt(d)})};return Object.keys(l).forEach((e=>{l[e]||delete l[e]})),l},qt=e=>nt(Ct(e.node,"EventStream").map((t=>{const i=Mt(t),n=i.schemeIdUri;return Ct(t,"Event").map((t=>{const s=Mt(t),a=s.presentationTime||0,r=i.timescale||1,o=s.duration||0,d=a/r+e.attributes.start;return{schemeIdUri:n,value:i.value,id:s.id,start:d,end:d+o/r,messageData:Ot(t)||s.messageData,contentEncoding:i.contentEncoding,presentationTimeOffset:i.presentationTimeOffset||0}}))}))),$t=(e,t)=>(i,n)=>{const s=Bt(t,Ct(i.node,"BaseURL")),a=tt(e,{periodStart:i.attributes.start});"number"==typeof i.attributes.duration&&(a.periodDuration=i.attributes.duration);const r=Ct(i.node,"AdaptationSet"),o=Ft(i.node);return nt(r.map(((e,t,i)=>n=>{const s=Mt(n),a=Bt(t,Ct(n,"BaseURL")),r=Ct(n,"Role")[0],o={role:Mt(r)};let d=tt(e,s,o);const u=Ct(n,"Accessibility")[0],l="urn:scte:dash:cc:cea-608:2015"===(h=Mt(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=tt(d,{captionServices:l}));const p=Ct(n,"Label")[0];if(p&&p.childNodes.length){const e=p.childNodes[0].nodeValue.trim();d=tt(d,{label:e})}const m=Ct(n,"ContentProtection").reduce(((e,t)=>{const i=Mt(t);i.schemeIdUri&&(i.schemeIdUri=i.schemeIdUri.toLowerCase());const n=Nt[i.schemeIdUri];if(n){e[n]={attributes:i};const s=Ct(t,"cenc:pssh")[0];if(s){const t=Ot(s);e[n].pssh=t&&c(t)}}return e}),{});Object.keys(m).length&&(d=tt(d,{contentProtection:m}));const g=Ft(n),f=Ct(n,"Representation"),y=tt(i,g);return nt(f.map(((e,t,i)=>n=>{const s=Ct(n,"BaseURL"),a=Bt(t,s),r=tt(e,Mt(n)),o=Ft(n);return a.map((e=>({segmentInfo:tt(i,o),attributes:tt(r,e)})))})(d,a,y)))})(a,s,o)))},Vt=(e,t)=>{if(e.length>1&&t({type:"warn",message:"The MPD manifest should contain no more than one ContentSteering tag"}),!e.length)return null;const i=tt({serverURL:Ot(e[0])},Mt(e[0]));return i.queryBeforeStart="true"===i.queryBeforeStart,i},Gt=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 Wt=Math.pow(2,32),Ht=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)*Wt+i.getUint32(4)},Xt=Fe([73,68,51]),jt=function e(t,i){return void 0===i&&(i=0),(t=Fe(t)).length-i<10||!We(t,Xt,{offset:i})?i:(i+=function(e,t){void 0===t&&(t=0);var i=(e=Fe(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))},zt=function(e){return"string"==typeof e?Ge(e):e},Yt=function e(t,i,n){void 0===n&&(n=!1),i=function(e){return Array.isArray(e)?e.map((function(e){return zt(e)})):[zt(e)]}(i),t=Fe(t);var s=[];if(!i.length)return s;for(var a=0;a<t.length;){var r=(t[a]<<24|t[a+1]<<16|t[a+2]<<8|t[a+3])>>>0,o=t.subarray(a+4,a+8);if(0===r)break;var d=a+r;if(d>t.length){if(n)break;d=t.length}var u=t.subarray(a+8,d);We(o,i[0])&&(1===i.length?s.push(u):s.push.apply(s,e(u,i.slice(1),n))),a=d}return s},Qt={EBML:Fe([26,69,223,163]),DocType:Fe([66,130]),Segment:Fe([24,83,128,103]),SegmentInfo:Fe([21,73,169,102]),Tracks:Fe([22,84,174,107]),Track:Fe([174]),TrackNumber:Fe([215]),DefaultDuration:Fe([35,227,131]),TrackEntry:Fe([174]),TrackType:Fe([131]),FlagDefault:Fe([136]),CodecID:Fe([134]),CodecPrivate:Fe([99,162]),VideoTrack:Fe([224]),AudioTrack:Fe([225]),Cluster:Fe([31,67,182,117]),Timestamp:Fe([231]),TimestampScale:Fe([42,215,177]),BlockGroup:Fe([160]),BlockDuration:Fe([155]),Block:Fe([161]),SimpleBlock:Fe([163])},Kt=[128,64,32,16,8,4,2,1],Jt=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<Kt.length&&!(e&Kt[i]);i++)t++;return t}(e[t]),a=e.subarray(t,t+s);return i&&((a=Array.prototype.slice.call(e,t,t+s))[0]^=Kt[s-1]),{length:s,value:Ve(a,{signed:n}),bytes:a}},Zt=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,a=(s=e=qe(e),Math.ceil(function(e){return e.toString(2).length}(s)/8)),r=new Uint8Array(new ArrayBuffer(a)),o=0;o<a;o++){var d=n?o:Math.abs(o+1-r.length);r[d]=Number(e/$e[o]&qe(255)),e<0&&(r[d]=Math.abs(~r[d]),r[d]-=0===o?1:2)}return r}(t):t},ei=function e(t,i,n){if(n>=i.length)return i.length;var s=Jt(i,n,!1);if(We(t.bytes,s.bytes))return n;var a=Jt(i,n+s.length);return e(t,i,n+a.length+a.value+s.length)},ti=function e(t,i){i=function(e){return Array.isArray(e)?e.map((function(e){return Zt(e)})):[Zt(e)]}(i),t=Fe(t);var n=[];if(!i.length)return n;for(var s=0;s<t.length;){var a=Jt(t,s,!1),r=Jt(t,s+a.length),o=s+a.length+r.length;127===r.value&&(r.value=ei(a,t,o),r.value!==t.length&&(r.value-=o));var d=o+r.value>t.length?t.length:o+r.value,u=t.subarray(o,d);We(i[0],a.bytes)&&(1===i.length?n.push(u):n=n.concat(e(u,i.slice(1)))),s+=a.length+r.length+u.length}return n},ii=Fe([0,0,0,1]),ni=Fe([0,0,1]),si=Fe([0,0,3]),ai=function(e){for(var t=[],i=1;i<e.length-2;)We(e.subarray(i,i+3),si)&&(t.push(i+2),i++),i++;if(0===t.length)return e;var n=e.length-t.length,s=new Uint8Array(n),a=0;for(i=0;i<n;a++,i++)a===t[0]&&(a++,t.shift()),s[i]=e[a];return s},ri=function(e,t,i,n){void 0===n&&(n=1/0),e=Fe(e),i=[].concat(i);for(var s,a=0,r=0;a<e.length&&(r<n||s);){var o=void 0;if(We(e.subarray(a),ii)?o=4:We(e.subarray(a),ni)&&(o=3),o){if(r++,s)return ai(e.subarray(s,a));var d=void 0;"h264"===t?d=31&e[a+o]:"h265"===t&&(d=e[a+o]>>1&63),-1!==i.indexOf(d)&&(s=a+o),a+=o+("h264"===t?1:2)}else a++}return e.subarray(0,0)},oi={webm:Fe([119,101,98,109]),matroska:Fe([109,97,116,114,111,115,107,97]),flac:Fe([102,76,97,67]),ogg:Fe([79,103,103,83]),ac3:Fe([11,119]),riff:Fe([82,73,70,70]),avi:Fe([65,86,73]),wav:Fe([87,65,86,69]),"3gp":Fe([102,116,121,112,51,103]),mp4:Fe([102,116,121,112]),fmp4:Fe([115,116,121,112]),mov:Fe([102,116,121,112,113,116]),moov:Fe([109,111,111,118]),moof:Fe([109,111,111,102])},di={aac:function(e){var t=jt(e);return We(e,[255,16],{offset:t,mask:[255,22]})},mp3:function(e){var t=jt(e);return We(e,[255,2],{offset:t,mask:[255,6]})},webm:function(e){var t=ti(e,[Qt.EBML,Qt.DocType])[0];return We(t,oi.webm)},mkv:function(e){var t=ti(e,[Qt.EBML,Qt.DocType])[0];return We(t,oi.matroska)},mp4:function(e){return!di["3gp"](e)&&!di.mov(e)&&(!(!We(e,oi.mp4,{offset:4})&&!We(e,oi.fmp4,{offset:4}))||!(!We(e,oi.moof,{offset:4})&&!We(e,oi.moov,{offset:4}))||void 0)},mov:function(e){return We(e,oi.mov,{offset:4})},"3gp":function(e){return We(e,oi["3gp"],{offset:4})},ac3:function(e){var t=jt(e);return We(e,oi.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=jt(e);return We(e,oi.flac,{offset:t})},ogg:function(e){return We(e,oi.ogg)},avi:function(e){return We(e,oi.riff)&&We(e,oi.avi,{offset:8})},wav:function(e){return We(e,oi.riff)&&We(e,oi.wav,{offset:8})},h264:function(e){return function(e,t,i){return ri(e,"h264",7,3)}(e).length},h265:function(e){return function(e,t,i){return ri(e,"h265",[32,33],3)}(e).length}},ui=Object.keys(di).filter((function(e){return"ts"!==e&&"h264"!==e&&"h265"!==e})).concat(["ts","h264","h265"]);ui.forEach((function(e){var t=di[e];di[e]=function(e){return t(Fe(e))}}));var li=di,hi=function(e){e=Fe(e);for(var t=0;t<ui.length;t++){var i=ui[t];if(li[i](e))return i}return""};const ci=(e,t)=>{if(4===e.readyState)return t()},{EventTarget:pi}=s.default,mi=function(e,t){if(!Ee(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 a=n.byterange,r=s.byterange;if(a&&!r||!a&&r)return!1;if(a.offset!==r.offset||a.length!==r.length)return!1}return!0},gi=(e,t,i,n)=>`placeholder-uri-${e}-${t}-${n.attributes.NAME||i}`,fi=(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,yi=(e,t)=>{const i={};for(const n in e){const s=e[n].sidx;if(s){const e=gt(s);if(!t[e])break;const n=t[e].sidxInfo;fi(n,s)&&(i[e]=t[e])}}return i};class _i extends pi{constructor(e,t,i={},n){super(),this.isPaused_=!0,this.mainPlaylistLoader_=n||this,n||(this.isMain_=!0);const{withCredentials:s=!1}=i;if(this.vhs_=t,this.withCredentials=s,this.addMetadataToTextTrack=i.addMetadataToTextTrack,!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_=l("DashPlaylistLoader"),this.isMain_?(this.mainPlaylistLoader_.srcUrl=e,this.mainPlaylistLoader_.sidxMapping_={}):this.childPlaylist_=e}get isPaused(){return this.isPaused_}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,metadata:e.metadata}:e,i&&(this.state=i),this.trigger("error"),!0):void 0)}addSidxSegments_(e,t,i){const n=e.sidx&>(e.sidx);if(!e.sidx||!n||this.mainPlaylistLoader_.sidxMapping_[n])return window.clearTimeout(this.mediaRequest_),void(this.mediaRequest_=window.setTimeout((()=>i(!1)),0));const s=u(e.sidx.resolvedUri),a=(s,a)=>{if(this.requestErrored_(s,a,t))return;const r=this.mainPlaylistLoader_.sidxMapping_,{requestType:o}=a;let d;try{d=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=Ht(e.subarray(n)),i.firstOffset=Ht(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}(Fe(a.response).subarray(8))}catch(e){return e.metadata=me({requestType:o,request:a,parseFailure:!0}),void this.requestErrored_(e,a,t)}return r[n]={sidxInfo:e.sidx,sidx:d},lt(e,d,e.sidx.resolvedUri),i(!0)};this.request=((e,t,i,n)=>{let s,a=[],r=!1;const o=function(e,t,n,s){return t.abort(),r=!0,i(e,t,n,s)},d=function(e,t){if(r)return;if(e)return e.metadata=me({requestType:n,request:t,error:e}),o(e,t,"",a);const i=t.responseText.substring(a&&a.byteLength||0,t.responseText.length);if(a=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 Fe(t[0]);var n=t.reduce((function(e,t,i){return e+(t.byteLength||t.length)}),0),s=new Uint8Array(n),a=0;return t.forEach((function(e){e=Fe(e),s.set(e,a),a+=e.byteLength})),s}(a,Ge(i,!0)),s=s||jt(a),a.length<10||s&&a.length<s+2)return ci(t,(()=>o(e,t,"",a)));const d=hi(a);return"ts"===d&&a.length<188||!d&&a.length<376?ci(t,(()=>o(e,t,"",a))):o(null,t,d,a)},u={uri:e,beforeSend(e){e.overrideMimeType("text/plain; charset=x-user-defined"),e.addEventListener("progress",(function({total:t,loaded:i}){return Le(e,null,{statusCode:e.status},d)}))}},l=t(u,(function(e,t){return Le(l,e,t,d)}));return l})(s,this.vhs_.xhr,((t,i,n,r)=>{if(t)return a(t,i);if(!n||"mp4"!==n){const t=n||"unknown";return a({status:i.status,message:`Unsupported ${t} 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(r.length>=d+o)return a(t,{response:r.subarray(o,o+d),status:i.status,uri:i.uri});this.request=this.vhs_.xhr({uri:s,responseType:"arraybuffer",requestType:"dash-sidx",headers:Ce({byterange:e.sidx.byterange})},a)}),"dash-sidx")}dispose(){this.isPaused_=!0,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,window.clearTimeout(this.mediaRequest_),this.mediaRequest_=null,this.refreshMedia_(t.id),"HAVE_MAIN_MANIFEST"===e?this.trigger("loadedmetadata"):this.trigger("mediachange")}pause(){this.isPaused_=!0,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){this.isPaused_=!1,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(){if(this.started=!0,!this.isMain_)return window.clearTimeout(this.mediaRequest_),void(this.mediaRequest_=window.setTimeout((()=>this.haveMain_()),0));this.requestMain_(((e,t)=>{this.haveMain_(),this.hasPendingRequest()||this.media_||this.media(this.mainPlaylistLoader_.main.playlists[0])}))}requestMain_(e){const t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};this.trigger({type:"manifestrequeststart",metadata:t}),this.request=this.vhs_.xhr({uri:this.mainPlaylistLoader_.srcUrl,withCredentials:this.withCredentials,requestType:"dash-manifest"},((i,n)=>{if(i){const{requestType:e}=n;i.metadata=me({requestType:e,request:n,error:i})}if(this.requestErrored_(i,n))return void("HAVE_NOTHING"===this.state&&(this.started=!1));this.trigger({type:"manifestrequestcomplete",metadata:t});const s=n.responseText!==this.mainPlaylistLoader_.mainXml_;return this.mainPlaylistLoader_.mainXml_=n.responseText,n.responseHeaders&&n.responseHeaders.date?this.mainLoaded_=Date.parse(n.responseHeaders.date):this.mainLoaded_=Date.now(),this.mainPlaylistLoader_.srcUrl=u(this.mainPlaylistLoader_.srcUrl,n),s?(this.handleMain_(),void this.syncClientServerClock_((()=>e(n,s)))):e(n,s)}))}syncClientServerClock_(e){const t=(i=this.mainPlaylistLoader_.mainXml_,(e=>{const t=Ct(e,"UTCTiming")[0];if(!t)return null;const i=Mt(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})(Gt(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:d(this.mainPlaylistLoader_.srcUrl,t.value),method:t.method,withCredentials:this.withCredentials,requestType:"dash-clock-sync"},((i,n)=>{if(!this.request)return;if(i){const{requestType:t}=n;return this.error.metadata=me({requestType:t,request:n,error:i}),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_(){window.clearTimeout(this.mediaRequest_),this.mediaRequest_=null;const e=this.mainPlaylistLoader_.main,t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};let i;this.trigger({type:"manifestparsestart",metadata:t});try{i=(({mainXml:e,srcUrl:t,clientOffset:i,sidxMapping:n,previousManifest:s})=>{const a=((e,t={})=>{const i=((e,t={})=>{const{manifestUri:i="",NOW:n=Date.now(),clientOffset:s=0,eventHandler:a=function(){}}=t,r=Ct(e,"Period");if(!r.length)throw new Error("INVALID_NUMBER_OF_PERIOD");const o=Ct(e,"Location"),d=Mt(e),u=Bt([{baseUrl:i}],Ct(e,"BaseURL")),l=Ct(e,"ContentSteering");d.type=d.type||"static",d.sourceDuration=d.mediaPresentationDuration||0,d.NOW=n,d.clientOffset=s,o.length&&(d.locations=o.map(Ot));const h=[];return r.forEach(((e,t)=>{const i=Mt(e),n=h[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:d.type}),h.push({node:e,attributes:i})})),{locations:d.locations,contentSteeringInfo:Vt(l,a),representationInfo:nt(h.map($t(d,u))),eventStream:nt(h.map(qt))}})(Gt(e),t),n=i.representationInfo.map(Pt);return It({dashPlaylists:n,locations:i.locations,contentSteering:i.contentSteeringInfo,sidxMapping:t.sidxMapping,previousManifest:t.previousManifest,eventStream:i.eventStream})})(e,{manifestUri:t,clientOffset:i,sidxMapping:n,previousManifest:s});return ce(a,t,gi),a})({mainXml:this.mainPlaylistLoader_.mainXml_,srcUrl:this.mainPlaylistLoader_.srcUrl,clientOffset:this.mainPlaylistLoader_.clientOffset_,sidxMapping:this.mainPlaylistLoader_.sidxMapping_,previousManifest:e})}catch(e){this.error=e,this.error.metadata={errorType:s.default.Error.StreamingDashManifestParserError,error:e},this.trigger("error")}e&&(i=((e,t,i)=>{let n=!0,s=C(e,{duration:t.duration,minimumUpdatePeriod:t.minimumUpdatePeriod,timelineStarts:t.timelineStarts});for(let e=0;e<t.playlists.length;e++){const a=t.playlists[e];if(a.sidx){const e=gt(a.sidx);i&&i[e]&&i[e].sidx&<(a,i[e].sidx,a.sidx.resolvedUri)}const r=Ae(s,a,mi);r&&(s=r,n=!1)}return le(t,((e,t,i,a)=>{if(e.playlists&&e.playlists.length){const r=e.playlists[0].id,o=Ae(s,e.playlists[0],mi);o&&(s=o,a in s.mediaGroups[t][i]||(s.mediaGroups[t][i][a]=e),s.mediaGroups[t][i][a].playlists[0]=s.playlists[r],n=!1)}})),((e,t)=>{le(e,((i,n,s,a)=>{t.mediaGroups[n][s]&&a in t.mediaGroups[n][s]||delete e.mediaGroups[n][s][a]}))})(s,t),t.minimumUpdatePeriod!==e.minimumUpdatePeriod&&(n=!1),n?null:s})(e,i,this.mainPlaylistLoader_.sidxMapping_)),this.mainPlaylistLoader_.main=i||e;const n=this.mainPlaylistLoader_.main.locations&&this.mainPlaylistLoader_.main.locations[0];if(n&&n!==this.mainPlaylistLoader_.srcUrl&&(this.mainPlaylistLoader_.srcUrl=n),(!e||i&&i.minimumUpdatePeriod!==e.minimumUpdatePeriod)&&this.updateMinimumUpdatePeriodTimeout_(),this.addEventStreamToMetadataTrack_(i),i){const{duration:e,endList:n}=i,s=[];i.playlists.forEach((e=>{s.push({id:e.id,bandwidth:e.attributes.BANDWIDTH,resolution:e.attributes.RESOLUTION,codecs:e.attributes.CODECS})}));const a={duration:e,isLive:!n,renditions:s};t.parsedManifest=a,this.trigger({type:"manifestparsecomplete",metadata:t})}return Boolean(i)}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=yi(e.playlists,t);return le(e,((e,n,s,a)=>{if(e.playlists&&e.playlists.length){const n=e.playlists;i=C(i,yi(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()}),De(this.media(),Boolean(i))))};e()}this.trigger("loadedplaylist")}addEventStreamToMetadataTrack_(e){if(e&&this.mainPlaylistLoader_.main.eventStream){const e=this.mainPlaylistLoader_.main.eventStream.map((e=>({cueTime:e.start,frames:[{data:e.messageData}]})));this.addMetadataToTextTrack("EventStream",e,this.mainPlaylistLoader_.main.duration)}}getKeyIdSet(e){if(e.contentProtection){const t=new Set;for(const i in e.contentProtection){const n=e.contentProtection[i].attributes["cenc:default_KID"];n&&t.add(n.replace(/-/g,"").toLowerCase())}return t}}}var Ti={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 bi=function(e){return e.on=e.addEventListener,e.off=e.removeEventListener,e},Si=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=bi(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}},vi=function(e){return`var browserWorkerPolyFill = ${bi.toString()};\nbrowserWorkerPolyFill(self);\n`+e},wi=function(e){return e.toString().replace(/^function.+?{/,"").slice(0,-1)},Ii=vi(wi((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,a;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(a=[],n=arguments.length,n=1;n<arguments.length;++n)a.push(arguments[n]);for(s=i.length,n=0;n<s;++n)i[n].apply(this,a)}},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,a,r,o,d,u,l,h,c,p,m,g,f,y,_,T,b,S,v,w,I,E,A,D,x,U,L,P,C,O,k,R,M,N,B,F,q,$,V=t,G=Math.pow(2,32),W={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=W.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]),D=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]),U={video:D,audio:x},C=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),P=new Uint8Array([0,0,0,0,0,0,0,0]),O=new Uint8Array([0,0,0,0,0,0,0,0]),k=O,R=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),M=O,L=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,C))},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]))},f=function(e){return i(w.hdlr,U[e])},g=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,g(e),f(e.type),o(e))},r=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,L):i(w.smhd,P),n(),_(e))},d=function(e,t){for(var n=[],s=t.length;s--;)n[s]=b(t[s]);return i.apply(null,[w.moof,r(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||[],a=new Uint8Array(4+s.length);for(n=0;n<s.length;n++)t=s[n].flags,a[n+4]=t.dependsOn<<4|t.isDependedOn<<2|t.hasRedundancy;return i(w.sdtp,a)},_=function(e){return i(w.stbl,T(e),i(w.stts,M),i(w.stsc,k),i(w.stsz,R),i(w.stco,O))},T=function(e){return i(w.stsd,new Uint8Array([0,0,0,0,0,0,0,1]),"video"===e.type?N(e):B(e))},N=function(e){var t,n,s=e.sps||[],a=e.pps||[],r=[],o=[];for(t=0;t<s.length;t++)r.push((65280&s[t].byteLength)>>>8),r.push(255&s[t].byteLength),r=r.concat(Array.prototype.slice.call(s[t]));for(t=0;t<a.length;t++)o.push((65280&a[t].byteLength)>>>8),o.push(255&a[t].byteLength),o=o.concat(Array.prototype.slice.call(a[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],r,[a.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)},B=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,a,r,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])),r=Math.floor(e.baseMediaDecodeTime/H),o=Math.floor(e.baseMediaDecodeTime%H),n=i(w.tfdt,new Uint8Array([1,0,0,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,o>>>24&255,o>>>16&255,o>>>8&255,255&o])),"audio"===e.type?(s=v(e,92),i(w.traf,t,n,s)):(a=y(e),s=v(e,a.length+92),i(w.traf,t,n,s,a))},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)},$=function(e,t){var i=0,n=0,s=0,a=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&&(a=8)),[0,0,i|n|s|a,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]},q=function(e,t){var n,s,a,r,o,d;for(t+=20+16*(r=e.samples||[]).length,a=$(r,t),(s=new Uint8Array(a.length+16*r.length)).set(a),n=a.length,d=0;d<r.length;d++)o=r[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,a,r,o,d;for(t+=20+8*(r=e.samples||[]).length,a=$(r,t),(n=new Uint8Array(a.length+8*r.length)).set(a),s=a.length,d=0;d<r.length;d++)o=r[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):q(e,t)};var X,j,z,Y,Q,K,J,Z,ee={ftyp:a=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=a(),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,a,r,o=t||0,d=[];for(i=0;i<e.length;i++)for(a=e[i],n=0;n<a.length;n++)r=a[n],o+=(s=te(r,o)).size,d.push(s);return d},concatenateNalData:function(e){var t,i,n,s,a,r,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(a=s[i],n=0;n<a.length;n++)r=a[n],h.setUint32(o,r.data.byteLength),o+=4,l.set(r.data,o),o+=r.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,a=e.length,r=new Uint8Array(s+4*a),o=new DataView(r.buffer);for(t=0;t<e.length;t++)i=e[t],o.setUint32(n,i.data.byteLength),n+=4,r.set(i.data,n),n+=i.data.byteLength;return r}},ne=[33,16,5,32,164,27],se=[33,65,108,84,1,2,4,8,168,2,4,8,17,191,252],ae=function(e){for(var t=[];e--;)t.push(0);return t},re=9e4;K=function(e,t){return j(Q(e,t))},J=function(e,t){return z(Y(e),t)},Z=function(e,t,i){return Y(i?e:e-t)};var oe={ONE_SECOND_IN_TS:re,secondsToVideoTs:j=function(e){return e*re},secondsToAudioTs:z=function(e,t){return e*t},videoTsToSeconds:Y=function(e){return e/re},audioTsToSeconds:Q=function(e,t){return e/t},audioTsToVideoTs:K,videoTsToAudioTs:J,metadataTsToSeconds:Z},de=oe,ue={prefixWithSilence:function(e,t,i,n){var s,a,r,o,d,u=0,l=0,h=0;if(t.length&&(s=de.audioTsToVideoTs(e.baseMediaDecodeTime,e.samplerate),a=Math.ceil(de.ONE_SECOND_IN_TS/(e.samplerate/1024)),i&&n&&(u=s-Math.max(i,n),h=(l=Math.floor(u/a))*a),!(l<1||h>de.ONE_SECOND_IN_TS/2))){for((r=function(){if(!X){var e={96e3:[ne,[227,64],ae(154),[56]],88200:[ne,[231],ae(170),[56]],64e3:[ne,[248,192],ae(240),[56]],48e3:[ne,[255,192],ae(268),[55,148,128],ae(54),[112]],44100:[ne,[255,192],ae(268),[55,163,128],ae(84),[112]],32e3:[ne,[255,192],ae(268),[55,234],ae(226),[112]],24e3:[ne,[255,192],ae(268),[55,255,128],ae(268),[111,112],ae(126),[224]],16e3:[ne,[255,192],ae(268),[55,255,128],ae(268),[111,255],ae(269),[223,108],ae(195),[1,192]],12e3:[se,ae(268),[3,127,248],ae(268),[6,255,240],ae(268),[13,255,224],ae(268),[27,253,128],ae(259),[56]],11025:[se,ae(268),[3,127,248],ae(268),[6,255,240],ae(268),[13,255,224],ae(268),[27,255,192],ae(268),[55,175,128],ae(108),[112]],8e3:[se,ae(268),[3,121,16],ae(47),[7]]};t=e,X=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 X}()[e.samplerate])||(r=t[0].data),o=0;o<l;o++)d=t[0],t.splice(0,0,{data:r,dts:d.dts-a,pts:d.pts-a});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,a,r=[];if(!(64&t[0]))return r;for(n=31&t[0],i=0;i<n;i++)a={type:3&t[2+(s=3*i)],pts:e},4&t[s+2]&&(a.ccData=t[s+3]<<8|t[s+4],r.push(a));return r},discardEmulationPreventionBytes:function(e){for(var t,i,n=e.byteLength,s=[],a=1;a<n-2;)0===e[a]&&0===e[a+1]&&3===e[a+2]?(s.push(a+2),a+=2):a++;if(0===s.length)return e;t=n-s.length,i=new Uint8Array(t);var r=0;for(a=0;a<t;r++,a++)r===s[0]&&(r++,s.shift()),i[a]=e[r];return i},USER_DATA_REGISTERED_ITU_T_T35:4},pe=V,me=ce,ge=function(e){e=e||{},ge.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")))};ge.prototype=new pe,ge.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}},ge.prototype.flushCCStreams=function(e){this.ccStreams_.forEach((function(t){return"flush"===e?t.flush():t.partialFlush()}),this)},ge.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)},ge.prototype.flush=function(){return this.flushStream("flush")},ge.prototype.partialFlush=function(){return this.flushStream("partialFlush")},ge.prototype.reset=function(){this.latestDts_=null,this.ignoreNextEqualDts_=!1,this.numSameDts_=0,this.activeCea608Channel_=[null,null],this.ccStreams_.forEach((function(e){e.reset()}))},ge.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)},ge.prototype.setsChannel1Active=function(e){return 4096==(30720&e.ccData)},ge.prototype.setsChannel2Active=function(e){return 6144==(30720&e.ccData)},ge.prototype.setsTextOrXDSActive=function(e){return 256==(28928&e.ccData)||4138==(30974&e.ccData)||6186==(30974&e.ccData)},ge.prototype.dispatchCea708Packet=function(e){this.parse708captions_&&this.cc708Stream_.push(e)};var fe={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,a=t[s++];for(e.seq=a>>6,e.sizeCode=63&a;s<t.length;s++)n=31&(a=t[s++]),7==(i=a>>5)&&n>0&&(i=a=t[s++]),this.pushServiceBlock(i,s,n),n>0&&(s+=n-1)},be.prototype.pushServiceBlock=function(e,t,i){var n,s=t,a=this.current708Packet.data,r=this.services[e];for(r||(r=this.initService(e,s));s<t+i&&s<a.length;s++)n=a[s],ye(n)?s=this.handleText(s,r):24===n?s=this.multiByteCharacter(s,r):16===n?s=this.extendedCommands(s,r):128<=n&&n<=135?s=this.setCurrentWindow(s,r):152<=n&&n<=159?s=this.defineWindow(s,r):136===n?s=this.clearWindows(s,r):140===n?s=this.deleteWindows(s,r):137===n?s=this.displayWindows(s,r):138===n?s=this.hideWindows(s,r):139===n?s=this.toggleWindows(s,r):151===n?s=this.setWindowAttributes(s,r):144===n?s=this.setPenAttributes(s,r):145===n?s=this.setPenColor(s,r):146===n?s=this.setPenLocation(s,r):143===n?r=this.reset(s,r):8===n?r.currentWindow.backspace():12===n?r.currentWindow.clearText():13===n?r.currentWindow.pendingNewLine=!0:14===n?r.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,a,r,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;if(d?(s=[h,c],e++):s=[h],t.textDecoder_&&!o)n=t.textDecoder_.decode(new Uint8Array(s));else if(d){const e=s.map((e=>("0"+(255&e).toString(16)).slice(-2))).join("");n=String.fromCharCode(parseInt(e,16))}else r=fe[a=l|h]||a,n=4096&a&&a===r?"":String.fromCharCode(r);return 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 a=t.currentWindow;return n=i[++e],a.visible=(32&n)>>5,a.rowLock=(16&n)>>4,a.columnLock=(8&n)>>3,a.priority=7&n,n=i[++e],a.relativePositioning=(128&n)>>7,a.anchorVertical=127&n,n=i[++e],a.anchorHorizontal=n,n=i[++e],a.anchorPoint=(240&n)>>4,a.rowCount=15&n,n=i[++e],a.columnCount=63&n,n=i[++e],a.windowStyle=(56&n)>>3,a.penStyle=7&n,a.virtualRowCount=a.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({text:"",indent:0,offset:0});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,a;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_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.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))a=ve((n=(3&n)<<8)|s),this[this.mode_](e.pts,a),this.column_++;else if(this.isExtCharacter(n,s))"popOn"===this.mode_?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1),a=ve((n=(3&n)<<8)|s),this[this.mode_](e.pts,a),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)){const e=3&s;this.nonDisplayed_[this.row_].offset=e,this.column_+=e}else if(this.isPAC(n,s)){var r=we.indexOf(7968&t);if("rollUp"===this.mode_&&(r-this.rollUpRows_+1<0&&(r=this.rollUpRows_-1),this.setRollUp(e.pts,r)),r!==this.row_&&r>=0&&r<=14&&(this.clearFormatting(e.pts),this.row_=r),1&s&&-1===this.formatting_.indexOf("u")&&this.addFormatting(e.pts,["u"]),16==(16&t)){const e=(14&t)>>1;this.column_=4*e,this.nonDisplayed_[this.row_].indent+=e}this.isColorPAC(s)&&14==(14&s)&&this.addFormatting(e.pts,["i"])}else this.isNormalChar(n)&&(0===s&&(s=null),a=ve(n),a+=ve(s),this[this.mode_](e.pts,a),this.column_+=a.length)}else this.lastControlCode_=null}};Ee.prototype=new pe,Ee.prototype.flushDisplayed=function(e){const t=e=>{this.trigger("log",{level:"warn",message:"Skipping a malformed 608 caption at index "+e+"."})},i=[];this.displayed_.forEach(((e,n)=>{if(e&&e.text&&e.text.length){try{e.text=e.text.trim()}catch(e){t(n)}e.text.length&&i.push({text:e.text,line:n+1,position:10+Math.min(70,10*e.indent)+2.5*e.offset})}else null==e&&t(n)})),i.length&&this.trigger("data",{startPts:this.startPts_,endPts:e,content:i,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]={text:"",indent:0,offset:0};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_].text;i+=t,this.nonDisplayed_[this.row_].text=i},Ee.prototype.rollUp=function(e,t){var i=this.displayed_[this.row_].text;i+=t,this.displayed_[this.row_].text=i},Ee.prototype.shiftRowsUp_=function(){var e;for(e=0;e<this.topRow_;e++)this.displayed_[e]={text:"",indent:0,offset:0};for(e=this.row_+1;e<15;e++)this.displayed_[e]={text:"",indent:0,offset:0};for(e=this.topRow_;e<this.row_;e++)this.displayed_[e]=this.displayed_[e+1];this.displayed_[this.row_]={text:"",indent:0,offset:0}},Ee.prototype.paintOn=function(e,t){var i=this.displayed_[this.row_].text;i+=t,this.displayed_[this.row_].text=i};var Ae={CaptionStream:ge,Cea608Stream:Ee,Cea708Stream:be},De={H264_STREAM_TYPE:27,ADTS_STREAM_TYPE:15,METADATA_STREAM_TYPE:21},xe=V,Ue="shared",Le=function(e,t){var i=1;for(e>t&&(i=-1);Math.abs(t-e)>4294967296;)e+=8589934592*i;return e},Pe=function(e){var t,i;Pe.prototype.init.call(this),this.type_=e||Ue,this.push=function(e){"metadata"!==e.type?this.type_!==Ue&&e.type!==this.type_||(void 0===i&&(i=e.dts),e.dts=Le(e.dts,i),e.pts=Le(e.pts,i),t=e.dts,this.trigger("data",e)):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")}};Pe.prototype=new xe;var Ce,Oe={TimestampRolloverStream:Pe,handleRollover:Le},ke=(e,t,i)=>{if(!e)return-1;for(var n=i;n<e.length;n++)if(e[n]===t)return n;return-1},Re=function(e,t,i){var n,s="";for(n=t;n<i;n++)s+="%"+("00"+e[n].toString(16)).slice(-2);return s},Me=function(e,t,i){return decodeURIComponent(Re(e,t,i))},Ne=function(e,t,i){return unescape(Re(e,t,i))},Be=function(e){return e[0]<<21|e[1]<<14|e[2]<<7|e[3]},Fe={APIC:function(e){var t,i,n=1;3===e.data[0]&&((t=ke(e.data,0,n))<0||(e.mimeType=Ne(e.data,n,t),n=t+1,e.pictureType=e.data[n],n++,(i=ke(e.data,0,n))<0||(e.description=Me(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=Me(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=ke(e.data,0,1))&&(e.description=Me(e.data,1,t),e.value=Me(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=ke(e.data,0,1))&&(e.description=Me(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}},qe={parseId3Frames:function(e){var t,i=10,n=0,s=[];if(!(e.length<10||e[0]!=="I".charCodeAt(0)||e[1]!=="D".charCodeAt(0)||e[2]!=="3".charCodeAt(0))){n=Be(e.subarray(6,10)),n+=10,64&e[5]&&(i+=4,i+=Be(e.subarray(10,14)),n-=Be(e.subarray(16,20)));do{if((t=Be(e.subarray(i+4,i+8)))<1)break;var a={id:String.fromCharCode(e[i],e[i+1],e[i+2],e[i+3]),data:e.subarray(i+10,i+t+10)};a.key=a.id,Fe[a.id]?Fe[a.id](a):"T"===a.id[0]?Fe["T*"](a):"W"===a.id[0]&&Fe["W*"](a),s.push(a),i+=10,i+=t}while(i<n);return s}},parseSyncSafeInteger:Be,frameParsers:Fe},$e=De,Ve=qe;(Ce=function(e){var t,i={descriptor:e&&e.descriptor},n=0,s=[],a=0;if(Ce.prototype.init.call(this),this.dispatchType=$e.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,r,o,d;if("timed-metadata"===e.type)if(e.dataAlignmentIndicator&&(a=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),a+=e.data.byteLength,1===s.length&&(n=Ve.parseSyncSafeInteger(e.data.subarray(6,10)),n+=10),!(a<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,a-=s[0].data.byteLength,s.shift();i=10,64&t.data[5]&&(i+=4,i+=Ve.parseSyncSafeInteger(t.data.subarray(10,14)),n-=Ve.parseSyncSafeInteger(t.data.subarray(16,20)));do{if((r=Ve.parseSyncSafeInteger(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+r+10)}).key=o.id,Ve.frameParsers[o.id]?Ve.frameParsers[o.id](o):"T"===o.id[0]?Ve.frameParsers["T*"](o):"W"===o.id[0]&&Ve.frameParsers["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+=r}while(i<n);this.trigger("data",t)}}}).prototype=new V;var Ge,We,He,Xe=Ce,je=V,ze=Ae,Ye=De,Qe=Oe.TimestampRolloverStream,Ke=188;(Ge=function(){var e=new Uint8Array(Ke),t=0;Ge.prototype.init.call(this),this.push=function(i){var n,s=0,a=Ke;for(t?((n=new Uint8Array(i.byteLength+t)).set(e.subarray(0,t)),n.set(i,t),t=0):n=i;a<n.byteLength;)71!==n[s]||71!==n[a]?(s++,a++):(this.trigger("data",n.subarray(s,a)),s+=Ke,a+=Ke);s<n.byteLength&&(e.set(n.subarray(s),0),t=n.byteLength-s)},this.flush=function(){t===Ke&&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 je,(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 a=e[s],r=(31&e[s+1])<<8|e[s+2];a===Ye.H264_STREAM_TYPE&&null===n.programMapTable.video?n.programMapTable.video=r:a===Ye.ADTS_STREAM_TYPE&&null===n.programMapTable.audio?n.programMapTable.audio=r:a===Ye.METADATA_STREAM_TYPE&&(n.programMapTable["timed-metadata"][r]=a),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=Ye.H264_STREAM_TYPE:i.pid===this.programMapTable.audio?i.streamType=Ye.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 je,We.STREAM_TYPES={h264:27,adts:15},He=function(){var e,t=this,i=!1,n={data:[],size:0},s={data:[],size:0},a={data:[],size:0},r=function(e,i,n){var s,a,r=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++)a=e.data[d],r.set(a.data,u),u+=a.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]))}(r,o),s="video"===i||o.packetLength<=e.size,(n||s)&&(e.size=0,e.data.length=0),s&&t.trigger("data",o)}};He.prototype.init.call(this),this.push=function(o){({pat:function(){},pes:function(){var e,t;switch(o.streamType){case Ye.H264_STREAM_TYPE:e=n,t="video";break;case Ye.ADTS_STREAM_TYPE:e=s,t="audio";break;case Ye.METADATA_STREAM_TYPE:e=a,t="timed-metadata";break;default:return}o.payloadUnitStartIndicator&&r(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(){r(n,"video"),r(s,"audio"),r(a,"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")}},He.prototype=new je;var Je={PAT_PID:0,MP2T_PACKET_LENGTH:Ke,TransportPacketStream:Ge,TransportParseStream:We,ElementaryStream:He,TimestampRolloverStream:Qe,CaptionStream:ze.CaptionStream,Cea608Stream:ze.Cea608Stream,Cea708Stream:ze.Cea708Stream,MetadataStream:Xe};for(var Ze in Ye)Ye.hasOwnProperty(Ze)&&(Je[Ze]=Ye[Ze]);var et,tt=Je,it=oe.ONE_SECOND_IN_TS,nt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];(et=function(e){var t,i=0;et.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,a,r,o,d,u=0;if(e||(i=0),"audio"===n.type){var l;for(t&&t.length?(r=t,(t=new Uint8Array(r.byteLength+n.data.byteLength)).set(r),t.set(n.data,r.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),a=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])))*it/nt[(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:nt[(60&t[u+2])>>>2],samplingfrequencyindex:(60&t[u+2])>>>2,samplesize:16,data:t.subarray(u+7+a,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 V;var st,at,rt,ot=et,dt=V,ut=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,a=new Uint8Array(4),r=Math.min(4,t);if(0===r)throw new Error("no bytes available");a.set(e.subarray(s,s+r)),i=new DataView(a.buffer).getUint32(0),n=8*r,t-=r},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),a=i>>>32-s;return(n-=s)>0?i<<=s:t>0&&this.loadWord(),(s=e-s)>0?a<<s|this.readBits(s):a},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()};(at=function(){var e,t,i=0;at.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 a=t.byteLength;i<a-3;i++)if(1===t[i+2]){e=i+5;break}for(;e<a;)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<a);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 dt,rt={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},st=function(){var e,t,i,n,s,a,r,o=new at;st.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(r){var o={trackId:t,pts:i,dts:n,data:r,nalUnitTypeCode:31&r[0]};switch(o.nalUnitTypeCode){case 5:o.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:o.nalUnitType="sei_rbsp",o.escapedRBSP=s(r.subarray(1));break;case 7:o.nalUnitType="seq_parameter_set_rbsp",o.escapedRBSP=s(r.subarray(1)),o.config=a(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()},r=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=[],a=1;a<n-2;)0===e[a]&&0===e[a+1]&&3===e[a+2]?(s.push(a+2),a+=2):a++;if(0===s.length)return e;t=n-s.length,i=new Uint8Array(t);var r=0;for(a=0;a<t;r++,a++)r===s[0]&&(r++,s.shift()),i[a]=e[r];return i},a=function(e){var t,i,n,s,a,o,d,u,l,h,c,p,m=0,g=0,f=0,y=0,_=[1,1];if(i=(t=new ut(e)).readUnsignedByte(),s=t.readUnsignedByte(),n=t.readUnsignedByte(),t.skipUnsignedExpGolomb(),rt[i]&&(3===(a=t.readUnsignedExpGolomb())&&t.skipBits(1),t.skipUnsignedExpGolomb(),t.skipUnsignedExpGolomb(),t.skipBits(1),t.readBoolean()))for(c=3!==a?8:12,p=0;p<c;p++)t.readBoolean()&&r(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(),g=t.readUnsignedExpGolomb(),f=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*g,height:(2-h)*(l+1)*16-2*f-2*y,sarRatio:_}}},st.prototype=new dt;var lt,ht={H264Stream:st,NalByteStream:at},ct=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],pt=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},mt=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+=pt(e,t),mt(e,t))},gt=function(e){return e[0]<<21|e[1]<<14|e[2]<<7|e[3]},ft={isLikelyAacData:function(e){var t=mt(e,0);return e.length>=t+2&&255==(255&e[t])&&240==(240&e[t+1])&&16==(22&e[t+1])},parseId3TagSize:pt,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 ct[(60&e[t+2])>>>2];t++}return null},parseAacTimestamp:function(e){var t,i,n;t=10,64&e[5]&&(t+=4,t+=gt(e.subarray(10,14)));do{if((i=gt(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 a=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"===a){var r=n.subarray(s+1),o=(1&r[3])<<30|r[4]<<22|r[5]<<14|r[6]<<6|r[7]>>>2;return(o*=4)+(3&r[7])}break}}t+=10,t+=i}while(t<e.byteLength);return null}},yt=ft;(lt=function(){var e=new Uint8Array,t=0;lt.prototype.init.call(this),this.setTimestamp=function(e){t=e},this.push=function(i){var n,s,a,r,o=0,d=0;for(e.length?(r=e.length,(e=new Uint8Array(i.byteLength+r)).set(e.subarray(0,r)),e.set(i,r)):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=yt.parseAdtsSize(e,d))>e.length)break;a={type:"audio",data:e.subarray(d,d+o),pts:t,dts:t},this.trigger("data",a),d+=o}else{if(e.length-d<10)break;if(d+(o=yt.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 V;var _t,Tt,bt,St,vt=V,wt=ee,It=ie,Et=ue,At=he,Dt=tt,xt=oe,Ut=ot,Lt=ht.H264Stream,Pt=lt,Ct=ft.isLikelyAacData,Ot=oe.ONE_SECOND_IN_TS,kt=["audioobjecttype","channelcount","samplerate","samplingfrequencyindex","samplesize"],Rt=["width","height","profileIdc","levelIdc","profileCompatibility","sarRatio"],Mt=function(e,t){t.stream=e,this.trigger("log",t)},Nt=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",Mt.bind(e,s))}},Bt=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},Ft=function(e,t,i,n,s,a){return{start:{dts:e,pts:e+(i-t)},end:{dts:e+(n-t),pts:e+(s-i)},prependedContentDuration:a,baseMediaDecodeTime:e}};Tt=function(e,t){var i,n=[],s=0,a=0,r=1/0;i=(t=t||{}).firstSequenceNumber||0,Tt.prototype.init.call(this),this.push=function(t){At.collectDtsInfo(e,t),e&&kt.forEach((function(i){e[i]=t[i]})),n.push(t)},this.setEarliestDts=function(e){s=e},this.setVideoBaseMediaDecodeTime=function(e){r=e},this.setAudioAppendStart=function(e){a=e},this.flush=function(){var o,d,u,l,h,c,p;0!==n.length?(o=Et.trimAdtsFramesByEarliestDts(n,e,s),e.baseMediaDecodeTime=At.calculateTrackBaseMediaDecodeTime(e,t.keepOriginalTimestamps),p=Et.prefixWithSilence(e,o,a,r),e.samples=Et.generateSampleTable(o),u=wt.mdat(Et.concatenateFrameData(o)),n=[],d=wt.moof(i,[e]),l=new Uint8Array(d.byteLength+u.byteLength),i++,l.set(d),l.set(u,d.byteLength),At.clearDtsInfo(e),h=Math.ceil(1024*Ot/e.samplerate),o.length&&(c=o.length*h,this.trigger("segmentTimingInfo",Ft(xt.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(){At.clearDtsInfo(e),n=[],this.trigger("reset")}},Tt.prototype=new vt,_t=function(e,t){var i,n,s,a=[],r=[];i=(t=t||{}).firstSequenceNumber||0,_t.prototype.init.call(this),delete e.minPTS,this.gopCache_=[],this.push=function(t){At.collectDtsInfo(e,t),"seq_parameter_set_rbsp"!==t.nalUnitType||n||(n=t.config,e.sps=[t.data],Rt.forEach((function(t){e[t]=n[t]}),this)),"pic_parameter_set_rbsp"!==t.nalUnitType||s||(s=t.data,e.pps=[t.data]),a.push(t)},this.flush=function(){for(var n,s,o,d,u,l,h,c,p=0;a.length&&"access_unit_delimiter_rbsp"!==a[0].nalUnitType;)a.shift();if(0===a.length)return this.resetStream_(),void this.trigger("done","VideoSegmentStream");if(n=It.groupNalsIntoFrames(a),(o=It.groupFramesIntoGops(n))[0][0].keyFrame||((s=this.getGopForFusion_(a[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=It.extendFirstKeyFrame(o)),r.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),a=[],this.resetStream_(),void this.trigger("done","VideoSegmentStream");At.clearDtsInfo(e),o=m}At.collectDtsInfo(e,o),e.samples=It.generateSampleTable(o),u=wt.mdat(It.concatenateNalData(o)),e.baseMediaDecodeTime=At.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",Ft(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),a=[],this.trigger("baseMediaDecodeTime",e.baseMediaDecodeTime),this.trigger("timelineStartInfo",e.timelineStartInfo),d=wt.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_(),a=[],this.gopCache_.length=0,r.length=0,this.trigger("reset")},this.resetStream_=function(){At.clearDtsInfo(e),n=void 0,s=void 0},this.getGopForFusion_=function(t){var i,n,s,a,r,o=1/0;for(r=0;r<this.gopCache_.length;r++)s=(a=this.gopCache_[r]).gop,e.pps&&Bt(e.pps[0],a.pps[0])&&e.sps&&Bt(e.sps[0],a.sps[0])&&(s.dts<e.timelineStartInfo.dts||(i=t.dts-s.dts-s.duration)>=-1e4&&i<=45e3&&(!n||o>i)&&(n=a,o=i));return n?n.gop:null},this.alignGopsAtStart_=function(e){var t,i,n,s,a,o,d,u;for(a=e.byteLength,o=e.nalCount,d=e.duration,t=i=0;t<r.length&&i<e.length&&(n=r[t],s=e[i],n.pts!==s.pts);)s.pts>n.pts?t++:(i++,a-=s.byteLength,o-=s.nalCount,d-=s.duration);return 0===i?e:i===e.length?null:((u=e.slice(i)).byteLength=a,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,a,o,d;for(t=r.length-1,i=e.length-1,a=null,o=!1;t>=0&&i>=0;){if(n=r[t],s=e[i],n.pts===s.pts){o=!0;break}n.pts>s.pts?t--:(t===r.length-1&&(a=i),i--)}if(!o&&null===a)return null;if(0===(d=o?i:a))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){r=e}},_t.prototype=new vt,St=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,St.prototype.init.call(this),this.push=function(e){return e.content||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))))}},St.prototype=new vt,St.prototype.flush=function(e){var t,i,n,s,a=0,r={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,Rt.forEach((function(e){r.info[e]=this.videoTrack[e]}),this)):this.audioTrack&&(o=this.audioTrack.timelineStartInfo.pts,kt.forEach((function(e){r.info[e]=this.audioTrack[e]}),this)),this.videoTrack||this.audioTrack){for(1===this.pendingTracks.length?r.type=this.pendingTracks[0].type:r.type="combined",this.emittedTracks+=this.pendingTracks.length,n=wt.initSegment(this.pendingTracks),r.initSegment=new Uint8Array(n.byteLength),r.initSegment.set(n),r.data=new Uint8Array(this.pendingBytes),s=0;s<this.pendingBoxes.length;s++)r.data.set(this.pendingBoxes[s],a),a+=this.pendingBoxes[s].byteLength;for(s=0;s<this.pendingCaptions.length;s++)(t=this.pendingCaptions[s]).startTime=xt.metadataTsToSeconds(t.startPts,o,this.keepOriginalTimestamps),t.endTime=xt.metadataTsToSeconds(t.endPts,o,this.keepOriginalTimestamps),r.captionStreams[t.stream]=!0,r.captions.push(t);for(s=0;s<this.pendingMetadata.length;s++)(i=this.pendingMetadata[s]).cueTime=xt.metadataTsToSeconds(i.pts,o,this.keepOriginalTimestamps),r.metadata.push(i);for(r.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",r),s=0;s<r.captions.length;s++)t=r.captions[s],this.trigger("caption",t);for(s=0;s<r.metadata.length;s++)i=r.metadata[s],this.trigger("id3Frame",i)}this.emittedTracks>=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0)},St.prototype.setRemux=function(e){this.remuxTracks=e},(bt=function(e){var t,i,n=this,s=!0;bt.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 Dt.MetadataStream,s.aacStream=new Pt,s.audioTimestampRolloverStream=new Dt.TimestampRolloverStream("audio"),s.timedMetadataTimestampRolloverStream=new Dt.TimestampRolloverStream("timed-metadata"),s.adtsStream=new Ut,s.coalesceStream=new St(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(a){"timed-metadata"!==a.type&&"audio"!==a.type||s.audioSegmentStream||(i=i||{timelineStartInfo:{baseMediaDecodeTime:n.baseMediaDecodeTime},codec:"adts",type:"audio"},s.coalesceStream.numberOfTracks++,s.audioSegmentStream=new Tt(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")),Nt(this,s)},this.setupTsPipeline=function(){var s={};this.transmuxPipeline_=s,s.type="ts",s.metadataStream=new Dt.MetadataStream,s.packetStream=new Dt.TransportPacketStream,s.parseStream=new Dt.TransportParseStream,s.elementaryStream=new Dt.ElementaryStream,s.timestampRolloverStream=new Dt.TimestampRolloverStream,s.adtsStream=new Ut,s.h264Stream=new Lt,s.captionStream=new Dt.CaptionStream(e),s.coalesceStream=new St(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(a){var r;if("metadata"===a.type){for(r=a.tracks.length;r--;)t||"video"!==a.tracks[r].type?i||"audio"!==a.tracks[r].type||((i=a.tracks[r]).timelineStartInfo.baseMediaDecodeTime=n.baseMediaDecodeTime):(t=a.tracks[r]).timelineStartInfo.baseMediaDecodeTime=n.baseMediaDecodeTime;t&&!s.videoSegmentStream&&(s.coalesceStream.numberOfTracks++,s.videoSegmentStream=new _t(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 Tt(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")),Nt(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,At.clearDtsInfo(i),s.audioTimestampRolloverStream&&s.audioTimestampRolloverStream.discontinuity()),t&&(s.videoSegmentStream&&(s.videoSegmentStream.gopCache_=[]),t.timelineStartInfo.dts=void 0,t.timelineStartInfo.pts=void 0,At.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=Ct(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 vt;var qt,$t,Vt={Transmuxer:bt,VideoSegmentStream:_t,AudioSegmentStream:Tt,AUDIO_PROPERTIES:kt,VIDEO_PROPERTIES:Rt,generateSegmentTimingInfo:Ft},Gt=function(e){return e>>>0},Wt=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,Xt=Wt,jt=function(e,t){var i,n,s,a,r,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=Xt(e.subarray(i+4,i+8)),a=n>1?i+n:e.byteLength,s===t[0]&&(1===t.length?o.push(e.subarray(i+8,a)):(r=jt(e.subarray(i+8,a),t.slice(1))).length&&(o=o.concat(r))),i=a;return o},zt=jt,Yt=Gt,Qt=W.getUint64,Kt=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=Yt(e[4]<<24|e[5]<<16|e[6]<<8|e[7]),t},Jt=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],a=2&n.flags[2],r=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),a&&(n.sampleDescriptionIndex=i.getUint32(t),t+=4),r&&(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},Zt=W.getUint64,ei=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]}},ti=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],a=4&i.flags[2],r=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),a&&l&&(t={flags:ei(e.subarray(h,h+4))},h+=4,r&&(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={},r&&(t.duration=n.getUint32(h),h+=4),o&&(t.size=n.getUint32(h),h+=4),d&&(t.flags=ei(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},ii=W.getUint64,ni=function(e){return new Date(1e3*e-20828448e5)},si=Wt,ai=function(e){var t,i,n=new DataView(e.buffer,e.byteOffset,e.byteLength),s=[];for(t=0;t+4<e.length;t+=i)if(i=n.getUint32(t),t+=4,i<=0)s.push("<span style='color:red;'>MALFORMED DATA</span>");else switch(31&e[t]){case 1:s.push("slice_layer_without_partitioning_rbsp");break;case 5:s.push("slice_layer_without_partitioning_rbsp_idr");break;case 6:s.push("sei_rbsp");break;case 7:s.push("seq_parameter_set_rbsp");break;case 8:s.push("pic_parameter_set_rbsp");break;case 9:s.push("access_unit_delimiter_rbsp");break;default:s.push("UNKNOWN NAL - "+e[t]&31)}return s},ri={avc1:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{dataReferenceIndex:t.getUint16(6),width:t.getUint16(24),height:t.getUint16(26),horizresolution:t.getUint16(28)+t.getUint16(30)/16,vertresolution:t.getUint16(32)+t.getUint16(34)/16,frameCount:t.getUint16(40),depth:t.getUint16(74),config:qt(e.subarray(78,e.byteLength))}},avcC:function(e){var t,i,n,s,a=new DataView(e.buffer,e.byteOffset,e.byteLength),r={configurationVersion:e[0],avcProfileIndication:e[1],profileCompatibility:e[2],avcLevelIndication:e[3],lengthSizeMinusOne:3&e[4],sps:[],pps:[]},o=31&e[5];for(n=6,s=0;s<o;s++)i=a.getUint16(n),n+=2,r.sps.push(new Uint8Array(e.subarray(n,n+i))),n+=i;for(t=e[n],n++,s=0;s<t;s++)i=a.getUint16(n),n+=2,r.pps.push(new Uint8Array(e.subarray(n,n+i))),n+=i;return r},btrt:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{bufferSizeDB:t.getUint32(0),maxBitrate:t.getUint32(4),avgBitrate:t.getUint32(8)}},edts:function(e){return{boxes:qt(e)}},elst:function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength),n={version:i.getUint8(0),flags:new Uint8Array(e.subarray(1,4)),edits:[]},s=i.getUint32(4);for(t=8;s;s--)0===n.version?(n.edits.push({segmentDuration:i.getUint32(t),mediaTime:i.getInt32(t+4),mediaRate:i.getUint16(t+8)+i.getUint16(t+10)/65536}),t+=12):(n.edits.push({segmentDuration:ii(e.subarray(t)),mediaTime:ii(e.subarray(t+8)),mediaRate:i.getUint16(t+16)+i.getUint16(t+18)/65536}),t+=20);return n},esds:function(e){return{version:e[0],flags:new Uint8Array(e.subarray(1,4)),esId:e[6]<<8|e[7],streamPriority:31&e[8],decoderConfig:{objectProfileIndication:e[11],streamType:e[12]>>>2&63,bufferSize:e[13]<<16|e[14]<<8|e[15],maxBitrate:e[16]<<24|e[17]<<16|e[18]<<8|e[19],avgBitrate:e[20]<<24|e[21]<<16|e[22]<<8|e[23],decoderConfigDescriptor:{tag:e[24],length:e[25],audioObjectType:e[26]>>>3&31,samplingFrequencyIndex:(7&e[26])<<1|e[27]>>>7&1,channelConfiguration:e[27]>>>3&15}}}},ftyp:function(e){for(var t=new DataView(e.buffer,e.byteOffset,e.byteLength),i={majorBrand:si(e.subarray(0,4)),minorVersion:t.getUint32(4),compatibleBrands:[]},n=8;n<e.byteLength;)i.compatibleBrands.push(si(e.subarray(n,n+4))),n+=4;return i},dinf:function(e){return{boxes:qt(e)}},dref:function(e){return{version:e[0],flags:new Uint8Array(e.subarray(1,4)),dataReferences:qt(e.subarray(8))}},hdlr:function(e){var t={version:new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0),flags:new Uint8Array(e.subarray(1,4)),handlerType:si(e.subarray(8,12)),name:""},i=8;for(i=24;i<e.byteLength;i++){if(0===e[i]){i++;break}t.name+=String.fromCharCode(e[i])}return t.name=decodeURIComponent(escape(t.name)),t},mdat:function(e){return{byteLength:e.byteLength,nals:ai(e)}},mdhd:function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength),n=4,s={version:i.getUint8(0),flags:new Uint8Array(e.subarray(1,4)),language:""};return 1===s.version?(n+=4,s.creationTime=ni(i.getUint32(n)),n+=8,s.modificationTime=ni(i.getUint32(n)),n+=4,s.timescale=i.getUint32(n),n+=8,s.duration=i.getUint32(n)):(s.creationTime=ni(i.getUint32(n)),n+=4,s.modificationTime=ni(i.getUint32(n)),n+=4,s.timescale=i.getUint32(n),n+=4,s.duration=i.getUint32(n)),n+=4,t=i.getUint16(n),s.language+=String.fromCharCode(96+(t>>10)),s.language+=String.fromCharCode(96+((992&t)>>5)),s.language+=String.fromCharCode(96+(31&t)),s},mdia:function(e){return{boxes:qt(e)}},mfhd:function(e){return{version:e[0],flags:new Uint8Array(e.subarray(1,4)),sequenceNumber:e[4]<<24|e[5]<<16|e[6]<<8|e[7]}},minf:function(e){return{boxes:qt(e)}},mp4a:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),i={dataReferenceIndex:t.getUint16(6),channelcount:t.getUint16(16),samplesize:t.getUint16(18),samplerate:t.getUint16(24)+t.getUint16(26)/65536};return e.byteLength>28&&(i.streamDescriptor=qt(e.subarray(28))[0]),i},moof:function(e){return{boxes:qt(e)}},moov:function(e){return{boxes:qt(e)}},mvex:function(e){return{boxes:qt(e)}},mvhd:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),i=4,n={version:t.getUint8(0),flags:new Uint8Array(e.subarray(1,4))};return 1===n.version?(i+=4,n.creationTime=ni(t.getUint32(i)),i+=8,n.modificationTime=ni(t.getUint32(i)),i+=4,n.timescale=t.getUint32(i),i+=8,n.duration=t.getUint32(i)):(n.creationTime=ni(t.getUint32(i)),i+=4,n.modificationTime=ni(t.getUint32(i)),i+=4,n.timescale=t.getUint32(i),i+=4,n.duration=t.getUint32(i)),i+=4,n.rate=t.getUint16(i)+t.getUint16(i+2)/16,i+=4,n.volume=t.getUint8(i)+t.getUint8(i+1)/8,i+=2,i+=2,i+=8,n.matrix=new Uint32Array(e.subarray(i,i+36)),i+=36,i+=24,n.nextTrackId=t.getUint32(i),n},pdin:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{version:t.getUint8(0),flags:new Uint8Array(e.subarray(1,4)),rate:t.getUint32(4),initialDelay:t.getUint32(8)}},sdtp:function(e){var t,i={version:e[0],flags:new Uint8Array(e.subarray(1,4)),samples:[]};for(t=4;t<e.byteLength;t++)i.samples.push({dependsOn:(48&e[t])>>4,isDependedOn:(12&e[t])>>2,hasRedundancy:3&e[t]});return i},sidx: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=Zt(e.subarray(n)),i.firstOffset=Zt(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},smhd:function(e){return{version:e[0],flags:new Uint8Array(e.subarray(1,4)),balance:e[4]+e[5]/256}},stbl:function(e){return{boxes:qt(e)}},ctts:function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength),n={version:i.getUint8(0),flags:new Uint8Array(e.subarray(1,4)),compositionOffsets:[]},s=i.getUint32(4);for(t=8;s;t+=8,s--)n.compositionOffsets.push({sampleCount:i.getUint32(t),sampleOffset:i[0===n.version?"getUint32":"getInt32"](t+4)});return n},stss:function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength),n={version:i.getUint8(0),flags:new Uint8Array(e.subarray(1,4)),syncSamples:[]},s=i.getUint32(4);for(t=8;s;t+=4,s--)n.syncSamples.push(i.getUint32(t));return n},stco:function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength),n={version:e[0],flags:new Uint8Array(e.subarray(1,4)),chunkOffsets:[]},s=i.getUint32(4);for(t=8;s;t+=4,s--)n.chunkOffsets.push(i.getUint32(t));return n},stsc:function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength),n=i.getUint32(4),s={version:e[0],flags:new Uint8Array(e.subarray(1,4)),sampleToChunks:[]};for(t=8;n;t+=12,n--)s.sampleToChunks.push({firstChunk:i.getUint32(t),samplesPerChunk:i.getUint32(t+4),sampleDescriptionIndex:i.getUint32(t+8)});return s},stsd:function(e){return{version:e[0],flags:new Uint8Array(e.subarray(1,4)),sampleDescriptions:qt(e.subarray(8))}},stsz:function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength),n={version:e[0],flags:new Uint8Array(e.subarray(1,4)),sampleSize:i.getUint32(4),entries:[]};for(t=12;t<e.byteLength;t+=4)n.entries.push(i.getUint32(t));return n},stts:function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength),n={version:e[0],flags:new Uint8Array(e.subarray(1,4)),timeToSamples:[]},s=i.getUint32(4);for(t=8;s;t+=8,s--)n.timeToSamples.push({sampleCount:i.getUint32(t),sampleDelta:i.getUint32(t+4)});return n},styp:function(e){return ri.ftyp(e)},tfdt:Kt,tfhd:Jt,tkhd:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),i=4,n={version:t.getUint8(0),flags:new Uint8Array(e.subarray(1,4))};return 1===n.version?(i+=4,n.creationTime=ni(t.getUint32(i)),i+=8,n.modificationTime=ni(t.getUint32(i)),i+=4,n.trackId=t.getUint32(i),i+=4,i+=8,n.duration=t.getUint32(i)):(n.creationTime=ni(t.getUint32(i)),i+=4,n.modificationTime=ni(t.getUint32(i)),i+=4,n.trackId=t.getUint32(i),i+=4,i+=4,n.duration=t.getUint32(i)),i+=4,i+=8,n.layer=t.getUint16(i),i+=2,n.alternateGroup=t.getUint16(i),i+=2,n.volume=t.getUint8(i)+t.getUint8(i+1)/8,i+=2,i+=2,n.matrix=new Uint32Array(e.subarray(i,i+36)),i+=36,n.width=t.getUint16(i)+t.getUint16(i+2)/65536,i+=4,n.height=t.getUint16(i)+t.getUint16(i+2)/65536,n},traf:function(e){return{boxes:qt(e)}},trak:function(e){return{boxes:qt(e)}},trex:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{version:e[0],flags:new Uint8Array(e.subarray(1,4)),trackId:t.getUint32(4),defaultSampleDescriptionIndex:t.getUint32(8),defaultSampleDuration:t.getUint32(12),defaultSampleSize:t.getUint32(16),sampleDependsOn:3&e[20],sampleIsDependedOn:(192&e[21])>>6,sampleHasRedundancy:(48&e[21])>>4,samplePaddingValue:(14&e[21])>>1,sampleIsDifferenceSample:!!(1&e[21]),sampleDegradationPriority:t.getUint16(22)}},trun:ti,"url ":function(e){return{version:e[0],flags:new Uint8Array(e.subarray(1,4))}},vmhd:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{version:e[0],flags:new Uint8Array(e.subarray(1,4)),graphicsmode:t.getUint16(4),opcolor:new Uint16Array([t.getUint16(6),t.getUint16(8),t.getUint16(10)])}}};qt=function(e){for(var t,i,n,s,a,r=0,o=[],d=new ArrayBuffer(e.length),u=new Uint8Array(d),l=0;l<e.length;++l)u[l]=e[l];for(t=new DataView(d);r<e.byteLength;)i=t.getUint32(r),n=si(e.subarray(r+4,r+8)),s=i>1?r+i:e.byteLength,(a=(ri[n]||function(e){return{data:e}})(e.subarray(r+8,s))).size=i,a.type=n,o.push(a),r=s;return o},$t=function(e,t){var i;return t=t||0,i=new Array(2*t+1).join(" "),e.map((function(e,n){return i+e.type+"\n"+Object.keys(e).filter((function(e){return"type"!==e&&"boxes"!==e})).map((function(t){var n=i+" "+t+": ",s=e[t];if(s instanceof Uint8Array||s instanceof Uint32Array){var a=Array.prototype.slice.call(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)).map((function(e){return" "+("00"+e.toString(16)).slice(-2)})).join("").match(/.{1,24}/g);return a?1===a.length?n+"<"+a.join("").slice(1)+">":n+"<\n"+a.map((function(e){return i+" "+e})).join("\n")+"\n"+i+" >":n+"<>"}return n+JSON.stringify(s,null,2).split("\n").map((function(e,t){return 0===t?e:i+" "+e})).join("\n")})).join("\n")+(e.boxes?"\n"+$t(e.boxes,t+1):"")})).join("\n")};var oi,di,ui,li,hi,ci,pi,mi={inspect:qt,textify:$t,parseType:si,findBox:zt,parseTraf:ri.traf,parseTfdt:ri.tfdt,parseHdlr:ri.hdlr,parseTfhd:ri.tfhd,parseTrun:ri.trun,parseSidx:ri.sidx},gi=function(e){for(var t=0,i=String.fromCharCode(e[t]),n="";"\0"!==i;)n+=i,t++,i=String.fromCharCode(e[t]);return n+i},fi=W.getUint64,yi=function(e){return void 0!==e||null!==e},_i={parseEmsgBox:function(e){var t,i,n,s,a,r,o,d=4,u=e[0];if(0===u)d+=(t=gi(e.subarray(d))).length,d+=(i=gi(e.subarray(d))).length,n=(l=new DataView(e.buffer)).getUint32(d),d+=4,a=l.getUint32(d),d+=4,r=l.getUint32(d),d+=4,o=l.getUint32(d),d+=4;else if(1===u){var l;n=(l=new DataView(e.buffer)).getUint32(d),d+=4,s=fi(e.subarray(d)),d+=8,r=l.getUint32(d),d+=4,o=l.getUint32(d),d+=4,d+=(t=gi(e.subarray(d))).length,d+=(i=gi(e.subarray(d))).length}var h={scheme_id_uri:t,value:i,timescale:n||1,presentation_time:s,presentation_time_delta:a,event_duration:r,id:o,message_data:new Uint8Array(e.subarray(d,e.byteLength))};return function(e,t){var i="\0"!==t.scheme_id_uri,n=0===e&&yi(t.presentation_time_delta)&&i,s=1===e&&yi(t.presentation_time)&&i;return!(e>1)&&n||s}(u,h)?h:void 0},scaleTime:function(e,t,i,n){return e||0===e?e/t:n+i/t}},Ti="undefined"!=typeof window?window:void 0!==e?e:"undefined"!=typeof self?self:{},bi=Gt,Si=function(e){return("00"+e.toString(16)).slice(-2)},vi=zt,wi=Wt,Ii=_i,Ei=Jt,Ai=ti,Di=Kt,xi=W.getUint64,Ui=Ti,Li=qe.parseId3Frames;oi=function(e){return vi(e,["moov","trak"]).reduce((function(e,t){var i,n,s,a,r;return(i=vi(t,["tkhd"])[0])?(n=i[0],a=bi(i[s=0===n?12:20]<<24|i[s+1]<<16|i[s+2]<<8|i[s+3]),(r=vi(t,["mdia","mdhd"])[0])?(s=0===(n=r[0])?12:20,e[a]=bi(r[s]<<24|r[s+1]<<16|r[s+2]<<8|r[s+3]),e):null):null}),{})},di=function(e,t){var i=vi(t,["moof","traf"]).reduce((function(t,i){var n,s=vi(i,["tfhd"])[0],a=bi(s[4]<<24|s[5]<<16|s[6]<<8|s[7]),r=e[a]||9e4,o=vi(i,["tfdt"])[0],d=new DataView(o.buffer,o.byteOffset,o.byteLength);let u;return"bigint"==typeof(n=1===o[0]?xi(o.subarray(4,12)):d.getUint32(4))?u=n/Ui.BigInt(r):"number"!=typeof n||isNaN(n)||(u=n/r),u<Number.MAX_SAFE_INTEGER&&(u=Number(u)),u<t&&(t=u),t}),1/0);return"bigint"==typeof i||isFinite(i)?i:0},ui=function(e,t){var i,n=vi(t,["moof","traf"]),s=0,a=0;if(n&&n.length){var r=vi(n[0],["tfhd"])[0],o=vi(n[0],["trun"])[0],d=vi(n[0],["tfdt"])[0];if(r&&(i=Ei(r).trackId),d&&(s=Di(d).baseMediaDecodeTime),o){var u=Ai(o);u.samples&&u.samples.length&&(a=u.samples[0].compositionTimeOffset||0)}}var l=e[i]||9e4;"bigint"==typeof s&&(a=Ui.BigInt(a),l=Ui.BigInt(l));var h=(s+a)/l;return"bigint"==typeof h&&h<Number.MAX_SAFE_INTEGER&&(h=Number(h)),h},li=function(e){var t=vi(e,["moov","trak"]),i=[];return t.forEach((function(e){var t=vi(e,["mdia","hdlr"]),n=vi(e,["tkhd"]);t.forEach((function(e,t){var s,a,r=wi(e.subarray(8,12)),o=n[t];"vide"===r&&(a=0===(s=new DataView(o.buffer,o.byteOffset,o.byteLength)).getUint8(0)?s.getUint32(12):s.getUint32(20),i.push(a))}))})),i},ci=function(e){var t=0===e[0]?12:20;return bi(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])},hi=function(e){var t=vi(e,["moov","trak"]),i=[];return t.forEach((function(e){var t,n,s={},a=vi(e,["tkhd"])[0];a&&(n=(t=new DataView(a.buffer,a.byteOffset,a.byteLength)).getUint8(0),s.id=0===n?t.getUint32(12):t.getUint32(20));var r=vi(e,["mdia","hdlr"])[0];if(r){var o=wi(r.subarray(8,12));s.type="vide"===o?"video":"soun"===o?"audio":o}var d=vi(e,["mdia","minf","stbl","stsd"])[0];if(d){var u=d.subarray(8);s.codec=wi(u.subarray(4,8));var l,h=vi(u,[s.codec])[0];h&&(/^[asm]vc[1-9]$/i.test(s.codec)?(l=h.subarray(78),"avcC"===wi(l.subarray(4,8))&&l.length>11?(s.codec+=".",s.codec+=Si(l[9]),s.codec+=Si(l[10]),s.codec+=Si(l[11])):s.codec="avc1.4d400d"):/^mp4[a,v]$/i.test(s.codec)?(l=h.subarray(28),"esds"===wi(l.subarray(4,8))&&l.length>20&&0!==l[19]?(s.codec+="."+Si(l[19]),s.codec+="."+Si(l[20]>>>2&63).replace(/^0/,"")):s.codec="mp4a.40.2"):s.codec=s.codec.toLowerCase())}var c=vi(e,["mdia","mdhd"])[0];c&&(s.timescale=ci(c)),i.push(s)})),i},pi=function(e,t=0){return vi(e,["emsg"]).map((e=>{var i=Ii.parseEmsgBox(new Uint8Array(e)),n=Li(i.message_data);return{cueTime:Ii.scaleTime(i.presentation_time,i.timescale,i.presentation_time_delta,t),duration:Ii.scaleTime(i.event_duration,i.timescale),frames:n}}))};var Pi={findBox:vi,parseType:wi,timescale:oi,startTime:di,compositionStartTime:ui,videoTrackIds:li,tracks:hi,getTimescaleFromMediaHeader:ci,getEmsgID3:pi};const{parseTrun:Ci}=mi,{findBox:Oi}=Pi;var ki=Ti,Ri={getMdatTrafPairs:function(e){var t=Oi(e,["moof","traf"]),i=Oi(e,["mdat"]),n=[];return i.forEach((function(e,i){var s=t[i];n.push({mdat:e,traf:s})})),n},parseSamples:function(e,t,i){var n=t,s=i.defaultSampleDuration||0,a=i.defaultSampleSize||0,r=i.trackId,o=[];return e.forEach((function(e){var t=Ci(e).samples;t.forEach((function(e){void 0===e.duration&&(e.duration=s),void 0===e.size&&(e.size=a),e.trackId=r,e.dts=n,void 0===e.compositionTimeOffset&&(e.compositionTimeOffset=0),"bigint"==typeof n?(e.pts=n+ki.BigInt(e.compositionTimeOffset),n+=ki.BigInt(e.duration)):(e.pts=n+e.compositionTimeOffset,n+=e.duration)})),o=o.concat(t)})),o}},Mi=ce.discardEmulationPreventionBytes,Ni=Ae.CaptionStream,Bi=zt,Fi=Kt,qi=Jt,{getMdatTrafPairs:$i,parseSamples:Vi}=Ri,Gi=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},Wi=function(){var e,t,i,n,s,a,r=!1;this.isInitialized=function(){return r},this.init=function(t){e=new Ni,r=!0,a=!!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,a,r){var o;if(!this.isInitialized())return null;if(!a||!r)return null;if(this.isNewInit(a,r))i=a[0],n=r[i];else if(null===i||!n)return t.push(e),null;for(;t.length>0;){var d=t.shift();this.parse(d,a,r)}return o=function(e,t,i){if(null===t)return null;var n=function(e,t){var i={};return $i(e).forEach((function(e){var n,s=e.mdat,a=e.traf,r=Bi(a,["tfhd"]),o=qi(r[0]),d=o.trackId,u=Bi(a,["tfdt"]),l=u.length>0?Fi(u[0]).baseMediaDecodeTime:0,h=Bi(a,["trun"]);t===d&&h.length>0&&(n=function(e,t,i){var n,s,a,r,o=new DataView(e.buffer,e.byteOffset,e.byteLength),d={logs:[],seiNals:[]};for(s=0;s+4<e.length;s+=a)if(a=o.getUint32(s),s+=4,!(a<=0))switch(31&e[s]){case 6:var u=e.subarray(s+1,s+1+a),l=Gi(s,t);if(n={nalUnitType:"sei_rbsp",size:a,data:u,escapedRBSP:Mi(u),trackId:i},l)n.pts=l.pts,n.dts=l.dts,r=l;else{if(!r){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=r.pts,n.dts=r.dts}d.seiNals.push(n)}return d}(s,Vi(h,l,o),d),i[d]||(i[d]={seiNals:[],logs:[]}),i[d].seiNals=i[d].seiNals.concat(n.seiNals),i[d].logs=i[d].logs.concat(n.logs))})),i}(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;a?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()};const{parseTfdt:Hi}=mi,Xi=zt,{getTimescaleFromMediaHeader:ji}=Pi,{parseSamples:zi,getMdatTrafPairs:Yi}=Ri;var Qi=function(){let e=9e4;this.init=function(t){const i=Xi(t,["moov","trak","mdia","mdhd"])[0];i&&(e=ji(i))},this.parseSegment=function(t){const i=[],n=Yi(t);let s=0;return n.forEach((function(t){const n=t.mdat,a=t.traf,r=Xi(a,["tfdt"])[0],o=Xi(a,["tfhd"])[0],d=Xi(a,["trun"]);if(r){const e=Hi(r);s=e.baseMediaDecodeTime}if(d.length&&o){const t=zi(d,s,o);let a=0;t.forEach((function(t){const s=new TextDecoder("utf-8"),r=n.slice(a,a+t.size);Xi(r,["vtte"])[0]||Xi(r,["vttc"]).forEach((function(n){const a=Xi(n,["payl"])[0],r=Xi(n,["sttg"])[0],o=t.pts/e,d=(t.pts+t.duration)/e;let u,l;if(a)try{u=s.decode(a)}catch(e){console.error(e)}if(r)try{l=s.decode(r)}catch(e){console.error(e)}t.duration&&u&&i.push({cueText:u,start:o,end:d,settings:l})})),a+=t.size}))}})),i}},Ki=De,Ji=function(e){var t=31&e[1];return(t<<=8)|e[2]},Zi=function(e){return!!(64&e[1])},en=function(e){var t=0;return(48&e[3])>>>4>1&&(t+=e[4]+1),t},tn=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}},nn={parseType:function(e,t){var i=Ji(e);return 0===i?"pat":i===t?"pmt":t?"pes":null},parsePat:function(e){var t=Zi(e),i=4+en(e);return t&&(i+=e[i]+1),(31&e[i+10])<<8|e[i+11]},parsePmt:function(e){var t={},i=Zi(e),n=4+en(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 a=12+((15&e[n+10])<<8|e[n+11]);a<s;){var r=n+a;t[(31&e[r+1])<<8|e[r+2]]=e[r],a+=5+((15&e[r+3])<<8|e[r+4])}return t}},parsePayloadUnitStartIndicator:Zi,parsePesType:function(e,t){switch(t[Ji(e)]){case Ki.H264_STREAM_TYPE:return"video";case Ki.ADTS_STREAM_TYPE:return"audio";case Ki.METADATA_STREAM_TYPE:return"timed-metadata";default:return null}},parsePesTime:function(e){if(!Zi(e))return null;var t=4+en(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+en(e),i=e.subarray(t),n=0,s=0,a=!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"===tn(31&i[s+3])&&(a=!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"===tn(31&i[s+3])&&(a=!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"===tn(31&i[s+3])&&(a=!0),a}},sn=De,an=Oe.handleRollover,rn={};rn.ts=nn,rn.aac=ft;var on=oe.ONE_SECOND_IN_TS,dn=188,un=71,ln=function(e,t,i){for(var n,s,a,r,o=0,d=dn,u=!1;d<=e.byteLength;)if(e[o]!==un||e[d]!==un&&d!==e.byteLength)o++,d++;else{if(n=e.subarray(o,d),"pes"===rn.ts.parseType(n,t.pid)&&(s=rn.ts.parsePesType(n,t.table),a=rn.ts.parsePayloadUnitStartIndicator(n),"audio"===s&&a&&(r=rn.ts.parsePesTime(n))&&(r.type="audio",i.audio.push(r),u=!0)),u)break;o+=dn,d+=dn}for(o=(d=e.byteLength)-dn,u=!1;o>=0;)if(e[o]!==un||e[d]!==un&&d!==e.byteLength)o--,d--;else{if(n=e.subarray(o,d),"pes"===rn.ts.parseType(n,t.pid)&&(s=rn.ts.parsePesType(n,t.table),a=rn.ts.parsePayloadUnitStartIndicator(n),"audio"===s&&a&&(r=rn.ts.parsePesTime(n))&&(r.type="audio",i.audio.push(r),u=!0)),u)break;o-=dn,d-=dn}},hn=function(e,t,i){for(var n,s,a,r,o,d,u,l=0,h=dn,c=!1,p={data:[],size:0};h<e.byteLength;)if(e[l]!==un||e[h]!==un)l++,h++;else{if(n=e.subarray(l,h),"pes"===rn.ts.parseType(n,t.pid)&&(s=rn.ts.parsePesType(n,t.table),a=rn.ts.parsePayloadUnitStartIndicator(n),"video"===s&&(a&&!c&&(r=rn.ts.parsePesTime(n))&&(r.type="video",i.video.push(r),c=!0),!i.firstKeyFrame))){if(a&&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(rn.ts.videoPacketContainsKeyFrame(o)){var m=rn.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+=dn,h+=dn}for(l=(h=e.byteLength)-dn,c=!1;l>=0;)if(e[l]!==un||e[h]!==un)l--,h--;else{if(n=e.subarray(l,h),"pes"===rn.ts.parseType(n,t.pid)&&(s=rn.ts.parsePesType(n,t.table),a=rn.ts.parsePayloadUnitStartIndicator(n),"video"===s&&a&&(r=rn.ts.parsePesTime(n))&&(r.type="video",i.video.push(r),c=!0)),c)break;l-=dn,h-=dn}},cn=function(e,t){var i;return i=rn.aac.isLikelyAacData(e)?function(e){for(var t,i=!1,n=0,s=null,a=null,r=0,o=0;e.length-o>=3;){switch(rn.aac.parseType(e,o)){case"timed-metadata":if(e.length-o<10){i=!0;break}if((r=rn.aac.parseId3TagSize(e,o))>e.length){i=!0;break}null===a&&(t=e.subarray(o,o+r),a=rn.aac.parseAacTimestamp(t)),o+=r;break;case"audio":if(e.length-o<7){i=!0;break}if((r=rn.aac.parseAdtsSize(e,o))>e.length){i=!0;break}null===s&&(t=e.subarray(o,o+r),s=rn.aac.parseSampleRate(t)),n++,o+=r;break;default:o++}if(i)return null}if(null===s||null===a)return null;var d=on/s;return{audio:[{type:"audio",dts:a,pts:a},{type:"audio",dts:a+1024*n*d,pts:a+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=dn;s<e.byteLength;)if(e[n]!==un||e[s]!==un)n++,s++;else{switch(i=e.subarray(n,s),rn.ts.parseType(i,t.pid)){case"pat":t.pid=rn.ts.parsePat(i);break;case"pmt":var a=rn.ts.parsePmt(i);t.table=t.table||{},Object.keys(a).forEach((function(e){t.table[e]=a[e]}))}n+=dn,s+=dn}}(e,t),t.table)if(t.table.hasOwnProperty(n))switch(t.table[n]){case sn.H264_STREAM_TYPE:i.video=[],hn(e,t,i),0===i.video.length&&delete i.video;break;case sn.ADTS_STREAM_TYPE:i.audio=[],ln(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=an(e.dts,i),e.pts=an(e.pts,i),e.dtsTime=e.dts/on,e.ptsTime=e.pts/on}))}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=an(e.dts,n),e.pts=an(e.pts,n),e.dtsTime=e.dts/on,e.ptsTime=e.pts/on})),e.firstKeyFrame){var s=e.firstKeyFrame;s.dts=an(s.dts,n),s.pts=an(s.pts,n),s.dtsTime=s.dts/on,s.ptsTime=s.pts/on}}}(i,t),i):null};class pn{constructor(e,t){this.options=t||{},this.self=e,this.init()}init(){this.transmuxer&&this.transmuxer.dispose(),this.transmuxer=new Vt.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 Wi,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])}initMp4WebVttParser(e){this.webVttParser||(this.webVttParser=new Qi);const t=new Uint8Array(e.data,e.byteOffset,e.byteLength);this.webVttParser.init(t)}getMp4WebVttText(e){this.webVttParser||(this.webVttParser=new Qi);const t=new Uint8Array(e.data,e.byteOffset,e.byteLength),i=this.webVttParser.parseSegment(t);this.self.postMessage({action:"getMp4WebVttText",mp4VttCues:i||[],data:t.buffer},[t.buffer])}probeMp4StartTime({timescales:e,data:t}){const i=Pi.startTime(e,t);this.self.postMessage({action:"probeMp4StartTime",startTime:i,data:t},[t.buffer])}probeMp4Tracks({data:e}){const t=Pi.tracks(e);this.self.postMessage({action:"probeMp4Tracks",tracks:t,data:e},[e.buffer])}probeEmsgID3({data:e,offset:t}){const i=Pi.getEmsgID3(e,t);this.self.postMessage({action:"probeEmsgID3",id3Frames:i,emsgData:e},[e.buffer])}probeTs({data:e,baseStartTime:t}){const i="number"!=typeof t||isNaN(t)?void 0:t*oe.ONE_SECOND_IN_TS,n=cn(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 pn(self,e.data.options):(this.messageHandlers||(this.messageHandlers=new pn(self)),e.data&&e.data.action&&"init"!==e.data.action&&this.messageHandlers[e.data.action]&&this.messageHandlers[e.data.action](e.data))}})));var Ei=Si(Ii);const Ai=e=>{const{transmuxer:t,bytes:i,audioAppendStart:n,gopsToAlignWith:a,remux:r,onData:o,onTrackInfo:d,onAudioTimingInfo:u,onVideoTimingInfo:l,onVideoSegmentTimingInfo:h,onAudioSegmentTimingInfo:c,onId3:p,onCaptions:m,onDone:g,onEndedTimeline:f,onTransmuxerLog:y,isEndOfTimeline:_,segment:T,triggerSegmentEventFn:b}=e,S={buffer:[]};let v=_;if(t.onmessage=i=>{t.currentTransmux===e&&("data"===i.data.action&&((e,t,i)=>{const{type:n,initSegment:s,captions:a,captionStreams:r,metadata:o,videoFrameDtsTime:d,videoFramePtsTime:u}=e.data.segment;t.buffer.push({captions:a,captionStreams:r,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,S,o),"trackinfo"===i.data.action&&d(i.data.trackInfo),"gopInfo"===i.data.action&&((e,t)=>{t.gopInfo=e.data.gopInfo})(i,S),"audioTimingInfo"===i.data.action&&u(i.data.audioTimingInfo),"videoTimingInfo"===i.data.action&&l(i.data.videoTimingInfo),"videoSegmentTimingInfo"===i.data.action&&h(i.data.videoSegmentTimingInfo),"audioSegmentTimingInfo"===i.data.action&&c(i.data.audioSegmentTimingInfo),"id3Frame"===i.data.action&&p([i.data.id3Frame],i.data.id3Frame.dispatchType),"caption"===i.data.action&&m(i.data.caption),"endedtimeline"===i.data.action&&(v=!1,f()),"log"===i.data.action&&y(i.data.log),"transmuxed"===i.data.type&&(v||(t.onmessage=null,(({transmuxedData:e,callback:t})=>{e.buffer=[],t(e)})({transmuxedData:S,callback:g}),Di(t))))},t.onerror=()=>{const e={message:"Received an error message from the transmuxer worker",metadata:{errorType:s.default.Error.StreamingFailedToTransmuxSegment,segmentInfo:ln({segment:T})}};g(null,e)},n&&t.postMessage({action:"setAudioAppendStart",appendStart:n}),Array.isArray(a)&&t.postMessage({action:"alignGopsWith",gopsToAlignWith:a}),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;b({type:"segmenttransmuxingstart",segment:T}),t.postMessage({action:"push",data:e,byteOffset:n,byteLength:i.byteLength},[e])}_&&t.postMessage({action:"endTimeline"}),t.postMessage({action:"flush"})},Di=e=>{e.currentTransmux=null,e.transmuxQueue.length&&(e.currentTransmux=e.transmuxQueue.shift(),"function"==typeof e.currentTransmux?e.currentTransmux():Ai(e.currentTransmux))},xi=(e,t)=>{e.postMessage({action:t}),Di(e)};var Ui=e=>{((e,t)=>{if(!t.currentTransmux)return t.currentTransmux=e,void xi(t,e);t.transmuxQueue.push(xi.bind(null,t,e))})("reset",e)};const Li=function(e){const t=e.transmuxer,i=e.endAction||e.action,n=e.callback,s=a({},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)},Pi=-101,Ci=-102,Oi="wvtt",ki=e=>{e.forEach((e=>{e.abort()}))},Ri=(e,t)=>{const{requestType:i}=t,n=me({requestType:i,request:t,error:e});return t.timedout?{status:t.status,message:"HLS request timed-out at URL: "+t.uri,code:Pi,xhr:t,metadata:n}:t.aborted?{status:t.status,message:"HLS request aborted at URL: "+t.uri,code:Ci,xhr:t,metadata:n}:e?{status:t.status,message:"HLS request errored at URL: "+t.uri,code:2,xhr:t,metadata:n}:"arraybuffer"===t.responseType&&0===t.response.byteLength?{status:t.status,message:"Empty HLS response at URL: "+t.uri,code:2,xhr:t,metadata:n}:null},Mi=(e,t,i,n)=>(s,a)=>{const r=a.response,o=Ri(s,a);if(o)return i(o,e);if(16!==r.byteLength)return i({status:a.status,message:"Invalid HLS key at URL: "+a.uri,code:2,xhr:a},e);const d=new DataView(r),u=new Uint32Array([d.getUint32(0),d.getUint32(4),d.getUint32(8),d.getUint32(12)]);for(let e=0;e<t.length;e++)t[e].bytes=u;const l={uri:a.uri};return n({type:"segmentkeyloadcomplete",segment:e,keyInfo:l}),i(null,e)},Ni=(e,t)=>{const i=hi(e.map.bytes);if("mp4"!==i){const n=e.map.resolvedUri||e.map.uri,s=i||"unknown";return t({internal:!0,message:`Found unsupported ${s} container for initialization segment at URL: ${n}`,code:2,metadata:{mediaType:s}})}Li({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),"text"===t.type&&((e,t)=>{t===Oi&&e.transmuxer.postMessage({action:"initMp4WebVttParser",data:e.map.bytes})})(e,t.codec))})),t(null))})},Bi=({segment:e,bytes:t,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l,doneFn:h,onTransmuxerLog:c,triggerSegmentEventFn:p})=>{const m=e.map&&e.map.tracks||{},g=Boolean(m.audio&&m.video);let f=n.bind(null,e,"audio","start");const y=n.bind(null,e,"audio","end");let _=n.bind(null,e,"video","start");const T=n.bind(null,e,"video","end");Li({action:"probeTs",transmuxer:e.transmuxer,data:t,baseStartTime:e.baseStartTime,callback:n=>{e.bytes=t=n.data;const m=n.result;m&&(i(e,{hasAudio:m.hasAudio,hasVideo:m.hasVideo,isMuxed:g}),i=null),(e=>{if(!e.transmuxer.currentTransmux)return e.transmuxer.currentTransmux=e,void Ai(e);e.transmuxer.transmuxQueue.push(e)})({bytes:t,transmuxer:e.transmuxer,audioAppendStart:e.audioAppendStart,gopsToAlignWith:e.gopsToAlignWith,remux:g,onData:t=>{t.type="combined"===t.type?"video":t.type,l(e,t)},onTrackInfo:t=>{i&&(g&&(t.isMuxed=!0),i(e,t))},onAudioTimingInfo:e=>{f&&void 0!==e.start&&(f(e.start),f=null),y&&void 0!==e.end&&y(e.end)},onVideoTimingInfo:e=>{_&&void 0!==e.start&&(_(e.start),_=null),T&&void 0!==e.end&&T(e.end)},onVideoSegmentTimingInfo:t=>{const i={pts:{start:t.start.presentation,end:t.end.presentation},dts:{start:t.start.decode,end:t.end.decode}};p({type:"segmenttransmuxingtiminginfoavailable",segment:e,timingInfo:i}),s(t)},onAudioSegmentTimingInfo:t=>{const i={pts:{start:t.start.pts,end:t.end.pts},dts:{start:t.start.dts,end:t.end.dts}};p({type:"segmenttransmuxingtiminginfoavailable",segment:e,timingInfo:i}),a(t)},onId3:(t,i)=>{r(e,t,i)},onCaptions:t=>{o(e,[t])},isEndOfTimeline:d,onEndedTimeline:()=>{u()},onTransmuxerLog:c,onDone:(t,i)=>{h&&(t.type="combined"===t.type?"video":t.type,p({type:"segmenttransmuxingcomplete",segment:e}),h(i,e,t))},segment:e,triggerSegmentEventFn:p})}})},Fi=({segment:e,bytes:t,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l,doneFn:h,onTransmuxerLog:c,triggerSegmentEventFn:p})=>{let m=new Uint8Array(t);if(function(e){return Yt(e,["moof"]).length>0}(m)){e.isFmp4=!0;const{tracks:s}=e.map;if(s.text&&(!s.audio||!s.video))return l(e,{data:m,type:"text"}),void((e,t,i)=>{t===Oi&&Li({action:"getMp4WebVttText",data:e.bytes,transmuxer:e.transmuxer,callback:({data:t,mp4VttCues:n})=>{e.bytes=t,i(null,e,{mp4VttCues:n})}})})(e,s.text.codec,h);const a={isFmp4:!0,hasVideo:!!s.video,hasAudio:!!s.audio};s.audio&&s.audio.codec&&"enca"!==s.audio.codec&&(a.audioCodec=s.audio.codec),s.video&&s.video.codec&&"encv"!==s.video.codec&&(a.videoCodec=s.video.codec),s.video&&s.audio&&(a.isMuxed=!0),i(e,a);const d=(t,i)=>{l(e,{data:m,type:a.hasAudio&&!a.isMuxed?"audio":"video"}),i&&i.length&&r(e,i),t&&t.length&&o(e,t),h(null,e,{})};Li({action:"probeMp4StartTime",timescales:e.map.timescales,data:m,transmuxer:e.transmuxer,callback:({data:i,startTime:r})=>{t=i.buffer,e.bytes=m=i,a.hasAudio&&!a.isMuxed&&n(e,"audio","start",r),a.hasVideo&&n(e,"video","start",r),Li({action:"probeEmsgID3",data:m,transmuxer:e.transmuxer,offset:r,callback:({emsgData:i,id3Frames:n})=>{t=i.buffer,e.bytes=m=i,s.video&&i.byteLength&&e.transmuxer?Li({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:e.transmuxer,data:m,timescales:e.map.timescales,trackIds:[s.video.id],callback:i=>{t=i.data.buffer,e.bytes=m=i.data,i.logs.forEach((function(e){c(C(e,{stream:"mp4CaptionParser"}))})),d(i.captions,n)}}):d(void 0,n)}})}})}else if(e.transmuxer){if(void 0===e.container&&(e.container=hi(m)),"ts"!==e.container&&"aac"!==e.container)return i(e,{hasAudio:!1,hasVideo:!1}),void h(null,e,{});Bi({segment:e,bytes:t,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l,doneFn:h,onTransmuxerLog:c,triggerSegmentEventFn:p})}else h(null,e,{})},qi=function({id:e,key:t,encryptedBytes:i,decryptionWorker:n,segment:a,doneFn:r},o){const d=t=>{if(t.data.source===e){n.removeEventListener("message",d);const e=t.data.decrypted;o(new Uint8Array(e.bytes,e.byteOffset,e.byteLength))}};let u;n.onerror=()=>{const e="An error occurred in the decryption worker",t=ln({segment:a}),i={message:e,metadata:{error:new Error(e),errorType:s.default.Error.StreamingFailedToDecryptSegment,segmentInfo:t,keyInfo:{uri:a.key.resolvedUri||a.map.key.resolvedUri}}};r(i,a)},n.addEventListener("message",d),u=t.bytes.slice?t.bytes.slice():new Uint32Array(Array.prototype.slice.call(t.bytes)),n.postMessage(ze({source:e,encrypted:i,key:u,iv:t.iv}),[i.buffer,u.buffer])},$i=({xhr:e,xhrOptions:t,decryptionWorker:i,segment:n,abortFn:s,progressFn:a,trackInfoFn:r,timingInfoFn:o,videoSegmentTimingInfoFn:d,audioSegmentTimingInfoFn:u,id3Fn:l,captionsFn:h,isEndOfTimeline:c,endedTimelineFn:p,dataFn:m,doneFn:g,onTransmuxerLog:f,triggerSegmentEventFn:y})=>{const _=[],T=(({activeXhrs:e,decryptionWorker:t,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l,doneFn:h,onTransmuxerLog:c,triggerSegmentEventFn:p})=>{let m=0,g=!1;return(f,y)=>{if(!g){if(f)return g=!0,ki(e),h(f,y);if(m+=1,m===e.length){const m=function(){if(y.encryptedBytes)return(({decryptionWorker:e,segment:t,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l,doneFn:h,onTransmuxerLog:c,triggerSegmentEventFn:p})=>{p({type:"segmentdecryptionstart"}),qi({id:t.requestId,key:t.key,encryptedBytes:t.encryptedBytes,decryptionWorker:e,segment:t,doneFn:h},(e=>{t.bytes=e,p({type:"segmentdecryptioncomplete",segment:t}),Fi({segment:t,bytes:t.bytes,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l,doneFn:h,onTransmuxerLog:c,triggerSegmentEventFn:p})}))})({decryptionWorker:t,segment:y,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l,doneFn:h,onTransmuxerLog:c,triggerSegmentEventFn:p});Fi({segment:y,bytes:y.bytes,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l,doneFn:h,onTransmuxerLog:c,triggerSegmentEventFn:p})};if(y.endOfAllRequests=Date.now(),y.map&&y.map.encryptedBytes&&!y.map.bytes)return p({type:"segmentdecryptionstart",segment:y}),qi({decryptionWorker:t,id:y.requestId+"-init",encryptedBytes:y.map.encryptedBytes,key:y.map.key,segment:y,doneFn:h},(t=>{y.map.bytes=t,p({type:"segmentdecryptioncomplete",segment:y}),Ni(y,(t=>{if(t)return ki(e),h(t,y);m()}))}));m()}}}})({activeXhrs:_,decryptionWorker:i,trackInfoFn:r,timingInfoFn:o,videoSegmentTimingInfoFn:d,audioSegmentTimingInfoFn:u,id3Fn:l,captionsFn:h,isEndOfTimeline:c,endedTimelineFn:p,dataFn:m,doneFn:g,onTransmuxerLog:f,triggerSegmentEventFn:y});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=C(t,{uri:n.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),a=Mi(n,i,T,y);y({type:"segmentkeyloadstart",segment:n,keyInfo:{uri:n.key.resolvedUri}});const r=e(s,a);_.push(r)}if(n.map&&!n.map.bytes){if(n.map.key&&(!n.key||n.key.resolvedUri!==n.map.key.resolvedUri)){const i=C(t,{uri:n.map.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),s=Mi(n,[n.map.key],T,y);y({type:"segmentkeyloadstart",segment:n,keyInfo:{uri:n.map.key.resolvedUri}});const a=e(i,s);_.push(a)}const i=C(t,{uri:n.map.resolvedUri,responseType:"arraybuffer",headers:Ce(n.map),requestType:"segment-media-initialization"}),s=(({segment:e,finishProcessingFn:t,triggerSegmentEventFn:i})=>(n,s)=>{const a=Ri(n,s);if(a)return t(a,e);const r=new Uint8Array(s.response);if(i({type:"segmentloaded",segment:e}),e.map.key)return e.map.encryptedBytes=r,t(null,e);e.map.bytes=r,Ni(e,(function(i){if(i)return i.xhr=s,i.status=s.status,t(i,e);t(null,e)}))})({segment:n,finishProcessingFn:T,triggerSegmentEventFn:y});y({type:"segmentloadstart",segment:n});const a=e(i,s);_.push(a)}const b=C(t,{uri:n.part&&n.part.resolvedUri||n.resolvedUri,responseType:"arraybuffer",headers:Ce(n),requestType:"segment"}),S=(({segment:e,finishProcessingFn:t,responseType:i,triggerSegmentEventFn:n})=>(s,a)=>{const r=Ri(s,a);if(r)return t(r,e);n({type:"segmentloaded",segment:e});const o="arraybuffer"!==i&&a.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})(a.responseText.substring(e.lastReachedChar||0)):a.response;return e.stats=(e=>({bandwidth:e.bandwidth,bytesReceived:e.bytesReceived||0,roundTripTime:e.roundTripTime||0}))(a),e.key?e.encryptedBytes=new Uint8Array(o):e.bytes=new Uint8Array(o),t(null,e)})({segment:n,finishProcessingFn:T,responseType:b.responseType,triggerSegmentEventFn:y});y({type:"segmentloadstart",segment:n});const v=e(b,S);v.addEventListener("progress",(({segment:e,progressFn:t,trackInfoFn:i,timingInfoFn:n,videoSegmentTimingInfoFn:s,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:u,dataFn:l})=>i=>{if(!i.target.aborted)return e.stats=C(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:a,trackInfoFn:r,timingInfoFn:o,videoSegmentTimingInfoFn:d,audioSegmentTimingInfoFn:u,id3Fn:l,captionsFn:h,isEndOfTimeline:c,endedTimelineFn:p,dataFn:m})),_.push(v);const w={};return _.forEach((e=>{e.addEventListener("loadend",(({loadendState:e,abortFn:t})=>i=>{i.target.aborted&&t&&!e.calledAbortFn&&(t(),e.calledAbortFn=!0)})({loadendState:w,abortFn:s}))})),()=>ki(_)},Vi=l("PlaylistSelector"),Gi=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||""})},Wi=function(e,t){if(!e)return"";const i=window.getComputedStyle(e);return i?i[t]:""},Hi=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}))},Xi=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 ji=function(e){const{main:t,bandwidth:i,playerWidth:n,playerHeight:s,playerObjectFit:a,limitRenditionByPlayerDimensions:r,playlistController:o}=e;if(!t)return;const d={bandwidth:i,width:n,height:s,limitRenditionByPlayerDimensions:r};let u=t.playlists;re.isAudioOnly(t)&&(u=o.getAudioTrackPlaylists_(),d.audioOnly=!0);let l=u.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}}));Hi(l,((e,t)=>e.bandwidth-t.bandwidth)),l=l.filter((e=>!re.isIncompatible(e.playlist)));let h=l.filter((e=>re.isEnabled(e.playlist)));h.length||(h=l.filter((e=>!re.isDisabled(e.playlist))));const c=h.filter((e=>e.bandwidth*Ti.BANDWIDTH_VARIANCE<i));let p=c[c.length-1];const m=c.filter((e=>e.bandwidth===p.bandwidth))[0];if(!1===r){const e=m||h[0]||l[0];if(e&&e.playlist){let t="sortedPlaylistReps";return m&&(t="bandwidthBestRep"),h[0]&&(t="enabledPlaylistReps"),Vi(`choosing ${Gi(e)} using ${t} with options`,d),e.playlist}return Vi("could not choose a playlist with options",d),null}const g=c.filter((e=>e.width&&e.height));Hi(g,((e,t)=>e.width-t.width));const f=g.filter((e=>e.width===n&&e.height===s));p=f[f.length-1];const y=f.filter((e=>e.bandwidth===p.bandwidth))[0];let _,T,b,S;if(y||(_=g.filter((e=>"cover"===a?e.width>n&&e.height>s:e.width>n||e.height>s)),T=_.filter((e=>e.width===_[0].width&&e.height===_[0].height)),p=T[T.length-1],b=T.filter((e=>e.bandwidth===p.bandwidth))[0]),o.leastPixelDiffSelector){const e=g.map((e=>(e.pixelDiff=Math.abs(e.width-n)+Math.abs(e.height-s),e)));Hi(e,((e,t)=>e.pixelDiff===t.pixelDiff?t.bandwidth-e.bandwidth:e.pixelDiff-t.pixelDiff)),S=e[0]}const v=S||b||y||m||h[0]||l[0];if(v&&v.playlist){let e="sortedPlaylistReps";return S?e="leastPixelDiffRep":b?e="resolutionPlusOneRep":y?e="resolutionBestRep":m?e="bandwidthBestRep":h[0]&&(e="enabledPlaylistReps"),Vi(`choosing ${Gi(v)} using ${e} with options`,d),v.playlist}return Vi("could not choose a playlist with options",d),null};const zi=function(){let e=this.useDevicePixelRatio&&window.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(e=this.customPixelRatio),ji({main:this.playlists.main,bandwidth:this.systemBandwidth,playerWidth:parseInt(Wi(this.tech_.el(),"width"),10)*e,playerHeight:parseInt(Wi(this.tech_.el(),"height"),10)*e,playerObjectFit:this.usePlayerObjectFit?Wi(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})};function Yi(e){try{return new URL(e).pathname.split("/").slice(-2).join("/")}catch(e){return""}}const Qi={id:"ID",class:"CLASS",startDate:"START-DATE",duration:"DURATION",endDate:"END-DATE",endOnNext:"END-ON-NEXT",plannedDuration:"PLANNED-DURATION",scte35Out:"SCTE35-OUT",scte35In:"SCTE35-IN"},Ki=new Set(["id","class","startDate","duration","endDate","endOnNext","startTime","endTime","processDateRange"]),Ji=(e,t,i)=>{e.metadataTrack_||(e.metadataTrack_=i.addRemoteTextTrack({kind:"metadata",label:"Timed Metadata"},!1).track,s.default.browser.IS_ANY_SAFARI||(e.metadataTrack_.inBandMetadataTrackDispatchType=t))},Zi=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 en=9e4,tn=en;const nn=e=>"number"==typeof e&&isFinite(e),sn=1/60,an=e=>{const{startOfSegment:t,duration:i,segment:n,part:s,playlist:{mediaSequence:a,id:r,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",g=p?X({preloadSegment:n})-1:0;return`${m} [${a+d}/${a+h}]`+(p?` part [${u}/${g}]`:"")+` 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 [${r}]`},rn=e=>`${e}TimingInfo`,on=({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},dn=e=>{const t=e.pendingSegment_;if(t&&on({timelineChangeController:e.timelineChangeController_,currentTimeline:e.currentTimeline_,segmentTimeline:t.timeline,loaderType:e.loaderType_,audioDisabled:e.audioDisabled_})&&(e=>{if(!e)return!1;const t=e.pendingTimelineChange({type:"audio"}),i=e.pendingTimelineChange({type:"main"}),n=t&&i,s=n&&t.to!==i.to;return!(!n||-1===t.from||-1===i.from||!s)})(e.timelineChangeController_)){if((e=>{const t=e.timelineChangeController_.pendingTimelineChange({type:"audio"}),i=e.timelineChangeController_.pendingTimelineChange({type:"main"});return t&&i&&t.to<i.to})(e))return void e.timelineChangeController_.trigger("audioTimelineBehind");e.timelineChangeController_.trigger("fixBadTimelineChange")}},un=({segmentDuration:e,maxDuration:t})=>!!e&&Math.round(e)>t+k,ln=({type:e,segment:t})=>{if(!t)return;const i=Boolean(t.key||t.map&&t.map.ke),n=Boolean(t.map&&!t.map.bytes),s=void 0===t.startOfSegment?t.start:t.startOfSegment;return{type:e||t.type,uri:t.resolvedUri||t.uri,start:s,duration:t.duration,isEncrypted:i,isMediaInitialization:n}};class hn 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.addMetadataToTextTrack=e.addMetadataToTextTrack,this.checkBufferTimeout_=null,this.error_=void 0,this.currentTimeline_=-1,this.shouldForceTimestampOffsetAfterResync_=!1,this.pendingSegment_=null,this.xhrOptions_=null,this.pendingSegments_=[],this.audioDisabled_=!1,this.isPendingTimestampOffset_=!1,this.gopBuffer_=[],this.timeMapping_=0,this.safeAppend_=!1,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_=l(`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_():dn(this)})),this.sourceUpdater_.on("codecschange",(e=>{this.trigger(a({type:"codecschange"},e))})),"main"===this.loaderType_&&this.timelineChangeController_.on("pendingtimelinechange",(()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():dn(this)})),"audio"===this.loaderType_&&this.timelineChangeController_.on("timelinechange",(e=>{this.trigger(a({type:"timelinechange"},e)),this.hasEnoughInfoToLoad_()?this.processLoadQueue_():dn(this),this.hasEnoughInfoToAppend_()?this.processCallQueue_():dn(this)}))}get mediaSequenceSync_(){return this.syncController_.getMediaSequenceSync(this.loaderType_)}createTransmuxer_(){return(e=>{const t=new Ei;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(){if("WAITING"!==this.state)return this.pendingSegment_&&(this.pendingSegment_=null),void this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);this.abort_(),this.state="READY",this.paused()||this.monitorBuffer_()}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_&&Ui(this.transmuxer_),this.gopBuffer_.length=0,this.pause(),this.trigger("ended")}buffered_(){const e=this.getMediaInfo_();if(!this.sourceUpdater_||!e)return O();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=Ye(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=Qe(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;if(this.playlist_&&this.playlist_.endList&&e.endList&&this.playlist_.uri===e.uri)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.mediaSequenceSync_&&(this.mediaSequenceSync_.update(e,this.currentTime_()),this.logger_(`Playlist update:\ncurrentTime: ${this.currentTime_()}\nbufferedEnd: ${$(this.buffered_())}\n`,this.mediaSequenceSync_.diagnostics)),this.trigger("syncinfoupdate"),"INIT"===this.state&&this.couldBeginLoading_())return this.init_();if(!i||i.uri!==e.uri)return null!==this.mediaIndex&&(e.endList||"number"!=typeof e.partTargetDuration?this.resyncLoader():this.resetLoader()),this.currentMediaInfo_=void 0,void this.trigger("playlistupdate");const a=e.mediaSequence-i.mediaSequence;if(this.logger_(`live window shift [${a}]`),null!==this.mediaIndex)if(this.mediaIndex-=a,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-=a,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.activeInitSegmentId_=null,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.mediaSequenceSync_&&this.mediaSequenceSync_.resetAppendedStatus(),this.resyncLoader()}resyncLoader(){this.transmuxer_&&Ui(this.transmuxer_),this.mediaIndex=null,this.partIndex=null,this.syncPoint_=null,this.isPendingTimestampOffset_=!1;const e=this.currentMediaInfo_&&this.currentMediaInfo_.isFmp4;"hls"===this.sourceType_&&!e&&(this.shouldForceTimestampOffsetAfterResync_=!0),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 a=()=>{s--,0===s&&i()};!n&&this.audioDisabled_||(s++,this.sourceUpdater_.removeAudio(e,t,a)),(n||"main"===this.loaderType_)&&(this.gopBuffer_=((e,t,i,n)=>{const s=Math.ceil((t-n)*tn),a=Math.ceil((i-n)*tn),r=e.slice();let o=e.length;for(;o--&&!(e[o].pts<=a););if(-1===o)return r;let d=o+1;for(;d--&&!(e[d].pts<=s););return d=Math.max(d,0),r.splice(d,o-d+1),r})(this.gopBuffer_,e,t,this.timeMapping_),s++,this.sourceUpdater_.removeVideo(e,t,a));for(const i in this.inbandTextTracks_)Zi(e,t,this.inbandTextTracks_[i]);Zi(e,t,this.segmentMetadataTrack_),a()}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_();if(!e)return;const t={segmentInfo:ln({type:this.loaderType_,segment:e})};this.trigger({type:"segmentselected",metadata:t}),"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,a=!n||!n.parts||i+1===n.parts.length;return t.endList&&"open"===this.mediaSource_.readyState&&s&&a}chooseNextRequest_(){const e=this.buffered_(),t=$(e)||0,i=V(e,this.currentTime_()),n=!this.hasPlayed_()&&i>=1,a=i>=this.goalBufferLength_(),r=this.playlist_.segments;if(!r.length||n||a)return null;this.syncPoint_=this.syncPoint_||this.syncController_.getSyncPoint(this.playlist_,this.duration_(),this.currentTimeline_,this.currentTime_(),this.loaderType_);const o={partIndex:null,mediaIndex:null,startOfSegment:null,playlist:this.playlist_,isSyncRequest:Boolean(!this.syncPoint_)};if(o.isSyncRequest)o.mediaIndex=function(e,t,i){t=t||[];const n=[];let s=0;for(let a=0;a<t.length;a++){const r=t[a];if(e===r.timeline&&(n.push(a),s+=r.duration,s>i))return a}return 0===n.length?0:n[n.length-1]}(this.currentTimeline_,r,t),this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${o.mediaIndex}`);else if(null!==this.mediaIndex){const e=r[this.mediaIndex],i="number"==typeof this.partIndex?this.partIndex:-1;o.startOfSegment=e.end?e.end:t,e.parts&&e.parts[i+1]?(o.mediaIndex=this.mediaIndex,o.partIndex=i+1):o.mediaIndex=this.mediaIndex+1}else{let e,i,n;const a=this.fetchAtBuffer_?t:this.currentTime_();if(this.mediaSequenceSync_&&this.logger_(`chooseNextRequest_ request after Quality Switch:\nFor TargetTime: ${a}.\nCurrentTime: ${this.currentTime_()}\nBufferedEnd: ${t}\nFetch At Buffer: ${this.fetchAtBuffer_}\n`,this.mediaSequenceSync_.diagnostics),this.mediaSequenceSync_&&this.mediaSequenceSync_.isReliable){const t=this.getSyncInfoFromMediaSequenceSync_(a);if(!t){const e="No sync info found while using media sequence sync";return this.error({message:e,metadata:{errorType:s.default.Error.StreamingFailedToSelectNextSegment,error:new Error(e)}}),this.logger_("chooseNextRequest_ - no sync info found using media sequence sync"),null}this.logger_(`chooseNextRequest_ mediaSequence syncInfo (${t.start} --\x3e ${t.end})`),e=t.segmentIndex,i=t.partIndex,n=t.start}else{this.logger_("chooseNextRequest_ - fallback to a regular segment selection algorithm, based on a syncPoint.");const t=re.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,playlist:this.playlist_,currentTime:a,startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time});e=t.segmentIndex,i=t.partIndex,n=t.startTime}o.getMediaInfoForTime=this.fetchAtBuffer_?`bufferedEnd ${a}`:`currentTime ${a}`,o.mediaIndex=e,o.startOfSegment=n,o.partIndex=i,this.logger_(`choose next request. Playlist switched and we have a sync point. Media Index: ${o.mediaIndex} `)}const d=r[o.mediaIndex];let u=d&&"number"==typeof o.partIndex&&d.parts&&d.parts[o.partIndex];if(!d||"number"==typeof o.partIndex&&!u)return null;"number"!=typeof o.partIndex&&d.parts&&(o.partIndex=0,u=d.parts[0]);const l=this.vhs_.playlists&&this.vhs_.playlists.main&&this.vhs_.playlists.main.independentSegments||this.playlist_.independentSegments;if(!i&&u&&!l&&!u.independent)if(0===o.partIndex){const e=r[o.mediaIndex-1],t=e.parts&&e.parts.length&&e.parts[e.parts.length-1];t&&t.independent&&(o.mediaIndex-=1,o.partIndex=e.parts.length-1,o.independent="previous segment")}else d.parts[o.partIndex-1].independent&&(o.partIndex-=1,o.independent="previous part");const h=this.mediaSource_&&"ended"===this.mediaSource_.readyState;return o.mediaIndex>=r.length-1&&h&&!this.seeking_()?null:(this.shouldForceTimestampOffsetAfterResync_&&(this.shouldForceTimestampOffsetAfterResync_=!1,o.forceTimestampOffset=!0,this.logger_("choose next request. Force timestamp offset after loader resync")),this.generateSegmentInfo_(o))}getSyncInfoFromMediaSequenceSync_(e){if(!this.mediaSequenceSync_)return null;const t=Math.max(e,this.mediaSequenceSync_.start);e!==t&&this.logger_(`getSyncInfoFromMediaSequenceSync_. Pulled target time from ${e} to ${t}`);const i=this.mediaSequenceSync_.getSyncInfoForTime(t);if(!i)return null;if(!i.isAppended)return i;const n=this.mediaSequenceSync_.getSyncInfoForTime(i.end);return n?(n.isAppended&&this.logger_("getSyncInfoFromMediaSequenceSync_: We encounter unexpected scenario where next media sequence sync info is also appended!"),n):null}generateSegmentInfo_(e){const{independent:t,playlist:i,mediaIndex:n,startOfSegment:s,isSyncRequest:a,partIndex:r,forceTimestampOffset:o,getMediaInfoForTime:d}=e,u=i.segments[n],l="number"==typeof r&&u.parts[r],h={requestId:"segment-loader-"+Math.random(),uri:l&&l.resolvedUri||u.resolvedUri,mediaIndex:n,partIndex:l?r:null,isSyncRequest:a,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=$(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)*tn);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=re.estimateSegmentRequestTime(n,i,this.playlist_,e.bytesReceived),a=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<=a)return;const r=function(e){const{main:t,currentTime:i,bandwidth:n,duration:s,segmentDuration:a,timeUntilRebuffer:r,currentTimeline:o,syncController:d}=e,u=t.playlists.filter((e=>!re.isIncompatible(e)));let l=u.filter(re.isEnabled);l.length||(l=u.filter((e=>!re.isDisabled(e))));const h=l.filter(re.hasAttribute.bind(null,"BANDWIDTH")).map((e=>{const t=d.getSyncPoint(e,s,o,i)?1:2;return{playlist:e,rebufferingImpact:re.estimateSegmentRequestTime(a,n,e)*t-r}})),c=h.filter((e=>e.rebufferingImpact<=0));return Hi(c,((e,t)=>Xi(t.playlist,e.playlist))),c.length?c[0]:(Hi(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:a,currentTimeline:this.currentTimeline_,syncController:this.syncController_});if(!r)return;const o=s-a-r.rebufferingImpact;let d=.5;a<=k&&(d=1),!r.playlist||r.playlist.uri===this.playlist_.uri||o<d||(this.bandwidth=r.playlist.attributes.BANDWIDTH*Ti.BANDWIDTH_VARIANCE+1,this.trigger("earlyabort"))}handleAbort_(e){this.logger_(`Aborting ${an(e)}`),this.mediaRequestsAborted+=1}handleProgress_(e,t){this.earlyAbortWhenNeeded_(t.stats),this.checkForAbort_(t.requestId)||this.trigger("progress")}handleTrackInfo_(e,t){const{hasAudio:i,hasVideo:n}=t,s={segmentInfo:ln({type:this.loaderType_,segment:e}),trackInfo:{hasAudio:i,hasVideo:n}};this.trigger({type:"segmenttransmuxingtrackinfoavailable",metadata:s}),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 a=i[s];if(a!==n[s])return!1;if(e[a]!==t[a])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_():dn(this)))}handleTimingInfo_(e,t,i,n){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;const s=this.pendingSegment_,a=rn(t);s[a]=s[a]||{},s[a][i]=n,this.logger_(`timinginfo: ${t} - ${i} - ${n}`),this.hasEnoughInfoToAppend_()?this.processCallQueue_():dn(this)}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:a}=n[e],r=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,a=i,r=!1;const o=(t.options_.vhs&&t.options_.vhs.captionServices||{})[n];o&&(s=o.label,a=o.language,r=o.default),e[i]=t.addRemoteTextTrack({kind:"captions",id:n,default:r,label:s,language:a},!1).track}}}(r,this.vhs_.tech_,e),Zi(t,s,r[e]),function({inbandTextTracks:e,captionArray:t,timestampOffset:i}){if(!t)return;const n=window.WebKitDataCue||window.VTTCue;t.forEach((t=>{const s=t.stream;t.content?t.content.forEach((a=>{const r=new n(t.startTime+i,t.endTime+i,a.text);r.line=a.line,r.align="left",r.position=a.position,r.positionAlign="line-left",e[s].addCue(r)})):e[s].addCue(new n(t.startTime+i,t.endTime+i,t.text))}))}({captionArray:a,inbandTextTracks:r,timestampOffset:i})})),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}handleId3_(e,t,i){this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId)||(this.pendingSegment_.hasAppendedData_?this.addMetadataToTextTrack(i,t,this.duration_()):this.metadataQueue_.id3.push(this.handleId3_.bind(this,e,t,i)))}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_()&&on({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_}getPendingSegmentPlaylist(){return this.pendingSegment_?this.pendingSegment_.playlist:null}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||on({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 dn(this),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[rn(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=Ye(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(),a=this.sourceUpdater_.videoBuffered();s.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: "+q(s).join(", ")),a.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: "+q(a).join(", "));const r=s.length?s.start(0):0,o=s.length?s.end(s.length-1):0,d=a.length?a.start(0):0,u=a.length?a.end(a.length-1):0;if(o-r<=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(a).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({message:`${t} append of ${i.length}b failed for segment #${e.mediaIndex} in playlist ${e.playlist.id}`,metadata:{errorType:s.default.Error.StreamingFailedToAppendSegment}}),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})}const a={segmentInfo:ln({type:this.loaderType_,segment:e})};this.trigger({type:"segmentappendstart",metadata:a}),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){if(this.state="WAITING",this.pendingSegment_=e,this.trimBackBuffer_(e),"number"==typeof e.timestampOffset&&this.transmuxer_&&this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),!this.hasEnoughInfoToLoad_())return dn(this),void this.loadQueue_.push((()=>{const t=a({},e,{forceTimestampOffset:!0});a(e,this.generateSegmentInfo_(t)),this.isPendingTimestampOffset_=!1,this.updateTransmuxerAndRequestSegment_(e)}));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,a=i||n&&s;this.logger_(`Requesting\n${Yi(e.uri)}\n${an(e)}`),t.map&&!t.map.bytes&&(this.logger_("going to request init segment."),this.appendInitSegment_={video:!0,audio:!0}),e.abortRequests=$i({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:a,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_(`${an(e)} logged from transmuxer stream ${n} as a ${i}: ${t}`)},triggerSegmentEventFn:({type:e,segment:t,keyInfo:i,trackInfo:n,timingInfo:s})=>{const a={segmentInfo:ln({segment:t})};i&&(a.keyInfo=i),n&&(a.trackInfo=n),s&&(a.timingInfo=s),this.trigger({type:e,metadata:a})}})}trimBackBuffer_(e){const t=((e,t,i)=>{let n=t-Ti.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=e.segment.key||e.segment.map&&e.segment.map.key,s=e.segment.map&&!e.segment.map.bytes,a={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,type:this.loaderType_,start:e.startOfSegment,duration:e.duration,isEncrypted:n,isMediaInitialization:s},r=e.playlist.segments[e.mediaIndex-1];if(r&&r.timeline===t.timeline&&(r.videoTimingInfo?a.baseStartTime=r.videoTimingInfo.transmuxedDecodeEnd:r.audioTimingInfo&&(a.baseStartTime=r.audioTimingInfo.transmuxedDecodeEnd)),t.key){const i=t.key.iv||new Uint32Array([0,0,0,e.mediaIndex+e.playlist.mediaSequence]);a.key=this.segmentKey(t.key),a.key.iv=i}return t.map&&(a.map=this.initSegmentForMap(t.map)),a}saveTransferStats_(e){this.mediaRequests+=1,e&&(this.mediaBytesTransferred+=e.bytesReceived,this.mediaTransferDuration+=e.roundTripTime)}saveBandwidthRelatedStats_(e,t){if(this.pendingSegment_.byteLength=t.bytesReceived,e<sn)return void this.logger_(`Ignoring segment's bandwidth because its duration of ${e} is less than the min to record 0.016666666666666666`);const i={bandwidthInfo:{from:this.bandwidth,to:t.bandwidth}};this.trigger({type:"bandwidthupdated",metadata:i}),this.bandwidth=t.bandwidth,this.roundTrip=t.roundTripTime}handleTimeout_(){this.mediaRequestsTimedout+=1,this.bandwidth=1,this.roundTrip=NaN,this.trigger("bandwidthupdate"),this.trigger("timeout")}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===Ci)return;return this.pause(),e.code===Pi?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:a,videoTimingInfo:r,audioTimingInfo:o}){if(void 0!==e)return e;if(!a)return o.start;const d=t.segments[i-1];return 0!==i&&d&&void 0!==d.start&&d.end===n+s?r.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,a="main"===this.loaderType_&&n,r=!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);a&&e.waitingOnAppends++,r&&e.waitingOnAppends++,a&&this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this,e)),r&&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_){const e={segmentInfo:ln({type:this.loaderType_,segment:this.pendingSegment_})};this.trigger({type:"appendsdone",metadata:e})}if(!this.pendingSegment_)return this.state="READY",void(this.paused()||this.monitorBuffer_());const e=this.pendingSegment_;e.part&&e.part.syncInfo?e.part.syncInfo.markAppended():e.segment.syncInfo&&e.segment.syncInfo.markAppended(),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:a}=n;let r;"bigint"==typeof s||"bigint"==typeof a?r=window.BigInt(a)-window.BigInt(s):"number"==typeof s&&"number"==typeof a&&(r=a-s),void 0!==r&&r>t&&(t=r)})),"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=un({segmentDuration:i,maxDuration:2*n}),a=un({segmentDuration:i,maxDuration:n}),r=`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||a?{severity:s?"warn":"info",message:r}: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 ${an(e)}`);this.logger_(`Appended ${an(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,a=i.end&&this.currentTime_()-i.end>3*e.playlist.targetDuration,r=n&&n.end&&this.currentTime_()-n.end>3*e.playlist.partTargetDuration;if(a||r)return this.logger_(`bad ${a?"segment":"part"} ${an(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<sn)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(!nn(i)||!nn(n))return;Zi(i,n,this.segmentMetadataTrack_);const s=window.WebKitDataCue||window.VTTCue,a={custom:t.custom,dateTimeObject:t.dateTimeObject,dateTimeString:t.dateTimeString,programDateTime:t.programDateTime,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},r=new s(i,n,JSON.stringify(a));r.value=a,this.segmentMetadataTrack_.addCue(r)}}function cn(){}const pn=function(e){return"string"!=typeof e?e:e.replace(/./,(e=>e.toUpperCase()))},mn=["video","audio"],gn=(e,t)=>{const i=t[`${e}Buffer`];return i&&i.updating||t.queuePending[e]},fn=(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&&!gn(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 fn(e,t))}}else t.updating()||"closed"===t.mediaSource.readyState||(t.queue.shift(),n.action(t),n.doneFn&&n.doneFn(),fn("audio",t),fn("video",t))},yn=(e,t)=>{const i=t[`${e}Buffer`],n=pn(e);i&&(i.removeEventListener("updateend",t[`on${n}UpdateEnd_`]),i.removeEventListener("error",t[`on${n}Error_`]),t.codecs[e]=null,t[`${e}Buffer`]=null)},_n=(e,t)=>e&&t&&-1!==Array.prototype.indexOf.call(e.sourceBuffers,t),Tn=(e,t,i)=>(n,s)=>{const a=s[`${n}Buffer`];if(_n(s.mediaSource,a)){s.logger_(`Appending segment ${t.mediaIndex}'s ${e.length} bytes to ${n}Buffer`);try{a.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)}}},bn=(e,t)=>(i,n)=>{const s=n[`${i}Buffer`];if(_n(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`)}}},Sn=e=>(t,i)=>{const n=i[`${t}Buffer`];_n(i.mediaSource,n)&&(i.logger_(`Setting ${t}timestampOffset to ${e}`),n.timestampOffset=e)},vn=e=>(t,i)=>{e()},wn=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)}}},In=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)}},En=(e,t)=>i=>{const n=pn(e),s=x(t);i.logger_(`Adding ${e}Buffer with codec ${t} to mediaSource`);const a=i.mediaSource.addSourceBuffer(s);a.addEventListener("updateend",i[`on${n}UpdateEnd_`]),a.addEventListener("error",i[`on${n}Error_`]),i.codecs[e]=t,i[`${e}Buffer`]=a},An=e=>t=>{const i=t[`${e}Buffer`];if(yn(e,t),_n(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)}}},Dn=e=>(t,i)=>{const n=i[`${t}Buffer`],a=x(e);if(!_n(i.mediaSource,n))return;const r=e.substring(0,e.indexOf(".")),o=i.codecs[t];if(o.substring(0,o.indexOf("."))===r)return;const d={codecsChangeInfo:{from:o,to:e}};i.trigger({type:"codecschange",metadata:d}),i.logger_(`changing ${t}Buffer codec from ${o} to ${e}`);try{n.changeType(a),i.codecs[t]=e}catch(e){d.errorType=s.default.Error.StreamingCodecsChangeError,d.error=e,e.metadata=d,i.error_=e,i.trigger("error"),s.default.log.warn(`Failed to changeType on ${t}Buffer`,e)}},xn=({type:e,sourceUpdater:t,action:i,doneFn:n,name:s})=>{t.queue.push({type:e,action:i,doneFn:n,name:s}),fn(e,t)},Un=(e,t)=>i=>{const n=function(e){if(0===e.length)return"Buffered Ranges are empty";let t="Buffered Ranges: \n";for(let i=0;i<e.length;i++){const n=e.start(i),s=e.end(i);t+=`${n} --\x3e ${s}. Duration (${s-n})\n`}return t}(t[`${e}Buffered`]());if(t.logger_(`received "updateend" event for ${e} Source Buffer: `,n),t.queuePending[e]){const i=t.queuePending[e].doneFn;t.queuePending[e]=null,i&&i(t[`${e}Error_`])}fn(e,t)};class Ln extends s.default.EventTarget{constructor(e){super(),this.mediaSource=e,this.sourceopenListener_=()=>fn("mediaSource",this),this.mediaSource.addEventListener("sourceopen",this.sourceopenListener_),this.logger_=l("SourceUpdater"),this.audioTimestampOffset_=0,this.videoTimestampOffset_=0,this.queue=[],this.queuePending={audio:null,video:null},this.delayedAudioAppendQueue_=[],this.videoAppendQueued_=!1,this.codecs={},this.onVideoUpdateEnd_=Un("video",this),this.onAudioUpdateEnd_=Un("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){xn({type:"mediaSource",sourceUpdater:this,action:En(e,t),name:"addSourceBuffer"})}abort(e){xn({type:e,sourceUpdater:this,action:(e,t)=>{if("open"!==t.mediaSource.readyState)return;const i=t[`${e}Buffer`];if(_n(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()?xn({type:"mediaSource",sourceUpdater:this,action:An(e),name:"removeSourceBuffer"}):s.default.log.error("removeSourceBuffer is not supported!")}canRemoveSourceBuffer(){return!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()?xn({type:e,sourceUpdater:this,action:Dn(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(xn({type:n,sourceUpdater:this,action:Tn(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 _n(this.mediaSource,this.audioBuffer)&&this.audioBuffer.buffered?this.audioBuffer.buffered:O()}videoBuffered(){return _n(this.mediaSource,this.videoBuffer)&&this.videoBuffer.buffered?this.videoBuffer.buffered:O()}buffered(){const e=_n(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,t=_n(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 a=[],r=[];if(!(e&&e.length&&t&&t.length))return O();let o=e.length;for(;o--;)a.push({time:e.start(o),type:"start"}),a.push({time:e.end(o),type:"end"});for(o=t.length;o--;)a.push({time:t.start(o),type:"start"}),a.push({time:t.end(o),type:"end"});for(a.sort((function(e,t){return e.time-t.time})),o=0;o<a.length;o++)"start"===a[o].type?(s++,2===s&&(i=a[o].time)):"end"===a[o].type&&(s--,1===s&&(n=a[o].time)),null!==i&&null!==n&&(r.push([i,n]),i=null,n=null);return O(r)}(this.audioBuffered(),this.videoBuffered())}setDuration(e,t=cn){xn({type:"mediaSource",sourceUpdater:this,action:In(e),name:"duration",doneFn:t})}endOfStream(e=null,t=cn){"string"!=typeof e&&(e=void 0),xn({type:"mediaSource",sourceUpdater:this,action:wn(e),name:"endOfStream",doneFn:t})}removeAudio(e,t,i=cn){this.audioBuffered().length&&0!==this.audioBuffered().end(0)?xn({type:"audio",sourceUpdater:this,action:bn(e,t),doneFn:i,name:"remove"}):i()}removeVideo(e,t,i=cn){this.videoBuffered().length&&0!==this.videoBuffered().end(0)?xn({type:"video",sourceUpdater:this,action:bn(e,t),doneFn:i,name:"remove"}):i()}updating(){return!(!gn("audio",this)&&!gn("video",this))}audioTimestampOffset(e){return void 0!==e&&this.audioBuffer&&this.audioTimestampOffset_!==e&&(xn({type:"audio",sourceUpdater:this,action:Sn(e),name:"timestampOffset"}),this.audioTimestampOffset_=e),this.audioTimestampOffset_}videoTimestampOffset(e){return void 0!==e&&this.videoBuffer&&this.videoTimestampOffset_!==e&&(xn({type:"video",sourceUpdater:this,action:Sn(e),name:"timestampOffset"}),this.videoTimestampOffset_=e),this.videoTimestampOffset_}audioQueueCallback(e){this.audioBuffer&&xn({type:"audio",sourceUpdater:this,action:vn(e),name:"callback"})}videoQueueCallback(e){this.videoBuffer&&xn({type:"video",sourceUpdater:this,action:vn(e),name:"callback"})}dispose(){this.trigger("dispose"),mn.forEach((e=>{this.abort(e),this.canRemoveSourceBuffer()?this.removeSourceBuffer(e):this[`${e}QueueCallback`]((()=>yn(e,this)))})),this.videoAppendQueued_=!1,this.delayedAudioAppendQueue_.length=0,this.sourceopenListener_&&this.mediaSource.removeEventListener("sourceopen",this.sourceopenListener_),this.off()}}const Pn=e=>decodeURIComponent(escape(String.fromCharCode.apply(null,e))),Cn=new Uint8Array("\n\n".split("").map((e=>e.charCodeAt(0))));class On extends Error{constructor(){super("Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.")}}class kn extends hn{constructor(e,t={}){super(e,t),this.mediaSource_=null,this.subtitlesTrack_=null,this.featuresNativeTextTracks_=e.featuresNativeTextTracks,this.loadVttJs=e.loadVttJs,this.shouldSaveSegmentTimingInfo_=!1}buffered_(){if(!this.subtitlesTrack_||!this.subtitlesTrack_.cues||!this.subtitlesTrack_.cues.length)return O();const e=this.subtitlesTrack_.cues;return O([[e[0].startTime,e[e.length-1].startTime]])}initSegmentForMap(e,t=!1){if(!e)return null;const i=Ye(e);let n=this.initSegments_[i];if(t&&!n&&e.bytes){const t=Cn.byteLength+e.bytes.byteLength,s=new Uint8Array(t);s.set(e.bytes),s.set(Cn,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){Zi(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===Pi&&this.handleTimeout_(),e.code===Ci?this.mediaRequestsAborted+=1:this.mediaRequestsErrored+=1,void this.stopForError(e);const n=this.pendingSegment_,a=i.mp4VttCues&&i.mp4VttCues.length;a&&(n.mp4VttCues=i.mp4VttCues),this.saveBandwidthRelatedStats_(n.duration,t.stats),t.key&&this.segmentKey(t.key,!0),this.state="APPENDING",this.trigger("appending");const r=n.segment;if(r.map&&(r.map.bytes=t.map.bytes),n.bytes=t.bytes,"function"!=typeof window.WebVTT&&"function"==typeof this.loadVttJs)return this.state="WAITING_ON_VTTJS",void this.loadVttJs().then((()=>this.segmentRequestFinished_(e,t,i)),(()=>this.stopForError({message:"Error loading vtt.js"})));r.requested=!0;try{this.parseVTTCues_(n)}catch(e){return void this.stopForError({message:e.message,metadata:{errorType:s.default.Error.StreamingVttParserError,error:e}})}if(a||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+=r.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)return;const i={};for(let n=t.length-1;n>=0;n--){const s=t[n],a=`${s.startTime}-${s.endTime}-${s.text}`;i[a]?e.removeCue(s):i[a]=s}}(this.subtitlesTrack_),this.handleAppendsDone_()}handleData_(e,t){const i=e&&"vtt"===e.type,n=t&&"text"===t.type;i&&n&&super.handleData_(e,t)}updateTimingInfoEnd_(){}parseMp4VttCues_(e){const t=null===this.sourceUpdater_.videoTimestampOffset()?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset();e.mp4VttCues.forEach((i=>{const n=i.start+t,s=i.end+t,a=new window.VTTCue(n,s,i.cueText);i.settings&&i.settings.split(" ").forEach((e=>{const t=e.split(":"),i=t[0],n=t[1];a[i]=isNaN(n)?n:Number(n)})),e.cues.push(a)}))}parseVTTCues_(e){let t,i=!1;if("function"!=typeof window.WebVTT)throw new On;if(e.cues=[],e.timestampmap={MPEGTS:0,LOCAL:0},e.mp4VttCues)return void this.parseMp4VttCues_(e);"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(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=Pn(t)),n.parse(t)}let a=e.bytes;i&&(a=Pn(a)),n.parse(a),n.flush()}updateTimeMapping_(e,t,i){const n=e.segment;if(!t)return;if(!e.cues.length)return void(n.empty=!0);const{MPEGTS:s,LOCAL:a}=e.timestampmap,r=s/tn-a+t.mapping;if(e.cues.forEach((e=>{const i=e.endTime-e.startTime,n=this.handleRollover_(e.startTime+r,t.time);e.startTime=Math.max(n,0),e.endTime=Math.max(n+i,0)})),!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)}}}handleRollover_(e,t){if(null===t)return e;let i=e*tn;const n=t*tn;let s;for(s=n<i?-8589934592:8589934592;Math.abs(i-n)>4294967296;)i+=s;return i/tn}}const Rn=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};class Mn{constructor({start:e,end:t,segmentIndex:i,partIndex:n=null,appended:s=!1}){this.start_=e,this.end_=t,this.segmentIndex_=i,this.partIndex_=n,this.appended_=s}isInRange(e){return e>=this.start&&e<this.end}markAppended(){this.appended_=!0}resetAppendedStatus(){this.appended_=!1}get isAppended(){return this.appended_}get start(){return this.start_}get end(){return this.end_}get segmentIndex(){return this.segmentIndex_}get partIndex(){return this.partIndex_}}class Nn{constructor(e,t=[]){this.segmentSyncInfo_=e,this.partsSyncInfo_=t}get segmentSyncInfo(){return this.segmentSyncInfo_}get partsSyncInfo(){return this.partsSyncInfo_}get hasPartsSyncInfo(){return this.partsSyncInfo_.length>0}resetAppendStatus(){this.segmentSyncInfo_.resetAppendedStatus(),this.partsSyncInfo_.forEach((e=>e.resetAppendedStatus()))}}class Bn{constructor(){this.storage_=new Map,this.diagnostics_="",this.isReliable_=!1,this.start_=-1/0,this.end_=1/0}get start(){return this.start_}get end(){return this.end_}get diagnostics(){return this.diagnostics_}get isReliable(){return this.isReliable_}resetAppendedStatus(){this.storage_.forEach((e=>e.resetAppendStatus()))}update(e,t){const{mediaSequence:i,segments:n}=e;if(this.isReliable_=this.isReliablePlaylist_(i,n),this.isReliable_)return this.updateStorage_(n,i,this.calculateBaseTime_(i,n,t))}getSyncInfoForTime(e){for(const{segmentSyncInfo:t,partsSyncInfo:i}of this.storage_.values())if(i.length){for(const t of i)if(t.isInRange(e))return t}else if(t.isInRange(e))return t;return null}getSyncInfoForMediaSequence(e){return this.storage_.get(e)}updateStorage_(e,t,i){const n=new Map;let s="\n",a=i,r=t;this.start_=a,e.forEach(((e,t)=>{const i=this.storage_.get(r),o=a,d=o+e.duration,u=Boolean(i&&i.segmentSyncInfo&&i.segmentSyncInfo.isAppended),l=new Mn({start:o,end:d,appended:u,segmentIndex:t});e.syncInfo=l;let h=a;const c=(e.parts||[]).map(((e,n)=>{const a=h,o=h+e.duration,d=Boolean(i&&i.partsSyncInfo&&i.partsSyncInfo[n]&&i.partsSyncInfo[n].isAppended),u=new Mn({start:a,end:o,appended:d,segmentIndex:t,partIndex:n});return h=o,s+=`Media Sequence: ${r}.${n} | Range: ${a} --\x3e ${o} | Appended: ${d}\n`,e.syncInfo=u,u}));n.set(r,new Nn(l,c)),s+=`${Yi(e.resolvedUri)} | Media Sequence: ${r} | Range: ${o} --\x3e ${d} | Appended: ${u}\n`,r++,a=d})),this.end_=a,this.storage_=n,this.diagnostics_=s}calculateBaseTime_(e,t,i){if(!this.storage_.size)return 0;if(this.storage_.has(e))return this.storage_.get(e).segmentSyncInfo.start;const n=Math.min(...this.storage_.keys());if(e<n){const i=n-e;let s=this.storage_.get(n).segmentSyncInfo.start;for(let e=0;e<i;e++)s-=t[e].duration;return s}return i}isReliablePlaylist_(e,t){return null!=e&&Array.isArray(t)&&t.length}}class Fn extends Bn{constructor(e){super(),this.parent_=e}calculateBaseTime_(e,t,i){if(!this.storage_.size){const t=this.parent_.getSyncInfoForMediaSequence(e);return t?t.segmentSyncInfo.start:0}return super.calculateBaseTime_(e,t,i)}}const qn=[{name:"VOD",run:(e,t,i,n,s)=>i!==1/0?{time:0,segmentIndex:0,partIndex:null}:null},{name:"MediaSequence",run:(e,t,i,n,s,a)=>{const r=e.getMediaSequenceSync(a);if(!r)return null;if(!r.isReliable)return null;const o=r.getSyncInfoForTime(s);return o?{time:o.start,partIndex:o.partIndex,segmentIndex:o.segmentIndex}:null}},{name:"ProgramDateTime",run:(e,t,i,n,s)=>{if(!Object.keys(e.timelineToDatetimeMappings).length)return null;let a=null,r=null;const o=W(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!==r&&(0===h||r<h))break;r=h,a={time:l,segmentIndex:n.segmentIndex,partIndex:n.partIndex}}return a}},{name:"Segment",run:(e,t,i,n,s)=>{let a=null,r=null;s=s||0;const o=W(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!==r&&r<e)break;(!a||null===r||r>=e)&&(r=e,a={time:u,segmentIndex:i.segmentIndex,partIndex:i.partIndex})}}return a}},{name:"Discontinuity",run:(e,t,i,n,s)=>{let a=null;if(s=s||0,t.discontinuityStarts&&t.discontinuityStarts.length){let i=null;for(let n=0;n<t.discontinuityStarts.length;n++){const r=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;(!a||null===i||i>=e)&&(i=e,a={time:d.time,segmentIndex:r,partIndex:null})}}}return a}},{name:"Playlist",run:(e,t,i,n,s)=>t.syncInfo?{time:t.syncInfo.time,segmentIndex:t.syncInfo.mediaSequence-t.mediaSequence,partIndex:null}:null}];class $n extends s.default.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={};const t=new Bn,i=new Fn(t),n=new Fn(t);this.mediaSequenceStorage_={main:t,audio:i,vtt:n},this.logger_=l("SyncController")}getMediaSequenceSync(e){return this.mediaSequenceStorage_[e]||null}getSyncPoint(e,t,i,n,s){if(t!==1/0)return qn.find((({name:e})=>"VOD"===e)).run(this,e,t);const a=this.runStrategies_(e,t,i,n,s);if(!a.length)return null;for(const t of a){const{syncPoint:i,strategy:s}=t,{segmentIndex:a,time:r}=i;if(a<0)continue;const o=r,d=o+e.segments[a].duration;if(this.logger_(`Strategy: ${s}. Current time: ${n}. selected segment: ${a}. Time: [${o} -> ${d}]}`),n>=o&&n<d)return this.logger_("Found sync point with exact match: ",i),i}return this.selectSyncPoint_(a,{key:"time",value:n})}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+Q({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:n.segmentIndex,endIndex:0}))}runStrategies_(e,t,i,n,s){const a=[];for(let r=0;r<qn.length;r++){const o=qn[r],d=o.run(this,e,t,i,n,s);d&&(d.strategy=o.name,a.push({strategy:o.name,syncPoint:d}))}return a}selectSyncPoint_(e,t){let i=e[0].syncPoint,n=Math.abs(e[0].syncPoint[t.key]-t.value),s=e[0].strategy;for(let a=1;a<e.length;a++){const r=Math.abs(e[a].syncPoint[t.key]-t.value);r<n&&(n=r,i=e[a].syncPoint,s=e[a].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 a,r,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}]`)),a=e.startOfSegment,r=t.end+o.mapping;else{if(!o)return!1;a=t.start+o.mapping,r=t.end+o.mapping}return s&&(s.start=a,s.end=r),(!n.start||a<n.start)&&(n.start=a),n.end=r,!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],a=t.discontinuitySequence+n+1,r=s-e.mediaIndex,o=Math.abs(r);if(!this.discontinuities[a]||this.discontinuities[a].accuracy>o){let n;n=r<0?i.start-Q({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:s}):i.end+Q({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:s}),this.discontinuities[a]={time:n,accuracy:o}}}}dispose(){this.trigger("dispose"),this.off()}}class Vn 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}){if("number"==typeof t&&"number"==typeof i){this.lastTimelineChanges_[e]={type:e,from:t,to:i},delete this.pendingTimelineChanges_[e];const n={timelineChangeInfo:{from:t,to:i}};this.trigger({type:"timelinechange",metadata:n})}return this.lastTimelineChanges_[e]}dispose(){this.trigger("dispose"),this.pendingTimelineChanges_={},this.lastTimelineChanges_={},this.off()}}const Gn=vi(wi((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),a=t.length,r=0;r<a;++r)t[r].apply(this,s)},t.dispose=function(){this.listeners={}},t.pipe=function(e){this.on("data",(function(t){e.push(t)}))},e}();
|
|
/*! @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 a,r,o;const d=[],u=[];let l,h,c,p,m,g;for(a=0;a<256;a++)u[(d[a]=a<<1^283*(a>>7))^a]=a;for(r=o=0;!n[r];r^=l||1,o=u[o]||1)for(p=o^o<<1^o<<2^o<<3^o<<4,p=p>>8^255&p^99,n[r]=p,s[p]=r,c=d[h=d[l=d[r]]],g=16843009*c^65537*h^257*l^16843008*r,m=257*d[p]^16843008*p,a=0;a<4;a++)t[a][r]=m=m<<24^m>>>8,i[a][p]=g=g<<24^g>>>8;for(a=0;a<5;a++)t[a]=t[a].slice(0),i[a]=i[a].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 a=this._tables[0][4],r=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=a[s>>>24]<<24^a[s>>16&255]<<16^a[s>>8&255]<<8^a[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:r[0][a[s>>>24]]^r[1][a[s>>16&255]]^r[2][a[s>>8&255]]^r[3][a[255&s]]}decrypt(e,t,i,n,s,a){const r=this._key[1];let o,d,u,l=e^r[0],h=n^r[1],c=i^r[2],p=t^r[3];const m=r.length/4-2;let g,f=4;const y=this._tables[1],_=y[0],T=y[1],b=y[2],S=y[3],v=y[4];for(g=0;g<m;g++)o=_[l>>>24]^T[h>>16&255]^b[c>>8&255]^S[255&p]^r[f],d=_[h>>>24]^T[c>>16&255]^b[p>>8&255]^S[255&l]^r[f+1],u=_[c>>>24]^T[p>>16&255]^b[l>>8&255]^S[255&h]^r[f+2],p=_[p>>>24]^T[l>>16&255]^b[h>>8&255]^S[255&c]^r[f+3],f+=4,l=o,h=d,c=u;for(g=0;g<4;g++)s[(3&-g)+a]=v[l>>>24]<<24^v[h>>16&255]<<16^v[c>>8&255]<<8^v[255&p]^r[f++],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 a{constructor(e,t,i,r){const o=a.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;
|
|
/*! @name aes-decrypter @version 4.0.2 @license Apache-2.0 */r(null,(e=u).subarray(0,e.byteLength-e[e.byteLength-1]))}))}static get STEP(){return 32e3}decryptChunk_(e,t,n,a){return function(){const r=function(e,t,n){const a=new Int32Array(e.buffer,e.byteOffset,e.byteLength>>2),r=new i(Array.prototype.slice.call(t)),o=new Uint8Array(e.byteLength),d=new Int32Array(o.buffer);let u,l,h,c,p,m,g,f,y;for(u=n[0],l=n[1],h=n[2],c=n[3],y=0;y<a.length;y+=4)p=s(a[y]),m=s(a[y+1]),g=s(a[y+2]),f=s(a[y+3]),r.decrypt(p,m,g,f,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=g,c=f;return o}(e,t,n);a.set(r,e.byteOffset)}}}var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},o=("undefined"!=typeof window?window:void 0!==r?r:"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 a(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 Wn=Si(Gn);const Hn=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)},jn=(e,t)=>{t.activePlaylistLoader=e,e.load()},zn={AUDIO:(e,t)=>()=>{const{mediaTypes:{[e]:i},excludePlaylist:n}=t,a=i.activeTrack(),r=i.activeGroup(),o=(r.filter((e=>e.default))[0]||r[0]).id,d=i.tracks[o];if(a!==d){s.default.log.warn("Problem encountered loading the alternate audio track.Switching back to default.");for(const e in i.tracks)i.tracks[e].enabled=i.tracks[e]===d;i.onTrackChanged()}else n({error:{message:"Problem encountered loading the default audio track."}})},SUBTITLES:(e,t)=>()=>{const{mediaTypes:{[e]:i}}=t;s.default.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");const n=i.activeTrack();n&&(n.mode="disabled"),i.onTrackChanged()}},Yn={AUDIO:(e,t,i)=>{if(!t)return;const{tech:n,requestOptions:s,segmentLoaders:{[e]:a}}=i;t.on("loadedmetadata",(()=>{const e=t.media();a.playlist(e,s),(!n.paused()||e.endList&&"none"!==n.preload())&&a.load()})),t.on("loadedplaylist",(()=>{a.playlist(t.media(),s),n.paused()||a.load()})),t.on("error",zn[e](e,i))},SUBTITLES:(e,t,i)=>{const{tech:n,requestOptions:s,segmentLoaders:{[e]:a},mediaTypes:{[e]:r}}=i;t.on("loadedmetadata",(()=>{const e=t.media();a.playlist(e,s),a.track(r.activeTrack()),(!n.paused()||e.endList&&"none"!==n.preload())&&a.load()})),t.on("loadedplaylist",(()=>{a.playlist(t.media(),s),n.paused()||a.load()})),t.on("error",zn[e](e,i))}},Qn={AUDIO:(e,t)=>{const{vhs:i,sourceType:n,segmentLoaders:{[e]:a},requestOptions:r,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 a in o[e]){d[a]||(d[a]=[]);for(const p in o[e][a]){let m,g=o[e][a][p];if(c?(l(`AUDIO group '${a}' label '${p}' is a main playlist`),g.isMainPlaylist=!0,m=null):m="vhs-json"===n&&g.playlists?new Ue(g.playlists[0],i,r):g.resolvedUri?new Ue(g.resolvedUri,i,r):g.playlists&&"dash"===n?new _i(g.playlists[0],i,r,h):null,g=C({id:p,playlistLoader:m},g),Yn[e](e,g.playlistLoader,t),d[a].push(g),void 0===u[p]){const e=new s.default.AudioTrack({id:p,kind:Hn(g),enabled:!1,language:g.language,default:g.default,label:p});u[p]=e}}}a.on("error",zn[e](e,t))},SUBTITLES:(e,t)=>{const{tech:i,vhs:n,sourceType:s,segmentLoaders:{[e]:a},requestOptions:r,main:{mediaGroups:o},mediaTypes:{[e]:{groups:d,tracks:u}},mainPlaylistLoader:l}=t;for(const a in o[e]){d[a]||(d[a]=[]);for(const h in o[e][a]){if(!n.options_.useForcedSubtitles&&o[e][a][h].forced)continue;let c,p=o[e][a][h];if("hls"===s)c=new Ue(p.resolvedUri,n,r);else if("dash"===s){if(!p.playlists.filter((e=>e.excludeUntil!==1/0)).length)return;c=new _i(p.playlists[0],n,r,l)}else"vhs-json"===s&&(c=new Ue(p.playlists?p.playlists[0]:p.resolvedUri,n,r));if(p=C({id:h,playlistLoader:c},p),Yn[e](e,p.playlistLoader,t),d[a].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}}}a.on("error",zn[e](e,t))},"CLOSED-CAPTIONS":(e,t)=>{const{tech:i,main:{mediaGroups:n},mediaTypes:{[e]:{groups:s,tracks:a}}}=t;for(const t in n[e]){s[t]||(s[t]=[]);for(const r in n[e][t]){const o=n[e][t][r];if(!/^(?:CC|SERVICE)/.test(o.instreamId))continue;const d=i.options_.vhs&&i.options_.vhs.captionServices||{};let u={label:r,language:o.language,instreamId:o.instreamId,default:o.default&&o.autoselect};if(d[u.instreamId]&&(u=C(u,d[u.instreamId])),void 0===u.default&&delete u.default,s[t].push(C({id:r},o)),void 0===a[r]){const e=i.addRemoteTextTrack({id:u.instreamId,kind:"captions",default:u.default,language:u.language,label:u.label},!1).track;a[r]=e}}}}},Kn=(e,t)=>{for(let i=0;i<e.length;i++){if(ne(t,e[i]))return!0;if(e[i].playlists&&Kn(e[i].playlists,t))return!0}return!1},Jn={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}};class Zn{constructor(){this.priority_=[],this.pathwayClones_=new Map}set version(e){1===e&&(this.version_=e)}set ttl(e){this.ttl_=e||300}set reloadUri(e){e&&(this.reloadUri_=d(this.reloadUri_,e))}set priority(e){e&&e.length&&(this.priority_=e)}set pathwayClones(e){e&&e.length&&(this.pathwayClones_=new Map(e.map((e=>[e.ID,e]))))}get version(){return this.version_}get ttl(){return this.ttl_}get reloadUri(){return this.reloadUri_}get priority(){return this.priority_}get pathwayClones(){return this.pathwayClones_}}class es extends s.default.EventTarget{constructor(e,t){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new Zn,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.currentPathwayClones=new Map,this.nextPathwayClones=new Map,this.excludedSteeringManifestURLs=new Set,this.logger_=l("Content Steering"),this.xhr_=e,this.getBandwidth_=t}assignTagProperties(e,t){this.manifestType_=t.serverUri?"HLS":"DASH";const i=t.serverUri||t.serverURL;if(!i)return this.logger_(`steering manifest URL is ${i}, cannot request steering manifest.`),void this.trigger("error");i.startsWith("data:")?this.decodeDataUriManifest_(i.substring(i.indexOf(",")+1)):(this.steeringManifest.reloadUri=d(e,i),this.defaultPathway=t.pathwayId||t.defaultServiceLocation,this.queryBeforeStart=t.queryBeforeStart,this.proxyServerUrl_=t.proxyServerURL,this.defaultPathway&&!this.queryBeforeStart&&this.trigger("content-steering"))}requestSteeringManifest(e){const t=this.steeringManifest.reloadUri;if(!t)return;const i=e?t:this.getRequestURI(t);if(!i)return this.logger_("No valid content steering manifest URIs. Stopping content steering."),this.trigger("error"),void this.dispose();const n={contentSteeringInfo:{uri:i}};this.trigger({type:"contentsteeringloadstart",metadata:n}),this.request_=this.xhr_({uri:i,requestType:"content-steering-manifest"},((e,t)=>{if(e){if(410===t.status)return this.logger_(`manifest request 410 ${e}.`),this.logger_(`There will be no more content steering requests to ${i} this session.`),void this.excludedSteeringManifestURLs.add(i);if(429===t.status){const i=t.responseHeaders["retry-after"];return this.logger_(`manifest request 429 ${e}.`),this.logger_(`content steering will retry in ${i} seconds.`),void this.startTTLTimeout_(parseInt(i,10))}return this.logger_(`manifest failed to load ${e}.`),void this.startTTLTimeout_()}let a;this.trigger({type:"contentsteeringloadcomplete",metadata:n});try{a=JSON.parse(this.request_.responseText)}catch(e){const t={errorType:s.default.Error.StreamingContentSteeringParserError,error:e};this.trigger({type:"error",metadata:t})}this.assignSteeringProperties_(a);const r={contentSteeringInfo:n.contentSteeringInfo,contentSteeringManifest:{version:this.steeringManifest.version,reloadUri:this.steeringManifest.reloadUri,priority:this.steeringManifest.priority}};this.trigger({type:"contentsteeringparsed",metadata:r}),this.startTTLTimeout_()}))}setProxyServerUrl_(e){const t=new window.URL(e),i=new window.URL(this.proxyServerUrl_);return i.searchParams.set("url",encodeURI(t.toString())),this.setSteeringParams_(i.toString())}decodeDataUriManifest_(e){const t=JSON.parse(window.atob(e));this.assignSteeringProperties_(t)}setSteeringParams_(e){const t=new window.URL(e),i=this.getPathway(),n=this.getBandwidth_();if(i){const e=`_${this.manifestType_}_pathway`;t.searchParams.set(e,i)}if(n){const e=`_${this.manifestType_}_throughput`;t.searchParams.set(e,n)}return t.toString()}assignSteeringProperties_(e){if(this.steeringManifest.version=e.VERSION,!this.steeringManifest.version)return this.logger_(`manifest version is ${e.VERSION}, which is not supported.`),void this.trigger("error");this.steeringManifest.ttl=e.TTL,this.steeringManifest.reloadUri=e["RELOAD-URI"],this.steeringManifest.priority=e["PATHWAY-PRIORITY"]||e["SERVICE-LOCATION-PRIORITY"],this.steeringManifest.pathwayClones=e["PATHWAY-CLONES"],this.nextPathwayClones=this.steeringManifest.pathwayClones,this.availablePathways_.size||(this.logger_("There are no available pathways for content steering. Ending content steering."),this.trigger("error"),this.dispose());const t=(e=>{for(const t of e)if(this.availablePathways_.has(t))return t;return[...this.availablePathways_][0]})(this.steeringManifest.priority);this.currentPathway!==t&&(this.currentPathway=t,this.trigger("content-steering"))}getPathway(){return this.currentPathway||this.defaultPathway}getRequestURI(e){if(!e)return null;const t=e=>this.excludedSteeringManifestURLs.has(e);if(this.proxyServerUrl_){const i=this.setProxyServerUrl_(e);if(!t(i))return i}const i=this.setSteeringParams_(e);return t(i)?null:i}startTTLTimeout_(e=this.steeringManifest.ttl){const t=1e3*e;this.ttlTimeout_=window.setTimeout((()=>{this.requestSteeringManifest()}),t)}clearTTLTimeout_(){window.clearTimeout(this.ttlTimeout_),this.ttlTimeout_=null}abort(){this.request_&&this.request_.abort(),this.request_=null}dispose(){this.off("content-steering"),this.off("error"),this.abort(),this.clearTTLTimeout_(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=null,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.excludedSteeringManifestURLs=new Set,this.availablePathways_=new Set,this.steeringManifest=new Zn}addAvailablePathway(e){e&&this.availablePathways_.add(e)}clearAvailablePathways(){this.availablePathways_.clear()}excludePathway(e){return this.availablePathways_.delete(e)}didDASHTagChange(e,t){return!t&&this.steeringManifest.reloadUri||t&&(d(e,t.serverURL)!==this.steeringManifest.reloadUri||t.defaultServiceLocation!==this.defaultPathway||t.queryBeforeStart!==this.queryBeforeStart||t.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}}let ts;const is=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],ns=function(e){return this.audioSegmentLoader_[e]+this.mainSegmentLoader_[e]};class ss extends s.default.EventTarget{constructor(e){super(),this.fastQualityChange_=((e,t)=>{let i=null;return(...t)=>{clearTimeout(i),i=setTimeout((()=>{e.apply(null,t)}),100)}})(this.fastQualityChange_.bind(this));const{src:t,withCredentials:i,tech:n,bandwidth:a,externVhs:r,useCueTags:o,playlistExclusionDuration:d,enableLowInitialPlaylist:u,sourceType:h,cacheEncryptionKeys:c,bufferBasedABR:p,leastPixelDiffSelector:m,captionServices:g,experimentalUseMMS:f}=e;if(!t)throw new Error("A non-empty playlist URL or JSON manifest string is required");let{maxPlaylistRetries:y}=e;null==y&&(y=1/0),ts=r,this.bufferBasedABR=Boolean(p),this.leastPixelDiffSelector=Boolean(m),this.withCredentials=i,this.tech_=n,this.vhs_=n.vhs,this.player_=e.player_,this.sourceType_=h,this.useCueTags_=o,this.playlistExclusionDuration=d,this.maxPlaylistRetries=y,this.enableLowInitialPlaylist=u,this.usingManagedMediaSource_=!1,this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack("metadata","ad-cues"),this.cueTagsTrack_.inBandMetadataTrackDispatchType=""),this.requestOptions_={withCredentials:i,maxPlaylistRetries:y,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:cn,activeTrack:cn,getActiveGroup:cn,onGroupChanged:cn,onTrackChanged:cn,lastTrack_:null,logger_:l(`MediaGroups[${t}]`)}})),e})(),f&&window.ManagedMediaSource?(this.tech_.el_.disableRemotePlayback=!0,this.mediaSource=new window.ManagedMediaSource,this.usingManagedMediaSource_=!0,s.default.log("Using ManagedMediaSource")):window.MediaSource&&(this.mediaSource=new window.MediaSource),this.handleDurationChange_=this.handleDurationChange_.bind(this),this.handleSourceOpen_=this.handleSourceOpen_.bind(this),this.handleSourceEnded_=this.handleSourceEnded_.bind(this),this.load=this.load.bind(this),this.pause=this.pause.bind(this),this.mediaSource.addEventListener("durationchange",this.handleDurationChange_),this.mediaSource.addEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.addEventListener("sourceended",this.handleSourceEnded_),this.mediaSource.addEventListener("startstreaming",this.load),this.mediaSource.addEventListener("endstreaming",this.pause),this.seekable_=O(),this.hasPlayed_=!1,this.syncController_=new $n(e),this.segmentMetadataTrack_=n.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.segmentMetadataTrack_.mode="hidden",this.decrypter_=new Wn,this.sourceUpdater_=new Ln(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new Vn,this.keyStatusMap_=new Map;const _={vhs:this.vhs_,parse708captions:e.parse708captions,useDtsForTimestampOffset:e.useDtsForTimestampOffset,captionServices:g,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:a,syncController:this.syncController_,decrypter:this.decrypter_,sourceType:this.sourceType_,inbandTextTracks:this.inbandTextTracks_,cacheEncryptionKeys:c,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:e.exactManifestTimings,addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)};this.mainPlaylistLoader_="dash"===this.sourceType_?new _i(t,this.vhs_,C(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new Ue(t,this.vhs_,C(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new hn(C(_,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),e),this.audioSegmentLoader_=new hn(C(_,{loaderType:"audio"}),e),this.subtitleSegmentLoader_=new kn(C(_,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise(((e,t)=>{function i(){n.off("vttjserror",s),e()}function s(){n.off("vttjsloaded",i),t()}n.one("vttjsloaded",i),n.one("vttjserror",s),n.addWebVttScript_()}))}),e),this.contentSteeringController_=new es(this.vhs_.xhr,(()=>this.mainSegmentLoader_.bandwidth)),this.setupSegmentLoaderListeners_(),this.bufferBasedABR&&(this.mainPlaylistLoader_.one("loadedplaylist",(()=>this.startABRTimer_())),this.tech_.on("pause",(()=>this.stopABRTimer_())),this.tech_.on("play",(()=>this.startABRTimer_()))),is.forEach((e=>{this[e+"_"]=ns.bind(this,e)})),this.logger_=l("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 T="none"===this.tech_.preload()?"play":"loadstart";this.tech_.one(T,(()=>{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_(e="abr"){const t=this.selectPlaylist();t&&this.shouldSwitchToMedia_(t)&&this.switchMedia_(t,e)}switchMedia_(e,t,i){const n=this.media(),s=n&&(n.id||n.uri),a=e&&(e.id||e.uri);if(s&&s!==a){this.logger_(`switch media ${s} -> ${a} from ${t}`);const i={renditionInfo:{id:a,bandwidth:e.attributes.BANDWIDTH,resolution:e.attributes.RESOLUTION,codecs:e.attributes.CODECS},cause:t};this.trigger({type:"renditionselected",metadata:i}),this.tech_.trigger({type:"usage",name:`vhs-rendition-change-${t}`})}this.mainPlaylistLoader_.media(e,i)}switchMediaForDASHContentSteering_(){["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((e=>{const t=this.mediaTypes_[e],i=t?t.activeGroup():null,n=this.contentSteeringController_.getPathway();if(i&&n){const t=(i.length?i[0].playlists:i.playlists).filter((e=>e.attributes.serviceLocation===n));t.length&&this.mediaTypes_[e].activePlaylistLoader.media(t[0])}}))}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 a=[];for(const t in i)if(i[t][s.label]){const n=i[t][s.label];if(n.playlists&&n.playlists.length)a.push.apply(a,n.playlists);else if(n.uri)a.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&&a.push(n)}}return a.length?a:t}setupMainPlaylistLoaderListeners_(){this.mainPlaylistLoader_.on("loadedmetadata",(()=>{const e=this.mainPlaylistLoader_.media(),t=1.5*e.targetDuration*1e3;ie(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=>{Qn[t](t,e)}));const{mediaTypes:t,mainPlaylistLoader:i,tech:n,vhs:s,segmentLoaders:{AUDIO:a,main:r}}=e;["AUDIO","SUBTITLES"].forEach((i=>{t[i].activeGroup=((e,t)=>i=>{const{mainPlaylistLoader:n,mediaTypes:{[e]:{groups:s}}}=t,a=n.media();if(!a)return null;let r=null;a.attributes[e]&&(r=s[a.attributes[e]]);const o=Object.keys(s);if(!r)if("AUDIO"===e&&o.length>1&&ae(t.main))for(let e=0;e<o.length;e++){const t=s[o[e]];if(Kn(t,a)){r=t;break}}else s.main?r=s.main:1===o.length&&(r=s[o[0]]);return void 0===i?r:null!==i&&r&&r.filter((e=>e.id===i.id))[0]||null})(i,e),t[i].activeTrack=Jn[i](i,e),t[i].onGroupChanged=((e,t)=>()=>{const{segmentLoaders:{[e]:i,main:n},mediaTypes:{[e]:s}}=t,a=s.activeTrack(),r=s.getActiveGroup(),o=s.activePlaylistLoader,d=s.lastGroup_;r&&d&&r.id===d.id||(s.lastGroup_=r,s.lastTrack_=a,Xn(i,s),r&&!r.isMainPlaylist&&(r.playlistLoader?(i.resyncLoader(),jn(r.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]:a}}=t,r=a.activeTrack(),o=a.getActiveGroup(),d=a.activePlaylistLoader,u=a.lastTrack_;if((!u||!r||u.id!==r.id)&&(a.lastGroup_=o,a.lastTrack_=r,Xn(n,a),o)){if(o.isMainPlaylist){if(!r||!u||r.id===u.id)return;const e=t.vhs.playlistController_,n=e.selectPlaylist();if(e.media()===n)return;return a.logger_(`track change. Switching main audio from ${u.id} to ${r.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(r),n.resetEverything(),jn(o.playlistLoader,a)):jn(o.playlistLoader,a)}})(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?(r.setAudio(!1),a.setAudio(!0)):r.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.attachContentSteeringListeners_(),this.initContentSteeringController_(),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;ie(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=t,"dash"===this.sourceType_&&this.mainPlaylistLoader_.isPaused&&this.mainPlaylistLoader_.load(),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_?this.runFastQualitySwitch_():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"})})),["manifestrequeststart","manifestrequestcomplete","manifestparsestart","manifestparsecomplete","playlistrequeststart","playlistrequestcomplete","playlistparsestart","playlistparsecomplete","renditiondisabled","renditionenabled"].forEach((e=>{this.mainPlaylistLoader_.on(e,(e=>{this.player_.trigger(a({},e))}))}))}handleUpdatedMediaPlaylist(e){this.useCueTags_&&this.updateAdCues_(e),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_&&this.runFastQualitySwitch_(),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"}),ts.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(),a=this.bufferHighWaterLine();return function({currentPlaylist:e,buffered:t,currentTime:i,nextPlaylist:n,bufferLowWaterLine:a,bufferHighWaterLine:r,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=V(t,i),p=d?Ti.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:Ti.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,g=e.attributes.BANDWIDTH;if(m<g&&(!d||c<r)){let e=`${l} as next bandwidth < current bandwidth (${m} < ${g})`;return d&&(e+=` and forwardBuffer < bufferHighWaterLine (${c} < ${r})`),u(e),!0}if((!d||m>g)&&c>=a){let e=`${l} as forwardBuffer >= bufferLowWaterLine (${c} >= ${a})`;return d&&(e+=` and next bandwidth > current bandwidth (${m} > ${g})`),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:a,duration:this.duration(),bufferBasedABR:this.bufferBasedABR,log:this.logger_})}setupSegmentLoaderListeners_(){this.mainSegmentLoader_.on("bandwidthupdate",(()=>{this.checkABR_("bandwidthupdate"),this.tech_.trigger("bandwidthupdate")})),this.mainSegmentLoader_.on("timeout",(()=>{this.bufferBasedABR&&this.mainSegmentLoader_.load()})),this.bufferBasedABR||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.timelineChangeController_.on("audioTimelineBehind",(()=>{const e=this.audioSegmentLoader_.pendingSegment_;if(!e||!e.segment||!e.segment.syncInfo)return;const t=e.segment.syncInfo.end+.01;this.tech_.setCurrentTime(t)})),this.timelineChangeController_.on("fixBadTimelineChange",(()=>{this.logger_("Fix bad timeline change. Restarting al segment loaders..."),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()})),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:10}))}));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()})),["segmentselected","segmentloadstart","segmentloaded","segmentkeyloadstart","segmentkeyloadcomplete","segmentdecryptionstart","segmentdecryptioncomplete","segmenttransmuxingstart","segmenttransmuxingcomplete","segmenttransmuxingtrackinfoavailable","segmenttransmuxingtiminginfoavailable","segmentappendstart","appendsdone","bandwidthupdated","timelinechange","codecschange"].forEach((e=>{this.mainSegmentLoader_.on(e,(e=>{this.player_.trigger(a({},e))})),this.audioSegmentLoader_.on(e,(e=>{this.player_.trigger(a({},e))})),this.subtitleSegmentLoader_.on(e,(e=>{this.player_.trigger(a({},e))}))}))}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()}pause(){this.mainSegmentLoader_.pause(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.pause(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.pause()}fastQualityChange_(e=this.selectPlaylist()){e&&e===this.mainPlaylistLoader_.media()?this.logger_("skipping fastQualityChange because new media is same as old"):(this.switchMedia_(e,"fast-quality"),this.waitingForFastQualityPlaylistReceived_=!0)}runFastQualitySwitch_(){this.waitingForFastQualityPlaylistReceived_=!1,this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}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||e.start){const t=this.seekable();if(!t.length)return!1;const i=t.end(0);let n=i;if(e.start){const s=e.start.timeOffset;n=s<0?Math.max(i+s,t.start(0)):Math.min(i,s)}this.trigger("firstplay"),this.tech_.setCurrentTime(n)}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=ts.Playlist.playlistEnd(e,t),n=this.tech_.currentTime(),s=this.tech_.buffered();if(!s.length)return i-n<=R;const a=s.end(s.length-1);return a-n<=R&&i-a<=R}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,a=n.filter(ee),r=1===a.length&&a[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(r);if(r){if(this.main().contentSteering){const t=this.pathwayAttribute_(e),i=1e3*this.contentSteeringController_.steeringManifest.ttl;return this.contentSteeringController_.excludePathway(t),this.excludeThenChangePathway_(),void setTimeout((()=>{this.contentSteeringController_.addAvailablePathway(t)}),i)}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",r||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_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),void this.load()):0}duration(){if(!this.mainPlaylistLoader_)return 0;const e=this.mainPlaylistLoader_.media();return e?e.endList?this.mediaSource?this.mediaSource.duration:ts.Playlist.duration(e):1/0:0}seekable(){return this.seekable_}getSeekableRange_(e,t){const i=e.media();if(!i)return null;const n=this.syncController_.getMediaSequenceSync(t);if(n&&n.isReliable){const e=n.start,t=n.end;if(!isFinite(e)||!isFinite(t))return null;const s=ts.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i);return O([[e,Math.max(e,t-s)]])}const s=this.syncController_.getExpiredTime(i,this.duration());if(null===s)return null;const a=ts.Playlist.seekable(i,s,ts.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i));return a.length?a:null}computeFinalSeekable_(e,t){if(!t)return e;const i=e.start(0),n=e.end(0),s=t.start(0),a=t.end(0);return s>n||i>a?e:O([[Math.max(i,s),Math.min(n,a)]])}onSyncInfoUpdate_(){if(!this.mainPlaylistLoader_)return;const e=this.getSeekableRange_(this.mainPlaylistLoader_,"main");if(!e)return;let t;if(this.mediaTypes_.AUDIO.activePlaylistLoader&&(t=this.getSeekableRange_(this.mediaTypes_.AUDIO.activePlaylistLoader,"audio"),!t))return;const i=this.seekable_;if(this.seekable_=this.computeFinalSeekable_(e,t),!this.seekable_)return;if(i&&i.length&&this.seekable_.length&&i.start(0)===this.seekable_.start(0)&&i.end(0)===this.seekable_.end(0))return;this.logger_(`seekable updated [${F(this.seekable_)}]`);const n={seekableRanges:this.seekable_};this.trigger({type:"seekablerangeschanged",metadata:n}),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=ts.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.contentSteeringController_.dispose(),this.keyStatusMap_.clear(),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_()||{}},t=this.mainSegmentLoader_.getPendingSegmentPlaylist()||this.media();e.video=e.main;const i=be(this.main(),t),n={},s=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(e.main.hasVideo&&(n.video=i.video||e.main.videoCodec||"avc1.4d400d"),e.main.isMuxed&&(n.video+=`,${i.audio||e.main.audioCodec||P}`),(e.main.hasAudio&&!e.main.isMuxed||e.audio.hasAudio||s)&&(n.audio=i.audio||e.main.audioCodec||e.audio.audioCodec||P,e.audio.isFmp4=e.main.hasAudio&&!e.main.isMuxed?e.main.isFmp4:e.audio.isFmp4),!n.audio&&!n.video)return void this.excludePlaylist({playlistToExclude:t,error:{message:"Could not determine codecs for playlist."},playlistExclusionDuration:1/0});const a=(e,t)=>e?U(t,this.usingManagedMediaSource_):L(t),r={};let o;if(["video","audio"].forEach((function(t){if(n.hasOwnProperty(t)&&!a(e[t].isFmp4,n[t])){const i=e[t].isFmp4?"browser":"muxer";r[i]=r[i]||[],r[i].push(n[t]),"audio"===t&&(o=i)}})),s&&o&&t.attributes.AUDIO){const e=t.attributes.AUDIO;this.main().playlists.forEach((i=>{(i.attributes&&i.attributes.AUDIO)===e&&i!==t&&(i.excludeUntil=1/0)})),this.logger_(`excluding audio group ${e} as ${o} does not support codec(s): "${n.audio}"`)}if(!Object.keys(r).length){if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){const e=[];if(["video","audio"].forEach((t=>{const i=(A(this.sourceUpdater_.codecs[t]||"")[0]||{}).type,s=(A(n[t]||"")[0]||{}).type;i&&s&&i.toLowerCase()!==s.toLowerCase()&&e.push(`"${this.sourceUpdater_.codecs[t]}" -> "${n[t]}"`)})),e.length)return void this.excludePlaylist({playlistToExclude:t,error:{message:`Codec switching not supported: ${e.join(", ")}.`,internal:!0},playlistExclusionDuration:1/0})}return n}{const e=Object.keys(r).reduce(((e,t)=>(e&&(e+=", "),e+`${t} does not support codec(s): "${r[t].join(",")}"`)),"")+".";this.excludePlaylist({playlistToExclude:t,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=be(this.main,n),a=[];!s.audio||L(s.audio)||U(s.audio,this.usingManagedMediaSource_)||a.push(`audio codec ${s.audio}`),!s.video||L(s.video)||U(s.video,this.usingManagedMediaSource_)||a.push(`video codec ${s.video}`),s.text&&"stpp.ttml.im1t"===s.text&&a.push(`text codec ${s.text}`),a.length&&(n.excludeUntil=1/0,this.logger_(`excluding ${n.id} for unsupported: ${a.join(", ")}`))}))}excludeIncompatibleVariants_(e){const t=[],i=this.main().playlists,n=_e(A(e)),s=Te(n),a=n.video&&A(n.video)[0]||null,r=n.audio&&A(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=be(this.mainPlaylistLoader_.main,n),u=Te(d);if(d.audio||d.video){if(u!==s&&o.push(`codec count "${u}" !== "${s}"`),!this.sourceUpdater_.canChangeType()){const e=d.video&&A(d.video)[0]||null,t=d.audio&&A(d.audio)[0]||null;e&&a&&e.type.toLowerCase()!==a.type.toLowerCase()&&o.push(`video codec "${e.type}" !== "${a.type}"`),t&&r&&t.type.toLowerCase()!==r.type.toLowerCase()&&o.push(`audio codec "${t.type}" !== "${r.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 a=e.segments[i];if(n||(n=Rn(t,s+a.duration/2)),n){if("cueIn"in a){n.endTime=s,n.adEndTime=s,s+=a.duration,n=null;continue}if(s<n.endTime){s+=a.duration;continue}n.endTime+=a.duration}else if("cueOut"in a&&(n=new window.VTTCue(s,s+a.duration,a.cueOut),n.adStartTime=s,n.adEndTime=s+parseFloat(a.cueOut),t.addCue(n)),"cueOutCont"in a){const[e,i]=a.cueOutCont.split("/").map(parseFloat);n=new window.VTTCue(s,s+a.duration,""),n.adStartTime=s-e,n.adEndTime=n.adStartTime+i,t.addCue(n)}s+=a.duration}}(e,this.cueTagsTrack_,t)}goalBufferLength(){const e=this.tech_.currentTime(),t=Ti.GOAL_BUFFER_LENGTH,i=Ti.GOAL_BUFFER_LENGTH_RATE,n=Math.max(t,Ti.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*i,n)}bufferLowWaterLine(){const e=this.tech_.currentTime(),t=Ti.BUFFER_LOW_WATER_LINE,i=Ti.BUFFER_LOW_WATER_LINE_RATE,n=Math.max(t,Ti.MAX_BUFFER_LOW_WATER_LINE),s=Math.max(t,Ti.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*i,this.bufferBasedABR?s:n)}bufferHighWaterLine(){return Ti.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(e){Ji(this.inbandTextTracks_,"com.apple.streaming",this.tech_),(({inbandTextTracks:e,dateRanges:t})=>{const i=e.metadataTrack_;if(!i)return;const n=window.WebKitDataCue||window.VTTCue;t.forEach((e=>{for(const t of Object.keys(e)){if(Ki.has(t))continue;const s=new n(e.startTime,e.endTime,"");s.id=e.id,s.type="com.apple.quicktime.HLS",s.value={key:Qi[t],data:e[t]},"scte35Out"!==t&&"scte35In"!==t||(s.value.data=new Uint8Array(s.value.data.match(/[\da-f]{2}/gi)).buffer),i.addCue(s)}e.processDateRange()}))})({inbandTextTracks:this.inbandTextTracks_,dateRanges:e})}addMetadataToTextTrack(e,t,i){const n=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();Ji(this.inbandTextTracks_,e,this.tech_),(({inbandTextTracks:e,metadataArray:t,timestampOffset:i,videoDuration:n})=>{if(!t)return;const a=window.WebKitDataCue||window.VTTCue,r=e.metadataTrack_;if(!r)return;if(t.forEach((e=>{const t=e.cueTime+i;!("number"!=typeof t||window.isNaN(t)||t<0)&&t<1/0&&e.frames&&e.frames.length&&e.frames.forEach((e=>{const i=new a(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),r.addCue(i)}))})),!r.cues||!r.cues.length)return;const o=r.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=isFinite(n)?n:e,a=Number(l[t+1])||s;i.forEach((e=>{e.endTime=a}))}))})({inbandTextTracks:this.inbandTextTracks_,metadataArray:t,timestampOffset:n,videoDuration:i})}pathwayAttribute_(e){return e.attributes["PATHWAY-ID"]||e.attributes.serviceLocation}initContentSteeringController_(){const e=this.main();if(e.contentSteering){for(const t of e.playlists)this.contentSteeringController_.addAvailablePathway(this.pathwayAttribute_(t));this.contentSteeringController_.assignTagProperties(e.uri,e.contentSteering),this.contentSteeringController_.queryBeforeStart?this.contentSteeringController_.requestSteeringManifest(!0):this.tech_.one("canplay",(()=>{this.contentSteeringController_.requestSteeringManifest()}))}}resetContentSteeringController_(){this.contentSteeringController_.clearAvailablePathways(),this.contentSteeringController_.dispose(),this.initContentSteeringController_()}attachContentSteeringListeners_(){this.contentSteeringController_.on("content-steering",this.excludeThenChangePathway_.bind(this)),["contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"].forEach((e=>{this.contentSteeringController_.on(e,(e=>{this.trigger(a({},e))}))})),"dash"===this.sourceType_&&this.mainPlaylistLoader_.on("loadedplaylist",(()=>{const e=this.main();(this.contentSteeringController_.didDASHTagChange(e.uri,e.contentSteering)||(()=>{const t=this.contentSteeringController_.getAvailablePathways(),i=[];for(const n of e.playlists){const e=n.attributes.serviceLocation;if(e&&(i.push(e),!t.has(e)))return!0}return!(i.length||!t.size)})())&&this.resetContentSteeringController_()}))}excludeThenChangePathway_(){const e=this.contentSteeringController_.getPathway();if(!e)return;this.handlePathwayClones_();const t=this.main().playlists,i=new Set;let n=!1;Object.keys(t).forEach((s=>{const a=t[s],r=this.pathwayAttribute_(a),o=r&&e!==r;a.excludeUntil===1/0&&"content-steering"===a.lastExcludeReason_&&!o&&(delete a.excludeUntil,delete a.lastExcludeReason_,n=!0);const d=!a.excludeUntil&&a.excludeUntil!==1/0;!i.has(a.id)&&o&&d&&(i.add(a.id),a.excludeUntil=1/0,a.lastExcludeReason_="content-steering",this.logger_(`excluding ${a.id} for ${a.lastExcludeReason_}`))})),"DASH"===this.contentSteeringController_.manifestType_&&Object.keys(this.mediaTypes_).forEach((t=>{const i=this.mediaTypes_[t];if(i.activePlaylistLoader){const t=i.activePlaylistLoader.media_;t&&t.attributes.serviceLocation!==e&&(n=!0)}})),n&&this.changeSegmentPathway_()}handlePathwayClones_(){const e=this.main().playlists,t=this.contentSteeringController_.currentPathwayClones,i=this.contentSteeringController_.nextPathwayClones;if(t&&t.size||i&&i.size){for(const[e,n]of t.entries())i.get(e)||(this.mainPlaylistLoader_.updateOrDeleteClone(n),this.contentSteeringController_.excludePathway(e));for(const[n,s]of i.entries()){const i=t.get(n);i?this.equalPathwayClones_(i,s)||(this.mainPlaylistLoader_.updateOrDeleteClone(s,!0),this.contentSteeringController_.addAvailablePathway(n)):(e.filter((e=>e.attributes["PATHWAY-ID"]===s["BASE-ID"])).forEach((e=>{this.mainPlaylistLoader_.addClonePathway(s,e)})),this.contentSteeringController_.addAvailablePathway(n))}this.contentSteeringController_.currentPathwayClones=new Map(JSON.parse(JSON.stringify([...i])))}}equalPathwayClones_(e,t){if(e["BASE-ID"]!==t["BASE-ID"]||e.ID!==t.ID||e["URI-REPLACEMENT"].HOST!==t["URI-REPLACEMENT"].HOST)return!1;const i=e["URI-REPLACEMENT"].PARAMS,n=t["URI-REPLACEMENT"].PARAMS;for(const e in i)if(i[e]!==n[e])return!1;for(const e in n)if(i[e]!==n[e])return!1;return!0}changeSegmentPathway_(){const e=this.selectPlaylist();this.pauseLoading(),"DASH"===this.contentSteeringController_.manifestType_&&this.switchMediaForDASHContentSteering_(),this.switchMedia_(e,"content-steering")}excludeNonUsablePlaylistsByKeyId_(){if(!this.mainPlaylistLoader_||!this.mainPlaylistLoader_.main)return;let e=0;const t="non-usable";this.mainPlaylistLoader_.main.playlists.forEach((i=>{const n=this.mainPlaylistLoader_.getKeyIdSet(i);n&&n.size&&n.forEach((n=>{const s=this.keyStatusMap_.has(n)&&"usable"===this.keyStatusMap_.get(n),a=i.lastExcludeReason_===t&&i.excludeUntil===1/0;s?s&&a&&(delete i.excludeUntil,delete i.lastExcludeReason_,this.logger_(`enabling playlist ${i.id} because key ID ${n} is usable`)):(i.excludeUntil!==1/0&&i.lastExcludeReason_!==t&&(i.excludeUntil=1/0,i.lastExcludeReason_=t,this.logger_(`excluding playlist ${i.id} because the key ID ${n} doesn't exist in the keyStatusMap or is not usable`)),e++)}))})),e>=this.mainPlaylistLoader_.main.playlists.length&&this.mainPlaylistLoader_.main.playlists.forEach((e=>{const i=e&&e.attributes&&e.attributes.RESOLUTION&&e.attributes.RESOLUTION.height<720,n=e.excludeUntil===1/0&&e.lastExcludeReason_===t;i&&n&&(delete e.excludeUntil,s.default.log.warn(`enabling non-HD playlist ${e.id} because all playlists were excluded due to non-usable key IDs`))}))}addKeyStatus_(e,t){const i=("string"==typeof e?e:(e=>{const t=new Uint8Array(e);return Array.from(t).map((e=>e.toString(16).padStart(2,"0"))).join("")})(e)).slice(0,32).toLowerCase();this.logger_(`KeyStatus '${t}' with key ID ${i} added to the keyStatusMap`),this.keyStatusMap_.set(i,t)}updatePlaylistByKeyStatus(e,t){this.addKeyStatus_(e,t),this.waitingForFastQualityPlaylistReceived_||this.excludeNonUsableThenChangePlaylist_(),this.mainPlaylistLoader_.off("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this)),this.mainPlaylistLoader_.on("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this))}excludeNonUsableThenChangePlaylist_(){this.excludeNonUsablePlaylistsByKeyId_(),this.fastQualityChange_()}}class as{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 a,r,o;this.codecs=be(n.main(),t),this.playlist=t,this.id=i,this.enabled=(a=e.playlists,r=t.id,o=s,e=>{const t=a.main.playlists[r],i=Z(t),n=ee(t);if(void 0===e)return n;e?delete t.disabled:t.disabled=!0;const s={renditionInfo:{id:r,bandwidth:t.attributes.BANDWIDTH,resolution:t.attributes.RESOLUTION,codecs:t.attributes.CODECS},cause:"fast-quality"};return e===n||i||(e?(o(t),a.trigger({type:"renditionenabled",metadata:s})):a.trigger({type:"renditiondisabled",metadata:s})),e})}}const rs=["seeking","seeked","pause","playing","error"];class os extends s.default.EventTarget{constructor(e){super(),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.playedRanges_=[],this.consecutiveUpdates=0,this.lastRecordedTime=null,this.checkCurrentTimeTimeout_=null,this.logger_=l("PlaybackWatcher"),this.logger_("initialize");const t=()=>this.monitorCurrentTime_(),i=()=>this.monitorCurrentTime_(),n=()=>this.techWaiting_(),s=()=>this.resetTimeUpdate_(),a=this.playlistController_,r=["main","subtitle","audio"],o={};r.forEach((e=>{o[e]={reset:()=>this.resetSegmentDownloads_(e),updateend:()=>this.checkSegmentDownloads_(e)},a[`${e}SegmentLoader_`].on("appendsdone",o[e].updateend),a[`${e}SegmentLoader_`].on("playlistupdate",o[e].reset),this.tech_.on(["seeked","seeking"],o[e].reset)}));const d=e=>{["main","audio"].forEach((t=>{a[`${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(rs,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(rs,s),this.tech_.off("canplay",i),this.tech_.off("play",t),this.tech_.off("seeking",this.watchForBadSeeking_),this.tech_.off("seeked",this.clearSeekingAppendCheck_),r.forEach((e=>{a[`${e}SegmentLoader_`].off("appendsdone",o[e].updateend),a[`${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);if(this[`${e}Buffered_`]=n,s){const i={bufferedRanges:n};return t.trigger({type:"bufferedrangeschanged",metadata:i}),void 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+R>=t.end(t.length-1)))return this.techWaiting_();if(this.consecutiveUpdates>=5&&e===this.lastRecordedTime)this.consecutiveUpdates++,this.waiting_();else if(e===this.lastRecordedTime)this.consecutiveUpdates++;else{this.playedRanges_.push(O([this.lastRecordedTime,e]));const t={playedRanges:this.playedRanges_};this.playlistController_.trigger({type:"playedrangeschanged",metadata:t}),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:R)}if(void 0!==i)return this.logger_(`Trying to seek outside of seekable at time ${t} with seekable range ${F(e)}. Seeking to ${i}.`),this.tech_.setCurrentTime(i),!0;const n=this.playlistController_.sourceUpdater_,s=this.tech_.buffered(),a=n.audioBuffer?n.audioBuffered():null,r=n.videoBuffer?n.videoBuffered():null,o=this.media(),d=o.partTargetDuration?o.partTargetDuration:2*(o.targetDuration-k),u=[a,r];for(let e=0;e<u.length;e++)if(u[e]&&V(u[e],t)<d)return!1;const l=B(s,t);return 0!==l.length&&(i=l.start(0)+R,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=B(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)+R;const a=!i.endList,r="number"==typeof i.partTargetDuration;return a&&(r||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),a=N(e,i),r=N(t,i);r.length&&!a.length&&s.length&&(n={start:s.end(0),end:r.end(0)})}else B(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=B(t,i);if(this.resetTimeUpdate_(),0===n.length||i!==e)return;this.logger_("skipTheGap_:","currentTime:",i,"scheduled currentTime:",e,"nextRange start:",n.start(0)),this.tech_.setCurrentTime(n.start(0)+k);const s={gapInfo:{from:i,to:n.start(0)}};this.playlistController_.trigger({type:"gapjumped",metadata:s}),this.tech_.trigger({type:"usage",name:"vhs-gap-skip"})}gapFromVideoUnderflow_(e,t){const i=function(e){if(e.length<2)return O();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 O(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 ds={errorInterval:30,getSource(e){return e(this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource())}},us=function(e,t){let i=0,n=0;const a=C(ds,t);e.ready((()=>{e.trigger({type:"usage",name:"vhs-error-reload-initialized"})}));const r=function(){n&&e.currentTime(n)},o=function(t){null!=t&&(n=e.duration()!==1/0&&e.currentTime()||0,e.one("loadedmetadata",r),e.src(t),e.trigger({type:"usage",name:"vhs-error-reload"}),e.play())},d=function(){if(Date.now()-i<1e3*a.errorInterval)e.trigger({type:"usage",name:"vhs-error-reload-canceled"});else{if(a.getSource&&"function"==typeof a.getSource)return i=Date.now(),a.getSource.call(e,o);s.default.log.error("ERROR: reloadSourceOnError - The option getSource must be a function!")}},u=function(){e.off("loadedmetadata",r),e.off("error",d),e.off("dispose",u)};e.on("error",d),e.on("dispose",u),e.reloadSourceOnError=function(t){u(),us(e,t)}};var ls="3.17.0";const hs={PlaylistLoader:Ue,Playlist:re,utils:Je,STANDARD_PLAYLIST_SELECTOR:zi,INITIAL_PLAYLIST_SELECTOR:function(){const e=this.playlists.main.playlists.filter(re.isEnabled);return Hi(e,((e,t)=>Xi(e,t))),e.filter((e=>!!be(this.playlists.main,e).video))[0]||null},lastBandwidthSelector:zi,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(){let n=this.useDevicePixelRatio&&window.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(n=this.customPixelRatio),t<0&&(t=this.systemBandwidth,i=this.systemBandwidth),this.systemBandwidth>0&&this.systemBandwidth!==i&&(t=e*this.systemBandwidth+(1-e)*t,i=this.systemBandwidth),ji({main:this.playlists.main,bandwidth:t,playerWidth:parseInt(Wi(this.tech_.el(),"width"),10)*n,playerHeight:parseInt(Wi(this.tech_.el(),"height"),10)*n,playerObjectFit:this.usePlayerObjectFit?Wi(this.tech_.el(),"objectFit"):"",limitRenditionByPlayerDimensions:this.limitRenditionByPlayerDimensions,playlistController:this.playlistController_})}},comparePlaylistBandwidth:Xi,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:Pe()};Object.keys(Ti).forEach((e=>{Object.defineProperty(hs,e,{get:()=>(s.default.log.warn(`using Vhs.${e} is UNSAFE be sure you know what you are doing`),Ti[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`):Ti[e]=t}})}));const cs="videojs-vhs",ps=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"})};hs.canPlaySource=function(){return s.default.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const ms=(e,t,i)=>{if(!e)return e;let n={};t&&t.attributes&&t.attributes.CODECS&&(n=_e(A(t.attributes.CODECS))),i&&i.attributes&&i.attributes.CODECS&&(n.audio=i.attributes.CODECS);const s=x(n.video),a=x(n.audio),r={};for(const i in e)r[i]={},a&&(r[i].audioContentType=a),s&&(r[i].videoContentType=s),t.contentProtection&&t.contentProtection[i]&&t.contentProtection[i].pssh&&(r[i].pssh=t.contentProtection[i].pssh),"string"==typeof e[i]&&(r[i].url=e[i]);return C(e,r)},gs=(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}),[]),fs=({player:e,sourceKeySystems:t,audioMedia:i,mainPlaylists:n})=>{if(!e.eme.initializeMediaKeys)return Promise.resolve();const s=i?n.concat([i]):n,a=gs(s,Object.keys(t)),r=[],o=[];return a.forEach((t=>{o.push(new Promise(((t,i)=>{e.tech_.one("keysessioncreated",t)}))),r.push(new Promise(((i,n)=>{e.eme.initializeMediaKeys({keySystems:t},(e=>{e?n(e):i()}))})))})),Promise.race([Promise.all(r),Promise.race(o)])},ys=({player:e,sourceKeySystems:t,media:i,audioMedia:n})=>{const a=ms(t,i,n);return!(!a||(e.currentSource().keySystems=a,a&&!e.eme&&(s.default.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),1)))},_s=()=>{if(!window.localStorage)return null;const e=window.localStorage.getItem(cs);if(!e)return null;try{return JSON.parse(e)}catch(e){return null}},Ts=e=>0===e.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")?JSON.parse(e.substring(e.indexOf(",")+1)):e,bs=(e,t)=>{e._requestCallbackSet||(e._requestCallbackSet=new Set),e._requestCallbackSet.add(t)},Ss=(e,t)=>{e._responseCallbackSet||(e._responseCallbackSet=new Set),e._responseCallbackSet.add(t)},vs=(e,t)=>{e._requestCallbackSet&&(e._requestCallbackSet.delete(t),e._requestCallbackSet.size||delete e._requestCallbackSet)},ws=(e,t)=>{e._responseCallbackSet&&(e._responseCallbackSet.delete(t),e._responseCallbackSet.size||delete e._responseCallbackSet)};hs.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))}))}(),hs.supportsNativeDash=!!(document&&document.createElement&&s.default.getTech("Html5").isSupported())&&/maybe|probably/i.test(document.createElement("video").canPlayType("application/dash+xml")),hs.supportsTypeNatively=e=>"hls"===e?hs.supportsNativeHls:"dash"===e&&hs.supportsNativeDash,hs.isSupported=function(){return s.default.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")},hs.xhr.onRequest=function(e){bs(hs.xhr,e)},hs.xhr.onResponse=function(e){Ss(hs.xhr,e)},hs.xhr.offRequest=function(e){vs(hs.xhr,e)},hs.xhr.offResponse=function(e){ws(hs.xhr,e)};const Is=s.default.getComponent("Component");class Es extends Is{constructor(e,t,i){if(super(t,i.vhs),"number"==typeof i.initialBandwidth&&(this.options_.bandwidth=i.initialBandwidth),this.logger_=l("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_(e={}){if(this.options_=C(this.options_,e),this.options_.withCredentials=this.options_.withCredentials||!1,this.options_.limitRenditionByPlayerDimensions=!1!==this.options_.limitRenditionByPlayerDimensions,this.options_.useDevicePixelRatio=this.options_.useDevicePixelRatio||!1,this.options_.usePlayerObjectFit=this.options_.usePlayerObjectFit||!1,this.options_.useBandwidthFromLocalStorage=void 0!==this.source_.useBandwidthFromLocalStorage?this.source_.useBandwidthFromLocalStorage:this.options_.useBandwidthFromLocalStorage||!1,this.options_.useForcedSubtitles=this.options_.useForcedSubtitles||!1,this.options_.useNetworkInformationApi=void 0===this.options_.useNetworkInformationApi||this.options_.useNetworkInformationApi,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=60),"number"!=typeof this.options_.bandwidth&&this.options_.useBandwidthFromLocalStorage){const e=_s();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=Ti.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===Ti.INITIAL_BANDWIDTH,["withCredentials","useDevicePixelRatio","usePlayerObjectFit","customPixelRatio","limitRenditionByPlayerDimensions","bandwidth","customTagParsers","customTagMappers","cacheEncryptionKeys","playlistSelector","initialPlaylistSelector","bufferBasedABR","liveRangeSafeTimeDelta","llhls","useForcedSubtitles","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,this.usePlayerObjectFit=this.options_.usePlayerObjectFit;const t=this.options_.customPixelRatio;"number"==typeof t&&t>=0&&(this.customPixelRatio=t)}setOptions(e={}){this.setOptions_(e)}src(e,t){if(!e)return;this.setOptions_(),this.options_.src=Ts(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=hs,this.options_.sourceType=Ne(t),this.options_.seekTo=e=>{this.tech_.setCurrentTime(e)},this.options_.player_=this.player_,this.playlistController_=new ss(this.options_);const i=C({liveRangeSafeTimeDelta:R},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new os(i),this.attachStreamingEventListeners_(),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?hs.movingAverageBandwidthSelector(.55):hs.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):n.bind(this),this.playlistController_.selectInitialPlaylist=hs.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=_s();t=t?C(t,e):e;try{window.localStorage.setItem(cs,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=>!Z(e))).map(((t,i)=>new as(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),(s.default.browser.IS_ANY_SAFARI||s.default.browser.IS_IOS)&&this.options_.overrideNative&&"hls"===this.options_.sourceType&&"function"==typeof this.tech_.addSourceElement?(this.tech_.addSourceElement(this.mediaSourceUrl_),this.tech_.addSourceElement(this.source_.src)):this.tech_.src(this.mediaSourceUrl_))}createKeySessions_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;this.logger_("waiting for EME key session creation"),fs({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=ys({player:this.player_,sourceKeySystems:this.source_.keySystems,media:this.playlists.media(),audioMedia:e&&e.media()});this.player_.tech_.on("keystatuschange",(e=>{this.playlistController_.updatePlaylistByKeyStatus(e.keyId,e.status)})),this.handleWaitingForKey_=this.handleWaitingForKey_.bind(this),this.player_.tech_.on("waitingforkey",this.handleWaitingForKey_),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)})),ps(e,t.playlists)})),this.playlists.on("mediachange",(()=>{ps(this.qualityLevels_,this.playlists)})))}static version(){return{"@videojs/http-streaming":ls,"mux.js":"7.1.0","mpd-parser":"1.3.1","m3u8-parser":"7.2.0","aes-decrypter":"4.0.2"}}version(){return this.constructor.version()}canChangeType(){return Ln.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},a=((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 a&&(s.programDateTime=a.toISOString()),i(null,s)})({playlist:this.playlistController_.media(),time:e,callback:t})}seekToProgramTime(e,t,i=!0,n=2){return Ze({programTime:e,playlist:this.playlistController_.media(),retryCount:n,pauseAfterSeek:i,seekTo:this.options_.seekTo,tech:this.options_.tech,callback:t})}setupXhrHooks_(){this.xhr.onRequest=e=>{bs(this.xhr,e)},this.xhr.onResponse=e=>{Ss(this.xhr,e)},this.xhr.offRequest=e=>{vs(this.xhr,e)},this.xhr.offResponse=e=>{ws(this.xhr,e)},this.player_.trigger("xhr-hooks-ready")}attachStreamingEventListeners_(){["seekablerangeschanged","bufferedrangeschanged","contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"].forEach((e=>{this.playlistController_.on(e,(e=>{this.player_.trigger(a({},e))}))})),["gapjumped","playedrangeschanged"].forEach((e=>{this.playbackWatcher_.on(e,(e=>{this.player_.trigger(a({},e))}))}))}}const As={name:"videojs-http-streaming",VERSION:ls,canHandleSource(e,t={}){const i=C(s.default.options,t);return!(!i.vhs.experimentalUseMMS&&!U("avc1.4d400d,mp4a.40.2",!1))&&As.canPlayType(e.type,i)},handleSource(e,t,i={}){const n=C(s.default.options,i);return t.vhs=new Es(e,t,n),t.vhs.xhr=Pe(),t.vhs.setupXhrHooks_(),t.vhs.src(e.src,e.type),t.vhs},canPlayType(e,t){const i=Ne(e);if(!i)return"";const n=As.getOverrideNative(t);return!hs.supportsTypeNatively(i)||n?"maybe":""},getOverrideNative(e={}){const{vhs:t={}}=e,i=!(s.default.browser.IS_ANY_SAFARI||s.default.browser.IS_IOS),{overrideNative:n=i}=t;return n}};U("avc1.4d400d,mp4a.40.2",!0)&&s.default.getTech("Html5").registerSourceHandler(As,0),s.default.VhsHandler=Es,s.default.VhsSourceHandler=As,s.default.Vhs=hs,s.default.use||s.default.registerComponent("Vhs",hs),s.default.options.vhs=s.default.options.vhs||{},s.default.getPlugin&&s.default.getPlugin("reloadSourceOnError")||s.default.registerPlugin("reloadSourceOnError",(function(e){us(this,e)})),e.LOCAL_STORAGE_KEY=cs,e.Vhs=hs,e.VhsHandler=Es,e.VhsSourceHandler=As,e.emeKeySystems=ms,e.expandDataUri=Ts,e.getAllPsshKeySystemsOptions=gs,e.setupEmeOptions=ys,e.simpleTypeFromSourceType=Ne,e.waitForKeySessionCreation=fs,Object.defineProperty(e,"__esModule",{value:!0})}));
|