UNPKG

338 kBJavaScriptView Raw
1/*! @name @videojs/http-streaming @version 3.10.0 @license Apache-2.0 */
2!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("video.js"),require("@xmldom/xmldom")):"function"==typeof define&&define.amd?define(["exports","video.js","@xmldom/xmldom"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).httpStreaming={},e.videojs,e.window)}(this,(function(e,t,i){"use strict";function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=s(t);function a(){return a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},a.apply(this,arguments)}var r={exports:{}};!function(e,t){!function(t){var i=/^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#[^]*)?$/,s=/^([^\/?#]*)([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,r={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var n=r.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=r.normalizePath(n.path),r.buildURLFromParts(n)}var a=r.parseURL(t);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return i.alwaysNormalize?(a.path=r.normalizePath(a.path),r.buildURLFromParts(a)):t;var o=r.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var d=s.exec(o.path);o.netLoc=d[1],o.path=d[2]}o.netLoc&&!o.path&&(o.path="/");var l={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(l.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var u=o.path,h=u.substring(0,u.lastIndexOf("/")+1)+a.path;l.path=r.normalizePath(h)}else l.path=o.path,a.params||(l.params=o.params,a.query||(l.query=o.query));return null===l.path&&(l.path=i.alwaysNormalize?r.normalizePath(a.path):a.path),r.buildURLFromParts(l)},parseURL:function(e){var t=i.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(n,"");e.length!==(e=e.replace(a,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=r}()}(r);var o=r.exports,d="http://example.com",l=function(e,t){if(/^[a-z]+:/i.test(t))return t;/^data:/.test(e)&&(e=window.location&&window.location.href||"");var i="function"==typeof window.URL,s=/^\/\//.test(e),n=!window.location&&!/\/\//i.test(e);if(i?e=new window.URL(e,window.location||d):/\/\//i.test(e)||(e=o.buildAbsoluteURL(window.location&&window.location.href||"",e)),i){var a=new URL(t,e);return n?a.href.slice(d.length):s?a.href.slice(a.protocol.length):a.href}return o.buildAbsoluteURL(e,t)};const u=l,h=(e,t)=>t&&t.responseURL&&e!==t.responseURL?t.responseURL:e,c=e=>n.default.log.debug?n.default.log.debug.bind(n.default,"VHS:",`${e} >`):function(){};var p=function(){function e(){this.listeners={}}var t=e.prototype;return t.on=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)},t.off=function(e,t){if(!this.listeners[e])return!1;var i=this.listeners[e].indexOf(t);return this.listeners[e]=this.listeners[e].slice(0),this.listeners[e].splice(i,1),i>-1},t.trigger=function(e){var t=this.listeners[e];if(t)if(2===arguments.length)for(var i=t.length,s=0;s<i;++s)t[s].call(this,arguments[1]);else for(var n=Array.prototype.slice.call(arguments,1),a=t.length,r=0;r<a;++r)t[r].apply(this,n)},t.dispose=function(){this.listeners={}},t.pipe=function(e){this.on("data",(function(t){e.push(t)}))},e}();function m(e){for(var t,i=(t=e,window.atob?window.atob(t):Buffer.from(t,"base64").toString("binary")),s=new Uint8Array(i.length),n=0;n<i.length;n++)s[n]=i.charCodeAt(n);return s}
3/*! @name m3u8-parser @version 7.1.0 @license Apache-2.0 */class g extends p{constructor(){super(),this.buffer=""}push(e){let t;for(this.buffer+=e,t=this.buffer.indexOf("\n");t>-1;t=this.buffer.indexOf("\n"))this.trigger("data",this.buffer.substring(0,t)),this.buffer=this.buffer.substring(t+1)}}const f=String.fromCharCode(9),y=function(e){const t=/([0-9.]*)?@?([0-9.]*)?/.exec(e||""),i={};return t[1]&&(i.length=parseInt(t[1],10)),t[2]&&(i.offset=parseInt(t[2],10)),i},_=function(e){const t={};if(!e)return t;const i=e.split(new RegExp('(?:^|,)((?:[^=]*)=(?:"[^"]*"|[^,]*))'));let s,n=i.length;for(;n--;)""!==i[n]&&(s=/([^=]*)=(.*)/.exec(i[n]).slice(1),s[0]=s[0].replace(/^\s+|\s+$/g,""),s[1]=s[1].replace(/^\s+|\s+$/g,""),s[1]=s[1].replace(/^['"](.*)['"]$/g,"$1"),t[s[0]]=s[1]);return t};class T extends p{constructor(){super(),this.customParsers=[],this.tagMappers=[]}push(e){let t,i;0!==(e=e.trim()).length&&("#"===e[0]?this.tagMappers.reduce(((t,i)=>{const s=i(e);return s===e?t:t.concat([s])}),[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(y(t[1]),{type:"tag",tagType:"byterange"}),void this.trigger("data",i);if(t=/^#EXT-X-ALLOW-CACHE:(YES|NO)?/.exec(e),t)return i={type:"tag",tagType:"allow-cache"},t[1]&&(i.allowed=!/NO/.test(t[1])),void this.trigger("data",i);if(t=/^#EXT-X-MAP:(.*)$/.exec(e),t){if(i={type:"tag",tagType:"map"},t[1]){const e=_(t[1]);e.URI&&(i.uri=e.URI),e.BYTERANGE&&(i.byterange=y(e.BYTERANGE))}this.trigger("data",i)}else if(t=/^#EXT-X-STREAM-INF:(.*)$/.exec(e),t){if(i={type:"tag",tagType:"stream-inf"},t[1]){if(i.attributes=_(t[1]),i.attributes.RESOLUTION){const e=i.attributes.RESOLUTION.split("x"),t={};e[0]&&(t.width=parseInt(e[0],10)),e[1]&&(t.height=parseInt(e[1],10)),i.attributes.RESOLUTION=t}i.attributes.BANDWIDTH&&(i.attributes.BANDWIDTH=parseInt(i.attributes.BANDWIDTH,10)),i.attributes["FRAME-RATE"]&&(i.attributes["FRAME-RATE"]=parseFloat(i.attributes["FRAME-RATE"])),i.attributes["PROGRAM-ID"]&&(i.attributes["PROGRAM-ID"]=parseInt(i.attributes["PROGRAM-ID"],10))}this.trigger("data",i)}else{if(t=/^#EXT-X-MEDIA:(.*)$/.exec(e),t)return i={type:"tag",tagType:"media"},t[1]&&(i.attributes=_(t[1])),void this.trigger("data",i);if(t=/^#EXT-X-ENDLIST/.exec(e),t)this.trigger("data",{type:"tag",tagType:"endlist"});else if(t=/^#EXT-X-DISCONTINUITY/.exec(e),t)this.trigger("data",{type:"tag",tagType:"discontinuity"});else{if(t=/^#EXT-X-PROGRAM-DATE-TIME:(.*)$/.exec(e),t)return i={type:"tag",tagType:"program-date-time"},t[1]&&(i.dateTimeString=t[1],i.dateTimeObject=new Date(t[1])),void this.trigger("data",i);if(t=/^#EXT-X-KEY:(.*)$/.exec(e),t)return i={type:"tag",tagType:"key"},t[1]&&(i.attributes=_(t[1]),i.attributes.IV&&("0x"===i.attributes.IV.substring(0,2).toLowerCase()&&(i.attributes.IV=i.attributes.IV.substring(2)),i.attributes.IV=i.attributes.IV.match(/.{8}/g),i.attributes.IV[0]=parseInt(i.attributes.IV[0],16),i.attributes.IV[1]=parseInt(i.attributes.IV[1],16),i.attributes.IV[2]=parseInt(i.attributes.IV[2],16),i.attributes.IV[3]=parseInt(i.attributes.IV[3],16),i.attributes.IV=new Uint32Array(i.attributes.IV))),void this.trigger("data",i);if(t=/^#EXT-X-START:(.*)$/.exec(e),t)return i={type:"tag",tagType:"start"},t[1]&&(i.attributes=_(t[1]),i.attributes["TIME-OFFSET"]=parseFloat(i.attributes["TIME-OFFSET"]),i.attributes.PRECISE=/YES/.test(i.attributes.PRECISE)),void this.trigger("data",i);if(t=/^#EXT-X-CUE-OUT-CONT:(.*)?$/.exec(e),t)return i={type:"tag",tagType:"cue-out-cont"},t[1]?i.data=t[1]:i.data="",void this.trigger("data",i);if(t=/^#EXT-X-CUE-OUT:(.*)?$/.exec(e),t)return i={type:"tag",tagType:"cue-out"},t[1]?i.data=t[1]:i.data="",void this.trigger("data",i);if(t=/^#EXT-X-CUE-IN:(.*)?$/.exec(e),t)return i={type:"tag",tagType:"cue-in"},t[1]?i.data=t[1]:i.data="",void this.trigger("data",i);if(t=/^#EXT-X-SKIP:(.*)$/.exec(e),t&&t[1])return i={type:"tag",tagType:"skip"},i.attributes=_(t[1]),i.attributes.hasOwnProperty("SKIPPED-SEGMENTS")&&(i.attributes["SKIPPED-SEGMENTS"]=parseInt(i.attributes["SKIPPED-SEGMENTS"],10)),i.attributes.hasOwnProperty("RECENTLY-REMOVED-DATERANGES")&&(i.attributes["RECENTLY-REMOVED-DATERANGES"]=i.attributes["RECENTLY-REMOVED-DATERANGES"].split(f)),void this.trigger("data",i);if(t=/^#EXT-X-PART:(.*)$/.exec(e),t&&t[1])return i={type:"tag",tagType:"part"},i.attributes=_(t[1]),["DURATION"].forEach((function(e){i.attributes.hasOwnProperty(e)&&(i.attributes[e]=parseFloat(i.attributes[e]))})),["INDEPENDENT","GAP"].forEach((function(e){i.attributes.hasOwnProperty(e)&&(i.attributes[e]=/YES/.test(i.attributes[e]))})),i.attributes.hasOwnProperty("BYTERANGE")&&(i.attributes.byterange=y(i.attributes.BYTERANGE)),void this.trigger("data",i);if(t=/^#EXT-X-SERVER-CONTROL:(.*)$/.exec(e),t&&t[1])return i={type:"tag",tagType:"server-control"},i.attributes=_(t[1]),["CAN-SKIP-UNTIL","PART-HOLD-BACK","HOLD-BACK"].forEach((function(e){i.attributes.hasOwnProperty(e)&&(i.attributes[e]=parseFloat(i.attributes[e]))})),["CAN-SKIP-DATERANGES","CAN-BLOCK-RELOAD"].forEach((function(e){i.attributes.hasOwnProperty(e)&&(i.attributes[e]=/YES/.test(i.attributes[e]))})),void this.trigger("data",i);if(t=/^#EXT-X-PART-INF:(.*)$/.exec(e),t&&t[1])return i={type:"tag",tagType:"part-inf"},i.attributes=_(t[1]),["PART-TARGET"].forEach((function(e){i.attributes.hasOwnProperty(e)&&(i.attributes[e]=parseFloat(i.attributes[e]))})),void this.trigger("data",i);if(t=/^#EXT-X-PRELOAD-HINT:(.*)$/.exec(e),t&&t[1])return i={type:"tag",tagType:"preload-hint"},i.attributes=_(t[1]),["BYTERANGE-START","BYTERANGE-LENGTH"].forEach((function(e){if(i.attributes.hasOwnProperty(e)){i.attributes[e]=parseInt(i.attributes[e],10);const t="BYTERANGE-LENGTH"===e?"length":"offset";i.attributes.byterange=i.attributes.byterange||{},i.attributes.byterange[t]=i.attributes[e],delete i.attributes[e]}})),void this.trigger("data",i);if(t=/^#EXT-X-RENDITION-REPORT:(.*)$/.exec(e),t&&t[1])return i={type:"tag",tagType:"rendition-report"},i.attributes=_(t[1]),["LAST-MSN","LAST-PART"].forEach((function(e){i.attributes.hasOwnProperty(e)&&(i.attributes[e]=parseInt(i.attributes[e],10))})),void this.trigger("data",i);if(t=/^#EXT-X-DATERANGE:(.*)$/.exec(e),t&&t[1]){i={type:"tag",tagType:"daterange"},i.attributes=_(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 s=/[0-9A-Fa-f]{6}/g.test(i.attributes[t]),n=/^\d+(\.\d+)?$/.test(i.attributes[t]);i.attributes[t]=s?i.attributes[t].toString(16):n?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-CONTENT-STEERING:(.*)$/.exec(e),t)return i={type:"tag",tagType:"content-steering"},i.attributes=_(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:s}){"function"!=typeof i&&(i=e=>e),this.customParsers.push((n=>{if(e.exec(n))return this.trigger("data",{type:"custom",data:i(n),customType:t,segment:s}),!0}))}addTagMapper({expression:e,map:t}){this.tagMappers.push((i=>e.test(i)?t(i):i))}}const b=function(e){const t={};return Object.keys(e).forEach((function(i){var s;t[(s=i,s.toLowerCase().replace(/-(\w)/g,(e=>e[1].toUpperCase())))]=e[i]})),t},S=function(e){const{serverControl:t,targetDuration:i,partTargetDuration:s}=e;if(!t)return;const n="#EXT-X-SERVER-CONTROL",a="holdBack",r="partHoldBack",o=i&&3*i,d=s&&2*s;i&&!t.hasOwnProperty(a)&&(t[a]=o,this.trigger("info",{message:`${n} defaulting HOLD-BACK to targetDuration * 3 (${o}).`})),o&&t[a]<o&&(this.trigger("warn",{message:`${n} clamping HOLD-BACK (${t[a]}) to targetDuration * 3 (${o})`}),t[a]=o),s&&!t.hasOwnProperty(r)&&(t[r]=3*s,this.trigger("info",{message:`${n} defaulting PART-HOLD-BACK to partTargetDuration * 3 (${t[r]}).`})),s&&t[r]<d&&(this.trigger("warn",{message:`${n} clamping PART-HOLD-BACK (${t[r]}) to partTargetDuration * 2 (${d}).`}),t[r]=d)};class v extends p{constructor(){super(),this.lineStream=new g,this.parseStream=new T,this.lineStream.pipe(this.parseStream),this.lastProgramDateTime=null;const e=this,t=[];let i,s,n={},r=!1;const o=function(){},d={AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}};let l=0;this.manifest={allowCache:!0,discontinuityStarts:[],dateRanges:[],segments:[]};let u=0,h=0;const c={};this.on("end",(()=>{n.uri||!n.parts&&!n.preloadHints||(!n.map&&i&&(n.map=i),!n.key&&s&&(n.key=s),n.timeline||"number"!=typeof l||(n.timeline=l),this.manifest.preloadSegment=n)})),this.parseStream.on("data",(function(p){let g,f;({tag(){({version(){p.version&&(this.manifest.version=p.version)},"allow-cache"(){this.manifest.allowCache=p.allowed,"allowed"in p||(this.trigger("info",{message:"defaulting allowCache to YES"}),this.manifest.allowCache=!0)},byterange(){const e={};"length"in p&&(n.byterange=e,e.length=p.length,"offset"in p||(p.offset=u)),"offset"in p&&(n.byterange=e,e.offset=p.offset),u=e.offset+e.length},endlist(){this.manifest.endList=!0},inf(){"mediaSequence"in this.manifest||(this.manifest.mediaSequence=0,this.trigger("info",{message:"defaulting media sequence to zero"})),"discontinuitySequence"in this.manifest||(this.manifest.discontinuitySequence=0,this.trigger("info",{message:"defaulting discontinuity sequence to zero"})),p.title&&(n.title=p.title),p.duration>0&&(n.duration=p.duration),0===p.duration&&(n.duration=.01,this.trigger("info",{message:"updating zero segment duration to a small value"})),this.manifest.segments=t},key(){if(p.attributes)if("NONE"!==p.attributes.METHOD)if(p.attributes.URI){if("com.apple.streamingkeydelivery"===p.attributes.KEYFORMAT)return this.manifest.contentProtection=this.manifest.contentProtection||{},void(this.manifest.contentProtection["com.apple.fps.1_0"]={attributes:p.attributes});if("com.microsoft.playready"===p.attributes.KEYFORMAT)return this.manifest.contentProtection=this.manifest.contentProtection||{},void(this.manifest.contentProtection["com.microsoft.playready"]={uri:p.attributes.URI});if("urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"===p.attributes.KEYFORMAT)return-1===["SAMPLE-AES","SAMPLE-AES-CTR","SAMPLE-AES-CENC"].indexOf(p.attributes.METHOD)?void this.trigger("warn",{message:"invalid key method provided for Widevine"}):("SAMPLE-AES-CENC"===p.attributes.METHOD&&this.trigger("warn",{message:"SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead"}),"data:text/plain;base64,"!==p.attributes.URI.substring(0,23)?void this.trigger("warn",{message:"invalid key URI provided for Widevine"}):p.attributes.KEYID&&"0x"===p.attributes.KEYID.substring(0,2)?(this.manifest.contentProtection=this.manifest.contentProtection||{},void(this.manifest.contentProtection["com.widevine.alpha"]={attributes:{schemeIdUri:p.attributes.KEYFORMAT,keyId:p.attributes.KEYID.substring(2)},pssh:m(p.attributes.URI.split(",")[1])})):void this.trigger("warn",{message:"invalid key ID provided for Widevine"}));p.attributes.METHOD||this.trigger("warn",{message:"defaulting key method to AES-128"}),s={method:p.attributes.METHOD||"AES-128",uri:p.attributes.URI},void 0!==p.attributes.IV&&(s.iv=p.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(p.number)?this.manifest.mediaSequence=p.number:this.trigger("warn",{message:"ignoring invalid media sequence: "+p.number})},"discontinuity-sequence"(){isFinite(p.number)?(this.manifest.discontinuitySequence=p.number,l=p.number):this.trigger("warn",{message:"ignoring invalid discontinuity sequence: "+p.number})},"playlist-type"(){/VOD|EVENT/.test(p.playlistType)?this.manifest.playlistType=p.playlistType:this.trigger("warn",{message:"ignoring unknown playlist type: "+p.playlist})},map(){i={},p.uri&&(i.uri=p.uri),p.byterange&&(i.byterange=p.byterange),s&&(i.key=s)},"stream-inf"(){this.manifest.playlists=t,this.manifest.mediaGroups=this.manifest.mediaGroups||d,p.attributes?(n.attributes||(n.attributes={}),a(n.attributes,p.attributes)):this.trigger("warn",{message:"ignoring empty stream-inf attributes"})},media(){if(this.manifest.mediaGroups=this.manifest.mediaGroups||d,!(p.attributes&&p.attributes.TYPE&&p.attributes["GROUP-ID"]&&p.attributes.NAME))return void this.trigger("warn",{message:"ignoring incomplete or missing media group"});const e=this.manifest.mediaGroups[p.attributes.TYPE];e[p.attributes["GROUP-ID"]]=e[p.attributes["GROUP-ID"]]||{},g=e[p.attributes["GROUP-ID"]],f={default:/yes/i.test(p.attributes.DEFAULT)},f.default?f.autoselect=!0:f.autoselect=/yes/i.test(p.attributes.AUTOSELECT),p.attributes.LANGUAGE&&(f.language=p.attributes.LANGUAGE),p.attributes.URI&&(f.uri=p.attributes.URI),p.attributes["INSTREAM-ID"]&&(f.instreamId=p.attributes["INSTREAM-ID"]),p.attributes.CHARACTERISTICS&&(f.characteristics=p.attributes.CHARACTERISTICS),p.attributes.FORCED&&(f.forced=/yes/i.test(p.attributes.FORCED)),g[p.attributes.NAME]=f},discontinuity(){l+=1,n.discontinuity=!0,this.manifest.discontinuityStarts.push(t.length)},"program-date-time"(){void 0===this.manifest.dateTimeString&&(this.manifest.dateTimeString=p.dateTimeString,this.manifest.dateTimeObject=p.dateTimeObject),n.dateTimeString=p.dateTimeString,n.dateTimeObject=p.dateTimeObject;const{lastProgramDateTime:e}=this;this.lastProgramDateTime=new Date(p.dateTimeString).getTime(),null===e&&this.manifest.segments.reduceRight(((e,t)=>(t.programDateTime=e-1e3*t.duration,t.programDateTime)),this.lastProgramDateTime)},targetduration(){!isFinite(p.duration)||p.duration<0?this.trigger("warn",{message:"ignoring invalid target duration: "+p.duration}):(this.manifest.targetDuration=p.duration,S.call(this,this.manifest))},start(){p.attributes&&!isNaN(p.attributes["TIME-OFFSET"])?this.manifest.start={timeOffset:p.attributes["TIME-OFFSET"],precise:p.attributes.PRECISE}:this.trigger("warn",{message:"ignoring start declaration without appropriate attribute list"})},"cue-out"(){n.cueOut=p.data},"cue-out-cont"(){n.cueOutCont=p.data},"cue-in"(){n.cueIn=p.data},skip(){this.manifest.skip=b(p.attributes),this.warnOnMissingAttributes_("#EXT-X-SKIP",p.attributes,["SKIPPED-SEGMENTS"])},part(){r=!0;const e=this.manifest.segments.length,t=b(p.attributes);n.parts=n.parts||[],n.parts.push(t),t.byterange&&(t.byterange.hasOwnProperty("offset")||(t.byterange.offset=h),h=t.byterange.offset+t.byterange.length);const i=n.parts.length-1;this.warnOnMissingAttributes_(`#EXT-X-PART #${i} for segment #${e}`,p.attributes,["URI","DURATION"]),this.manifest.renditionReports&&this.manifest.renditionReports.forEach(((e,t)=>{e.hasOwnProperty("lastPart")||this.trigger("warn",{message:`#EXT-X-RENDITION-REPORT #${t} lacks required attribute(s): LAST-PART`})}))},"server-control"(){const e=this.manifest.serverControl=b(p.attributes);e.hasOwnProperty("canBlockReload")||(e.canBlockReload=!1,this.trigger("info",{message:"#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false"})),S.call(this,this.manifest),e.canSkipDateranges&&!e.hasOwnProperty("canSkipUntil")&&this.trigger("warn",{message:"#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set"})},"preload-hint"(){const e=this.manifest.segments.length,t=b(p.attributes),i=t.type&&"PART"===t.type;n.preloadHints=n.preloadHints||[],n.preloadHints.push(t),t.byterange&&(t.byterange.hasOwnProperty("offset")||(t.byterange.offset=i?h:0,i&&(h=t.byterange.offset+t.byterange.length)));const s=n.preloadHints.length-1;if(this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${s} for segment #${e}`,p.attributes,["TYPE","URI"]),t.type)for(let i=0;i<n.preloadHints.length-1;i++){const a=n.preloadHints[i];a.type&&a.type===t.type&&this.trigger("warn",{message:`#EXT-X-PRELOAD-HINT #${s} for segment #${e} has the same TYPE ${t.type} as preload hint #${i}`})}},"rendition-report"(){const e=b(p.attributes);this.manifest.renditionReports=this.manifest.renditionReports||[],this.manifest.renditionReports.push(e);const t=this.manifest.renditionReports.length-1,i=["LAST-MSN","URI"];r&&i.push("LAST-PART"),this.warnOnMissingAttributes_(`#EXT-X-RENDITION-REPORT #${t}`,p.attributes,i)},"part-inf"(){this.manifest.partInf=b(p.attributes),this.warnOnMissingAttributes_("#EXT-X-PART-INF",p.attributes,["PART-TARGET"]),this.manifest.partInf.partTarget&&(this.manifest.partTargetDuration=this.manifest.partInf.partTarget),S.call(this,this.manifest)},daterange(){this.manifest.dateRanges.push(b(p.attributes));const e=this.manifest.dateRanges.length-1;this.warnOnMissingAttributes_(`#EXT-X-DATERANGE #${e}`,p.attributes,["ID","START-DATE"]);const t=this.manifest.dateRanges[e];t.endDate&&t.startDate&&new Date(t.endDate)<new Date(t.startDate)&&this.trigger("warn",{message:"EXT-X-DATERANGE END-DATE must be equal to or later than the value of the START-DATE"}),t.duration&&t.duration<0&&this.trigger("warn",{message:"EXT-X-DATERANGE DURATION must not be negative"}),t.plannedDuration&&t.plannedDuration<0&&this.trigger("warn",{message:"EXT-X-DATERANGE PLANNED-DURATION must not be negative"});const i=!!t.endOnNext;if(i&&!t.class&&this.trigger("warn",{message:"EXT-X-DATERANGE with an END-ON-NEXT=YES attribute must have a CLASS attribute"}),i&&(t.duration||t.endDate)&&this.trigger("warn",{message:"EXT-X-DATERANGE with an END-ON-NEXT=YES attribute must not contain DURATION or END-DATE attributes"}),t.duration&&t.endDate){const i=t.startDate.getTime()+1e3*t.duration;this.manifest.dateRanges[e].endDate=new Date(i)}if(c[t.id]){for(const e in c[t.id])if(t[e]&&JSON.stringify(c[t.id][e])!==JSON.stringify(t[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===t.id));this.manifest.dateRanges[e]=a(this.manifest.dateRanges[e],t),c[t.id]=a(c[t.id],t),this.manifest.dateRanges.pop()}else c[t.id]=t},"independent-segments"(){this.manifest.independentSegments=!0},"content-steering"(){this.manifest.contentSteering=b(p.attributes),this.warnOnMissingAttributes_("#EXT-X-CONTENT-STEERING",p.attributes,["SERVER-URI"])}}[p.tagType]||o).call(e)},uri(){n.uri=p.uri,t.push(n),this.manifest.targetDuration&&!("duration"in n)&&(this.trigger("warn",{message:"defaulting segment duration to the target duration"}),n.duration=this.manifest.targetDuration),s&&(n.key=s),n.timeline=l,i&&(n.map=i),h=0,null!==this.lastProgramDateTime&&(n.programDateTime=this.lastProgramDateTime,this.lastProgramDateTime+=1e3*n.duration),n={}},comment(){},custom(){p.segment?(n.custom=n.custom||{},n.custom[p.customType]=p.data):(this.manifest.custom=this.manifest.custom||{},this.manifest.custom[p.customType]=p.data)}})[p.type].call(e)}))}warnOnMissingAttributes_(e,t,i){const s=[];i.forEach((function(e){t.hasOwnProperty(e)||s.push(e)})),s.length&&this.trigger("warn",{message:`${e} lacks required attribute(s): ${s.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 w={mp4:/^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,webm:/^(vp0?[89]|av0?1|opus|vorbis)/,ogg:/^(vp0?[89]|theora|flac|opus|vorbis)/,video:/^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,audio:/^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,text:/^(stpp.ttml.im1t)/,muxerVideo:/^(avc0?1)/,muxerAudio:/^(mp4a)/,muxerText:/a^/},I=["video","audio","text"],E=["Video","Audio","Text"],A=function(e){return e?e.replace(/avc1\.(\d+)\.(\d+)/i,(function(e,t,i){return"avc1."+("00"+Number(t).toString(16)).slice(-2)+"00"+("00"+Number(i).toString(16)).slice(-2)})):e},D=function(e){void 0===e&&(e="");var t=e.split(","),i=[];return t.forEach((function(e){var t;e=e.trim(),I.forEach((function(s){var n=w[s].exec(e.toLowerCase());if(n&&!(n.length<=1)){t=s;var a=e.substring(0,n[1].length),r=e.replace(a,"");i.push({type:a,details:r,mediaType:s})}})),t||i.push({type:e,details:"",mediaType:"unknown"})})),i},x=function(e){return void 0===e&&(e=""),w.audio.test(e.trim().toLowerCase())},L=function(e){if(e&&"string"==typeof e){var t,i=e.toLowerCase().split(",").map((function(e){return A(e.trim())})),s="video";1===i.length&&x(i[0])?s="audio":1===i.length&&(void 0===(t=i[0])&&(t=""),w.text.test(t.trim().toLowerCase()))&&(s="application");var n="mp4";return i.every((function(e){return w.mp4.test(e)}))?n="mp4":i.every((function(e){return w.webm.test(e)}))?n="webm":i.every((function(e){return w.ogg.test(e)}))&&(n="ogg"),s+"/"+n+';codecs="'+e+'"'}},P=function(e){return void 0===e&&(e=""),window.MediaSource&&window.MediaSource.isTypeSupported&&window.MediaSource.isTypeSupported(L(e))||!1},C=function(e){return void 0===e&&(e=""),e.toLowerCase().split(",").every((function(e){e=e.trim();for(var t=0;t<E.length;t++)if(w["muxer"+E[t]].test(e))return!0;return!1}))},k="mp4a.40.2";function U(...e){const t=n.default.obj||n.default;return(t.merge||t.mergeOptions).apply(t,e)}function O(...e){const t=n.default.time||n.default;return(t.createTimeRanges||t.createTimeRanges).apply(t,e)}const R=1/30,M=.1,N=function(e,t){const i=[];let s;if(e&&e.length)for(s=0;s<e.length;s++)t(e.start(s),e.end(s))&&i.push([e.start(s),e.end(s)]);return O(i)},B=function(e,t){return N(e,(function(e,i){return e-M<=t&&i+M>=t}))},F=function(e,t){return N(e,(function(e){return e-R>=t}))},q=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(", ")},$=e=>{const t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t},G=function(e){if(e&&e.length&&e.end)return e.end(e.length-1)},W=function(e,t){let i=0;if(!e||!e.length)return i;for(let s=0;s<e.length;s++){const n=e.start(s),a=e.end(s);t>a||(i+=t>n&&t<=a?a-t:a-n)}return i},V=(e,t)=>{if(!t.preload)return t.duration;let i=0;return(t.parts||[]).forEach((function(e){i+=e.duration})),(t.preloadHints||[]).forEach((function(t){"PART"===t.type&&(i+=e.partTargetDuration)})),i},H=e=>(e.segments||[]).reduce(((e,t,i)=>(t.parts?t.parts.forEach((function(s,n){e.push({duration:s.duration,segmentIndex:i,partIndex:n,part:s,segment:t})})):e.push({duration:t.duration,segmentIndex:i,partIndex:null,segment:t,part:null}),e)),[]),X=e=>{const t=e.segments&&e.segments.length&&e.segments[e.segments.length-1];return t&&t.parts||[]},j=({preloadSegment:e})=>{if(!e)return;const{parts:t,preloadHints:i}=e;let s=(i||[]).reduce(((e,t)=>e+("PART"===t.type?1:0)),0);return s+=t&&t.length?t.length:0,s},z=(e,t)=>{if(t.endList)return 0;if(e&&e.suggestedPresentationDelay)return e.suggestedPresentationDelay;const i=X(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},Y=function(e,t,i){if(void 0===t&&(t=e.mediaSequence+e.segments.length),t<e.mediaSequence)return 0;const s=function(e,t){let i=0,s=t-e.mediaSequence,n=e.segments[s];if(n){if(void 0!==n.start)return{result:n.start,precise:!0};if(void 0!==n.end)return{result:n.end-n.duration,precise:!0}}for(;s--;){if(n=e.segments[s],void 0!==n.end)return{result:i+n.end,precise:!0};if(i+=V(e,n),void 0!==n.start)return{result:i+n.start,precise:!0}}return{result:i,precise:!1}}(e,t);if(s.precise)return s.result;const n=function(e,t){let i,s=0,n=t-e.mediaSequence;for(;n<e.segments.length;n++){if(i=e.segments[n],void 0!==i.start)return{result:i.start-s,precise:!0};if(s+=V(e,i),void 0!==i.end)return{result:i.end-s,precise:!0}}return{result:-1,precise:!1}}(e,t);return n.precise?n.result:s.result+i},Q=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 Y(e,t,i)},K=function({defaultDuration:e,durationList:t,startIndex:i,endIndex:s}){let n=0;if(i>s&&([i,s]=[s,i]),i<0){for(let t=i;t<Math.min(0,s);t++)n+=e;i=0}for(let e=i;e<s;e++)n+=t[e].duration;return n},J=function(e,t,i,s){if(!e||!e.segments)return null;if(e.endList)return Q(e);if(null===t)return null;t=t||0;let n=Y(e,e.mediaSequence+e.segments.length,t);return i&&(n-=s="number"==typeof s?s:z(null,e)),Math.max(0,n)},Z=function(e){return e.excludeUntil&&e.excludeUntil>Date.now()},ee=function(e){return e.excludeUntil&&e.excludeUntil===1/0},te=function(e){const t=Z(e);return!e.disabled&&!t},ie=function(e,t){return t.attributes&&t.attributes[e]},se=(e,t)=>{if(1===e.playlists.length)return!0;const i=t.attributes.BANDWIDTH||Number.MAX_VALUE;return 0===e.playlists.filter((e=>!!te(e)&&(e.attributes.BANDWIDTH||0)<i)).length},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)),ae=function(e,t){const i=e&&e.mediaGroups&&e.mediaGroups.AUDIO||{};let s=!1;for(const e in i){for(const n in i[e])if(s=t(i[e][n]),s)break;if(s)break}return!!s},re=e=>{if(!e||!e.playlists||!e.playlists.length)return ae(e,(e=>e.playlists&&e.playlists.length||e.uri));for(let t=0;t<e.playlists.length;t++){const i=e.playlists[t],s=i.attributes&&i.attributes.CODECS;if((!s||!s.split(",").every((e=>x(e))))&&!ae(e,(e=>ne(i,e))))return!1}return!0};var oe={liveEdgeDelay:z,duration:Q,seekable:function(e,t,i){const s=t||0;let n=J(e,t,!0,i);return null===n?O():(n<s&&(n=s),O(s,n))},getMediaInfoForTime:function({playlist:e,currentTime:t,startingSegmentIndex:i,startingPartIndex:s,startTime:n,exactManifestTimings:a}){let r=t-n;const o=H(e);let d=0;for(let e=0;e<o.length;e++){const t=o[e];if(i===t.segmentIndex&&("number"!=typeof s||"number"!=typeof t.partIndex||s===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+R<=0)continue;return{partIndex:i.partIndex,segmentIndex:i.segmentIndex,startTime:n-K({defaultDuration:e.targetDuration,durationList:o,startIndex:d,endIndex:t})}}return{partIndex:o[0]&&o[0].partIndex||null,segmentIndex:o[0]&&o[0].segmentIndex||0,startTime:t}}if(d<0){for(let i=d;i<0;i++)if(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 s=i.duration>R&&r+R>=0;if(0!==r&&!s||t===o.length-1){if(a){if(r>0)continue}else if(r-R>=0)continue;return{partIndex:i.partIndex,segmentIndex:i.segmentIndex,startTime:n+K({defaultDuration:e.targetDuration,durationList:o,startIndex:d,endIndex:t})}}}return{segmentIndex:o[o.length-1].segmentIndex,partIndex:o[o.length-1].partIndex,startTime:t}},isEnabled:te,isDisabled:function(e){return e.disabled},isExcluded:Z,isIncompatible:ee,playlistEnd:J,isAes:function(e){for(let t=0;t<e.segments.length;t++)if(e.segments[t].key)return!0;return!1},hasAttribute:ie,estimateSegmentRequestTime:function(e,t,i,s=0){return ie("BANDWIDTH",i)?(e*i.attributes.BANDWIDTH-8*s)/t:NaN},isLowestEnabledRendition:se,isAudioOnly:re,playlistMatch:ne,segmentDurationWithParts:V};const{log:de}=n.default,le=(e,t)=>`${e}-${t}`,ue=(e,t,i)=>`placeholder-uri-${e}-${t}-${i}`,he=(e,t)=>{e.mediaGroups&&["AUDIO","SUBTITLES"].forEach((i=>{if(e.mediaGroups[i])for(const s in e.mediaGroups[i])for(const n in e.mediaGroups[i][s]){const a=e.mediaGroups[i][s][n];t(a,i,s,n)}}))},ce=({playlist:e,uri:t,id:i})=>{e.id=i,e.playlistErrors_=0,t&&(e.uri=t),e.attributes=e.attributes||{}},pe=(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 s=re(e);he(e,((t,n,r,o)=>{if(!t.playlists||!t.playlists.length){if(s&&"AUDIO"===n&&!t.uri)for(let t=0;t<e.playlists.length;t++){const i=e.playlists[t];if(i.attributes&&i.attributes.AUDIO&&i.attributes.AUDIO===r)return}t.playlists=[a({},t)]}t.playlists.forEach((function(t,s){const a=i(n,r,o,t),d=le(s,a);t.uri?t.resolvedUri=t.resolvedUri||u(e.uri,t.uri):(t.uri=0===s?a:d,t.resolvedUri=t.uri),t.id=t.id||d,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];ce({playlist:i,id:le(t,i.uri)}),i.resolvedUri=u(e.uri,i.uri),e.playlists[i.id]=i,e.playlists[i.uri]=i,i.attributes.BANDWIDTH||de.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.")}})(e),(e=>{he(e,(t=>{t.uri&&(t.resolvedUri=u(e.uri,t.uri))}))})(e)};class me{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,s)=>{if(!this.processedDateRanges_.has(s)&&(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{EventTarget:ge}=n.default,fe=(e,t)=>{if(!e)return t;const i=U(e,t);if(e.preloadHints&&!t.preloadHints&&delete i.preloadHints,e.parts&&!t.parts)delete i.parts;else if(e.parts&&t.parts)for(let s=0;s<t.parts.length;s++)e.parts&&e.parts[s]&&(i.parts[s]=U(e.parts[s],t.parts[s]));return!e.skipped&&t.skipped&&(i.skipped=!1),e.preload&&!t.preload&&(i.preload=!1),i},ye=(e,t)=>{!e.resolvedUri&&e.uri&&(e.resolvedUri=u(t,e.uri)),e.key&&!e.key.resolvedUri&&(e.key.resolvedUri=u(t,e.key.uri)),e.map&&!e.map.resolvedUri&&(e.map.resolvedUri=u(t,e.map.uri)),e.map&&e.map.key&&!e.map.key.resolvedUri&&(e.map.key.resolvedUri=u(t,e.map.key.uri)),e.parts&&e.parts.length&&e.parts.forEach((e=>{e.resolvedUri||(e.resolvedUri=u(t,e.uri))})),e.preloadHints&&e.preloadHints.length&&e.preloadHints.forEach((e=>{e.resolvedUri||(e.resolvedUri=u(t,e.uri))}))},_e=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},Te=(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,be=(e,t,i=Te)=>{const s=U(e,{}),n=s.playlists[t.id];if(!n)return null;if(i(n,t))return null;t.segments=_e(t);const a=U(n,t);if(a.preloadSegment&&!t.preloadSegment&&delete a.preloadSegment,n.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 s=e.slice(),n=t.slice();i=i||0;const a=[];let r;for(let e=0;e<n.length;e++){const t=s[e+i],o=n[e];t?(r=t.map||r,a.push(fe(t,o))):(r&&!o.map&&(o.map=r),a.push(o))}return a})(n.segments,t.segments,t.mediaSequence-n.mediaSequence)}a.segments.forEach((e=>{ye(e,a.resolvedUri)}));for(let e=0;e<s.playlists.length;e++)s.playlists[e].id===t.id&&(s.playlists[e]=a);return s.playlists[t.id]=a,s.playlists[t.uri]=a,he(e,((e,i,s,n)=>{if(e.playlists)for(let i=0;i<e.playlists.length;i++)t.id===e.playlists[i].id&&(e.playlists[i]=a)})),s},Se=(e,t)=>{const i=e.segments||[],s=i[i.length-1],n=s&&s.parts&&s.parts[s.parts.length-1],a=n&&n.duration||s&&s.duration;return t&&a?1e3*a:500*(e.partTargetDuration||e.targetDuration||10)};class ve extends ge{constructor(e,t,i={}){if(super(),!e)throw new Error("A non-empty playlist URL or object is required");this.logger_=c("PlaylistLoader");const{withCredentials:s=!1}=i;this.src=e,this.vhs_=t,this.withCredentials=s,this.addDateRangesToTextTrack_=i.addDateRangesToTextTrack;const n=t.options_;this.customTagParsers=n&&n.customTagParsers||[],this.customTagMappers=n&&n.customTagMappers||[],this.llhls=n&&n.llhls,this.dateRangesStorage_=new me,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=u(this.main.uri,e.uri);this.llhls&&(t=((e,t)=>{if(t.endList||!t.serverControl)return e;const i={};if(t.serverControl.canBlockReload){const{preloadSegment:e}=t;let s=t.mediaSequence+t.segments.length;if(e){const n=e.parts||[],a=j(t)-1;a>-1&&a!==n.length-1&&(i._HLS_part=a),(a>-1||n.length)&&s--}i._HLS_msn=s}if(t.serverControl&&t.serverControl.canSkipUntil&&(i._HLS_skip=t.serverControl.canSkipDateranges?"v2":"YES"),Object.keys(i).length){const t=new window.URL(e);["_HLS_skip","_HLS_msn","_HLS_part"].forEach((function(e){i.hasOwnProperty(e)&&t.searchParams.set(e,i[e])})),e=t.toString()}return e})(t,e)),this.state="HAVE_CURRENT_METADATA",this.request=this.vhs_.xhr({uri:t,withCredentials:this.withCredentials},((e,t)=>{if(this.request)return e?this.playlistRequestError(this.request,this.media(),"HAVE_METADATA"):void this.haveMetadata({playlistString:this.request.responseText,url:this.media().uri,id:this.media().id})}))}playlistRequestError(e,t,i){const{uri:s,id:n}=t;this.request=null,i&&(this.state=i),this.error={playlist:this.main.playlists[n],status:e.status,message:`HLS playlist request error at URL: ${s}.`,responseText:e.responseText,code:e.status>=500?4:2},this.trigger("error")}parseManifest_({url:e,manifestString:t}){return(({onwarn:e,oninfo:t,manifestString:i,customTagParsers:s=[],customTagMappers:n=[],llhls:a})=>{const r=new v;e&&r.on("warn",e),t&&r.on("info",t),s.forEach((e=>r.addParser(e))),n.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=X(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}`}),de.error("LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.")),o.partTargetDuration=t}return o})({onwarn:({message:t})=>this.logger_(`m3u8-parser warn for ${e}: ${t}`),oninfo:({message:t})=>this.logger_(`m3u8-parser info for ${e}: ${t}`),manifestString:t,customTagParsers:this.customTagParsers,customTagMappers:this.customTagMappers,llhls:this.llhls})}haveMetadata({playlistString:e,playlistObject:t,url:i,id:s}){this.request=null,this.state="HAVE_METADATA";const n=t||this.parseManifest_({url:i,manifestString:e});n.lastRequest=Date.now(),ce({playlist:n,uri:i,id:s});const a=be(this.main,n);this.targetDuration=n.partTargetDuration||n.targetDuration,this.pendingMedia_=null,a?(this.main=a,this.media_=this.main.playlists[s]):this.trigger("playlistunchanged"),this.updateMediaUpdateTimeout_(Se(this.media(),!!a)),this.trigger("loadedplaylist")}dispose(){this.trigger("dispose"),this.stopRequest(),window.clearTimeout(this.mediaUpdateTimeout),window.clearTimeout(this.finalRenditionTimeout),this.dateRangesStorage_=new me,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,s=!this.media_||e.id!==this.media_.id,n=this.main.playlists[e.id];if(n&&n.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(s&&(this.trigger("mediachanging"),"HAVE_MAIN_MANIFEST"===i?this.trigger("loadedmetadata"):this.trigger("mediachange")));if(this.updateMediaUpdateTimeout_(Se(e,!0)),s){if(this.state="SWITCHING_MEDIA",this.request){if(e.resolvedUri===this.request.url)return;this.request.onreadystatechange=null,this.request.abort(),this.request=null}this.media_&&this.trigger("mediachanging"),this.pendingMedia_=e,this.request=this.vhs_.xhr({uri:e.resolvedUri,withCredentials:this.withCredentials},((t,s)=>{if(this.request){if(e.lastRequest=Date.now(),e.resolvedUri=h(e.resolvedUri,s),t)return this.playlistRequestError(this.request,e,i);this.haveMetadata({playlistString:s.responseText,url:e.uri,id:e.id}),"HAVE_MAIN_MANIFEST"===i?this.trigger("loadedmetadata"):this.trigger("mediachange")}}))}}pause(){this.mediaUpdateTimeout&&(window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),this.stopRequest(),"HAVE_NOTHING"===this.state&&(this.started=!1),"SWITCHING_MEDIA"===this.state?this.media_?this.state="HAVE_METADATA":this.state="HAVE_MAIN_MANIFEST":"HAVE_CURRENT_METADATA"===this.state&&(this.state="HAVE_METADATA")}load(e){this.mediaUpdateTimeout&&(window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);const t=this.media();if(e){const e=t?(t.partTargetDuration||t.targetDuration)/2*1e3:5e3;this.mediaUpdateTimeout=window.setTimeout((()=>{this.mediaUpdateTimeout=null,this.load()}),e)}else this.started?t&&!t.endList?this.trigger("mediaupdatetimeout"):this.trigger("loadedplaylist"):this.start()}updateMediaUpdateTimeout_(e){this.mediaUpdateTimeout&&(window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),this.media()&&!this.media().endList&&(this.mediaUpdateTimeout=window.setTimeout((()=>{this.mediaUpdateTimeout=null,this.trigger("mediaupdatetimeout"),this.updateMediaUpdateTimeout_(e)}),e))}start(){if(this.started=!0,"object"==typeof this.src)return this.src.uri||(this.src.uri=window.location.href),this.src.resolvedUri=this.src.uri,void setTimeout((()=>{this.setupInitialPlaylist(this.src)}),0);this.request=this.vhs_.xhr({uri:this.src,withCredentials:this.withCredentials},((e,t)=>{if(!this.request)return;if(this.request=null,e)return this.error={status:t.status,message:`HLS playlist request error at URL: ${this.src}.`,responseText:t.responseText,code:2},"HAVE_NOTHING"===this.state&&(this.started=!1),this.trigger("error");this.src=h(this.src,t);const i=this.parseManifest_({manifestString:t.responseText,url:this.src});this.setupInitialPlaylist(i)}))}srcUri(){return"string"==typeof this.src?this.src:this.src.uri}setupInitialPlaylist(e){if(this.state="HAVE_MAIN_MANIFEST",e.playlists)return this.main=e,pe(this.main,this.srcUri()),e.playlists.forEach((e=>{e.segments=_e(e),e.segments.forEach((t=>{ye(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=le(0,t),s={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:window.location.href,resolvedUri:window.location.href,playlists:[{uri:t,id:i,resolvedUri:t,attributes:{}}]};return s.playlists[i]=s.playlists[0],s.playlists[t]=s.playlists[0],s})(0,t),this.haveMetadata({playlistObject:e,url:t,id:this.main.playlists[0].id}),this.trigger("loadedmetadata")}updateOrDeleteClone(e,t){const i=this.main,s=e.ID;let n=i.playlists.length;for(;n--;){const a=i.playlists[n];if(a.attributes["PATHWAY-ID"]===s){const r=a.resolvedUri,o=a.id;if(t){const t=this.createCloneURI_(a.resolvedUri,e),r=le(s,t),o=this.createCloneAttributes_(s,a.attributes),d=this.createClonePlaylist_(a,r,e,o);i.playlists[n]=d,i.playlists[r]=d,i.playlists[t]=d}else i.playlists.splice(n,1);delete i.playlists[o],delete i.playlists[r]}}this.updateOrDeleteCloneMedia(e,t)}updateOrDeleteCloneMedia(e,t){const i=this.main,s=e.ID;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((e=>{if(i.mediaGroups[e]&&i.mediaGroups[e][s])for(const t in i.mediaGroups[e])if(t===s){for(const s in i.mediaGroups[e][t])i.mediaGroups[e][t][s].playlists.forEach(((e,t)=>{const s=i.playlists[e.id],n=s.id,a=s.resolvedUri;delete i.playlists[n],delete i.playlists[a]}));delete i.mediaGroups[e][t]}})),t&&this.createClonedMediaGroups_(e)}addClonePathway(e,t={}){const i=this.main,s=i.playlists.length,n=this.createCloneURI_(t.resolvedUri,e),a=le(e.ID,n),r=this.createCloneAttributes_(e.ID,t.attributes),o=this.createClonePlaylist_(t,a,e,r);i.playlists[s]=o,i.playlists[a]=o,i.playlists[n]=o,this.createClonedMediaGroups_(e)}createClonedMediaGroups_(e){const t=e.ID,i=e["BASE-ID"],s=this.main;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((n=>{if(s.mediaGroups[n]&&!s.mediaGroups[n][t])for(const r in s.mediaGroups[n])if(r===i){s.mediaGroups[n][t]={};for(const i in s.mediaGroups[n][r]){const o=s.mediaGroups[n][r][i];s.mediaGroups[n][t][i]=a({},o);const d=s.mediaGroups[n][t][i],l=this.createCloneURI_(o.resolvedUri,e);d.resolvedUri=l,d.uri=l,d.playlists=[],o.playlists.forEach(((a,r)=>{const o=s.playlists[a.id],l=ue(n,t,i),u=le(t,l);if(o&&!s.playlists[u]){const t=this.createClonePlaylist_(o,u,e),i=t.resolvedUri;s.playlists[u]=t,s.playlists[i]=t}d.playlists[r]=this.createClonePlaylist_(a,u,e)}))}}}))}createClonePlaylist_(e,t,i,s){const n=this.createCloneURI_(e.resolvedUri,i),a={resolvedUri:n,uri:n,id:t};return e.segments&&(a.segments=[]),s&&(a.attributes=s),U(e,a)}createCloneURI_(e,t){const i=new URL(e);i.hostname=t["URI-REPLACEMENT"].HOST;const s=t["URI-REPLACEMENT"].PARAMS;for(const e of Object.keys(s))i.searchParams.set(e,s[e]);return i.href}createCloneAttributes_(e,t){const i={"PATHWAY-ID":e};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((s=>{t[s]&&(i[s]=e)})),i}getKeyIdSet(e){if(e.contentProtection){const t=new Set;for(const i in e.contentProtection){const s=e.contentProtection[i].attributes.keyId;s&&t.add(s.toLowerCase())}return t}}}const{xhr:we}=n.default,Ie=function(e,t,i,s){const n="arraybuffer"===e.responseType?e.response:e.responseText;!t&&n&&(e.responseTime=Date.now(),e.roundTripTime=e.responseTime-e.requestTime,e.bytesReceived=n.byteLength||n.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&&(n||e.responseText)))),s(t,e)},Ee=function(){const e=function e(t,i){t=U({timeout:45e3},t);const s=e.beforeRequest||n.default.Vhs.xhr.beforeRequest,a=e._requestCallbackSet||n.default.Vhs.xhr._requestCallbackSet||new Set,r=e._responseCallbackSet||n.default.Vhs.xhr._responseCallbackSet;s&&"function"==typeof s&&(n.default.log.warn("beforeRequest is deprecated, use onRequest instead."),a.add(s));const o=!0===n.default.Vhs.xhr.original?we:n.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(s);const l=o(d||t,(function(e,t){return((e,t,i,s)=>{e&&e.size&&e.forEach((e=>{e(t,i,s)}))})(r,l,e,t),Ie(l,e,t,i)})),u=l.abort;return l.abort=function(){return l.aborted=!0,u.apply(l,arguments)},l.uri=t.uri,l.requestTime=Date.now(),l};return e.original=!0,e},Ae=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 De,xe,Le=/^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i,Pe=/^application\/dash\+xml/i,Ce=function(e){return Le.test(e)?"hls":Pe.test(e)?"dash":"application/vnd.videojs.vhs+json"===e?"vhs-json":null},ke=function(e){return"function"===ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer},Ue=function(e){return e instanceof Uint8Array?e:(Array.isArray(e)||ke(e)||e instanceof ArrayBuffer||(e="number"!=typeof e||"number"==typeof e&&e!=e?0:[e]),new Uint8Array(e&&e.buffer||e,e&&e.byteOffset||0,e&&e.byteLength||0))},Oe=window.BigInt||Number,Re=[Oe("0x1"),Oe("0x100"),Oe("0x10000"),Oe("0x1000000"),Oe("0x100000000"),Oe("0x10000000000"),Oe("0x1000000000000"),Oe("0x100000000000000"),Oe("0x10000000000000000")];De=new Uint16Array([65484]),255===(xe=new Uint8Array(De.buffer,De.byteOffset,De.byteLength))[0]||xe[0];var Me=function(e,t){var i=void 0===t?{}:t,s=i.signed,n=void 0!==s&&s,a=i.le,r=void 0!==a&&a;e=Ue(e);var o=r?"reduce":"reduceRight",d=(e[o]?e[o]:Array.prototype[o]).call(e,(function(t,i,s){var n=r?s:Math.abs(s+1-e.length);return t+Oe(i)*Re[n]}),Oe(0));if(n){var l=Re[e.length]/Oe(2)-Oe(1);(d=Oe(d))>l&&(d-=l,d-=l,d-=Oe(2))}return Number(d)},Ne=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),s=0;s<e.length;s++)i[s]=e.charCodeAt(s);return i},Be=function(e,t,i){var s=void 0===i?{}:i,n=s.offset,a=void 0===n?0:n,r=s.mask,o=void 0===r?[]:r;e=Ue(e);var d=(t=Ue(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 Fe=function(e,t){return e.start(t)+"-"+e.end(t)},qe=function(e,t){const i=e.toString(16);return"00".substring(0,2-i.length)+i+(t%2?" ":"")},$e=function(e){return e>=32&&e<126?String.fromCharCode(e):"."},Ge=function(e){const t={};return Object.keys(e).forEach((i=>{const s=e[i];ke(s)?t[i]={bytes:s.buffer,byteOffset:s.byteOffset,byteLength:s.byteLength}:t[i]=s})),t},We=function(e){const t=e.byterange||{length:1/0,offset:0};return[t.length,t.offset,e.resolvedUri].join(",")},Ve=function(e){return e.resolvedUri},He=e=>{const t=Array.prototype.slice.call(e),i=16;let s,n,a="";for(let e=0;e<t.length/i;e++)s=t.slice(e*i,e*i+i).map(qe).join(""),n=t.slice(e*i,e*i+i).map($e).join(""),a+=s+" "+n+"\n";return a};var Xe=Object.freeze({__proto__:null,createTransferableMessage:Ge,initSegmentId:We,segmentKeyId:Ve,hexDump:He,tagDump:({bytes:e})=>He(e),textRanges:e=>{let t,i="";for(t=0;t<e.length;t++)i+=Fe(e,t)+" ";return i}});const je=({programTime:e,playlist:t,retryCount:i=2,seekTo:s,pauseAfterSeek:n=!0,tech:a,callback:r})=>{if(!r)throw new Error("seekToProgramTime: callback must be provided");if(void 0===e||!t||!s)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 s=t.segments[0];if(i<new Date(s.dateTimeObject))return null;for(let e=0;e<t.segments.length-1&&(s=t.segments[e],!(i<new Date(t.segments[e+1].dateTimeObject)));e++);const n=t.segments[t.segments.length-1],a=n.dateTimeObject,r=n.videoTimingInfo?(o=n.videoTimingInfo).transmuxedPresentationEnd-o.transmuxedPresentationStart-o.transmuxerPrependedSeconds:n.duration+.25*n.duration;var o;return i>new Date(a.getTime()+1e3*r)?null:(i>new Date(a)&&(s=n),{segment:s,estimatedStart:s.videoTimingInfo?s.videoTimingInfo.transmuxedPresentationStart:oe.duration(t,t.mediaSequence+t.segments.indexOf(s)),type:s.videoTimingInfo?"accurate":"estimate"})})(e,t);if(!o)return r({message:`${e} was not found in the stream`});const d=o.segment,l=((e,t)=>{let i,s;try{i=new Date(e),s=new Date(t)}catch(e){}const n=i.getTime();return(s.getTime()-n)/1e3})(d.dateTimeObject,e);if("estimate"===o.type)return 0===i?r({message:`${e} is not buffered yet. Try again`}):(s(o.estimatedStart+l),void a.one("seeked",(()=>{je({programTime:e,playlist:t,retryCount:i-1,seekTo:s,pauseAfterSeek:n,tech:a,callback:r})})));const u=d.start+l;a.one("seeked",(()=>r(null,a.currentTime()))),n&&a.pause(),s(u)},ze=e=>!!e&&"object"==typeof e,Ye=(...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]):ze(e[i])&&ze(t[i])?e[i]=Ye(e[i],t[i]):e[i]=t[i]})),e)),{}),Qe=e=>Object.keys(e).map((t=>e[t])),Ke=e=>e.reduce(((e,t)=>e.concat(t)),[]),Je=e=>{if(!e.length)return[];const t=[];for(let i=0;i<e.length;i++)t.push(e[i]);return t};const Ze=({baseUrl:e="",source:t="",range:i="",indexRange:s=""})=>{const n={uri:t,resolvedUri:l(e||"",t)};if(i||s){const e=(i||s).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)),n.byterange={length:t,offset:a}}return n},et=e=>(e&&"number"!=typeof e&&(e=parseInt(e,10)),isNaN(e)?null:e),tt={static(e){const{duration:t,timescale:i=1,sourceDuration:s,periodDuration:n}=e,a=et(e.endNumber),r=t/i;return"number"==typeof a?{start:0,end:a}:"number"==typeof n?{start:0,end:n/r}:{start:0,end:s/r}},dynamic(e){const{NOW:t,clientOffset:i,availabilityStartTime:s,timescale:n=1,duration:a,periodStart:r=0,minimumUpdatePeriod:o=0,timeShiftBufferDepth:d=1/0}=e,l=et(e.endNumber),u=(t+i)/1e3,h=s+r,c=u+o-h,p=Math.ceil(c*n/a),m=Math.floor((u-h-d)*n/a),g=Math.floor((u-h)*n/a);return{start:Math.max(0,m),end:"number"==typeof l?l:Math.min(p,g)}}},it=e=>{const{type:t,duration:i,timescale:s=1,periodDuration:n,sourceDuration:a}=e,{start:r,end:o}=tt[t](e),d=((e,t)=>{const i=[];for(let s=e;s<t;s++)i.push(s);return i})(r,o).map((e=>t=>{const{duration:i,timescale:s=1,periodStart:n,startNumber:a=1}=e;return{number:a+t,duration:i/s,timeline:n,time:t*i}})(e));if("static"===t){const e=d.length-1,t="number"==typeof n?n:a;d[e].duration=t-i/s*e}return d},st=e=>{const{baseUrl:t,initialization:i={},sourceDuration:s,indexRange:n="",periodStart:a,presentationTime:r,number:o=0,duration:d}=e;if(!t)throw new Error("NO_BASE_URL");const l=Ze({baseUrl:t,source:i.sourceURL,range:i.range}),u=Ze({baseUrl:t,source:t,indexRange:n});if(u.map=l,d){const t=it(e);t.length&&(u.duration=t[0].duration,u.timeline=t[0].timeline)}else s&&(u.duration=s,u.timeline=a);return u.presentationTime=r||a,u.number=o,[u]},nt=(e,t,i)=>{const s=e.sidx.map?e.sidx.map:null,n=e.sidx.duration,a=e.timeline||0,r=e.sidx.byterange,o=r.offset+r.length,d=t.timescale,l=t.references.filter((e=>1!==e.referenceType)),u=[],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<l.length;e++){const r=t.references[e],o=r.referencedSize,l=r.subsegmentDuration;let f;f="bigint"==typeof p?p+window.BigInt(o)-window.BigInt(1):p+o-1;const y=st({baseUrl:i,timescale:d,timeline:a,periodStart:c,presentationTime:m,number:g,duration:l,sourceDuration:n,indexRange:`${p}-${f}`,type:h})[0];s&&(y.map=s),u.push(y),p+="bigint"==typeof p?window.BigInt(o):o,m+=l/d,g++}return e.segments=u,e},at=["AUDIO","SUBTITLES"],rt=e=>{return(t=e,i=({timeline:e})=>e,Qe(t.reduce(((e,t)=>(t.forEach((t=>{e[i(t)]=t})),e)),{}))).sort(((e,t)=>e.timeline>t.timeline?1:-1));var t,i},ot=e=>{let t=[];var i,s;return i=e,s=(e,i,s,n)=>{t=t.concat(e.playlists||[])},at.forEach((function(e){for(var t in i.mediaGroups[e])for(var n in i.mediaGroups[e][t]){var a=i.mediaGroups[e][t][n];s(a)}})),t},dt=({playlist:e,mediaSequence:t})=>{e.mediaSequence=t,e.segments.forEach(((t,i)=>{t.number=e.mediaSequence+i}))},lt=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),ut=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=Qe(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}))},ht=(e,t)=>{const i=lt(e.sidx),s=i&&t[i]&&t[i].sidx;return s&&nt(e,s,e.sidx.resolvedUri),e},ct=(e,t={})=>{if(!Object.keys(t).length)return e;for(const i in e)e[i]=ht(e[i],t);return e},pt=({attributes:e,segments:t,sidx:i,discontinuityStarts:s})=>{const n={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:s,timelineStarts:e.timelineStarts,segments:t};return e.frameRate&&(n.attributes["FRAME-RATE"]=e.frameRate),e.contentProtection&&(n.contentProtection=e.contentProtection),e.serviceLocation&&(n.attributes.serviceLocation=e.serviceLocation),i&&(n.sidx=i),n},mt=({attributes:e})=>"video/mp4"===e.mimeType||"video/webm"===e.mimeType||"video"===e.contentType,gt=({attributes:e})=>"audio/mp4"===e.mimeType||"audio/webm"===e.mimeType||"audio"===e.contentType,ft=({attributes:e})=>"text/vtt"===e.mimeType||"text"===e.contentType,yt=e=>e?Object.keys(e).reduce(((t,i)=>{const s=e[i];return t.concat(s.playlists)}),[]):[],_t=({dashPlaylists:e,locations:t,contentSteering:i,sidxMapping:s={},previousManifest:n,eventStream:a})=>{if(!e.length)return{};const{sourceDuration:r,type:o,suggestedPresentationDelay:d,minimumUpdatePeriod:l}=e[0].attributes,u=ut(e.filter(mt)).map(pt),h=ut(e.filter(gt)),c=ut(e.filter(ft)),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:ct(u,s)};l>=0&&(m.minimumUpdatePeriod=1e3*l),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 s;const n=e.reduce(((e,n)=>{const a=n.attributes.role&&n.attributes.role.value||"",r=n.attributes.lang||"";let o=n.attributes.label||"main";if(r&&!n.attributes.label){const e=a?` (${a})`:"";o=`${n.attributes.lang}${e}`}e[o]||(e[o]={language:r,autoselect:!0,default:"main"===a,playlists:[],uri:""});const d=ht((({attributes:e,segments:t,sidx:i,mediaSequence:s,discontinuitySequence:n,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:n,discontinuityStarts:a,timelineStarts:e.timelineStarts,mediaSequence:s,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})(n,i),t);return e[o].playlists.push(d),void 0===s&&"main"===a&&(s=n,s.default=!0),e}),{});return s||(n[Object.keys(n)[0]].default=!0),n})(h,s,g):null,y=c.length?((e,t={})=>e.reduce(((e,i)=>{const s=i.attributes.label||i.attributes.lang||"text";return e[s]||(e[s]={language:s,default:!1,autoselect:!1,playlists:[],uri:""}),e[s].playlists.push(ht((({attributes:e,segments:t,mediaSequence:i,discontinuityStarts:s,discontinuitySequence:n})=>{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:s,discontinuitySequence:n,mediaSequence:i,segments:t};return e.serviceLocation&&(r.attributes.serviceLocation=e.serviceLocation),r})(i),t)),e}),{}))(c,s):null,_=u.concat(yt(f),yt(y)),T=_.map((({timelineStarts:e})=>e));var b,S;return m.timelineStarts=rt(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:s}=t;e[s]={autoselect:!1,default:!1,instreamId:i,language:s},t.hasOwnProperty("aspectRatio")&&(e[s].aspectRatio=t.aspectRatio),t.hasOwnProperty("easyReader")&&(e[s].easyReader=t.easyReader),t.hasOwnProperty("3D")&&(e[s]["3D"]=t["3D"])})),e):e),{})),n?(({oldManifest:e,newManifest:t})=>{const i=e.playlists.concat(ot(e)),s=t.playlists.concat(ot(t));return t.timelineStarts=rt([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 s=((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(!s)return;if(t.sidx)return;const n=t.segments[0],a=s.segments.findIndex((function(e){return Math.abs(e.presentationTime-n.presentationTime)<.016666666666666666}));if(-1===a)return dt({playlist:t,mediaSequence:s.mediaSequence+s.segments.length}),t.segments[0].discontinuity=!0,t.discontinuityStarts.unshift(0),void((!s.segments.length&&t.timeline>s.timeline||s.segments.length&&t.timeline>s.segments[s.segments.length-1].timeline)&&t.discontinuitySequence--);s.segments[a].discontinuity&&!n.discontinuity&&(n.discontinuity=!0,t.discontinuityStarts.unshift(0),t.discontinuitySequence--),dt({playlist:t,mediaSequence:s.segments[a].number})}))})({oldPlaylists:i,newPlaylists:s,timelineStarts:t.timelineStarts}),t})({oldManifest:n,newManifest:m}):m},Tt=(e,t,i)=>{const{NOW:s,clientOffset:n,availabilityStartTime:a,timescale:r=1,periodStart:o=0,minimumUpdatePeriod:d=0}=e,l=(s+n)/1e3+d-(a+o);return Math.ceil((l*r-t)/i)},bt=(e,t)=>{const{type:i,minimumUpdatePeriod:s=0,media:n="",sourceDuration:a,timescale:r=1,startNumber:o=1,periodStart:d}=e,l=[];let u=-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(u<0&&(u=g),g&&g>u&&(u=g),m<0){const o=h+1;f=o===t.length?"dynamic"===i&&s>0&&n.indexOf("$Number$")>0?Tt(e,u,p):(a*r-u)/p:(t[o].t-u)/p}else f=m+1;const y=o+l.length+f;let _=o+l.length;for(;_<y;)l.push({number:_,duration:p/r,time:u,timeline:d}),u+=p,_++}return l},St=/\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g,vt=(e,t)=>e.replace(St,(e=>(t,i,s,n)=>{if("$$"===t)return"$";if(void 0===e[i])return t;const a=""+e[i];return"RepresentationID"===i?a:(n=s?parseInt(n,10):1,a.length>=n?a:`${new Array(n-a.length+1).join("0")}${a}`)})(t)),wt=(e,t)=>{const i={RepresentationID:e.id,Bandwidth:e.bandwidth||0},{initialization:s={sourceURL:"",range:""}}=e,n=Ze({baseUrl:e.baseUrl,source:vt(s.sourceURL,i),range:s.range}),a=((e,t)=>e.duration||t?e.duration?it(e):bt(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 s=vt(e.media||"",i),a=e.timescale||1,r=e.presentationTimeOffset||0,o=e.periodStart+(t.time-r)/a;return{uri:s,timeline:t.timeline,duration:t.duration,resolvedUri:l(e.baseUrl||"",s),map:n,number:t.number,presentationTime:o}}))},It=(e,t)=>{const{duration:i,segmentUrls:s=[],periodStart:n}=e;if(!i&&!t||i&&t)throw new Error("SEGMENT_TIME_UNSPECIFIED");const a=s.map((t=>((e,t)=>{const{baseUrl:i,initialization:s={}}=e,n=Ze({baseUrl:i,source:s.sourceURL,range:s.range}),a=Ze({baseUrl:i,source:t.media,range:t.mediaRange});return a.map=n,a})(e,t)));let r;return i&&(r=it(e)),t&&(r=bt(e,t)),r.map(((t,i)=>{if(a[i]){const s=a[i],r=e.timescale||1,o=e.presentationTimeOffset||0;return s.timeline=t.timeline,s.duration=t.duration,s.number=t.number,s.presentationTime=n+(t.time-o)/r,s}})).filter((e=>e))},Et=({attributes:e,segmentInfo:t})=>{let i,s;t.template?(s=wt,i=Ye(e,t.template)):t.base?(s=st,i=Ye(e,t.base)):t.list&&(s=It,i=Ye(e,t.list));const n={attributes:e};if(!s)return n;const a=s(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 n.attributes=i,n.segments=a,t.base&&i.indexRange&&(n.sidx=a[0],n.segments=[]),n},At=(e,t)=>Je(e.childNodes).filter((({tagName:e})=>e===t)),Dt=e=>e.textContent.trim(),xt=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,s,n,a,r,o]=t.slice(1);return 31536e3*parseFloat(i||0)+2592e3*parseFloat(s||0)+86400*parseFloat(n||0)+3600*parseFloat(a||0)+60*parseFloat(r||0)+parseFloat(o||0)},Lt={mediaPresentationDuration:e=>xt(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=>xt(e),suggestedPresentationDelay:e=>xt(e),type:e=>e,timeShiftBufferDepth:e=>xt(e),start:e=>xt(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)?xt(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},Pt=e=>e&&e.attributes?Je(e.attributes).reduce(((e,t)=>{const i=Lt[t.name]||Lt.DEFAULT;return e[t.name]=i(t.value),e}),{}):{},Ct={"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"},kt=(e,t)=>t.length?Ke(e.map((function(e){return t.map((function(t){const i=Dt(t),s=l(e.baseUrl,i),n=Ye(Pt(t),{baseUrl:s});return s!==i&&!n.serviceLocation&&e.serviceLocation&&(n.serviceLocation=e.serviceLocation),n}))}))):e,Ut=e=>{const t=At(e,"SegmentTemplate")[0],i=At(e,"SegmentList")[0],s=i&&At(i,"SegmentURL").map((e=>Ye({tag:"SegmentURL"},Pt(e)))),n=At(e,"SegmentBase")[0],a=i||t,r=a&&At(a,"SegmentTimeline")[0],o=i||n||t,d=o&&At(o,"Initialization")[0],l=t&&Pt(t);l&&d?l.initialization=d&&Pt(d):l&&l.initialization&&(l.initialization={sourceURL:l.initialization});const u={template:l,segmentTimeline:r&&At(r,"S").map((e=>Pt(e))),list:i&&Ye(Pt(i),{segmentUrls:s,initialization:Pt(d)}),base:n&&Ye(Pt(n),{initialization:Pt(d)})};return Object.keys(u).forEach((e=>{u[e]||delete u[e]})),u},Ot=e=>Ke(At(e.node,"EventStream").map((t=>{const i=Pt(t),s=i.schemeIdUri;return At(t,"Event").map((t=>{const n=Pt(t),a=n.presentationTime||0,r=i.timescale||1,o=n.duration||0,d=a/r+e.attributes.start;return{schemeIdUri:s,value:i.value,id:n.id,start:d,end:d+o/r,messageData:Dt(t)||n.messageData,contentEncoding:i.contentEncoding,presentationTimeOffset:i.presentationTimeOffset||0}}))}))),Rt=(e,t)=>(i,s)=>{const n=kt(t,At(i.node,"BaseURL")),a=Ye(e,{periodStart:i.attributes.start});"number"==typeof i.attributes.duration&&(a.periodDuration=i.attributes.duration);const r=At(i.node,"AdaptationSet"),o=Ut(i.node);return Ke(r.map(((e,t,i)=>s=>{const n=Pt(s),a=kt(t,At(s,"BaseURL")),r=At(s,"Role")[0],o={role:Pt(r)};let d=Ye(e,n,o);const l=At(s,"Accessibility")[0],u="urn:scte:dash:cc:cea-608:2015"===(h=Pt(l)).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,s=""]=e.split("=");t.channel=i,t.language=e,s.split(",").forEach((e=>{const[i,s]=e.split(":");"lang"===i?t.language=s:"er"===i?t.easyReader=Number(s):"war"===i?t.aspectRatio=Number(s):"3D"===i&&(t["3D"]=Number(s))}))}else t.language=e;return t.channel&&(t.channel="SERVICE"+t.channel),t})):void 0;var h;u&&(d=Ye(d,{captionServices:u}));const c=At(s,"Label")[0];if(c&&c.childNodes.length){const e=c.childNodes[0].nodeValue.trim();d=Ye(d,{label:e})}const p=At(s,"ContentProtection").reduce(((e,t)=>{const i=Pt(t);i.schemeIdUri&&(i.schemeIdUri=i.schemeIdUri.toLowerCase());const s=Ct[i.schemeIdUri];if(s){e[s]={attributes:i};const n=At(t,"cenc:pssh")[0];if(n){const t=Dt(n);e[s].pssh=t&&m(t)}}return e}),{});Object.keys(p).length&&(d=Ye(d,{contentProtection:p}));const g=Ut(s),f=At(s,"Representation"),y=Ye(i,g);return Ke(f.map(((e,t,i)=>s=>{const n=At(s,"BaseURL"),a=kt(t,n),r=Ye(e,Pt(s)),o=Ut(s);return a.map((e=>({segmentInfo:Ye(i,o),attributes:Ye(r,e)})))})(d,a,y)))})(a,n,o)))},Mt=(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=Ye({serverURL:Dt(e[0])},Pt(e[0]));return i.queryBeforeStart="true"===i.queryBeforeStart,i},Nt=e=>{if(""===e)throw new Error("DASH_EMPTY_MANIFEST");const t=new i.DOMParser;let s,n;try{s=t.parseFromString(e,"application/xml"),n=s&&"MPD"===s.documentElement.tagName?s.documentElement:null}catch(e){}if(!n||n&&n.getElementsByTagName("parsererror").length>0)throw new Error("DASH_INVALID_XML");return n};var Bt=Math.pow(2,32),Ft=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)*Bt+i.getUint32(4)},qt=Ue([73,68,51]),$t=function e(t,i){return void 0===i&&(i=0),(t=Ue(t)).length-i<10||!Be(t,qt,{offset:i})?i:(i+=function(e,t){void 0===t&&(t=0);var i=(e=Ue(e))[t+5],s=e[t+6]<<21|e[t+7]<<14|e[t+8]<<7|e[t+9];return(16&i)>>4?s+20:s+10}(t,i),e(t,i))},Gt=function(e){return"string"==typeof e?Ne(e):e},Wt=function e(t,i,s){void 0===s&&(s=!1),i=function(e){return Array.isArray(e)?e.map((function(e){return Gt(e)})):[Gt(e)]}(i),t=Ue(t);var n=[];if(!i.length)return n;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(s)break;d=t.length}var l=t.subarray(a+8,d);Be(o,i[0])&&(1===i.length?n.push(l):n.push.apply(n,e(l,i.slice(1),s))),a=d}return n},Vt={EBML:Ue([26,69,223,163]),DocType:Ue([66,130]),Segment:Ue([24,83,128,103]),SegmentInfo:Ue([21,73,169,102]),Tracks:Ue([22,84,174,107]),Track:Ue([174]),TrackNumber:Ue([215]),DefaultDuration:Ue([35,227,131]),TrackEntry:Ue([174]),TrackType:Ue([131]),FlagDefault:Ue([136]),CodecID:Ue([134]),CodecPrivate:Ue([99,162]),VideoTrack:Ue([224]),AudioTrack:Ue([225]),Cluster:Ue([31,67,182,117]),Timestamp:Ue([231]),TimestampScale:Ue([42,215,177]),BlockGroup:Ue([160]),BlockDuration:Ue([155]),Block:Ue([161]),SimpleBlock:Ue([163])},Ht=[128,64,32,16,8,4,2,1],Xt=function(e,t,i,s){void 0===i&&(i=!0),void 0===s&&(s=!1);var n=function(e){for(var t=1,i=0;i<Ht.length&&!(e&Ht[i]);i++)t++;return t}(e[t]),a=e.subarray(t,t+n);return i&&((a=Array.prototype.slice.call(e,t,t+n))[0]^=Ht[n-1]),{length:n,value:Me(a,{signed:s}),bytes:a}},jt=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,s=void 0!==i&&i;("bigint"!=typeof e&&"number"!=typeof e||"number"==typeof e&&e!=e)&&(e=0);for(var n,a=(n=e=Oe(e),Math.ceil(function(e){return e.toString(2).length}(n)/8)),r=new Uint8Array(new ArrayBuffer(a)),o=0;o<a;o++){var d=s?o:Math.abs(o+1-r.length);r[d]=Number(e/Re[o]&Oe(255)),e<0&&(r[d]=Math.abs(~r[d]),r[d]-=0===o?1:2)}return r}(t):t},zt=function e(t,i,s){if(s>=i.length)return i.length;var n=Xt(i,s,!1);if(Be(t.bytes,n.bytes))return s;var a=Xt(i,s+n.length);return e(t,i,s+a.length+a.value+n.length)},Yt=function e(t,i){i=function(e){return Array.isArray(e)?e.map((function(e){return jt(e)})):[jt(e)]}(i),t=Ue(t);var s=[];if(!i.length)return s;for(var n=0;n<t.length;){var a=Xt(t,n,!1),r=Xt(t,n+a.length),o=n+a.length+r.length;127===r.value&&(r.value=zt(a,t,o),r.value!==t.length&&(r.value-=o));var d=o+r.value>t.length?t.length:o+r.value,l=t.subarray(o,d);Be(i[0],a.bytes)&&(1===i.length?s.push(l):s=s.concat(e(l,i.slice(1)))),n+=a.length+r.length+l.length}return s},Qt=Ue([0,0,0,1]),Kt=Ue([0,0,1]),Jt=Ue([0,0,3]),Zt=function(e){for(var t=[],i=1;i<e.length-2;)Be(e.subarray(i,i+3),Jt)&&(t.push(i+2),i++),i++;if(0===t.length)return e;var s=e.length-t.length,n=new Uint8Array(s),a=0;for(i=0;i<s;a++,i++)a===t[0]&&(a++,t.shift()),n[i]=e[a];return n},ei=function(e,t,i,s){void 0===s&&(s=1/0),e=Ue(e),i=[].concat(i);for(var n,a=0,r=0;a<e.length&&(r<s||n);){var o=void 0;if(Be(e.subarray(a),Qt)?o=4:Be(e.subarray(a),Kt)&&(o=3),o){if(r++,n)return Zt(e.subarray(n,a));var d=void 0;"h264"===t?d=31&e[a+o]:"h265"===t&&(d=e[a+o]>>1&63),-1!==i.indexOf(d)&&(n=a+o),a+=o+("h264"===t?1:2)}else a++}return e.subarray(0,0)},ti={webm:Ue([119,101,98,109]),matroska:Ue([109,97,116,114,111,115,107,97]),flac:Ue([102,76,97,67]),ogg:Ue([79,103,103,83]),ac3:Ue([11,119]),riff:Ue([82,73,70,70]),avi:Ue([65,86,73]),wav:Ue([87,65,86,69]),"3gp":Ue([102,116,121,112,51,103]),mp4:Ue([102,116,121,112]),fmp4:Ue([115,116,121,112]),mov:Ue([102,116,121,112,113,116]),moov:Ue([109,111,111,118]),moof:Ue([109,111,111,102])},ii={aac:function(e){var t=$t(e);return Be(e,[255,16],{offset:t,mask:[255,22]})},mp3:function(e){var t=$t(e);return Be(e,[255,2],{offset:t,mask:[255,6]})},webm:function(e){var t=Yt(e,[Vt.EBML,Vt.DocType])[0];return Be(t,ti.webm)},mkv:function(e){var t=Yt(e,[Vt.EBML,Vt.DocType])[0];return Be(t,ti.matroska)},mp4:function(e){return!ii["3gp"](e)&&!ii.mov(e)&&(!(!Be(e,ti.mp4,{offset:4})&&!Be(e,ti.fmp4,{offset:4}))||!(!Be(e,ti.moof,{offset:4})&&!Be(e,ti.moov,{offset:4}))||void 0)},mov:function(e){return Be(e,ti.mov,{offset:4})},"3gp":function(e){return Be(e,ti["3gp"],{offset:4})},ac3:function(e){var t=$t(e);return Be(e,ti.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=$t(e);return Be(e,ti.flac,{offset:t})},ogg:function(e){return Be(e,ti.ogg)},avi:function(e){return Be(e,ti.riff)&&Be(e,ti.avi,{offset:8})},wav:function(e){return Be(e,ti.riff)&&Be(e,ti.wav,{offset:8})},h264:function(e){return function(e,t,i){return ei(e,"h264",7,3)}(e).length},h265:function(e){return function(e,t,i){return ei(e,"h265",[32,33],3)}(e).length}},si=Object.keys(ii).filter((function(e){return"ts"!==e&&"h264"!==e&&"h265"!==e})).concat(["ts","h264","h265"]);si.forEach((function(e){var t=ii[e];ii[e]=function(e){return t(Ue(e))}}));var ni=ii,ai=function(e){e=Ue(e);for(var t=0;t<si.length;t++){var i=si[t];if(ni[i](e))return i}return""};const ri=(e,t)=>{if(4===e.readyState)return t()},{EventTarget:oi}=n.default,di=function(e,t){if(!Te(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 s=e.segments[i],n=t.segments[i];if(s.uri!==n.uri)return!1;if(!s.byterange&&!n.byterange)continue;const a=s.byterange,r=n.byterange;if(a&&!r||!a&&r)return!1;if(a.offset!==r.offset||a.length!==r.length)return!1}return!0},li=(e,t,i,s)=>`placeholder-uri-${e}-${t}-${s.attributes.NAME||i}`,ui=(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,hi=(e,t)=>{const i={};for(const s in e){const n=e[s].sidx;if(n){const e=lt(n);if(!t[e])break;const s=t[e].sidxInfo;ui(s,n)&&(i[e]=t[e])}}return i};class ci extends oi{constructor(e,t,i={},s){super(),this.mainPlaylistLoader_=s||this,s||(this.isMain_=!0);const{withCredentials:n=!1}=i;if(this.vhs_=t,this.withCredentials=n,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_=c("DashPlaylistLoader"),this.isMain_?(this.mainPlaylistLoader_.srcUrl=e,this.mainPlaylistLoader_.sidxMapping_={}):this.childPlaylist_=e}requestErrored_(e,t,i){return!this.request||(this.request=null,e?(this.error="object"!=typeof e||e instanceof Error?{status:t.status,message:"DASH request error at URL: "+t.uri,response:t.response,code:2}:e,i&&(this.state=i),this.trigger("error"),!0):void 0)}addSidxSegments_(e,t,i){const s=e.sidx&&lt(e.sidx);if(!e.sidx||!s||this.mainPlaylistLoader_.sidxMapping_[s])return void(this.mediaRequest_=window.setTimeout((()=>i(!1)),0));const n=h(e.sidx.resolvedUri),a=(n,a)=>{if(this.requestErrored_(n,a,t))return;const r=this.mainPlaylistLoader_.sidxMapping_;let o;try{o=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),i={version:e[0],flags:new Uint8Array(e.subarray(1,4)),references:[],referenceId:t.getUint32(4),timescale:t.getUint32(8)},s=12;0===i.version?(i.earliestPresentationTime=t.getUint32(s),i.firstOffset=t.getUint32(s+4),s+=8):(i.earliestPresentationTime=Ft(e.subarray(s)),i.firstOffset=Ft(e.subarray(s+8)),s+=16),s+=2;var n=t.getUint16(s);for(s+=2;n>0;s+=12,n--)i.references.push({referenceType:(128&e[s])>>>7,referencedSize:2147483647&t.getUint32(s),subsegmentDuration:t.getUint32(s+4),startsWithSap:!!(128&e[s+8]),sapType:(112&e[s+8])>>>4,sapDeltaTime:268435455&t.getUint32(s+8)});return i}(Ue(a.response).subarray(8))}catch(e){return void this.requestErrored_(e,a,t)}return r[s]={sidxInfo:e.sidx,sidx:o},nt(e,o,e.sidx.resolvedUri),i(!0)};this.request=((e,t,i)=>{let s,n=[],a=!1;const r=function(e,t,s,n){return t.abort(),a=!0,i(e,t,s,n)},o=function(e,t){if(a)return;if(e)return r(e,t,"",n);const i=t.responseText.substring(n&&n.byteLength||0,t.responseText.length);if(n=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 Ue(t[0]);var s=t.reduce((function(e,t,i){return e+(t.byteLength||t.length)}),0),n=new Uint8Array(s),a=0;return t.forEach((function(e){e=Ue(e),n.set(e,a),a+=e.byteLength})),n}(n,Ne(i,!0)),s=s||$t(n),n.length<10||s&&n.length<s+2)return ri(t,(()=>r(e,t,"",n)));const o=ai(n);return"ts"===o&&n.length<188||!o&&n.length<376?ri(t,(()=>r(e,t,"",n))):r(null,t,o,n)},d={uri:e,beforeSend(e){e.overrideMimeType("text/plain; charset=x-user-defined"),e.addEventListener("progress",(function({total:t,loaded:i}){return Ie(e,null,{statusCode:e.status},o)}))}},l=t(d,(function(e,t){return Ie(l,e,t,o)}));return l})(n,this.vhs_.xhr,((t,i,s,r)=>{if(t)return a(t,i);if(!s||"mp4"!==s)return a({status:i.status,message:`Unsupported ${s||"unknown"} container type for sidx segment at URL: ${n}`,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:n,responseType:"arraybuffer",headers:Ae({byterange:e.sidx.byterange})},a)}))}dispose(){this.trigger("dispose"),this.stopRequest(),this.loadedPlaylists_={},window.clearTimeout(this.minimumUpdatePeriodTimeout_),window.clearTimeout(this.mediaRequest_),window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.mediaRequest_=null,this.minimumUpdatePeriodTimeout_=null,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.off()}hasPendingRequest(){return this.request||this.mediaRequest_}stopRequest(){if(this.request){const e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e){if(!e)return this.media_;if("HAVE_NOTHING"===this.state)throw new Error("Cannot switch media playlist from "+this.state);const t=this.state;if("string"==typeof e){if(!this.mainPlaylistLoader_.main.playlists[e])throw new Error("Unknown playlist URI: "+e);e=this.mainPlaylistLoader_.main.playlists[e]}const i=!this.media_||e.id!==this.media_.id;if(i&&this.loadedPlaylists_[e.id]&&this.loadedPlaylists_[e.id].endList)return this.state="HAVE_METADATA",this.media_=e,void(i&&(this.trigger("mediachanging"),this.trigger("mediachange")));i&&(this.media_&&this.trigger("mediachanging"),this.addSidxSegments_(e,t,(i=>{this.haveMetadata({startingState:t,playlist:e})})))}haveMetadata({startingState:e,playlist:t}){this.state="HAVE_METADATA",this.loadedPlaylists_[t.id]=t,this.mediaRequest_=null,this.refreshMedia_(t.id),"HAVE_MAIN_MANIFEST"===e?this.trigger("loadedmetadata"):this.trigger("mediachange")}pause(){this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.stopRequest(),window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.isMain_&&(window.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_),this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_=null),"HAVE_NOTHING"===this.state&&(this.started=!1)}load(e){window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null;const t=this.media();if(e){const e=t?t.targetDuration/2*1e3:5e3;this.mediaUpdateTimeout=window.setTimeout((()=>this.load()),e)}else this.started?t&&!t.endList?(this.isMain_&&!this.minimumUpdatePeriodTimeout_&&(this.trigger("minimumUpdatePeriod"),this.updateMinimumUpdatePeriodTimeout_()),this.trigger("mediaupdatetimeout")):this.trigger("loadedplaylist"):this.start()}start(){this.started=!0,this.isMain_?this.requestMain_(((e,t)=>{this.haveMain_(),this.hasPendingRequest()||this.media_||this.media(this.mainPlaylistLoader_.main.playlists[0])})):this.mediaRequest_=window.setTimeout((()=>this.haveMain_()),0)}requestMain_(e){this.request=this.vhs_.xhr({uri:this.mainPlaylistLoader_.srcUrl,withCredentials:this.withCredentials},((t,i)=>{if(this.requestErrored_(t,i))return void("HAVE_NOTHING"===this.state&&(this.started=!1));const s=i.responseText!==this.mainPlaylistLoader_.mainXml_;return this.mainPlaylistLoader_.mainXml_=i.responseText,i.responseHeaders&&i.responseHeaders.date?this.mainLoaded_=Date.parse(i.responseHeaders.date):this.mainLoaded_=Date.now(),this.mainPlaylistLoader_.srcUrl=h(this.mainPlaylistLoader_.srcUrl,i),s?(this.handleMain_(),void this.syncClientServerClock_((()=>e(i,s)))):e(i,s)}))}syncClientServerClock_(e){const t=(i=this.mainPlaylistLoader_.mainXml_,(e=>{const t=At(e,"UTCTiming")[0];if(!t)return null;const i=Pt(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})(Nt(i)));var i;return null===t?(this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e()):"DIRECT"===t.method?(this.mainPlaylistLoader_.clientOffset_=t.value-Date.now(),e()):void(this.request=this.vhs_.xhr({uri:u(this.mainPlaylistLoader_.srcUrl,t.value),method:t.method,withCredentials:this.withCredentials},((i,s)=>{if(!this.request)return;if(i)return this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e();let n;n="HEAD"===t.method?s.responseHeaders&&s.responseHeaders.date?Date.parse(s.responseHeaders.date):this.mainLoaded_:Date.parse(s.responseText),this.mainPlaylistLoader_.clientOffset_=n-Date.now(),e()})))}haveMain_(){this.state="HAVE_MAIN_MANIFEST",this.isMain_?this.trigger("loadedplaylist"):this.media_||this.media(this.childPlaylist_)}handleMain_(){this.mediaRequest_=null;const e=this.mainPlaylistLoader_.main;let t=(({mainXml:e,srcUrl:t,clientOffset:i,sidxMapping:s,previousManifest:n})=>{const a=((e,t={})=>{const i=((e,t={})=>{const{manifestUri:i="",NOW:s=Date.now(),clientOffset:n=0,eventHandler:a=function(){}}=t,r=At(e,"Period");if(!r.length)throw new Error("INVALID_NUMBER_OF_PERIOD");const o=At(e,"Location"),d=Pt(e),l=kt([{baseUrl:i}],At(e,"BaseURL")),u=At(e,"ContentSteering");d.type=d.type||"static",d.sourceDuration=d.mediaPresentationDuration||0,d.NOW=s,d.clientOffset=n,o.length&&(d.locations=o.map(Dt));const h=[];return r.forEach(((e,t)=>{const i=Pt(e),s=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:s?s.attributes:null,mpdType:d.type}),h.push({node:e,attributes:i})})),{locations:d.locations,contentSteeringInfo:Mt(u,a),representationInfo:Ke(h.map(Rt(d,l))),eventStream:Ke(h.map(Ot))}})(Nt(e),t),s=i.representationInfo.map(Et);return _t({dashPlaylists:s,locations:i.locations,contentSteering:i.contentSteeringInfo,sidxMapping:t.sidxMapping,previousManifest:t.previousManifest,eventStream:i.eventStream})})(e,{manifestUri:t,clientOffset:i,sidxMapping:s,previousManifest:n});return pe(a,t,li),a})({mainXml:this.mainPlaylistLoader_.mainXml_,srcUrl:this.mainPlaylistLoader_.srcUrl,clientOffset:this.mainPlaylistLoader_.clientOffset_,sidxMapping:this.mainPlaylistLoader_.sidxMapping_,previousManifest:e});e&&(t=((e,t,i)=>{let s=!0,n=U(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=lt(a.sidx);i&&i[e]&&i[e].sidx&&nt(a,i[e].sidx,a.sidx.resolvedUri)}const r=be(n,a,di);r&&(n=r,s=!1)}return he(t,((e,t,i,a)=>{if(e.playlists&&e.playlists.length){const r=e.playlists[0].id,o=be(n,e.playlists[0],di);o&&(n=o,a in n.mediaGroups[t][i]||(n.mediaGroups[t][i][a]=e),n.mediaGroups[t][i][a].playlists[0]=n.playlists[r],s=!1)}})),((e,t)=>{he(e,((i,s,n,a)=>{a in t.mediaGroups[s][n]||delete e.mediaGroups[s][n][a]}))})(n,t),t.minimumUpdatePeriod!==e.minimumUpdatePeriod&&(s=!1),s?null:n})(e,t,this.mainPlaylistLoader_.sidxMapping_)),this.mainPlaylistLoader_.main=t||e;const i=this.mainPlaylistLoader_.main.locations&&this.mainPlaylistLoader_.main.locations[0];return i&&i!==this.mainPlaylistLoader_.srcUrl&&(this.mainPlaylistLoader_.srcUrl=i),(!e||t&&t.minimumUpdatePeriod!==e.minimumUpdatePeriod)&&this.updateMinimumUpdatePeriodTimeout_(),this.addEventStreamToMetadataTrack_(t),Boolean(t)}updateMinimumUpdatePeriodTimeout_(){const e=this.mainPlaylistLoader_;e.createMupOnMedia_&&(e.off("loadedmetadata",e.createMupOnMedia_),e.createMupOnMedia_=null),e.minimumUpdatePeriodTimeout_&&(window.clearTimeout(e.minimumUpdatePeriodTimeout_),e.minimumUpdatePeriodTimeout_=null);let t=e.main&&e.main.minimumUpdatePeriod;0===t&&(e.media()?t=1e3*e.media().targetDuration:(e.createMupOnMedia_=e.updateMinimumUpdatePeriodTimeout_,e.one("loadedmetadata",e.createMupOnMedia_))),"number"!=typeof t||t<=0?t<0&&this.logger_(`found invalid minimumUpdatePeriod of ${t}, not setting a timeout`):this.createMUPTimeout_(t)}createMUPTimeout_(e){const t=this.mainPlaylistLoader_;t.minimumUpdatePeriodTimeout_=window.setTimeout((()=>{t.minimumUpdatePeriodTimeout_=null,t.trigger("minimumUpdatePeriod"),t.createMUPTimeout_(e)}),e)}refreshXml_(){this.requestMain_(((e,t)=>{t&&(this.media_&&(this.media_=this.mainPlaylistLoader_.main.playlists[this.media_.id]),this.mainPlaylistLoader_.sidxMapping_=((e,t)=>{let i=hi(e.playlists,t);return he(e,((e,s,n,a)=>{if(e.playlists&&e.playlists.length){const s=e.playlists;i=U(i,hi(s,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()}),Se(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 s=e.contentProtection[i].attributes["cenc:default_KID"];s&&t.add(s.replace(/-/g,"").toLowerCase())}return t}}}var pi={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 mi=function(e){return e.on=e.addEventListener,e.off=e.removeEventListener,e},gi=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=mi(new Worker(t));i.objURL=t;const s=i.terminate;return i.on=i.addEventListener,i.off=i.removeEventListener,i.terminate=function(){return URL.revokeObjectURL(t),s.call(this)},i}},fi=function(e){return`var browserWorkerPolyFill = ${mi.toString()};\nbrowserWorkerPolyFill(self);\n`+e},yi=function(e){return e.toString().replace(/^function.+?{/,"").slice(0,-1)},_i=fi(yi((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 s;return!!e[t]&&(s=e[t].indexOf(i),e[t]=e[t].slice(),e[t].splice(s,1),s>-1)},this.trigger=function(t){var i,s,n,a;if(i=e[t])if(2===arguments.length)for(n=i.length,s=0;s<n;++s)i[s].call(this,arguments[1]);else{for(a=[],s=arguments.length,s=1;s<arguments.length;++s)a.push(arguments[s]);for(n=i.length,s=0;s<n;++s)i[s].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,s,n,a,r,o,d,l,u,h,c,p,m,g,f,y,_,T,b,S,v,w,I,E,A,D,x,L,P,C,k,U,O,R,M,N,B,F,q,$,G=t,W=Math.pow(2,32),V={getUint64:function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength);return i.getBigUint64?(t=i.getBigUint64(0))<Number.MAX_SAFE_INTEGER?Number(t):t:i.getUint32(0)*W+i.getUint32(4)},MAX_UINT32:W},H=V.MAX_UINT32;!function(){var e;if(w={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],mvex:[],mvhd:[],pasp:[],sdtp:[],smhd:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],styp:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[]},"undefined"!=typeof Uint8Array){for(e in w)w.hasOwnProperty(e)&&(w[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);I=new Uint8Array(["i".charCodeAt(0),"s".charCodeAt(0),"o".charCodeAt(0),"m".charCodeAt(0)]),A=new Uint8Array(["a".charCodeAt(0),"v".charCodeAt(0),"c".charCodeAt(0),"1".charCodeAt(0)]),E=new Uint8Array([0,0,0,1]),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]),L={video:D,audio:x},k=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),C=new Uint8Array([0,0,0,0,0,0,0,0]),U=new Uint8Array([0,0,0,0,0,0,0,0]),O=U,R=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),M=U,P=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}}(),i=function(e){var t,i,s=[],n=0;for(t=1;t<arguments.length;t++)s.push(arguments[t]);for(t=s.length;t--;)n+=s[t].byteLength;for(i=new Uint8Array(n+8),new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,i.byteLength),i.set(e,4),t=0,n=8;t<s.length;t++)i.set(s[t],n),n+=s[t].byteLength;return i},s=function(){return i(w.dinf,i(w.dref,k))},n=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,L[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,P):i(w.smhd,C),s(),_(e))},d=function(e,t){for(var s=[],n=t.length;n--;)s[n]=b(t[n]);return i.apply(null,[w.moof,r(e)].concat(s))},l=function(e){for(var t=e.length,s=[];t--;)s[t]=c(e[t]);return i.apply(null,[w.moov,h(4294967295)].concat(s).concat(u(e)))},u=function(e){for(var t=e.length,s=[];t--;)s[t]=S(e[t]);return i.apply(null,[w.mvex].concat(s))},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,s,n=e.samples||[],a=new Uint8Array(4+n.length);for(s=0;s<n.length;s++)t=n[s].flags,a[s+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,O),i(w.stsz,R),i(w.stco,U))},T=function(e){return i(w.stsd,new Uint8Array([0,0,0,0,0,0,0,1]),"video"===e.type?N(e):B(e))},N=function(e){var t,s,n=e.sps||[],a=e.pps||[],r=[],o=[];for(t=0;t<n.length;t++)r.push((65280&n[t].byteLength)>>>8),r.push(255&n[t].byteLength),r=r.concat(Array.prototype.slice.call(n[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(s=[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([n.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],l=e.sarRatio[1];s.push(i(w.pasp,new Uint8Array([(4278190080&d)>>24,(16711680&d)>>16,(65280&d)>>8,255&d,(4278190080&l)>>24,(16711680&l)>>16,(65280&l)>>8,255&l])))}return i.apply(null,s)},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]),n(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,s,n,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),s=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?(n=v(e,92),i(w.traf,t,s,n)):(a=y(e),n=v(e,a.length+92),i(w.traf,t,s,n,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,s=0,n=0,a=0;return e.length&&(void 0!==e[0].duration&&(i=1),void 0!==e[0].size&&(s=2),void 0!==e[0].flags&&(n=4),void 0!==e[0].compositionTimeOffset&&(a=8)),[0,0,i|s|n|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 s,n,a,r,o,d;for(t+=20+16*(r=e.samples||[]).length,a=$(r,t),(n=new Uint8Array(a.length+16*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,n[s++]=o.flags.isLeading<<2|o.flags.dependsOn,n[s++]=o.flags.isDependedOn<<6|o.flags.hasRedundancy<<4|o.flags.paddingValue<<1|o.flags.isNonSyncSample,n[s++]=61440&o.flags.degradationPriority,n[s++]=15&o.flags.degradationPriority,n[s++]=(4278190080&o.compositionTimeOffset)>>>24,n[s++]=(16711680&o.compositionTimeOffset)>>>16,n[s++]=(65280&o.compositionTimeOffset)>>>8,n[s++]=255&o.compositionTimeOffset;return i(w.trun,n)},F=function(e,t){var s,n,a,r,o,d;for(t+=20+8*(r=e.samples||[]).length,a=$(r,t),(s=new Uint8Array(a.length+8*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;return i(w.trun,s)},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:l,initSegment:function(e){var t,i=a(),s=l(e);return(t=new Uint8Array(i.byteLength+s.byteLength)).set(i),t.set(s,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,s=[],n=[];for(n.byteLength=0,n.nalCount=0,n.duration=0,s.byteLength=0,t=0;t<e.length;t++)"access_unit_delimiter_rbsp"===(i=e[t]).nalUnitType?(s.length&&(s.duration=i.dts-s.dts,n.byteLength+=s.byteLength,n.nalCount+=s.length,n.duration+=s.duration,n.push(s)),(s=[i]).byteLength=i.data.byteLength,s.pts=i.pts,s.dts=i.dts):("slice_layer_without_partitioning_rbsp_idr"===i.nalUnitType&&(s.keyFrame=!0),s.duration=i.dts-s.dts,s.byteLength+=i.data.byteLength,s.push(i));return n.length&&(!s.duration||s.duration<=0)&&(s.duration=n[n.length-1].duration),n.byteLength+=s.byteLength,n.nalCount+=s.length,n.duration+=s.duration,n.push(s),n},groupFramesIntoGops:function(e){var t,i,s=[],n=[];for(s.byteLength=0,s.nalCount=0,s.duration=0,s.pts=e[0].pts,s.dts=e[0].dts,n.byteLength=0,n.nalCount=0,n.duration=0,n.pts=e[0].pts,n.dts=e[0].dts,t=0;t<e.length;t++)(i=e[t]).keyFrame?(s.length&&(n.push(s),n.byteLength+=s.byteLength,n.nalCount+=s.nalCount,n.duration+=s.duration),(s=[i]).nalCount=i.length,s.byteLength=i.byteLength,s.pts=i.pts,s.dts=i.dts,s.duration=i.duration):(s.duration+=i.duration,s.nalCount+=i.length,s.byteLength+=i.byteLength,s.push(i));return n.length&&s.duration<=0&&(s.duration=n[n.length-1].duration),n.byteLength+=s.byteLength,n.nalCount+=s.nalCount,n.duration+=s.duration,n.push(s),n},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,s,n,a,r,o=t||0,d=[];for(i=0;i<e.length;i++)for(a=e[i],s=0;s<a.length;s++)r=a[s],o+=(n=te(r,o)).size,d.push(n);return d},concatenateNalData:function(e){var t,i,s,n,a,r,o=0,d=e.byteLength,l=e.nalCount,u=new Uint8Array(d+4*l),h=new DataView(u.buffer);for(t=0;t<e.length;t++)for(n=e[t],i=0;i<n.length;i++)for(a=n[i],s=0;s<a.length;s++)r=a[s],h.setUint32(o,r.data.byteLength),o+=4,u.set(r.data,o),o+=r.data.byteLength;return u},generateSampleTableForFrame:function(e,t){var i,s=[];return i=te(e,t||0),s.push(i),s},concatenateNalDataForFrame:function(e){var t,i,s=0,n=e.byteLength,a=e.length,r=new Uint8Array(n+4*a),o=new DataView(r.buffer);for(t=0;t<e.length;t++)i=e[t],o.setUint32(s,i.data.byteLength),s+=4,r.set(i.data,s),s+=i.data.byteLength;return r}},se=[33,16,5,32,164,27],ne=[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,le={prefixWithSilence:function(e,t,i,s){var n,a,r,o,d,l=0,u=0,h=0;if(t.length&&(n=de.audioTsToVideoTs(e.baseMediaDecodeTime,e.samplerate),a=Math.ceil(de.ONE_SECOND_IN_TS/(e.samplerate/1024)),i&&s&&(l=n-Math.max(i,s),h=(u=Math.floor(l/a))*a),!(u<1||h>de.ONE_SECOND_IN_TS/2))){for((r=function(){if(!X){var e={96e3:[se,[227,64],ae(154),[56]],88200:[se,[231],ae(170),[56]],64e3:[se,[248,192],ae(240),[56]],48e3:[se,[255,192],ae(268),[55,148,128],ae(54),[112]],44100:[se,[255,192],ae(268),[55,163,128],ae(84),[112]],32e3:[se,[255,192],ae(268),[55,234],ae(226),[112]],24e3:[se,[255,192],ae(268),[55,255,128],ae(268),[111,112],ae(126),[224]],16e3:[se,[255,192],ae(268),[55,255,128],ae(268),[111,255],ae(269),[223,108],ae(195),[1,192]],12e3:[ne,ae(268),[3,127,248],ae(268),[6,255,240],ae(268),[13,255,224],ae(268),[27,253,128],ae(259),[56]],11025:[ne,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:[ne,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<u;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,s=[];for(t=0;t<e.length;t++)i=e[t],s.push({size:i.data.byteLength,duration:1024});return s},concatenateFrameData:function(e){var t,i,s=0,n=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],n.set(i.data,s),s+=i.data.byteLength;return n}},ue=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,s=e.minSegmentDts;return t||(s-=e.timelineStartInfo.dts),i=e.timelineStartInfo.baseMediaDecodeTime,i+=s,i=Math.max(0,i),"audio"===e.type&&(i*=e.samplerate/ue,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},s=0,n=0;t<e.byteLength&&128!==e[t];){for(;255===e[t];)s+=255,t++;for(s+=e[t++];255===e[t];)n+=255,t++;if(n+=e[t++],!i.payload&&4===s){if("GA94"===String.fromCharCode(e[t+3],e[t+4],e[t+5],e[t+6])){i.payloadType=s,i.payloadSize=n,i.payload=e.subarray(t,t+n);break}i.payload=void 0}t+=n,s=0,n=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,s,n,a,r=[];if(!(64&t[0]))return r;for(s=31&t[0],i=0;i<s;i++)a={type:3&t[2+(n=3*i)],pts:e},4&t[n+2]&&(a.ccData=t[n+3]<<8|t[n+4],r.push(a));return r},discardEmulationPreventionBytes:function(e){for(var t,i,s=e.byteLength,n=[],a=1;a<s-2;)0===e[a]&&0===e[a+1]&&3===e[a+2]?(n.push(a+2),a+=2):a++;if(0===n.length)return e;t=s-n.length,i=new Uint8Array(t);var r=0;for(a=0;a<t;r++,a++)r===n[0]&&(r++,n.shift()),i[a]=e[r];return i},USER_DATA_REGISTERED_ITU_T_T35:4},pe=G,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,s;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));s=me.parseCaptionPackets(e.pts,i),this.captionPackets_=this.captionPackets_.concat(s),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,s=e.captionServices||{},n={};Object.keys(s).forEach((e=>{t=s[e],/^SERVICE/.test(e)&&(n[e]=t.encoding)})),this.serviceEncodings=n,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,s=255&t;this.current708Packet.ptsVals.push(e.pts),this.current708Packet.data.push(i),this.current708Packet.data.push(s)},be.prototype.push708Packet=function(){var e=this.current708Packet,t=e.data,i=null,s=null,n=0,a=t[n++];for(e.seq=a>>6,e.sizeCode=63&a;n<t.length;n++)s=31&(a=t[n++]),7==(i=a>>5)&&s>0&&(i=a=t[n++]),this.pushServiceBlock(i,n,s),s>0&&(n+=s-1)},be.prototype.pushServiceBlock=function(e,t,i){var s,n=t,a=this.current708Packet.data,r=this.services[e];for(r||(r=this.initService(e,n));n<t+i&&n<a.length;n++)s=a[n],ye(s)?n=this.handleText(n,r):24===s?n=this.multiByteCharacter(n,r):16===s?n=this.extendedCommands(n,r):128<=s&&s<=135?n=this.setCurrentWindow(n,r):152<=s&&s<=159?n=this.defineWindow(n,r):136===s?n=this.clearWindows(n,r):140===s?n=this.deleteWindows(n,r):137===s?n=this.displayWindows(n,r):138===s?n=this.hideWindows(n,r):139===s?n=this.toggleWindows(n,r):151===s?n=this.setWindowAttributes(n,r):144===s?n=this.setPenAttributes(n,r):145===s?n=this.setPenColor(n,r):146===s?n=this.setPenLocation(n,r):143===s?r=this.reset(n,r):8===s?r.currentWindow.backspace():12===s?r.currentWindow.clearText():13===s?r.currentWindow.pendingNewLine=!0:14===s?r.currentWindow.clearText():141===s&&n++},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,s,n=this;return(i="SERVICE"+e)in this.serviceEncodings&&(s=this.serviceEncodings[i]),this.services[e]=new Te(e,s,n),this.services[e].init(this.getPts(t),(function(t){n.flushDisplayed(t,n.services[e])})),this.services[e]},be.prototype.handleText=function(e,t,i){var s,n,a,r,o=i&&i.isExtended,d=i&&i.isMultiByte,l=this.current708Packet.data,u=o?4096:0,h=l[e],c=l[e+1],p=t.currentWindow;if(d?(n=[h,c],e++):n=[h],t.textDecoder_&&!o)s=t.textDecoder_.decode(new Uint8Array(n));else if(d){const e=n.map((e=>("0"+(255&e).toString(16)).slice(-2))).join("");s=String.fromCharCode(parseInt(e,16))}else r=fe[a=u|h]||a,s=4096&a&&a===r?"":String.fromCharCode(r);return p.pendingNewLine&&!p.isEmpty()&&p.newLine(this.getPts(e)),p.pendingNewLine=!1,p.addText(s),e},be.prototype.multiByteCharacter=function(e,t){var i=this.current708Packet.data,s=i[e+1],n=i[e+2];return ye(s)&&ye(n)&&(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,s=i[e],n=7&s;t.setCurrentWindow(n);var a=t.currentWindow;return s=i[++e],a.visible=(32&s)>>5,a.rowLock=(16&s)>>4,a.columnLock=(8&s)>>3,a.priority=7&s,s=i[++e],a.relativePositioning=(128&s)>>7,a.anchorVertical=127&s,s=i[++e],a.anchorHorizontal=s,s=i[++e],a.anchorPoint=(240&s)>>4,a.rowCount=15&s,s=i[++e],a.columnCount=63&s,s=i[++e],a.windowStyle=(56&s)>>3,a.penStyle=7&s,a.virtualRowCount=a.rowCount+1,e},be.prototype.setWindowAttributes=function(e,t){var i=this.current708Packet.data,s=i[e],n=t.currentWindow.winAttr;return s=i[++e],n.fillOpacity=(192&s)>>6,n.fillRed=(48&s)>>4,n.fillGreen=(12&s)>>2,n.fillBlue=3&s,s=i[++e],n.borderType=(192&s)>>6,n.borderRed=(48&s)>>4,n.borderGreen=(12&s)>>2,n.borderBlue=3&s,s=i[++e],n.borderType+=(128&s)>>5,n.wordWrap=(64&s)>>6,n.printDirection=(48&s)>>4,n.scrollDirection=(12&s)>>2,n.justify=3&s,s=i[++e],n.effectSpeed=(240&s)>>4,n.effectDirection=(12&s)>>2,n.displayEffect=3&s,e},be.prototype.flushDisplayed=function(e,t){for(var i=[],s=0;s<8;s++)t.windows[s].visible&&!t.windows[s].isEmpty()&&i.push(t.windows[s].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],s=this.getPts(e);this.flushDisplayed(s,t);for(var n=0;n<8;n++)i&1<<n&&(t.windows[n].visible=1);return e},be.prototype.hideWindows=function(e,t){var i=this.current708Packet.data[++e],s=this.getPts(e);this.flushDisplayed(s,t);for(var n=0;n<8;n++)i&1<<n&&(t.windows[n].visible=0);return e},be.prototype.toggleWindows=function(e,t){var i=this.current708Packet.data[++e],s=this.getPts(e);this.flushDisplayed(s,t);for(var n=0;n<8;n++)i&1<<n&&(t.windows[n].visible^=1);return e},be.prototype.clearWindows=function(e,t){var i=this.current708Packet.data[++e],s=this.getPts(e);this.flushDisplayed(s,t);for(var n=0;n<8;n++)i&1<<n&&t.windows[n].clearText();return e},be.prototype.deleteWindows=function(e,t){var i=this.current708Packet.data[++e],s=this.getPts(e);this.flushDisplayed(s,t);for(var n=0;n<8;n++)i&1<<n&&t.windows[n].reset();return e},be.prototype.setPenAttributes=function(e,t){var i=this.current708Packet.data,s=i[e],n=t.currentWindow.penAttr;return s=i[++e],n.textTag=(240&s)>>4,n.offset=(12&s)>>2,n.penSize=3&s,s=i[++e],n.italics=(128&s)>>7,n.underline=(64&s)>>6,n.edgeType=(56&s)>>3,n.fontStyle=7&s,e},be.prototype.setPenColor=function(e,t){var i=this.current708Packet.data,s=i[e],n=t.currentWindow.penColor;return s=i[++e],n.fgOpacity=(192&s)>>6,n.fgRed=(48&s)>>4,n.fgGreen=(12&s)>>2,n.fgBlue=3&s,s=i[++e],n.bgOpacity=(192&s)>>6,n.bgRed=(48&s)>>4,n.bgGreen=(12&s)>>2,n.bgBlue=3&s,s=i[++e],n.edgeRed=(48&s)>>4,n.edgeGreen=(12&s)>>2,n.edgeBlue=3&s,e},be.prototype.setPenLocation=function(e,t){var i=this.current708Packet.data,s=i[e],n=t.currentWindow.penLoc;return t.currentWindow.pendingNewLine=!0,s=i[++e],n.row=15&s,s=i[++e],n.column=63&s,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,s,n,a;if((t=32639&e.ccData)!==this.lastControlCode_){if(4096==(61440&t)?this.lastControlCode_=t:t!==this.PADDING_&&(this.lastControlCode_=null),s=t>>>8,n=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(s,n))a=ve((s=(3&s)<<8)|n),this[this.mode_](e.pts,a),this.column_++;else if(this.isExtCharacter(s,n))"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((s=(3&s)<<8)|n),this[this.mode_](e.pts,a),this.column_++;else if(this.isMidRowCode(s,n))this.clearFormatting(e.pts),this[this.mode_](e.pts," "),this.column_++,14==(14&n)&&this.addFormatting(e.pts,["i"]),1==(1&n)&&this.addFormatting(e.pts,["u"]);else if(this.isOffsetControlCode(s,n)){const e=3&n;this.nonDisplayed_[this.row_].offset=e,this.column_+=e}else if(this.isPAC(s,n)){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_&&(this.clearFormatting(e.pts),this.row_=r),1&n&&-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(n)&&14==(14&n)&&this.addFormatting(e.pts,["i"])}else this.isNormalChar(s)&&(0===n&&(n=null),a=ve(s),a+=ve(n),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,s)=>{if(e&&e.text&&e.text.length){try{e.text=e.text.trim()}catch(e){t(s)}e.text.length&&i.push({text:e.text,line:s+1,position:10+Math.min(70,10*e.indent)+2.5*e.offset})}else null==e&&t(s)})),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=G,Le="shared",Pe=function(e,t){var i=1;for(e>t&&(i=-1);Math.abs(t-e)>4294967296;)e+=8589934592*i;return e},Ce=function(e){var t,i;Ce.prototype.init.call(this),this.type_=e||Le,this.push=function(e){"metadata"!==e.type?this.type_!==Le&&e.type!==this.type_||(void 0===i&&(i=e.dts),e.dts=Pe(e.dts,i),e.pts=Pe(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")}};Ce.prototype=new xe;var ke,Ue={TimestampRolloverStream:Ce,handleRollover:Pe},Oe=(e,t,i)=>{if(!e)return-1;for(var s=i;s<e.length;s++)if(e[s]===t)return s;return-1},Re=function(e,t,i){var s,n="";for(s=t;s<i;s++)n+="%"+("00"+e[s].toString(16)).slice(-2);return n},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,s=1;3===e.data[0]&&((t=Oe(e.data,0,s))<0||(e.mimeType=Ne(e.data,s,t),s=t+1,e.pictureType=e.data[s],s++,(i=Oe(e.data,0,s))<0||(e.description=Me(e.data,s,i),s=i+1,"--\x3e"===e.mimeType?e.url=Ne(e.data,s,e.data.length):e.pictureData=e.data.subarray(s,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=Oe(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=Oe(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,s=0,n=[];if(!(e.length<10||e[0]!=="I".charCodeAt(0)||e[1]!=="D".charCodeAt(0)||e[2]!=="3".charCodeAt(0))){s=Be(e.subarray(6,10)),s+=10,64&e[5]&&(i+=4,i+=Be(e.subarray(10,14)),s-=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),n.push(a),i+=10,i+=t}while(i<s);return n}},parseSyncSafeInteger:Be,frameParsers:Fe},$e=De,Ge=qe;(ke=function(e){var t,i={descriptor:e&&e.descriptor},s=0,n=[],a=0;if(ke.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,n.length=0),0===n.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(n.push(e),a+=e.data.byteLength,1===n.length&&(s=Ge.parseSyncSafeInteger(e.data.subarray(6,10)),s+=10),!(a<s)){for(t={data:new Uint8Array(s),frames:[],pts:n[0].pts,dts:n[0].dts},d=0;d<s;)t.data.set(n[0].data.subarray(0,s-d),d),d+=n[0].data.byteLength,a-=n[0].data.byteLength,n.shift();i=10,64&t.data[5]&&(i+=4,i+=Ge.parseSyncSafeInteger(t.data.subarray(10,14)),s-=Ge.parseSyncSafeInteger(t.data.subarray(16,20)));do{if((r=Ge.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,Ge.frameParsers[o.id]?Ge.frameParsers[o.id](o):"T"===o.id[0]?Ge.frameParsers["T*"](o):"W"===o.id[0]&&Ge.frameParsers["W*"](o),"com.apple.streaming.transportStreamTimestamp"===o.owner){var l=o.data,u=(1&l[3])<<30|l[4]<<22|l[5]<<14|l[6]<<6|l[7]>>>2;u*=4,u+=3&l[7],o.timeStamp=u,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<s);this.trigger("data",t)}}}).prototype=new G;var We,Ve,He,Xe=ke,je=G,ze=Ae,Ye=De,Qe=Ue.TimestampRolloverStream,Ke=188;(We=function(){var e=new Uint8Array(Ke),t=0;We.prototype.init.call(this),this.push=function(i){var s,n=0,a=Ke;for(t?((s=new Uint8Array(i.byteLength+t)).set(e.subarray(0,t)),s.set(i,t),t=0):s=i;a<s.byteLength;)71!==s[n]||71!==s[a]?(n++,a++):(this.trigger("data",s.subarray(n,a)),n+=Ke,a+=Ke);n<s.byteLength&&(e.set(s.subarray(n),0),t=s.byteLength-n)},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,(Ve=function(){var e,t,i,s;Ve.prototype.init.call(this),s=this,this.packetsWaitingForPmt=[],this.programMapTable=void 0,e=function(e,s){var n=0;s.payloadUnitStartIndicator&&(n+=e[n]+1),"pat"===s.type?t(e.subarray(n),s):i(e.subarray(n),s)},t=function(e,t){t.section_number=e[7],t.last_section_number=e[8],s.pmtPid=(31&e[10])<<8|e[11],t.pmtPid=s.pmtPid},i=function(e,t){var i,n;if(1&e[5]){for(s.programMapTable={video:null,audio:null,"timed-metadata":{}},i=3+((15&e[1])<<8|e[2])-4,n=12+((15&e[10])<<8|e[11]);n<i;){var a=e[n],r=(31&e[n+1])<<8|e[n+2];a===Ye.H264_STREAM_TYPE&&null===s.programMapTable.video?s.programMapTable.video=r:a===Ye.ADTS_STREAM_TYPE&&null===s.programMapTable.audio?s.programMapTable.audio=r:a===Ye.METADATA_STREAM_TYPE&&(s.programMapTable["timed-metadata"][r]=a),n+=5+((15&e[n+3])<<8|e[n+4])}t.programMapTable=s.programMapTable}},this.push=function(t){var i={},s=4;if(i.payloadUnitStartIndicator=!!(64&t[1]),i.pid=31&t[1],i.pid<<=8,i.pid|=t[2],(48&t[3])>>>4>1&&(s+=t[s]+1),0===i.pid)i.type="pat",e(t.subarray(s),i),this.trigger("data",i);else if(i.pid===this.pmtPid)for(i.type="pmt",e(t.subarray(s),i),this.trigger("data",i);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else void 0===this.programMapTable?this.packetsWaitingForPmt.push([t,s,i]):this.processPes_(t,s,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,Ve.STREAM_TYPES={h264:27,adts:15},He=function(){var e,t=this,i=!1,s={data:[],size:0},n={data:[],size:0},a={data:[],size:0},r=function(e,i,s){var n,a,r=new Uint8Array(e.size),o={type:i},d=0,l=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,l),l+=a.data.byteLength;!function(e,t){var i;const s=e[0]<<16|e[1]<<8|e[2];t.data=new Uint8Array,1===s&&(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),n="video"===i||o.packetLength<=e.size,(s||n)&&(e.size=0,e.data.length=0),n&&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=s,t="video";break;case Ye.ADTS_STREAM_TYPE:e=n,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 s={type:"metadata",tracks:[]};null!==(e=o.programMapTable).video&&s.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+e.video,codec:"avc",type:"video"}),null!==e.audio&&s.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+e.audio,codec:"adts",type:"audio"}),i=!0,t.trigger("data",s)}})[o.type]()},this.reset=function(){s.size=0,s.data.length=0,n.size=0,n.data.length=0,this.trigger("reset")},this.flushStreams_=function(){r(s,"video"),r(n,"audio"),r(a,"timed-metadata")},this.flush=function(){if(!i&&e){var s={type:"metadata",tracks:[]};null!==e.video&&s.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+e.video,codec:"avc",type:"video"}),null!==e.audio&&s.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+e.audio,codec:"adts",type:"audio"}),t.trigger("data",s)}i=!1,this.flushStreams_(),this.trigger("done")}},He.prototype=new je;var Je={PAT_PID:0,MP2T_PACKET_LENGTH:Ke,TransportPacketStream:We,TransportParseStream:Ve,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,st=[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(s){var n,a,r,o,d,l=0;if(e||(i=0),"audio"===s.type){var u;for(t&&t.length?(r=t,(t=new Uint8Array(r.byteLength+s.data.byteLength)).set(r),t.set(s.data,r.byteLength)):t=s.data;l+7<t.length;)if(255===t[l]&&240==(246&t[l+1])){if("number"==typeof u&&(this.skipWarn_(u,l),u=null),a=2*(1&~t[l+1]),n=(3&t[l+3])<<11|t[l+4]<<3|(224&t[l+5])>>5,d=(o=1024*(1+(3&t[l+6])))*it/st[(60&t[l+2])>>>2],t.byteLength-l<n)break;this.trigger("data",{pts:s.pts+i*d,dts:s.dts+i*d,sampleCount:o,audioobjecttype:1+(t[l+2]>>>6&3),channelcount:(1&t[l+2])<<2|(192&t[l+3])>>>6,samplerate:st[(60&t[l+2])>>>2],samplingfrequencyindex:(60&t[l+2])>>>2,samplesize:16,data:t.subarray(l+7+a,l+n)}),i++,l+=n}else"number"!=typeof u&&(u=l),l++;"number"==typeof u&&(this.skipWarn_(u,l),u=null),t=t.subarray(l)}},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 G;var nt,at,rt,ot=et,dt=G,lt=function(e){var t=e.byteLength,i=0,s=0;this.length=function(){return 8*t},this.bitsAvailable=function(){return 8*t+s},this.loadWord=function(){var n=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(n,n+r)),i=new DataView(a.buffer).getUint32(0),s=8*r,t-=r},this.skipBits=function(e){var n;s>e?(i<<=e,s-=e):(e-=s,e-=8*(n=Math.floor(e/8)),t-=n,this.loadWord(),i<<=e,s-=e)},this.readBits=function(e){var n=Math.min(s,e),a=i>>>32-n;return(s-=n)>0?i<<=n:t>0&&this.loadWord(),(n=e-n)>0?a<<n|this.readBits(n):a},this.skipLeadingZeros=function(){var e;for(e=0;e<s;++e)if(0!=(i&2147483648>>>e))return i<<=e,s-=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(s){var n;t?((n=new Uint8Array(t.byteLength+s.data.byteLength)).set(t),n.set(s.data,t.byteLength),t=n):t=s.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},nt=function(){var e,t,i,s,n,a,r,o=new at;nt.prototype.init.call(this),e=this,this.push=function(e){"video"===e.type&&(t=e.trackId,i=e.pts,s=e.dts,o.push(e))},o.on("data",(function(r){var o={trackId:t,pts:i,dts:s,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=n(r.subarray(1));break;case 7:o.nalUnitType="seq_parameter_set_rbsp",o.escapedRBSP=n(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,s=8,n=8;for(i=0;i<e;i++)0!==n&&(n=(s+t.readExpGolomb()+256)%256),s=0===n?s:n},n=function(e){for(var t,i,s=e.byteLength,n=[],a=1;a<s-2;)0===e[a]&&0===e[a+1]&&3===e[a+2]?(n.push(a+2),a+=2):a++;if(0===n.length)return e;t=s-n.length,i=new Uint8Array(t);var r=0;for(a=0;a<t;r++,a++)r===n[0]&&(r++,n.shift()),i[a]=e[r];return i},a=function(e){var t,i,s,n,a,o,d,l,u,h,c,p,m=0,g=0,f=0,y=0,_=[1,1];if(i=(t=new lt(e)).readUnsignedByte(),n=t.readUnsignedByte(),s=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),l=t.readUnsignedExpGolomb(),u=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:s,profileCompatibility:n,width:16*(l+1)-2*m-2*g,height:(2-h)*(u+1)*16-2*f-2*y,sarRatio:_}}},nt.prototype=new dt;var ut,ht={H264Stream:nt,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,s=e[t+4]<<3;return 6144&e[t+3]|s|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,s;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])){s=e.subarray(t+10,t+i+10);for(var n=0;n<s.byteLength;n++)if(0===s[n]){var a=unescape(function(e,t,i){var s,n="";for(s=0;s<i;s++)n+="%"+("00"+e[s].toString(16)).slice(-2);return n}(s,0,n));if("com.apple.streaming.transportStreamTimestamp"===a){var r=s.subarray(n+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;(ut=function(){var e=new Uint8Array,t=0;ut.prototype.init.call(this),this.setTimestamp=function(e){t=e},this.push=function(i){var s,n,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;n={type:"timed-metadata",data:e.subarray(d,d+o)},this.trigger("data",n),d+=o}s=e.length-d,e=s>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 G;var _t,Tt,bt,St,vt=G,wt=ee,It=ie,Et=le,At=he,Dt=tt,xt=oe,Lt=ot,Pt=ht.H264Stream,Ct=ut,kt=ft.isLikelyAacData,Ut=oe.ONE_SECOND_IN_TS,Ot=["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),s=0;s<i.length;s++){var n=i[s];"headOfPipeline"!==n&&t[n].on&&t[n].on("log",Mt.bind(e,n))}},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,s,n,a){return{start:{dts:e,pts:e+(i-t)},end:{dts:e+(s-t),pts:e+(n-i)},prependedContentDuration:a,baseMediaDecodeTime:e}};Tt=function(e,t){var i,s=[],n=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&&Ot.forEach((function(i){e[i]=t[i]})),s.push(t)},this.setEarliestDts=function(e){n=e},this.setVideoBaseMediaDecodeTime=function(e){r=e},this.setAudioAppendStart=function(e){a=e},this.flush=function(){var o,d,l,u,h,c,p;0!==s.length?(o=Et.trimAdtsFramesByEarliestDts(s,e,n),e.baseMediaDecodeTime=At.calculateTrackBaseMediaDecodeTime(e,t.keepOriginalTimestamps),p=Et.prefixWithSilence(e,o,a,r),e.samples=Et.generateSampleTable(o),l=wt.mdat(Et.concatenateFrameData(o)),s=[],d=wt.moof(i,[e]),u=new Uint8Array(d.byteLength+l.byteLength),i++,u.set(d),u.set(l,d.byteLength),At.clearDtsInfo(e),h=Math.ceil(1024*Ut/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:u}),this.trigger("done","AudioSegmentStream")):this.trigger("done","AudioSegmentStream")},this.reset=function(){At.clearDtsInfo(e),s=[],this.trigger("reset")}},Tt.prototype=new vt,_t=function(e,t){var i,s,n,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||s||(s=t.config,e.sps=[t.data],Rt.forEach((function(t){e[t]=s[t]}),this)),"pic_parameter_set_rbsp"!==t.nalUnitType||n||(n=t.data,e.pps=[t.data]),a.push(t)},this.flush=function(){for(var s,n,o,d,l,u,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(s=It.groupNalsIntoFrames(a),(o=It.groupFramesIntoGops(s))[0][0].keyFrame||((n=this.getGopForFusion_(a[0],e))?(p=n.duration,o.unshift(n),o.byteLength+=n.byteLength,o.nalCount+=n.nalCount,o.pts=n.pts,o.dts=n.dts,o.duration+=n.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),l=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]),u=new Uint8Array(d.byteLength+l.byteLength),i++,u.set(d),u.set(l,d.byteLength),this.trigger("data",{track:e,boxes:u}),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),s=void 0,n=void 0},this.getGopForFusion_=function(t){var i,s,n,a,r,o=1/0;for(r=0;r<this.gopCache_.length;r++)n=(a=this.gopCache_[r]).gop,e.pps&&Bt(e.pps[0],a.pps[0])&&e.sps&&Bt(e.sps[0],a.sps[0])&&(n.dts<e.timelineStartInfo.dts||(i=t.dts-n.dts-n.duration)>=-1e4&&i<=45e3&&(!s||o>i)&&(s=a,o=i));return s?s.gop:null},this.alignGopsAtStart_=function(e){var t,i,s,n,a,o,d,l;for(a=e.byteLength,o=e.nalCount,d=e.duration,t=i=0;t<r.length&&i<e.length&&(s=r[t],n=e[i],s.pts!==n.pts);)n.pts>s.pts?t++:(i++,a-=n.byteLength,o-=n.nalCount,d-=n.duration);return 0===i?e:i===e.length?null:((l=e.slice(i)).byteLength=a,l.duration=d,l.nalCount=o,l.pts=l[0].pts,l.dts=l[0].dts,l)},this.alignGopsAtEnd_=function(e){var t,i,s,n,a,o,d;for(t=r.length-1,i=e.length-1,a=null,o=!1;t>=0&&i>=0;){if(s=r[t],n=e[i],s.pts===n.pts){o=!0;break}s.pts>n.pts?t--:(t===r.length-1&&(a=i),i--)}if(!o&&null===a)return null;if(0===(d=o?i:a))return e;var l=e.slice(d),u=l.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 l.byteLength=u.byteLength,l.duration=u.duration,l.nalCount=u.nalCount,l.pts=l[0].pts,l.dts=l[0].dts,l},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,s,n,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,Ot.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,s=wt.initSegment(this.pendingTracks),r.initSegment=new Uint8Array(s.byteLength),r.initSegment.set(s),r.data=new Uint8Array(this.pendingBytes),n=0;n<this.pendingBoxes.length;n++)r.data.set(this.pendingBoxes[n],a),a+=this.pendingBoxes[n].byteLength;for(n=0;n<this.pendingCaptions.length;n++)(t=this.pendingCaptions[n]).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(n=0;n<this.pendingMetadata.length;n++)(i=this.pendingMetadata[n]).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),n=0;n<r.captions.length;n++)t=r.captions[n],this.trigger("caption",t);for(n=0;n<r.metadata.length;n++)i=r.metadata[n],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,s=this,n=!0;bt.prototype.init.call(this),e=e||{},this.baseMediaDecodeTime=e.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var n={};this.transmuxPipeline_=n,n.type="aac",n.metadataStream=new Dt.MetadataStream,n.aacStream=new Ct,n.audioTimestampRolloverStream=new Dt.TimestampRolloverStream("audio"),n.timedMetadataTimestampRolloverStream=new Dt.TimestampRolloverStream("timed-metadata"),n.adtsStream=new Lt,n.coalesceStream=new St(e,n.metadataStream),n.headOfPipeline=n.aacStream,n.aacStream.pipe(n.audioTimestampRolloverStream).pipe(n.adtsStream),n.aacStream.pipe(n.timedMetadataTimestampRolloverStream).pipe(n.metadataStream).pipe(n.coalesceStream),n.metadataStream.on("timestamp",(function(e){n.aacStream.setTimestamp(e.timeStamp)})),n.aacStream.on("data",(function(a){"timed-metadata"!==a.type&&"audio"!==a.type||n.audioSegmentStream||(i=i||{timelineStartInfo:{baseMediaDecodeTime:s.baseMediaDecodeTime},codec:"adts",type:"audio"},n.coalesceStream.numberOfTracks++,n.audioSegmentStream=new Tt(i,e),n.audioSegmentStream.on("log",s.getLogTrigger_("audioSegmentStream")),n.audioSegmentStream.on("timingInfo",s.trigger.bind(s,"audioTimingInfo")),n.adtsStream.pipe(n.audioSegmentStream).pipe(n.coalesceStream),s.trigger("trackinfo",{hasAudio:!!i,hasVideo:!!t}))})),n.coalesceStream.on("data",this.trigger.bind(this,"data")),n.coalesceStream.on("done",this.trigger.bind(this,"done")),Nt(this,n)},this.setupTsPipeline=function(){var n={};this.transmuxPipeline_=n,n.type="ts",n.metadataStream=new Dt.MetadataStream,n.packetStream=new Dt.TransportPacketStream,n.parseStream=new Dt.TransportParseStream,n.elementaryStream=new Dt.ElementaryStream,n.timestampRolloverStream=new Dt.TimestampRolloverStream,n.adtsStream=new Lt,n.h264Stream=new Pt,n.captionStream=new Dt.CaptionStream(e),n.coalesceStream=new St(e,n.metadataStream),n.headOfPipeline=n.packetStream,n.packetStream.pipe(n.parseStream).pipe(n.elementaryStream).pipe(n.timestampRolloverStream),n.timestampRolloverStream.pipe(n.h264Stream),n.timestampRolloverStream.pipe(n.adtsStream),n.timestampRolloverStream.pipe(n.metadataStream).pipe(n.coalesceStream),n.h264Stream.pipe(n.captionStream).pipe(n.coalesceStream),n.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=s.baseMediaDecodeTime):(t=a.tracks[r]).timelineStartInfo.baseMediaDecodeTime=s.baseMediaDecodeTime;t&&!n.videoSegmentStream&&(n.coalesceStream.numberOfTracks++,n.videoSegmentStream=new _t(t,e),n.videoSegmentStream.on("log",s.getLogTrigger_("videoSegmentStream")),n.videoSegmentStream.on("timelineStartInfo",(function(t){i&&!e.keepOriginalTimestamps&&(i.timelineStartInfo=t,n.audioSegmentStream.setEarliestDts(t.dts-s.baseMediaDecodeTime))})),n.videoSegmentStream.on("processedGopsInfo",s.trigger.bind(s,"gopInfo")),n.videoSegmentStream.on("segmentTimingInfo",s.trigger.bind(s,"videoSegmentTimingInfo")),n.videoSegmentStream.on("baseMediaDecodeTime",(function(e){i&&n.audioSegmentStream.setVideoBaseMediaDecodeTime(e)})),n.videoSegmentStream.on("timingInfo",s.trigger.bind(s,"videoTimingInfo")),n.h264Stream.pipe(n.videoSegmentStream).pipe(n.coalesceStream)),i&&!n.audioSegmentStream&&(n.coalesceStream.numberOfTracks++,n.audioSegmentStream=new Tt(i,e),n.audioSegmentStream.on("log",s.getLogTrigger_("audioSegmentStream")),n.audioSegmentStream.on("timingInfo",s.trigger.bind(s,"audioTimingInfo")),n.audioSegmentStream.on("segmentTimingInfo",s.trigger.bind(s,"audioSegmentTimingInfo")),n.adtsStream.pipe(n.audioSegmentStream).pipe(n.coalesceStream)),s.trigger("trackinfo",{hasAudio:!!i,hasVideo:!!t})}})),n.coalesceStream.on("data",this.trigger.bind(this,"data")),n.coalesceStream.on("id3Frame",(function(e){e.dispatchType=n.metadataStream.dispatchType,s.trigger("id3Frame",e)})),n.coalesceStream.on("caption",this.trigger.bind(this,"caption")),n.coalesceStream.on("done",this.trigger.bind(this,"done")),Nt(this,n)},this.setBaseMediaDecodeTime=function(s){var n=this.transmuxPipeline_;e.keepOriginalTimestamps||(this.baseMediaDecodeTime=s),i&&(i.timelineStartInfo.dts=void 0,i.timelineStartInfo.pts=void 0,At.clearDtsInfo(i),n.audioTimestampRolloverStream&&n.audioTimestampRolloverStream.discontinuity()),t&&(n.videoSegmentStream&&(n.videoSegmentStream.gopCache_=[]),t.timelineStartInfo.dts=void 0,t.timelineStartInfo.pts=void 0,At.clearDtsInfo(t),n.captionStream.reset()),n.timestampRolloverStream&&n.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(n){var t=kt(e);t&&"aac"!==this.transmuxPipeline_.type?this.setupAacPipeline():t||"ts"===this.transmuxPipeline_.type||this.setupTsPipeline(),n=!1}this.transmuxPipeline_.headOfPipeline.push(e)},this.flush=function(){n=!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,Gt,Wt,Vt={Transmuxer:bt,VideoSegmentStream:_t,AudioSegmentStream:Tt,AUDIO_PROPERTIES:Ot,VIDEO_PROPERTIES:Rt,generateSegmentTimingInfo:Ft},Ht=function(e){return e>>>0},Xt=function(e){var t="";return t+=String.fromCharCode(e[0]),t+=String.fromCharCode(e[1]),(t+=String.fromCharCode(e[2]))+String.fromCharCode(e[3])},jt=Ht,zt=Xt,Yt=function(e,t){var i,s,n,a,r,o=[];if(!t.length)return null;for(i=0;i<e.byteLength;)s=jt(e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]),n=zt(e.subarray(i+4,i+8)),a=s>1?i+s:e.byteLength,n===t[0]&&(1===t.length?o.push(e.subarray(i+8,a)):(r=Yt(e.subarray(i+8,a),t.slice(1))).length&&(o=o.concat(r))),i=a;return o},Qt=Ht,Kt=V.getUint64,Jt=function(e){var t={version:e[0],flags:new Uint8Array(e.subarray(1,4))};return 1===t.version?t.baseMediaDecodeTime=Kt(e.subarray(4)):t.baseMediaDecodeTime=Qt(e[4]<<24|e[5]<<16|e[6]<<8|e[7]),t},Zt=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]}},ei=function(e){var t,i={version:e[0],flags:new Uint8Array(e.subarray(1,4)),samples:[]},s=new DataView(e.buffer,e.byteOffset,e.byteLength),n=1&i.flags[2],a=4&i.flags[2],r=1&i.flags[1],o=2&i.flags[1],d=4&i.flags[1],l=8&i.flags[1],u=s.getUint32(4),h=8;for(n&&(i.dataOffset=s.getInt32(h),h+=4),a&&u&&(t={flags:Zt(e.subarray(h,h+4))},h+=4,r&&(t.duration=s.getUint32(h),h+=4),o&&(t.size=s.getUint32(h),h+=4),l&&(1===i.version?t.compositionTimeOffset=s.getInt32(h):t.compositionTimeOffset=s.getUint32(h),h+=4),i.samples.push(t),u--);u--;)t={},r&&(t.duration=s.getUint32(h),h+=4),o&&(t.size=s.getUint32(h),h+=4),d&&(t.flags=Zt(e.subarray(h,h+4)),h+=4),l&&(1===i.version?t.compositionTimeOffset=s.getInt32(h):t.compositionTimeOffset=s.getUint32(h),h+=4),i.samples.push(t);return i},ti=function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength),s={version:e[0],flags:new Uint8Array(e.subarray(1,4)),trackId:i.getUint32(4)},n=1&s.flags[2],a=2&s.flags[2],r=8&s.flags[2],o=16&s.flags[2],d=32&s.flags[2],l=65536&s.flags[0],u=131072&s.flags[0];return t=8,n&&(t+=4,s.baseDataOffset=i.getUint32(12),t+=4),a&&(s.sampleDescriptionIndex=i.getUint32(t),t+=4),r&&(s.defaultSampleDuration=i.getUint32(t),t+=4),o&&(s.defaultSampleSize=i.getUint32(t),t+=4),d&&(s.defaultSampleFlags=i.getUint32(t)),l&&(s.durationIsEmpty=!0),!n&&u&&(s.baseDataOffsetIsMoof=!0),s},ii=(qt="undefined"!=typeof window?window:void 0!==e?e:"undefined"!=typeof self?self:{},ce.discardEmulationPreventionBytes),si=Ae.CaptionStream,ni=Yt,ai=Jt,ri=ei,oi=ti,di=qt,li=function(e,t){for(var i=e,s=0;s<t.length;s++){var n=t[s];if(i<n.size)return n;i-=n.size}return null},ui=function(){var e,t,i,s,n,a,r=!1;this.isInitialized=function(){return r},this.init=function(t){e=new si,r=!0,a=!!t&&t.isPartial,e.on("data",(function(e){e.startTime=e.startPts/s,e.endTime=e.endPts/s,n.captions.push(e),n.captionStreams[e.stream]=!0})),e.on("log",(function(e){n.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]&&s===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],s=r[i];else if(null===i||!s)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 s=function(e,t){var i=ni(e,["moof","traf"]),s=ni(e,["mdat"]),n={},a=[];return s.forEach((function(e,t){var s=i[t];a.push({mdat:e,traf:s})})),a.forEach((function(e){var i,s,a=e.mdat,r=e.traf,o=ni(r,["tfhd"]),d=oi(o[0]),l=d.trackId,u=ni(r,["tfdt"]),h=u.length>0?ai(u[0]).baseMediaDecodeTime:0,c=ni(r,["trun"]);t===l&&c.length>0&&(i=function(e,t,i){var s=t,n=i.defaultSampleDuration||0,a=i.defaultSampleSize||0,r=i.trackId,o=[];return e.forEach((function(e){var t=ri(e).samples;t.forEach((function(e){void 0===e.duration&&(e.duration=n),void 0===e.size&&(e.size=a),e.trackId=r,e.dts=s,void 0===e.compositionTimeOffset&&(e.compositionTimeOffset=0),"bigint"==typeof s?(e.pts=s+di.BigInt(e.compositionTimeOffset),s+=di.BigInt(e.duration)):(e.pts=s+e.compositionTimeOffset,s+=e.duration)})),o=o.concat(t)})),o}(c,h,d),s=function(e,t,i){var s,n,a,r,o=new DataView(e.buffer,e.byteOffset,e.byteLength),d={logs:[],seiNals:[]};for(n=0;n+4<e.length;n+=a)if(a=o.getUint32(n),n+=4,!(a<=0))switch(31&e[n]){case 6:var l=e.subarray(n+1,n+1+a),u=li(n,t);if(s={nalUnitType:"sei_rbsp",size:a,data:l,escapedRBSP:ii(l),trackId:i},u)s.pts=u.pts,s.dts=u.dts,r=u;else{if(!r){d.logs.push({level:"warn",message:"We've encountered a nal unit without data at "+n+" for trackId "+i+". See mux.js#223."});break}s.pts=r.pts,s.dts=r.dts}d.seiNals.push(s)}return d}(a,i,l),n[l]||(n[l]={seiNals:[],logs:[]}),n[l].seiNals=n[l].seiNals.concat(s.seiNals),n[l].logs=n[l].logs.concat(s.logs))})),n}(e,t)[t]||{};return{seiNals:s.seiNals,logs:s.logs,timescale:i}}(e,i,s),o&&o.logs&&(n.logs=n.logs.concat(o.logs)),null!==o&&o.seiNals?(this.pushNals(o.seiNals),this.flushStream(),n):n.logs.length?{logs:n.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(){n.captions=[],n.captionStreams={},n.logs=[]},this.resetCaptionStream=function(){if(!this.isInitialized())return null;e.reset()},this.clearAllCaptions=function(){this.clearParsedCaptions(),this.resetCaptionStream()},this.reset=function(){t=[],i=null,s=null,n?this.clearParsedCaptions():n={captions:[],captionStreams:{},logs:[]},this.resetCaptionStream()},this.reset()},hi=function(e){for(var t=0,i=String.fromCharCode(e[t]),s="";"\0"!==i;)s+=i,t++,i=String.fromCharCode(e[t]);return s+i},ci=V.getUint64,pi=function(e){return void 0!==e||null!==e},mi={parseEmsgBox:function(e){var t,i,s,n,a,r,o,d=4,l=e[0];if(0===l)d+=(t=hi(e.subarray(d))).length,d+=(i=hi(e.subarray(d))).length,s=(u=new DataView(e.buffer)).getUint32(d),d+=4,a=u.getUint32(d),d+=4,r=u.getUint32(d),d+=4,o=u.getUint32(d),d+=4;else if(1===l){var u;s=(u=new DataView(e.buffer)).getUint32(d),d+=4,n=ci(e.subarray(d)),d+=8,r=u.getUint32(d),d+=4,o=u.getUint32(d),d+=4,d+=(t=hi(e.subarray(d))).length,d+=(i=hi(e.subarray(d))).length}var h={scheme_id_uri:t,value:i,timescale:s||1,presentation_time:n,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,s=0===e&&pi(t.presentation_time_delta)&&i,n=1===e&&pi(t.presentation_time)&&i;return!(e>1)&&s||n}(l,h)?h:void 0},scaleTime:function(e,t,i,s){return e||0===e?e/t:s+i/t}},gi=Ht,fi=function(e){return("00"+e.toString(16)).slice(-2)},yi=Yt,_i=Xt,Ti=mi,bi=V.getUint64,Si=qt,vi=qe.parseId3Frames;$t=function(e,t){var i=yi(t,["moof","traf"]).reduce((function(t,i){var s,n=yi(i,["tfhd"])[0],a=gi(n[4]<<24|n[5]<<16|n[6]<<8|n[7]),r=e[a]||9e4,o=yi(i,["tfdt"])[0],d=new DataView(o.buffer,o.byteOffset,o.byteLength);let l;return"bigint"==typeof(s=1===o[0]?bi(o.subarray(4,12)):d.getUint32(4))?l=s/Si.BigInt(r):"number"!=typeof s||isNaN(s)||(l=s/r),l<Number.MAX_SAFE_INTEGER&&(l=Number(l)),l<t&&(t=l),t}),1/0);return"bigint"==typeof i||isFinite(i)?i:0},Wt=function(e){var t=0===e[0]?12:20;return gi(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])},Gt=function(e){var t=yi(e,["moov","trak"]),i=[];return t.forEach((function(e){var t,s,n={},a=yi(e,["tkhd"])[0];a&&(s=(t=new DataView(a.buffer,a.byteOffset,a.byteLength)).getUint8(0),n.id=0===s?t.getUint32(12):t.getUint32(20));var r=yi(e,["mdia","hdlr"])[0];if(r){var o=_i(r.subarray(8,12));n.type="vide"===o?"video":"soun"===o?"audio":o}var d=yi(e,["mdia","minf","stbl","stsd"])[0];if(d){var l=d.subarray(8);n.codec=_i(l.subarray(4,8));var u,h=yi(l,[n.codec])[0];h&&(/^[asm]vc[1-9]$/i.test(n.codec)?(u=h.subarray(78),"avcC"===_i(u.subarray(4,8))&&u.length>11?(n.codec+=".",n.codec+=fi(u[9]),n.codec+=fi(u[10]),n.codec+=fi(u[11])):n.codec="avc1.4d400d"):/^mp4[a,v]$/i.test(n.codec)?(u=h.subarray(28),"esds"===_i(u.subarray(4,8))&&u.length>20&&0!==u[19]?(n.codec+="."+fi(u[19]),n.codec+="."+fi(u[20]>>>2&63).replace(/^0/,"")):n.codec="mp4a.40.2"):n.codec=n.codec.toLowerCase())}var c=yi(e,["mdia","mdhd"])[0];c&&(n.timescale=Wt(c)),i.push(n)})),i};var wi=$t,Ii=Gt,Ei=function(e,t=0){return yi(e,["emsg"]).map((e=>{var i=Ti.parseEmsgBox(new Uint8Array(e)),s=vi(i.message_data);return{cueTime:Ti.scaleTime(i.presentation_time,i.timescale,i.presentation_time_delta,t),duration:Ti.scaleTime(i.event_duration,i.timescale),frames:s}}))},Ai=De,Di=function(e){var t=31&e[1];return(t<<=8)|e[2]},xi=function(e){return!!(64&e[1])},Li=function(e){var t=0;return(48&e[3])>>>4>1&&(t+=e[4]+1),t},Pi=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}},Ci={parseType:function(e,t){var i=Di(e);return 0===i?"pat":i===t?"pmt":t?"pes":null},parsePat:function(e){var t=xi(e),i=4+Li(e);return t&&(i+=e[i]+1),(31&e[i+10])<<8|e[i+11]},parsePmt:function(e){var t={},i=xi(e),s=4+Li(e);if(i&&(s+=e[s]+1),1&e[s+5]){var n;n=3+((15&e[s+1])<<8|e[s+2])-4;for(var a=12+((15&e[s+10])<<8|e[s+11]);a<n;){var r=s+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:xi,parsePesType:function(e,t){switch(t[Di(e)]){case Ai.H264_STREAM_TYPE:return"video";case Ai.ADTS_STREAM_TYPE:return"audio";case Ai.METADATA_STREAM_TYPE:return"timed-metadata";default:return null}},parsePesTime:function(e){if(!xi(e))return null;var t=4+Li(e);if(t>=e.byteLength)return null;var i,s=null;return 192&(i=e[t+7])&&((s={}).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,s.pts*=4,s.pts+=(6&e[t+13])>>>1,s.dts=s.pts,64&i&&(s.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,s.dts*=4,s.dts+=(6&e[t+18])>>>1)),s},videoPacketContainsKeyFrame:function(e){for(var t=4+Li(e),i=e.subarray(t),s=0,n=0,a=!1;n<i.byteLength-3;n++)if(1===i[n+2]){s=n+5;break}for(;s<i.byteLength;)switch(i[s]){case 0:if(0!==i[s-1]){s+=2;break}if(0!==i[s-2]){s++;break}n+3!==s-2&&"slice_layer_without_partitioning_rbsp_idr"===Pi(31&i[n+3])&&(a=!0);do{s++}while(1!==i[s]&&s<i.length);n=s-2,s+=3;break;case 1:if(0!==i[s-1]||0!==i[s-2]){s+=3;break}"slice_layer_without_partitioning_rbsp_idr"===Pi(31&i[n+3])&&(a=!0),n=s-2,s+=3;break;default:s+=3}return i=i.subarray(n),s-=n,n=0,i&&i.byteLength>3&&"slice_layer_without_partitioning_rbsp_idr"===Pi(31&i[n+3])&&(a=!0),a}},ki=De,Ui=Ue.handleRollover,Oi={};Oi.ts=Ci,Oi.aac=ft;var Ri=oe.ONE_SECOND_IN_TS,Mi=188,Ni=71,Bi=function(e,t,i){for(var s,n,a,r,o=0,d=Mi,l=!1;d<=e.byteLength;)if(e[o]!==Ni||e[d]!==Ni&&d!==e.byteLength)o++,d++;else{if(s=e.subarray(o,d),"pes"===Oi.ts.parseType(s,t.pid)&&(n=Oi.ts.parsePesType(s,t.table),a=Oi.ts.parsePayloadUnitStartIndicator(s),"audio"===n&&a&&(r=Oi.ts.parsePesTime(s))&&(r.type="audio",i.audio.push(r),l=!0)),l)break;o+=Mi,d+=Mi}for(o=(d=e.byteLength)-Mi,l=!1;o>=0;)if(e[o]!==Ni||e[d]!==Ni&&d!==e.byteLength)o--,d--;else{if(s=e.subarray(o,d),"pes"===Oi.ts.parseType(s,t.pid)&&(n=Oi.ts.parsePesType(s,t.table),a=Oi.ts.parsePayloadUnitStartIndicator(s),"audio"===n&&a&&(r=Oi.ts.parsePesTime(s))&&(r.type="audio",i.audio.push(r),l=!0)),l)break;o-=Mi,d-=Mi}},Fi=function(e,t,i){for(var s,n,a,r,o,d,l,u=0,h=Mi,c=!1,p={data:[],size:0};h<e.byteLength;)if(e[u]!==Ni||e[h]!==Ni)u++,h++;else{if(s=e.subarray(u,h),"pes"===Oi.ts.parseType(s,t.pid)&&(n=Oi.ts.parsePesType(s,t.table),a=Oi.ts.parsePayloadUnitStartIndicator(s),"video"===n&&(a&&!c&&(r=Oi.ts.parsePesTime(s))&&(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;)l=p.data.shift(),o.set(l,d),d+=l.byteLength;if(Oi.ts.videoPacketContainsKeyFrame(o)){var m=Oi.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(s),p.size+=s.byteLength}if(c&&i.firstKeyFrame)break;u+=Mi,h+=Mi}for(u=(h=e.byteLength)-Mi,c=!1;u>=0;)if(e[u]!==Ni||e[h]!==Ni)u--,h--;else{if(s=e.subarray(u,h),"pes"===Oi.ts.parseType(s,t.pid)&&(n=Oi.ts.parsePesType(s,t.table),a=Oi.ts.parsePayloadUnitStartIndicator(s),"video"===n&&a&&(r=Oi.ts.parsePesTime(s))&&(r.type="video",i.video.push(r),c=!0)),c)break;u-=Mi,h-=Mi}},qi=function(e,t){var i;return i=Oi.aac.isLikelyAacData(e)?function(e){for(var t,i=!1,s=0,n=null,a=null,r=0,o=0;e.length-o>=3;){switch(Oi.aac.parseType(e,o)){case"timed-metadata":if(e.length-o<10){i=!0;break}if((r=Oi.aac.parseId3TagSize(e,o))>e.length){i=!0;break}null===a&&(t=e.subarray(o,o+r),a=Oi.aac.parseAacTimestamp(t)),o+=r;break;case"audio":if(e.length-o<7){i=!0;break}if((r=Oi.aac.parseAdtsSize(e,o))>e.length){i=!0;break}null===n&&(t=e.subarray(o,o+r),n=Oi.aac.parseSampleRate(t)),s++,o+=r;break;default:o++}if(i)return null}if(null===n||null===a)return null;var d=Ri/n;return{audio:[{type:"audio",dts:a,pts:a},{type:"audio",dts:a+1024*s*d,pts:a+1024*s*d}]}}(e):function(e){var t={pid:null,table:null},i={};for(var s in function(e,t){for(var i,s=0,n=Mi;n<e.byteLength;)if(e[s]!==Ni||e[n]!==Ni)s++,n++;else{switch(i=e.subarray(s,n),Oi.ts.parseType(i,t.pid)){case"pat":t.pid=Oi.ts.parsePat(i);break;case"pmt":var a=Oi.ts.parsePmt(i);t.table=t.table||{},Object.keys(a).forEach((function(e){t.table[e]=a[e]}))}s+=Mi,n+=Mi}}(e,t),t.table)if(t.table.hasOwnProperty(s))switch(t.table[s]){case ki.H264_STREAM_TYPE:i.video=[],Fi(e,t,i),0===i.video.length&&delete i.video;break;case ki.ADTS_STREAM_TYPE:i.audio=[],Bi(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=Ui(e.dts,i),e.pts=Ui(e.pts,i),e.dtsTime=e.dts/Ri,e.ptsTime=e.pts/Ri}))}if(e.video&&e.video.length){var s=t;if((void 0===s||isNaN(s))&&(s=e.video[0].dts),e.video.forEach((function(e){e.dts=Ui(e.dts,s),e.pts=Ui(e.pts,s),e.dtsTime=e.dts/Ri,e.ptsTime=e.pts/Ri})),e.firstKeyFrame){var n=e.firstKeyFrame;n.dts=Ui(n.dts,s),n.pts=Ui(n.pts,s),n.dtsTime=n.dts/Ri,n.ptsTime=n.pts/Ri}}}(i,t),i):null};class $i{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 s=t.data;t.data=s.buffer,e.postMessage({action:"data",segment:t,byteOffset:s.byteOffset,byteLength:s.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 ui,this.captionParser.init());const t=new Uint8Array(e.data,e.byteOffset,e.byteLength),i=this.captionParser.parse(t,e.trackIds,e.timescales);this.self.postMessage({action:"mp4Captions",captions:i&&i.captions||[],logs:i&&i.logs||[],data:t.buffer},[t.buffer])}probeMp4StartTime({timescales:e,data:t}){const i=wi(e,t);this.self.postMessage({action:"probeMp4StartTime",startTime:i,data:t},[t.buffer])}probeMp4Tracks({data:e}){const t=Ii(e);this.self.postMessage({action:"probeMp4Tracks",tracks:t,data:e},[e.buffer])}probeEmsgID3({data:e,offset:t}){const i=Ei(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,s=qi(e,i);let n=null;s&&(n={hasVideo:s.video&&2===s.video.length||!1,hasAudio:s.audio&&2===s.audio.length||!1},n.hasVideo&&(n.videoStart=s.video[0].ptsTime),n.hasAudio&&(n.audioStart=s.audio[0].ptsTime)),this.self.postMessage({action:"probeTs",result:n,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 $i(self,e.data.options):(this.messageHandlers||(this.messageHandlers=new $i(self)),e.data&&e.data.action&&"init"!==e.data.action&&this.messageHandlers[e.data.action]&&this.messageHandlers[e.data.action](e.data))}})));var Ti=gi(_i);const bi=e=>{const{transmuxer:t,bytes:i,audioAppendStart:s,gopsToAlignWith:n,remux:a,onData:r,onTrackInfo:o,onAudioTimingInfo:d,onVideoTimingInfo:l,onVideoSegmentTimingInfo:u,onAudioSegmentTimingInfo:h,onId3:c,onCaptions:p,onDone:m,onEndedTimeline:g,onTransmuxerLog:f,isEndOfTimeline:y}=e,_={buffer:[]};let T=y;if(t.onmessage=i=>{t.currentTransmux===e&&("data"===i.data.action&&((e,t,i)=>{const{type:s,initSegment:n,captions:a,captionStreams:r,metadata:o,videoFrameDtsTime:d,videoFramePtsTime:l}=e.data.segment;t.buffer.push({captions:a,captionStreams:r,metadata:o});const u=e.data.segment.boxes||{data:e.data.segment.data},h={type:s,data:new Uint8Array(u.data,u.data.byteOffset,u.data.byteLength),initSegment:new Uint8Array(n.data,n.byteOffset,n.byteLength)};void 0!==d&&(h.videoFrameDtsTime=d),void 0!==l&&(h.videoFramePtsTime=l),i(h)})(i,_,r),"trackinfo"===i.data.action&&o(i.data.trackInfo),"gopInfo"===i.data.action&&((e,t)=>{t.gopInfo=e.data.gopInfo})(i,_),"audioTimingInfo"===i.data.action&&d(i.data.audioTimingInfo),"videoTimingInfo"===i.data.action&&l(i.data.videoTimingInfo),"videoSegmentTimingInfo"===i.data.action&&u(i.data.videoSegmentTimingInfo),"audioSegmentTimingInfo"===i.data.action&&h(i.data.audioSegmentTimingInfo),"id3Frame"===i.data.action&&c([i.data.id3Frame],i.data.id3Frame.dispatchType),"caption"===i.data.action&&p(i.data.caption),"endedtimeline"===i.data.action&&(T=!1,g()),"log"===i.data.action&&f(i.data.log),"transmuxed"===i.data.type&&(T||(t.onmessage=null,(({transmuxedData:e,callback:t})=>{e.buffer=[],t(e)})({transmuxedData:_,callback:m}),Si(t))))},s&&t.postMessage({action:"setAudioAppendStart",appendStart:s}),Array.isArray(n)&&t.postMessage({action:"alignGopsWith",gopsToAlignWith:n}),void 0!==a&&t.postMessage({action:"setRemux",remux:a}),i.byteLength){const e=i instanceof ArrayBuffer?i:i.buffer,s=i instanceof ArrayBuffer?0:i.byteOffset;t.postMessage({action:"push",data:e,byteOffset:s,byteLength:i.byteLength},[e])}y&&t.postMessage({action:"endTimeline"}),t.postMessage({action:"flush"})},Si=e=>{e.currentTransmux=null,e.transmuxQueue.length&&(e.currentTransmux=e.transmuxQueue.shift(),"function"==typeof e.currentTransmux?e.currentTransmux():bi(e.currentTransmux))},vi=(e,t)=>{e.postMessage({action:t}),Si(e)};var wi=e=>{((e,t)=>{if(!t.currentTransmux)return t.currentTransmux=e,void vi(t,e);t.transmuxQueue.push(vi.bind(null,t,e))})("reset",e)};const Ii=function(e){const t=e.transmuxer,i=e.endAction||e.action,s=e.callback,n=a({},e,{endAction:null,transmuxer:null,callback:null}),r=n=>{n.data.action===i&&(t.removeEventListener("message",r),n.data.data&&(n.data.data=new Uint8Array(n.data.data,e.byteOffset||0,e.byteLength||n.data.data.byteLength),e.data&&(e.data=n.data.data)),s(n.data))};if(t.addEventListener("message",r),e.data){const i=e.data instanceof ArrayBuffer;n.byteOffset=i?0:e.data.byteOffset,n.byteLength=e.data.byteLength;const s=[i?e.data:e.data.buffer];t.postMessage(n,s)}else t.postMessage(n)},Ei=-101,Ai=-102,Di=e=>{e.forEach((e=>{e.abort()}))},xi=(e,t)=>t.timedout?{status:t.status,message:"HLS request timed-out at URL: "+t.uri,code:Ei,xhr:t}:t.aborted?{status:t.status,message:"HLS request aborted at URL: "+t.uri,code:Ai,xhr:t}:e?{status:t.status,message:"HLS request errored at URL: "+t.uri,code:2,xhr:t}:"arraybuffer"===t.responseType&&0===t.response.byteLength?{status:t.status,message:"Empty HLS response at URL: "+t.uri,code:2,xhr:t}:null,Li=(e,t,i)=>(s,n)=>{const a=n.response,r=xi(s,n);if(r)return i(r,e);if(16!==a.byteLength)return i({status:n.status,message:"Invalid HLS key at URL: "+n.uri,code:2,xhr:n},e);const o=new DataView(a),d=new Uint32Array([o.getUint32(0),o.getUint32(4),o.getUint32(8),o.getUint32(12)]);for(let e=0;e<t.length;e++)t[e].bytes=d;return i(null,e)},Pi=(e,t)=>{const i=ai(e.map.bytes);if("mp4"!==i){const s=e.map.resolvedUri||e.map.uri;return t({internal:!0,message:`Found unsupported ${i||"unknown"} container for initialization segment at URL: ${s}`,code:2})}Ii({action:"probeMp4Tracks",data:e.map.bytes,transmuxer:e.transmuxer,callback:({tracks:i,data:s})=>(e.map.bytes=s,i.forEach((function(t){e.map.tracks=e.map.tracks||{},e.map.tracks[t.type]||(e.map.tracks[t.type]=t,"number"==typeof t.id&&t.timescale&&(e.map.timescales=e.map.timescales||{},e.map.timescales[t.id]=t.timescale))})),t(null))})},Ci=({segment:e,bytes:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:l,dataFn:u,doneFn:h,onTransmuxerLog:c})=>{const p=e.map&&e.map.tracks||{},m=Boolean(p.audio&&p.video);let g=s.bind(null,e,"audio","start");const f=s.bind(null,e,"audio","end");let y=s.bind(null,e,"video","start");const _=s.bind(null,e,"video","end");Ii({action:"probeTs",transmuxer:e.transmuxer,data:t,baseStartTime:e.baseStartTime,callback:s=>{e.bytes=t=s.data;const p=s.result;p&&(i(e,{hasAudio:p.hasAudio,hasVideo:p.hasVideo,isMuxed:m}),i=null),(e=>{if(!e.transmuxer.currentTransmux)return e.transmuxer.currentTransmux=e,void bi(e);e.transmuxer.transmuxQueue.push(e)})({bytes:t,transmuxer:e.transmuxer,audioAppendStart:e.audioAppendStart,gopsToAlignWith:e.gopsToAlignWith,remux:m,onData:t=>{t.type="combined"===t.type?"video":t.type,u(e,t)},onTrackInfo:t=>{i&&(m&&(t.isMuxed=!0),i(e,t))},onAudioTimingInfo:e=>{g&&void 0!==e.start&&(g(e.start),g=null),f&&void 0!==e.end&&f(e.end)},onVideoTimingInfo:e=>{y&&void 0!==e.start&&(y(e.start),y=null),_&&void 0!==e.end&&_(e.end)},onVideoSegmentTimingInfo:e=>{n(e)},onAudioSegmentTimingInfo:e=>{a(e)},onId3:(t,i)=>{r(e,t,i)},onCaptions:t=>{o(e,[t])},isEndOfTimeline:d,onEndedTimeline:()=>{l()},onTransmuxerLog:c,onDone:t=>{h&&(t.type="combined"===t.type?"video":t.type,h(null,e,t))}})}})},ki=({segment:e,bytes:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:l,dataFn:u,doneFn:h,onTransmuxerLog:c})=>{let p=new Uint8Array(t);if(function(e){return Wt(e,["moof"]).length>0}(p)){e.isFmp4=!0;const{tracks:n}=e.map,a={isFmp4:!0,hasVideo:!!n.video,hasAudio:!!n.audio};n.audio&&n.audio.codec&&"enca"!==n.audio.codec&&(a.audioCodec=n.audio.codec),n.video&&n.video.codec&&"encv"!==n.video.codec&&(a.videoCodec=n.video.codec),n.video&&n.audio&&(a.isMuxed=!0),i(e,a);const d=(t,i)=>{u(e,{data:p,type:a.hasAudio&&!a.isMuxed?"audio":"video"}),i&&i.length&&r(e,i),t&&t.length&&o(e,t),h(null,e,{})};Ii({action:"probeMp4StartTime",timescales:e.map.timescales,data:p,transmuxer:e.transmuxer,callback:({data:i,startTime:r})=>{t=i.buffer,e.bytes=p=i,a.hasAudio&&!a.isMuxed&&s(e,"audio","start",r),a.hasVideo&&s(e,"video","start",r),Ii({action:"probeEmsgID3",data:p,transmuxer:e.transmuxer,offset:r,callback:({emsgData:i,id3Frames:s})=>{t=i.buffer,e.bytes=p=i,n.video&&i.byteLength&&e.transmuxer?Ii({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:e.transmuxer,data:p,timescales:e.map.timescales,trackIds:[n.video.id],callback:i=>{t=i.data.buffer,e.bytes=p=i.data,i.logs.forEach((function(e){c(U(e,{stream:"mp4CaptionParser"}))})),d(i.captions,s)}}):d(void 0,s)}})}})}else if(e.transmuxer){if(void 0===e.container&&(e.container=ai(p)),"ts"!==e.container&&"aac"!==e.container)return i(e,{hasAudio:!1,hasVideo:!1}),void h(null,e,{});Ci({segment:e,bytes:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:l,dataFn:u,doneFn:h,onTransmuxerLog:c})}else h(null,e,{})},Ui=function({id:e,key:t,encryptedBytes:i,decryptionWorker:s},n){const a=t=>{if(t.data.source===e){s.removeEventListener("message",a);const e=t.data.decrypted;n(new Uint8Array(e.bytes,e.byteOffset,e.byteLength))}};let r;s.addEventListener("message",a),r=t.bytes.slice?t.bytes.slice():new Uint32Array(Array.prototype.slice.call(t.bytes)),s.postMessage(Ge({source:e,encrypted:i,key:r,iv:t.iv}),[i.buffer,r.buffer])},Oi=({xhr:e,xhrOptions:t,decryptionWorker:i,segment:s,abortFn:n,progressFn:a,trackInfoFn:r,timingInfoFn:o,videoSegmentTimingInfoFn:d,audioSegmentTimingInfoFn:l,id3Fn:u,captionsFn:h,isEndOfTimeline:c,endedTimelineFn:p,dataFn:m,doneFn:g,onTransmuxerLog:f})=>{const y=[],_=(({activeXhrs:e,decryptionWorker:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:l,dataFn:u,doneFn:h,onTransmuxerLog:c})=>{let p=0,m=!1;return(g,f)=>{if(!m){if(g)return m=!0,Di(e),h(g,f);if(p+=1,p===e.length){const p=function(){if(f.encryptedBytes)return(({decryptionWorker:e,segment:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:l,dataFn:u,doneFn:h,onTransmuxerLog:c})=>{Ui({id:t.requestId,key:t.key,encryptedBytes:t.encryptedBytes,decryptionWorker:e},(e=>{t.bytes=e,ki({segment:t,bytes:t.bytes,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:l,dataFn:u,doneFn:h,onTransmuxerLog:c})}))})({decryptionWorker:t,segment:f,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:l,dataFn:u,doneFn:h,onTransmuxerLog:c});ki({segment:f,bytes:f.bytes,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:l,dataFn:u,doneFn:h,onTransmuxerLog:c})};if(f.endOfAllRequests=Date.now(),f.map&&f.map.encryptedBytes&&!f.map.bytes)return Ui({decryptionWorker:t,id:f.requestId+"-init",encryptedBytes:f.map.encryptedBytes,key:f.map.key},(t=>{f.map.bytes=t,Pi(f,(t=>{if(t)return Di(e),h(t,f);p()}))}));p()}}}})({activeXhrs:y,decryptionWorker:i,trackInfoFn:r,timingInfoFn:o,videoSegmentTimingInfoFn:d,audioSegmentTimingInfoFn:l,id3Fn:u,captionsFn:h,isEndOfTimeline:c,endedTimelineFn:p,dataFn:m,doneFn:g,onTransmuxerLog:f});if(s.key&&!s.key.bytes){const i=[s.key];s.map&&!s.map.bytes&&s.map.key&&s.map.key.resolvedUri===s.key.resolvedUri&&i.push(s.map.key);const n=e(U(t,{uri:s.key.resolvedUri,responseType:"arraybuffer"}),Li(s,i,_));y.push(n)}if(s.map&&!s.map.bytes){if(s.map.key&&(!s.key||s.key.resolvedUri!==s.map.key.resolvedUri)){const i=e(U(t,{uri:s.map.key.resolvedUri,responseType:"arraybuffer"}),Li(s,[s.map.key],_));y.push(i)}const i=U(t,{uri:s.map.resolvedUri,responseType:"arraybuffer",headers:Ae(s.map)}),n=(({segment:e,finishProcessingFn:t})=>(i,s)=>{const n=xi(i,s);if(n)return t(n,e);const a=new Uint8Array(s.response);if(e.map.key)return e.map.encryptedBytes=a,t(null,e);e.map.bytes=a,Pi(e,(function(i){if(i)return i.xhr=s,i.status=s.status,t(i,e);t(null,e)}))})({segment:s,finishProcessingFn:_}),a=e(i,n);y.push(a)}const T=U(t,{uri:s.part&&s.part.resolvedUri||s.resolvedUri,responseType:"arraybuffer",headers:Ae(s)}),b=e(T,(({segment:e,finishProcessingFn:t,responseType:i})=>(s,n)=>{const a=xi(s,n);if(a)return t(a,e);const r="arraybuffer"!==i&&n.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})(n.responseText.substring(e.lastReachedChar||0)):n.response;return e.stats=(e=>({bandwidth:e.bandwidth,bytesReceived:e.bytesReceived||0,roundTripTime:e.roundTripTime||0}))(n),e.key?e.encryptedBytes=new Uint8Array(r):e.bytes=new Uint8Array(r),t(null,e)})({segment:s,finishProcessingFn:_,responseType:T.responseType}));b.addEventListener("progress",(({segment:e,progressFn:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:n,audioSegmentTimingInfoFn:a,id3Fn:r,captionsFn:o,isEndOfTimeline:d,endedTimelineFn:l,dataFn:u})=>i=>{if(!i.target.aborted)return e.stats=U(e.stats,(e=>{const t=e.target,i={bandwidth:1/0,bytesReceived:0,roundTripTime:Date.now()-t.requestTime||0};return i.bytesReceived=e.loaded,i.bandwidth=Math.floor(i.bytesReceived/i.roundTripTime*8*1e3),i})(i)),!e.stats.firstBytesReceivedAt&&e.stats.bytesReceived&&(e.stats.firstBytesReceivedAt=Date.now()),t(i,e)})({segment:s,progressFn:a,trackInfoFn:r,timingInfoFn:o,videoSegmentTimingInfoFn:d,audioSegmentTimingInfoFn:l,id3Fn:u,captionsFn:h,isEndOfTimeline:c,endedTimelineFn:p,dataFn:m})),y.push(b);const S={};return y.forEach((e=>{e.addEventListener("loadend",(({loadendState:e,abortFn:t})=>i=>{i.target.aborted&&t&&!e.calledAbortFn&&(t(),e.calledAbortFn=!0)})({loadendState:S,abortFn:n}))})),()=>Di(y)},Ri=c("CodecUtils"),Mi=(e,t)=>{const i=t.attributes||{};return e&&e.mediaGroups&&e.mediaGroups.AUDIO&&i.AUDIO&&e.mediaGroups.AUDIO[i.AUDIO]},Ni=function(e){const t={};return e.forEach((({mediaType:e,type:i,details:s})=>{t[e]=t[e]||[],t[e].push(A(`${i}${s}`))})),Object.keys(t).forEach((function(e){if(t[e].length>1)return Ri(`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},Bi=function(e){let t=0;return e.audio&&t++,e.video&&t++,t},Fi=function(e,t){const i=t.attributes||{},s=Ni(function(e){const t=e.attributes||{};if(t.CODECS)return D(t.CODECS)}(t)||[]);if(Mi(e,t)&&!s.audio&&!((e,t)=>{if(!Mi(e,t))return!0;const i=t.attributes||{},s=e.mediaGroups.AUDIO[i.AUDIO];for(const e in s)if(!s[e].uri&&!s[e].playlists)return!0;return!1})(e,t)){const t=Ni(function(e,t){if(!e.mediaGroups.AUDIO||!t)return null;var i=e.mediaGroups.AUDIO[t];if(!i)return null;for(var s in i){var n=i[s];if(n.default&&n.playlists)return D(n.playlists[0].attributes.CODECS)}return null}(e,i.AUDIO)||[]);t.audio&&(s.audio=t.audio)}return s},qi=c("PlaylistSelector"),$i=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||""})},Gi=function(e,t){if(!e)return"";const i=window.getComputedStyle(e);return i?i[t]:""},Wi=function(e,t){const i=e.slice();e.sort((function(e,s){const n=t(e,s);return 0===n?i.indexOf(e)-i.indexOf(s):n}))},Vi=function(e,t){let i,s;return e.attributes.BANDWIDTH&&(i=e.attributes.BANDWIDTH),i=i||window.Number.MAX_VALUE,t.attributes.BANDWIDTH&&(s=t.attributes.BANDWIDTH),s=s||window.Number.MAX_VALUE,i-s};let Hi=function(e,t,i,s,n,a){if(!e)return;const r={bandwidth:t,width:i,height:s,limitRenditionByPlayerDimensions:n};let o=e.playlists;oe.isAudioOnly(e)&&(o=a.getAudioTrackPlaylists_(),r.audioOnly=!0);let d=o.map((e=>{let t;const i=e.attributes&&e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width,s=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:s,playlist:e}}));Wi(d,((e,t)=>e.bandwidth-t.bandwidth)),d=d.filter((e=>!oe.isIncompatible(e.playlist)));let l=d.filter((e=>oe.isEnabled(e.playlist)));l.length||(l=d.filter((e=>!oe.isDisabled(e.playlist))));const u=l.filter((e=>e.bandwidth*pi.BANDWIDTH_VARIANCE<t));let h=u[u.length-1];const c=u.filter((e=>e.bandwidth===h.bandwidth))[0];if(!1===n){const e=c||l[0]||d[0];if(e&&e.playlist){let t="sortedPlaylistReps";return c&&(t="bandwidthBestRep"),l[0]&&(t="enabledPlaylistReps"),qi(`choosing ${$i(e)} using ${t} with options`,r),e.playlist}return qi("could not choose a playlist with options",r),null}const p=u.filter((e=>e.width&&e.height));Wi(p,((e,t)=>e.width-t.width));const m=p.filter((e=>e.width===i&&e.height===s));h=m[m.length-1];const g=m.filter((e=>e.bandwidth===h.bandwidth))[0];let f,y,_,T;if(g||(f=p.filter((e=>e.width>i||e.height>s)),y=f.filter((e=>e.width===f[0].width&&e.height===f[0].height)),h=y[y.length-1],_=y.filter((e=>e.bandwidth===h.bandwidth))[0]),a.leastPixelDiffSelector){const e=p.map((e=>(e.pixelDiff=Math.abs(e.width-i)+Math.abs(e.height-s),e)));Wi(e,((e,t)=>e.pixelDiff===t.pixelDiff?t.bandwidth-e.bandwidth:e.pixelDiff-t.pixelDiff)),T=e[0]}const b=T||_||g||c||l[0]||d[0];if(b&&b.playlist){let e="sortedPlaylistReps";return T?e="leastPixelDiffRep":_?e="resolutionPlusOneRep":g?e="resolutionBestRep":c?e="bandwidthBestRep":l[0]&&(e="enabledPlaylistReps"),qi(`choosing ${$i(b)} using ${e} with options`,r),b.playlist}return qi("could not choose a playlist with options",r),null};const Xi=function(){const e=this.useDevicePixelRatio&&window.devicePixelRatio||1;return Hi(this.playlists.main,this.systemBandwidth,parseInt(Gi(this.tech_.el(),"width"),10)*e,parseInt(Gi(this.tech_.el(),"height"),10)*e,this.limitRenditionByPlayerDimensions,this.playlistController_)},ji={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"},zi=new Set(["id","class","startDate","duration","endDate","endOnNext","startTime","endTime","processDateRange"]),Yi=(e,t,i)=>{e.metadataTrack_||(e.metadataTrack_=i.addRemoteTextTrack({kind:"metadata",label:"Timed Metadata"},!1).track,n.default.browser.IS_ANY_SAFARI||(e.metadataTrack_.inBandMetadataTrackDispatchType=t))},Qi=function(e,t,i){let s,n;if(i&&i.cues)for(s=i.cues.length;s--;)n=i.cues[s],n.startTime>=e&&n.endTime<=t&&i.removeCue(n)};var Ki=9e4,Ji=Ki;const Zi=e=>"number"==typeof e&&isFinite(e),es=1/60,ts=e=>{const{startOfSegment:t,duration:i,segment:s,part:n,playlist:{mediaSequence:a,id:r,segments:o=[]},mediaIndex:d,partIndex:l,timeline:u}=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 l,m=e.segment.uri?"segment":"pre-segment",g=p?j({preloadSegment:s})-1:0;return`${m} [${a+d}/${a+h}]`+(p?` part [${l}/${g}]`:"")+` segment start/end [${s.start} => ${s.end}]`+(p?` part start/end [${n.start} => ${n.end}]`:"")+` startOfSegment [${t}]`+` duration [${i}]`+` timeline [${u}]`+` selected by [${c}]`+` playlist [${r}]`},is=e=>`${e}TimingInfo`,ss=({timelineChangeController:e,currentTimeline:t,segmentTimeline:i,loaderType:s,audioDisabled:n})=>{if(t===i)return!1;if("audio"===s){const t=e.lastTimelineChange({type:"main"});return!t||t.to!==i}if("main"===s&&n){const t=e.pendingTimelineChange({type:"audio"});return!t||t.to!==i}return!1},ns=({segmentDuration:e,maxDuration:t})=>!!e&&Math.round(e)>t+R;class as extends n.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_=c(`SegmentLoader[${this.loaderType_}]`),Object.defineProperty(this,"state",{get(){return this.state_},set(e){e!==this.state_&&(this.logger_(`${this.state_} -> ${e}`),this.state_=e,this.trigger("statechange"))}}),this.sourceUpdater_.on("ready",(()=>{this.hasEnoughInfoToAppend_()&&this.processCallQueue_()})),"main"===this.loaderType_&&this.timelineChangeController_.on("pendingtimelinechange",(()=>{this.hasEnoughInfoToAppend_()&&this.processCallQueue_()})),"audio"===this.loaderType_&&this.timelineChangeController_.on("timelinechange",(()=>{this.hasEnoughInfoToLoad_()&&this.processLoadQueue_(),this.hasEnoughInfoToAppend_()&&this.processCallQueue_()}))}createTransmuxer_(){return(e=>{const t=new Ti;t.currentTransmux=null,t.transmuxQueue=[];const i=t.terminate;return t.terminate=()=>(t.currentTransmux=null,t.transmuxQueue.length=0,i.call(t)),t.postMessage({action:"init",options:e}),t})({remux:!1,alignGopsAtEnd:this.safeAppend_,keepOriginalTimestamps:!0,parse708captions:this.parse708captions_,captionServices:this.captionServices_})}resetStats_(){this.mediaBytesTransferred=0,this.mediaRequests=0,this.mediaRequestsAborted=0,this.mediaRequestsTimedout=0,this.mediaRequestsErrored=0,this.mediaTransferDuration=0,this.mediaSecondsLoaded=0,this.mediaAppends=0}dispose(){this.trigger("dispose"),this.state="DISPOSED",this.pause(),this.abort_(),this.transmuxer_&&this.transmuxer_.terminate(),this.resetStats_(),this.checkBufferTimeout_&&window.clearTimeout(this.checkBufferTimeout_),this.syncController_&&this.triggerSyncInfoUpdate_&&this.syncController_.off("syncinfoupdate",this.triggerSyncInfoUpdate_),this.off()}setAudio(e){this.audioDisabled_=!e,e?this.appendInitSegment_.audio=!0:this.sourceUpdater_.removeAudio(0,this.duration_())}abort(){"WAITING"===this.state?(this.abort_(),this.state="READY",this.paused()||this.monitorBuffer_()):this.pendingSegment_&&(this.pendingSegment_=null)}abort_(){this.pendingSegment_&&this.pendingSegment_.abortRequests&&this.pendingSegment_.abortRequests(),this.pendingSegment_=null,this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_),this.waitingOnRemove_=!1,window.clearTimeout(this.quotaExceededErrorRetryTimeout_),this.quotaExceededErrorRetryTimeout_=null}checkForAbort_(e){return"APPENDING"!==this.state||this.pendingSegment_?!this.pendingSegment_||this.pendingSegment_.requestId!==e:(this.state="READY",!0)}error(e){return void 0!==e&&(this.logger_("error occurred:",e),this.error_=e),this.pendingSegment_=null,this.error_}endOfStream(){this.ended_=!0,this.transmuxer_&&wi(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:s}=e;if(i&&t&&!this.audioDisabled_&&!s)return this.sourceUpdater_.buffered();if(i)return this.sourceUpdater_.videoBuffered()}return this.sourceUpdater_.audioBuffered()}initSegmentForMap(e,t=!1){if(!e)return null;const i=We(e);let s=this.initSegments_[i];return t&&!s&&e.bytes&&(this.initSegments_[i]=s={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:e.bytes,tracks:e.tracks,timescales:e.timescales}),s||e}segmentKey(e,t=!1){if(!e)return null;const i=Ve(e);let s=this.keyCache_[i];this.cacheEncryptionKeys_&&t&&!s&&e.bytes&&(this.keyCache_[i]=s={resolvedUri:e.resolvedUri,bytes:e.bytes});const n={resolvedUri:(s||e).resolvedUri};return s&&(n.bytes=s.bytes),n}couldBeginLoading_(){return this.playlist_&&!this.paused()}load(){if(this.monitorBuffer_(),this.playlist_)return"INIT"===this.state&&this.couldBeginLoading_()?this.init_():void(!this.couldBeginLoading_()||"READY"!==this.state&&"INIT"!==this.state||(this.state="READY"))}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}playlist(e,t={}){if(!e)return;const i=this.playlist_,s=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 n=null;if(i&&(i.id?n=i.id:i.uri&&(n=i.uri)),this.logger_(`playlist update [${n} => ${e.id||e.uri}]`),this.syncController_.updateMediaSequenceMap(e,this.currentTime_(),this.loaderType_),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}}s&&(s.mediaIndex-=a,s.mediaIndex<0?(s.mediaIndex=null,s.partIndex=null):(s.mediaIndex>=0&&(s.segment=e.segments[s.mediaIndex]),s.partIndex>=0&&s.segment.parts&&(s.part=s.segment.parts[s.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.resyncLoader()}resyncLoader(){this.transmuxer_&&wi(this.transmuxer_),this.mediaIndex=null,this.partIndex=null,this.syncPoint_=null,this.isPendingTimestampOffset_=!1,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=(()=>{}),s=!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 n=1;const a=()=>{n--,0===n&&i()};!s&&this.audioDisabled_||(n++,this.sourceUpdater_.removeAudio(e,t,a)),(s||"main"===this.loaderType_)&&(this.gopBuffer_=((e,t,i,s)=>{const n=Math.ceil((t-s)*Ji),a=Math.ceil((i-s)*Ji),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<=n););return d=Math.max(d,0),r.splice(d,o-d+1),r})(this.gopBuffer_,e,t,this.timeMapping_),n++,this.sourceUpdater_.removeVideo(e,t,a));for(const i in this.inbandTextTracks_)Qi(e,t,this.inbandTextTracks_[i]);Qi(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_();e&&("number"==typeof e.timestampOffset&&(this.isPendingTimestampOffset_=!1,this.timelineChangeController_.pendingTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline})),this.loadSegment_(e))}isEndOfStream_(e=this.mediaIndex,t=this.playlist_,i=this.partIndex){if(!t||!this.mediaSource_)return!1;const s="number"==typeof e&&t.segments[e],n=e+1===t.segments.length,a=!s||!s.parts||i+1===s.parts.length;return t.endList&&"open"===this.mediaSource_.readyState&&n&&a}chooseNextRequest_(){const e=this.buffered_(),t=G(e)||0,i=W(e,this.currentTime_()),s=!this.hasPlayed_()&&i>=1,n=i>=this.goalBufferLength_(),a=this.playlist_.segments;if(!a.length||s||n)return null;this.syncPoint_=this.syncPoint_||this.syncController_.getSyncPoint(this.playlist_,this.duration_(),this.currentTimeline_,this.currentTime_(),this.loaderType_);const r={partIndex:null,mediaIndex:null,startOfSegment:null,playlist:this.playlist_,isSyncRequest:Boolean(!this.syncPoint_)};if(r.isSyncRequest)r.mediaIndex=function(e,t,i){t=t||[];const s=[];let n=0;for(let a=0;a<t.length;a++){const r=t[a];if(e===r.timeline&&(s.push(a),n+=r.duration,n>i))return a}return 0===s.length?0:s[s.length-1]}(this.currentTimeline_,a,t),this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${r.mediaIndex}`);else if(null!==this.mediaIndex){const e=a[this.mediaIndex],i="number"==typeof this.partIndex?this.partIndex:-1;r.startOfSegment=e.end?e.end:t,e.parts&&e.parts[i+1]?(r.mediaIndex=this.mediaIndex,r.partIndex=i+1):r.mediaIndex=this.mediaIndex+1}else{const{segmentIndex:e,startTime:i,partIndex:s}=oe.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,playlist:this.playlist_,currentTime:this.fetchAtBuffer_?t:this.currentTime_(),startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time});r.getMediaInfoForTime=this.fetchAtBuffer_?`bufferedEnd ${t}`:`currentTime ${this.currentTime_()}`,r.mediaIndex=e,r.startOfSegment=i,r.partIndex=s,this.logger_(`choose next request. Playlist switched and we have a sync point. Media Index: ${r.mediaIndex} `)}const o=a[r.mediaIndex];let d=o&&"number"==typeof r.partIndex&&o.parts&&o.parts[r.partIndex];if(!o||"number"==typeof r.partIndex&&!d)return null;"number"!=typeof r.partIndex&&o.parts&&(r.partIndex=0,d=o.parts[0]);const l=this.vhs_.playlists&&this.vhs_.playlists.main&&this.vhs_.playlists.main.independentSegments||this.playlist_.independentSegments;if(!i&&d&&!l&&!d.independent)if(0===r.partIndex){const e=a[r.mediaIndex-1],t=e.parts&&e.parts.length&&e.parts[e.parts.length-1];t&&t.independent&&(r.mediaIndex-=1,r.partIndex=e.parts.length-1,r.independent="previous segment")}else o.parts[r.partIndex-1].independent&&(r.partIndex-=1,r.independent="previous part");const u=this.mediaSource_&&"ended"===this.mediaSource_.readyState;return r.mediaIndex>=a.length-1&&u&&!this.seeking_()?null:(this.shouldForceTimestampOffsetAfterResync_&&(this.shouldForceTimestampOffsetAfterResync_=!1,r.forceTimestampOffset=!0,this.logger_("choose next request. Force timestamp offset after loader resync")),this.generateSegmentInfo_(r))}generateSegmentInfo_(e){const{independent:t,playlist:i,mediaIndex:s,startOfSegment:n,isSyncRequest:a,partIndex:r,forceTimestampOffset:o,getMediaInfoForTime:d}=e,l=i.segments[s],u="number"==typeof r&&l.parts[r],h={requestId:"segment-loader-"+Math.random(),uri:u&&u.resolvedUri||l.resolvedUri,mediaIndex:s,partIndex:u?r:null,isSyncRequest:a,startOfSegment:n,playlist:i,bytes:null,encryptedBytes:null,timestampOffset:null,timeline:l.timeline,duration:u&&u.duration||l.duration,segment:l,part:u,byteLength:0,transmuxer:this.transmuxer_,getMediaInfoForTime:d,independent:t},c=void 0!==o?o:this.isPendingTimestampOffset_;h.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:l.timeline,currentTimeline:this.currentTimeline_,startOfSegment:n,buffered:this.buffered_(),overrideCheck:c});const p=G(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 s=Math.ceil((t-i+3)*Ji);let n;for(n=0;n<e.length&&!(e[n].pts>s);n++);return e.slice(n)})(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_)),h}timestampOffsetForSegment_(e){return(({segmentTimeline:e,currentTimeline:t,startOfSegment:i,buffered:s,overrideCheck:n})=>n||e!==t?e<t?i:s.length?s.end(s.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,s=this.pendingSegment_.duration,n=oe.estimateSegmentRequestTime(s,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(n<=a)return;const r=function(e){const{main:t,currentTime:i,bandwidth:s,duration:n,segmentDuration:a,timeUntilRebuffer:r,currentTimeline:o,syncController:d}=e,l=t.playlists.filter((e=>!oe.isIncompatible(e)));let u=l.filter(oe.isEnabled);u.length||(u=l.filter((e=>!oe.isDisabled(e))));const h=u.filter(oe.hasAttribute.bind(null,"BANDWIDTH")).map((e=>{const t=d.getSyncPoint(e,n,o,i)?1:2;return{playlist:e,rebufferingImpact:oe.estimateSegmentRequestTime(a,s,e)*t-r}})),c=h.filter((e=>e.rebufferingImpact<=0));return Wi(c,((e,t)=>Vi(t.playlist,e.playlist))),c.length?c[0]:(Wi(h,((e,t)=>e.rebufferingImpact-t.rebufferingImpact)),h[0]||null)}({main:this.vhs_.playlists.main,currentTime:t,bandwidth:i,duration:this.duration_(),segmentDuration:s,timeUntilRebuffer:a,currentTimeline:this.currentTimeline_,syncController:this.syncController_});if(!r)return;const o=n-a-r.rebufferingImpact;let d=.5;a<=R&&(d=1),!r.playlist||r.playlist.uri===this.playlist_.uri||o<d||(this.bandwidth=r.playlist.attributes.BANDWIDTH*pi.BANDWIDTH_VARIANCE+1,this.trigger("earlyabort"))}handleAbort_(e){this.logger_(`Aborting ${ts(e)}`),this.mediaRequestsAborted+=1}handleProgress_(e,t){this.earlyAbortWhenNeeded_(t.stats),this.checkForAbort_(t.requestId)||this.trigger("progress")}handleTrackInfo_(e,t){this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId)||this.checkForIllegalMediaSwitch(t)||(t=t||{},function(e,t){if(!e&&!t||!e&&t||e&&!t)return!1;if(e===t)return!0;const i=Object.keys(e).sort(),s=Object.keys(t).sort();if(i.length!==s.length)return!1;for(let n=0;n<i.length;n++){const a=i[n];if(a!==s[n])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_()))}handleTimingInfo_(e,t,i,s){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;const n=this.pendingSegment_,a=is(t);n[a]=n[a]||{},n[a][i]=s,this.logger_(`timinginfo: ${t} - ${i} - ${s}`),this.hasEnoughInfoToAppend_()&&this.processCallQueue_()}handleCaptions_(e,t){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(0===t.length)return void this.logger_("SegmentLoader received no captions from a caption event");if(!this.pendingSegment_.hasAppendedData_)return void this.metadataQueue_.caption.push(this.handleCaptions_.bind(this,e,t));const i=null===this.sourceUpdater_.videoTimestampOffset()?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset(),s={};t.forEach((e=>{s[e.stream]=s[e.stream]||{startTime:1/0,captions:[],endTime:0};const t=s[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(s).forEach((e=>{const{startTime:t,endTime:n,captions:a}=s[e],r=this.inbandTextTracks_;this.logger_(`adding cues from ${t} -> ${n} for ${e}`),function(e,t,i){if(!e[i]){t.trigger({type:"usage",name:"vhs-608"});let s=i;/^cc708_/.test(i)&&(s="SERVICE"+i.split("_")[1]);const n=t.textTracks().getTrackById(s);if(n)e[i]=n;else{let n=i,a=i,r=!1;const o=(t.options_.vhs&&t.options_.vhs.captionServices||{})[s];o&&(n=o.label,a=o.language,r=o.default),e[i]=t.addRemoteTextTrack({kind:"captions",id:s,default:r,label:n,language:a},!1).track}}}(r,this.vhs_.tech_,e),Qi(t,n,r[e]),function({inbandTextTracks:e,captionArray:t,timestampOffset:i}){if(!t)return;const s=window.WebKitDataCue||window.VTTCue;t.forEach((t=>{const n=t.stream;t.content?t.content.forEach((a=>{const r=new s(t.startTime+i,t.endTime+i,a.text);r.line=a.line,r.align="left",r.position=a.position,r.positionAlign="line-left",e[n].addCue(r)})):e[n].addCue(new s(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_()&&ss({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:s,isMuxed:n}=t;return!(s&&!e.videoTimingInfo||i&&!this.audioDisabled_&&!n&&!e.audioTimingInfo||ss({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}))}handleData_(e,t){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(this.callQueue_.length||!this.hasEnoughInfoToAppend_())return void this.callQueue_.push(this.handleData_.bind(this,e,t));const i=this.pendingSegment_;if(this.setTimeMapping_(i.timeline),this.updateMediaSecondsLoaded_(i.part||i.segment),"closed"!==this.mediaSource_.readyState){if(e.map&&(e.map=this.initSegmentForMap(e.map,!0),i.segment.map=e.map),e.key&&this.segmentKey(e.key,!0),i.isFmp4=e.isFmp4,i.timingInfo=i.timingInfo||{},i.isFmp4)this.trigger("fmp4"),i.timingInfo.start=i[is(t.type)].start;else{const e=this.getCurrentMediaInfo_(),t="main"===this.loaderType_&&e&&e.hasVideo;let s;t&&(s=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:s,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:s}){if(i){const e=We(i);if(this.activeInitSegmentId_===e)return null;t=this.initSegmentForMap(i,!0).bytes,this.activeInitSegmentId_=e}return t&&this.appendInitSegment_[e]?(this.playlistOfLastInitSegment_[e]=s,this.appendInitSegment_[e]=!1,this.activeInitSegmentId_=null,t):null}handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i},s){const n=this.sourceUpdater_.audioBuffered(),a=this.sourceUpdater_.videoBuffered();n.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: "+$(n).join(", ")),a.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: "+$(a).join(", "));const r=n.length?n.start(0):0,o=n.length?n.end(n.length-1):0,d=a.length?a.start(0):0,l=a.length?a.end(a.length-1):0;if(o-r<=1&&l-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: ${$(n).join(", ")}, video buffer: ${$(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 u=this.currentTime_()-1;this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${u}`),this.remove(0,u,(()=>{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},s){s&&(22!==s.code?(this.logger_("Received non QUOTA_EXCEEDED_ERR on append",s),this.error(`${t} append of ${i.length}b failed for segment #${e.mediaIndex} in playlist ${e.playlist.id}`),this.trigger("appenderror")):this.handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i}))}appendToSourceBuffer_({segmentInfo:e,type:t,initSegment:i,data:s,bytes:n}){if(!n){const e=[s];let t=s.byteLength;i&&(e.unshift(i),t+=i.byteLength),n=(e=>{let t,i=0;return e.bytes&&(t=new Uint8Array(e.bytes),e.segments.forEach((e=>{t.set(e,i),i+=e.byteLength}))),t})({bytes:t,segments:e})}this.sourceUpdater_.appendBuffer({segmentInfo:e,type:t,bytes:n},this.handleAppendError_.bind(this,{segmentInfo:e,type:t,bytes:n}))}handleSegmentTimingInfo_(e,t,i){if(!this.pendingSegment_||t!==this.pendingSegment_.requestId)return;const s=this.pendingSegment_.segment,n=`${e}TimingInfo`;s[n]||(s[n]={}),s[n].transmuxerPrependedSeconds=i.prependedContentDuration||0,s[n].transmuxedPresentationStart=i.start.presentation,s[n].transmuxedDecodeStart=i.start.decode,s[n].transmuxedPresentationEnd=i.end.presentation,s[n].transmuxedDecodeEnd=i.end.decode,s[n].baseMediaDecodeTime=i.baseMediaDecodeTime}appendData_(e,t){const{type:i,data:s}=t;if(!s||!s.byteLength)return;if("audio"===i&&this.audioDisabled_)return;const n=this.getInitSegmentAndUpdateState_({type:i,initSegment:t.initSegment,playlist:e.playlist,map:e.isFmp4?e.segment.map:null});this.appendToSourceBuffer_({segmentInfo:e,type:i,initSegment:n,data:s})}loadSegment_(e){this.state="WAITING",this.pendingSegment_=e,this.trimBackBuffer_(e),"number"==typeof e.timestampOffset&&this.transmuxer_&&this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),this.hasEnoughInfoToLoad_()?this.updateTransmuxerAndRequestSegment_(e):this.loadQueue_.push((()=>{const t=a({},e,{forceTimestampOffset:!0});a(e,this.generateSegmentInfo_(t)),this.isPendingTimestampOffset_=!1,this.updateTransmuxerAndRequestSegment_(e)}))}updateTransmuxerAndRequestSegment_(e){this.shouldUpdateTransmuxerTimestampOffset_(e.timestampOffset)&&(this.gopBuffer_.length=0,e.gopsToAlignWith=[],this.timeMapping_=0,this.transmuxer_.postMessage({action:"reset"}),this.transmuxer_.postMessage({action:"setTimestampOffset",timestampOffset:e.timestampOffset}));const t=this.createSimplifiedSegmentObj_(e),i=this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex),s=null!==this.mediaIndex,n=e.timeline!==this.currentTimeline_&&e.timeline>0,a=i||s&&n;this.logger_(`Requesting ${ts(e)}`),t.map&&!t.map.bytes&&(this.logger_("going to request init segment."),this.appendInitSegment_={video:!0,audio:!0}),e.abortRequests=Oi({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:s})=>{this.logger_(`${ts(e)} logged from transmuxer stream ${s} as a ${i}: ${t}`)}})}trimBackBuffer_(e){const t=((e,t,i)=>{let s=t-pi.BACK_BUFFER_LENGTH;e.length&&(s=Math.max(s,e.start(0)));const n=t-i;return Math.min(n,s)})(this.seekable_(),this.currentTime_(),this.playlist_.targetDuration||10);t>0&&this.remove(0,t)}createSimplifiedSegmentObj_(e){const t=e.segment,i=e.part,s={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},n=e.playlist.segments[e.mediaIndex-1];if(n&&n.timeline===t.timeline&&(n.videoTimingInfo?s.baseStartTime=n.videoTimingInfo.transmuxedDecodeEnd:n.audioTimingInfo&&(s.baseStartTime=n.audioTimingInfo.transmuxedDecodeEnd)),t.key){const i=t.key.iv||new Uint32Array([0,0,0,e.mediaIndex+e.playlist.mediaSequence]);s.key=this.segmentKey(t.key),s.key.iv=i}return t.map&&(s.map=this.initSegmentForMap(t.map)),s}saveTransferStats_(e){this.mediaRequests+=1,e&&(this.mediaBytesTransferred+=e.bytesReceived,this.mediaTransferDuration+=e.roundTripTime)}saveBandwidthRelatedStats_(e,t){this.pendingSegment_.byteLength=t.bytesReceived,e<es?this.logger_(`Ignoring segment's bandwidth because its duration of ${e} is less than the min to record 0.016666666666666666`):(this.bandwidth=t.bandwidth,this.roundTrip=t.roundTripTime)}handleTimeout_(){this.mediaRequestsTimedout+=1,this.bandwidth=1,this.roundTrip=NaN,this.trigger("bandwidthupdate"),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===Ai)return;return this.pause(),e.code===Ei?void this.handleTimeout_():(this.mediaRequestsErrored+=1,this.error(e),void this.trigger("error"))}const s=this.pendingSegment_;this.saveBandwidthRelatedStats_(s.duration,t.stats),s.endOfAllRequests=t.endOfAllRequests,i.gopInfo&&(this.gopBuffer_=((e,t,i)=>{if(!t.length)return e;if(i)return t.slice();const s=t[0].pts;let n=0;for(;n<e.length&&!(e[n].pts>=s);n++);return e.slice(0,n).concat(t)})(this.gopBuffer_,i.gopInfo,this.safeAppend_)),this.state="APPENDING",this.trigger("appending"),this.waitForAppendsToComplete_(s)}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:s,currentVideoTimestampOffset:n,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===s+n?r.start:s}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:s,isMuxed:n}=t,a="main"===this.loaderType_&&s,r=!this.audioDisabled_&&i&&!n;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_&&this.trigger("appendsdone"),!this.pendingSegment_)return this.state="READY",void(this.paused()||this.monitorBuffer_());const e=this.pendingSegment_;this.updateTimingInfoEnd_(e),this.shouldSaveSegmentTimingInfo_&&this.syncController_.saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:"main"===this.loaderType_});const t=((e,t)=>{if("hls"!==t)return null;const i=(e=>{let t=0;return["video","audio"].forEach((function(i){const s=e[`${i}TimingInfo`];if(!s)return;const{start:n,end:a}=s;let r;"bigint"==typeof n||"bigint"==typeof a?r=window.BigInt(a)-window.BigInt(n):"number"==typeof n&&"number"==typeof a&&(r=a-n),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 s=e.playlist.targetDuration,n=ns({segmentDuration:i,maxDuration:2*s}),a=ns({segmentDuration:i,maxDuration:s}),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 ${s}. 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 n||a?{severity:n?"warn":"info",message:r}:null})(e,this.sourceType_);if(t&&("warn"===t.severity?n.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 ${ts(e)}`);this.logger_(`Appended ${ts(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,s=e.part,a=i.end&&this.currentTime_()-i.end>3*e.playlist.targetDuration,r=s&&s.end&&this.currentTime_()-s.end>3*e.playlist.partTargetDuration;if(a||r)return this.logger_(`bad ${a?"segment":"part"} ${ts(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<es)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,s=Math.floor(e.byteLength/i*8*1e3);this.throughput.rate+=(s-t)/++this.throughput.count}addSegmentMetadataCue_(e){if(!this.segmentMetadataTrack_)return;const t=e.segment,i=t.start,s=t.end;if(!Zi(i)||!Zi(s))return;Qi(i,s,this.segmentMetadataTrack_);const n=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:s},r=new n(i,s,JSON.stringify(a));r.value=a,this.segmentMetadataTrack_.addCue(r)}}function rs(){}const os=function(e){return"string"!=typeof e?e:e.replace(/./,(e=>e.toUpperCase()))},ds=["video","audio"],ls=(e,t)=>{const i=t[`${e}Buffer`];return i&&i.updating||t.queuePending[e]},us=(e,t)=>{if(0===t.queue.length)return;let i=0,s=t.queue[i];if("mediaSource"!==s.type){if("mediaSource"!==e&&t.ready()&&"closed"!==t.mediaSource.readyState&&!ls(e,t)){if(s.type!==e){if(i=((e,t)=>{for(let i=0;i<t.length;i++){const s=t[i];if("mediaSource"===s.type)return null;if(s.type===e)return i}return null})(e,t.queue),null===i)return;s=t.queue[i]}return t.queue.splice(i,1),t.queuePending[e]=s,s.action(e,t),s.doneFn?void 0:(t.queuePending[e]=null,void us(e,t))}}else t.updating()||"closed"===t.mediaSource.readyState||(t.queue.shift(),s.action(t),s.doneFn&&s.doneFn(),us("audio",t),us("video",t))},hs=(e,t)=>{const i=t[`${e}Buffer`],s=os(e);i&&(i.removeEventListener("updateend",t[`on${s}UpdateEnd_`]),i.removeEventListener("error",t[`on${s}Error_`]),t.codecs[e]=null,t[`${e}Buffer`]=null)},cs=(e,t)=>e&&t&&-1!==Array.prototype.indexOf.call(e.sourceBuffers,t),ps=(e,t,i)=>(s,n)=>{const a=n[`${s}Buffer`];if(cs(n.mediaSource,a)){n.logger_(`Appending segment ${t.mediaIndex}'s ${e.length} bytes to ${s}Buffer`);try{a.appendBuffer(e)}catch(e){n.logger_(`Error with code ${e.code} `+(22===e.code?"(QUOTA_EXCEEDED_ERR) ":"")+`when appending segment ${t.mediaIndex} to ${s}Buffer`),n.queuePending[s]=null,i(e)}}},ms=(e,t)=>(i,s)=>{const n=s[`${i}Buffer`];if(cs(s.mediaSource,n)){s.logger_(`Removing ${e} to ${t} from ${i}Buffer`);try{n.remove(e,t)}catch(n){s.logger_(`Remove ${e} to ${t} from ${i}Buffer failed`)}}},gs=e=>(t,i)=>{const s=i[`${t}Buffer`];cs(i.mediaSource,s)&&(i.logger_(`Setting ${t}timestampOffset to ${e}`),s.timestampOffset=e)},fs=e=>(t,i)=>{e()},ys=e=>t=>{if("open"===t.mediaSource.readyState){t.logger_(`Calling mediaSource endOfStream(${e||""})`);try{t.mediaSource.endOfStream(e)}catch(e){n.default.log.warn("Failed to call media source endOfStream",e)}}},_s=e=>t=>{t.logger_(`Setting mediaSource duration to ${e}`);try{t.mediaSource.duration=e}catch(e){n.default.log.warn("Failed to set media source duration",e)}},Ts=(e,t)=>i=>{const s=os(e),n=L(t);i.logger_(`Adding ${e}Buffer with codec ${t} to mediaSource`);const a=i.mediaSource.addSourceBuffer(n);a.addEventListener("updateend",i[`on${s}UpdateEnd_`]),a.addEventListener("error",i[`on${s}Error_`]),i.codecs[e]=t,i[`${e}Buffer`]=a},bs=e=>t=>{const i=t[`${e}Buffer`];if(hs(e,t),cs(t.mediaSource,i)){t.logger_(`Removing ${e}Buffer with codec ${t.codecs[e]} from mediaSource`);try{t.mediaSource.removeSourceBuffer(i)}catch(t){n.default.log.warn(`Failed to removeSourceBuffer ${e}Buffer`,t)}}},Ss=e=>(t,i)=>{const s=i[`${t}Buffer`],a=L(e);if(cs(i.mediaSource,s)&&i.codecs[t]!==e){i.logger_(`changing ${t}Buffer codec from ${i.codecs[t]} to ${e}`);try{s.changeType(a),i.codecs[t]=e}catch(e){n.default.log.warn(`Failed to changeType on ${t}Buffer`,e)}}},vs=({type:e,sourceUpdater:t,action:i,doneFn:s,name:n})=>{t.queue.push({type:e,action:i,doneFn:s,name:n}),us(e,t)},ws=(e,t)=>i=>{if(t.queuePending[e]){const i=t.queuePending[e].doneFn;t.queuePending[e]=null,i&&i(t[`${e}Error_`])}us(e,t)};class Is extends n.default.EventTarget{constructor(e){super(),this.mediaSource=e,this.sourceopenListener_=()=>us("mediaSource",this),this.mediaSource.addEventListener("sourceopen",this.sourceopenListener_),this.logger_=c("SourceUpdater"),this.audioTimestampOffset_=0,this.videoTimestampOffset_=0,this.queue=[],this.queuePending={audio:null,video:null},this.delayedAudioAppendQueue_=[],this.videoAppendQueued_=!1,this.codecs={},this.onVideoUpdateEnd_=ws("video",this),this.onAudioUpdateEnd_=ws("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){vs({type:"mediaSource",sourceUpdater:this,action:Ts(e,t),name:"addSourceBuffer"})}abort(e){vs({type:e,sourceUpdater:this,action:(e,t)=>{if("open"!==t.mediaSource.readyState)return;const i=t[`${e}Buffer`];if(cs(t.mediaSource,i)){t.logger_(`calling abort on ${e}Buffer`);try{i.abort()}catch(t){n.default.log.warn(`Failed to abort on ${e}Buffer`,t)}}},name:"abort"})}removeSourceBuffer(e){this.canRemoveSourceBuffer()?vs({type:"mediaSource",sourceUpdater:this,action:bs(e),name:"removeSourceBuffer"}):n.default.log.error("removeSourceBuffer is not supported!")}canRemoveSourceBuffer(){return!n.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()?vs({type:e,sourceUpdater:this,action:Ss(t),name:"changeType"}):n.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:s,bytes:n}=e;if(this.processedAppend_=!0,"audio"===s&&this.videoBuffer&&!this.videoAppendQueued_)return this.delayedAudioAppendQueue_.push([e,t]),void this.logger_(`delayed audio append of ${n.length} until video append`);if(vs({type:s,sourceUpdater:this,action:ps(n,i||{mediaIndex:-1},t),doneFn:t,name:"appendBuffer"}),"video"===s){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 cs(this.mediaSource,this.audioBuffer)&&this.audioBuffer.buffered?this.audioBuffer.buffered:O()}videoBuffered(){return cs(this.mediaSource,this.videoBuffer)&&this.videoBuffer.buffered?this.videoBuffer.buffered:O()}buffered(){const e=cs(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,t=cs(this.mediaSource,this.audioBuffer)?this.audioBuffer:null;return t&&!e?this.audioBuffered():e&&!t?this.videoBuffered():function(e,t){let i=null,s=null,n=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?(n++,2===n&&(i=a[o].time)):"end"===a[o].type&&(n--,1===n&&(s=a[o].time)),null!==i&&null!==s&&(r.push([i,s]),i=null,s=null);return O(r)}(this.audioBuffered(),this.videoBuffered())}setDuration(e,t=rs){vs({type:"mediaSource",sourceUpdater:this,action:_s(e),name:"duration",doneFn:t})}endOfStream(e=null,t=rs){"string"!=typeof e&&(e=void 0),vs({type:"mediaSource",sourceUpdater:this,action:ys(e),name:"endOfStream",doneFn:t})}removeAudio(e,t,i=rs){this.audioBuffered().length&&0!==this.audioBuffered().end(0)?vs({type:"audio",sourceUpdater:this,action:ms(e,t),doneFn:i,name:"remove"}):i()}removeVideo(e,t,i=rs){this.videoBuffered().length&&0!==this.videoBuffered().end(0)?vs({type:"video",sourceUpdater:this,action:ms(e,t),doneFn:i,name:"remove"}):i()}updating(){return!(!ls("audio",this)&&!ls("video",this))}audioTimestampOffset(e){return void 0!==e&&this.audioBuffer&&this.audioTimestampOffset_!==e&&(vs({type:"audio",sourceUpdater:this,action:gs(e),name:"timestampOffset"}),this.audioTimestampOffset_=e),this.audioTimestampOffset_}videoTimestampOffset(e){return void 0!==e&&this.videoBuffer&&this.videoTimestampOffset!==e&&(vs({type:"video",sourceUpdater:this,action:gs(e),name:"timestampOffset"}),this.videoTimestampOffset_=e),this.videoTimestampOffset_}audioQueueCallback(e){this.audioBuffer&&vs({type:"audio",sourceUpdater:this,action:fs(e),name:"callback"})}videoQueueCallback(e){this.videoBuffer&&vs({type:"video",sourceUpdater:this,action:fs(e),name:"callback"})}dispose(){this.trigger("dispose"),ds.forEach((e=>{this.abort(e),this.canRemoveSourceBuffer()?this.removeSourceBuffer(e):this[`${e}QueueCallback`]((()=>hs(e,this)))})),this.videoAppendQueued_=!1,this.delayedAudioAppendQueue_.length=0,this.sourceopenListener_&&this.mediaSource.removeEventListener("sourceopen",this.sourceopenListener_),this.off()}}const Es=e=>decodeURIComponent(escape(String.fromCharCode.apply(null,e))),As=new Uint8Array("\n\n".split("").map((e=>e.charCodeAt(0))));class Ds extends Error{constructor(){super("Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.")}}class xs extends as{constructor(e,t={}){super(e,t),this.mediaSource_=null,this.subtitlesTrack_=null,this.loaderType_="subtitle",this.featuresNativeTextTracks_=e.featuresNativeTextTracks,this.loadVttJs=e.loadVttJs,this.shouldSaveSegmentTimingInfo_=!1}createTransmuxer_(){return null}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=We(e);let s=this.initSegments_[i];if(t&&!s&&e.bytes){const t=As.byteLength+e.bytes.byteLength,n=new Uint8Array(t);n.set(e.bytes),n.set(As,e.bytes.byteLength),this.initSegments_[i]=s={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:n}}return s||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){Qi(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===Ei&&this.handleTimeout_(),e.code===Ai?this.mediaRequestsAborted+=1:this.mediaRequestsErrored+=1,void this.stopForError(e);const s=this.pendingSegment_;this.saveBandwidthRelatedStats_(s.duration,t.stats),t.key&&this.segmentKey(t.key,!0),this.state="APPENDING",this.trigger("appending");const n=s.segment;if(n.map&&(n.map.bytes=t.map.bytes),s.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"})));n.requested=!0;try{this.parseVTTCues_(s)}catch(e){return void this.stopForError({message:e.message})}if(this.updateTimeMapping_(s,this.syncController_.timelines[s.timeline],this.playlist_),s.cues.length?s.timingInfo={start:s.cues[0].startTime,end:s.cues[s.cues.length-1].endTime}:s.timingInfo={start:s.startOfSegment,end:s.startOfSegment+s.duration},s.isSyncRequest)return this.trigger("syncinfoupdate"),this.pendingSegment_=null,void(this.state="READY");s.byteLength=s.bytes.byteLength,this.mediaSecondsLoaded+=n.duration,s.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 s=t.length-1;s>=0;s--){const n=t[s],a=`${n.startTime}-${n.endTime}-${n.text}`;i[a]?e.removeCue(n):i[a]=n}}(this.subtitlesTrack_),this.handleAppendsDone_()}handleData_(){}updateTimingInfoEnd_(){}parseVTTCues_(e){let t,i=!1;if("function"!=typeof window.WebVTT)throw new Ds;"function"==typeof window.TextDecoder?t=new window.TextDecoder("utf8"):(t=window.WebVTT.StringDecoder(),i=!0);const s=new window.WebVTT.Parser(window,window.vttjs,t);if(e.cues=[],e.timestampmap={MPEGTS:0,LOCAL:0},s.oncue=e.cues.push.bind(e.cues),s.ontimestampmap=t=>{e.timestampmap=t},s.onparsingerror=e=>{n.default.log.warn("Error encountered when parsing cues: "+e.message)},e.segment.map){let t=e.segment.map.bytes;i&&(t=Es(t)),s.parse(t)}let a=e.bytes;i&&(a=Es(a)),s.parse(a),s.flush()}updateTimeMapping_(e,t,i){const s=e.segment;if(!t)return;if(!e.cues.length)return void(s.empty=!0);const{MPEGTS:n,LOCAL:a}=e.timestampmap,r=n/Ji-a+t.mapping;if(e.cues.forEach((e=>{const i=e.endTime-e.startTime,s=0===n?e.startTime+r:this.handleRollover_(e.startTime+r,t.time);e.startTime=Math.max(s,0),e.endTime=Math.max(s+i,0)})),!i.syncInfo){const t=e.cues[0].startTime,n=e.cues[e.cues.length-1].startTime;i.syncInfo={mediaSequence:i.mediaSequence+e.mediaIndex,time:Math.min(t,n-s.duration)}}}handleRollover_(e,t){if(null===t)return e;let i=e*Ji;const s=t*Ji;let n;for(n=s<i?-8589934592:8589934592;Math.abs(i-s)>4294967296;)i+=n;return i/Ji}}const Ls=function(e,t){const i=e.cues;for(let e=0;e<i.length;e++){const s=i[e];if(t>=s.adStartTime&&t<=s.adEndTime)return s}return null},Ps=[{name:"VOD",run:(e,t,i,s,n)=>i!==1/0?{time:0,segmentIndex:0,partIndex:null}:null},{name:"MediaSequence",run:(e,t,i,s,n,a)=>{if(!a)return null;const r=e.getMediaSequenceMap(a);if(!r||0===r.size)return null;if(void 0===t.mediaSequence||!Array.isArray(t.segments)||!t.segments.length)return null;let o=t.mediaSequence,d=0;for(const e of t.segments){const t=r.get(o);if(!t)break;if(n>=t.start&&n<t.end){if(Array.isArray(e.parts)&&e.parts.length){let i=t.start,s=0;for(const a of e.parts){const e=i,r=e+a.duration;if(n>=e&&n<r)return{time:t.start,segmentIndex:d,partIndex:s};s++,i=r}}return{time:t.start,segmentIndex:d,partIndex:null}}d++,o++}return null}},{name:"ProgramDateTime",run:(e,t,i,s,n)=>{if(!Object.keys(e.timelineToDatetimeMappings).length)return null;let a=null,r=null;const o=H(t);n=n||0;for(let i=0;i<o.length;i++){const s=o[t.endList||0===n?i:o.length-(i+1)],d=s.segment,l=e.timelineToDatetimeMappings[d.timeline];if(!l||!d.dateTimeObject)continue;let u=d.dateTimeObject.getTime()/1e3+l;if(d.parts&&"number"==typeof s.partIndex)for(let e=0;e<s.partIndex;e++)u+=d.parts[e].duration;const h=Math.abs(n-u);if(null!==r&&(0===h||r<h))break;r=h,a={time:u,segmentIndex:s.segmentIndex,partIndex:s.partIndex}}return a}},{name:"Segment",run:(e,t,i,s,n)=>{let a=null,r=null;n=n||0;const o=H(t);for(let e=0;e<o.length;e++){const i=o[t.endList||0===n?e:o.length-(e+1)],d=i.segment,l=i.part&&i.part.start||d&&d.start;if(d.timeline===s&&void 0!==l){const e=Math.abs(n-l);if(null!==r&&r<e)break;(!a||null===r||r>=e)&&(r=e,a={time:l,segmentIndex:i.segmentIndex,partIndex:i.partIndex})}}return a}},{name:"Discontinuity",run:(e,t,i,s,n)=>{let a=null;if(n=n||0,t.discontinuityStarts&&t.discontinuityStarts.length){let i=null;for(let s=0;s<t.discontinuityStarts.length;s++){const r=t.discontinuityStarts[s],o=t.discontinuitySequence+s+1,d=e.discontinuities[o];if(d){const e=Math.abs(n-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,s,n)=>t.syncInfo?{time:t.syncInfo.time,segmentIndex:t.syncInfo.mediaSequence-t.mediaSequence,partIndex:null}:null}];class Cs extends n.default.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={},this.mediaSequenceStorage_=new Map,this.logger_=c("SyncController")}getMediaSequenceMap(e){return this.mediaSequenceStorage_.get(e)}updateMediaSequenceMap(e,t,i){if(void 0===e.mediaSequence||!Array.isArray(e.segments)||!e.segments.length)return;const s=this.getMediaSequenceMap(i),n=new Map;let a,r=e.mediaSequence;s?s.has(e.mediaSequence)?a=s.get(e.mediaSequence).start:(this.logger_(`MediaSequence sync for ${i} segment loader - received a gap between playlists.\nFallback base time to: ${t}.\nReceived media sequence: ${r}.\nCurrent map: `,s),a=t):a=0,this.logger_(`MediaSequence sync for ${i} segment loader.\nReceived media sequence: ${r}.\nbase time is ${a}\nCurrent map: `,s),e.segments.forEach((e=>{const t=a,i=t+e.duration,s={start:t,end:i};n.set(r,s),r++,a=i})),this.mediaSequenceStorage_.set(i,n)}getSyncPoint(e,t,i,s,n){if(t!==1/0)return Ps.find((({name:e})=>"VOD"===e)).run(this,e,t);const a=this.runStrategies_(e,t,i,s,n);if(!a.length)return null;for(const t of a){const{syncPoint:i,strategy:n}=t,{segmentIndex:a,time:r}=i;if(a<0)continue;const o=r,d=o+e.segments[a].duration;if(this.logger_(`Strategy: ${n}. Current time: ${s}. selected segment: ${a}. Time: [${o} -> ${d}]}`),s>=o&&s<d)return this.logger_("Found sync point with exact match: ",i),i}return this.selectSyncPoint_(a,{key:"time",value:s})}getExpiredTime(e,t){if(!e||!e.segments)return null;const i=this.runStrategies_(e,t,e.discontinuitySequence,0,"main");if(!i.length)return null;const s=this.selectSyncPoint_(i,{key:"segmentIndex",value:0});return s.segmentIndex>0&&(s.time*=-1),Math.abs(s.time+K({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:s.segmentIndex,endIndex:0}))}runStrategies_(e,t,i,s,n){const a=[];for(let r=0;r<Ps.length;r++){const o=Ps[r],d=o.run(this,e,t,i,s,n);d&&(d.strategy=o.name,a.push({strategy:o.name,syncPoint:d}))}return a}selectSyncPoint_(e,t){let i=e[0].syncPoint,s=Math.abs(e[0].syncPoint[t.key]-t.value),n=e[0].strategy;for(let a=1;a<e.length;a++){const r=Math.abs(e[a].syncPoint[t.key]-t.value);r<s&&(s=r,i=e[a].syncPoint,n=e[a].strategy)}return this.logger_(`syncPoint for [${t.key}: ${t.value}] chosen with strategy [${n}]: [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)n.default.log.warn(`Not saving expired segment info. Media sequence gap ${i} is too large.`);else for(let s=i-1;s>=0;s--){const i=e.segments[s];if(i&&void 0!==i.start){t.syncInfo={mediaSequence:e.mediaSequence+s,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),s=e.segment;i&&(this.saveDiscontinuitySyncInfo_(e),e.playlist.syncInfo||(e.playlist.syncInfo={mediaSequence:e.playlist.mediaSequence+e.mediaIndex,time:s.start}));const n=s.dateTimeObject;s.discontinuity&&t&&n&&(this.timelineToDatetimeMappings[s.timeline]=-n.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 s=e.segment,n=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 n&&(n.start=a,n.end=r),(!s.start||a<s.start)&&(s.start=a),s.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 s=0;s<t.discontinuityStarts.length;s++){const n=t.discontinuityStarts[s],a=t.discontinuitySequence+s+1,r=n-e.mediaIndex,o=Math.abs(r);if(!this.discontinuities[a]||this.discontinuities[a].accuracy>o){let s;s=r<0?i.start-K({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:n}):i.end+K({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:n}),this.discontinuities[a]={time:s,accuracy:o}}}}dispose(){this.trigger("dispose"),this.off()}}class ks extends n.default.EventTarget{constructor(){super(),this.pendingTimelineChanges_={},this.lastTimelineChanges_={}}clearPendingTimelineChange(e){this.pendingTimelineChanges_[e]=null,this.trigger("pendingtimelinechange")}pendingTimelineChange({type:e,from:t,to:i}){return"number"==typeof t&&"number"==typeof i&&(this.pendingTimelineChanges_[e]={type:e,from:t,to:i},this.trigger("pendingtimelinechange")),this.pendingTimelineChanges_[e]}lastTimelineChange({type:e,from:t,to:i}){return"number"==typeof t&&"number"==typeof i&&(this.lastTimelineChanges_[e]={type:e,from:t,to:i},delete this.pendingTimelineChanges_[e],this.trigger("timelinechange")),this.lastTimelineChanges_[e]}dispose(){this.trigger("dispose"),this.pendingTimelineChanges_={},this.lastTimelineChanges_={},this.off()}}const Us=fi(yi((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,s=0;s<i;++s)t[s].call(this,arguments[1]);else for(var n=Array.prototype.slice.call(arguments,1),a=t.length,r=0;r<a;++r)t[r].apply(this,n)},t.dispose=function(){this.listeners={}},t.pipe=function(e){this.on("data",(function(t){e.push(t)}))},e}();
4/*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */let t=null;class i{constructor(e){let i,s,n;t||(t=function(){const e=[[[],[],[],[],[]],[[],[],[],[],[]]],t=e[0],i=e[1],s=t[4],n=i[4];let a,r,o;const d=[],l=[];let u,h,c,p,m,g;for(a=0;a<256;a++)l[(d[a]=a<<1^283*(a>>7))^a]=a;for(r=o=0;!s[r];r^=u||1,o=l[o]||1)for(p=o^o<<1^o<<2^o<<3^o<<4,p=p>>8^255&p^99,s[r]=p,n[p]=r,c=d[h=d[u=d[r]]],g=16843009*c^65537*h^257*u^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 l=e.slice(0),u=[];for(this._key=[l,u],i=o;i<4*o+28;i++)n=l[i-1],(i%o==0||8===o&&i%o==4)&&(n=a[n>>>24]<<24^a[n>>16&255]<<16^a[n>>8&255]<<8^a[255&n],i%o==0&&(n=n<<8^n>>>24^d<<24,d=d<<1^283*(d>>7))),l[i]=l[i-o]^n;for(s=0;i;s++,i--)n=l[3&s?i:i-4],u[s]=i<=4||s<4?n:r[0][a[n>>>24]]^r[1][a[n>>16&255]]^r[2][a[n>>8&255]]^r[3][a[255&n]]}decrypt(e,t,i,s,n,a){const r=this._key[1];let o,d,l,u=e^r[0],h=s^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=_[u>>>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&u]^r[f+1],l=_[c>>>24]^T[p>>16&255]^b[u>>8&255]^S[255&h]^r[f+2],p=_[p>>>24]^T[u>>16&255]^b[h>>8&255]^S[255&c]^r[f+3],f+=4,u=o,h=d,c=l;for(g=0;g<4;g++)n[(3&-g)+a]=v[u>>>24]<<24^v[h>>16&255]<<16^v[c>>8&255]<<8^v[255&p]^r[f++],o=u,u=h,h=c,c=p,p=o}}class s 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 n=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),l=new Uint8Array(e.byteLength);let u=0;for(this.asyncStream_=new s,this.asyncStream_.push(this.decryptChunk_(d.subarray(u,u+o),t,i,l)),u=o;u<d.length;u+=o)i=new Uint32Array([n(d[u-4]),n(d[u-3]),n(d[u-2]),n(d[u-1])]),this.asyncStream_.push(this.decryptChunk_(d.subarray(u,u+o),t,i,l));this.asyncStream_.push((function(){var e;
5/*! @name aes-decrypter @version 4.0.1 @license Apache-2.0 */r(null,(e=l).subarray(0,e.byteLength-e[e.byteLength-1]))}))}static get STEP(){return 32e3}decryptChunk_(e,t,s,a){return function(){const r=function(e,t,s){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 l,u,h,c,p,m,g,f,y;for(l=s[0],u=s[1],h=s[2],c=s[3],y=0;y<a.length;y+=4)p=n(a[y]),m=n(a[y+1]),g=n(a[y+2]),f=n(a[y+3]),r.decrypt(p,m,g,f,d,y),d[y]=n(d[y]^l),d[y+1]=n(d[y+1]^u),d[y+2]=n(d[y+2]^h),d[y+3]=n(d[y+3]^c),l=p,u=m,h=g,c=f;return o}(e,t,s);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),s=new Uint32Array(t.key.bytes,t.key.byteOffset,t.key.byteLength/4),n=new Uint32Array(t.iv.bytes,t.iv.byteOffset,t.iv.byteLength/4);new a(i,s,n,(function(e,i){self.postMessage(function(e){const t={};return Object.keys(e).forEach((i=>{const s=e[i];var n;n=s,("function"===ArrayBuffer.isView?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer)?t[i]={bytes:s.buffer,byteOffset:s.byteOffset,byteLength:s.byteLength}:t[i]=s})),t}({source:t.source,decrypted:i}),[i.buffer])}))}})));var Os=gi(Us);const Rs=e=>{let t=e.default?"main":"alternative";return e.characteristics&&e.characteristics.indexOf("public.accessibility.describes-video")>=0&&(t="main-desc"),t},Ms=(e,t)=>{e.abort(),e.pause(),t&&t.activePlaylistLoader&&(t.activePlaylistLoader.pause(),t.activePlaylistLoader=null)},Ns=(e,t)=>{t.activePlaylistLoader=e,e.load()},Bs={AUDIO:(e,t)=>()=>{const{mediaTypes:{[e]:i},excludePlaylist:s}=t,a=i.activeTrack(),r=i.activeGroup(),o=(r.filter((e=>e.default))[0]||r[0]).id,d=i.tracks[o];if(a!==d){n.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 s({error:{message:"Problem encountered loading the default audio track."}})},SUBTITLES:(e,t)=>()=>{const{mediaTypes:{[e]:i}}=t;n.default.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");const s=i.activeTrack();s&&(s.mode="disabled"),i.onTrackChanged()}},Fs={AUDIO:(e,t,i)=>{if(!t)return;const{tech:s,requestOptions:n,segmentLoaders:{[e]:a}}=i;t.on("loadedmetadata",(()=>{const e=t.media();a.playlist(e,n),(!s.paused()||e.endList&&"none"!==s.preload())&&a.load()})),t.on("loadedplaylist",(()=>{a.playlist(t.media(),n),s.paused()||a.load()})),t.on("error",Bs[e](e,i))},SUBTITLES:(e,t,i)=>{const{tech:s,requestOptions:n,segmentLoaders:{[e]:a},mediaTypes:{[e]:r}}=i;t.on("loadedmetadata",(()=>{const e=t.media();a.playlist(e,n),a.track(r.activeTrack()),(!s.paused()||e.endList&&"none"!==s.preload())&&a.load()})),t.on("loadedplaylist",(()=>{a.playlist(t.media(),n),s.paused()||a.load()})),t.on("error",Bs[e](e,i))}},qs={AUDIO:(e,t)=>{const{vhs:i,sourceType:s,segmentLoaders:{[e]:a},requestOptions:r,main:{mediaGroups:o},mediaTypes:{[e]:{groups:d,tracks:l,logger_:u}},mainPlaylistLoader:h}=t,c=re(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?(u(`AUDIO group '${a}' label '${p}' is a main playlist`),g.isMainPlaylist=!0,m=null):m="vhs-json"===s&&g.playlists?new ve(g.playlists[0],i,r):g.resolvedUri?new ve(g.resolvedUri,i,r):g.playlists&&"dash"===s?new ci(g.playlists[0],i,r,h):null,g=U({id:p,playlistLoader:m},g),Fs[e](e,g.playlistLoader,t),d[a].push(g),void 0===l[p]){const e=new n.default.AudioTrack({id:p,kind:Rs(g),enabled:!1,language:g.language,default:g.default,label:p});l[p]=e}}}a.on("error",Bs[e](e,t))},SUBTITLES:(e,t)=>{const{tech:i,vhs:s,sourceType:n,segmentLoaders:{[e]:a},requestOptions:r,main:{mediaGroups:o},mediaTypes:{[e]:{groups:d,tracks:l}},mainPlaylistLoader:u}=t;for(const a in o[e]){d[a]||(d[a]=[]);for(const h in o[e][a]){if(!s.options_.useForcedSubtitles&&o[e][a][h].forced)continue;let c,p=o[e][a][h];if("hls"===n)c=new ve(p.resolvedUri,s,r);else if("dash"===n){if(!p.playlists.filter((e=>e.excludeUntil!==1/0)).length)return;c=new ci(p.playlists[0],s,r,u)}else"vhs-json"===n&&(c=new ve(p.playlists?p.playlists[0]:p.resolvedUri,s,r));if(p=U({id:h,playlistLoader:c},p),Fs[e](e,p.playlistLoader,t),d[a].push(p),void 0===l[h]){const e=i.addRemoteTextTrack({id:h,kind:"subtitles",default:p.default&&p.autoselect,language:p.language,label:h},!1).track;l[h]=e}}}a.on("error",Bs[e](e,t))},"CLOSED-CAPTIONS":(e,t)=>{const{tech:i,main:{mediaGroups:s},mediaTypes:{[e]:{groups:n,tracks:a}}}=t;for(const t in s[e]){n[t]||(n[t]=[]);for(const r in s[e][t]){const o=s[e][t][r];if(!/^(?:CC|SERVICE)/.test(o.instreamId))continue;const d=i.options_.vhs&&i.options_.vhs.captionServices||{};let l={label:r,language:o.language,instreamId:o.instreamId,default:o.default&&o.autoselect};if(d[l.instreamId]&&(l=U(l,d[l.instreamId])),void 0===l.default&&delete l.default,n[t].push(U({id:r},o)),void 0===a[r]){const e=i.addRemoteTextTrack({id:l.instreamId,kind:"captions",default:l.default,language:l.language,label:l.label},!1).track;a[r]=e}}}}},$s=(e,t)=>{for(let i=0;i<e.length;i++){if(ne(t,e[i]))return!0;if(e[i].playlists&&$s(e[i].playlists,t))return!0}return!1},Gs={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 Ws{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_=u(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 Vs extends n.default.EventTarget{constructor(e,t){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new Ws,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_=c("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=u(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();this.request_=this.xhr_({uri:i},((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_()}const s=JSON.parse(this.request_.responseText);this.assignSteeringProperties_(s),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(),s=this.getBandwidth_();if(i){const e=`_${this.manifestType_}_pathway`;t.searchParams.set(e,i)}if(s){const e=`_${this.manifestType_}_throughput`;t.searchParams.set(e,s)}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 Ws}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&&(u(e,t.serverURL)!==this.steeringManifest.reloadUri||t.defaultServiceLocation!==this.defaultPathway||t.queryBeforeStart!==this.queryBeforeStart||t.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}}let Hs;const Xs=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],js=function(e){return this.audioSegmentLoader_[e]+this.mainSegmentLoader_[e]};class zs extends n.default.EventTarget{constructor(e){super();const{src:t,withCredentials:i,tech:s,bandwidth:n,externVhs:a,useCueTags:r,playlistExclusionDuration:o,enableLowInitialPlaylist:d,sourceType:l,cacheEncryptionKeys:u,bufferBasedABR:h,leastPixelDiffSelector:p,captionServices:m}=e;if(!t)throw new Error("A non-empty playlist URL or JSON manifest string is required");let{maxPlaylistRetries:g}=e;null==g&&(g=1/0),Hs=a,this.bufferBasedABR=Boolean(h),this.leastPixelDiffSelector=Boolean(p),this.withCredentials=i,this.tech_=s,this.vhs_=s.vhs,this.sourceType_=l,this.useCueTags_=r,this.playlistExclusionDuration=o,this.maxPlaylistRetries=g,this.enableLowInitialPlaylist=d,this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack("metadata","ad-cues"),this.cueTagsTrack_.inBandMetadataTrackDispatchType=""),this.requestOptions_={withCredentials:i,maxPlaylistRetries:g,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:rs,activeTrack:rs,getActiveGroup:rs,onGroupChanged:rs,onTrackChanged:rs,lastTrack_:null,logger_:c(`MediaGroups[${t}]`)}})),e})(),this.mediaSource=new window.MediaSource,this.handleDurationChange_=this.handleDurationChange_.bind(this),this.handleSourceOpen_=this.handleSourceOpen_.bind(this),this.handleSourceEnded_=this.handleSourceEnded_.bind(this),this.mediaSource.addEventListener("durationchange",this.handleDurationChange_),this.mediaSource.addEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.addEventListener("sourceended",this.handleSourceEnded_),this.seekable_=O(),this.hasPlayed_=!1,this.syncController_=new Cs(e),this.segmentMetadataTrack_=s.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.decrypter_=new Os,this.sourceUpdater_=new Is(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new ks,this.keyStatusMap_=new Map;const f={vhs:this.vhs_,parse708captions:e.parse708captions,useDtsForTimestampOffset:e.useDtsForTimestampOffset,captionServices:m,mediaSource:this.mediaSource,currentTime:this.tech_.currentTime.bind(this.tech_),seekable:()=>this.seekable(),seeking:()=>this.tech_.seeking(),duration:()=>this.duration(),hasPlayed:()=>this.hasPlayed_,goalBufferLength:()=>this.goalBufferLength(),bandwidth:n,syncController:this.syncController_,decrypter:this.decrypter_,sourceType:this.sourceType_,inbandTextTracks:this.inbandTextTracks_,cacheEncryptionKeys:u,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:e.exactManifestTimings,addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)};this.mainPlaylistLoader_="dash"===this.sourceType_?new ci(t,this.vhs_,U(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new ve(t,this.vhs_,U(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new as(U(f,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),e),this.audioSegmentLoader_=new as(U(f,{loaderType:"audio"}),e),this.subtitleSegmentLoader_=new xs(U(f,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise(((e,t)=>{function i(){s.off("vttjserror",n),e()}function n(){s.off("vttjsloaded",i),t()}s.one("vttjsloaded",i),s.one("vttjserror",n),s.addWebVttScript_()}))}),e),this.contentSteeringController_=new Vs(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_()))),Xs.forEach((e=>{this[e+"_"]=js.bind(this,e)})),this.logger_=c("pc"),this.triggeredFmp4Usage=!1,"none"===this.tech_.preload()?(this.loadOnPlay_=()=>{this.loadOnPlay_=null,this.mainPlaylistLoader_.load()},this.tech_.one("play",this.loadOnPlay_)):this.mainPlaylistLoader_.load(),this.timeToLoadedData__=-1,this.mainAppendsToLoadedData__=-1,this.audioAppendsToLoadedData__=-1;const y="none"===this.tech_.preload()?"play":"loadstart";this.tech_.one(y,(()=>{const e=Date.now();this.tech_.one("loadeddata",(()=>{this.timeToLoadedData__=Date.now()-e,this.mainAppendsToLoadedData__=this.mainSegmentLoader_.mediaAppends,this.audioAppendsToLoadedData__=this.audioSegmentLoader_.mediaAppends}))}))}mainAppendsToLoadedData_(){return this.mainAppendsToLoadedData__}audioAppendsToLoadedData_(){return this.audioAppendsToLoadedData__}appendsToLoadedData_(){const e=this.mainAppendsToLoadedData_(),t=this.audioAppendsToLoadedData_();return-1===e||-1===t?-1:e+t}timeToLoadedData_(){return this.timeToLoadedData__}checkABR_(e="abr"){const t=this.selectPlaylist();t&&this.shouldSwitchToMedia_(t)&&this.switchMedia_(t,e)}switchMedia_(e,t,i){const s=this.media(),n=s&&(s.id||s.uri),a=e&&(e.id||e.uri);n&&n!==a&&(this.logger_(`switch media ${n} -> ${a} from ${t}`),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,s=this.contentSteeringController_.getPathway();if(i&&s){const t=(i.length?i[0].playlists:i.playlists).filter((e=>e.attributes.serviceLocation===s));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,s=Object.keys(i);let n;if(Object.keys(this.mediaTypes_.AUDIO.groups).length)n=this.mediaTypes_.AUDIO.activeTrack();else{const e=i.main||s.length&&i[s[0]];for(const t in e)if(e[t].default){n={label:t};break}}if(!n)return t;const a=[];for(const t in i)if(i[t][n.label]){const s=i[t][n.label];if(s.playlists&&s.playlists.length)a.push.apply(a,s.playlists);else if(s.uri)a.push(s);else if(e.playlists.length)for(let i=0;i<e.playlists.length;i++){const s=e.playlists[i];s.attributes&&s.attributes.AUDIO&&s.attributes.AUDIO===t&&a.push(s)}}return a.length?a:t}setupMainPlaylistLoaderListeners_(){this.mainPlaylistLoader_.on("loadedmetadata",(()=>{const e=this.mainPlaylistLoader_.media(),t=1.5*e.targetDuration*1e3;se(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=>{qs[t](t,e)}));const{mediaTypes:t,mainPlaylistLoader:i,tech:s,vhs:n,segmentLoaders:{AUDIO:a,main:r}}=e;["AUDIO","SUBTITLES"].forEach((i=>{t[i].activeGroup=((e,t)=>i=>{const{mainPlaylistLoader:s,mediaTypes:{[e]:{groups:n}}}=t,a=s.media();if(!a)return null;let r=null;a.attributes[e]&&(r=n[a.attributes[e]]);const o=Object.keys(n);if(!r)if("AUDIO"===e&&o.length>1&&re(t.main))for(let e=0;e<o.length;e++){const t=n[o[e]];if($s(t,a)){r=t;break}}else n.main?r=n.main:1===o.length&&(r=n[o[0]]);return void 0===i?r:null!==i&&r&&r.filter((e=>e.id===i.id))[0]||null})(i,e),t[i].activeTrack=Gs[i](i,e),t[i].onGroupChanged=((e,t)=>()=>{const{segmentLoaders:{[e]:i,main:s},mediaTypes:{[e]:n}}=t,a=n.activeTrack(),r=n.getActiveGroup(),o=n.activePlaylistLoader,d=n.lastGroup_;r&&d&&r.id===d.id||(n.lastGroup_=r,n.lastTrack_=a,Ms(i,n),r&&!r.isMainPlaylist&&(r.playlistLoader?(i.resyncLoader(),Ns(r.playlistLoader,n)):o&&s.resetEverything()))})(i,e),t[i].onGroupChanging=((e,t)=>()=>{const{segmentLoaders:{[e]:i},mediaTypes:{[e]:s}}=t;s.lastGroup_=null,i.abort(),i.pause()})(i,e),t[i].onTrackChanged=((e,t)=>()=>{const{mainPlaylistLoader:i,segmentLoaders:{[e]:s,main:n},mediaTypes:{[e]:a}}=t,r=a.activeTrack(),o=a.getActiveGroup(),d=a.activePlaylistLoader,l=a.lastTrack_;if((!l||!r||l.id!==r.id)&&(a.lastGroup_=o,a.lastTrack_=r,Ms(s,a),o)){if(o.isMainPlaylist){if(!r||!l||r.id===l.id)return;const e=t.vhs.playlistController_,s=e.selectPlaylist();if(e.media()===s)return;return a.logger_(`track change. Switching main audio from ${l.id} to ${r.id}`),i.pause(),n.resetEverything(),void e.fastQualityChange_(s)}if("AUDIO"===e){if(!o.playlistLoader)return n.setAudio(!0),void n.resetEverything();s.setAudio(!0),n.setAudio(!1)}d!==o.playlistLoader?(s.track&&s.track(r),s.resetEverything(),Ns(o.playlistLoader,a)):Ns(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(),s.trigger({type:"usage",name:"vhs-audio-change"})};s.audioTracks().addEventListener("change",d),s.remoteTextTracks().addEventListener("change",t.SUBTITLES.onTrackChanged),n.on("dispose",(()=>{s.audioTracks().removeEventListener("change",d),s.remoteTextTracks().removeEventListener("change",t.SUBTITLES.onTrackChanged)})),s.clearTracks("audio");for(const e in t.AUDIO.tracks)s.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;se(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=t,"dash"===this.sourceType_&&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"})}))}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 s=!0;const n=Object.keys(i.AUDIO);for(const e in i.AUDIO)for(const t in i.AUDIO[e])i.AUDIO[e][t].uri||(s=!1);s&&this.tech_.trigger({type:"usage",name:"vhs-demuxed"}),Object.keys(i.SUBTITLES).length&&this.tech_.trigger({type:"usage",name:"vhs-webvtt"}),Hs.Playlist.isAes(t)&&this.tech_.trigger({type:"usage",name:"vhs-aes"}),n.length&&Object.keys(i.AUDIO[n[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(),s=this.bufferLowWaterLine(),a=this.bufferHighWaterLine();return function({currentPlaylist:e,buffered:t,currentTime:i,nextPlaylist:s,bufferLowWaterLine:a,bufferHighWaterLine:r,duration:o,bufferBasedABR:d,log:l}){if(!s)return n.default.log.warn("We received no playlist to switch to. Please check your stream."),!1;const u=`allowing switch ${e&&e.id||"null"} -> ${s.id}`;if(!e)return l(`${u} as current playlist is not set`),!0;if(s.id===e.id)return!1;const h=Boolean(B(t,i).length);if(!e.endList)return h||"number"!=typeof e.partTargetDuration?(l(`${u} as current playlist is live`),!0):(l(`not ${u} as current playlist is live llhls, but currentTime isn't in buffered.`),!1);const c=W(t,i),p=d?pi.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:pi.MAX_BUFFER_LOW_WATER_LINE;if(o<p)return l(`${u} as duration < max low water line (${o} < ${p})`),!0;const m=s.attributes.BANDWIDTH,g=e.attributes.BANDWIDTH;if(m<g&&(!d||c<r)){let e=`${u} as next bandwidth < current bandwidth (${m} < ${g})`;return d&&(e+=` and forwardBuffer < bufferHighWaterLine (${c} < ${r})`),l(e),!0}if((!d||m>g)&&c>=a){let e=`${u} as forwardBuffer >= bufferLowWaterLine (${c} >= ${a})`;return d&&(e+=` and next bandwidth > current bandwidth (${m} > ${g})`),l(e),!0}return l(`not ${u} as no switching criteria met`),!1}({buffered:this.tech_.buffered(),currentTime:i,currentPlaylist:t,nextPlaylist:e,bufferLowWaterLine:s,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.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()}))}mediaSecondsLoaded_(){return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded+this.mainSegmentLoader_.mediaSecondsLoaded)}load(){this.mainSegmentLoader_.load(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.load(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.load()}fastQualityChange_(e=this.selectPlaylist()){e&&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.tech_.setCurrentTime(this.tech_.currentTime())}))}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 s=i;if(e.start){const n=e.start.timeOffset;s=n<0?Math.max(i+n,t.start(0)):Math.min(i,n)}this.trigger("firstplay"),this.tech_.setCurrentTime(s)}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=Hs.Playlist.playlistEnd(e,t),s=this.tech_.currentTime(),n=this.tech_.buffered();if(!n.length)return i-s<=M;const a=n.end(n.length-1);return a-s<=M&&i-a<=M}excludePlaylist({playlistToExclude:e=this.mainPlaylistLoader_.media(),error:t={},playlistExclusionDuration:i}){if(e=e||this.mainPlaylistLoader_.media(),i=i||t.playlistExclusionDuration||this.playlistExclusionDuration,!e)return this.error=t,void("open"!==this.mediaSource.readyState?this.trigger("error"):this.sourceUpdater_.endOfStream("network"));e.playlistErrors_++;const s=this.mainPlaylistLoader_.main.playlists,a=s.filter(te),r=1===a.length&&a[0]===e;if(1===s.length&&i!==1/0)return n.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;s.forEach((i=>{if(i===e)return;const s=i.excludeUntil;void 0!==s&&s!==1/0&&(t=!0,delete i.excludeUntil)})),t&&(n.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 l=t.internal?this.logger_:n.default.log.warn,u=t.message?" "+t.message:"";l(`${t.internal?"Internal problem":"Problem"} encountered with playlist ${e.id}.${u} 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=[],s="all"===e;(s||"main"===e)&&i.push(this.mainPlaylistLoader_);const n=[];(s||"audio"===e)&&n.push("AUDIO"),(s||"subtitle"===e)&&(n.push("CLOSED-CAPTIONS"),n.push("SUBTITLES")),n.forEach((e=>{const t=this.mediaTypes_[e]&&this.mediaTypes_[e].activePlaylistLoader;t&&i.push(t)})),["main","audio","subtitle"].forEach((t=>{const s=this[`${t}SegmentLoader_`];!s||e!==t&&"all"!==e||i.push(s)})),i.forEach((e=>t.forEach((t=>{"function"==typeof e[t]&&e[t]()}))))}setCurrentTime(e){const t=B(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:Hs.Playlist.duration(e):1/0:0}seekable(){return this.seekable_}onSyncInfoUpdate_(){let e;if(!this.mainPlaylistLoader_)return;let t=this.mainPlaylistLoader_.media();if(!t)return;let i=this.syncController_.getExpiredTime(t,this.duration());if(null===i)return;const s=this.mainPlaylistLoader_.main,n=Hs.Playlist.seekable(t,i,Hs.Playlist.liveEdgeDelay(s,t));if(0===n.length)return;if(this.mediaTypes_.AUDIO.activePlaylistLoader){if(t=this.mediaTypes_.AUDIO.activePlaylistLoader.media(),i=this.syncController_.getExpiredTime(t,this.duration()),null===i)return;if(e=Hs.Playlist.seekable(t,i,Hs.Playlist.liveEdgeDelay(s,t)),0===e.length)return}let a,r;this.seekable_&&this.seekable_.length&&(a=this.seekable_.end(0),r=this.seekable_.start(0)),e?e.start(0)>n.end(0)||n.start(0)>e.end(0)?this.seekable_=n:this.seekable_=O([[e.start(0)>n.start(0)?e.start(0):n.start(0),e.end(0)<n.end(0)?e.end(0):n.end(0)]]):this.seekable_=n,this.seekable_&&this.seekable_.length&&this.seekable_.end(0)===a&&this.seekable_.start(0)===r||(this.logger_(`seekable updated [${q(this.seekable_)}]`),this.tech_.trigger("seekablechanged"))}updateDuration(e){if(this.updateDuration_&&(this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.updateDuration_=null),"open"!==this.mediaSource.readyState)return this.updateDuration_=this.updateDuration.bind(this,e),void this.mediaSource.addEventListener("sourceopen",this.updateDuration_);if(e){const e=this.seekable();if(!e.length)return;return void((isNaN(this.mediaSource.duration)||this.mediaSource.duration<e.end(e.length-1))&&this.sourceUpdater_.setDuration(e.end(e.length-1)))}const t=this.tech_.buffered();let i=Hs.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=Fi(this.main(),t),s={},n=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(e.main.hasVideo&&(s.video=i.video||e.main.videoCodec||"avc1.4d400d"),e.main.isMuxed&&(s.video+=`,${i.audio||e.main.audioCodec||k}`),(e.main.hasAudio&&!e.main.isMuxed||e.audio.hasAudio||n)&&(s.audio=i.audio||e.main.audioCodec||e.audio.audioCodec||k,e.audio.isFmp4=e.main.hasAudio&&!e.main.isMuxed?e.main.isFmp4:e.audio.isFmp4),!s.audio&&!s.video)return void this.excludePlaylist({playlistToExclude:t,error:{message:"Could not determine codecs for playlist."},playlistExclusionDuration:1/0});const a={};let r;if(["video","audio"].forEach((function(t){if(s.hasOwnProperty(t)&&(i=e[t].isFmp4,n=s[t],!(i?P(n):C(n)))){const i=e[t].isFmp4?"browser":"muxer";a[i]=a[i]||[],a[i].push(s[t]),"audio"===t&&(r=i)}var i,n})),n&&r&&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 ${r} does not support codec(s): "${s.audio}"`)}if(!Object.keys(a).length){if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){const e=[];if(["video","audio"].forEach((t=>{const i=(D(this.sourceUpdater_.codecs[t]||"")[0]||{}).type,n=(D(s[t]||"")[0]||{}).type;i&&n&&i.toLowerCase()!==n.toLowerCase()&&e.push(`"${this.sourceUpdater_.codecs[t]}" -> "${s[t]}"`)})),e.length)return void this.excludePlaylist({playlistToExclude:t,error:{message:`Codec switching not supported: ${e.join(", ")}.`,internal:!0},playlistExclusionDuration:1/0})}return s}{const e=Object.keys(a).reduce(((e,t)=>(e&&(e+=", "),e+`${t} does not support codec(s): "${a[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 s=e[i];if(-1!==t.indexOf(s.id))return;t.push(s.id);const n=Fi(this.main,s),a=[];!n.audio||C(n.audio)||P(n.audio)||a.push(`audio codec ${n.audio}`),!n.video||C(n.video)||P(n.video)||a.push(`video codec ${n.video}`),n.text&&"stpp.ttml.im1t"===n.text&&a.push(`text codec ${n.text}`),a.length&&(s.excludeUntil=1/0,this.logger_(`excluding ${s.id} for unsupported: ${a.join(", ")}`))}))}excludeIncompatibleVariants_(e){const t=[],i=this.main().playlists,s=Ni(D(e)),n=Bi(s),a=s.video&&D(s.video)[0]||null,r=s.audio&&D(s.audio)[0]||null;Object.keys(i).forEach((e=>{const s=i[e];if(-1!==t.indexOf(s.id)||s.excludeUntil===1/0)return;t.push(s.id);const o=[],d=Fi(this.mainPlaylistLoader_.main,s),l=Bi(d);if(d.audio||d.video){if(l!==n&&o.push(`codec count "${l}" !== "${n}"`),!this.sourceUpdater_.canChangeType()){const e=d.video&&D(d.video)[0]||null,t=d.audio&&D(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&&(s.excludeUntil=1/0,this.logger_(`excluding ${s.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 s,n=i;for(let i=0;i<e.segments.length;i++){const a=e.segments[i];if(s||(s=Ls(t,n+a.duration/2)),s){if("cueIn"in a){s.endTime=n,s.adEndTime=n,n+=a.duration,s=null;continue}if(n<s.endTime){n+=a.duration;continue}s.endTime+=a.duration}else if("cueOut"in a&&(s=new window.VTTCue(n,n+a.duration,a.cueOut),s.adStartTime=n,s.adEndTime=n+parseFloat(a.cueOut),t.addCue(s)),"cueOutCont"in a){const[e,i]=a.cueOutCont.split("/").map(parseFloat);s=new window.VTTCue(n,n+a.duration,""),s.adStartTime=n-e,s.adEndTime=s.adStartTime+i,t.addCue(s)}n+=a.duration}}(e,this.cueTagsTrack_,t)}goalBufferLength(){const e=this.tech_.currentTime(),t=pi.GOAL_BUFFER_LENGTH,i=pi.GOAL_BUFFER_LENGTH_RATE,s=Math.max(t,pi.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*i,s)}bufferLowWaterLine(){const e=this.tech_.currentTime(),t=pi.BUFFER_LOW_WATER_LINE,i=pi.BUFFER_LOW_WATER_LINE_RATE,s=Math.max(t,pi.MAX_BUFFER_LOW_WATER_LINE),n=Math.max(t,pi.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*i,this.bufferBasedABR?n:s)}bufferHighWaterLine(){return pi.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(e){Yi(this.inbandTextTracks_,"com.apple.streaming",this.tech_),(({inbandTextTracks:e,dateRanges:t})=>{const i=e.metadataTrack_;if(!i)return;const s=window.WebKitDataCue||window.VTTCue;t.forEach((e=>{for(const t of Object.keys(e)){if(zi.has(t))continue;const n=new s(e.startTime,e.endTime,"");n.id=e.id,n.type="com.apple.quicktime.HLS",n.value={key:ji[t],data:e[t]},"scte35Out"!==t&&"scte35In"!==t||(n.value.data=new Uint8Array(n.value.data.match(/[\da-f]{2}/gi)).buffer),i.addCue(n)}e.processDateRange()}))})({inbandTextTracks:this.inbandTextTracks_,dateRanges:e})}addMetadataToTextTrack(e,t,i){const s=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();Yi(this.inbandTextTracks_,e,this.tech_),(({inbandTextTracks:e,metadataArray:t,timestampOffset:i,videoDuration:s})=>{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:()=>(n.default.log.warn("cue.frame.id is deprecated. Use cue.value.key instead."),e.value.key)},value:{get:()=>(n.default.log.warn("cue.frame.value is deprecated. Use cue.value.data instead."),e.value.data)},privateData:{get:()=>(n.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 l=d.reduce(((e,t)=>{const i=e[t.startTime]||[];return i.push(t),e[t.startTime]=i,e}),{}),u=Object.keys(l).sort(((e,t)=>Number(e)-Number(t)));u.forEach(((e,t)=>{const i=l[e],n=isFinite(s)?s:e,a=Number(u[t+1])||n;i.forEach((e=>{e.endTime=a}))}))})({inbandTextTracks:this.inbandTextTracks_,metadataArray:t,timestampOffset:s,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)),"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 s of e.playlists){const e=s.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 s=!1;Object.keys(t).forEach((n=>{const a=t[n],r=this.pathwayAttribute_(a),o=r&&e!==r;a.excludeUntil===1/0&&"content-steering"===a.lastExcludeReason_&&!o&&(delete a.excludeUntil,delete a.lastExcludeReason_,s=!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&&(s=!0)}})),s&&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,s]of t.entries())i.get(e)||(this.mainPlaylistLoader_.updateOrDeleteClone(s),this.contentSteeringController_.excludePathway(e));for(const[s,n]of i.entries()){const i=t.get(s);i?this.equalPathwayClones_(i,n)||(this.mainPlaylistLoader_.updateOrDeleteClone(n,!0),this.contentSteeringController_.addAvailablePathway(s)):(e.filter((e=>e.attributes["PATHWAY-ID"]===n["BASE-ID"])).forEach((e=>{this.mainPlaylistLoader_.addClonePathway(n,e)})),this.contentSteeringController_.addAvailablePathway(s))}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,s=t["URI-REPLACEMENT"].PARAMS;for(const e in i)if(i[e]!==s[e])return!1;for(const e in s)if(i[e]!==s[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 s=this.mainPlaylistLoader_.getKeyIdSet(i);s&&s.size&&s.forEach((s=>{const n=this.keyStatusMap_.has(s)&&"usable"===this.keyStatusMap_.get(s),a=i.lastExcludeReason_===t&&i.excludeUntil===1/0;n?n&&a&&(delete i.excludeUntil,delete i.lastExcludeReason_,this.logger_(`enabling playlist ${i.id} because key ID ${s} 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 ${s} 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,s=e.excludeUntil===1/0&&e.lastExcludeReason_===t;i&&s&&(delete e.excludeUntil,n.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 Ys{constructor(e,t,i){const{playlistController_:s}=e,n=s.fastQualityChange_.bind(s);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=Fi(s.main(),t),this.playlist=t,this.id=i,this.enabled=(a=e.playlists,r=t.id,o=n,e=>{const t=a.main.playlists[r],i=ee(t),s=te(t);return void 0===e?s:(e?delete t.disabled:t.disabled=!0,e===s||i||(o(),e?a.trigger("renditionenabled"):a.trigger("renditiondisabled")),e)})}}const Qs=["seeking","seeked","pause","playing","error"];class Ks{constructor(e){this.playlistController_=e.playlistController,this.tech_=e.tech,this.seekable=e.seekable,this.allowSeeksWithinUnsafeLiveWindow=e.allowSeeksWithinUnsafeLiveWindow,this.liveRangeSafeTimeDelta=e.liveRangeSafeTimeDelta,this.media=e.media,this.consecutiveUpdates=0,this.lastRecordedTime=null,this.checkCurrentTimeTimeout_=null,this.logger_=c("PlaybackWatcher"),this.logger_("initialize");const t=()=>this.monitorCurrentTime_(),i=()=>this.monitorCurrentTime_(),s=()=>this.techWaiting_(),n=()=>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",s),this.tech_.on(Qs,n),this.tech_.on("canplay",i),this.tech_.one("play",t),this.dispose=()=>{this.clearSeekingAppendCheck_(),this.logger_("dispose"),this.tech_.off("waiting",s),this.tech_.off(Qs,n),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_`],s=i.buffered_(),n=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_`],s);this[`${e}Buffered_`]=s,n?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:$(s)}),this[`${e}StalledDownloads_`]<10||(this.logger_(`${e} loader stalled download exclusion`),this.resetSegmentDownloads_(e),this.tech_.trigger({type:"usage",name:`vhs-${e}-download-exclusion`}),"subtitle"!==e&&t.excludePlaylist({error:{message:`Excessive ${e} segment downloading detected.`},playlistExclusionDuration:1/0})))}checkCurrentTime_(){if(this.tech_.paused()||this.tech_.seeking())return;const e=this.tech_.currentTime(),t=this.tech_.buffered();if(this.lastRecordedTime===e&&(!t.length||e+M>=t.end(t.length-1)))return this.techWaiting_();this.consecutiveUpdates>=5&&e===this.lastRecordedTime?(this.consecutiveUpdates++,this.waiting_()):e===this.lastRecordedTime?this.consecutiveUpdates++:(this.consecutiveUpdates=0,this.lastRecordedTime=e)}resetTimeUpdate_(){this.consecutiveUpdates=0}fixesBadSeeks_(){if(!this.tech_.seeking())return!1;const e=this.seekable(),t=this.tech_.currentTime();let i;if(this.afterSeekableWindow_(e,t,this.media(),this.allowSeeksWithinUnsafeLiveWindow)&&(i=e.end(e.length-1)),this.beforeSeekableWindow_(e,t)){const t=e.start(0);i=t+(t===e.end(0)?0:M)}if(void 0!==i)return this.logger_(`Trying to seek outside of seekable at time ${t} with seekable range ${q(e)}. Seeking to ${i}.`),this.tech_.setCurrentTime(i),!0;const s=this.playlistController_.sourceUpdater_,n=this.tech_.buffered(),a=s.audioBuffer?s.audioBuffered():null,r=s.videoBuffer?s.videoBuffered():null,o=this.media(),d=o.partTargetDuration?o.partTargetDuration:2*(o.targetDuration-R),l=[a,r];for(let e=0;e<l.length;e++)if(l[e]&&W(l[e],t)<d)return!1;const u=F(n,t);return 0!==u.length&&(i=u.start(0)+M,this.logger_(`Buffered region starts (${u.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=B(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_,s=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 n=F(s,t);return n.length>0&&(this.logger_(`Stopped at ${t} and seeking to ${n.start(0)}`),this.resetTimeUpdate_(),this.skipTheGap_(t),!0)}afterSeekableWindow_(e,t,i,s=!1){if(!e.length)return!1;let n=e.end(e.length-1)+M;const a=!i.endList,r="number"==typeof i.partTargetDuration;return a&&(r||s)&&(n=e.end(e.length-1)+3*i.targetDuration),t>n}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 s;if(e.length&&t.length){const n=B(e,i-3),a=B(e,i),r=B(t,i);r.length&&!a.length&&n.length&&(s={start:n.end(0),end:r.end(0)})}else F(e,i).length||(s=this.gapFromVideoUnderflow_(e,i));return!!s&&(this.logger_(`Encountered a gap in video from ${s.start} to ${s.end}. Seeking to current time ${i}`),!0)}skipTheGap_(e){const t=this.tech_.buffered(),i=this.tech_.currentTime(),s=F(t,i);this.resetTimeUpdate_(),0!==s.length&&i===e&&(this.logger_("skipTheGap_:","currentTime:",i,"scheduled currentTime:",e,"nextRange start:",s.start(0)),this.tech_.setCurrentTime(s.start(0)+R),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 s=e.end(i-1),n=e.start(i);t.push([s,n])}return O(t)}(e);for(let e=0;e<i.length;e++){const s=i.start(e),n=i.end(e);if(t-s<4&&t-s>2)return{start:s,end:n}}return null}}const Js={errorInterval:30,getSource(e){return e(this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource())}},Zs=function(e,t){let i=0,s=0;const a=U(Js,t);e.ready((()=>{e.trigger({type:"usage",name:"vhs-error-reload-initialized"})}));const r=function(){s&&e.currentTime(s)},o=function(t){null!=t&&(s=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);n.default.log.error("ERROR: reloadSourceOnError - The option getSource must be a function!")}},l=function(){e.off("loadedmetadata",r),e.off("error",d),e.off("dispose",l)};e.on("error",d),e.on("dispose",l),e.reloadSourceOnError=function(t){l(),Zs(e,t)}};var en="3.10.0";const tn={PlaylistLoader:ve,Playlist:oe,utils:Xe,STANDARD_PLAYLIST_SELECTOR:Xi,INITIAL_PLAYLIST_SELECTOR:function(){const e=this.playlists.main.playlists.filter(oe.isEnabled);return Wi(e,((e,t)=>Vi(e,t))),e.filter((e=>!!Fi(this.playlists.main,e).video))[0]||null},lastBandwidthSelector:Xi,movingAverageBandwidthSelector:function(e){let t=-1,i=-1;if(e<0||e>1)throw new Error("Moving average bandwidth decay must be between 0 and 1.");return function(){const s=this.useDevicePixelRatio&&window.devicePixelRatio||1;return t<0&&(t=this.systemBandwidth,i=this.systemBandwidth),this.systemBandwidth>0&&this.systemBandwidth!==i&&(t=e*this.systemBandwidth+(1-e)*t,i=this.systemBandwidth),Hi(this.playlists.main,t,parseInt(Gi(this.tech_.el(),"width"),10)*s,parseInt(Gi(this.tech_.el(),"height"),10)*s,this.limitRenditionByPlayerDimensions,this.playlistController_)}},comparePlaylistBandwidth:Vi,comparePlaylistResolution:function(e,t){let i,s;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&&(s=t.attributes.RESOLUTION.width),s=s||window.Number.MAX_VALUE,i===s&&e.attributes.BANDWIDTH&&t.attributes.BANDWIDTH?e.attributes.BANDWIDTH-t.attributes.BANDWIDTH:i-s},xhr:Ee()};Object.keys(pi).forEach((e=>{Object.defineProperty(tn,e,{get:()=>(n.default.log.warn(`using Vhs.${e} is UNSAFE be sure you know what you are doing`),pi[e]),set(t){n.default.log.warn(`using Vhs.${e} is UNSAFE be sure you know what you are doing`),"number"!=typeof t||t<0?n.default.log.warn(`value of Vhs.${e} must be greater than or equal to 0`):pi[e]=t}})}));const sn="videojs-vhs",nn=function(e,t){const i=t.media();let s=-1;for(let t=0;t<e.length;t++)if(e[t].id===i.id){s=t;break}e.selectedIndex_=s,e.trigger({selectedIndex:s,type:"change"})};tn.canPlaySource=function(){return n.default.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const an=(e,t,i)=>{if(!e)return e;let s={};t&&t.attributes&&t.attributes.CODECS&&(s=Ni(D(t.attributes.CODECS))),i&&i.attributes&&i.attributes.CODECS&&(s.audio=i.attributes.CODECS);const n=L(s.video),a=L(s.audio),r={};for(const i in e)r[i]={},a&&(r[i].audioContentType=a),n&&(r[i].videoContentType=n),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 U(e,r)},rn=(e,t)=>e.reduce(((e,i)=>{if(!i.contentProtection)return e;const s=t.reduce(((e,t)=>{const s=i.contentProtection[t];return s&&s.pssh&&(e[t]={pssh:s.pssh}),e}),{});return Object.keys(s).length&&e.push(s),e}),[]),on=({player:e,sourceKeySystems:t,audioMedia:i,mainPlaylists:s})=>{if(!e.eme.initializeMediaKeys)return Promise.resolve();const n=i?s.concat([i]):s,a=rn(n,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,s)=>{e.eme.initializeMediaKeys({keySystems:t},(e=>{e?s(e):i()}))})))})),Promise.race([Promise.all(r),Promise.race(o)])},dn=({player:e,sourceKeySystems:t,media:i,audioMedia:s})=>{const a=an(t,i,s);return!(!a||(e.currentSource().keySystems=a,a&&!e.eme&&(n.default.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),1)))},ln=()=>{if(!window.localStorage)return null;const e=window.localStorage.getItem(sn);if(!e)return null;try{return JSON.parse(e)}catch(e){return null}},un=e=>0===e.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")?JSON.parse(e.substring(e.indexOf(",")+1)):e,hn=(e,t)=>{e._requestCallbackSet||(e._requestCallbackSet=new Set),e._requestCallbackSet.add(t)},cn=(e,t)=>{e._responseCallbackSet||(e._responseCallbackSet=new Set),e._responseCallbackSet.add(t)},pn=(e,t)=>{e._requestCallbackSet&&(e._requestCallbackSet.delete(t),e._requestCallbackSet.size||delete e._requestCallbackSet)},mn=(e,t)=>{e._responseCallbackSet&&(e._responseCallbackSet.delete(t),e._responseCallbackSet.size||delete e._responseCallbackSet)};tn.supportsNativeHls=function(){if(!document||!document.createElement)return!1;const e=document.createElement("video");return!!n.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))}))}(),tn.supportsNativeDash=!!(document&&document.createElement&&n.default.getTech("Html5").isSupported())&&/maybe|probably/i.test(document.createElement("video").canPlayType("application/dash+xml")),tn.supportsTypeNatively=e=>"hls"===e?tn.supportsNativeHls:"dash"===e&&tn.supportsNativeDash,tn.isSupported=function(){return n.default.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")},tn.xhr.onRequest=function(e){hn(tn.xhr,e)},tn.xhr.onResponse=function(e){cn(tn.xhr,e)},tn.xhr.offRequest=function(e){pn(tn.xhr,e)},tn.xhr.offResponse=function(e){mn(tn.xhr,e)};const gn=n.default.getComponent("Component");class fn extends gn{constructor(e,t,i){if(super(t,i.vhs),"number"==typeof i.initialBandwidth&&(this.options_.bandwidth=i.initialBandwidth),this.logger_=c("VhsHandler"),t.options_&&t.options_.playerId){const e=n.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_=U(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_.useBandwidthFromLocalStorage=void 0!==this.source_.useBandwidthFromLocalStorage?this.source_.useBandwidthFromLocalStorage:this.options_.useBandwidthFromLocalStorage||!1,this.options_.useForcedSubtitles=this.options_.useForcedSubtitles||!1,this.options_.useNetworkInformationApi=this.options_.useNetworkInformationApi||!1,this.options_.useDtsForTimestampOffset=this.options_.useDtsForTimestampOffset||!1,this.options_.customTagParsers=this.options_.customTagParsers||[],this.options_.customTagMappers=this.options_.customTagMappers||[],this.options_.cacheEncryptionKeys=this.options_.cacheEncryptionKeys||!1,this.options_.llhls=!1!==this.options_.llhls,this.options_.bufferBasedABR=this.options_.bufferBasedABR||!1,"number"!=typeof this.options_.playlistExclusionDuration&&(this.options_.playlistExclusionDuration=60),"number"!=typeof this.options_.bandwidth&&this.options_.useBandwidthFromLocalStorage){const e=ln();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=pi.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===pi.INITIAL_BANDWIDTH,["withCredentials","useDevicePixelRatio","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}setOptions(e={}){this.setOptions_(e)}src(e,t){if(!e)return;this.setOptions_(),this.options_.src=un(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=tn,this.options_.sourceType=Ce(t),this.options_.seekTo=e=>{this.tech_.setCurrentTime(e)},this.playlistController_=new zs(this.options_);const i=U({liveRangeSafeTimeDelta:M},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new Ks(i),this.playlistController_.on("error",(()=>{const e=n.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 s=this.options_.bufferBasedABR?tn.movingAverageBandwidthSelector(.55):tn.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):s.bind(this),this.playlistController_.selectInitialPlaylist=tn.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 s=1e3*t.downlink*1e3;e=s>=i&&e>=i?Math.max(e,s):s}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(){n.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:()=>$(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:()=>$(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=ln();t=t?U(t,e):e;try{window.localStorage.setItem(sn,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=re(t)?e.playlistController_.getAudioTrackPlaylists_():t.playlists;return i?i.filter((e=>!ee(e))).map(((t,i)=>new Ys(e,t,t.id))):[]}})),this.playlistController_.sourceUpdater_.on("createdsourcebuffers",(()=>{this.setupEme_()})),this.on(this.playlistController_,"progress",(function(){this.tech_.trigger("progress")})),this.on(this.playlistController_,"firstplay",(function(){this.ignoreNextSeekingEvent_=!0})),this.setupQualityLevels_(),this.tech_.el()&&(this.mediaSourceUrl_=window.URL.createObjectURL(this.playlistController_.mediaSource),this.tech_.src(this.mediaSourceUrl_))}createKeySessions_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;this.logger_("waiting for EME key session creation"),on({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=dn({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=n.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)})),nn(e,t.playlists)})),this.playlists.on("mediachange",(()=>{nn(this.qualityLevels_,this.playlists)})))}static version(){return{"@videojs/http-streaming":en,"mux.js":"7.0.2","mpd-parser":"1.3.0","m3u8-parser":"7.1.0","aes-decrypter":"4.0.1"}}version(){return this.constructor.version()}canChangeType(){return Is.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 s=((e,t)=>{if(!t||!t.segments||0===t.segments.length)return null;let i,s=0;for(let n=0;n<t.segments.length&&(i=t.segments[n],s=i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationEnd:s+i.duration,!(e<=s));n++);const n=t.segments[t.segments.length-1];if(n.videoTimingInfo&&n.videoTimingInfo.transmuxedPresentationEnd<e)return null;if(e>s){if(e>s+.25*n.duration)return null;i=n}return{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:s-i.duration,type:i.videoTimingInfo?"accurate":"estimate"}})(t,e);if(!s)return i({message:"valid programTime was not found"});if("estimate"===s.type)return i({message:"Accurate programTime could not be determined. Please seek to e.seekTime and try again",seekTime:s.estimatedStart});const n={mediaSeconds:t},a=((e,t)=>{if(!t.dateTimeObject)return null;const i=t.videoTimingInfo.transmuxerPrependedSeconds,s=e-(t.videoTimingInfo.transmuxedPresentationStart+i);return new Date(t.dateTimeObject.getTime()+1e3*s)})(t,s.segment);return a&&(n.programDateTime=a.toISOString()),i(null,n)})({playlist:this.playlistController_.media(),time:e,callback:t})}seekToProgramTime(e,t,i=!0,s=2){return je({programTime:e,playlist:this.playlistController_.media(),retryCount:s,pauseAfterSeek:i,seekTo:this.options_.seekTo,tech:this.options_.tech,callback:t})}setupXhrHooks_(){this.xhr.onRequest=e=>{hn(this.xhr,e)},this.xhr.onResponse=e=>{cn(this.xhr,e)},this.xhr.offRequest=e=>{pn(this.xhr,e)},this.xhr.offResponse=e=>{mn(this.xhr,e)},this.player_.trigger("xhr-hooks-ready")}}const yn={name:"videojs-http-streaming",VERSION:en,canHandleSource(e,t={}){const i=U(n.default.options,t);return yn.canPlayType(e.type,i)},handleSource(e,t,i={}){const s=U(n.default.options,i);return t.vhs=new fn(e,t,s),t.vhs.xhr=Ee(),t.vhs.setupXhrHooks_(),t.vhs.src(e.src,e.type),t.vhs},canPlayType(e,t){const i=Ce(e);if(!i)return"";const s=yn.getOverrideNative(t);return!tn.supportsTypeNatively(i)||s?"maybe":""},getOverrideNative(e={}){const{vhs:t={}}=e,i=!(n.default.browser.IS_ANY_SAFARI||n.default.browser.IS_IOS),{overrideNative:s=i}=t;return s}};P("avc1.4d400d,mp4a.40.2")&&n.default.getTech("Html5").registerSourceHandler(yn,0),n.default.VhsHandler=fn,n.default.VhsSourceHandler=yn,n.default.Vhs=tn,n.default.use||n.default.registerComponent("Vhs",tn),n.default.options.vhs=n.default.options.vhs||{},n.default.getPlugin&&n.default.getPlugin("reloadSourceOnError")||n.default.registerPlugin("reloadSourceOnError",(function(e){Zs(this,e)})),e.LOCAL_STORAGE_KEY=sn,e.Vhs=tn,e.VhsHandler=fn,e.VhsSourceHandler=yn,e.emeKeySystems=an,e.expandDataUri=un,e.getAllPsshKeySystemsOptions=rn,e.setupEmeOptions=dn,e.simpleTypeFromSourceType=Ce,e.waitForKeySessionCreation=on,Object.defineProperty(e,"__esModule",{value:!0})}));