@mux/playback-core 0.19.0 → 0.19.1-canary.0-e90e096
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +396 -0
- package/dist/cjs.json +168 -0
- package/dist/esm.json +215 -0
- package/dist/iife.json +191 -0
- package/dist/index.cjs.js +2 -2
- package/dist/index.cjs.js.map +4 -4
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +4 -4
- package/dist/module.json +238 -0
- package/dist/playback-core.js +1 -1
- package/dist/playback-core.js.map +4 -4
- package/dist/playback-core.mjs +1 -1
- package/dist/playback-core.mjs.map +4 -4
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/media-tracks.d.ts +2 -0
- package/dist/types/{tracks.d.ts → text-tracks.d.ts} +1 -1
- package/dist/types-ts3.4/index.d.ts +2 -2
- package/dist/types-ts3.4/media-tracks.d.ts +2 -0
- package/dist/types-ts3.4/{tracks.d.ts → text-tracks.d.ts} +1 -1
- package/package.json +3 -4
- package/LICENSE +0 -9
- package/dist/types/renditions.d.ts +0 -2
- package/dist/types-ts3.4/renditions.d.ts +0 -2
package/dist/module.json
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
{
|
|
2
|
+
"inputs": {
|
|
3
|
+
"../../node_modules/mux-embed/dist/mux.js": {
|
|
4
|
+
"bytes": 83733,
|
|
5
|
+
"imports": []
|
|
6
|
+
},
|
|
7
|
+
"../../node_modules/hls.js/dist/hls.mjs": {
|
|
8
|
+
"bytes": 887116,
|
|
9
|
+
"imports": []
|
|
10
|
+
},
|
|
11
|
+
"src/hls.ts": {
|
|
12
|
+
"bytes": 127,
|
|
13
|
+
"imports": [
|
|
14
|
+
{
|
|
15
|
+
"path": "../../node_modules/hls.js/dist/hls.mjs",
|
|
16
|
+
"kind": "import-statement"
|
|
17
|
+
}
|
|
18
|
+
]
|
|
19
|
+
},
|
|
20
|
+
"src/errors.ts": {
|
|
21
|
+
"bytes": 1336,
|
|
22
|
+
"imports": []
|
|
23
|
+
},
|
|
24
|
+
"src/types.ts": {
|
|
25
|
+
"bytes": 4817,
|
|
26
|
+
"imports": []
|
|
27
|
+
},
|
|
28
|
+
"src/util.ts": {
|
|
29
|
+
"bytes": 3305,
|
|
30
|
+
"imports": [
|
|
31
|
+
{
|
|
32
|
+
"path": "src/types.ts",
|
|
33
|
+
"kind": "import-statement"
|
|
34
|
+
}
|
|
35
|
+
]
|
|
36
|
+
},
|
|
37
|
+
"src/autoplay.ts": {
|
|
38
|
+
"bytes": 4533,
|
|
39
|
+
"imports": [
|
|
40
|
+
{
|
|
41
|
+
"path": "src/util.ts",
|
|
42
|
+
"kind": "import-statement"
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
"path": "src/types.ts",
|
|
46
|
+
"kind": "import-statement"
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
"path": "src/hls.ts",
|
|
50
|
+
"kind": "import-statement"
|
|
51
|
+
}
|
|
52
|
+
]
|
|
53
|
+
},
|
|
54
|
+
"src/preload.ts": {
|
|
55
|
+
"bytes": 1932,
|
|
56
|
+
"imports": [
|
|
57
|
+
{
|
|
58
|
+
"path": "src/util.ts",
|
|
59
|
+
"kind": "import-statement"
|
|
60
|
+
}
|
|
61
|
+
]
|
|
62
|
+
},
|
|
63
|
+
"src/media-tracks.ts": {
|
|
64
|
+
"bytes": 3089,
|
|
65
|
+
"imports": [
|
|
66
|
+
{
|
|
67
|
+
"path": "src/hls.ts",
|
|
68
|
+
"kind": "import-statement"
|
|
69
|
+
}
|
|
70
|
+
]
|
|
71
|
+
},
|
|
72
|
+
"src/text-tracks.ts": {
|
|
73
|
+
"bytes": 9689,
|
|
74
|
+
"imports": [
|
|
75
|
+
{
|
|
76
|
+
"path": "src/hls.ts",
|
|
77
|
+
"kind": "import-statement"
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
"path": "src/util.ts",
|
|
81
|
+
"kind": "import-statement"
|
|
82
|
+
}
|
|
83
|
+
]
|
|
84
|
+
},
|
|
85
|
+
"src/pdt.ts": {
|
|
86
|
+
"bytes": 1104,
|
|
87
|
+
"imports": []
|
|
88
|
+
},
|
|
89
|
+
"src/index.ts": {
|
|
90
|
+
"bytes": 25668,
|
|
91
|
+
"imports": [
|
|
92
|
+
{
|
|
93
|
+
"path": "../../node_modules/mux-embed/dist/mux.js",
|
|
94
|
+
"kind": "import-statement"
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
"path": "src/hls.ts",
|
|
98
|
+
"kind": "import-statement"
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
"path": "src/errors.ts",
|
|
102
|
+
"kind": "import-statement"
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
"path": "src/autoplay.ts",
|
|
106
|
+
"kind": "import-statement"
|
|
107
|
+
},
|
|
108
|
+
{
|
|
109
|
+
"path": "src/preload.ts",
|
|
110
|
+
"kind": "import-statement"
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
"path": "src/media-tracks.ts",
|
|
114
|
+
"kind": "import-statement"
|
|
115
|
+
},
|
|
116
|
+
{
|
|
117
|
+
"path": "src/text-tracks.ts",
|
|
118
|
+
"kind": "import-statement"
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
"path": "src/pdt.ts",
|
|
122
|
+
"kind": "import-statement"
|
|
123
|
+
},
|
|
124
|
+
{
|
|
125
|
+
"path": "src/util.ts",
|
|
126
|
+
"kind": "import-statement"
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
"path": "src/types.ts",
|
|
130
|
+
"kind": "import-statement"
|
|
131
|
+
},
|
|
132
|
+
{
|
|
133
|
+
"path": "src/types.ts",
|
|
134
|
+
"kind": "import-statement"
|
|
135
|
+
}
|
|
136
|
+
]
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
"outputs": {
|
|
140
|
+
"dist/playback-core.mjs.map": {
|
|
141
|
+
"imports": [],
|
|
142
|
+
"exports": [],
|
|
143
|
+
"inputs": {},
|
|
144
|
+
"bytes": 1900679
|
|
145
|
+
},
|
|
146
|
+
"dist/playback-core.mjs": {
|
|
147
|
+
"imports": [],
|
|
148
|
+
"exports": [
|
|
149
|
+
"AutoplayTypes",
|
|
150
|
+
"CmcdTypeValues",
|
|
151
|
+
"CmcdTypes",
|
|
152
|
+
"ExtensionMimeTypeMap",
|
|
153
|
+
"Hls",
|
|
154
|
+
"MediaError",
|
|
155
|
+
"MimeTypeShorthandMap",
|
|
156
|
+
"PlaybackTypes",
|
|
157
|
+
"StreamTypes",
|
|
158
|
+
"addCuePoints",
|
|
159
|
+
"addTextTrack",
|
|
160
|
+
"allMediaTypes",
|
|
161
|
+
"generatePlayerInitTime",
|
|
162
|
+
"generateUUID",
|
|
163
|
+
"getActiveCuePoint",
|
|
164
|
+
"getCuePoints",
|
|
165
|
+
"getCuePointsTrack",
|
|
166
|
+
"getCurrentPdt",
|
|
167
|
+
"getEnded",
|
|
168
|
+
"getError",
|
|
169
|
+
"getLiveEdgeStart",
|
|
170
|
+
"getMediaPlaylistLinesFromMultivariantPlaylistSrc",
|
|
171
|
+
"getSeekable",
|
|
172
|
+
"getStartDate",
|
|
173
|
+
"getStreamInfoFromHlsjsLevelDetails",
|
|
174
|
+
"getStreamInfoFromPlaylistLines",
|
|
175
|
+
"getStreamInfoFromSrcAndType",
|
|
176
|
+
"getStreamType",
|
|
177
|
+
"getStreamTypeConfig",
|
|
178
|
+
"getTargetLiveWindow",
|
|
179
|
+
"initialize",
|
|
180
|
+
"isKeyOf",
|
|
181
|
+
"isMuxVideoSrc",
|
|
182
|
+
"isPseudoEnded",
|
|
183
|
+
"loadMedia",
|
|
184
|
+
"mux",
|
|
185
|
+
"muxMediaState",
|
|
186
|
+
"removeTextTrack",
|
|
187
|
+
"setupCuePoints",
|
|
188
|
+
"setupHls",
|
|
189
|
+
"setupMux",
|
|
190
|
+
"shorthandKeys",
|
|
191
|
+
"teardown",
|
|
192
|
+
"toMuxVideoURL",
|
|
193
|
+
"updateStreamInfoFromHlsjsLevelDetails",
|
|
194
|
+
"updateStreamInfoFromSrc"
|
|
195
|
+
],
|
|
196
|
+
"entryPoint": "src/index.ts",
|
|
197
|
+
"inputs": {
|
|
198
|
+
"../../node_modules/mux-embed/dist/mux.js": {
|
|
199
|
+
"bytesInOutput": 83954
|
|
200
|
+
},
|
|
201
|
+
"src/index.ts": {
|
|
202
|
+
"bytesInOutput": 8192
|
|
203
|
+
},
|
|
204
|
+
"../../node_modules/hls.js/dist/hls.mjs": {
|
|
205
|
+
"bytesInOutput": 356376
|
|
206
|
+
},
|
|
207
|
+
"src/hls.ts": {
|
|
208
|
+
"bytesInOutput": 10
|
|
209
|
+
},
|
|
210
|
+
"src/errors.ts": {
|
|
211
|
+
"bytesInOutput": 845
|
|
212
|
+
},
|
|
213
|
+
"src/types.ts": {
|
|
214
|
+
"bytesInOutput": 361
|
|
215
|
+
},
|
|
216
|
+
"src/util.ts": {
|
|
217
|
+
"bytesInOutput": 710
|
|
218
|
+
},
|
|
219
|
+
"src/autoplay.ts": {
|
|
220
|
+
"bytesInOutput": 911
|
|
221
|
+
},
|
|
222
|
+
"src/preload.ts": {
|
|
223
|
+
"bytesInOutput": 563
|
|
224
|
+
},
|
|
225
|
+
"src/media-tracks.ts": {
|
|
226
|
+
"bytesInOutput": 1044
|
|
227
|
+
},
|
|
228
|
+
"src/text-tracks.ts": {
|
|
229
|
+
"bytesInOutput": 3579
|
|
230
|
+
},
|
|
231
|
+
"src/pdt.ts": {
|
|
232
|
+
"bytesInOutput": 360
|
|
233
|
+
}
|
|
234
|
+
},
|
|
235
|
+
"bytes": 458780
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
package/dist/playback-core.js
CHANGED
|
@@ -41,7 +41,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
41
41
|
`),c=[],u=e?Bu(e.baseTime,e.timescale):0,d="00:00.000",h=0,m=0,y,E=!0;o.oncue=function(b){let A=t[i],D=t.ccOffset,L=(h-u)/9e4;if(A!=null&&A.new&&(m!==void 0?D=t.ccOffset=A.start:ad(t,i,L)),L){if(!e){y=new Error("Missing initPTS for VTT MPEGTS");return}D=L-t.presentationOffset}let F=b.endTime-b.startTime,k=rt((b.startTime+D-m)*9e4,r*9e4)/9e4;b.startTime=Math.max(k,0),b.endTime=Math.max(k+F,0);let G=b.text.trim();b.text=decodeURIComponent(encodeURIComponent(G)),b.id||(b.id=ks(b.startTime,b.endTime,G)),b.endTime>0&&c.push(b)},o.onparsingerror=function(b){y=b},o.onflush=function(){if(y){n(y);return}s(c)},l.forEach(b=>{if(E)if(pr(b,"X-TIMESTAMP-MAP=")){E=!1,b.slice(16).split(",").forEach(A=>{pr(A,"LOCAL:")?d=A.slice(6):pr(A,"MPEGTS:")&&(h=parseInt(A.slice(7)))});try{m=nd(d)/1e3}catch(A){y=A}return}else b===""&&(E=!1);o.parse(b+`
|
|
42
42
|
`)}),o.flush()}var vr="stpp.ttml.im1t",Za=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,eo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ld={left:"start",center:"center",right:"end",start:"start",end:"end"};function oa(a,e,t,i){let r=ye(new Uint8Array(a),["mdat"]);if(r.length===0){i(new Error("Could not parse IMSC1 mdat"));return}let s=r.map(o=>ft(o)),n=Uu(e.baseTime,1,e.timescale);try{s.forEach(o=>t(cd(o,n)))}catch(o){i(o)}}function cd(a,e){let r=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");let s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(s).reduce((d,h)=>(d[h]=r.getAttribute(`ttp:${h}`)||s[h],d),{}),o=r.getAttribute("xml:space")!=="preserve",l=la(Tr(r,"styling","style")),c=la(Tr(r,"layout","region")),u=Tr(r,"body","[begin]");return[].map.call(u,d=>{let h=to(d,o);if(!h||!d.hasAttribute("begin"))return null;let m=xr(d.getAttribute("begin"),n),y=xr(d.getAttribute("dur"),n),E=xr(d.getAttribute("end"),n);if(m===null)throw ca(d);if(E===null){if(y===null)throw ca(d);E=m+y}let b=new ws(m-e,E-e,h);b.id=ks(b.startTime,b.endTime,b.text);let A=c[d.getAttribute("region")],D=l[d.getAttribute("style")],L=ud(A,D,l),{textAlign:F}=L;if(F){let k=ld[F];k&&(b.lineAlign=k),b.align=F}return De(b,L),b}).filter(d=>d!==null)}function Tr(a,e,t){let i=a.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function la(a){return a.reduce((e,t)=>{let i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function to(a,e){return[].slice.call(a.childNodes).reduce((t,i,r)=>{var s;return i.nodeName==="br"&&r?t+`
|
|
43
43
|
`:(s=i.childNodes)!=null&&s.length?to(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function ud(a,e,t){let i="http://www.w3.org/ns/ttml#styling",r=null,s=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],n=a!=null&&a.hasAttribute("style")?a.getAttribute("style"):null;return n&&t.hasOwnProperty(n)&&(r=t[n]),s.reduce((o,l)=>{let c=Er(e,i,l)||Er(a,i,l)||Er(r,i,l);return c&&(o[l]=c),o},{})}function Er(a,e,t){return a&&a.hasAttributeNS(e,t)?a.getAttributeNS(e,t):null}function ca(a){return new Error(`Could not parse ttml timestamp ${a}`)}function xr(a,e){if(!a)return null;let t=Xa(a);return t===null&&(Za.test(a)?t=dd(a,e):eo.test(a)&&(t=hd(a,e))),t}function dd(a,e){let t=Za.exec(a),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function hd(a,e){let t=eo.exec(a),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}var ps=class{constructor(e){if(this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ua(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},this.config.enableCEA708Captions){let t=new Ut(this,"textTrack1"),i=new Ut(this,"textTrack2"),r=new Ut(this,"textTrack3"),s=new Ut(this,"textTrack4");this.cea608Parser1=new Ui(1,t,i),this.cea608Parser2=new Ui(3,r,s)}e.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(v.FRAG_LOADING,this.onFragLoading,this),e.on(v.FRAG_LOADED,this.onFragLoaded,this),e.on(v.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(v.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(v.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(v.FRAG_LOADING,this.onFragLoading,this),e.off(v.FRAG_LOADED,this.onFragLoaded,this),e.off(v.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(v.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(v.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null}addCues(e,t,i,r,s){let n=!1;for(let o=s.length;o--;){let l=s[o],c=gd(l[0],l[1],t,i);if(c>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),n=!0,c/(i-t)>.5))return}if(n||s.push([t,i]),this.config.renderTextTracksNatively){let o=this.captionsTracks[e];this.Cues.newCue(o,t,i,r)}else{let o=this.Cues.newCue(null,t,i,r);this.hls.trigger(v.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:s}){let{unparsedVttFrags:n}=this;i==="main"&&(this.initPTS[t.cc]={baseTime:r,timescale:s}),n.length&&(this.unparsedVttFrags=[],n.forEach(o=>{this.onFragLoaded(v.FRAG_LOADED,o)}))}getExistingTrack(e){let{media:t}=this;if(t)for(let i=0;i<t.textTracks.length;i++){let r=t.textTracks[i];if(r[e])return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:i,media:r}=this,{label:s,languageCode:n}=t[e],o=this.getExistingTrack(e);if(o)i[e]=o,Nt(i[e]),Ra(i[e],r);else{let l=this.createTextTrack("captions",s,n);l&&(l[e]=!0,i[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let i=t.label,r={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(v.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}createTextTrack(e,t,i){let r=this.media;if(!!r)return r.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){let{captionsTracks:e}=this;Object.keys(e).forEach(t=>{Nt(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ua(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let i=0;i<t.length;i++)Nt(t[i])}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[],r=i.some(s=>s.textCodec===vr);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(Ya(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){let n=this.media?this.media.textTracks:null;this.tracks.forEach((o,l)=>{let c;if(n&&l<n.length){let u=null;for(let d=0;d<n.length;d++)if(fd(n[d],o)){u=n[d];break}u&&(c=u)}if(c)Nt(c);else{let u=this._captionsOrSubtitlesFromCharacteristics(o);c=this.createTextTrack(u,o.name,o.lang),c&&(c.mode="disabled")}c&&(c.groupId=o.groupId,this.textTracks.push(c))})}else if(this.tracks.length){let n=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(v.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:n})}}}_captionsOrSubtitlesFromCharacteristics(e){if(e.attrs.CHARACTERISTICS){let t=/transcribes-spoken-dialog/gi.test(e.attrs.CHARACTERISTICS),i=/describes-music-and-sound/gi.test(e.attrs.CHARACTERISTICS);if(t&&i)return"captions"}return"subtitles"}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{let r=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!r)return;let s=`textTrack${r[1]}`,n=this.captionsProperties[s];!n||(n.label=i.name,i.lang&&(n.languageCode=i.lang),n.media=i)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){let{cea608Parser1:i,cea608Parser2:r,lastSn:s,lastPartIndex:n}=this;if(!(!this.enabled||!(i&&r))&&t.frag.type===re.MAIN){var o,l;let c=t.frag.sn,u=(o=t==null||(l=t.part)==null?void 0:l.index)!=null?o:-1;c===s+1||c===s&&u===n+1||(i.reset(),r.reset()),this.lastSn=c,this.lastPartIndex=u}}onFragLoaded(e,t){let{frag:i,payload:r}=t;if(i.type===re.SUBTITLE)if(r.byteLength){let s=i.decryptdata,n="stats"in t;if(s==null||!s.encrypted||n){let o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===vr?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){let i=this.hls;oa(t,this.initPTS[e.cc],r=>{this._appendCues(r,e.level),i.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},r=>{w.log(`Failed to parse IMSC1: ${r}`),i.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:r})})}_parseVTTs(e){var t;let{frag:i,payload:r}=e,{initPTS:s,unparsedVttFrags:n}=this,o=s.length-1;if(!s[i.cc]&&o===-1){n.push(e);return}let l=this.hls,c=(t=i.initSegment)!=null&&t.data?It(i.initSegment.data,new Uint8Array(r)):r;od(c,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,u=>{this._appendCues(u,i.level),l.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},u=>{let d=u.message==="Missing initPTS for VTT MPEGTS";d?n.push(e):this._fallbackToIMSC1(i,r),w.log(`Failed to parse VTT cue: ${u}`),!(d&&o>i.cc)&&l.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:u})})}_fallbackToIMSC1(e,t){let i=this.tracks[e.level];i.textCodec||oa(t,this.initPTS[e.cc],()=>{i.textCodec=vr,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){let r=this.textTracks[t];if(!r||r.mode==="disabled")return;e.forEach(s=>Ia(r,s))}else{let r=this.tracks[t];if(!r)return;let s=r.default?"default":"subtitles"+t;i.trigger(v.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){let{frag:i}=t;i.type===re.SUBTITLE&&this.onFragLoaded(v.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){let{cea608Parser1:i,cea608Parser2:r}=this;if(!this.enabled||!(i&&r))return;let{frag:s,samples:n}=t;if(!(s.type===re.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let o=0;o<n.length;o++){let l=n[o].bytes;if(l){let c=this.extractCea608Data(l);i.addData(n[o].pts,c[0]),r.addData(n[o].pts,c[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:r,type:s}){let{media:n}=this;if(!(!n||n.currentTime<i)){if(!s||s==="video"){let{captionsTracks:o}=this;Object.keys(o).forEach(l=>Rr(o[l],t,i))}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){let{textTracks:o}=this;Object.keys(o).forEach(l=>Rr(o[l],t,r))}}}extractCea608Data(e){let t=[[],[]],i=e[0]&31,r=2;for(let s=0;s<i;s++){let n=e[r++],o=127&e[r++],l=127&e[r++];if(o===0&&l===0)continue;if((4&n)!==0){let u=3&n;(u===0||u===1)&&(t[u].push(o),t[u].push(l))}}return t}};function fd(a,e){return!!a&&a.label===e.name&&!(a.textTrack1||a.textTrack2)}function gd(a,e,t,i){return Math.min(e,i)-Math.max(a,t)}function ua(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var ri=class{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){let{hls:e}=this;e.on(v.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.BUFFER_CODECS,this.onBufferCodecs,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(v.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.BUFFER_CODECS,this.onBufferCodecs,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null}onManifestParsed(e,t){let i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){let e=this.hls.levels;if(e.length){let t=this.hls;t.autoLevelCapping=this.getMaxLevel(e.length-1),t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){let t=this.hls.levels;if(!t.length)return-1;let i=t.filter((r,s)=>this.isLevelAllowed(r)&&s<=e);return this.clientRect=null,ri.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return e}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;let r=(n,o)=>o?n.width!==o.width||n.height!==o.height:!0,s=e.length-1;for(let n=0;n<e.length;n+=1){let o=e[n];if((o.width>=t||o.height>=i)&&r(o,e[n+1])){s=n;break}}return s}},ys=class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&typeof r.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){let r=performance.now();if(t){if(this.lastTime){let s=r-this.lastTime,n=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*n/s,c=this.hls;if(c.trigger(v.FPS_DROP,{currentDropped:n,currentDecoded:o,totalDroppedFrames:i}),l>0&&n>c.config.fpsDroppedMonitoringThreshold*o){let u=c.currentLevel;w.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=u)&&(u=u-1,c.trigger(v.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:c.currentLevel}),c.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},vi="[eme]",_t=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=_t.CDMCleanupPromise?[_t.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=w.debug.bind(w,vi),this.log=w.log.bind(w,vi),this.warn=w.warn.bind(w,vi),this.error=w.error.bind(w,vi),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(v.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(v.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(v.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(v.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(v.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(v.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:i}=this.config,r=t[e];if(r)return r.licenseUrl;if(e===Se.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){let{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,i=(n,o,l)=>!!n&&l.indexOf(n)===o,r=t.map(n=>n.audioCodec).filter(i),s=t.map(n=>n.videoCodec).filter(i);return r.length+s.length===0&&s.push("avc1.42e01e"),new Promise((n,o)=>{let l=c=>{let u=c.shift();this.getMediaKeysPromise(u,r,s).then(d=>n({keySystem:u,mediaKeys:d})).catch(d=>{c.length?l(c):d instanceof Qe?o(d):o(new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_NO_ACCESS,error:d,fatal:!0},d.message))})};l(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${i}`;return ma===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return i(e,t)}getMediaKeysPromise(e,t,i){let r=fc(e,t,i,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e],n=s==null?void 0:s.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(r)}`),n=this.requestMediaKeySystemAccess(e,r);let o=this.keySystemAccessPromises[e]={keySystemAccess:n};return n.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),n.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);let c=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=l.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),c.then(d=>d?this.setMediaKeysServerCertificate(u,e,d):u))),o.mediaKeys.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),o.mediaKeys})}return n.then(()=>s.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${lt.hexDump(e.keyId||[])}`);let r=i.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let i=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,s,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return lt.hexDump(e.keyId)}updateKeySession(e,t){var i;let r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${lt.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])}
|
|
44
|
-
} (data length: ${t&&t.byteLength})`),r.update(t)}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,i)=>{let r=tr(this.config),s=e.map(In).filter(n=>!!n&&r.indexOf(n)!==-1);return this.getKeySystemSelectionPromise(s).then(({keySystem:n})=>{let o=Dn(n);o?t(o):i(new Error(`Unable to find format for key-system "${n}"`))}).catch(i)})}loadKey(e){let t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let s=this.keyIdToKeySessionPromise[i];return s||(s=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then(({keySystem:n,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(n,o).then(()=>{this.throwIfDestroyed();let l=this.createMediaKeySessionContext({keySystem:n,mediaKeys:o,decryptdata:t}),c="cenc";return this.generateRequestWithPreferredKeySession(l,c,t.pssh,"playlist-key")}))),s.catch(n=>this.handleError(n))),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){!this.hls||(this.error(e.message),e instanceof Qe?this.hls.trigger(v.ERROR,e.data):this.hls.trigger(v.ERROR,{type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){let t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){let r=In(e.keyFormat),s=r?[r]:tr(this.config);return this.attemptKeySystemAccess(s)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=tr(this.config)),e.length===0)throw new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){let{initDataType:t,initData:i}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),i===null)return;let r,s;if(t==="sinf"&&this.config.drmSystems[Se.FAIRPLAY]){let u=Ne(new Uint8Array(i));try{let d=bs(JSON.parse(u).sinf),h=_a(new Uint8Array(d));if(!h)return;r=h.subarray(8,24),s=Se.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{let u=Nc(i);if(u===null)return;u.version===0&&u.systemId===ga.WIDEVINE&&u.data&&(r=u.data.subarray(8,24)),s=hc(u.systemId)}if(!s||!r)return;let n=lt.hexDump(r),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this,c=o[n];for(let u=0;u<l.length;u++){let d=l[u],h=d.decryptdata;if(h.pssh||!h.keyId)continue;let m=lt.hexDump(h.keyId);if(n===m||h.uri.replace(/-/g,"").indexOf(n)!==-1){c=o[m],delete o[m],h.pssh=new Uint8Array(i),h.keyId=r,c=o[n]=c.then(()=>this.generateRequestWithPreferredKeySession(d,t,i,"encrypted-event-key-match"));break}}c||(c=o[n]=this.getKeySystemSelectionPromise([s]).then(({keySystem:u,mediaKeys:d})=>{var h;this.throwIfDestroyed();let m=new Dt("ISO-23001-7",n,(h=Dn(u))!=null?h:"");return m.pssh=new Uint8Array(i),m.keyId=r,this.attemptSetMediaKeys(u,d).then(()=>{this.throwIfDestroyed();let y=this.createMediaKeySessionContext({decryptdata:m,keySystem:u,mediaKeys:d});return this.generateRequestWithPreferredKeySession(y,t,i,"encrypted-event-no-match")})})),c.catch(u=>this.handleError(u))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(s=>i.indexOf(s)===-1)})}generateRequestWithPreferredKeySession(e,t,i,r){var s,n;let o=(s=this.config.drmSystems)==null||(n=s[e.keySystem])==null?void 0:n.generateRequest;if(o)try{let h=o.call(this.hls,t,i,e);if(!h)throw new Error("Invalid response from configured generateRequest filter");t=h.initDataType,i=e.decryptdata.pssh=h.initData?new Uint8Array(h.initData):null}catch(h){var l;if(this.warn(h.message),(l=this.hls)!=null&&l.config.debug)throw h}if(i===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let c=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${c} (init data type: ${t} length: ${i?i.byteLength:null})`);let u=new Ds;e.mediaKeysSession.onmessage=h=>{let m=e.mediaKeysSession;if(!m){u.emit("error",new Error("invalid state"));return}let{messageType:y,message:E}=h;this.log(`"${y}" message event for session "${m.sessionId}" message size: ${E.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,E).catch(b=>{this.handleError(b),u.emit("error",b)}):y==="license-release"?e.keySystem===Se.FAIRPLAY&&(this.updateKeySession(e,fa("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${y}"`)},e.mediaKeysSession.onkeystatuseschange=h=>{if(!e.mediaKeysSession){u.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);let y=e.keyStatus;u.emit("keyStatus",y),y==="expired"&&(this.warn(`${e.keySystem} expired for key ${c}`),this.renewKeySession(e))};let d=new Promise((h,m)=>{u.on("error",m),u.on("keyStatus",y=>{y.startsWith("usable")?h():y==="output-restricted"?m(new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):y==="internal-error"?m(new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${y}"`)):y==="expired"?m(new Error("key expired while generating request")):this.warn(`unhandled key status change "${y}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var h;this.log(`Request generated for key-session "${(h=e.mediaKeysSession)==null?void 0:h.sessionId}" keyId: ${c}`)}).catch(h=>{throw new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_NO_SESSION,error:h,fatal:!1},`Error generating key-session request: ${h}`)}).then(()=>d).catch(h=>{throw u.removeAllListeners(),this.removeSession(e),h}).then(()=>(u.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${lt.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${lt.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){let t=this.config,i=t.loader,r=new i(t),s=this.getServerCertificateUrl(e);return s?(this.log(`Fetching serverCertificate for "${e}"`),new Promise((n,o)=>{let l={responseType:"arraybuffer",url:s},c=t.certLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,m,y,E)=>{n(h.data)},onError:(h,m,y,E)=>{o(new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:y,response:Ze({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${s}). Status: ${h.code} (${h.text})`))},onTimeout:(h,m,y)=>{o(new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:y,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${s})`))},onAbort:(h,m,y)=>{o(new Error("aborted"))}};r.load(l,u,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((r,s)=>{e.setServerCertificate(i).then(n=>{this.log(`setServerCertificate ${n?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${t}"`),r(e)}).catch(n=>{s(new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:n,fatal:!0},n.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(r=>{throw new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:r,fatal:!0},r.message)}))}setupLicenseXHR(e,t,i,r){let s=this.config.licenseXhrSetup;return s?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,t,i,r)}).catch(n=>{if(!i.decryptdata)throw n;return e.open("POST",t,!0),s.call(this.hls,e,t,i,r)}).then(n=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:n||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let i=this.config.keyLoadPolicy.default;return new Promise((r,s)=>{let n=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${n}`);let o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);let c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,o,n,e)}catch(u){this.error(u)}r(l)}else{let l=i.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)s(new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:n,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${n}). Status: ${o.status} (${o.statusText})`));else{let u=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(r,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,n,e,t).then(({xhr:l,licenseChallenge:c})=>{l.send(c)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){let e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Dt.clearKeyUriToKeyIdMap();let i=t.length;_t.CDMCleanupPromise=Promise.all(t.map(r=>this.removeSession(r)).concat(e==null?void 0:e.setMediaKeys(null).catch(r=>{this.log(`Could not clear media keys: ${r}. media.src: ${e==null?void 0:e.src}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(r=>{this.log(`Could not close sessions and clear media keys: ${r}. media.src: ${e==null?void 0:e.src}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let i=t.reduce((r,s)=>(r.indexOf(s.keyFormat)===-1&&r.push(s.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),t.onmessage=null,t.onkeystatuseschange=null,i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let r=this.mediaKeySessions.indexOf(e);return r>-1&&this.mediaKeySessions.splice(r,1),t.remove().catch(s=>{this.log(`Could not remove session: ${s}`)}).then(()=>t.close()).catch(s=>{this.log(`Could not close session: ${s}`)})}}};_t.CDMCleanupPromise=void 0;var Qe=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}},md=1,ze={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},pd="h",dt=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=r=>{try{this.apply(r,{ot:ze.MANIFEST,su:!this.initialized})}catch(s){w.warn("Could not generate manifest CMCD data.",s)}},this.applyFragmentData=r=>{try{let s=r.frag,n=this.hls.levels[s.level],o=this.getObjectType(s),l={d:s.duration*1e3,ot:o};(o===ze.VIDEO||o===ze.AUDIO||o==ze.MUXED)&&(l.br=n.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(r,l)}catch(s){w.warn("Could not generate segment CMCD data.",s)}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||dt.uuid(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.registerListeners())}registerListeners(){let e=this.hls;e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHED,this.onMediaDetached,this),e.on(v.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHED,this.onMediaDetached,this),e.off(v.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){!this.media||(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,r;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(r=t.tracks.video)==null?void 0:r.buffer}createData(){var e;return{v:md,sf:pd,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){De(t,this.createData());let i=t.ot===ze.INIT||t.ot===ze.VIDEO||t.ot===ze.MUXED;if(this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering),this.useHeaders){let r=dt.toHeaders(t);if(!Object.keys(r).length)return;e.headers||(e.headers={}),De(e.headers,r)}else{let r=dt.toQuery(t);if(!r)return;e.url=dt.appendQueryToUri(e.url,r)}}getObjectType(e){let{type:t}=e;if(t==="subtitle")return ze.TIMED_TEXT;if(e.sn==="initSegment")return ze.INIT;if(t==="audio")return ze.AUDIO;if(t==="main")return this.hls.audioTracks.length?ze.VIDEO:ze.MUXED}getTopBandwidth(e){let t=0,i,r=this.hls;if(e===ze.AUDIO)i=r.audioTracks;else{let s=r.maxAutoLevel,n=s>-1?s+1:r.levels.length;i=r.levels.slice(0,n)}for(let s of i)s.bitrate>t&&(t=s.bitrate);return t>0?t:NaN}getBufferLength(e){let t=this.hls.media,i=e===ze.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:xe.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new i(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,n,o){t(s),this.loader.load(s,n,o)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new i(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,n,o){t(s),this.loader.load(s,n,o)}}}static uuid(){let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}static serialize(e){let t=[],i=c=>!Number.isNaN(c)&&c!=null&&c!==""&&c!==!1,r=c=>Math.round(c),s=c=>r(c/100)*100,o={br:r,d:r,bl:s,dl:s,mtp:s,nor:c=>encodeURIComponent(c),rtp:s,tb:r},l=Object.keys(e||{}).sort();for(let c of l){let u=e[c];if(!i(u)||c==="v"&&u===1||c=="pr"&&u===1)continue;let d=o[c];d&&(u=d(u));let h=typeof u,m;c==="ot"||c==="sf"||c==="st"?m=`${c}=${u}`:h==="boolean"?m=c:h==="number"?m=`${c}=${u}`:m=`${c}=${JSON.stringify(u)}`,t.push(m)}return t.join(",")}static toHeaders(e){let t=Object.keys(e),i={},r=["Object","Request","Session","Status"],s=[{},{},{},{}],n={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(let o of t){let l=n[o]!=null?n[o]:1;s[l][o]=e[o]}for(let o=0;o<s.length;o++){let l=dt.serialize(s[o]);l&&(i[`CMCD-${r[o]}`]=l)}return i}static toQuery(e){return`CMCD=${encodeURIComponent(dt.serialize(e))}`}static appendQueryToUri(e,t){if(!t)return e;let i=e.includes("?")?"&":"?";return`${e}${i}${t}`}},yd=3e5,vs=class{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=w.log.bind(w,"[content-steering]:"),this.registerListeners()}registerListeners(){let e=this.hls;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;!e||(e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.ERROR,this.onError,this))}startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri)if(this.updated){let e=Math.max(this.timeToLoad*1e3-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,e)}else this.loadSteeringManifest(this.uri)}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),self.clearTimeout(this.reloadTimer)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:i}=t;if((i==null?void 0:i.action)===Ke.SendAlternateToPenaltyBox&&i.flags===st.MoveAllAlternatesMatchingHost){let r=this.pathwayPriority,s=this.pathwayId;this.penalizedPathways[s]||(this.penalizedPathways[s]=performance.now()),!r&&this.levels&&(r=this.levels.reduce((n,o)=>(n.indexOf(o.pathwayId)===-1&&n.push(o.pathwayId),n),[])),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==s)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t,i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach(s=>{r-i[s]>yd&&delete i[s]});for(let s=0;s<e.length;s++){let n=e[s];if(i[n])continue;if(n===this.pathwayId)return;let o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(n),t.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,this.hls.trigger(v.LEVELS_UPDATED,{levels:t});let c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}clonePathways(e){let t=this.levels;if(!t)return;let i={},r={};e.forEach(s=>{let{ID:n,"BASE-ID":o,"URI-REPLACEMENT":l}=s;if(t.some(u=>u.pathwayId===n))return;let c=this.getLevelsForPathway(o).map(u=>{let d=De({},u);d.details=void 0,d.url=io(u.uri,u.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l);let h=new be(u.attrs);h["PATHWAY-ID"]=n;let m=h.AUDIO&&`${h.AUDIO}_clone_${n}`,y=h.SUBTITLES&&`${h.SUBTITLES}_clone_${n}`;m&&(i[h.AUDIO]=m,h.AUDIO=m),y&&(r[h.SUBTITLES]=y,h.SUBTITLES=y),d.attrs=h;let E=new wt(d);return Ri(E,"audio",m),Ri(E,"text",y),E});t.push(...c),da(this.audioTracks,i,l,n),da(this.subtitleTracks,r,l,n)})}loadSteeringManifest(e){let t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){let u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+u)}let s={responseType:"json",url:r.href},n=t.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},l={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(u,d,h,m)=>{this.log(`Loaded steering manifest: "${r}"`);let y=u.data;if(y.VERSION!==1){this.log(`Steering VERSION ${y.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=y.TTL;let{"RELOAD-URI":E,"PATHWAY-CLONES":b,"PATHWAY-PRIORITY":A}=y;if(E)try{this.uri=new self.URL(E,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${E}`);return}this.scheduleRefresh(this.uri||h.url),b&&this.clonePathways(b),A&&this.updatePathwayPriority(A)},onError:(u,d,h,m)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${d.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let y=this.timeToLoad*1e3;if(u.code===429){let E=this.loader;if(typeof(E==null?void 0:E.getResponseHeader)=="function"){let b=E.getResponseHeader("Retry-After");b&&(y=parseFloat(b)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,y)},onTimeout:(u,d,h)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(s,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout(()=>{this.loadSteeringManifest(e)},t)}};function da(a,e,t,i){!a||Object.keys(e).forEach(r=>{let s=a.filter(n=>n.groupId===r).map(n=>{let o=De({},n);return o.details=void 0,o.attrs=new be(o.attrs),o.url=o.attrs.URI=io(n.url,n.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=i,o});a.push(...s)})}function io(a,e,t,i){let{HOST:r,PARAMS:s,[t]:n}=i,o;e&&(o=n==null?void 0:n[e],o&&(a=o));let l=new self.URL(a);return r&&!o&&(l.host=r),s&&Object.keys(s).sort().forEach(c=>{c&&l.searchParams.set(c,s[c])}),l.href}var vd=/^age:\s*[\d.]+\s*$/im,Bi=class{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Bt,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e)return;let i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let s=this.xhrSetup;s?Promise.resolve().then(()=>{if(!this.stats.aborted)return s(i,t.url)}).catch(n=>(i.open("GET",t.url,!0),s(i,t.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(n=>{this.callbacks.onError({code:i.status,text:n.message},t,i,r)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);let r=this.context.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:n}=i.loadPolicy;if(r)for(let o in r)e.setRequestHeader(o,r[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=s&&J(s)?s:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let r=t.readyState,s=this.config;if(!i.aborted&&r>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let n=t.status,o=t.responseType!=="text";if(n>=200&&n<300&&(o&&t.response||t.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);let l=o?t.response:t.responseText,c=t.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=c,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;let u=this.callbacks.onProgress;if(u&&u(i,e,l,t),!this.callbacks)return;let d={url:t.responseURL,data:l,code:n};this.callbacks.onSuccess(d,i,e,t)}else{let l=s.loadPolicy.errorRetry,c=i.retry;Li(l,c,!1,n)?this.retry(l):(w.error(`${n} while loading ${e.url}`),this.callbacks.onError({code:n,text:t.statusText},e,t,i))}}}loadtimeout(){var e;let t=(e=this.config)==null?void 0:e.loadPolicy.timeoutRetry,i=this.stats.retry;if(Li(t,i,!0))this.retry(t);else{w.warn(`timeout while loading ${this.context.url}`);let r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:i}=this;this.retryDelay=Ss(e,i.retry),i.retry++,w.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&vd.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}};function Td(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var Ed=/(\d+)-(\d+)\/(\d+)/,$i=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Sd,this.controller=new self.AbortController,this.stats=new Bt}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){let e=this.response;e!=null&&e.ok||(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){let r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();let s=xd(e,this.controller.signal),n=i.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:u}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=c&&J(c)?c:u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response)},t.timeout),self.fetch(this.request).then(d=>{this.response=this.loader=d;let h=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response)},u-(h-r.loading.start)),!d.ok){let{status:m,statusText:y}=d;throw new Ts(y||"fetch, bad network response",m,d)}return r.loading.first=h,r.total=_d(d.headers)||r.total,n&&J(t.highWaterMark)?this.loadProgressively(d,r,e,t.highWaterMark,n):o?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{let{response:h}=this;self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let m=d[l];m&&(r.loaded=r.total=m);let y={url:h.url,data:d,code:h.status};n&&!J(t.highWaterMark)&&n(r,e,d,h),i.onSuccess(y,r,e,h)}).catch(d=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;let h=d&&d.code||0,m=d?d.message:null;i.onError({code:h,text:m},e,d?d.details:null,r)})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,s){let n=new Mi,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return n.dataLength&&s(t,i,n.flush(),e),Promise.resolve(new ArrayBuffer(0));let u=c.value,d=u.length;return t.loaded+=d,d<r||n.dataLength?(n.push(u),n.dataLength>=r&&s(t,i,n.flush(),e)):s(t,i,u,e),l()}).catch(()=>Promise.reject());return l()}};function xd(a,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(De({},a.headers))};return a.rangeEnd&&t.headers.set("Range","bytes="+a.rangeStart+"-"+String(a.rangeEnd-1)),t}function bd(a){let e=Ed.exec(a);if(e)return parseInt(e[2])-parseInt(e[1])+1}function _d(a){let e=a.get("Content-Range");if(e){let i=bd(e);if(J(i))return i}let t=a.get("Content-Length");if(t)return parseInt(t)}function Sd(a,e){return new self.Request(a.url,e)}var Ts=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}},Ad=/\s/,Ld={newCue(a,e,t,i){let r=[],s,n,o,l,c,u=self.VTTCue||self.TextTrackCue;for(let h=0;h<i.rows.length;h++)if(s=i.rows[h],o=!0,l=0,c="",!s.isEmpty()){var d;for(let E=0;E<s.chars.length;E++)Ad.test(s.chars[E].uchar)&&o?l++:(c+=s.chars[E].uchar,o=!1);s.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let m=Ja(c.trim()),y=ks(e,t,m);a!=null&&(d=a.cues)!=null&&d.getCueById(y)||(n=new u(e,t,m),n.id=y,n.line=h+1,n.align="left",n.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(n))}return a&&r.length&&(r.sort((h,m)=>h.line==="auto"||m.line==="auto"?0:h.line>8&&m.line>8?m.line-h.line:h.line-m.line),r.forEach(h=>Ia(a,h))),r}},Rd={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Id=Ze(Ze({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:Bi,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:ts,bufferController:ls,capLevelController:ri,errorController:Or,fpsController:ys,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:ma,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,certLoadPolicy:{default:Rd},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},Dd()),{},{subtitleStreamController:ss,subtitleTrackController:as,timelineController:ps,audioStreamController:is,audioTrackController:rs,emeController:_t,cmcdController:dt,contentSteeringController:vs});function Dd(){return{cueHandler:Ld,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function wd(a,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let t=Es(a),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(s=>{let n=`${s==="level"?"playlist":s}LoadPolicy`,o=e[n]===void 0,l=[];r.forEach(c=>{let u=`${s}Loading${c}`,d=e[u];if(d!==void 0&&o){l.push(u);let h=t[n].default;switch(e[n]={default:h},c){case"TimeOut":h.maxLoadTimeMs=d,h.maxTimeToFirstByteMs=d;break;case"MaxRetry":h.errorRetry.maxNumRetry=d,h.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":h.errorRetry.retryDelayMs=d,h.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":h.errorRetry.maxRetryDelayMs=d,h.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&w.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${n}": ${JSON.stringify(e[n])}`)}),Ze(Ze({},t),e)}function Es(a){return a&&typeof a=="object"?Array.isArray(a)?a.map(Es):Object.keys(a).reduce((e,t)=>(e[t]=Es(a[t]),e),{}):a}function kd(a){let e=a.loader;e!==$i&&e!==Bi?(w.log("[config]: Custom loader detected, cannot enable progressive streaming"),a.progressive=!1):Td()&&(a.loader=$i,a.progressive=!0,a.enableSoftwareAES=!0,w.log("[config]: Progressive streaming enabled, using FetchLoader"))}var ht=class{static get version(){return"1.4.8"}static isSupported(){return vu()}static get Events(){return v}static get ErrorTypes(){return ie}static get ErrorDetails(){return N}static get DefaultConfig(){return ht.defaultConfig?ht.defaultConfig:Id}static set DefaultConfig(e){ht.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Ds,this._autoLevelCapping=void 0,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,sc(e.debug||!1,"Hls instance");let t=this.config=wd(ht.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,t.progressive&&kd(t);let{abrController:i,bufferController:r,capLevelController:s,errorController:n,fpsController:o}=t,l=new n(this),c=this.abrController=new i(this),u=this.bufferController=new r(this),d=this.capLevelController=new s(this),h=new o(this),m=new Lr(this),y=new Dr(this),E=t.contentSteeringController,b=E?new E(this):null,A=this.levelController=new Mr(this,b),D=new Fr(this),L=new Ur(this.config),F=this.streamController=new Zr(this,D,L);d.setStreamController(F),h.setStreamController(F);let k=[m,A,F];b&&k.splice(1,0,b),this.networkControllers=k;let G=[c,u,d,h,y,D];this.audioTrackController=this.createController(t.audioTrackController,k);let M=t.audioStreamController;M&&k.push(new M(this,D,L)),this.subtitleTrackController=this.createController(t.subtitleTrackController,k);let $=t.subtitleStreamController;$&&k.push(new $(this,D,L)),this.createController(t.timelineController,G),L.emeController=this.emeController=this.createController(t.emeController,G),this.cmcdController=this.createController(t.cmcdController,G),this.latencyController=this.createController(wr,G),this.coreComponents=G,k.push(l);let K=l.onErrorOut;typeof K=="function"&&this.on(v.ERROR,K,l)}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,r){this._emitter.off(e,t,i,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){w.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),this.trigger(v.ERROR,{type:ie.OTHER_ERROR,details:N.INTERNAL_EXCEPTION,fatal:!1,event:e,error:i})}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){w.log("destroy"),this.trigger(v.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){w.log("attachMedia"),this._media=e,this.trigger(v.MEDIA_ATTACHING,{media:e})}detachMedia(){w.log("detachMedia"),this.trigger(v.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();let t=this.media,i=this.url,r=this.url=xs.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});w.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(v.MANIFEST_LOADING,{url:e})}startLoad(e=-1){w.log(`startLoad(${e})`),this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){w.log("stopLoad"),this.networkControllers.forEach(e=>{e.stopLoad()})}swapAudioCodec(){w.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){w.log("recoverMediaError");let e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e,t=0){this.levelController.removeLevel(e,t)}get levels(){let e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){w.log(`set currentLevel:${e}`),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){w.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){w.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){w.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){return this.levelController.startLevel}set startLevel(e){w.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(w.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){kr.indexOf(e)>-1&&(this._maxHdcpLevel=e)}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this,r;if(t===-1&&e&&e.length?r=e.length-1:r=t,i)for(let s=r;s--;){let n=e[s].attrs["HDCP-LEVEL"];if(n&&n<=i)return s}return r}get nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}};ht.defaultConfig=void 0;var Le=ht;var $t=class extends Error{constructor(t,i=$t.MEDIA_ERR_CUSTOM,r,s){var n;super(t);this.name="MediaError",this.code=i,this.context=s,this.fatal=r!=null?r:i>=$t.MEDIA_ERR_NETWORK&&i<=$t.MEDIA_ERR_ENCRYPTED,this.message||(this.message=(n=$t.defaultMessages[this.code])!=null?n:"")}},$e=$t;$e.MEDIA_ERR_ABORTED=1,$e.MEDIA_ERR_NETWORK=2,$e.MEDIA_ERR_DECODE=3,$e.MEDIA_ERR_SRC_NOT_SUPPORTED=4,$e.MEDIA_ERR_ENCRYPTED=5,$e.MEDIA_ERR_CUSTOM=100,$e.defaultMessages={1:"You aborted the media playback",2:"A network error caused the media download to fail.",3:"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.",4:"An unsupported error occurred. The server or network failed, or your browser does not support this format.",5:"The media is encrypted and there are no keys to decrypt it."};var Cd=a=>a==null,Cs=(a,e)=>Cd(e)?!1:a in e,Ki={ANY:"any",MUTED:"muted"},gt={ON_DEMAND:"on-demand",LIVE:"live",UNKNOWN:"unknown"},Ps={MSE:"mse",NATIVE:"native"},Vi={HEADER:"header",QUERY:"query",NONE:"none"},fh=Object.values(Vi),mt={M3U8:"application/vnd.apple.mpegurl",MP4:"video/mp4"},qi={HLS:mt.M3U8},gh=Object.keys(qi),mh=[...Object.values(mt),"hls","HLS"];var Ve=(a,e,t,i,r=a)=>{r.addEventListener(e,t,i),a.addEventListener("teardown",()=>{r.removeEventListener(e,t)},{once:!0})};function ro(a,e,t){e&&t>e&&(t=e);for(let i=0;i<a.length;i++)if(a.start(i)<=t&&a.end(i)>=t)return!0;return!1}var so=a=>{let e=a.indexOf("?");if(e<0)return[a];let t=a.slice(0,e),i=a.slice(e);return[t,i]},si=a=>{let e=a.type;if(e){let i=e.toUpperCase();return Cs(i,qi)?qi[i]:e}let{src:t}=a;return t?Pd(t):""},Os=a=>a==="VOD"?gt.ON_DEMAND:gt.LIVE,Ms=a=>a==="EVENT"?Number.POSITIVE_INFINITY:a==="VOD"?Number.NaN:0,Pd=a=>{let e="";try{e=new URL(a).pathname}catch{console.error("invalid url")}let t=e.lastIndexOf(".");if(t<0)return"";let r=e.slice(t+1).toUpperCase();return Cs(r,mt)?mt[r]:""};var Od=Object.values(Ki),no=a=>typeof a=="boolean"||typeof a=="string"&&Od.includes(a),ao=({autoplay:a},e,t)=>{let i=!1,r=!1,s=no(a)?a:!!a,n=()=>{i||Ve(e,"playing",()=>{i=!0},{once:!0})};if(n(),Ve(e,"loadstart",()=>{i=!1,n(),Fs(e,s)},{once:!0}),Ve(e,"loadstart",()=>{t||(r=!Number.isFinite(e.duration)),Fs(e,s)},{once:!0}),t&&t.once(Le.Events.LEVEL_LOADED,(l,c)=>{var u;r=(u=c.details.live)!=null?u:!1}),!s){let l=()=>{!r||(t!=null&&t.liveSyncPosition?e.currentTime=t.liveSyncPosition:Number.isFinite(e.seekable.end(0))&&(e.currentTime=e.seekable.end(0)))};t&&Ve(e,"play",()=>{e.preload==="metadata"?t.once(Le.Events.LEVEL_UPDATED,l):l()},{once:!0})}return l=>{i||(s=no(l)?l:!!l,Fs(e,s))}},Fs=(a,e)=>{if(!e)return;let t=a.muted,i=()=>a.muted=t;switch(e){case Ki.ANY:a.play().catch(()=>{a.muted=!0,a.play().catch(i)});break;case Ki.MUTED:a.muted=!0,a.play().catch(i);break;default:a.play().catch(()=>{});break}};var oo=({preload:a,src:e},t,i)=>{let r=d=>{d!=null&&["","none","metadata","auto"].includes(d)?t.setAttribute("preload",d):t.removeAttribute("preload")};if(!i)return r(a),r;let s=!1,n=!1,o=i.config.maxBufferLength,l=i.config.maxBufferSize,c=d=>{r(d);let h=d!=null?d:t.preload;n||h==="none"||(h==="metadata"?(i.config.maxBufferLength=1,i.config.maxBufferSize=1):(i.config.maxBufferLength=o,i.config.maxBufferSize=l),u())},u=()=>{!s&&e&&(s=!0,i.loadSource(e))};return Ve(t,"play",()=>{n=!0,i.config.maxBufferLength=o,i.config.maxBufferSize=l,u()},{once:!0}),c(a),c};function lo(a,e){if(!("videoTracks"in a))return;let t=new WeakMap;e.on(Le.Events.MANIFEST_PARSED,function(s,n){r();let o=a.addVideoTrack("main");o.selected=!0;for(let[l,c]of n.levels.entries()){let u=o.addRendition(c.url[0],c.width,c.height,c.videoCodec,c.bitrate);t.set(c,`${l}`),u.id=`${l}`}}),e.on(Le.Events.LEVELS_UPDATED,function(s,n){var c;let o=a.videoTracks[(c=a.videoTracks.selectedIndex)!=null?c:0];if(!o)return;let l=n.levels.map(u=>t.get(u));for(let u of a.videoRenditions)u.id&&!l.includes(u.id)&&o.removeRendition(u)});let i=s=>{let n=s.target.selectedIndex;n!=e.nextLevel&&(e.nextLevel=n)};a.videoRenditions.addEventListener("change",i);let r=()=>{for(let s of a.videoTracks)a.removeVideoTrack(s)};e.once(Le.Events.DESTROYING,()=>{r()})}function co(a,e){e.on(Le.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(r,{tracks:s})=>{s.forEach(n=>{var c;let o=(c=n.subtitleTrack)!=null?c:n.closedCaptions,l=e.subtitleTracks.findIndex(({lang:u,name:d,type:h})=>u==(o==null?void 0:o.lang)&&d===n.label&&h.toLowerCase()===n.kind);Ns(a,n.kind,n.label,o==null?void 0:o.lang,`${n.kind}${l}`)})});let t=()=>{var n;if(!e.subtitleTracks.length)return;let r=Array.from(a.textTracks).find(o=>o.id&&o.mode==="showing"&&["subtitles","captions"].includes(o.kind)),s=`${(n=e.subtitleTracks[e.subtitleTrack])==null?void 0:n.type.toLowerCase()}${e.subtitleTrack}`;if(r&&(e.subtitleTrack<0||(r==null?void 0:r.id)!==s)){let o=e.subtitleTracks.findIndex(({lang:l,name:c,type:u})=>l==r.language&&c===r.label&&u.toLowerCase()===r.kind);e.subtitleTrack=o}r&&(r==null?void 0:r.id)===s&&r.cues&&Array.from(r.cues).forEach(o=>{r.addCue(o)})};a.textTracks.addEventListener("change",t),e.on(Le.Events.CUES_PARSED,(r,{track:s,cues:n})=>{let o=a.textTracks.getTrackById(s);if(!o)return;let l=o.mode==="disabled";l&&(o.mode="hidden"),n.forEach(c=>{var u;(u=o.cues)!=null&&u.getCueById(c.id)||o.addCue(c)}),l&&(o.mode="disabled")}),e.once(Le.Events.DESTROYING,()=>{a.textTracks.removeEventListener("change",t),a.querySelectorAll("track[data-removeondestroy]").forEach(s=>{s.remove()})});let i=()=>{Array.from(a.textTracks).forEach(r=>{var s,n;if(!["subtitles","caption"].includes(r.kind)&&r.label==="thumbnails"){if(!((s=r.cues)!=null&&s.length)){let o=a.querySelector('track[label="thumbnails"]'),l=(n=o==null?void 0:o.getAttribute("src"))!=null?n:"";o==null||o.removeAttribute("src"),setTimeout(()=>{o==null||o.setAttribute("src",l)},0)}r.mode!=="hidden"&&(r.mode="hidden")}})};e.once(Le.Events.MANIFEST_LOADED,i),e.once(Le.Events.MEDIA_ATTACHED,i)}function Ns(a,e,t,i,r){let s=document.createElement("track");return s.kind=e,s.label=t,i&&(s.srclang=i),r&&(s.id=r),s.track.mode=["subtitles","captions"].includes(e)?"disabled":"hidden",s.setAttribute("data-removeondestroy",""),a.append(s),s.track}function Md(a,e){let t=Array.prototype.find.call(a.querySelectorAll("track"),i=>i.track===e);t==null||t.remove()}var ni="cuepoints",Us=Object.freeze({label:ni}),Wi=(a,{label:e=ni}=Us)=>{var t;return(t=Array.from(a.querySelectorAll("track")).find(i=>i.track.label===e&&i.track.kind==="metadata"))==null?void 0:t.track};async function uo(a,e,t=Us){let i=Wi(a,t);if(!i){let{label:r=ni}=t;i=Ns(a,"metadata",r),i.mode="hidden",await new Promise(s=>setTimeout(()=>s(void 0),0))}return i.mode!=="hidden"&&(i.mode="hidden"),[...e].sort(({time:r},{time:s})=>s-r).forEach(({time:r,value:s})=>{var d,h;let n=Array.prototype.findIndex.call(i==null?void 0:i.cues,m=>m.startTime>=r),o=(d=i==null?void 0:i.cues)==null?void 0:d[n],l=o?o.startTime:Number.isFinite(a.duration)?a.duration:Number.MAX_SAFE_INTEGER,c=(h=i==null?void 0:i.cues)==null?void 0:h[n-1];c&&(c.endTime=r);let u=new VTTCue(r,l,JSON.stringify(s!=null?s:null));i.addCue(u)}),i}var ho=a=>({time:a.startTime,value:JSON.parse(a.text)});function Fd(a,e={label:ni}){let t=Wi(a,e);return t!=null&&t.cues?Array.from(t.cues,i=>ho(i)):[]}function fo(a,e={label:ni}){var s,n;let t=Wi(a,e);if(!((s=t==null?void 0:t.activeCues)!=null&&s.length))return;let{currentTime:i}=a,r=Array.prototype.find.call((n=t.activeCues)!=null?n:[],({startTime:o,endTime:l})=>o<=i&&l>i);return ho(r)}async function go(a,e=Us){return new Promise(t=>{Ve(a,"loadstart",async()=>{let i=await uo(a,[],e);Ve(a,"cuechange",()=>{let r=fo(a);if(r){let s=new CustomEvent("cuepointchange",{composed:!0,bubbles:!0,detail:r});a.dispatchEvent(s)}},{},i),t(i)})})}function Nd(a,e){if(e){let t=e.playingDate;if(t!=null)return new Date(t.getTime()-a.currentTime*1e3)}return typeof a.getStartDate=="function"?a.getStartDate():new Date(NaN)}function Ud(a,e){if(e&&e.playingDate)return e.playingDate;if(typeof a.getStartDate=="function"){let t=a.getStartDate();return new Date(t.getTime()+a.currentTime*1e3)}return new Date(NaN)}var Bd=async a=>fetch(a).then(e=>e.text()).then(e=>{let t=e.split(`
|
|
44
|
+
} (data length: ${t&&t.byteLength})`),r.update(t)}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,i)=>{let r=tr(this.config),s=e.map(In).filter(n=>!!n&&r.indexOf(n)!==-1);return this.getKeySystemSelectionPromise(s).then(({keySystem:n})=>{let o=Dn(n);o?t(o):i(new Error(`Unable to find format for key-system "${n}"`))}).catch(i)})}loadKey(e){let t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let s=this.keyIdToKeySessionPromise[i];return s||(s=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then(({keySystem:n,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(n,o).then(()=>{this.throwIfDestroyed();let l=this.createMediaKeySessionContext({keySystem:n,mediaKeys:o,decryptdata:t}),c="cenc";return this.generateRequestWithPreferredKeySession(l,c,t.pssh,"playlist-key")}))),s.catch(n=>this.handleError(n))),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){!this.hls||(this.error(e.message),e instanceof Qe?this.hls.trigger(v.ERROR,e.data):this.hls.trigger(v.ERROR,{type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){let t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){let r=In(e.keyFormat),s=r?[r]:tr(this.config);return this.attemptKeySystemAccess(s)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=tr(this.config)),e.length===0)throw new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){let{initDataType:t,initData:i}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),i===null)return;let r,s;if(t==="sinf"&&this.config.drmSystems[Se.FAIRPLAY]){let u=Ne(new Uint8Array(i));try{let d=bs(JSON.parse(u).sinf),h=_a(new Uint8Array(d));if(!h)return;r=h.subarray(8,24),s=Se.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{let u=Nc(i);if(u===null)return;u.version===0&&u.systemId===ga.WIDEVINE&&u.data&&(r=u.data.subarray(8,24)),s=hc(u.systemId)}if(!s||!r)return;let n=lt.hexDump(r),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this,c=o[n];for(let u=0;u<l.length;u++){let d=l[u],h=d.decryptdata;if(h.pssh||!h.keyId)continue;let m=lt.hexDump(h.keyId);if(n===m||h.uri.replace(/-/g,"").indexOf(n)!==-1){c=o[m],delete o[m],h.pssh=new Uint8Array(i),h.keyId=r,c=o[n]=c.then(()=>this.generateRequestWithPreferredKeySession(d,t,i,"encrypted-event-key-match"));break}}c||(c=o[n]=this.getKeySystemSelectionPromise([s]).then(({keySystem:u,mediaKeys:d})=>{var h;this.throwIfDestroyed();let m=new Dt("ISO-23001-7",n,(h=Dn(u))!=null?h:"");return m.pssh=new Uint8Array(i),m.keyId=r,this.attemptSetMediaKeys(u,d).then(()=>{this.throwIfDestroyed();let y=this.createMediaKeySessionContext({decryptdata:m,keySystem:u,mediaKeys:d});return this.generateRequestWithPreferredKeySession(y,t,i,"encrypted-event-no-match")})})),c.catch(u=>this.handleError(u))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(s=>i.indexOf(s)===-1)})}generateRequestWithPreferredKeySession(e,t,i,r){var s,n;let o=(s=this.config.drmSystems)==null||(n=s[e.keySystem])==null?void 0:n.generateRequest;if(o)try{let h=o.call(this.hls,t,i,e);if(!h)throw new Error("Invalid response from configured generateRequest filter");t=h.initDataType,i=e.decryptdata.pssh=h.initData?new Uint8Array(h.initData):null}catch(h){var l;if(this.warn(h.message),(l=this.hls)!=null&&l.config.debug)throw h}if(i===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let c=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${c} (init data type: ${t} length: ${i?i.byteLength:null})`);let u=new Ds;e.mediaKeysSession.onmessage=h=>{let m=e.mediaKeysSession;if(!m){u.emit("error",new Error("invalid state"));return}let{messageType:y,message:E}=h;this.log(`"${y}" message event for session "${m.sessionId}" message size: ${E.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,E).catch(b=>{this.handleError(b),u.emit("error",b)}):y==="license-release"?e.keySystem===Se.FAIRPLAY&&(this.updateKeySession(e,fa("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${y}"`)},e.mediaKeysSession.onkeystatuseschange=h=>{if(!e.mediaKeysSession){u.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);let y=e.keyStatus;u.emit("keyStatus",y),y==="expired"&&(this.warn(`${e.keySystem} expired for key ${c}`),this.renewKeySession(e))};let d=new Promise((h,m)=>{u.on("error",m),u.on("keyStatus",y=>{y.startsWith("usable")?h():y==="output-restricted"?m(new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):y==="internal-error"?m(new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${y}"`)):y==="expired"?m(new Error("key expired while generating request")):this.warn(`unhandled key status change "${y}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var h;this.log(`Request generated for key-session "${(h=e.mediaKeysSession)==null?void 0:h.sessionId}" keyId: ${c}`)}).catch(h=>{throw new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_NO_SESSION,error:h,fatal:!1},`Error generating key-session request: ${h}`)}).then(()=>d).catch(h=>{throw u.removeAllListeners(),this.removeSession(e),h}).then(()=>(u.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${lt.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${lt.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){let t=this.config,i=t.loader,r=new i(t),s=this.getServerCertificateUrl(e);return s?(this.log(`Fetching serverCertificate for "${e}"`),new Promise((n,o)=>{let l={responseType:"arraybuffer",url:s},c=t.certLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,m,y,E)=>{n(h.data)},onError:(h,m,y,E)=>{o(new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:y,response:Ze({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${s}). Status: ${h.code} (${h.text})`))},onTimeout:(h,m,y)=>{o(new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:y,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${s})`))},onAbort:(h,m,y)=>{o(new Error("aborted"))}};r.load(l,u,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((r,s)=>{e.setServerCertificate(i).then(n=>{this.log(`setServerCertificate ${n?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${t}"`),r(e)}).catch(n=>{s(new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:n,fatal:!0},n.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(r=>{throw new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:r,fatal:!0},r.message)}))}setupLicenseXHR(e,t,i,r){let s=this.config.licenseXhrSetup;return s?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,t,i,r)}).catch(n=>{if(!i.decryptdata)throw n;return e.open("POST",t,!0),s.call(this.hls,e,t,i,r)}).then(n=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:n||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let i=this.config.keyLoadPolicy.default;return new Promise((r,s)=>{let n=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${n}`);let o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);let c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,o,n,e)}catch(u){this.error(u)}r(l)}else{let l=i.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)s(new Qe({type:ie.KEY_SYSTEM_ERROR,details:N.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:n,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${n}). Status: ${o.status} (${o.statusText})`));else{let u=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(r,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,n,e,t).then(({xhr:l,licenseChallenge:c})=>{l.send(c)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){let e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Dt.clearKeyUriToKeyIdMap();let i=t.length;_t.CDMCleanupPromise=Promise.all(t.map(r=>this.removeSession(r)).concat(e==null?void 0:e.setMediaKeys(null).catch(r=>{this.log(`Could not clear media keys: ${r}. media.src: ${e==null?void 0:e.src}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(r=>{this.log(`Could not close sessions and clear media keys: ${r}. media.src: ${e==null?void 0:e.src}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let i=t.reduce((r,s)=>(r.indexOf(s.keyFormat)===-1&&r.push(s.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),t.onmessage=null,t.onkeystatuseschange=null,i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let r=this.mediaKeySessions.indexOf(e);return r>-1&&this.mediaKeySessions.splice(r,1),t.remove().catch(s=>{this.log(`Could not remove session: ${s}`)}).then(()=>t.close()).catch(s=>{this.log(`Could not close session: ${s}`)})}}};_t.CDMCleanupPromise=void 0;var Qe=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}},md=1,ze={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},pd="h",dt=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=r=>{try{this.apply(r,{ot:ze.MANIFEST,su:!this.initialized})}catch(s){w.warn("Could not generate manifest CMCD data.",s)}},this.applyFragmentData=r=>{try{let s=r.frag,n=this.hls.levels[s.level],o=this.getObjectType(s),l={d:s.duration*1e3,ot:o};(o===ze.VIDEO||o===ze.AUDIO||o==ze.MUXED)&&(l.br=n.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(r,l)}catch(s){w.warn("Could not generate segment CMCD data.",s)}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||dt.uuid(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.registerListeners())}registerListeners(){let e=this.hls;e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHED,this.onMediaDetached,this),e.on(v.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHED,this.onMediaDetached,this),e.off(v.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){!this.media||(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,r;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(r=t.tracks.video)==null?void 0:r.buffer}createData(){var e;return{v:md,sf:pd,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){De(t,this.createData());let i=t.ot===ze.INIT||t.ot===ze.VIDEO||t.ot===ze.MUXED;if(this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering),this.useHeaders){let r=dt.toHeaders(t);if(!Object.keys(r).length)return;e.headers||(e.headers={}),De(e.headers,r)}else{let r=dt.toQuery(t);if(!r)return;e.url=dt.appendQueryToUri(e.url,r)}}getObjectType(e){let{type:t}=e;if(t==="subtitle")return ze.TIMED_TEXT;if(e.sn==="initSegment")return ze.INIT;if(t==="audio")return ze.AUDIO;if(t==="main")return this.hls.audioTracks.length?ze.VIDEO:ze.MUXED}getTopBandwidth(e){let t=0,i,r=this.hls;if(e===ze.AUDIO)i=r.audioTracks;else{let s=r.maxAutoLevel,n=s>-1?s+1:r.levels.length;i=r.levels.slice(0,n)}for(let s of i)s.bitrate>t&&(t=s.bitrate);return t>0?t:NaN}getBufferLength(e){let t=this.hls.media,i=e===ze.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:xe.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new i(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,n,o){t(s),this.loader.load(s,n,o)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new i(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,n,o){t(s),this.loader.load(s,n,o)}}}static uuid(){let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}static serialize(e){let t=[],i=c=>!Number.isNaN(c)&&c!=null&&c!==""&&c!==!1,r=c=>Math.round(c),s=c=>r(c/100)*100,o={br:r,d:r,bl:s,dl:s,mtp:s,nor:c=>encodeURIComponent(c),rtp:s,tb:r},l=Object.keys(e||{}).sort();for(let c of l){let u=e[c];if(!i(u)||c==="v"&&u===1||c=="pr"&&u===1)continue;let d=o[c];d&&(u=d(u));let h=typeof u,m;c==="ot"||c==="sf"||c==="st"?m=`${c}=${u}`:h==="boolean"?m=c:h==="number"?m=`${c}=${u}`:m=`${c}=${JSON.stringify(u)}`,t.push(m)}return t.join(",")}static toHeaders(e){let t=Object.keys(e),i={},r=["Object","Request","Session","Status"],s=[{},{},{},{}],n={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(let o of t){let l=n[o]!=null?n[o]:1;s[l][o]=e[o]}for(let o=0;o<s.length;o++){let l=dt.serialize(s[o]);l&&(i[`CMCD-${r[o]}`]=l)}return i}static toQuery(e){return`CMCD=${encodeURIComponent(dt.serialize(e))}`}static appendQueryToUri(e,t){if(!t)return e;let i=e.includes("?")?"&":"?";return`${e}${i}${t}`}},yd=3e5,vs=class{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=w.log.bind(w,"[content-steering]:"),this.registerListeners()}registerListeners(){let e=this.hls;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;!e||(e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.ERROR,this.onError,this))}startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri)if(this.updated){let e=Math.max(this.timeToLoad*1e3-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,e)}else this.loadSteeringManifest(this.uri)}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),self.clearTimeout(this.reloadTimer)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:i}=t;if((i==null?void 0:i.action)===Ke.SendAlternateToPenaltyBox&&i.flags===st.MoveAllAlternatesMatchingHost){let r=this.pathwayPriority,s=this.pathwayId;this.penalizedPathways[s]||(this.penalizedPathways[s]=performance.now()),!r&&this.levels&&(r=this.levels.reduce((n,o)=>(n.indexOf(o.pathwayId)===-1&&n.push(o.pathwayId),n),[])),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==s)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t,i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach(s=>{r-i[s]>yd&&delete i[s]});for(let s=0;s<e.length;s++){let n=e[s];if(i[n])continue;if(n===this.pathwayId)return;let o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(n),t.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,this.hls.trigger(v.LEVELS_UPDATED,{levels:t});let c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}clonePathways(e){let t=this.levels;if(!t)return;let i={},r={};e.forEach(s=>{let{ID:n,"BASE-ID":o,"URI-REPLACEMENT":l}=s;if(t.some(u=>u.pathwayId===n))return;let c=this.getLevelsForPathway(o).map(u=>{let d=De({},u);d.details=void 0,d.url=io(u.uri,u.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l);let h=new be(u.attrs);h["PATHWAY-ID"]=n;let m=h.AUDIO&&`${h.AUDIO}_clone_${n}`,y=h.SUBTITLES&&`${h.SUBTITLES}_clone_${n}`;m&&(i[h.AUDIO]=m,h.AUDIO=m),y&&(r[h.SUBTITLES]=y,h.SUBTITLES=y),d.attrs=h;let E=new wt(d);return Ri(E,"audio",m),Ri(E,"text",y),E});t.push(...c),da(this.audioTracks,i,l,n),da(this.subtitleTracks,r,l,n)})}loadSteeringManifest(e){let t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){let u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+u)}let s={responseType:"json",url:r.href},n=t.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},l={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(u,d,h,m)=>{this.log(`Loaded steering manifest: "${r}"`);let y=u.data;if(y.VERSION!==1){this.log(`Steering VERSION ${y.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=y.TTL;let{"RELOAD-URI":E,"PATHWAY-CLONES":b,"PATHWAY-PRIORITY":A}=y;if(E)try{this.uri=new self.URL(E,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${E}`);return}this.scheduleRefresh(this.uri||h.url),b&&this.clonePathways(b),A&&this.updatePathwayPriority(A)},onError:(u,d,h,m)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${d.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let y=this.timeToLoad*1e3;if(u.code===429){let E=this.loader;if(typeof(E==null?void 0:E.getResponseHeader)=="function"){let b=E.getResponseHeader("Retry-After");b&&(y=parseFloat(b)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,y)},onTimeout:(u,d,h)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(s,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout(()=>{this.loadSteeringManifest(e)},t)}};function da(a,e,t,i){!a||Object.keys(e).forEach(r=>{let s=a.filter(n=>n.groupId===r).map(n=>{let o=De({},n);return o.details=void 0,o.attrs=new be(o.attrs),o.url=o.attrs.URI=io(n.url,n.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=i,o});a.push(...s)})}function io(a,e,t,i){let{HOST:r,PARAMS:s,[t]:n}=i,o;e&&(o=n==null?void 0:n[e],o&&(a=o));let l=new self.URL(a);return r&&!o&&(l.host=r),s&&Object.keys(s).sort().forEach(c=>{c&&l.searchParams.set(c,s[c])}),l.href}var vd=/^age:\s*[\d.]+\s*$/im,Bi=class{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Bt,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e)return;let i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let s=this.xhrSetup;s?Promise.resolve().then(()=>{if(!this.stats.aborted)return s(i,t.url)}).catch(n=>(i.open("GET",t.url,!0),s(i,t.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(n=>{this.callbacks.onError({code:i.status,text:n.message},t,i,r)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);let r=this.context.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:n}=i.loadPolicy;if(r)for(let o in r)e.setRequestHeader(o,r[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=s&&J(s)?s:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let r=t.readyState,s=this.config;if(!i.aborted&&r>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let n=t.status,o=t.responseType!=="text";if(n>=200&&n<300&&(o&&t.response||t.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);let l=o?t.response:t.responseText,c=t.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=c,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;let u=this.callbacks.onProgress;if(u&&u(i,e,l,t),!this.callbacks)return;let d={url:t.responseURL,data:l,code:n};this.callbacks.onSuccess(d,i,e,t)}else{let l=s.loadPolicy.errorRetry,c=i.retry;Li(l,c,!1,n)?this.retry(l):(w.error(`${n} while loading ${e.url}`),this.callbacks.onError({code:n,text:t.statusText},e,t,i))}}}loadtimeout(){var e;let t=(e=this.config)==null?void 0:e.loadPolicy.timeoutRetry,i=this.stats.retry;if(Li(t,i,!0))this.retry(t);else{w.warn(`timeout while loading ${this.context.url}`);let r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:i}=this;this.retryDelay=Ss(e,i.retry),i.retry++,w.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&vd.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}};function Td(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var Ed=/(\d+)-(\d+)\/(\d+)/,$i=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Sd,this.controller=new self.AbortController,this.stats=new Bt}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){let e=this.response;e!=null&&e.ok||(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){let r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();let s=xd(e,this.controller.signal),n=i.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:u}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=c&&J(c)?c:u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response)},t.timeout),self.fetch(this.request).then(d=>{this.response=this.loader=d;let h=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response)},u-(h-r.loading.start)),!d.ok){let{status:m,statusText:y}=d;throw new Ts(y||"fetch, bad network response",m,d)}return r.loading.first=h,r.total=_d(d.headers)||r.total,n&&J(t.highWaterMark)?this.loadProgressively(d,r,e,t.highWaterMark,n):o?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{let{response:h}=this;self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let m=d[l];m&&(r.loaded=r.total=m);let y={url:h.url,data:d,code:h.status};n&&!J(t.highWaterMark)&&n(r,e,d,h),i.onSuccess(y,r,e,h)}).catch(d=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;let h=d&&d.code||0,m=d?d.message:null;i.onError({code:h,text:m},e,d?d.details:null,r)})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,s){let n=new Mi,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return n.dataLength&&s(t,i,n.flush(),e),Promise.resolve(new ArrayBuffer(0));let u=c.value,d=u.length;return t.loaded+=d,d<r||n.dataLength?(n.push(u),n.dataLength>=r&&s(t,i,n.flush(),e)):s(t,i,u,e),l()}).catch(()=>Promise.reject());return l()}};function xd(a,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(De({},a.headers))};return a.rangeEnd&&t.headers.set("Range","bytes="+a.rangeStart+"-"+String(a.rangeEnd-1)),t}function bd(a){let e=Ed.exec(a);if(e)return parseInt(e[2])-parseInt(e[1])+1}function _d(a){let e=a.get("Content-Range");if(e){let i=bd(e);if(J(i))return i}let t=a.get("Content-Length");if(t)return parseInt(t)}function Sd(a,e){return new self.Request(a.url,e)}var Ts=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}},Ad=/\s/,Ld={newCue(a,e,t,i){let r=[],s,n,o,l,c,u=self.VTTCue||self.TextTrackCue;for(let h=0;h<i.rows.length;h++)if(s=i.rows[h],o=!0,l=0,c="",!s.isEmpty()){var d;for(let E=0;E<s.chars.length;E++)Ad.test(s.chars[E].uchar)&&o?l++:(c+=s.chars[E].uchar,o=!1);s.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let m=Ja(c.trim()),y=ks(e,t,m);a!=null&&(d=a.cues)!=null&&d.getCueById(y)||(n=new u(e,t,m),n.id=y,n.line=h+1,n.align="left",n.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(n))}return a&&r.length&&(r.sort((h,m)=>h.line==="auto"||m.line==="auto"?0:h.line>8&&m.line>8?m.line-h.line:h.line-m.line),r.forEach(h=>Ia(a,h))),r}},Rd={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Id=Ze(Ze({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:Bi,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:ts,bufferController:ls,capLevelController:ri,errorController:Or,fpsController:ys,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:ma,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,certLoadPolicy:{default:Rd},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},Dd()),{},{subtitleStreamController:ss,subtitleTrackController:as,timelineController:ps,audioStreamController:is,audioTrackController:rs,emeController:_t,cmcdController:dt,contentSteeringController:vs});function Dd(){return{cueHandler:Ld,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function wd(a,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let t=Es(a),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(s=>{let n=`${s==="level"?"playlist":s}LoadPolicy`,o=e[n]===void 0,l=[];r.forEach(c=>{let u=`${s}Loading${c}`,d=e[u];if(d!==void 0&&o){l.push(u);let h=t[n].default;switch(e[n]={default:h},c){case"TimeOut":h.maxLoadTimeMs=d,h.maxTimeToFirstByteMs=d;break;case"MaxRetry":h.errorRetry.maxNumRetry=d,h.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":h.errorRetry.retryDelayMs=d,h.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":h.errorRetry.maxRetryDelayMs=d,h.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&w.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${n}": ${JSON.stringify(e[n])}`)}),Ze(Ze({},t),e)}function Es(a){return a&&typeof a=="object"?Array.isArray(a)?a.map(Es):Object.keys(a).reduce((e,t)=>(e[t]=Es(a[t]),e),{}):a}function kd(a){let e=a.loader;e!==$i&&e!==Bi?(w.log("[config]: Custom loader detected, cannot enable progressive streaming"),a.progressive=!1):Td()&&(a.loader=$i,a.progressive=!0,a.enableSoftwareAES=!0,w.log("[config]: Progressive streaming enabled, using FetchLoader"))}var ht=class{static get version(){return"1.4.8"}static isSupported(){return vu()}static get Events(){return v}static get ErrorTypes(){return ie}static get ErrorDetails(){return N}static get DefaultConfig(){return ht.defaultConfig?ht.defaultConfig:Id}static set DefaultConfig(e){ht.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Ds,this._autoLevelCapping=void 0,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,sc(e.debug||!1,"Hls instance");let t=this.config=wd(ht.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,t.progressive&&kd(t);let{abrController:i,bufferController:r,capLevelController:s,errorController:n,fpsController:o}=t,l=new n(this),c=this.abrController=new i(this),u=this.bufferController=new r(this),d=this.capLevelController=new s(this),h=new o(this),m=new Lr(this),y=new Dr(this),E=t.contentSteeringController,b=E?new E(this):null,A=this.levelController=new Mr(this,b),D=new Fr(this),L=new Ur(this.config),F=this.streamController=new Zr(this,D,L);d.setStreamController(F),h.setStreamController(F);let k=[m,A,F];b&&k.splice(1,0,b),this.networkControllers=k;let G=[c,u,d,h,y,D];this.audioTrackController=this.createController(t.audioTrackController,k);let M=t.audioStreamController;M&&k.push(new M(this,D,L)),this.subtitleTrackController=this.createController(t.subtitleTrackController,k);let $=t.subtitleStreamController;$&&k.push(new $(this,D,L)),this.createController(t.timelineController,G),L.emeController=this.emeController=this.createController(t.emeController,G),this.cmcdController=this.createController(t.cmcdController,G),this.latencyController=this.createController(wr,G),this.coreComponents=G,k.push(l);let K=l.onErrorOut;typeof K=="function"&&this.on(v.ERROR,K,l)}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,r){this._emitter.off(e,t,i,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){w.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),this.trigger(v.ERROR,{type:ie.OTHER_ERROR,details:N.INTERNAL_EXCEPTION,fatal:!1,event:e,error:i})}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){w.log("destroy"),this.trigger(v.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){w.log("attachMedia"),this._media=e,this.trigger(v.MEDIA_ATTACHING,{media:e})}detachMedia(){w.log("detachMedia"),this.trigger(v.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();let t=this.media,i=this.url,r=this.url=xs.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});w.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(v.MANIFEST_LOADING,{url:e})}startLoad(e=-1){w.log(`startLoad(${e})`),this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){w.log("stopLoad"),this.networkControllers.forEach(e=>{e.stopLoad()})}swapAudioCodec(){w.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){w.log("recoverMediaError");let e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e,t=0){this.levelController.removeLevel(e,t)}get levels(){let e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){w.log(`set currentLevel:${e}`),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){w.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){w.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){w.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){return this.levelController.startLevel}set startLevel(e){w.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(w.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){kr.indexOf(e)>-1&&(this._maxHdcpLevel=e)}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this,r;if(t===-1&&e&&e.length?r=e.length-1:r=t,i)for(let s=r;s--;){let n=e[s].attrs["HDCP-LEVEL"];if(n&&n<=i)return s}return r}get nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}};ht.defaultConfig=void 0;var Le=ht;var $t=class extends Error{constructor(t,i=$t.MEDIA_ERR_CUSTOM,r,s){var n;super(t);this.name="MediaError",this.code=i,this.context=s,this.fatal=r!=null?r:i>=$t.MEDIA_ERR_NETWORK&&i<=$t.MEDIA_ERR_ENCRYPTED,this.message||(this.message=(n=$t.defaultMessages[this.code])!=null?n:"")}},$e=$t;$e.MEDIA_ERR_ABORTED=1,$e.MEDIA_ERR_NETWORK=2,$e.MEDIA_ERR_DECODE=3,$e.MEDIA_ERR_SRC_NOT_SUPPORTED=4,$e.MEDIA_ERR_ENCRYPTED=5,$e.MEDIA_ERR_CUSTOM=100,$e.defaultMessages={1:"You aborted the media playback",2:"A network error caused the media download to fail.",3:"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.",4:"An unsupported error occurred. The server or network failed, or your browser does not support this format.",5:"The media is encrypted and there are no keys to decrypt it."};var Cd=a=>a==null,Cs=(a,e)=>Cd(e)?!1:a in e,Ki={ANY:"any",MUTED:"muted"},gt={ON_DEMAND:"on-demand",LIVE:"live",UNKNOWN:"unknown"},Ps={MSE:"mse",NATIVE:"native"},Vi={HEADER:"header",QUERY:"query",NONE:"none"},fh=Object.values(Vi),mt={M3U8:"application/vnd.apple.mpegurl",MP4:"video/mp4"},qi={HLS:mt.M3U8},gh=Object.keys(qi),mh=[...Object.values(mt),"hls","HLS"];var Ve=(a,e,t,i,r=a)=>{r.addEventListener(e,t,i),a.addEventListener("teardown",()=>{r.removeEventListener(e,t)},{once:!0})};function ro(a,e,t){e&&t>e&&(t=e);for(let i=0;i<a.length;i++)if(a.start(i)<=t&&a.end(i)>=t)return!0;return!1}var so=a=>{let e=a.indexOf("?");if(e<0)return[a];let t=a.slice(0,e),i=a.slice(e);return[t,i]},si=a=>{let e=a.type;if(e){let i=e.toUpperCase();return Cs(i,qi)?qi[i]:e}let{src:t}=a;return t?Pd(t):""},Os=a=>a==="VOD"?gt.ON_DEMAND:gt.LIVE,Ms=a=>a==="EVENT"?Number.POSITIVE_INFINITY:a==="VOD"?Number.NaN:0,Pd=a=>{let e="";try{e=new URL(a).pathname}catch{console.error("invalid url")}let t=e.lastIndexOf(".");if(t<0)return"";let r=e.slice(t+1).toUpperCase();return Cs(r,mt)?mt[r]:""};var Od=Object.values(Ki),no=a=>typeof a=="boolean"||typeof a=="string"&&Od.includes(a),ao=({autoplay:a},e,t)=>{let i=!1,r=!1,s=no(a)?a:!!a,n=()=>{i||Ve(e,"playing",()=>{i=!0},{once:!0})};if(n(),Ve(e,"loadstart",()=>{i=!1,n(),Fs(e,s)},{once:!0}),Ve(e,"loadstart",()=>{t||(r=!Number.isFinite(e.duration)),Fs(e,s)},{once:!0}),t&&t.once(Le.Events.LEVEL_LOADED,(l,c)=>{var u;r=(u=c.details.live)!=null?u:!1}),!s){let l=()=>{!r||(t!=null&&t.liveSyncPosition?e.currentTime=t.liveSyncPosition:Number.isFinite(e.seekable.end(0))&&(e.currentTime=e.seekable.end(0)))};t&&Ve(e,"play",()=>{e.preload==="metadata"?t.once(Le.Events.LEVEL_UPDATED,l):l()},{once:!0})}return l=>{i||(s=no(l)?l:!!l,Fs(e,s))}},Fs=(a,e)=>{if(!e)return;let t=a.muted,i=()=>a.muted=t;switch(e){case Ki.ANY:a.play().catch(()=>{a.muted=!0,a.play().catch(i)});break;case Ki.MUTED:a.muted=!0,a.play().catch(i);break;default:a.play().catch(()=>{});break}};var oo=({preload:a,src:e},t,i)=>{let r=d=>{d!=null&&["","none","metadata","auto"].includes(d)?t.setAttribute("preload",d):t.removeAttribute("preload")};if(!i)return r(a),r;let s=!1,n=!1,o=i.config.maxBufferLength,l=i.config.maxBufferSize,c=d=>{r(d);let h=d!=null?d:t.preload;n||h==="none"||(h==="metadata"?(i.config.maxBufferLength=1,i.config.maxBufferSize=1):(i.config.maxBufferLength=o,i.config.maxBufferSize=l),u())},u=()=>{!s&&e&&(s=!0,i.loadSource(e))};return Ve(t,"play",()=>{n=!0,i.config.maxBufferLength=o,i.config.maxBufferSize=l,u()},{once:!0}),c(a),c};function lo(a,e){if(!("videoTracks"in a))return;let t=new WeakMap;e.on(Le.Events.MANIFEST_PARSED,function(s,n){r();let o=a.addVideoTrack("main");o.selected=!0;for(let[l,c]of n.levels.entries()){let u=o.addRendition(c.url[0],c.width,c.height,c.videoCodec,c.bitrate);t.set(c,`${l}`),u.id=`${l}`}for(let[l,c]of n.audioTracks.entries()){let u=c.default?"main":"alternative",d=a.addAudioTrack(u,c.name,c.lang);d.id=`${l}`,c.default&&(d.enabled=!0)}}),a.audioTracks.addEventListener("change",()=>{e.audioTrack=[...a.audioTracks].find(s=>s.enabled).id}),e.on(Le.Events.LEVELS_UPDATED,function(s,n){var c;let o=a.videoTracks[(c=a.videoTracks.selectedIndex)!=null?c:0];if(!o)return;let l=n.levels.map(u=>t.get(u));for(let u of a.videoRenditions)u.id&&!l.includes(u.id)&&o.removeRendition(u)});let i=s=>{let n=s.target.selectedIndex;n!=e.nextLevel&&(e.nextLevel=n)};a.videoRenditions.addEventListener("change",i);let r=()=>{for(let s of a.videoTracks)a.removeVideoTrack(s);for(let s of a.audioTracks)a.removeAudioTrack(s)};e.once(Le.Events.DESTROYING,r)}function co(a,e){e.on(Le.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(r,{tracks:s})=>{s.forEach(n=>{var c;let o=(c=n.subtitleTrack)!=null?c:n.closedCaptions,l=e.subtitleTracks.findIndex(({lang:u,name:d,type:h})=>u==(o==null?void 0:o.lang)&&d===n.label&&h.toLowerCase()===n.kind);Ns(a,n.kind,n.label,o==null?void 0:o.lang,`${n.kind}${l}`)})});let t=()=>{var n;if(!e.subtitleTracks.length)return;let r=Array.from(a.textTracks).find(o=>o.id&&o.mode==="showing"&&["subtitles","captions"].includes(o.kind)),s=`${(n=e.subtitleTracks[e.subtitleTrack])==null?void 0:n.type.toLowerCase()}${e.subtitleTrack}`;if(r&&(e.subtitleTrack<0||(r==null?void 0:r.id)!==s)){let o=e.subtitleTracks.findIndex(({lang:l,name:c,type:u})=>l==r.language&&c===r.label&&u.toLowerCase()===r.kind);e.subtitleTrack=o}r&&(r==null?void 0:r.id)===s&&r.cues&&Array.from(r.cues).forEach(o=>{r.addCue(o)})};a.textTracks.addEventListener("change",t),e.on(Le.Events.CUES_PARSED,(r,{track:s,cues:n})=>{let o=a.textTracks.getTrackById(s);if(!o)return;let l=o.mode==="disabled";l&&(o.mode="hidden"),n.forEach(c=>{var u;(u=o.cues)!=null&&u.getCueById(c.id)||o.addCue(c)}),l&&(o.mode="disabled")}),e.once(Le.Events.DESTROYING,()=>{a.textTracks.removeEventListener("change",t),a.querySelectorAll("track[data-removeondestroy]").forEach(s=>{s.remove()})});let i=()=>{Array.from(a.textTracks).forEach(r=>{var s,n;if(!["subtitles","caption"].includes(r.kind)&&r.label==="thumbnails"){if(!((s=r.cues)!=null&&s.length)){let o=a.querySelector('track[label="thumbnails"]'),l=(n=o==null?void 0:o.getAttribute("src"))!=null?n:"";o==null||o.removeAttribute("src"),setTimeout(()=>{o==null||o.setAttribute("src",l)},0)}r.mode!=="hidden"&&(r.mode="hidden")}})};e.once(Le.Events.MANIFEST_LOADED,i),e.once(Le.Events.MEDIA_ATTACHED,i)}function Ns(a,e,t,i,r){let s=document.createElement("track");return s.kind=e,s.label=t,i&&(s.srclang=i),r&&(s.id=r),s.track.mode=["subtitles","captions"].includes(e)?"disabled":"hidden",s.setAttribute("data-removeondestroy",""),a.append(s),s.track}function Md(a,e){let t=Array.prototype.find.call(a.querySelectorAll("track"),i=>i.track===e);t==null||t.remove()}var ni="cuepoints",Us=Object.freeze({label:ni}),Wi=(a,{label:e=ni}=Us)=>{var t;return(t=Array.from(a.querySelectorAll("track")).find(i=>i.track.label===e&&i.track.kind==="metadata"))==null?void 0:t.track};async function uo(a,e,t=Us){let i=Wi(a,t);if(!i){let{label:r=ni}=t;i=Ns(a,"metadata",r),i.mode="hidden",await new Promise(s=>setTimeout(()=>s(void 0),0))}return i.mode!=="hidden"&&(i.mode="hidden"),[...e].sort(({time:r},{time:s})=>s-r).forEach(({time:r,value:s})=>{var d,h;let n=Array.prototype.findIndex.call(i==null?void 0:i.cues,m=>m.startTime>=r),o=(d=i==null?void 0:i.cues)==null?void 0:d[n],l=o?o.startTime:Number.isFinite(a.duration)?a.duration:Number.MAX_SAFE_INTEGER,c=(h=i==null?void 0:i.cues)==null?void 0:h[n-1];c&&(c.endTime=r);let u=new VTTCue(r,l,JSON.stringify(s!=null?s:null));i.addCue(u)}),i}var ho=a=>({time:a.startTime,value:JSON.parse(a.text)});function Fd(a,e={label:ni}){let t=Wi(a,e);return t!=null&&t.cues?Array.from(t.cues,i=>ho(i)):[]}function fo(a,e={label:ni}){var s,n;let t=Wi(a,e);if(!((s=t==null?void 0:t.activeCues)!=null&&s.length))return;let{currentTime:i}=a,r=Array.prototype.find.call((n=t.activeCues)!=null?n:[],({startTime:o,endTime:l})=>o<=i&&l>i);return ho(r)}async function go(a,e=Us){return new Promise(t=>{Ve(a,"loadstart",async()=>{let i=await uo(a,[],e);Ve(a,"cuechange",()=>{let r=fo(a);if(r){let s=new CustomEvent("cuepointchange",{composed:!0,bubbles:!0,detail:r});a.dispatchEvent(s)}},{},i),t(i)})})}function Nd(a,e){if(e){let t=e.playingDate;if(t!=null)return new Date(t.getTime()-a.currentTime*1e3)}return typeof a.getStartDate=="function"?a.getStartDate():new Date(NaN)}function Ud(a,e){if(e&&e.playingDate)return e.playingDate;if(typeof a.getStartDate=="function"){let t=a.getStartDate();return new Date(t.getTime()+a.currentTime*1e3)}return new Date(NaN)}var Bd=async a=>fetch(a).then(e=>e.text()).then(e=>{let t=e.split(`
|
|
45
45
|
`).find((i,r,s)=>r&&s[r-1].startsWith("#EXT-X-STREAM-INF"));return fetch(t).then(i=>i.text()).then(i=>i.split(`
|
|
46
46
|
`))}),$d=a=>{var n,o;let t=(o=((n=a.find(l=>l.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?n:"").split(":")[1])==null?void 0:o.trim(),i=Os(t),r=Ms(t),s;if(i===gt.LIVE){let l=a.find(u=>u.startsWith("#EXT-X-PART-INF"));!!l?s=+l.split(":")[1].split("=")[1]*2:s=+a.find(h=>h.startsWith("#EXT-X-TARGETDURATION")).split(":")[1]*3}return{streamType:i,targetLiveWindow:r,liveEdgeStartOffset:s}},Gd=async(a,e)=>{if(e===mt.MP4)return{streamType:gt.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0};if(e===mt.M3U8){let t=await Bd(a);return $d(t)}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${a}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0}},mo=async(a,e,t=si({src:a}))=>{var n,o,l;let{streamType:i,targetLiveWindow:r,liveEdgeStartOffset:s}=await Gd(a,t);((n=Ue.get(e))!=null?n:{}).liveEdgeStartOffset=s,((o=Ue.get(e))!=null?o:{}).targetLiveWindow=r,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((l=Ue.get(e))!=null?l:{}).streamType=i,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},Hd=a=>{var n;let e=a.type,t=Os(e),i=Ms(e),r,s=!!((n=a.partList)!=null&&n.length);return t===gt.LIVE&&(r=s?a.partTarget*2:a.targetduration*3),{streamType:t,targetLiveWindow:i,liveEdgeStartOffset:r,lowLatency:s}},Kd=(a,e,t)=>{var o,l,c,u,d,h,m,y;let{streamType:i,targetLiveWindow:r,liveEdgeStartOffset:s,lowLatency:n}=Hd(a);if(i===gt.LIVE){n?(t.config.backBufferLength=(o=t.userConfig.backBufferLength)!=null?o:4,t.config.maxFragLookUpTolerance=(l=t.userConfig.maxFragLookUpTolerance)!=null?l:.001,t.config.abrBandWidthUpFactor=(c=t.userConfig.abrBandWidthUpFactor)!=null?c:t.config.abrBandWidthFactor):t.config.backBufferLength=(u=t.userConfig.backBufferLength)!=null?u:8;let E=Object.freeze({get length(){return e.seekable.length},start(b){return e.seekable.start(b)},end(b){var A;return b>this.length?e.seekable.end(b):(A=t.liveSyncPosition)!=null?A:e.seekable.end(b)}});((d=Ue.get(e))!=null?d:{}).seekable=E}((h=Ue.get(e))!=null?h:{}).liveEdgeStartOffset=s,((m=Ue.get(e))!=null?m:{}).targetLiveWindow=r,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((y=Ue.get(e))!=null?y:{}).streamType=i,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},po,yo,Vd=(yo=(po=globalThis==null?void 0:globalThis.navigator)==null?void 0:po.userAgent)!=null?yo:"",qd=Vd.toLowerCase().indexOf("android")!==-1,Ue=new WeakMap,Eo="mux.com",vo,To,xo=(To=(vo=Le).isSupported)==null?void 0:To.call(vo),Wd=qd,Wh=()=>ji.default.utils.now(),jd=ji.default.utils.generateUUID,jh=(a,{domain:e=Eo,maxResolution:t=""}={})=>{if(!a)return;let[i,r=""]=so(a),s=new URL(`https://stream.${e}/${i}.m3u8${r}`);return t&&s.searchParams.set("max_resolution",t),s.toString()},Yd=a=>{if(!a)return;let[e]=a.split("?");return e||void 0},zd=a=>{if(!a||!a.startsWith("https://stream."))return;let[e]=new URL(a).pathname.slice(1).split(".m3u8");return e||void 0},Xd=a=>{var e,t,i;return(e=a==null?void 0:a.metadata)!=null&&e.video_id?a.metadata.video_id:So(a)&&(i=(t=Yd(a.playbackId))!=null?t:zd(a.src))!=null?i:a.src},Yh=a=>{var e;return(e=Ue.get(a))==null?void 0:e.error},zh=a=>{var e,t;return(t=(e=Ue.get(a))==null?void 0:e.streamType)!=null?t:gt.UNKNOWN},Xh=a=>{var e,t;return(t=(e=Ue.get(a))==null?void 0:e.targetLiveWindow)!=null?t:Number.NaN},Qd=a=>{var e,t;return(t=(e=Ue.get(a))==null?void 0:e.seekable)!=null?t:a.seekable},Qh=a=>{var i;let e=(i=Ue.get(a))==null?void 0:i.liveEdgeStartOffset;if(typeof e!="number")return Number.NaN;let t=Qd(a);return t.length?t.end(t.length-1)-e:Number.NaN},Jd=(a,e,t=.001)=>Math.abs(a-e)<=t,bo=(a,e,t=.001)=>a>e||Jd(a,e,t),Zd=a=>a.paused&&bo(a.currentTime,a.duration),eh=(a,e)=>a.loop||!!e?a.ended:a.ended||Zd(a),Jh=(a,e,t)=>{th(e,t);let{metadata:i={}}=a,{view_session_id:r=jd()}=i,s=Xd(a);i.view_session_id=r,i.video_id=s,a.metadata=i,Ue.set(e,{});let n=ih(a,e);sh(a,e,n),nh(a,e,n),go(e);let o=ao(a,e,n),l=oo(a,e,n);return{engine:n,setAutoplay:o,setPreload:l}},th=(a,e)=>{let t=e==null?void 0:e.engine;t&&(t.detachMedia(),t.destroy()),(a==null?void 0:a.mux)&&!a.mux.deleted&&(a.mux.destroy(),delete a.mux),a&&(a.removeAttribute("src"),a.load(),a.removeEventListener("error",Lo),a.removeEventListener("error",Bs),a.removeEventListener("durationchange",Ao),Ue.delete(a),a.dispatchEvent(new Event("teardown")))};function _o(a,e){var c;let t=si(a);if(!(t===mt.M3U8))return!0;let r=!t||((c=e.canPlayType(t))!=null?c:!0),{preferPlayback:s}=a,n=s===Ps.MSE,o=s===Ps.NATIVE;return r&&(o||!(xo&&(n||Wd)))}var ih=(a,e)=>{let{debug:t,streamType:i,startTime:r=-1,metadata:s,preferCmcd:n}=a,l=si(a)===mt.M3U8,c=_o(a,e);if(l&&!c&&xo){let u={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelToPlayerSize:!0,capLevelOnFPSDrop:!0},d=rh(i),h=n!==Vi.NONE?{useHeaders:n===Vi.HEADER,sessionId:s==null?void 0:s.view_session_id,contentId:s==null?void 0:s.video_id}:void 0;return new Le({debug:t,startPosition:r,cmcd:h,...u,...d})}},rh=a=>a===gt.LIVE?{backBufferLength:8}:{},So=({playbackId:a,src:e,customDomain:t})=>{if(a)return!0;if(typeof e!="string")return!1;let i=window==null?void 0:window.location.href,r=new URL(e,i).hostname.toLocaleLowerCase();return r.includes(Eo)||!!t&&r.includes(t.toLocaleLowerCase())},sh=(a,e,t)=>{var s;let{envKey:i}=a,r=So(a);if(i||r){let{playerInitTime:n,playerSoftwareName:o,playerSoftwareVersion:l,beaconCollectionDomain:c,debug:u,disableCookies:d}=a,h={...a.metadata,video_title:((s=a==null?void 0:a.metadata)==null?void 0:s.video_title)||void 0},m=y=>typeof y.player_error_code=="string"?!1:typeof a.errorTranslator=="function"?a.errorTranslator(y):y;ji.default.monitor(e,{debug:u,beaconCollectionDomain:c,hlsjs:t,Hls:t?Le:void 0,automaticErrorTracking:!1,errorTranslator:m,disableCookies:d,data:{...i?{env_key:i}:{},player_software_name:o,player_software:o,player_software_version:l,player_init_time:n,...h}})}},nh=(a,e,t)=>{var s;let i=_o(a,e),{src:r}=a;if(e&&i){let n=si(a);typeof r=="string"?(e.preload==="none"?Ve(e,"loadstart",()=>mo(r,e,n)):mo(r,e,n),e.setAttribute("src",r),a.startTime&&(((s=Ue.get(e))!=null?s:{}).startTime=a.startTime,e.addEventListener("durationchange",Ao,{once:!0}))):e.removeAttribute("src"),e.addEventListener("error",Lo),e.addEventListener("error",Bs),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(c=>{c.remove()})},{once:!0});let o=()=>{e.ended||!eh(e)||e.dispatchEvent(new Event("ended"))};Ve(e,"pause",o),Ve(e,"seeked",o),Ve(e,"play",()=>{e.ended||!bo(e.currentTime,e.duration)||(e.currentTime=e.seekable.start(0))})}else t&&r?(t.once(Le.Events.LEVEL_LOADED,(n,o)=>{Kd(o.details,e,t)}),t.on(Le.Events.ERROR,(n,o)=>{let l={[Le.ErrorTypes.NETWORK_ERROR]:$e.MEDIA_ERR_NETWORK,[Le.ErrorTypes.MEDIA_ERROR]:$e.MEDIA_ERR_DECODE},c=new $e("",l[o.type]);c.fatal=o.fatal,c.data=o,e.dispatchEvent(new CustomEvent("error",{detail:c}))}),e.addEventListener("error",Bs),lo(a,t),co(e,t),t.attachMedia(e)):console.error("It looks like the video you're trying to play will not work on this system! If possible, try upgrading to the newest versions of your browser or software.")};function Ao(a){var i;let e=a.target,t=(i=Ue.get(e))==null?void 0:i.startTime;if(!!t&&ro(e.seekable,e.duration,t)){let r=e.preload==="auto";r&&(e.preload="none"),e.currentTime=t,r&&(e.preload="auto")}}async function Lo(a){if(!a.isTrusted)return;a.stopImmediatePropagation();let e=a.target;if(!(e!=null&&e.error))return;let{message:t,code:i}=e.error,r=new $e(t,i);if(e.src&&(i!==$e.MEDIA_ERR_DECODE||i!==void 0))try{let{status:s}=await fetch(e.src);r.data={response:{code:s}}}catch{}e.dispatchEvent(new CustomEvent("error",{detail:r}))}function Bs(a){var i,r;if(!(a instanceof CustomEvent)||!(a.detail instanceof $e))return;let e=a.target,t=a.detail;!t||!t.fatal||(((i=Ue.get(e))!=null?i:{}).error=t,(r=e.mux)==null||r.emit("error",{player_error_code:t.code,player_error_message:t.message,player_error_context:t.context}))}})();
|
|
47
47
|
/*!
|