@file-viewer/web-full 2.1.6 → 2.1.8
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/README.en.md +1 -1
- package/README.md +1 -1
- package/dist/assets/pptx.worker-BZNcmFr3.js +20174 -0
- package/dist/flyfish-file-viewer-web-full.iife.js +3 -3
- package/dist/flyfish-viewer-manifest.json +1 -1
- package/dist/renderers/archive.iife.js +37 -320
- package/dist/renderers/cad.iife.js +9 -9
- package/dist/renderers/data.iife.js +1 -1
- package/dist/renderers/drawing.iife.js +1 -1
- package/dist/renderers/ebook.iife.js +9 -9
- package/dist/renderers/eda.iife.js +16 -16
- package/dist/renderers/email.iife.js +15 -15
- package/dist/renderers/geo.iife.js +1 -1
- package/dist/renderers/image.iife.js +1 -1
- package/dist/renderers/media.iife.js +15 -15
- package/dist/renderers/mindmap.iife.js +11 -11
- package/dist/renderers/model.iife.js +36 -36
- package/dist/renderers/ofd.iife.js +8 -8
- package/dist/renderers/pdf.iife.js +92 -38
- package/dist/renderers/presentation.iife.js +3 -3
- package/dist/renderers/spreadsheet.iife.js +1 -1
- package/dist/renderers/text.iife.js +39 -39
- package/dist/renderers/typst.iife.js +7 -7
- package/dist/renderers/word.iife.js +18 -18
- package/package.json +23 -23
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(){var zc=Object.create,xt=Object.defineProperty,qc=Object.getOwnPropertyDescriptor,Xc=Object.getOwnPropertyNames,Qc=Object.getPrototypeOf,Cn=Object.prototype.hasOwnProperty,ee=(e,t)=>()=>(e&&(t=e(e=0)),t),Ae=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Mt=(e,t)=>{let i={};for(var s in e)xt(i,s,{get:e[s],enumerable:!0});return t||xt(i,Symbol.toStringTag,{value:"Module"}),i},xn=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(var r=Xc(t),n=0,a=r.length,o;n<a;n++)o=r[n],!Cn.call(e,o)&&o!==i&&xt(e,o,{get:(l=>t[l]).bind(null,o),enumerable:!(s=qc(t,o))||s.enumerable});return e},Zc=(e,t,i)=>(i=e!=null?zc(Qc(e)):{},xn(t||!e||!e.__esModule?xt(i,"default",{value:e,enumerable:!0}):i,e)),Jc=e=>Cn.call(e,"module.exports")?e["module.exports"]:xn(xt({},"__esModule",{value:!0}),e),eh=ee((()=>{})),th=ee((()=>{eh()})),Es,Ts,Ss,bs,je,ih,nt=ee((()=>{Es=["zip","zipx","7z","rar","tar","gz","gzip","tgz","bz2","bzip2","tbz","tbz2","xz","txz","lzma","zst","tzst","cab","ar","cpio","iso","xar","lha","lzh","jar","war","ear","apk","cbz","cbr"],Ts=["glb","gltf","obj","stl","ply","fbx","dae","3ds","3mf","amf","usd","usda","usdc","usdz","kmz","step","stp","iges","igs","ifc","3dm","brep","pcd","wrl","vrml","xyz","vtk","vtp"],Ss=["txt","json","js","mjs","cjs","css","java","py","html","htm","jsx","ts","tsx","xml","log","vue","yaml","yml","ini","sh","bash","sql","go","rs","php","c","cpp","cc","h","hpp","cs","diff","patch","bundle","bdl","jsonc","json5","ipynb","toml","proto","hcl","tex","gv","http","react","rb","swift","kt"],bs=["gif","jpg","jpeg","bmp","tiff","tif","png","svg","webp","avif","ico","heic","heif","jxl"],je=[{id:"office-word-openxml",label:"Word OpenXML",category:"office",extensions:["docx","docm","dotx","dotm"],async:!0,capabilities:{download:!0,print:"adapter",exportHtml:"adapter",zoom:"provider",search:!0}},{id:"office-word-binary",label:"Word Binary",category:"office",extensions:["doc","dot"],async:!0,capabilities:{download:!0,print:"adapter",exportHtml:"adapter",zoom:"provider",search:!0}},{id:"office-presentation",label:"PowerPoint",category:"office",extensions:["pptx","pptm","potx","potm","ppsx","ppsm"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!0}},{id:"open-document",label:"Open Document",category:"office",extensions:["rtf","odt","odp"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!0}},{id:"spreadsheet-openxml",label:"Spreadsheet",category:"office",extensions:["xlsx","xltx","xlsm","xlsb","xls","xlt","xltm","csv","ods","fods","numbers"],async:!0,capabilities:{download:!0,print:!1,exportHtml:!1,zoom:"provider",search:!0}},{id:"pdf",label:"PDF",category:"document",extensions:["pdf"],async:!0,capabilities:{download:!0,print:"adapter",exportHtml:"adapter",zoom:"provider",search:"provider"}},{id:"ofd",label:"OFD",category:"document",extensions:["ofd"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!0}},{id:"typst",label:"Typst",category:"document",extensions:["typ","typst"],async:!0,capabilities:{download:!0,print:"adapter",exportHtml:"adapter",zoom:"provider",search:!0}},{id:"archive",label:"Archive",category:"archive",extensions:Es,async:!0,capabilities:{download:!0,print:!1,exportHtml:!1,zoom:!1,search:!0}},{id:"email",label:"Email",category:"email",extensions:["eml","msg","mbox"],async:!0,capabilities:{download:!0,print:!1,exportHtml:!0,zoom:!1,search:!0}},{id:"eda",label:"EDA",category:"eda",extensions:["olb","dra","gds","oas","oasis"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:!1,search:!0}},{id:"cad",label:"CAD",category:"cad",extensions:["dxf","dwg","dwf","dwfx","xps"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!1}},{id:"model",label:"3D Model",category:"model",extensions:Ts,async:!0,capabilities:{download:!0,print:!1,exportHtml:!1,zoom:"provider",search:!1}},{id:"geo",label:"Geospatial",category:"geo",extensions:["geojson","kml","gpx","shp"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!0}},{id:"drawing",label:"Drawing",category:"drawing",extensions:["excalidraw","drawio","dio","mermaid","mmd","plantuml","puml"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!0}},{id:"mindmap",label:"Mind Map",category:"mindmap",extensions:["xmind"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!0}},{id:"epub",label:"EPUB",category:"ebook",extensions:["epub"],async:!0,capabilities:{download:!0,print:!1,exportHtml:!0,zoom:!1,search:"provider"}},{id:"umd",label:"UMD",category:"ebook",extensions:["umd"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!0}},{id:"image",label:"Image",category:"image",extensions:bs,async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!1}},{id:"markdown",label:"Markdown",category:"markdown",extensions:["md","markdown"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:!1,search:!0}},{id:"code",label:"Code and Text",category:"code",extensions:Ss,async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:!1,search:!0}},{id:"video",label:"Video",category:"media",extensions:["mp4","webm","m3u8"],async:!0,capabilities:{download:!0,print:!1,exportHtml:!1,zoom:!1,search:!1}},{id:"audio",label:"Audio",category:"media",extensions:["mp3","mpeg","wav","ogg","oga","opus","m4a","aac","flac","weba","midi","mid"],async:!0,capabilities:{download:!0,print:!1,exportHtml:!1,zoom:!1,search:!1}},{id:"data-asset",label:"Data Asset",category:"asset",extensions:["ttf","otf","woff","woff2","psd","ai","eps","sqlite","wasm","parquet","avro","webarchive"],async:!0,capabilities:{download:!0,print:!1,exportHtml:!0,zoom:!1,search:!0}}],ih=Object.freeze(Array.from(new Set(je.flatMap(e=>e.extensions))).sort())})),sh,rh,nh=ee((()=>{sh=["[data-viewer-anchor-id]",".pdfViewer .page",".docx-wrapper section",".docx p",".docx li",".docx table",".markdown-body h1",".markdown-body h2",".markdown-body h3",".markdown-body h4",".markdown-body h5",".markdown-body h6",".markdown-body p",".markdown-body li",".markdown-body pre",".markdown-body table","article h1","article h2","article h3","article h4","article h5","article h6","article p","article li","article pre","article table","pre code","p","li","tr","h1","h2","h3","h4","h5","h6","pre","table"].join(","),rh=[".viewer-actions",".viewer-watermark",".state-panel",".pdf-toolbar",".pdf-nav-pane",".flyfish-search-match"].join(",")})),Is,Mn,On,ah=ee((()=>{Is=new WeakMap,Mn=(e,t)=>{Is.set(e,t),e.dataset.viewerZoomProvider=e.dataset.viewerZoomProvider||"custom",e.__flyfishViewerZoomProvider=t},On=e=>{e&&(Is.delete(e),delete e.dataset.viewerZoomProvider,delete e.__flyfishViewerZoomProvider)}})),Ot=ee((()=>{nh(),ah()})),oh,Fn=ee((()=>{Ot(),oh=["script","style","textarea","input","select","button",".viewer-actions",".viewer-watermark",".state-panel",".pdf-toolbar",".pdf-nav-pane",".flyfish-search-match",".textLayer",".annotationLayer",".xfaLayer","svg","canvas","iframe","video","audio"].join(",")})),Nn=ee((()=>{Ot(),Fn()})),Un,As=ee((()=>{Ot(),Un=()=>{const e=new Set;return{emit(){e.forEach(t=>t())},subscribe(t){return e.add(t),()=>{e.delete(t)}}}}})),ke,gi=ee((()=>{ke=e=>e.trim().replace(/^\./,"").toLowerCase()})),lh,Bn,$n,Ls,Gn,Vn,Kn,Rs,Hn,et,mi,Et=ee((()=>{lh="zh-CN",Bn={"toolbar.zoomGroup":"缩放控制","toolbar.zoomOut":"缩小预览","toolbar.zoomIn":"放大预览","toolbar.zoomReset":"还原比例","toolbar.download":"下载","toolbar.downloadTitle":"下载原始文件","toolbar.print":"打印","toolbar.printTitle":"打印完整渲染内容","toolbar.exportHtml":"HTML","toolbar.exportHtmlTitle":"导出当前渲染后的 HTML","state.ready.title":"预览完成","state.ready.message":"文件内容已完成渲染。","state.empty.title":"暂无文件","state.empty.message":"请选择文件或提供可访问的文件地址后开始预览。","state.unsupported.install.title":"需要装配预览能力","state.unsupported.install.message":"{extension} 格式已在支持矩阵中,但当前项目尚未装配 {rendererLabel} renderer。","state.unsupported.install.description":"推荐安装 {presetPackage},通过 options.preset / options.renderers 注入对应能力{rendererTip};Vite 项目也可以使用 @file-viewer/vite-plugin 自动发现已安装 preset。","state.unsupported.title":"暂不支持在线预览","state.unsupported.message":"不支持{extension}格式的在线预览,请下载后预览或转换为支持的格式。","state.unsupported.description":"支持 Office、PDF、OFD、Typst、压缩包、邮件、OLB/DRA、CAD、地理数据、3D 模型、Excalidraw、draw.io、EPUB、UMD、Markdown、代码/文本、图片、音视频、字体和数据资产的在线预览","state.error.title":"预览失败","preview.downloading":"正在下载文件资源...","preview.streamingPdf":"正在建立 PDF 流式预览...","preview.reading":"正在解析文件内容...","error.download":"下载失败","error.print":"打印失败","error.exportHtml":"导出 HTML 失败","error.noDownloadSource":"当前没有可下载的源文件","error.noExportContent":"当前没有可导出的预览内容","error.printUnavailable":"当前文件类型不支持完整打印,请下载原文件后在本地应用中打印","error.printWindowBlocked":"浏览器拦截了打印窗口","error.remoteDownload":"文件下载失败","error.localRead":"读取文件异常","error.load":"加载文件异常","error.stream":"加载 PDF 流式预览异常","error.beforeOperation":"操作前置校验失败","operation.download":"下载原始文件","operation.print":"打印完整渲染内容","operation.exportHtml":"导出渲染 HTML","operation.zoomIn":"放大预览","operation.zoomOut":"缩小预览","operation.zoomReset":"还原预览比例","pdf.toolbar.toggleNavigation":"切换导航窗格","pdf.toolbar.previousPage":"上一页","pdf.toolbar.nextPage":"下一页","pdf.toolbar.fitWidth":"适合宽度","pdf.toolbar.zoomOut":"缩小","pdf.toolbar.zoomIn":"放大","pdf.toolbar.rotateLeft":"向左旋转","pdf.toolbar.rotateRight":"向右旋转","pdf.nav.typeLabel":"PDF 导航类型","pdf.nav.pagesTab":"页面","pdf.nav.outlineTab":"目录","pdf.nav.pagesTitle":"页面导航","pdf.nav.outlineTitle":"目录导航","pdf.nav.pageCount":"{count} 页","pdf.nav.itemCount":"{count} 项","pdf.nav.pageLabel":"第 {page} 页","pdf.nav.outlineEmpty":"当前 PDF 没有可用目录","pdf.nav.outlineFallbackTitle":"目录 {index}","pdf.thumbnail.alt":"第 {page} 页缩略图","pdf.state.loading":"正在加载 PDF...","pdf.error.browserWindow":"PDF 预览需要浏览器窗口","pdf.error.missingSource":"PDF 缺少可读取的数据源","pdf.error.loadFailed":"PDF 加载失败","pdf.error.notLoaded":"PDF 尚未加载完成,请稍后再试","pdf.error.unloaded":"PDF 已卸载,无法继续打印","pdf.error.canvasUnavailable":"当前浏览器无法创建 PDF 打印画布","pdf.export.pageTitle":"{title} - 第 {page} 页","spreadsheet.loading.kicker":"Excel 表格","spreadsheet.loading.title":"正在解析 Excel 工作簿","spreadsheet.loading.hint":"正在准备工作表、样式和大数据视口,请稍候。","spreadsheet.loading.streaming":"正在平滑补充可视区数据","spreadsheet.tabs.ariaLabel":"工作表列表","spreadsheet.state.parsingWorkbook":"正在解析 Excel 工作簿,请耐心等待...","spreadsheet.state.preparingSheet":"正在准备工作表内容...","spreadsheet.state.preparingSheetNamed":"正在准备「{name}」...","spreadsheet.state.cachedRows":"已缓存 {cached} / {total} 行","spreadsheet.state.rows":"共 {rows} 行,按视口预取平滑加载","spreadsheet.state.rowsAndColumns":"共 {rows} 行,{cols} 列,按视口预取平滑加载","spreadsheet.error.parseFailed":"Excel 解析失败","spreadsheet.error.workerFailed":"Excel Worker 运行失败","archive.error.nestedUnsupported":"不支持 .{type} 格式的在线预览,请下载后预览或转换为支持的格式","archive.loading.readingDirectory":"正在读取压缩包目录...","archive.loading.readingDirectoryHint":"大文件会在 Worker 中解析,避免阻塞主线程。","archive.search.placeholder":"筛选压缩包内文件","archive.preview.title":"压缩包内预览","archive.preview.chooseFile":"请选择一个文件","archive.preview.downloadFile":"下载文件","archive.error.title":"压缩包预览提示","archive.stats.summary":"{count} 个文件 · {size} · {previewable} 个可直接预览","archive.warning.encrypted":"检测到加密内容,当前在线预览不接收密码,建议下载后本地解压。","archive.empty.title":"选择左侧文件即可预览","archive.empty.message":"压缩包只读取目录;文件内容会在点击后按需解压,并在体积允许时缓存到 IndexedDB。","archive.loading.initializingCandidate":"正在初始化 {label}...","archive.loading.initializingCandidateHint":"如果当前服务器没有正确发布 Worker/WASM,会自动切换兼容模式。","archive.error.candidateInitTimeout":"{label} 初始化超时","archive.error.encryptedCheckTimeout":"{label} 加密检测超时","archive.loading.directoryReadyHint":"目录读取完成后,点击内部文件才会按需解压。","archive.error.candidateReadTimeout":"{label} 读取目录超时","archive.loading.workerFallback":"Worker 不可用,正在切换 ZIP/TAR 兼容模式...","archive.loading.workerFallbackHint":"兼容模式无需额外静态 Worker,适合手机 WebView 或本地临时服务器。","archive.notice.workerFallback":"当前环境的 libarchive Worker 未能启动,已自动切换到 ZIP/TAR/GZIP 兼容模式。RAR、7z 等格式仍建议发布 vendor/libarchive/worker-bundle.js 与 libarchive.wasm。","archive.error.tooLarge":"压缩包体积 {size} 超过安全上限 {limit},请下载后在本地解压。","archive.loading.initializingWorker":"正在初始化压缩包解析 Worker...","archive.loading.initializingWorkerHint":"大文件会在 Worker 中解析,避免阻塞主线程。","archive.error.workerInitFailed":"压缩包 Worker 初始化失败","archive.error.entryTooLarge":"压缩包内文件 {name} 体积 {size} 超过预览上限 {limit}。","archive.loading.extracting":"正在按需解压 {name}...","archive.loading.rendering":"正在渲染 {name}...","archive.loading.exporting":"正在导出 {name}...","media.audio.title":"音频预览","media.audio.description":"使用浏览器原生播放器打开,兼容性取决于当前浏览器支持的音频编码。","media.audio.unsupported":"当前浏览器不支持音频播放。","media.video.title":"视频预览","media.video.unsupported":"当前浏览器不支持该视频格式。","media.video.hlsHint":"HLS 会优先使用原始 URL 加载分片;如果传入的是本地单文件清单,请确保分片地址可被浏览器访问。","media.midi.title":"MIDI 文件","media.midi.loading":"正在解析 MIDI 轨道...","media.midi.trackHeader":"轨道","media.midi.instrumentHeader":"乐器","media.midi.channelHeader":"通道","media.midi.noteCountHeader":"音符数","media.midi.durationHeader":"时长","media.midi.durationStat":"时长","media.midi.trackStat":"轨道","media.midi.noteStat":"音符","media.midi.parseFailed":"MIDI 解析失败","email.mbox.subject":"{filename} · 第 1 封","email.mbox.summary":"MBOX 共识别 {count} 封邮件,当前展示第 1 封。","email.error.title":"邮件预览提示","email.meta.from":"发件人","email.meta.to":"收件人","email.meta.cc":"抄送","email.meta.date":"时间","email.tabs.text":"正文","email.tabs.headers":"头信息","email.attachments.title":"附件","email.attachments.empty":"暂无附件","email.attachments.download":"下载附件","email.attachments.opening":"正在打开附件 {name}...","email.attachments.nestedUnavailable":"当前运行环境未提供附件嵌套预览入口,请下载 {name} 后查看。","email.loading.parsing":"正在解析邮件...","data.font.sample":"Flyfish Viewer 轻量预览 AaBbCc 1234567890","data.error.fontFaceUnsupported":"当前浏览器不支持 FontFace API","data.title.font":"字体文件预览","data.title.sqlite":"SQLite 数据库预览","data.title.parquet":"Parquet 列式数据预览","data.title.avro":"Avro 对象容器预览","data.title.wasm":"WebAssembly 模块预览","data.title.eps":"EPS 矢量文件摘要","data.title.ai":"Illustrator 文件摘要","data.title.webarchive":"WebArchive 摘要预览","data.title.summary":"数据资产摘要","data.label.format":"格式","data.label.size":"大小","data.label.rendering":"渲染方式","data.label.objects":"对象数","data.label.sampleTable":"示例表","data.label.rows":"行数","data.label.columns":"列数","data.label.sampleRows":"示例行","data.label.imports":"导入","data.label.exports":"导出","data.label.magic":"Magic","data.label.note":"说明","data.label.container":"容器","data.value.schemaRead":"已读取","data.value.schemaUnread":"未读取","data.note.aiSummary":"非 PDF-compatible AI 按摘要展示","data.note.postscriptSummary":"PostScript 摘要展示","data.note.webarchive":"安全提取可读片段,不执行网页脚本","data.image.alt":"资产预览","psd.title":"PSD 图层预览","psd.action.fit":"适合","psd.action.showAll":"全显","psd.action.hideAll":"全隐","psd.layers.title":"图层","psd.layers.redrawable":"{count} 可重绘","psd.layers.empty":"未发现可展示图层,使用合成图预览。","psd.layers.hidden":"隐藏","drawing.error.viewerLoadFailed":"diagrams.net viewer 加载失败","drawing.error.excalidrawEmpty":"Excalidraw 文件中没有可预览图元","drawing.error.excalidrawTimeout":"Excalidraw 官方导出超时,自动切换 rough.js 兼容渲染","drawing.error.drawioParseFailed":"Draw.io XML 解析失败:{message}","drawing.error.drawioNoModel":"当前 Draw.io 文件没有可直接渲染的 mxGraphModel。","drawing.error.drawioNoElements":"当前 Draw.io 文件没有可预览图元。","drawing.error.viewerInitFailed":"diagrams.net viewer 未正确初始化","drawing.error.drawioTimeout":"diagrams.net 官方 Viewer 加载超时,自动切换本地 SVG 预览","drawing.error.svgParseFailed":"SVG 解析失败","drawing.error.plantumlRenderFailed":"PlantUML SVG 渲染失败:{status}","drawing.title.excalidraw":"Excalidraw 官方 SVG 预览","drawing.title.mermaid":"Mermaid SVG 预览","drawing.title.plantuml":"PlantUML SVG 预览","drawing.title.drawio":"Draw.io 离线 SVG 预览","drawing.toolbar.zoomOut":"缩小","drawing.toolbar.zoomIn":"放大","drawing.toolbar.fit":"适合","drawing.toolbar.fitWidth":"适合宽度","drawing.state.loading":"正在加载绘图预览...","text.code.loadingHighlight":"正在加载高亮...","ebook.toc":"目录","ebook.reading":"阅读中","ebook.itemCount":"{count} 项","epub.title":"EPUB 电子书","epub.previousPage":"上一页","epub.nextPage":"下一页","epub.loading":"正在解析 EPUB...","epub.chapterFallback":"章节 {index}","epub.renderIncomplete":"EPUB 正文渲染未完成,请刷新后重试","umd.title":"UMD 电子书","umd.previousChapter":"上一章","umd.nextChapter":"下一章","umd.loading":"正在解析 UMD...","umd.emptyContent":"未解析到正文内容","umd.chapterFallback":"章节 {index}","umd.galleryFallback":"图集 {index}","umd.warningBodyTooShort":"UMD 正文长度小于声明长度,文件可能不完整","umd.error.unexpectedEnd":"UMD 文件结构不完整,读取时遇到意外结尾","umd.error.invalidFile":"不是有效的 UMD 电子书文件","typst.summaryRenderer":"Typst WASM 渲染器","typst.pageSummary.empty":"0 页","typst.pageSummary.ready":"{count} 页 / {width} x {height} pt","typst.status.compiling":"正在编译","typst.status.failed":"编译失败","typst.status.rendered":"已渲染","typst.loading.title":"正在解析 Typst","typst.loading.hint":"加载编译器并生成页面预览...","typst.error.title":"Typst 渲染失败","typst.error.timeout":"Typst WASM / 字体加载或编译超过 {seconds} 秒","typst.error.timeoutHint":"请检查 Typst compiler WASM、renderer WASM、字体目录的下载速度和缓存策略;弱网或跨境部署可通过 options.typst.renderTimeoutMs 调大浏览器端加载/编译超时。","typst.error.assetHint":"Typst 需要本地 compiler / renderer WASM 和字体目录。请运行 file-viewer-copy-assets,或配置 options.typst.compilerWasmUrl / options.typst.rendererWasmUrl / options.typst.fontAssetsUrl,并确认服务器以 application/wasm 返回 WASM。","typst.error.svgParseFailed":"Typst SVG 解析失败","typst.error.wasmLoadFailed":"Typst WASM 加载失败","xmind.toolbar.zoomOut":"缩小","xmind.toolbar.zoomIn":"放大","xmind.toolbar.fit":"适合","xmind.toolbar.fitTitle":"适配画布","xmind.state.loading":"正在解析 XMind 脑图...","xmind.stats.nodes":"节点","xmind.stats.depth":"层级","xmind.stats.theme":"主题","xmind.stats.template":"模板","xmind.badge.paused":"暂停","xmind.badge.collapsed":"折叠","xmind.badge.floating":"浮动","xmind.badge.summary":"概要","xmind.badge.callout":"标注","xmind.imageResource":"图片资源: {name}","xmind.error.unrecognized":"无法识别 XMind 文件: ZIP 中未找到 content.json 或 content.xml","xmind.error.noCanvas":"XMind 文件中没有可预览的画布","cad.toolbar.fit":"适配","cad.toolbar.zoomOut":"缩小","cad.toolbar.zoomIn":"放大","cad.layers.title":"图层","cad.layers.count":"{count} 项","cad.inspector.title":"结构","cad.inspector.entities":"实体","cad.inspector.blocks":"块","cad.inspector.pages":"页面","cad.inspector.drawn":"绘制","cad.state.loadingViewer":"正在加载 CAD 预览器...","cad.state.parsing":"正在解析 CAD...","cad.error.parseFailed":"CAD 文件解析失败","image.alt":"图片","image.lightbox.alt":"图片预览","image.lightbox.close":"关闭图片预览","gitBundle.error.invalid":"当前文件不是标准 Git bundle。","gitBundle.error.missingPack":"Git bundle header 后未找到 PACK 数据。","gitBundle.notice.delta":"当前 bundle 包含 delta 压缩对象。预览器已在浏览器端解析常规 OFS_DELTA / REF_DELTA;若仍有缺失文件,通常是包体过大、对象过多或依赖外部 prerequisite。","gitBundle.title.history":"历史记录","gitBundle.title.fileTree":"文件树","gitBundle.file.choose":"选择文件查看内容","gitBundle.file.noTree":"当前 bundle 的 tree/blob 可能被 delta 压缩,暂未解析到可展开文件。","gitBundle.file.none":"未解析到文件","gitBundle.history.empty":"当前 bundle 未解析到 commit 对象,仅展示 refs 和 pack 摘要。","gitBundle.toolbar.summary":"{commits} commits · {files} files","gitBundle.meta.bundle":"Bundle","gitBundle.meta.refs":"Refs","gitBundle.meta.commits":"Commits","gitBundle.meta.objects":"Objects","gitBundle.meta.deltas":"Deltas","gitBundle.meta.objectFormat":"Object format","gitBundle.meta.objectTypes":"Object types","geo.error.unrecognized":"无法识别的 GeoJSON 数据","geo.error.xmlParseFailed":"XML 解析失败","geo.error.unsupported":"不支持 .{type} 地理格式","geo.title":"地理数据预览","geo.featureCount":"要素数","geo.bounds":"范围","geo.geometryTypes":"几何类型","geo.aria":"地理数据 SVG 预览","geo.loading":"正在解析地理数据...","model.toolbar.fit":"适配","model.toolbar.rotate":"旋转","model.toolbar.wireframe":"线框","model.toolbar.grid":"网格","model.toolbar.axes":"坐标","model.state.loadingSummary":"正在加载模型","model.state.loading":"正在解析 3D 模型...","model.state.loaded":"模型已加载","model.state.parseFailed":"模型解析失败","model.summary.meshes":"{count} 个网格","model.summary.points":"{count} 个点云","model.error.daeEmpty":"DAE 模型未解析出有效场景","model.error.unsupported":"暂不支持 .{type} 模型格式","model.error.parseFailed":"{type} 模型解析失败","model.notice.signature":"检测到文件签名: {signature}。","loading.generic.label":"文件内容","loading.generic.hint":"正在整理内容结构并生成预览。","loading.word.label":"Word 文档","loading.word.hint":"正在准备分页、文本样式和文档结构。","loading.wordWorker.hint":"正在通过 Worker 准备文档结构、文本样式和分页结果。","loading.sheet.label":"Excel 表格","loading.sheet.hint":"正在准备工作表、样式和可视区数据。","loading.csv.label":"表格数据","loading.csv.hint":"正在准备行列数据和基础样式。","loading.presentation.label":"PPT 演示文稿","loading.presentation.hint":"正在构建幻灯片布局和媒体内容。","loading.pdf.label":"PDF 文档","loading.pdf.hint":"正在载入页面位图、文本层和缩放视图。","loading.ofd.label":"OFD 版式文件","loading.ofd.hint":"正在解析国产版式文档和页面对象。","loading.archive.label":"压缩包","loading.archive.hint":"正在启动 Worker 并读取压缩包目录。","loading.email.label":"邮件文件","loading.email.hint":"正在解析邮件头、正文和附件。","loading.msg.hint":"正在解析 Outlook 邮件和附件。","loading.eda.label":"EDA 文件","loading.eda.hint":"正在读取 EDA 容器结构和可读属性。","loading.cad.label":"CAD 图纸","loading.cad.hint":"正在准备 CAD 图层、几何对象和画布视图。","loading.dwg.hint":"正在通过 Worker 加载 DWG 几何和 LibreDWG WASM。","loading.dwf.hint":"正在加载 DWF native renderer 与 W2D/W3D 图形。","loading.dwfx.hint":"正在加载 DWFx/XPS native renderer 与页面图形。","loading.xps.hint":"正在加载 XPS native renderer 与嵌入字体。","loading.drawio.label":"draw.io 图纸","loading.drawio.hint":"正在解析图元、连线和 SVG 预览。","loading.excalidraw.label":"Excalidraw 图纸","loading.excalidraw.hint":"正在解析手绘图元并生成安全 SVG。","loading.epub.label":"EPUB 电子书","loading.epub.hint":"正在解析目录、章节资源和阅读分页。","loading.umd.label":"UMD 电子书","loading.umd.hint":"正在解析移动电子书结构、目录和压缩正文。","loading.image.label":"图片文件","loading.image.hint":"正在解码像素数据并生成预览。","loading.video.label":"视频文件","loading.video.hint":"正在准备媒体资源和播放组件。","loading.audio.label":"音频文件","loading.audio.hint":"正在准备音频资源和播放控件。"},$n={"toolbar.zoomGroup":"Zoom controls","toolbar.zoomOut":"Zoom out","toolbar.zoomIn":"Zoom in","toolbar.zoomReset":"Reset zoom","toolbar.download":"Download","toolbar.downloadTitle":"Download the original file","toolbar.print":"Print","toolbar.printTitle":"Print the complete rendered document","toolbar.exportHtml":"HTML","toolbar.exportHtmlTitle":"Export the rendered HTML","state.ready.title":"Preview ready","state.ready.message":"The file has been rendered.","state.empty.title":"No file selected","state.empty.message":"Choose a file or provide an accessible URL to start previewing.","state.unsupported.install.title":"Preview capability required","state.unsupported.install.message":"{extension} is in the supported matrix, but {rendererLabel} renderer is not assembled in this project.","state.unsupported.install.description":"Install {presetPackage} and pass the capability through options.preset / options.renderers{rendererTip}. Vite projects can also use @file-viewer/vite-plugin to auto-discover installed presets.","state.unsupported.title":"Online preview is not supported yet","state.unsupported.message":"{extension} cannot be previewed online. Download it or convert it to a supported format.","state.unsupported.description":"Supports online preview for Office, PDF, OFD, Typst, archives, email, OLB/DRA, CAD, geospatial data, 3D models, Excalidraw, draw.io, EPUB, UMD, Markdown, code/text, images, audio/video, fonts, and structured data assets.","state.error.title":"Preview failed","preview.downloading":"Downloading file resources...","preview.streamingPdf":"Preparing streaming PDF preview...","preview.reading":"Parsing file content...","error.download":"Download failed","error.print":"Print failed","error.exportHtml":"HTML export failed","error.noDownloadSource":"There is no original file source to download.","error.noExportContent":"There is no rendered preview content to export.","error.printUnavailable":"This file type does not support full-document printing. Download the original file and print it locally.","error.printWindowBlocked":"The browser blocked the print window.","error.remoteDownload":"File download failed","error.localRead":"Failed to read local file","error.load":"Failed to load file","error.stream":"Failed to load streaming PDF preview","error.beforeOperation":"Before-operation check failed","operation.download":"Download original file","operation.print":"Print complete rendered content","operation.exportHtml":"Export rendered HTML","operation.zoomIn":"Zoom in","operation.zoomOut":"Zoom out","operation.zoomReset":"Reset preview zoom","pdf.toolbar.toggleNavigation":"Toggle navigation pane","pdf.toolbar.previousPage":"Previous page","pdf.toolbar.nextPage":"Next page","pdf.toolbar.fitWidth":"Fit to width","pdf.toolbar.zoomOut":"Zoom out","pdf.toolbar.zoomIn":"Zoom in","pdf.toolbar.rotateLeft":"Rotate left","pdf.toolbar.rotateRight":"Rotate right","pdf.nav.typeLabel":"PDF navigation type","pdf.nav.pagesTab":"Pages","pdf.nav.outlineTab":"Outline","pdf.nav.pagesTitle":"Page navigation","pdf.nav.outlineTitle":"Outline navigation","pdf.nav.pageCount":"{count} pages","pdf.nav.itemCount":"{count} items","pdf.nav.pageLabel":"Page {page}","pdf.nav.outlineEmpty":"This PDF has no available outline.","pdf.nav.outlineFallbackTitle":"Outline {index}","pdf.thumbnail.alt":"Page {page} thumbnail","pdf.state.loading":"Loading PDF...","pdf.error.browserWindow":"PDF preview requires a browser window","pdf.error.missingSource":"PDF has no readable data source","pdf.error.loadFailed":"Failed to load PDF","pdf.error.notLoaded":"The PDF is not loaded yet. Please try again later.","pdf.error.unloaded":"The PDF has been unloaded and cannot continue printing.","pdf.error.canvasUnavailable":"This browser cannot create a PDF print canvas.","pdf.export.pageTitle":"{title} - Page {page}","spreadsheet.loading.kicker":"Excel workbook","spreadsheet.loading.title":"Parsing Excel workbook","spreadsheet.loading.hint":"Preparing worksheets, styles, and virtualized viewport data.","spreadsheet.loading.streaming":"Loading visible worksheet data","spreadsheet.tabs.ariaLabel":"Worksheet list","spreadsheet.state.parsingWorkbook":"Parsing the Excel workbook. Please wait...","spreadsheet.state.preparingSheet":"Preparing worksheet content...","spreadsheet.state.preparingSheetNamed":"Preparing “{name}”...","spreadsheet.state.cachedRows":"Cached {cached} / {total} rows","spreadsheet.state.rows":"{rows} rows, loading smoothly by viewport","spreadsheet.state.rowsAndColumns":"{rows} rows, {cols} columns, loading smoothly by viewport","spreadsheet.error.parseFailed":"Failed to parse Excel","spreadsheet.error.workerFailed":"Excel Worker failed","archive.error.nestedUnsupported":".{type} cannot be previewed online. Download it or convert it to a supported format.","archive.loading.readingDirectory":"Reading archive directory...","archive.loading.readingDirectoryHint":"Large files are parsed in a Worker to keep the main thread responsive.","archive.search.placeholder":"Filter files inside the archive","archive.preview.title":"Archive entry preview","archive.preview.chooseFile":"Choose a file","archive.preview.downloadFile":"Download file","archive.error.title":"Archive preview notice","archive.stats.summary":"{count} files · {size} · {previewable} directly previewable","archive.warning.encrypted":"Encrypted content was detected. Online preview does not accept passwords; download and extract it locally.","archive.empty.title":"Choose a file from the left to preview","archive.empty.message":"The archive directory is read first. File contents are extracted on demand and cached in IndexedDB when size allows.","archive.loading.initializingCandidate":"Initializing {label}...","archive.loading.initializingCandidateHint":"If the server does not publish Worker/WASM assets correctly, the viewer falls back automatically.","archive.error.candidateInitTimeout":"{label} initialization timed out","archive.error.encryptedCheckTimeout":"{label} encryption check timed out","archive.loading.directoryReadyHint":"After the directory is ready, click an entry to extract it on demand.","archive.error.candidateReadTimeout":"{label} directory read timed out","archive.loading.workerFallback":"Worker unavailable. Switching to ZIP/TAR compatibility mode...","archive.loading.workerFallbackHint":"Compatibility mode needs no static Worker and works well in mobile WebViews or temporary local servers.","archive.notice.workerFallback":"The libarchive Worker could not start in this environment, so ZIP/TAR/GZIP compatibility mode is active. RAR, 7z, and similar formats should still publish vendor/libarchive/worker-bundle.js and libarchive.wasm.","archive.error.tooLarge":"Archive size {size} exceeds the safety limit {limit}. Download and extract it locally.","archive.loading.initializingWorker":"Initializing archive parsing Worker...","archive.loading.initializingWorkerHint":"Large files are parsed in a Worker to keep the main thread responsive.","archive.error.workerInitFailed":"Archive Worker initialization failed","archive.error.entryTooLarge":"Entry {name} is {size}, exceeding the preview limit {limit}.","archive.loading.extracting":"Extracting {name} on demand...","archive.loading.rendering":"Rendering {name}...","archive.loading.exporting":"Exporting {name}...","media.audio.title":"Audio preview","media.audio.description":"Opened with the browser-native audio player. Codec support depends on the current browser.","media.audio.unsupported":"This browser does not support audio playback.","media.video.title":"Video preview","media.video.unsupported":"This browser does not support this video format.","media.video.hlsHint":"HLS prefers the original URL for segment loading. If the input is a local single-file playlist, make sure segment URLs are reachable by the browser.","media.midi.title":"MIDI file","media.midi.loading":"Parsing MIDI tracks...","media.midi.trackHeader":"Track","media.midi.instrumentHeader":"Instrument","media.midi.channelHeader":"Channel","media.midi.noteCountHeader":"Notes","media.midi.durationHeader":"Duration","media.midi.durationStat":"Duration","media.midi.trackStat":"Tracks","media.midi.noteStat":"Notes","media.midi.parseFailed":"Failed to parse MIDI","email.mbox.subject":"{filename} · message 1","email.mbox.summary":"Detected {count} messages in the MBOX archive. Showing message 1.","email.error.title":"Email preview notice","email.meta.from":"From","email.meta.to":"To","email.meta.cc":"Cc","email.meta.date":"Date","email.tabs.text":"Body","email.tabs.headers":"Headers","email.attachments.title":"Attachments","email.attachments.empty":"No attachments","email.attachments.download":"Download attachment","email.attachments.opening":"Opening attachment {name}...","email.attachments.nestedUnavailable":"Nested attachment preview is not available in this environment. Download {name} to inspect it.","email.loading.parsing":"Parsing email...","data.font.sample":"Flyfish Viewer preview AaBbCc 1234567890","data.error.fontFaceUnsupported":"This browser does not support the FontFace API","data.title.font":"Font file preview","data.title.sqlite":"SQLite database preview","data.title.parquet":"Parquet columnar data preview","data.title.avro":"Avro object container preview","data.title.wasm":"WebAssembly module preview","data.title.eps":"EPS vector file summary","data.title.ai":"Illustrator file summary","data.title.webarchive":"WebArchive summary preview","data.title.summary":"Data asset summary","data.label.format":"Format","data.label.size":"Size","data.label.rendering":"Renderer","data.label.objects":"Objects","data.label.sampleTable":"Sample table","data.label.rows":"Rows","data.label.columns":"Columns","data.label.sampleRows":"Sample rows","data.label.imports":"Imports","data.label.exports":"Exports","data.label.magic":"Magic","data.label.note":"Note","data.label.container":"Container","data.value.schemaRead":"Read","data.value.schemaUnread":"Not read","data.note.aiSummary":"Non PDF-compatible AI is shown as a safe summary.","data.note.postscriptSummary":"PostScript summary preview","data.note.webarchive":"Readable fragments are extracted safely. Web scripts are not executed.","data.image.alt":"Asset preview","psd.title":"PSD layer preview","psd.action.fit":"Fit","psd.action.showAll":"Show all","psd.action.hideAll":"Hide all","psd.layers.title":"Layers","psd.layers.redrawable":"{count} redrawable","psd.layers.empty":"No displayable layers were found. Showing the composite image.","psd.layers.hidden":"hidden","drawing.error.viewerLoadFailed":"Failed to load the diagrams.net viewer","drawing.error.excalidrawEmpty":"This Excalidraw file has no previewable elements","drawing.error.excalidrawTimeout":"Official Excalidraw export timed out. Falling back to the rough.js renderer.","drawing.error.drawioParseFailed":"Failed to parse Draw.io XML: {message}","drawing.error.drawioNoModel":"This Draw.io file has no directly renderable mxGraphModel.","drawing.error.drawioNoElements":"This Draw.io file has no previewable elements.","drawing.error.viewerInitFailed":"The diagrams.net viewer was not initialized correctly","drawing.error.drawioTimeout":"Official diagrams.net Viewer timed out. Falling back to the local SVG preview.","drawing.error.svgParseFailed":"Failed to parse SVG","drawing.error.plantumlRenderFailed":"Failed to render PlantUML SVG: {status}","drawing.title.excalidraw":"Official Excalidraw SVG preview","drawing.title.mermaid":"Mermaid SVG preview","drawing.title.plantuml":"PlantUML SVG preview","drawing.title.drawio":"Draw.io offline SVG preview","drawing.toolbar.zoomOut":"Zoom out","drawing.toolbar.zoomIn":"Zoom in","drawing.toolbar.fit":"Fit","drawing.toolbar.fitWidth":"Fit width","drawing.state.loading":"Loading drawing preview...","text.code.loadingHighlight":"Loading syntax highlighting...","ebook.toc":"Table of contents","ebook.reading":"Reading","ebook.itemCount":"{count} items","epub.title":"EPUB ebook","epub.previousPage":"Previous","epub.nextPage":"Next","epub.loading":"Parsing EPUB...","epub.chapterFallback":"Chapter {index}","epub.renderIncomplete":"EPUB content did not finish rendering. Refresh and try again.","umd.title":"UMD ebook","umd.previousChapter":"Previous chapter","umd.nextChapter":"Next chapter","umd.loading":"Parsing UMD...","umd.emptyContent":"No readable body content was parsed.","umd.chapterFallback":"Chapter {index}","umd.galleryFallback":"Gallery {index}","umd.warningBodyTooShort":"The UMD body is shorter than declared and may be incomplete.","umd.error.unexpectedEnd":"The UMD structure is incomplete and ended unexpectedly.","umd.error.invalidFile":"This is not a valid UMD ebook file.","typst.summaryRenderer":"Typst WASM renderer","typst.pageSummary.empty":"0 pages","typst.pageSummary.ready":"{count} pages / {width} x {height} pt","typst.status.compiling":"Compiling","typst.status.failed":"Compilation failed","typst.status.rendered":"Rendered","typst.loading.title":"Parsing Typst","typst.loading.hint":"Loading the compiler and generating page previews...","typst.error.title":"Typst render failed","typst.error.timeout":"Typst WASM / font loading or compilation exceeded {seconds} seconds","typst.error.timeoutHint":"Check the download speed and cache strategy for the Typst compiler WASM, renderer WASM, and font directory. On weak networks or cross-region deployments, increase options.typst.renderTimeoutMs.","typst.error.assetHint":"Typst requires local compiler / renderer WASM files and a font directory. Run file-viewer-copy-assets, or configure options.typst.compilerWasmUrl / options.typst.rendererWasmUrl / options.typst.fontAssetsUrl, and make sure the server returns WASM with application/wasm.","typst.error.svgParseFailed":"Failed to parse Typst SVG","typst.error.wasmLoadFailed":"Failed to load Typst WASM","xmind.toolbar.zoomOut":"Zoom out","xmind.toolbar.zoomIn":"Zoom in","xmind.toolbar.fit":"Fit","xmind.toolbar.fitTitle":"Fit canvas","xmind.state.loading":"Parsing XMind mind map...","xmind.stats.nodes":"Nodes","xmind.stats.depth":"Depth","xmind.stats.theme":"Theme","xmind.stats.template":"Template","xmind.badge.paused":"Paused","xmind.badge.collapsed":"Collapsed","xmind.badge.floating":"Floating","xmind.badge.summary":"Summary","xmind.badge.callout":"Callout","xmind.imageResource":"Image resource: {name}","xmind.error.unrecognized":"Unrecognized XMind file: content.json or content.xml was not found in the ZIP package.","xmind.error.noCanvas":"This XMind file has no previewable canvas.","cad.toolbar.fit":"Fit","cad.toolbar.zoomOut":"Zoom out","cad.toolbar.zoomIn":"Zoom in","cad.layers.title":"Layers","cad.layers.count":"{count} items","cad.inspector.title":"Structure","cad.inspector.entities":"Entities","cad.inspector.blocks":"Blocks","cad.inspector.pages":"Pages","cad.inspector.drawn":"Drawn","cad.state.loadingViewer":"Loading CAD viewer...","cad.state.parsing":"Parsing CAD...","cad.error.parseFailed":"Failed to parse CAD file","image.alt":"Image","image.lightbox.alt":"Image preview","image.lightbox.close":"Close image preview","gitBundle.error.invalid":"This file is not a valid Git bundle.","gitBundle.error.missingPack":"No PACK data was found after the Git bundle header.","gitBundle.notice.delta":"This bundle contains delta-compressed objects. The viewer resolves common OFS_DELTA / REF_DELTA objects in the browser. Missing files usually indicate a very large bundle, too many objects, or an external prerequisite.","gitBundle.title.history":"History","gitBundle.title.fileTree":"File tree","gitBundle.file.choose":"Select a file to inspect","gitBundle.file.noTree":"The tree/blob objects in this bundle may be delta-compressed, and no expandable files were parsed.","gitBundle.file.none":"No files parsed","gitBundle.history.empty":"No commit objects were parsed. Showing refs and pack summary only.","gitBundle.toolbar.summary":"{commits} commits · {files} files","gitBundle.meta.bundle":"Bundle","gitBundle.meta.refs":"Refs","gitBundle.meta.commits":"Commits","gitBundle.meta.objects":"Objects","gitBundle.meta.deltas":"Deltas","gitBundle.meta.objectFormat":"Object format","gitBundle.meta.objectTypes":"Object types","geo.error.unrecognized":"Unrecognized GeoJSON data","geo.error.xmlParseFailed":"Failed to parse XML","geo.error.unsupported":".{type} geospatial format is not supported","geo.title":"Geospatial preview","geo.featureCount":"Features","geo.bounds":"Bounds","geo.geometryTypes":"Geometry types","geo.aria":"Geospatial SVG preview","geo.loading":"Parsing geospatial data...","model.toolbar.fit":"Fit","model.toolbar.rotate":"Rotate","model.toolbar.wireframe":"Wireframe","model.toolbar.grid":"Grid","model.toolbar.axes":"Axes","model.state.loadingSummary":"Loading model","model.state.loading":"Parsing 3D model...","model.state.loaded":"Model loaded","model.state.parseFailed":"Failed to parse model","model.summary.meshes":"{count} meshes","model.summary.points":"{count} point clouds","model.error.daeEmpty":"The DAE model did not contain a valid scene.","model.error.unsupported":".{type} model format is not supported yet","model.error.parseFailed":"Failed to parse {type} model","model.notice.signature":"Detected file signature: {signature}.","loading.generic.label":"File content","loading.generic.hint":"Preparing content structure and preview.","loading.word.label":"Word document","loading.word.hint":"Preparing document structure, text styles, and layout.","loading.wordWorker.hint":"Preparing document structure, text styles, and layout in a Worker.","loading.sheet.label":"Excel workbook","loading.sheet.hint":"Preparing worksheets, styles, and viewport data.","loading.csv.label":"Tabular data","loading.csv.hint":"Preparing rows, columns, and basic styling.","loading.presentation.label":"PowerPoint deck","loading.presentation.hint":"Building slide layout and media content.","loading.pdf.label":"PDF document","loading.pdf.hint":"Loading page bitmaps, text layers, and zoom view.","loading.ofd.label":"OFD layout document","loading.ofd.hint":"Parsing OFD pages and layout objects.","loading.archive.label":"Archive","loading.archive.hint":"Starting Worker and reading archive entries.","loading.email.label":"Email file","loading.email.hint":"Parsing message headers, body, and attachments.","loading.msg.hint":"Parsing Outlook message and attachments.","loading.eda.label":"EDA file","loading.eda.hint":"Reading EDA container structure and properties.","loading.cad.label":"CAD drawing","loading.cad.hint":"Preparing CAD layers, geometry, and canvas view.","loading.dwg.hint":"Loading DWG geometry and LibreDWG WASM in a Worker.","loading.dwf.hint":"Loading native DWF renderer and W2D/W3D graphics.","loading.dwfx.hint":"Loading native DWFx/XPS renderer and page graphics.","loading.xps.hint":"Loading native XPS renderer and embedded fonts.","loading.drawio.label":"draw.io diagram","loading.drawio.hint":"Parsing shapes, connectors, and SVG preview.","loading.excalidraw.label":"Excalidraw scene","loading.excalidraw.hint":"Parsing hand-drawn elements and generating safe SVG.","loading.epub.label":"EPUB ebook","loading.epub.hint":"Parsing table of contents, chapter resources, and reading pages.","loading.umd.label":"UMD ebook","loading.umd.hint":"Parsing mobile ebook metadata, table of contents, and compressed chapters.","loading.image.label":"Image file","loading.image.hint":"Decoding pixels and generating preview.","loading.video.label":"Video file","loading.video.hint":"Preparing media resource and player.","loading.audio.label":"Audio file","loading.audio.hint":"Preparing audio resource and playback controls."},Ls=Object.freeze({"zh-CN":Bn,"en-US":$n}),Gn=()=>{var e;if(!(typeof navigator>"u"))return((e=navigator.languages)===null||e===void 0?void 0:e[0])||navigator.language},Vn=e=>{const t=!e||e==="auto"?Gn():e;return String(t||"zh-CN").toLowerCase().startsWith("zh")?"zh-CN":"en-US"},Kn=e=>{var t;return((t=e?.i18n)===null||t===void 0?void 0:t.messages)||e?.messages},Rs=e=>{var t;return Vn(((t=e?.i18n)===null||t===void 0?void 0:t.locale)||e?.locale)},Hn=(e,t={})=>e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(i,s)=>{const r=t[s];return r==null?"":String(r)}),et=(e,t,i={})=>{const s=Rs(e),r=Kn(e);return Hn((typeof r=="function"?r(t,i,s):r?.[t])||Ls[s][t]||Ls["zh-CN"][t],i)},mi=e=>(t,i)=>et(e,t,i)})),Ds=ee((()=>{Et()})),Wn,pi,yi=ee((()=>{nt(),gi(),Wn=e=>({...e,extensions:e.extensions.map(ke)}),pi=(e=je)=>{const t=new Map,i=new Map,s=r=>{const n=Wn(r),a=t.get(n.id);a&&a.extensions.forEach(o=>{var l;((l=i.get(o))===null||l===void 0?void 0:l.id)===a.id&&i.delete(o)}),t.set(n.id,n),n.extensions.forEach(o=>{const l=i.get(o);if(l&&l.id!==n.id)throw new Error(`File extension "${o}" is already registered by renderer "${l.id}".`);i.set(o,n)})};return e.forEach(s),{register:s,unregister(r){const n=t.get(r);return n?(n.extensions.forEach(a=>{var o;((o=i.get(a))===null||o===void 0?void 0:o.id)===r&&i.delete(a)}),t.delete(r),!0):!1},getById(r){return t.get(r)},getByExtension(r){return i.get(ke(r))},hasExtension(r){return i.has(ke(r))},list(){return Array.from(t.values())},listExtensions(){return Array.from(i.keys()).sort()}}}})),Ps,ws=ee((()=>{nt(),yi(),gi(),Ps=({registry:e=pi(je),handlers:t,fallbackHandler:i,fallbackKey:s="error"})=>{const r=Array.from(t).reduce((l,d)=>(l.set(d.rendererId,d.handler),l),new Map),n=new Map,a=[];e.list().forEach(l=>{const d=r.get(l.id);if(!d){a.push(l.id);return}l.extensions.forEach(c=>{n.set(ke(c),d)})}),i&&s&&n.set(ke(s),i);const o=l=>n.get(ke(l));return{handlersByRendererId:r,handlersByExtension:n,missingRendererIds:a,get:o,resolve(l){return o(l)||(s?o(s):void 0)},has(l){return n.has(ke(l))},listExtensions(){return Array.from(n.keys()).sort()}}}})),dh,ch,hh,_s=ee((()=>{nt(),dh=Object.freeze({download:!1,print:!1,exportHtml:!1,zoom:!1,zoomIn:!1,zoomOut:!1,zoomReset:!1}),ch=["pptx","pptm","potx","potm","ppsx","ppsm","ofd","dxf","dwg","dwf","dwfx","xps","excalidraw","drawio","dio","mermaid","mmd","plantuml","puml","umd","md","markdown","olb","dra",...Ss,...bs],hh=["xlsx","xltx","xlsm","xlsb","xls","xlt","xltm","csv","ods","fods","numbers",...Es,"eml","msg","epub","mp4","mp3","mpeg","wav","ogg","oga","opus","m4a","aac","flac","weba",...Ts]})),Ft=ee((()=>{_s(),Et(),Ds()})),uh,ks,jn,Yn,zn,qn,Xn,Qn,Zn,Cs,Jn,vi=ee((()=>{gi(),nt(),Et(),uh=Object.freeze({downloading:"正在下载文件资源...",streamingPdf:"正在建立 PDF 流式预览...",reading:"正在解析文件内容..."}),ks=Object.freeze({accent:"#5f6f82",soft:"rgba(95, 111, 130, 0.12)",badge:"DOC",label:"文件内容",hint:"正在整理内容结构并生成预览。"}),jn=e=>{const t=ke(e);return t?`.${t}`:"当前"},Yn={"office-word-openxml":"@file-viewer/renderer-word","office-word-binary":"@file-viewer/renderer-word","office-presentation":"@file-viewer/renderer-presentation","open-document":"@file-viewer/renderer-word","spreadsheet-openxml":"@file-viewer/renderer-spreadsheet",pdf:"@file-viewer/renderer-pdf",ofd:"@file-viewer/renderer-ofd",typst:"@file-viewer/renderer-typst",archive:"@file-viewer/renderer-archive",email:"@file-viewer/renderer-email",eda:"@file-viewer/renderer-eda",cad:"@file-viewer/renderer-cad",model:"@file-viewer/renderer-3d",geo:"@file-viewer/renderer-geo",drawing:"@file-viewer/renderer-drawing",mindmap:"@file-viewer/renderer-mindmap",epub:"@file-viewer/renderer-epub",umd:"@file-viewer/renderer-epub",image:"@file-viewer/renderer-image",markdown:"@file-viewer/renderer-text",code:"@file-viewer/renderer-text",video:"@file-viewer/renderer-media",audio:"@file-viewer/renderer-media","data-asset":"@file-viewer/renderer-data"},zn=new Set(["office-word-openxml","office-word-binary","office-presentation","open-document","spreadsheet-openxml","pdf","ofd"]),qn=new Set(["image","markdown","code","video","audio"]),Xn=new Set(["typst","archive","eda","cad","model","geo","drawing","mindmap","data-asset"]),Qn=e=>zn.has(e.id)?{packageName:"@file-viewer/preset-office",vitePreset:"office",label:"Office preset"}:Xn.has(e.id)?{packageName:"@file-viewer/preset-engineering",vitePreset:"engineering",label:"Engineering preset"}:qn.has(e.id)?{packageName:"@file-viewer/preset-lite",vitePreset:"lite",label:"Lite preset"}:{packageName:"@file-viewer/preset-all",vitePreset:"all",label:"Full preset"},Zn=(e="")=>{const t=ke(e),i=je.find(r=>r.extensions.map(ke).includes(t));if(!i)return null;const s=Qn(i);return{extension:t,rendererId:i.id,rendererLabel:i.label,rendererCategory:i.category,rendererPackage:Yn[i.id],presetPackage:s.packageName,vitePreset:s.vitePreset,presetLabel:s.label}},Cs=({state:e,extension:t="",title:i,message:s,description:r,theme:n=ks,recoverable:a})=>({state:e,extension:ke(t),title:i,message:s,description:r,theme:n,recoverable:a}),Jn=(e="",t=ks,i)=>{const s=jn(e),r=Zn(e);if(r){const n=Rs(i),a=r.rendererPackage?n==="zh-CN"?`;如果需要极致裁剪,也可以只安装 ${r.rendererPackage}`:`; for a strict custom cut, install only ${r.rendererPackage}`:"";return Cs({state:"unsupported",extension:e,title:et(i,"state.unsupported.install.title"),message:et(i,"state.unsupported.install.message",{extension:s,rendererLabel:r.rendererLabel}),description:et(i,"state.unsupported.install.description",{extension:s,rendererLabel:r.rendererLabel,presetPackage:r.presetPackage,vitePreset:r.vitePreset,rendererTip:a}),theme:t,recoverable:!0})}return Cs({state:"unsupported",extension:e,title:et(i,"state.unsupported.title"),message:et(i,"state.unsupported.message",{extension:s}),description:et(i,"state.unsupported.description"),theme:t,recoverable:!0})}})),Ei=ee((()=>{Ft(),vi(),Et()})),ea,xs,ta,ia,sa,Ms=ee((()=>{nt(),ws(),yi(),Ei(),ea=(e,t)=>({rendered:e,destroy:()=>t?t():xs(e)}),xs=e=>{if(!e||typeof e!="object")return;const t=e;if(typeof t.unmount=="function")return t.unmount();if(typeof t.$destroy=="function")return t.$destroy();if(typeof t.destroy=="function")return t.destroy()},ta=({source:e,options:t,registerExportAdapter:i,renderContext:s})=>({filename:e.filename,url:e.url,streamUrl:e.url,options:t,registerExportAdapter:i,...s}),ia=({handler:e,getTarget:t=r=>r.surface.container,createContext:i=ta,destroy:s})=>async r=>{const{source:n}=r;if(!n.buffer)throw new Error("FileRenderHandler renderer requires an ArrayBuffer source.");const a=t(r),o=await e(n.buffer,a,n.extension,i(r));return ea(o,()=>s?s(o,r):xs(o))},sa=({definitions:e=je,handlers:t,getTarget:i,createContext:s,destroy:r})=>{const n=pi(e),a=Ps({registry:n,handlers:t});return{registry:pi(n.list().map(o=>{const l=a.handlersByRendererId.get(o.id);return l?{...o,load:ia({handler:l,getTarget:i,createContext:s,destroy:r})}:o})),dispatcher:a,missingRendererIds:a.missingRendererIds}}})),fh=Mt({default:()=>gh});async function gh(e,t,i){const s=await da(e,i);let r=1,n=0;const a=Un(),o=document.createElement("div");o.className="image-viewer",o.dataset.viewerZoomProvider="image";const l=document.createElement("div");l.className="image-stage";const d=document.createElement("img");d.alt="图片",d.src=s,l.append(d),o.append(l);const c=ha(s),h=()=>c.open();d.addEventListener("click",h),document.body.append(c.element);const u=()=>{n=o.clientHeight||0,Os(d,n,r),a.emit()},f=new ResizeObserver(u);f.observe(o);const m=()=>({scale:r,label:`${Math.round(r*100)}%`,canZoomIn:r<5,canZoomOut:r>.1,canReset:r!==1,minScale:.1,maxScale:5}),g=y=>(r=ca(y),Os(d,n,r),a.emit(),m());return Mn(o,{zoomIn:()=>g(r+.15),zoomOut:()=>g(r-.15),resetZoom:()=>g(1),setZoom:g,getState:m,subscribe:a.subscribe}),t.replaceChildren(aa(),o),u(),{$el:t,unmount(){On(o),f.disconnect(),d.removeEventListener("click",h),c.destroy(),t.replaceChildren()}}}var ra,na,aa,oa,la,da,ca,Os,ha,mh=ee((()=>{Ot(),As(),ra={avif:"image/avif",bmp:"image/bmp",gif:"image/gif",heic:"image/heic",heif:"image/heif",ico:"image/x-icon",jxl:"image/jxl",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",svg:"image/svg+xml",tif:"image/tiff",tiff:"image/tiff",webp:"image/webp"},na=`
|
|
1
|
+
(function(){var zc=Object.create,xt=Object.defineProperty,qc=Object.getOwnPropertyDescriptor,Xc=Object.getOwnPropertyNames,Qc=Object.getPrototypeOf,Cn=Object.prototype.hasOwnProperty,ee=(e,t)=>()=>(e&&(t=e(e=0)),t),Ae=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Mt=(e,t)=>{let i={};for(var s in e)xt(i,s,{get:e[s],enumerable:!0});return t||xt(i,Symbol.toStringTag,{value:"Module"}),i},xn=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(var r=Xc(t),n=0,a=r.length,o;n<a;n++)o=r[n],!Cn.call(e,o)&&o!==i&&xt(e,o,{get:(l=>t[l]).bind(null,o),enumerable:!(s=qc(t,o))||s.enumerable});return e},Zc=(e,t,i)=>(i=e!=null?zc(Qc(e)):{},xn(t||!e||!e.__esModule?xt(i,"default",{value:e,enumerable:!0}):i,e)),Jc=e=>Cn.call(e,"module.exports")?e["module.exports"]:xn(xt({},"__esModule",{value:!0}),e),eh=ee((()=>{})),th=ee((()=>{eh()})),Es,Ts,Ss,bs,je,ih,nt=ee((()=>{Es=["zip","zipx","7z","rar","tar","gz","gzip","tgz","bz2","bzip2","tbz","tbz2","xz","txz","lzma","zst","tzst","cab","ar","cpio","iso","xar","lha","lzh","jar","war","ear","apk","cbz","cbr"],Ts=["glb","gltf","obj","stl","ply","fbx","dae","3ds","3mf","amf","usd","usda","usdc","usdz","kmz","step","stp","iges","igs","ifc","3dm","brep","pcd","wrl","vrml","xyz","vtk","vtp"],Ss=["txt","json","js","mjs","cjs","css","java","py","html","htm","jsx","ts","tsx","xml","log","vue","yaml","yml","ini","sh","bash","sql","go","rs","php","c","cpp","cc","h","hpp","cs","diff","patch","bundle","bdl","jsonc","json5","ipynb","toml","proto","hcl","tex","gv","http","react","rb","swift","kt"],bs=["gif","jpg","jpeg","bmp","tiff","tif","png","svg","webp","avif","ico","heic","heif","jxl"],je=[{id:"office-word-openxml",label:"Word OpenXML",category:"office",extensions:["docx","docm","dotx","dotm"],async:!0,capabilities:{download:!0,print:"adapter",exportHtml:"adapter",zoom:"provider",search:!0}},{id:"office-word-binary",label:"Word Binary",category:"office",extensions:["doc","dot"],async:!0,capabilities:{download:!0,print:"adapter",exportHtml:"adapter",zoom:"provider",search:!0}},{id:"office-presentation",label:"PowerPoint",category:"office",extensions:["pptx","pptm","potx","potm","ppsx","ppsm"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!0}},{id:"open-document",label:"Open Document",category:"office",extensions:["rtf","odt","odp"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!0}},{id:"spreadsheet-openxml",label:"Spreadsheet",category:"office",extensions:["xlsx","xltx","xlsm","xlsb","xls","xlt","xltm","csv","ods","fods","numbers"],async:!0,capabilities:{download:!0,print:!1,exportHtml:!1,zoom:"provider",search:!0}},{id:"pdf",label:"PDF",category:"document",extensions:["pdf"],async:!0,capabilities:{download:!0,print:"adapter",exportHtml:"adapter",zoom:"provider",search:"provider"}},{id:"ofd",label:"OFD",category:"document",extensions:["ofd"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!0}},{id:"typst",label:"Typst",category:"document",extensions:["typ","typst"],async:!0,capabilities:{download:!0,print:"adapter",exportHtml:"adapter",zoom:"provider",search:!0}},{id:"archive",label:"Archive",category:"archive",extensions:Es,async:!0,capabilities:{download:!0,print:!1,exportHtml:!1,zoom:!1,search:!0}},{id:"email",label:"Email",category:"email",extensions:["eml","msg","mbox"],async:!0,capabilities:{download:!0,print:!1,exportHtml:!0,zoom:!1,search:!0}},{id:"eda",label:"EDA",category:"eda",extensions:["olb","dra","gds","oas","oasis"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:!1,search:!0}},{id:"cad",label:"CAD",category:"cad",extensions:["dxf","dwg","dwf","dwfx","xps"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!1}},{id:"model",label:"3D Model",category:"model",extensions:Ts,async:!0,capabilities:{download:!0,print:!1,exportHtml:!1,zoom:"provider",search:!1}},{id:"geo",label:"Geospatial",category:"geo",extensions:["geojson","kml","gpx","shp"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!0}},{id:"drawing",label:"Drawing",category:"drawing",extensions:["excalidraw","drawio","dio","mermaid","mmd","plantuml","puml"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!0}},{id:"mindmap",label:"Mind Map",category:"mindmap",extensions:["xmind"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!0}},{id:"epub",label:"EPUB",category:"ebook",extensions:["epub"],async:!0,capabilities:{download:!0,print:!1,exportHtml:!0,zoom:!1,search:"provider"}},{id:"umd",label:"UMD",category:"ebook",extensions:["umd"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!0}},{id:"image",label:"Image",category:"image",extensions:bs,async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:"provider",search:!1}},{id:"markdown",label:"Markdown",category:"markdown",extensions:["md","markdown"],async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:!1,search:!0}},{id:"code",label:"Code and Text",category:"code",extensions:Ss,async:!0,capabilities:{download:!0,print:!0,exportHtml:!0,zoom:!1,search:!0}},{id:"video",label:"Video",category:"media",extensions:["mp4","webm","m3u8"],async:!0,capabilities:{download:!0,print:!1,exportHtml:!1,zoom:!1,search:!1}},{id:"audio",label:"Audio",category:"media",extensions:["mp3","mpeg","wav","ogg","oga","opus","m4a","aac","flac","weba","midi","mid"],async:!0,capabilities:{download:!0,print:!1,exportHtml:!1,zoom:!1,search:!1}},{id:"data-asset",label:"Data Asset",category:"asset",extensions:["ttf","otf","woff","woff2","psd","ai","eps","sqlite","wasm","parquet","avro","webarchive"],async:!0,capabilities:{download:!0,print:!1,exportHtml:!0,zoom:!1,search:!0}}],ih=Object.freeze(Array.from(new Set(je.flatMap(e=>e.extensions))).sort())})),sh,rh,nh=ee((()=>{sh=["[data-viewer-anchor-id]",".pdfViewer .page",".docx-wrapper section",".docx p",".docx li",".docx table",".markdown-body h1",".markdown-body h2",".markdown-body h3",".markdown-body h4",".markdown-body h5",".markdown-body h6",".markdown-body p",".markdown-body li",".markdown-body pre",".markdown-body table","article h1","article h2","article h3","article h4","article h5","article h6","article p","article li","article pre","article table","pre code","p","li","tr","h1","h2","h3","h4","h5","h6","pre","table"].join(","),rh=[".viewer-actions",".viewer-watermark",".state-panel",".pdf-toolbar",".pdf-nav-pane",".flyfish-search-match"].join(",")})),Is,Mn,On,ah=ee((()=>{Is=new WeakMap,Mn=(e,t)=>{Is.set(e,t),e.dataset.viewerZoomProvider=e.dataset.viewerZoomProvider||"custom",e.__flyfishViewerZoomProvider=t},On=e=>{e&&(Is.delete(e),delete e.dataset.viewerZoomProvider,delete e.__flyfishViewerZoomProvider)}})),Ot=ee((()=>{nh(),ah()})),oh,Fn=ee((()=>{Ot(),oh=["script","style","textarea","input","select","button",".viewer-actions",".viewer-watermark",".state-panel",".pdf-toolbar",".pdf-nav-pane",".flyfish-search-match",".textLayer",".annotationLayer",".xfaLayer","svg","canvas","iframe","video","audio"].join(",")})),Nn=ee((()=>{Ot(),Fn()})),Un,As=ee((()=>{Ot(),Un=()=>{const e=new Set;return{emit(){e.forEach(t=>t())},subscribe(t){return e.add(t),()=>{e.delete(t)}}}}})),ke,gi=ee((()=>{ke=e=>e.trim().replace(/^\./,"").toLowerCase()})),lh,Bn,$n,Ls,Gn,Vn,Kn,Rs,Hn,et,mi,Et=ee((()=>{lh="zh-CN",Bn={"toolbar.zoomGroup":"缩放控制","toolbar.zoomOut":"缩小预览","toolbar.zoomIn":"放大预览","toolbar.zoomReset":"还原比例","toolbar.download":"下载","toolbar.downloadTitle":"下载原始文件","toolbar.print":"打印","toolbar.printTitle":"打印完整渲染内容","toolbar.exportHtml":"HTML","toolbar.exportHtmlTitle":"导出当前渲染后的 HTML","state.ready.title":"预览完成","state.ready.message":"文件内容已完成渲染。","state.empty.title":"暂无文件","state.empty.message":"请选择文件或提供可访问的文件地址后开始预览。","state.unsupported.install.title":"需要装配预览能力","state.unsupported.install.message":"{extension} 格式已在支持矩阵中,但当前项目尚未装配 {rendererLabel} renderer。","state.unsupported.install.description":"推荐安装 {presetPackage},通过 options.preset / options.renderers 注入对应能力{rendererTip};Vite 项目也可以使用 @file-viewer/vite-plugin 自动发现已安装 preset。","state.unsupported.title":"暂不支持在线预览","state.unsupported.message":"不支持{extension}格式的在线预览,请下载后预览或转换为支持的格式。","state.unsupported.description":"支持 Office、PDF、OFD、Typst、压缩包、邮件、OLB/DRA、CAD、地理数据、3D 模型、Excalidraw、draw.io、EPUB、UMD、Markdown、代码/文本、图片、音视频、字体和数据资产的在线预览","state.error.title":"预览失败","preview.downloading":"正在下载文件资源...","preview.streamingPdf":"正在建立 PDF 流式预览...","preview.reading":"正在解析文件内容...","error.download":"下载失败","error.print":"打印失败","error.exportHtml":"导出 HTML 失败","error.noDownloadSource":"当前没有可下载的源文件","error.noExportContent":"当前没有可导出的预览内容","error.printUnavailable":"当前文件类型不支持完整打印,请下载原文件后在本地应用中打印","error.printWindowBlocked":"浏览器拦截了打印窗口","error.remoteDownload":"文件下载失败","error.localRead":"读取文件异常","error.load":"加载文件异常","error.stream":"加载 PDF 流式预览异常","error.beforeOperation":"操作前置校验失败","operation.download":"下载原始文件","operation.print":"打印完整渲染内容","operation.exportHtml":"导出渲染 HTML","operation.zoomIn":"放大预览","operation.zoomOut":"缩小预览","operation.zoomReset":"还原预览比例","pdf.toolbar.toggleNavigation":"切换导航窗格","pdf.toolbar.previousPage":"上一页","pdf.toolbar.nextPage":"下一页","pdf.toolbar.fitWidth":"适合宽度","pdf.toolbar.zoomOut":"缩小","pdf.toolbar.zoomIn":"放大","pdf.toolbar.rotateLeft":"向左旋转","pdf.toolbar.rotateRight":"向右旋转","pdf.nav.typeLabel":"PDF 导航类型","pdf.nav.pagesTab":"页面","pdf.nav.outlineTab":"目录","pdf.nav.pagesTitle":"页面导航","pdf.nav.outlineTitle":"目录导航","pdf.nav.pageCount":"{count} 页","pdf.nav.itemCount":"{count} 项","pdf.nav.pageLabel":"第 {page} 页","pdf.nav.outlineEmpty":"当前 PDF 没有可用目录","pdf.nav.outlineFallbackTitle":"目录 {index}","pdf.thumbnail.alt":"第 {page} 页缩略图","pdf.state.loading":"正在加载 PDF...","pdf.error.browserWindow":"PDF 预览需要浏览器窗口","pdf.error.missingSource":"PDF 缺少可读取的数据源","pdf.error.loadFailed":"PDF 加载失败","pdf.error.notLoaded":"PDF 尚未加载完成,请稍后再试","pdf.error.unloaded":"PDF 已卸载,无法继续打印","pdf.error.canvasUnavailable":"当前浏览器无法创建 PDF 打印画布","pdf.export.pageTitle":"{title} - 第 {page} 页","spreadsheet.loading.kicker":"Excel 表格","spreadsheet.loading.title":"正在解析 Excel 工作簿","spreadsheet.loading.hint":"正在准备工作表、样式和大数据视口,请稍候。","spreadsheet.loading.streaming":"正在平滑补充可视区数据","spreadsheet.tabs.ariaLabel":"工作表列表","spreadsheet.state.parsingWorkbook":"正在解析 Excel 工作簿,请耐心等待...","spreadsheet.state.preparingSheet":"正在准备工作表内容...","spreadsheet.state.preparingSheetNamed":"正在准备「{name}」...","spreadsheet.state.cachedRows":"已缓存 {cached} / {total} 行","spreadsheet.state.rows":"共 {rows} 行,按视口预取平滑加载","spreadsheet.state.rowsAndColumns":"共 {rows} 行,{cols} 列,按视口预取平滑加载","spreadsheet.error.parseFailed":"Excel 解析失败","spreadsheet.error.workerFailed":"Excel Worker 运行失败","archive.error.nestedUnsupported":"不支持 .{type} 格式的在线预览,请下载后预览或转换为支持的格式","archive.loading.readingDirectory":"正在读取压缩包目录...","archive.loading.readingDirectoryHint":"大文件会在 Worker 中解析,避免阻塞主线程。","archive.search.placeholder":"筛选压缩包内文件","archive.sidebar.hide":"隐藏压缩包文件列表","archive.sidebar.show":"显示压缩包文件列表","archive.preview.title":"压缩包内预览","archive.preview.chooseFile":"请选择一个文件","archive.preview.downloadFile":"下载文件","archive.error.title":"压缩包预览提示","archive.stats.summary":"{count} 个文件 · {size} · {previewable} 个可直接预览","archive.warning.encrypted":"检测到加密内容,输入正确密码后即可预览;密码仅在当前会话中传递给 libarchive Worker。","archive.password.title":"请输入压缩包密码","archive.password.description":"该压缩包包含加密内容,需要密码才能继续读取目录或预览内部文件。","archive.password.placeholder":"压缩包密码","archive.password.invalid":"密码不正确或无法解密,请重新输入。","archive.password.required":"请输入密码后继续。","archive.password.cancel":"取消","archive.password.confirm":"解锁预览","archive.error.passwordRequired":"已取消输入密码,无法预览加密压缩包。","archive.error.encryptedRequiresWorker":"该压缩包包含加密内容,需要发布 libarchive Worker/WASM 后才能在线解密预览。","archive.empty.title":"选择左侧文件即可预览","archive.empty.message":"压缩包只读取目录;文件内容会在点击后按需解压,并在体积允许时缓存到 IndexedDB。","archive.loading.initializingCandidate":"正在初始化 {label}...","archive.loading.initializingCandidateHint":"如果当前服务器没有正确发布 Worker/WASM,会自动切换兼容模式。","archive.error.candidateInitTimeout":"{label} 初始化超时","archive.error.encryptedCheckTimeout":"{label} 加密检测超时","archive.loading.directoryReadyHint":"目录读取完成后,点击内部文件才会按需解压。","archive.error.candidateReadTimeout":"{label} 读取目录超时","archive.loading.workerFallback":"Worker 不可用,正在切换 ZIP/TAR 兼容模式...","archive.loading.workerFallbackHint":"兼容模式无需额外静态 Worker,适合手机 WebView 或本地临时服务器。","archive.notice.workerFallback":"当前环境的 libarchive Worker 未能启动,已自动切换到 ZIP/TAR/GZIP 兼容模式。RAR、7z 等格式仍建议发布 vendor/libarchive/worker-bundle.js 与 libarchive.wasm。","archive.error.tooLarge":"压缩包体积 {size} 超过安全上限 {limit},请下载后在本地解压。","archive.loading.initializingWorker":"正在初始化压缩包解析 Worker...","archive.loading.initializingWorkerHint":"大文件会在 Worker 中解析,避免阻塞主线程。","archive.error.workerInitFailed":"压缩包 Worker 初始化失败","archive.error.entryTooLarge":"压缩包内文件 {name} 体积 {size} 超过预览上限 {limit}。","archive.loading.extracting":"正在按需解压 {name}...","archive.loading.rendering":"正在渲染 {name}...","archive.loading.exporting":"正在导出 {name}...","media.audio.title":"音频预览","media.audio.description":"使用浏览器原生播放器打开,兼容性取决于当前浏览器支持的音频编码。","media.audio.unsupported":"当前浏览器不支持音频播放。","media.video.title":"视频预览","media.video.unsupported":"当前浏览器不支持该视频格式。","media.video.hlsHint":"HLS 会优先使用原始 URL 加载分片;如果传入的是本地单文件清单,请确保分片地址可被浏览器访问。","media.midi.title":"MIDI 文件","media.midi.loading":"正在解析 MIDI 轨道...","media.midi.trackHeader":"轨道","media.midi.instrumentHeader":"乐器","media.midi.channelHeader":"通道","media.midi.noteCountHeader":"音符数","media.midi.durationHeader":"时长","media.midi.durationStat":"时长","media.midi.trackStat":"轨道","media.midi.noteStat":"音符","media.midi.parseFailed":"MIDI 解析失败","email.mbox.subject":"{filename} · 第 1 封","email.mbox.summary":"MBOX 共识别 {count} 封邮件,当前展示第 1 封。","email.error.title":"邮件预览提示","email.meta.from":"发件人","email.meta.to":"收件人","email.meta.cc":"抄送","email.meta.date":"时间","email.tabs.text":"正文","email.tabs.headers":"头信息","email.attachments.title":"附件","email.attachments.empty":"暂无附件","email.attachments.download":"下载附件","email.attachments.opening":"正在打开附件 {name}...","email.attachments.nestedUnavailable":"当前运行环境未提供附件嵌套预览入口,请下载 {name} 后查看。","email.loading.parsing":"正在解析邮件...","data.font.sample":"Flyfish Viewer 轻量预览 AaBbCc 1234567890","data.error.fontFaceUnsupported":"当前浏览器不支持 FontFace API","data.title.font":"字体文件预览","data.title.sqlite":"SQLite 数据库预览","data.title.parquet":"Parquet 列式数据预览","data.title.avro":"Avro 对象容器预览","data.title.wasm":"WebAssembly 模块预览","data.title.eps":"EPS 矢量文件摘要","data.title.ai":"Illustrator 文件摘要","data.title.webarchive":"WebArchive 摘要预览","data.title.summary":"数据资产摘要","data.label.format":"格式","data.label.size":"大小","data.label.rendering":"渲染方式","data.label.objects":"对象数","data.label.sampleTable":"示例表","data.label.rows":"行数","data.label.columns":"列数","data.label.sampleRows":"示例行","data.label.imports":"导入","data.label.exports":"导出","data.label.magic":"Magic","data.label.note":"说明","data.label.container":"容器","data.value.schemaRead":"已读取","data.value.schemaUnread":"未读取","data.note.aiSummary":"非 PDF-compatible AI 按摘要展示","data.note.postscriptSummary":"PostScript 摘要展示","data.note.webarchive":"安全提取可读片段,不执行网页脚本","data.image.alt":"资产预览","psd.title":"PSD 图层预览","psd.action.fit":"适合","psd.action.showAll":"全显","psd.action.hideAll":"全隐","psd.layers.title":"图层","psd.layers.redrawable":"{count} 可重绘","psd.layers.empty":"未发现可展示图层,使用合成图预览。","psd.layers.hidden":"隐藏","drawing.error.viewerLoadFailed":"diagrams.net viewer 加载失败","drawing.error.excalidrawEmpty":"Excalidraw 文件中没有可预览图元","drawing.error.excalidrawTimeout":"Excalidraw 官方导出超时,自动切换 rough.js 兼容渲染","drawing.error.drawioParseFailed":"Draw.io XML 解析失败:{message}","drawing.error.drawioNoModel":"当前 Draw.io 文件没有可直接渲染的 mxGraphModel。","drawing.error.drawioNoElements":"当前 Draw.io 文件没有可预览图元。","drawing.error.viewerInitFailed":"diagrams.net viewer 未正确初始化","drawing.error.drawioTimeout":"diagrams.net 官方 Viewer 加载超时,自动切换本地 SVG 预览","drawing.error.svgParseFailed":"SVG 解析失败","drawing.error.plantumlRenderFailed":"PlantUML SVG 渲染失败:{status}","drawing.title.excalidraw":"Excalidraw 官方 SVG 预览","drawing.title.mermaid":"Mermaid SVG 预览","drawing.title.plantuml":"PlantUML SVG 预览","drawing.title.drawio":"Draw.io 离线 SVG 预览","drawing.toolbar.zoomOut":"缩小","drawing.toolbar.zoomIn":"放大","drawing.toolbar.fit":"适合","drawing.toolbar.fitWidth":"适合宽度","drawing.state.loading":"正在加载绘图预览...","text.code.loadingHighlight":"正在加载高亮...","ebook.toc":"目录","ebook.reading":"阅读中","ebook.itemCount":"{count} 项","epub.title":"EPUB 电子书","epub.previousPage":"上一页","epub.nextPage":"下一页","epub.loading":"正在解析 EPUB...","epub.chapterFallback":"章节 {index}","epub.renderIncomplete":"EPUB 正文渲染未完成,请刷新后重试","umd.title":"UMD 电子书","umd.previousChapter":"上一章","umd.nextChapter":"下一章","umd.loading":"正在解析 UMD...","umd.emptyContent":"未解析到正文内容","umd.chapterFallback":"章节 {index}","umd.galleryFallback":"图集 {index}","umd.warningBodyTooShort":"UMD 正文长度小于声明长度,文件可能不完整","umd.error.unexpectedEnd":"UMD 文件结构不完整,读取时遇到意外结尾","umd.error.invalidFile":"不是有效的 UMD 电子书文件","typst.summaryRenderer":"Typst WASM 渲染器","typst.pageSummary.empty":"0 页","typst.pageSummary.ready":"{count} 页 / {width} x {height} pt","typst.status.compiling":"正在编译","typst.status.failed":"编译失败","typst.status.rendered":"已渲染","typst.loading.title":"正在解析 Typst","typst.loading.hint":"加载编译器并生成页面预览...","typst.error.title":"Typst 渲染失败","typst.error.timeout":"Typst WASM / 字体加载或编译超过 {seconds} 秒","typst.error.timeoutHint":"请检查 Typst compiler WASM、renderer WASM、字体目录的下载速度和缓存策略;弱网或跨境部署可通过 options.typst.renderTimeoutMs 调大浏览器端加载/编译超时。","typst.error.assetHint":"Typst 需要本地 compiler / renderer WASM 和字体目录。请运行 file-viewer-copy-assets,或配置 options.typst.compilerWasmUrl / options.typst.rendererWasmUrl / options.typst.fontAssetsUrl,并确认服务器以 application/wasm 返回 WASM。","typst.error.svgParseFailed":"Typst SVG 解析失败","typst.error.wasmLoadFailed":"Typst WASM 加载失败","xmind.toolbar.zoomOut":"缩小","xmind.toolbar.zoomIn":"放大","xmind.toolbar.fit":"适合","xmind.toolbar.fitTitle":"适配画布","xmind.state.loading":"正在解析 XMind 脑图...","xmind.stats.nodes":"节点","xmind.stats.depth":"层级","xmind.stats.theme":"主题","xmind.stats.template":"模板","xmind.badge.paused":"暂停","xmind.badge.collapsed":"折叠","xmind.badge.floating":"浮动","xmind.badge.summary":"概要","xmind.badge.callout":"标注","xmind.imageResource":"图片资源: {name}","xmind.error.unrecognized":"无法识别 XMind 文件: ZIP 中未找到 content.json 或 content.xml","xmind.error.noCanvas":"XMind 文件中没有可预览的画布","cad.toolbar.fit":"适配","cad.toolbar.zoomOut":"缩小","cad.toolbar.zoomIn":"放大","cad.layers.title":"图层","cad.layers.count":"{count} 项","cad.inspector.title":"结构","cad.inspector.entities":"实体","cad.inspector.blocks":"块","cad.inspector.pages":"页面","cad.inspector.drawn":"绘制","cad.state.loadingViewer":"正在加载 CAD 预览器...","cad.state.parsing":"正在解析 CAD...","cad.error.parseFailed":"CAD 文件解析失败","image.alt":"图片","image.lightbox.alt":"图片预览","image.lightbox.close":"关闭图片预览","gitBundle.error.invalid":"当前文件不是标准 Git bundle。","gitBundle.error.missingPack":"Git bundle header 后未找到 PACK 数据。","gitBundle.notice.delta":"当前 bundle 包含 delta 压缩对象。预览器已在浏览器端解析常规 OFS_DELTA / REF_DELTA;若仍有缺失文件,通常是包体过大、对象过多或依赖外部 prerequisite。","gitBundle.title.history":"历史记录","gitBundle.title.fileTree":"文件树","gitBundle.file.choose":"选择文件查看内容","gitBundle.file.noTree":"当前 bundle 的 tree/blob 可能被 delta 压缩,暂未解析到可展开文件。","gitBundle.file.none":"未解析到文件","gitBundle.history.empty":"当前 bundle 未解析到 commit 对象,仅展示 refs 和 pack 摘要。","gitBundle.toolbar.summary":"{commits} commits · {files} files","gitBundle.meta.bundle":"Bundle","gitBundle.meta.refs":"Refs","gitBundle.meta.commits":"Commits","gitBundle.meta.objects":"Objects","gitBundle.meta.deltas":"Deltas","gitBundle.meta.objectFormat":"Object format","gitBundle.meta.objectTypes":"Object types","geo.error.unrecognized":"无法识别的 GeoJSON 数据","geo.error.xmlParseFailed":"XML 解析失败","geo.error.unsupported":"不支持 .{type} 地理格式","geo.title":"地理数据预览","geo.featureCount":"要素数","geo.bounds":"范围","geo.geometryTypes":"几何类型","geo.aria":"地理数据 SVG 预览","geo.loading":"正在解析地理数据...","model.toolbar.fit":"适配","model.toolbar.rotate":"旋转","model.toolbar.wireframe":"线框","model.toolbar.grid":"网格","model.toolbar.axes":"坐标","model.state.loadingSummary":"正在加载模型","model.state.loading":"正在解析 3D 模型...","model.state.loaded":"模型已加载","model.state.parseFailed":"模型解析失败","model.summary.meshes":"{count} 个网格","model.summary.points":"{count} 个点云","model.error.daeEmpty":"DAE 模型未解析出有效场景","model.error.unsupported":"暂不支持 .{type} 模型格式","model.error.parseFailed":"{type} 模型解析失败","model.notice.signature":"检测到文件签名: {signature}。","loading.generic.label":"文件内容","loading.generic.hint":"正在整理内容结构并生成预览。","loading.word.label":"Word 文档","loading.word.hint":"正在准备分页、文本样式和文档结构。","loading.wordWorker.hint":"正在通过 Worker 准备文档结构、文本样式和分页结果。","loading.sheet.label":"Excel 表格","loading.sheet.hint":"正在准备工作表、样式和可视区数据。","loading.csv.label":"表格数据","loading.csv.hint":"正在准备行列数据和基础样式。","loading.presentation.label":"PPT 演示文稿","loading.presentation.hint":"正在构建幻灯片布局和媒体内容。","loading.pdf.label":"PDF 文档","loading.pdf.hint":"正在载入页面位图、文本层和缩放视图。","loading.ofd.label":"OFD 版式文件","loading.ofd.hint":"正在解析国产版式文档和页面对象。","loading.archive.label":"压缩包","loading.archive.hint":"正在启动 Worker 并读取压缩包目录。","loading.email.label":"邮件文件","loading.email.hint":"正在解析邮件头、正文和附件。","loading.msg.hint":"正在解析 Outlook 邮件和附件。","loading.eda.label":"EDA 文件","loading.eda.hint":"正在读取 EDA 容器结构和可读属性。","loading.cad.label":"CAD 图纸","loading.cad.hint":"正在准备 CAD 图层、几何对象和画布视图。","loading.dwg.hint":"正在通过 Worker 加载 DWG 几何和 LibreDWG WASM。","loading.dwf.hint":"正在加载 DWF native renderer 与 W2D/W3D 图形。","loading.dwfx.hint":"正在加载 DWFx/XPS native renderer 与页面图形。","loading.xps.hint":"正在加载 XPS native renderer 与嵌入字体。","loading.drawio.label":"draw.io 图纸","loading.drawio.hint":"正在解析图元、连线和 SVG 预览。","loading.excalidraw.label":"Excalidraw 图纸","loading.excalidraw.hint":"正在解析手绘图元并生成安全 SVG。","loading.epub.label":"EPUB 电子书","loading.epub.hint":"正在解析目录、章节资源和阅读分页。","loading.umd.label":"UMD 电子书","loading.umd.hint":"正在解析移动电子书结构、目录和压缩正文。","loading.image.label":"图片文件","loading.image.hint":"正在解码像素数据并生成预览。","loading.video.label":"视频文件","loading.video.hint":"正在准备媒体资源和播放组件。","loading.audio.label":"音频文件","loading.audio.hint":"正在准备音频资源和播放控件。"},$n={"toolbar.zoomGroup":"Zoom controls","toolbar.zoomOut":"Zoom out","toolbar.zoomIn":"Zoom in","toolbar.zoomReset":"Reset zoom","toolbar.download":"Download","toolbar.downloadTitle":"Download the original file","toolbar.print":"Print","toolbar.printTitle":"Print the complete rendered document","toolbar.exportHtml":"HTML","toolbar.exportHtmlTitle":"Export the rendered HTML","state.ready.title":"Preview ready","state.ready.message":"The file has been rendered.","state.empty.title":"No file selected","state.empty.message":"Choose a file or provide an accessible URL to start previewing.","state.unsupported.install.title":"Preview capability required","state.unsupported.install.message":"{extension} is in the supported matrix, but {rendererLabel} renderer is not assembled in this project.","state.unsupported.install.description":"Install {presetPackage} and pass the capability through options.preset / options.renderers{rendererTip}. Vite projects can also use @file-viewer/vite-plugin to auto-discover installed presets.","state.unsupported.title":"Online preview is not supported yet","state.unsupported.message":"{extension} cannot be previewed online. Download it or convert it to a supported format.","state.unsupported.description":"Supports online preview for Office, PDF, OFD, Typst, archives, email, OLB/DRA, CAD, geospatial data, 3D models, Excalidraw, draw.io, EPUB, UMD, Markdown, code/text, images, audio/video, fonts, and structured data assets.","state.error.title":"Preview failed","preview.downloading":"Downloading file resources...","preview.streamingPdf":"Preparing streaming PDF preview...","preview.reading":"Parsing file content...","error.download":"Download failed","error.print":"Print failed","error.exportHtml":"HTML export failed","error.noDownloadSource":"There is no original file source to download.","error.noExportContent":"There is no rendered preview content to export.","error.printUnavailable":"This file type does not support full-document printing. Download the original file and print it locally.","error.printWindowBlocked":"The browser blocked the print window.","error.remoteDownload":"File download failed","error.localRead":"Failed to read local file","error.load":"Failed to load file","error.stream":"Failed to load streaming PDF preview","error.beforeOperation":"Before-operation check failed","operation.download":"Download original file","operation.print":"Print complete rendered content","operation.exportHtml":"Export rendered HTML","operation.zoomIn":"Zoom in","operation.zoomOut":"Zoom out","operation.zoomReset":"Reset preview zoom","pdf.toolbar.toggleNavigation":"Toggle navigation pane","pdf.toolbar.previousPage":"Previous page","pdf.toolbar.nextPage":"Next page","pdf.toolbar.fitWidth":"Fit to width","pdf.toolbar.zoomOut":"Zoom out","pdf.toolbar.zoomIn":"Zoom in","pdf.toolbar.rotateLeft":"Rotate left","pdf.toolbar.rotateRight":"Rotate right","pdf.nav.typeLabel":"PDF navigation type","pdf.nav.pagesTab":"Pages","pdf.nav.outlineTab":"Outline","pdf.nav.pagesTitle":"Page navigation","pdf.nav.outlineTitle":"Outline navigation","pdf.nav.pageCount":"{count} pages","pdf.nav.itemCount":"{count} items","pdf.nav.pageLabel":"Page {page}","pdf.nav.outlineEmpty":"This PDF has no available outline.","pdf.nav.outlineFallbackTitle":"Outline {index}","pdf.thumbnail.alt":"Page {page} thumbnail","pdf.state.loading":"Loading PDF...","pdf.error.browserWindow":"PDF preview requires a browser window","pdf.error.missingSource":"PDF has no readable data source","pdf.error.loadFailed":"Failed to load PDF","pdf.error.notLoaded":"The PDF is not loaded yet. Please try again later.","pdf.error.unloaded":"The PDF has been unloaded and cannot continue printing.","pdf.error.canvasUnavailable":"This browser cannot create a PDF print canvas.","pdf.export.pageTitle":"{title} - Page {page}","spreadsheet.loading.kicker":"Excel workbook","spreadsheet.loading.title":"Parsing Excel workbook","spreadsheet.loading.hint":"Preparing worksheets, styles, and virtualized viewport data.","spreadsheet.loading.streaming":"Loading visible worksheet data","spreadsheet.tabs.ariaLabel":"Worksheet list","spreadsheet.state.parsingWorkbook":"Parsing the Excel workbook. Please wait...","spreadsheet.state.preparingSheet":"Preparing worksheet content...","spreadsheet.state.preparingSheetNamed":"Preparing “{name}”...","spreadsheet.state.cachedRows":"Cached {cached} / {total} rows","spreadsheet.state.rows":"{rows} rows, loading smoothly by viewport","spreadsheet.state.rowsAndColumns":"{rows} rows, {cols} columns, loading smoothly by viewport","spreadsheet.error.parseFailed":"Failed to parse Excel","spreadsheet.error.workerFailed":"Excel Worker failed","archive.error.nestedUnsupported":".{type} cannot be previewed online. Download it or convert it to a supported format.","archive.loading.readingDirectory":"Reading archive directory...","archive.loading.readingDirectoryHint":"Large files are parsed in a Worker to keep the main thread responsive.","archive.search.placeholder":"Filter files inside the archive","archive.sidebar.hide":"Hide archive file list","archive.sidebar.show":"Show archive file list","archive.preview.title":"Archive entry preview","archive.preview.chooseFile":"Choose a file","archive.preview.downloadFile":"Download file","archive.error.title":"Archive preview notice","archive.stats.summary":"{count} files · {size} · {previewable} directly previewable","archive.warning.encrypted":"Encrypted content was detected. Enter the correct password to preview it; the password is passed only to the libarchive Worker for this session.","archive.password.title":"Enter archive password","archive.password.description":"This archive contains encrypted content. A password is required to read the directory or preview entries.","archive.password.placeholder":"Archive password","archive.password.invalid":"The password is incorrect or the entry could not be decrypted. Try again.","archive.password.required":"Enter a password to continue.","archive.password.cancel":"Cancel","archive.password.confirm":"Unlock preview","archive.error.passwordRequired":"Password entry was cancelled, so the encrypted archive cannot be previewed.","archive.error.encryptedRequiresWorker":"This archive contains encrypted content and requires the libarchive Worker/WASM assets for online decryption.","archive.empty.title":"Choose a file from the left to preview","archive.empty.message":"The archive directory is read first. File contents are extracted on demand and cached in IndexedDB when size allows.","archive.loading.initializingCandidate":"Initializing {label}...","archive.loading.initializingCandidateHint":"If the server does not publish Worker/WASM assets correctly, the viewer falls back automatically.","archive.error.candidateInitTimeout":"{label} initialization timed out","archive.error.encryptedCheckTimeout":"{label} encryption check timed out","archive.loading.directoryReadyHint":"After the directory is ready, click an entry to extract it on demand.","archive.error.candidateReadTimeout":"{label} directory read timed out","archive.loading.workerFallback":"Worker unavailable. Switching to ZIP/TAR compatibility mode...","archive.loading.workerFallbackHint":"Compatibility mode needs no static Worker and works well in mobile WebViews or temporary local servers.","archive.notice.workerFallback":"The libarchive Worker could not start in this environment, so ZIP/TAR/GZIP compatibility mode is active. RAR, 7z, and similar formats should still publish vendor/libarchive/worker-bundle.js and libarchive.wasm.","archive.error.tooLarge":"Archive size {size} exceeds the safety limit {limit}. Download and extract it locally.","archive.loading.initializingWorker":"Initializing archive parsing Worker...","archive.loading.initializingWorkerHint":"Large files are parsed in a Worker to keep the main thread responsive.","archive.error.workerInitFailed":"Archive Worker initialization failed","archive.error.entryTooLarge":"Entry {name} is {size}, exceeding the preview limit {limit}.","archive.loading.extracting":"Extracting {name} on demand...","archive.loading.rendering":"Rendering {name}...","archive.loading.exporting":"Exporting {name}...","media.audio.title":"Audio preview","media.audio.description":"Opened with the browser-native audio player. Codec support depends on the current browser.","media.audio.unsupported":"This browser does not support audio playback.","media.video.title":"Video preview","media.video.unsupported":"This browser does not support this video format.","media.video.hlsHint":"HLS prefers the original URL for segment loading. If the input is a local single-file playlist, make sure segment URLs are reachable by the browser.","media.midi.title":"MIDI file","media.midi.loading":"Parsing MIDI tracks...","media.midi.trackHeader":"Track","media.midi.instrumentHeader":"Instrument","media.midi.channelHeader":"Channel","media.midi.noteCountHeader":"Notes","media.midi.durationHeader":"Duration","media.midi.durationStat":"Duration","media.midi.trackStat":"Tracks","media.midi.noteStat":"Notes","media.midi.parseFailed":"Failed to parse MIDI","email.mbox.subject":"{filename} · message 1","email.mbox.summary":"Detected {count} messages in the MBOX archive. Showing message 1.","email.error.title":"Email preview notice","email.meta.from":"From","email.meta.to":"To","email.meta.cc":"Cc","email.meta.date":"Date","email.tabs.text":"Body","email.tabs.headers":"Headers","email.attachments.title":"Attachments","email.attachments.empty":"No attachments","email.attachments.download":"Download attachment","email.attachments.opening":"Opening attachment {name}...","email.attachments.nestedUnavailable":"Nested attachment preview is not available in this environment. Download {name} to inspect it.","email.loading.parsing":"Parsing email...","data.font.sample":"Flyfish Viewer preview AaBbCc 1234567890","data.error.fontFaceUnsupported":"This browser does not support the FontFace API","data.title.font":"Font file preview","data.title.sqlite":"SQLite database preview","data.title.parquet":"Parquet columnar data preview","data.title.avro":"Avro object container preview","data.title.wasm":"WebAssembly module preview","data.title.eps":"EPS vector file summary","data.title.ai":"Illustrator file summary","data.title.webarchive":"WebArchive summary preview","data.title.summary":"Data asset summary","data.label.format":"Format","data.label.size":"Size","data.label.rendering":"Renderer","data.label.objects":"Objects","data.label.sampleTable":"Sample table","data.label.rows":"Rows","data.label.columns":"Columns","data.label.sampleRows":"Sample rows","data.label.imports":"Imports","data.label.exports":"Exports","data.label.magic":"Magic","data.label.note":"Note","data.label.container":"Container","data.value.schemaRead":"Read","data.value.schemaUnread":"Not read","data.note.aiSummary":"Non PDF-compatible AI is shown as a safe summary.","data.note.postscriptSummary":"PostScript summary preview","data.note.webarchive":"Readable fragments are extracted safely. Web scripts are not executed.","data.image.alt":"Asset preview","psd.title":"PSD layer preview","psd.action.fit":"Fit","psd.action.showAll":"Show all","psd.action.hideAll":"Hide all","psd.layers.title":"Layers","psd.layers.redrawable":"{count} redrawable","psd.layers.empty":"No displayable layers were found. Showing the composite image.","psd.layers.hidden":"hidden","drawing.error.viewerLoadFailed":"Failed to load the diagrams.net viewer","drawing.error.excalidrawEmpty":"This Excalidraw file has no previewable elements","drawing.error.excalidrawTimeout":"Official Excalidraw export timed out. Falling back to the rough.js renderer.","drawing.error.drawioParseFailed":"Failed to parse Draw.io XML: {message}","drawing.error.drawioNoModel":"This Draw.io file has no directly renderable mxGraphModel.","drawing.error.drawioNoElements":"This Draw.io file has no previewable elements.","drawing.error.viewerInitFailed":"The diagrams.net viewer was not initialized correctly","drawing.error.drawioTimeout":"Official diagrams.net Viewer timed out. Falling back to the local SVG preview.","drawing.error.svgParseFailed":"Failed to parse SVG","drawing.error.plantumlRenderFailed":"Failed to render PlantUML SVG: {status}","drawing.title.excalidraw":"Official Excalidraw SVG preview","drawing.title.mermaid":"Mermaid SVG preview","drawing.title.plantuml":"PlantUML SVG preview","drawing.title.drawio":"Draw.io offline SVG preview","drawing.toolbar.zoomOut":"Zoom out","drawing.toolbar.zoomIn":"Zoom in","drawing.toolbar.fit":"Fit","drawing.toolbar.fitWidth":"Fit width","drawing.state.loading":"Loading drawing preview...","text.code.loadingHighlight":"Loading syntax highlighting...","ebook.toc":"Table of contents","ebook.reading":"Reading","ebook.itemCount":"{count} items","epub.title":"EPUB ebook","epub.previousPage":"Previous","epub.nextPage":"Next","epub.loading":"Parsing EPUB...","epub.chapterFallback":"Chapter {index}","epub.renderIncomplete":"EPUB content did not finish rendering. Refresh and try again.","umd.title":"UMD ebook","umd.previousChapter":"Previous chapter","umd.nextChapter":"Next chapter","umd.loading":"Parsing UMD...","umd.emptyContent":"No readable body content was parsed.","umd.chapterFallback":"Chapter {index}","umd.galleryFallback":"Gallery {index}","umd.warningBodyTooShort":"The UMD body is shorter than declared and may be incomplete.","umd.error.unexpectedEnd":"The UMD structure is incomplete and ended unexpectedly.","umd.error.invalidFile":"This is not a valid UMD ebook file.","typst.summaryRenderer":"Typst WASM renderer","typst.pageSummary.empty":"0 pages","typst.pageSummary.ready":"{count} pages / {width} x {height} pt","typst.status.compiling":"Compiling","typst.status.failed":"Compilation failed","typst.status.rendered":"Rendered","typst.loading.title":"Parsing Typst","typst.loading.hint":"Loading the compiler and generating page previews...","typst.error.title":"Typst render failed","typst.error.timeout":"Typst WASM / font loading or compilation exceeded {seconds} seconds","typst.error.timeoutHint":"Check the download speed and cache strategy for the Typst compiler WASM, renderer WASM, and font directory. On weak networks or cross-region deployments, increase options.typst.renderTimeoutMs.","typst.error.assetHint":"Typst requires local compiler / renderer WASM files and a font directory. Run file-viewer-copy-assets, or configure options.typst.compilerWasmUrl / options.typst.rendererWasmUrl / options.typst.fontAssetsUrl, and make sure the server returns WASM with application/wasm.","typst.error.svgParseFailed":"Failed to parse Typst SVG","typst.error.wasmLoadFailed":"Failed to load Typst WASM","xmind.toolbar.zoomOut":"Zoom out","xmind.toolbar.zoomIn":"Zoom in","xmind.toolbar.fit":"Fit","xmind.toolbar.fitTitle":"Fit canvas","xmind.state.loading":"Parsing XMind mind map...","xmind.stats.nodes":"Nodes","xmind.stats.depth":"Depth","xmind.stats.theme":"Theme","xmind.stats.template":"Template","xmind.badge.paused":"Paused","xmind.badge.collapsed":"Collapsed","xmind.badge.floating":"Floating","xmind.badge.summary":"Summary","xmind.badge.callout":"Callout","xmind.imageResource":"Image resource: {name}","xmind.error.unrecognized":"Unrecognized XMind file: content.json or content.xml was not found in the ZIP package.","xmind.error.noCanvas":"This XMind file has no previewable canvas.","cad.toolbar.fit":"Fit","cad.toolbar.zoomOut":"Zoom out","cad.toolbar.zoomIn":"Zoom in","cad.layers.title":"Layers","cad.layers.count":"{count} items","cad.inspector.title":"Structure","cad.inspector.entities":"Entities","cad.inspector.blocks":"Blocks","cad.inspector.pages":"Pages","cad.inspector.drawn":"Drawn","cad.state.loadingViewer":"Loading CAD viewer...","cad.state.parsing":"Parsing CAD...","cad.error.parseFailed":"Failed to parse CAD file","image.alt":"Image","image.lightbox.alt":"Image preview","image.lightbox.close":"Close image preview","gitBundle.error.invalid":"This file is not a valid Git bundle.","gitBundle.error.missingPack":"No PACK data was found after the Git bundle header.","gitBundle.notice.delta":"This bundle contains delta-compressed objects. The viewer resolves common OFS_DELTA / REF_DELTA objects in the browser. Missing files usually indicate a very large bundle, too many objects, or an external prerequisite.","gitBundle.title.history":"History","gitBundle.title.fileTree":"File tree","gitBundle.file.choose":"Select a file to inspect","gitBundle.file.noTree":"The tree/blob objects in this bundle may be delta-compressed, and no expandable files were parsed.","gitBundle.file.none":"No files parsed","gitBundle.history.empty":"No commit objects were parsed. Showing refs and pack summary only.","gitBundle.toolbar.summary":"{commits} commits · {files} files","gitBundle.meta.bundle":"Bundle","gitBundle.meta.refs":"Refs","gitBundle.meta.commits":"Commits","gitBundle.meta.objects":"Objects","gitBundle.meta.deltas":"Deltas","gitBundle.meta.objectFormat":"Object format","gitBundle.meta.objectTypes":"Object types","geo.error.unrecognized":"Unrecognized GeoJSON data","geo.error.xmlParseFailed":"Failed to parse XML","geo.error.unsupported":".{type} geospatial format is not supported","geo.title":"Geospatial preview","geo.featureCount":"Features","geo.bounds":"Bounds","geo.geometryTypes":"Geometry types","geo.aria":"Geospatial SVG preview","geo.loading":"Parsing geospatial data...","model.toolbar.fit":"Fit","model.toolbar.rotate":"Rotate","model.toolbar.wireframe":"Wireframe","model.toolbar.grid":"Grid","model.toolbar.axes":"Axes","model.state.loadingSummary":"Loading model","model.state.loading":"Parsing 3D model...","model.state.loaded":"Model loaded","model.state.parseFailed":"Failed to parse model","model.summary.meshes":"{count} meshes","model.summary.points":"{count} point clouds","model.error.daeEmpty":"The DAE model did not contain a valid scene.","model.error.unsupported":".{type} model format is not supported yet","model.error.parseFailed":"Failed to parse {type} model","model.notice.signature":"Detected file signature: {signature}.","loading.generic.label":"File content","loading.generic.hint":"Preparing content structure and preview.","loading.word.label":"Word document","loading.word.hint":"Preparing document structure, text styles, and layout.","loading.wordWorker.hint":"Preparing document structure, text styles, and layout in a Worker.","loading.sheet.label":"Excel workbook","loading.sheet.hint":"Preparing worksheets, styles, and viewport data.","loading.csv.label":"Tabular data","loading.csv.hint":"Preparing rows, columns, and basic styling.","loading.presentation.label":"PowerPoint deck","loading.presentation.hint":"Building slide layout and media content.","loading.pdf.label":"PDF document","loading.pdf.hint":"Loading page bitmaps, text layers, and zoom view.","loading.ofd.label":"OFD layout document","loading.ofd.hint":"Parsing OFD pages and layout objects.","loading.archive.label":"Archive","loading.archive.hint":"Starting Worker and reading archive entries.","loading.email.label":"Email file","loading.email.hint":"Parsing message headers, body, and attachments.","loading.msg.hint":"Parsing Outlook message and attachments.","loading.eda.label":"EDA file","loading.eda.hint":"Reading EDA container structure and properties.","loading.cad.label":"CAD drawing","loading.cad.hint":"Preparing CAD layers, geometry, and canvas view.","loading.dwg.hint":"Loading DWG geometry and LibreDWG WASM in a Worker.","loading.dwf.hint":"Loading native DWF renderer and W2D/W3D graphics.","loading.dwfx.hint":"Loading native DWFx/XPS renderer and page graphics.","loading.xps.hint":"Loading native XPS renderer and embedded fonts.","loading.drawio.label":"draw.io diagram","loading.drawio.hint":"Parsing shapes, connectors, and SVG preview.","loading.excalidraw.label":"Excalidraw scene","loading.excalidraw.hint":"Parsing hand-drawn elements and generating safe SVG.","loading.epub.label":"EPUB ebook","loading.epub.hint":"Parsing table of contents, chapter resources, and reading pages.","loading.umd.label":"UMD ebook","loading.umd.hint":"Parsing mobile ebook metadata, table of contents, and compressed chapters.","loading.image.label":"Image file","loading.image.hint":"Decoding pixels and generating preview.","loading.video.label":"Video file","loading.video.hint":"Preparing media resource and player.","loading.audio.label":"Audio file","loading.audio.hint":"Preparing audio resource and playback controls."},Ls=Object.freeze({"zh-CN":Bn,"en-US":$n}),Gn=()=>{var e;if(!(typeof navigator>"u"))return((e=navigator.languages)===null||e===void 0?void 0:e[0])||navigator.language},Vn=e=>{const t=!e||e==="auto"?Gn():e;return String(t||"zh-CN").toLowerCase().startsWith("zh")?"zh-CN":"en-US"},Kn=e=>{var t;return((t=e?.i18n)===null||t===void 0?void 0:t.messages)||e?.messages},Rs=e=>{var t;return Vn(((t=e?.i18n)===null||t===void 0?void 0:t.locale)||e?.locale)},Hn=(e,t={})=>e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(i,s)=>{const r=t[s];return r==null?"":String(r)}),et=(e,t,i={})=>{const s=Rs(e),r=Kn(e);return Hn((typeof r=="function"?r(t,i,s):r?.[t])||Ls[s][t]||Ls["zh-CN"][t],i)},mi=e=>(t,i)=>et(e,t,i)})),Ds=ee((()=>{Et()})),Wn,pi,yi=ee((()=>{nt(),gi(),Wn=e=>({...e,extensions:e.extensions.map(ke)}),pi=(e=je)=>{const t=new Map,i=new Map,s=r=>{const n=Wn(r),a=t.get(n.id);a&&a.extensions.forEach(o=>{var l;((l=i.get(o))===null||l===void 0?void 0:l.id)===a.id&&i.delete(o)}),t.set(n.id,n),n.extensions.forEach(o=>{const l=i.get(o);if(l&&l.id!==n.id)throw new Error(`File extension "${o}" is already registered by renderer "${l.id}".`);i.set(o,n)})};return e.forEach(s),{register:s,unregister(r){const n=t.get(r);return n?(n.extensions.forEach(a=>{var o;((o=i.get(a))===null||o===void 0?void 0:o.id)===r&&i.delete(a)}),t.delete(r),!0):!1},getById(r){return t.get(r)},getByExtension(r){return i.get(ke(r))},hasExtension(r){return i.has(ke(r))},list(){return Array.from(t.values())},listExtensions(){return Array.from(i.keys()).sort()}}}})),ws,Ps=ee((()=>{nt(),yi(),gi(),ws=({registry:e=pi(je),handlers:t,fallbackHandler:i,fallbackKey:s="error"})=>{const r=Array.from(t).reduce((l,d)=>(l.set(d.rendererId,d.handler),l),new Map),n=new Map,a=[];e.list().forEach(l=>{const d=r.get(l.id);if(!d){a.push(l.id);return}l.extensions.forEach(c=>{n.set(ke(c),d)})}),i&&s&&n.set(ke(s),i);const o=l=>n.get(ke(l));return{handlersByRendererId:r,handlersByExtension:n,missingRendererIds:a,get:o,resolve(l){return o(l)||(s?o(s):void 0)},has(l){return n.has(ke(l))},listExtensions(){return Array.from(n.keys()).sort()}}}})),dh,ch,hh,_s=ee((()=>{nt(),dh=Object.freeze({download:!1,print:!1,exportHtml:!1,zoom:!1,zoomIn:!1,zoomOut:!1,zoomReset:!1}),ch=["pptx","pptm","potx","potm","ppsx","ppsm","ofd","dxf","dwg","dwf","dwfx","xps","excalidraw","drawio","dio","mermaid","mmd","plantuml","puml","umd","md","markdown","olb","dra",...Ss,...bs],hh=["xlsx","xltx","xlsm","xlsb","xls","xlt","xltm","csv","ods","fods","numbers",...Es,"eml","msg","epub","mp4","mp3","mpeg","wav","ogg","oga","opus","m4a","aac","flac","weba",...Ts]})),Ft=ee((()=>{_s(),Et(),Ds()})),uh,ks,jn,Yn,zn,qn,Xn,Qn,Zn,Cs,Jn,vi=ee((()=>{gi(),nt(),Et(),uh=Object.freeze({downloading:"正在下载文件资源...",streamingPdf:"正在建立 PDF 流式预览...",reading:"正在解析文件内容..."}),ks=Object.freeze({accent:"#5f6f82",soft:"rgba(95, 111, 130, 0.12)",badge:"DOC",label:"文件内容",hint:"正在整理内容结构并生成预览。"}),jn=e=>{const t=ke(e);return t?`.${t}`:"当前"},Yn={"office-word-openxml":"@file-viewer/renderer-word","office-word-binary":"@file-viewer/renderer-word","office-presentation":"@file-viewer/renderer-presentation","open-document":"@file-viewer/renderer-word","spreadsheet-openxml":"@file-viewer/renderer-spreadsheet",pdf:"@file-viewer/renderer-pdf",ofd:"@file-viewer/renderer-ofd",typst:"@file-viewer/renderer-typst",archive:"@file-viewer/renderer-archive",email:"@file-viewer/renderer-email",eda:"@file-viewer/renderer-eda",cad:"@file-viewer/renderer-cad",model:"@file-viewer/renderer-3d",geo:"@file-viewer/renderer-geo",drawing:"@file-viewer/renderer-drawing",mindmap:"@file-viewer/renderer-mindmap",epub:"@file-viewer/renderer-epub",umd:"@file-viewer/renderer-epub",image:"@file-viewer/renderer-image",markdown:"@file-viewer/renderer-text",code:"@file-viewer/renderer-text",video:"@file-viewer/renderer-media",audio:"@file-viewer/renderer-media","data-asset":"@file-viewer/renderer-data"},zn=new Set(["office-word-openxml","office-word-binary","office-presentation","open-document","spreadsheet-openxml","pdf","ofd"]),qn=new Set(["image","markdown","code","video","audio"]),Xn=new Set(["typst","archive","eda","cad","model","geo","drawing","mindmap","data-asset"]),Qn=e=>zn.has(e.id)?{packageName:"@file-viewer/preset-office",vitePreset:"office",label:"Office preset"}:Xn.has(e.id)?{packageName:"@file-viewer/preset-engineering",vitePreset:"engineering",label:"Engineering preset"}:qn.has(e.id)?{packageName:"@file-viewer/preset-lite",vitePreset:"lite",label:"Lite preset"}:{packageName:"@file-viewer/preset-all",vitePreset:"all",label:"Full preset"},Zn=(e="")=>{const t=ke(e),i=je.find(r=>r.extensions.map(ke).includes(t));if(!i)return null;const s=Qn(i);return{extension:t,rendererId:i.id,rendererLabel:i.label,rendererCategory:i.category,rendererPackage:Yn[i.id],presetPackage:s.packageName,vitePreset:s.vitePreset,presetLabel:s.label}},Cs=({state:e,extension:t="",title:i,message:s,description:r,theme:n=ks,recoverable:a})=>({state:e,extension:ke(t),title:i,message:s,description:r,theme:n,recoverable:a}),Jn=(e="",t=ks,i)=>{const s=jn(e),r=Zn(e);if(r){const n=Rs(i),a=r.rendererPackage?n==="zh-CN"?`;如果需要极致裁剪,也可以只安装 ${r.rendererPackage}`:`; for a strict custom cut, install only ${r.rendererPackage}`:"";return Cs({state:"unsupported",extension:e,title:et(i,"state.unsupported.install.title"),message:et(i,"state.unsupported.install.message",{extension:s,rendererLabel:r.rendererLabel}),description:et(i,"state.unsupported.install.description",{extension:s,rendererLabel:r.rendererLabel,presetPackage:r.presetPackage,vitePreset:r.vitePreset,rendererTip:a}),theme:t,recoverable:!0})}return Cs({state:"unsupported",extension:e,title:et(i,"state.unsupported.title"),message:et(i,"state.unsupported.message",{extension:s}),description:et(i,"state.unsupported.description"),theme:t,recoverable:!0})}})),Ei=ee((()=>{Ft(),vi(),Et()})),ea,xs,ta,ia,sa,Ms=ee((()=>{nt(),Ps(),yi(),Ei(),ea=(e,t)=>({rendered:e,destroy:()=>t?t():xs(e)}),xs=e=>{if(!e||typeof e!="object")return;const t=e;if(typeof t.unmount=="function")return t.unmount();if(typeof t.$destroy=="function")return t.$destroy();if(typeof t.destroy=="function")return t.destroy()},ta=({source:e,options:t,registerExportAdapter:i,renderContext:s})=>({filename:e.filename,url:e.url,streamUrl:e.url,options:t,registerExportAdapter:i,...s}),ia=({handler:e,getTarget:t=r=>r.surface.container,createContext:i=ta,destroy:s})=>async r=>{const{source:n}=r;if(!n.buffer)throw new Error("FileRenderHandler renderer requires an ArrayBuffer source.");const a=t(r),o=await e(n.buffer,a,n.extension,i(r));return ea(o,()=>s?s(o,r):xs(o))},sa=({definitions:e=je,handlers:t,getTarget:i,createContext:s,destroy:r})=>{const n=pi(e),a=ws({registry:n,handlers:t});return{registry:pi(n.list().map(o=>{const l=a.handlersByRendererId.get(o.id);return l?{...o,load:ia({handler:l,getTarget:i,createContext:s,destroy:r})}:o})),dispatcher:a,missingRendererIds:a.missingRendererIds}}})),fh=Mt({default:()=>gh});async function gh(e,t,i){const s=await da(e,i);let r=1,n=0;const a=Un(),o=document.createElement("div");o.className="image-viewer",o.dataset.viewerZoomProvider="image";const l=document.createElement("div");l.className="image-stage";const d=document.createElement("img");d.alt="图片",d.src=s,l.append(d),o.append(l);const c=ha(s),h=()=>c.open();d.addEventListener("click",h),document.body.append(c.element);const u=()=>{n=o.clientHeight||0,Os(d,n,r),a.emit()},f=new ResizeObserver(u);f.observe(o);const m=()=>({scale:r,label:`${Math.round(r*100)}%`,canZoomIn:r<5,canZoomOut:r>.1,canReset:r!==1,minScale:.1,maxScale:5}),g=y=>(r=ca(y),Os(d,n,r),a.emit(),m());return Mn(o,{zoomIn:()=>g(r+.15),zoomOut:()=>g(r-.15),resetZoom:()=>g(1),setZoom:g,getState:m,subscribe:a.subscribe}),t.replaceChildren(aa(),o),u(),{$el:t,unmount(){On(o),f.disconnect(),d.removeEventListener("click",h),c.destroy(),t.replaceChildren()}}}var ra,na,aa,oa,la,da,ca,Os,ha,mh=ee((()=>{Ot(),As(),ra={avif:"image/avif",bmp:"image/bmp",gif:"image/gif",heic:"image/heic",heif:"image/heif",ico:"image/x-icon",jxl:"image/jxl",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",svg:"image/svg+xml",tif:"image/tiff",tiff:"image/tiff",webp:"image/webp"},na=`
|
|
2
2
|
.image-viewer{position:relative;width:100%;height:100%;overflow:auto;background:#eef1f4;box-sizing:border-box}
|
|
3
3
|
.image-stage{min-width:100%;min-height:100%;display:flex;align-items:center;justify-content:center;padding:24px;box-sizing:border-box}
|
|
4
4
|
.image-stage img{display:block;width:auto;max-width:none;margin:0 auto;border:0;box-shadow:0 18px 48px rgba(15,23,42,.16);background:#fff;cursor:zoom-in}
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
.file-viewer[data-viewer-theme='dark'] .image-viewer{background:#101820}
|
|
10
10
|
@media (prefers-color-scheme:dark){.file-viewer[data-viewer-theme='system'] .image-viewer{background:#101820}}
|
|
11
11
|
@media (max-width:767px){.image-stage{padding:12px}.image-lightbox{padding:16px}.image-lightbox button{top:12px;right:12px}}
|
|
12
|
-
`,aa=()=>{const e=document.createElement("style");return e.textContent=na,e},oa=e=>ra[(e||"").trim().toLowerCase()]||"image/*",la=async e=>await new Promise((t,i)=>{const s=new FileReader;s.onload=r=>{var n;const a=(n=r.target)===null||n===void 0?void 0:n.result;if(typeof a=="string"){t(a);return}i(new Error("Unable to read image data URL."))},s.onerror=()=>i(s.error||new Error("Unable to read image data URL.")),s.readAsDataURL(e)}),da=async(e,t)=>{const i=(t||"").trim().toLowerCase();if(i==="heic"||i==="heif")throw new Error("HEIC/HEIF image conversion has moved out of @file-viewer/core. Install and pass @file-viewer/renderer-image, or use @file-viewer/preset-all.");return la(new Blob([e],{type:oa(i)}))},ca=e=>Math.min(5,Math.max(.1,Number(e.toFixed(2)))),Os=(e,t,i)=>{if(t>0){e.style.height=`${Math.max(1,Math.round(t*i))}px`;return}e.style.height=`${i*100}%`},ha=e=>{const t=document.createElement("div");t.className="image-lightbox",t.hidden=!0,t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true");const i=document.createElement("img");i.alt="Preview image",i.src=e;const s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Close image preview"),s.textContent="x";const r=()=>{t.hidden=!0};return s.addEventListener("click",r),i.addEventListener("click",r),t.addEventListener("click",n=>{n.target===t&&r()}),t.append(i,s),{element:t,open(){t.hidden=!1},destroy(){s.removeEventListener("click",r),i.removeEventListener("click",r),t.remove()}}}})),ua,Ti,Fs,fa,ga,ma,pa,ya,va,Si,ph,yh,vh,Ea=ee((()=>{nt(),Ms(),ws(),vi(),ua=e=>({$el:e,unmount(){}}),Ti=[{rendererId:"image",handler:async(e,t,i)=>{const{default:s}=await Promise.resolve().then(()=>(mh(),fh));return s(e,t,i)}}],Fs=["image"],fa=Ti.filter(e=>Fs.includes(e.rendererId)),ga=je.filter(e=>Fs.includes(e.id)),ma=e=>e==="none"?[]:e==="lite"?ga:je,pa=e=>e==="none"?[]:e==="lite"?fa:Ti,ya=async(e,t,i)=>{const s=Jn(i),r=document.createElement("div");r.style.textAlign="center",r.style.marginTop="80px";const n=document.createElement("div");if(n.textContent=s.message,r.appendChild(n),s.description){const a=document.createElement("div");a.textContent=s.description,r.appendChild(a)}return t.replaceChildren(r),ua(t)},va=(e={})=>{const t=e.builtinRenderers||"all",i=sa({definitions:ma(t),handlers:pa(t)});return{...i,dispatcher:Ps({registry:i.registry,handlers:Ti,fallbackHandler:ya})}},Si=va(),ph=Si.registry,yh=Si.dispatcher,vh=Si.missingRendererIds})),Eh=ee((()=>{Et()})),Th=ee((()=>{Ft(),Ei()})),Sh=ee((()=>{Ft()})),bh=ee((()=>{Nn(),As(),Ds(),_s(),Ft(),yi(),Ms(),Ea(),Ei(),vi()})),Ns=ee((()=>{th(),nt(),Fn(),Nn(),As(),Ot(),Ds(),Et(),yi(),Ea(),_s(),Ft(),Eh(),Th(),Sh(),ws(),Ms(),gi(),vi(),Ei(),bh()})),Ih=Ae(((e,t)=>{function i(a){var o=new n(a),l=o.readChunk();if(l.id!="MThd")throw"Bad MIDI file. Expected 'MHdr', got: '"+l.id+"'";for(var d=s(l.data),c=[],h=0;!o.eof()&&h<d.numTracks;h++){var u=o.readChunk();if(u.id!="MTrk")throw"Bad MIDI file. Expected 'MTrk', got: '"+u.id+"'";var f=r(u.data);c.push(f)}return{header:d,tracks:c}}function s(a){var o=new n(a),l={format:o.readUInt16(),numTracks:o.readUInt16()},d=o.readUInt16();return d&32768?(l.framesPerSecond=256-(d>>8),l.ticksPerFrame=d&255):l.ticksPerBeat=d,l}function r(a){for(var o=new n(a),l=[];!o.eof();){var d=c();l.push(d)}return l;function c(){var u={};u.deltaTime=o.readVarInt();var f=o.readUInt8();if((f&240)===240)if(f===255){u.meta=!0;var m=o.readUInt8(),g=o.readVarInt();switch(m){case 0:if(u.type="sequenceNumber",g!==2)throw"Expected length for sequenceNumber event is 2, got "+g;return u.number=o.readUInt16(),u;case 1:return u.type="text",u.text=o.readString(g),u;case 2:return u.type="copyrightNotice",u.text=o.readString(g),u;case 3:return u.type="trackName",u.text=o.readString(g),u;case 4:return u.type="instrumentName",u.text=o.readString(g),u;case 5:return u.type="lyrics",u.text=o.readString(g),u;case 6:return u.type="marker",u.text=o.readString(g),u;case 7:return u.type="cuePoint",u.text=o.readString(g),u;case 32:if(u.type="channelPrefix",g!=1)throw"Expected length for channelPrefix event is 1, got "+g;return u.channel=o.readUInt8(),u;case 33:if(u.type="portPrefix",g!=1)throw"Expected length for portPrefix event is 1, got "+g;return u.port=o.readUInt8(),u;case 47:if(u.type="endOfTrack",g!=0)throw"Expected length for endOfTrack event is 0, got "+g;return u;case 81:if(u.type="setTempo",g!=3)throw"Expected length for setTempo event is 3, got "+g;return u.microsecondsPerBeat=o.readUInt24(),u;case 84:if(u.type="smpteOffset",g!=5)throw"Expected length for smpteOffset event is 5, got "+g;var y=o.readUInt8();return u.frameRate={0:24,32:25,64:29,96:30}[y&96],u.hour=y&31,u.min=o.readUInt8(),u.sec=o.readUInt8(),u.frame=o.readUInt8(),u.subFrame=o.readUInt8(),u;case 88:if(u.type="timeSignature",g!=2&&g!=4)throw"Expected length for timeSignature event is 4 or 2, got "+g;return u.numerator=o.readUInt8(),u.denominator=1<<o.readUInt8(),g===4?(u.metronome=o.readUInt8(),u.thirtyseconds=o.readUInt8()):(u.metronome=36,u.thirtyseconds=8),u;case 89:if(u.type="keySignature",g!=2)throw"Expected length for keySignature event is 2, got "+g;return u.key=o.readInt8(),u.scale=o.readUInt8(),u;case 127:return u.type="sequencerSpecific",u.data=o.readBytes(g),u;default:return u.type="unknownMeta",u.data=o.readBytes(g),u.metatypeByte=m,u}}else if(f==240){u.type="sysEx";var g=o.readVarInt();return u.data=o.readBytes(g),u}else if(f==247){u.type="endSysEx";var g=o.readVarInt();return u.data=o.readBytes(g),u}else throw"Unrecognised MIDI event type byte: "+f;else{var v;if((f&128)===0){if(h===null)throw"Running status byte encountered before status byte";v=f,f=h,u.running=!0}else v=o.readUInt8(),h=f;var E=f>>4;switch(u.channel=f&15,E){case 8:return u.type="noteOff",u.noteNumber=v,u.velocity=o.readUInt8(),u;case 9:var T=o.readUInt8();return u.type=T===0?"noteOff":"noteOn",u.noteNumber=v,u.velocity=T,T===0&&(u.byte9=!0),u;case 10:return u.type="noteAftertouch",u.noteNumber=v,u.amount=o.readUInt8(),u;case 11:return u.type="controller",u.controllerType=v,u.value=o.readUInt8(),u;case 12:return u.type="programChange",u.programNumber=v,u;case 13:return u.type="channelAftertouch",u.amount=v,u;case 14:return u.type="pitchBend",u.value=v+(o.readUInt8()<<7)-8192,u;default:throw"Unrecognised MIDI event type: "+E}}}var h}function n(a){this.buffer=a,this.bufferLen=this.buffer.length,this.pos=0}n.prototype.eof=function(){return this.pos>=this.bufferLen},n.prototype.readUInt8=function(){var a=this.buffer[this.pos];return this.pos+=1,a},n.prototype.readInt8=function(){var a=this.readUInt8();return a&128?a-256:a},n.prototype.readUInt16=function(){var a=this.readUInt8(),o=this.readUInt8();return(a<<8)+o},n.prototype.readInt16=function(){var a=this.readUInt16();return a&32768?a-65536:a},n.prototype.readUInt24=function(){var a=this.readUInt8(),o=this.readUInt8(),l=this.readUInt8();return(a<<16)+(o<<8)+l},n.prototype.readInt24=function(){var a=this.readUInt24();return a&8388608?a-16777216:a},n.prototype.readUInt32=function(){var a=this.readUInt8(),o=this.readUInt8(),l=this.readUInt8(),d=this.readUInt8();return(a<<24)+(o<<16)+(l<<8)+d},n.prototype.readBytes=function(a){var o=this.buffer.slice(this.pos,this.pos+a);return this.pos+=a,o},n.prototype.readString=function(a){var o=this.readBytes(a);return String.fromCharCode.apply(null,o)},n.prototype.readVarInt=function(){for(var a=0;!this.eof();){var o=this.readUInt8();if(o&128)a+=o&127,a<<=7;else return a+o}return a},n.prototype.readChunk=function(){var a=this.readString(4),o=this.readUInt32();return{id:a,length:o,data:this.readBytes(o)}},t.exports=i})),Ah=Ae(((e,t)=>{function i(o,l){if(typeof o!="object")throw"Invalid MIDI data";l=l||{};var d=o.header||{},c=o.tracks||[],h,u=c.length,f=new a;for(s(f,d,u),h=0;h<u;h++)r(f,c[h],l);return f.buffer}function s(o,l,d){var c=l.format==null?1:l.format,h=128;l.timeDivision?h=l.timeDivision:l.ticksPerFrame&&l.framesPerSecond?h=-(l.framesPerSecond&255)<<8|l.ticksPerFrame&255:l.ticksPerBeat&&(h=l.ticksPerBeat&32767);var u=new a;u.writeUInt16(c),u.writeUInt16(d),u.writeUInt16(h),o.writeChunk("MThd",u.buffer)}function r(o,l,d){var c=new a,h,u=l.length,f=null;for(h=0;h<u;h++)(d.running===!1||!d.running&&!l[h].running)&&(f=null),f=n(c,l[h],f,d.useByte9ForNoteOff);o.writeChunk("MTrk",c.buffer)}function n(o,l,d,c){var h=l.type,u=l.deltaTime,f=l.text||"",m=l.data||[],g=null;switch(o.writeVarInt(u),h){case"sequenceNumber":o.writeUInt8(255),o.writeUInt8(0),o.writeVarInt(2),o.writeUInt16(l.number);break;case"text":o.writeUInt8(255),o.writeUInt8(1),o.writeVarInt(f.length),o.writeString(f);break;case"copyrightNotice":o.writeUInt8(255),o.writeUInt8(2),o.writeVarInt(f.length),o.writeString(f);break;case"trackName":o.writeUInt8(255),o.writeUInt8(3),o.writeVarInt(f.length),o.writeString(f);break;case"instrumentName":o.writeUInt8(255),o.writeUInt8(4),o.writeVarInt(f.length),o.writeString(f);break;case"lyrics":o.writeUInt8(255),o.writeUInt8(5),o.writeVarInt(f.length),o.writeString(f);break;case"marker":o.writeUInt8(255),o.writeUInt8(6),o.writeVarInt(f.length),o.writeString(f);break;case"cuePoint":o.writeUInt8(255),o.writeUInt8(7),o.writeVarInt(f.length),o.writeString(f);break;case"channelPrefix":o.writeUInt8(255),o.writeUInt8(32),o.writeVarInt(1),o.writeUInt8(l.channel);break;case"portPrefix":o.writeUInt8(255),o.writeUInt8(33),o.writeVarInt(1),o.writeUInt8(l.port);break;case"endOfTrack":o.writeUInt8(255),o.writeUInt8(47),o.writeVarInt(0);break;case"setTempo":o.writeUInt8(255),o.writeUInt8(81),o.writeVarInt(3),o.writeUInt24(l.microsecondsPerBeat);break;case"smpteOffset":o.writeUInt8(255),o.writeUInt8(84),o.writeVarInt(5);var y=l.hour&31|{24:0,25:32,29:64,30:96}[l.frameRate];o.writeUInt8(y),o.writeUInt8(l.min),o.writeUInt8(l.sec),o.writeUInt8(l.frame),o.writeUInt8(l.subFrame);break;case"timeSignature":o.writeUInt8(255),o.writeUInt8(88),o.writeVarInt(4),o.writeUInt8(l.numerator);var v=Math.floor(Math.log(l.denominator)/Math.LN2)&255;o.writeUInt8(v),o.writeUInt8(l.metronome),o.writeUInt8(l.thirtyseconds||8);break;case"keySignature":o.writeUInt8(255),o.writeUInt8(89),o.writeVarInt(2),o.writeInt8(l.key),o.writeUInt8(l.scale);break;case"sequencerSpecific":o.writeUInt8(255),o.writeUInt8(127),o.writeVarInt(m.length),o.writeBytes(m);break;case"unknownMeta":l.metatypeByte!=null&&(o.writeUInt8(255),o.writeUInt8(l.metatypeByte),o.writeVarInt(m.length),o.writeBytes(m));break;case"sysEx":o.writeUInt8(240),o.writeVarInt(m.length),o.writeBytes(m);break;case"endSysEx":o.writeUInt8(247),o.writeVarInt(m.length),o.writeBytes(m);break;case"noteOff":g=(c!==!1&&l.byte9||c&&l.velocity==0?144:128)|l.channel,g!==d&&o.writeUInt8(g),o.writeUInt8(l.noteNumber),o.writeUInt8(l.velocity);break;case"noteOn":g=144|l.channel,g!==d&&o.writeUInt8(g),o.writeUInt8(l.noteNumber),o.writeUInt8(l.velocity);break;case"noteAftertouch":g=160|l.channel,g!==d&&o.writeUInt8(g),o.writeUInt8(l.noteNumber),o.writeUInt8(l.amount);break;case"controller":g=176|l.channel,g!==d&&o.writeUInt8(g),o.writeUInt8(l.controllerType),o.writeUInt8(l.value);break;case"programChange":g=192|l.channel,g!==d&&o.writeUInt8(g),o.writeUInt8(l.programNumber);break;case"channelAftertouch":g=208|l.channel,g!==d&&o.writeUInt8(g),o.writeUInt8(l.amount);break;case"pitchBend":g=224|l.channel,g!==d&&o.writeUInt8(g);var E=8192+l.value,T=E&127,S=E>>7&127;o.writeUInt8(T),o.writeUInt8(S);break;default:throw"Unrecognized event type: "+h}return g}function a(){this.buffer=[]}a.prototype.writeUInt8=function(o){this.buffer.push(o&255)},a.prototype.writeInt8=a.prototype.writeUInt8,a.prototype.writeUInt16=function(o){var l=o>>8&255,d=o&255;this.writeUInt8(l),this.writeUInt8(d)},a.prototype.writeInt16=a.prototype.writeUInt16,a.prototype.writeUInt24=function(o){var l=o>>16&255,d=o>>8&255,c=o&255;this.writeUInt8(l),this.writeUInt8(d),this.writeUInt8(c)},a.prototype.writeInt24=a.prototype.writeUInt24,a.prototype.writeUInt32=function(o){var l=o>>24&255,d=o>>16&255,c=o>>8&255,h=o&255;this.writeUInt8(l),this.writeUInt8(d),this.writeUInt8(c),this.writeUInt8(h)},a.prototype.writeInt32=a.prototype.writeUInt32,a.prototype.writeBytes=function(o){this.buffer=this.buffer.concat(Array.prototype.slice.call(o,0))},a.prototype.writeString=function(o){var l,d=o.length,c=[];for(l=0;l<d;l++)c.push(o.codePointAt(l));this.writeBytes(c)},a.prototype.writeVarInt=function(o){if(o<0)throw"Cannot write negative variable-length integer";if(o<=127)this.writeUInt8(o);else{var l=o,d=[];for(d.push(l&127),l>>=7;l;){var c=l&127|128;d.push(c),l>>=7}this.writeBytes(d.reverse())}},a.prototype.writeChunk=function(o,l){this.writeString(o),this.writeUInt32(l.length),this.writeBytes(l)},t.exports=i})),Ta=Ae((e=>{e.parseMidi=Ih(),e.writeMidi=Ah()})),Sa=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.insert=e.search=void 0;function t(s,r,n){n===void 0&&(n="ticks");var a=0,o=s.length,l=o;if(o>0&&s[o-1][n]<=r)return o-1;for(;a<l;){var d=Math.floor(a+(l-a)/2),c=s[d],h=s[d+1];if(c[n]===r){for(var u=d;u<s.length;u++)s[u][n]===r&&(d=u);return d}else{if(c[n]<r&&h[n]>r)return d;c[n]>r?l=d:c[n]<r&&(a=d+1)}}return-1}e.search=t;function i(s,r,n){if(n===void 0&&(n="ticks"),s.length){var a=t(s,r[n],n);s.splice(a+1,0,r)}else s.push(r)}e.insert=i})),Us=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Header=e.keySignatureKeys=void 0;var t=Sa(),i=new WeakMap;e.keySignatureKeys=["Cb","Gb","Db","Ab","Eb","Bb","F","C","G","D","A","E","B","F#","C#"];var s=(function(){function r(n){var a=this;if(this.tempos=[],this.timeSignatures=[],this.keySignatures=[],this.meta=[],this.name="",i.set(this,480),n){i.set(this,n.header.ticksPerBeat),n.tracks.forEach(function(l){l.forEach(function(d){d.meta&&(d.type==="timeSignature"?a.timeSignatures.push({ticks:d.absoluteTime,timeSignature:[d.numerator,d.denominator]}):d.type==="setTempo"?a.tempos.push({bpm:6e7/d.microsecondsPerBeat,ticks:d.absoluteTime}):d.type==="keySignature"&&a.keySignatures.push({key:e.keySignatureKeys[d.key+7],scale:d.scale===0?"major":"minor",ticks:d.absoluteTime}))})});var o=0;n.tracks[0].forEach(function(l){o+=l.deltaTime,l.meta&&(l.type==="trackName"?a.name=l.text:(l.type==="text"||l.type==="cuePoint"||l.type==="marker"||l.type==="lyrics")&&a.meta.push({text:l.text,ticks:o,type:l.type}))}),this.update()}}return r.prototype.update=function(){var n=this,a=0,o=0;this.tempos.sort(function(l,d){return l.ticks-d.ticks}),this.tempos.forEach(function(l,d){var c=d>0?n.tempos[d-1].bpm:n.tempos[0].bpm,h=l.ticks/n.ppq-o;l.time=60/c*h+a,a=l.time,o+=h}),this.timeSignatures.sort(function(l,d){return l.ticks-d.ticks}),this.timeSignatures.forEach(function(l,d){var c=d>0?n.timeSignatures[d-1]:n.timeSignatures[0],h=(l.ticks-c.ticks)/n.ppq/c.timeSignature[0]/(c.timeSignature[1]/4);c.measures=c.measures||0,l.measures=h+c.measures})},r.prototype.ticksToSeconds=function(n){var a=(0,t.search)(this.tempos,n);if(a!==-1){var o=this.tempos[a],l=o.time,d=(n-o.ticks)/this.ppq;return l+60/o.bpm*d}else return 60/120*(n/this.ppq)},r.prototype.ticksToMeasures=function(n){var a=(0,t.search)(this.timeSignatures,n);if(a!==-1){var o=this.timeSignatures[a],l=(n-o.ticks)/this.ppq;return o.measures+l/(o.timeSignature[0]/o.timeSignature[1])/4}else return n/this.ppq/4},Object.defineProperty(r.prototype,"ppq",{get:function(){return i.get(this)},enumerable:!1,configurable:!0}),r.prototype.secondsToTicks=function(n){var a=(0,t.search)(this.tempos,n,"time");if(a!==-1){var o=this.tempos[a],l=(n-o.time)/(60/o.bpm);return Math.round(o.ticks+l*this.ppq)}else{var d=n/.5;return Math.round(d*this.ppq)}},r.prototype.toJSON=function(){return{keySignatures:this.keySignatures,meta:this.meta,name:this.name,ppq:this.ppq,tempos:this.tempos.map(function(n){return{bpm:n.bpm,ticks:n.ticks}}),timeSignatures:this.timeSignatures}},r.prototype.fromJSON=function(n){this.name=n.name,this.tempos=n.tempos.map(function(a){return Object.assign({},a)}),this.timeSignatures=n.timeSignatures.map(function(a){return Object.assign({},a)}),this.keySignatures=n.keySignatures.map(function(a){return Object.assign({},a)}),this.meta=n.meta.map(function(a){return Object.assign({},a)}),i.set(this,n.ppq),this.update()},r.prototype.setTempo=function(n){this.tempos=[{bpm:n,ticks:0}],this.update()},r})();e.Header=s})),ba=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ControlChange=e.controlChangeIds=e.controlChangeNames=void 0,e.controlChangeNames={1:"modulationWheel",2:"breath",4:"footController",5:"portamentoTime",7:"volume",8:"balance",10:"pan",64:"sustain",65:"portamentoTime",66:"sostenuto",67:"softPedal",68:"legatoFootswitch",84:"portamentoControl"},e.controlChangeIds=Object.keys(e.controlChangeNames).reduce(function(r,n){return r[e.controlChangeNames[n]]=n,r},{});var t=new WeakMap,i=new WeakMap,s=(function(){function r(n,a){t.set(this,a),i.set(this,n.controllerType),this.ticks=n.absoluteTime,this.value=n.value}return Object.defineProperty(r.prototype,"number",{get:function(){return i.get(this)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"name",{get:function(){return e.controlChangeNames[this.number]?e.controlChangeNames[this.number]:null},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"time",{get:function(){return t.get(this).ticksToSeconds(this.ticks)},set:function(n){var a=t.get(this);this.ticks=a.secondsToTicks(n)},enumerable:!1,configurable:!0}),r.prototype.toJSON=function(){return{number:this.number,ticks:this.ticks,time:this.time,value:this.value}},r})();e.ControlChange=s})),Lh=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createControlChanges=void 0;var t=ba();function i(){return new Proxy({},{get:function(s,r){if(s[r])return s[r];if(t.controlChangeIds.hasOwnProperty(r))return s[t.controlChangeIds[r]]},set:function(s,r,n){return t.controlChangeIds.hasOwnProperty(r)?s[t.controlChangeIds[r]]=n:s[r]=n,!0}})}e.createControlChanges=i})),Rh=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PitchBend=void 0;var t=new WeakMap,i=(function(){function s(r,n){t.set(this,n),this.ticks=r.absoluteTime,this.value=r.value}return Object.defineProperty(s.prototype,"time",{get:function(){return t.get(this).ticksToSeconds(this.ticks)},set:function(r){var n=t.get(this);this.ticks=n.secondsToTicks(r)},enumerable:!1,configurable:!0}),s.prototype.toJSON=function(){return{ticks:this.ticks,time:this.time,value:this.value}},s})();e.PitchBend=i})),Dh=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DrumKitByPatchID=e.InstrumentFamilyByID=e.instrumentByPatchID=void 0,e.instrumentByPatchID=["acoustic grand piano","bright acoustic piano","electric grand piano","honky-tonk piano","electric piano 1","electric piano 2","harpsichord","clavi","celesta","glockenspiel","music box","vibraphone","marimba","xylophone","tubular bells","dulcimer","drawbar organ","percussive organ","rock organ","church organ","reed organ","accordion","harmonica","tango accordion","acoustic guitar (nylon)","acoustic guitar (steel)","electric guitar (jazz)","electric guitar (clean)","electric guitar (muted)","overdriven guitar","distortion guitar","guitar harmonics","acoustic bass","electric bass (finger)","electric bass (pick)","fretless bass","slap bass 1","slap bass 2","synth bass 1","synth bass 2","violin","viola","cello","contrabass","tremolo strings","pizzicato strings","orchestral harp","timpani","string ensemble 1","string ensemble 2","synthstrings 1","synthstrings 2","choir aahs","voice oohs","synth voice","orchestra hit","trumpet","trombone","tuba","muted trumpet","french horn","brass section","synthbrass 1","synthbrass 2","soprano sax","alto sax","tenor sax","baritone sax","oboe","english horn","bassoon","clarinet","piccolo","flute","recorder","pan flute","blown bottle","shakuhachi","whistle","ocarina","lead 1 (square)","lead 2 (sawtooth)","lead 3 (calliope)","lead 4 (chiff)","lead 5 (charang)","lead 6 (voice)","lead 7 (fifths)","lead 8 (bass + lead)","pad 1 (new age)","pad 2 (warm)","pad 3 (polysynth)","pad 4 (choir)","pad 5 (bowed)","pad 6 (metallic)","pad 7 (halo)","pad 8 (sweep)","fx 1 (rain)","fx 2 (soundtrack)","fx 3 (crystal)","fx 4 (atmosphere)","fx 5 (brightness)","fx 6 (goblins)","fx 7 (echoes)","fx 8 (sci-fi)","sitar","banjo","shamisen","koto","kalimba","bag pipe","fiddle","shanai","tinkle bell","agogo","steel drums","woodblock","taiko drum","melodic tom","synth drum","reverse cymbal","guitar fret noise","breath noise","seashore","bird tweet","telephone ring","helicopter","applause","gunshot"],e.InstrumentFamilyByID=["piano","chromatic percussion","organ","guitar","bass","strings","ensemble","brass","reed","pipe","synth lead","synth pad","synth effects","world","percussive","sound effects"],e.DrumKitByPatchID={0:"standard kit",8:"room kit",16:"power kit",24:"electronic kit",25:"tr-808 kit",32:"jazz kit",40:"brush kit",48:"orchestra kit",56:"sound fx kit"}})),Ph=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Instrument=void 0;var t=Dh(),i=new WeakMap,s=(function(){function r(n,a){if(this.number=0,i.set(this,a),this.number=0,n){var o=n.find(function(l){return l.type==="programChange"});o&&(this.number=o.programNumber)}}return Object.defineProperty(r.prototype,"name",{get:function(){return this.percussion?t.DrumKitByPatchID[this.number]:t.instrumentByPatchID[this.number]},set:function(n){var a=t.instrumentByPatchID.indexOf(n);a!==-1&&(this.number=a)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"family",{get:function(){return this.percussion?"drums":t.InstrumentFamilyByID[Math.floor(this.number/8)]},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"percussion",{get:function(){return i.get(this).channel===9},enumerable:!1,configurable:!0}),r.prototype.toJSON=function(){return{family:this.family,number:this.number,name:this.name}},r.prototype.fromJSON=function(n){this.number=n.number},r})();e.Instrument=s})),wh=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Note=void 0;function t(o){var l=Math.floor(o/12)-1;return i(o)+l.toString()}function i(o){return["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"][o%12]}function s(o){return["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"].indexOf(o)}var r=(function(){var o=/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i,l={cbb:-2,cb:-1,c:0,"c#":1,cx:2,dbb:0,db:1,d:2,"d#":3,dx:4,ebb:2,eb:3,e:4,"e#":5,ex:6,fbb:3,fb:4,f:5,"f#":6,fx:7,gbb:5,gb:6,g:7,"g#":8,gx:9,abb:7,ab:8,a:9,"a#":10,ax:11,bbb:9,bb:10,b:11,"b#":12,bx:13};return function(d){var c=o.exec(d),h=c[1],u=c[2];return l[h.toLowerCase()]+(parseInt(u,10)+1)*12}})(),n=new WeakMap,a=(function(){function o(l,d,c){n.set(this,c),this.midi=l.midi,this.velocity=l.velocity,this.noteOffVelocity=d.velocity,this.ticks=l.ticks,this.durationTicks=d.ticks-l.ticks}return Object.defineProperty(o.prototype,"name",{get:function(){return t(this.midi)},set:function(l){this.midi=r(l)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"octave",{get:function(){return Math.floor(this.midi/12)-1},set:function(l){var d=l-this.octave;this.midi+=d*12},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"pitch",{get:function(){return i(this.midi)},set:function(l){this.midi=12*(this.octave+1)+s(l)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"duration",{get:function(){var l=n.get(this);return l.ticksToSeconds(this.ticks+this.durationTicks)-l.ticksToSeconds(this.ticks)},set:function(l){var d=n.get(this).secondsToTicks(this.time+l);this.durationTicks=d-this.ticks},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"time",{get:function(){return n.get(this).ticksToSeconds(this.ticks)},set:function(l){var d=n.get(this);this.ticks=d.secondsToTicks(l)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"bars",{get:function(){return n.get(this).ticksToMeasures(this.ticks)},enumerable:!1,configurable:!0}),o.prototype.toJSON=function(){return{duration:this.duration,durationTicks:this.durationTicks,midi:this.midi,name:this.name,ticks:this.ticks,time:this.time,velocity:this.velocity}},o})();e.Note=a})),Ia=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Track=void 0;var t=Sa(),i=ba(),s=Lh(),r=Rh(),n=Ph(),a=wh(),o=new WeakMap,l=(function(){function d(c,h){var u=this;if(this.name="",this.notes=[],this.controlChanges=(0,s.createControlChanges)(),this.pitchBends=[],o.set(this,h),c){var f=c.find(function(T){return T.type==="trackName"});this.name=f?f.text:""}if(this.instrument=new n.Instrument(c,this),this.channel=0,c){for(var m=c.filter(function(T){return T.type==="noteOn"}),g=c.filter(function(T){return T.type==="noteOff"}),y=function(){var T=m.shift();v.channel=T.channel;var S=g.findIndex(function(b){return b.noteNumber===T.noteNumber&&b.absoluteTime>=T.absoluteTime});if(S!==-1){var A=g.splice(S,1)[0];v.addNote({durationTicks:A.absoluteTime-T.absoluteTime,midi:T.noteNumber,noteOffVelocity:A.velocity/127,ticks:T.absoluteTime,velocity:T.velocity/127})}},v=this;m.length;)y();c.filter(function(T){return T.type==="controller"}).forEach(function(T){u.addCC({number:T.controllerType,ticks:T.absoluteTime,value:T.value/127})}),c.filter(function(T){return T.type==="pitchBend"}).forEach(function(T){u.addPitchBend({ticks:T.absoluteTime,value:T.value/Math.pow(2,13)})});var E=c.find(function(T){return T.type==="endOfTrack"});this.endOfTrackTicks=E!==void 0?E.absoluteTime:void 0}}return d.prototype.addNote=function(c){var h=o.get(this),u=new a.Note({midi:0,ticks:0,velocity:1},{ticks:0,velocity:0},h);return Object.assign(u,c),(0,t.insert)(this.notes,u,"ticks"),this},d.prototype.addCC=function(c){var h=o.get(this),u=new i.ControlChange({controllerType:c.number},h);return delete c.number,Object.assign(u,c),Array.isArray(this.controlChanges[u.number])||(this.controlChanges[u.number]=[]),(0,t.insert)(this.controlChanges[u.number],u,"ticks"),this},d.prototype.addPitchBend=function(c){var h=o.get(this),u=new r.PitchBend({},h);return Object.assign(u,c),(0,t.insert)(this.pitchBends,u,"ticks"),this},Object.defineProperty(d.prototype,"duration",{get:function(){if(!this.notes.length)return 0;for(var c=this.notes[this.notes.length-1].time+this.notes[this.notes.length-1].duration,h=0;h<this.notes.length-1;h++){var u=this.notes[h].time+this.notes[h].duration;c<u&&(c=u)}return c},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"durationTicks",{get:function(){if(!this.notes.length)return 0;for(var c=this.notes[this.notes.length-1].ticks+this.notes[this.notes.length-1].durationTicks,h=0;h<this.notes.length-1;h++){var u=this.notes[h].ticks+this.notes[h].durationTicks;c<u&&(c=u)}return c},enumerable:!1,configurable:!0}),d.prototype.fromJSON=function(c){var h=this;this.name=c.name,this.channel=c.channel,this.instrument=new n.Instrument(void 0,this),this.instrument.fromJSON(c.instrument),c.endOfTrackTicks!==void 0&&(this.endOfTrackTicks=c.endOfTrackTicks);for(var u in c.controlChanges)c.controlChanges[u]&&c.controlChanges[u].forEach(function(f){h.addCC({number:f.number,ticks:f.ticks,value:f.value})});c.notes.forEach(function(f){h.addNote({durationTicks:f.durationTicks,midi:f.midi,ticks:f.ticks,velocity:f.velocity})})},d.prototype.toJSON=function(){for(var c={},h=0;h<127;h++)this.controlChanges.hasOwnProperty(h)&&(c[h]=this.controlChanges[h].map(function(f){return f.toJSON()}));var u={channel:this.channel,controlChanges:c,pitchBends:this.pitchBends.map(function(f){return f.toJSON()}),instrument:this.instrument.toJSON(),name:this.name,notes:this.notes.map(function(f){return f.toJSON()})};return this.endOfTrackTicks!==void 0&&(u.endOfTrackTicks=this.endOfTrackTicks),u},d})();e.Track=l})),_h=Mt({flatten:()=>kh});function kh(e){var t=[];return Aa(e,t),t}function Aa(e,t){for(var i=0;i<e.length;i++){var s=e[i];Array.isArray(s)?Aa(s,t):t.push(s)}}var Ch=ee((()=>{})),xh=Ae((e=>{var t=e&&e.__spreadArray||function(E,T,S){if(S||arguments.length===2)for(var A=0,b=T.length,I;A<b;A++)(I||!(A in T))&&(I||(I=Array.prototype.slice.call(T,0,A)),I[A]=T[A]);return E.concat(I||Array.prototype.slice.call(T))};Object.defineProperty(e,"__esModule",{value:!0}),e.encode=void 0;var i=Ta(),s=Us(),r=(Ch(),Jc(_h));function n(E,T){return[{absoluteTime:E.ticks,channel:T,deltaTime:0,noteNumber:E.midi,type:"noteOn",velocity:Math.floor(E.velocity*127)},{absoluteTime:E.ticks+E.durationTicks,channel:T,deltaTime:0,noteNumber:E.midi,type:"noteOff",velocity:Math.floor(E.noteOffVelocity*127)}]}function a(E){return(0,r.flatten)(E.notes.map(function(T){return n(T,E.channel)}))}function o(E,T){return{absoluteTime:E.ticks,channel:T,controllerType:E.number,deltaTime:0,type:"controller",value:Math.floor(E.value*127)}}function l(E){for(var T=[],S=0;S<127;S++)E.controlChanges.hasOwnProperty(S)&&E.controlChanges[S].forEach(function(A){T.push(o(A,E.channel))});return T}function d(E,T){return{absoluteTime:E.ticks,channel:T,deltaTime:0,type:"pitchBend",value:E.value}}function c(E){var T=[];return E.pitchBends.forEach(function(S){T.push(d(S,E.channel))}),T}function h(E){return{absoluteTime:0,channel:E.channel,deltaTime:0,programNumber:E.instrument.number,type:"programChange"}}function u(E){return{absoluteTime:0,deltaTime:0,meta:!0,text:E,type:"trackName"}}function f(E){return{absoluteTime:E.ticks,deltaTime:0,meta:!0,microsecondsPerBeat:Math.floor(6e7/E.bpm),type:"setTempo"}}function m(E){return{absoluteTime:E.ticks,deltaTime:0,denominator:E.timeSignature[1],meta:!0,metronome:24,numerator:E.timeSignature[0],thirtyseconds:8,type:"timeSignature"}}function g(E){var T=s.keySignatureKeys.indexOf(E.key);return{absoluteTime:E.ticks,deltaTime:0,key:T+7,meta:!0,scale:E.scale==="major"?0:1,type:"keySignature"}}function y(E){return{absoluteTime:E.ticks,deltaTime:0,meta:!0,text:E.text,type:E.type}}function v(E){var T={header:{format:1,numTracks:E.tracks.length+1,ticksPerBeat:E.header.ppq},tracks:t([t(t(t(t([{absoluteTime:0,deltaTime:0,meta:!0,text:E.header.name,type:"trackName"}],E.header.keySignatures.map(function(S){return g(S)}),!0),E.header.meta.map(function(S){return y(S)}),!0),E.header.tempos.map(function(S){return f(S)}),!0),E.header.timeSignatures.map(function(S){return m(S)}),!0)],E.tracks.map(function(S){return t(t(t([u(S.name),h(S)],a(S),!0),l(S),!0),c(S),!0)}),!0)};return T.tracks=T.tracks.map(function(S){S=S.sort(function(b,I){return b.absoluteTime-I.absoluteTime});var A=0;return S.forEach(function(b){b.deltaTime=b.absoluteTime-A,A=b.absoluteTime,delete b.absoluteTime}),S.push({deltaTime:0,meta:!0,type:"endOfTrack"}),S}),new Uint8Array((0,i.writeMidi)(T))}e.encode=v})),Mh=Ae((e=>{var t=e&&e.__awaiter||function(h,u,f,m){function g(y){return y instanceof f?y:new f(function(v){v(y)})}return new(f||(f=Promise))(function(y,v){function E(A){try{S(m.next(A))}catch(b){v(b)}}function T(A){try{S(m.throw(A))}catch(b){v(b)}}function S(A){A.done?y(A.value):g(A.value).then(E,T)}S((m=m.apply(h,u||[])).next())})},i=e&&e.__generator||function(h,u){var f={label:0,sent:function(){if(y[0]&1)throw y[1];return y[1]},trys:[],ops:[]},m,g,y,v;return v={next:E(0),throw:E(1),return:E(2)},typeof Symbol=="function"&&(v[Symbol.iterator]=function(){return this}),v;function E(S){return function(A){return T([S,A])}}function T(S){if(m)throw new TypeError("Generator is already executing.");for(;f;)try{if(m=1,g&&(y=S[0]&2?g.return:S[0]?g.throw||((y=g.return)&&y.call(g),0):g.next)&&!(y=y.call(g,S[1])).done)return y;switch(g=0,y&&(S=[S[0]&2,y.value]),S[0]){case 0:case 1:y=S;break;case 4:return f.label++,{value:S[1],done:!1};case 5:f.label++,g=S[1],S=[0];continue;case 7:S=f.ops.pop(),f.trys.pop();continue;default:if(y=f.trys,!(y=y.length>0&&y[y.length-1])&&(S[0]===6||S[0]===2)){f=0;continue}if(S[0]===3&&(!y||S[1]>y[0]&&S[1]<y[3])){f.label=S[1];break}if(S[0]===6&&f.label<y[1]){f.label=y[1],y=S;break}if(y&&f.label<y[2]){f.label=y[2],f.ops.push(S);break}y[2]&&f.ops.pop(),f.trys.pop();continue}S=u.call(h,f)}catch(A){S=[6,A],g=0}finally{m=y=0}if(S[0]&5)throw S[1];return{value:S[0]?S[1]:void 0,done:!0}}};Object.defineProperty(e,"__esModule",{value:!0}),e.Header=e.Track=e.Midi=void 0;var s=Ta(),r=Us(),n=Ia(),a=xh(),o=(function(){function h(u){var f=this,m=null;if(u){var g=u instanceof ArrayBuffer?new Uint8Array(u):u;m=(0,s.parseMidi)(g),m.tracks.forEach(function(y){var v=0;y.forEach(function(E){v+=E.deltaTime,E.absoluteTime=v})}),m.tracks=c(m.tracks)}this.header=new r.Header(m),this.tracks=[],u&&(this.tracks=m.tracks.map(function(y){return new n.Track(y,f.header)}),m.header.format===1&&this.tracks[0].duration===0&&this.tracks.shift())}return h.fromUrl=function(u){return t(this,void 0,void 0,function(){var f,m;return i(this,function(g){switch(g.label){case 0:return[4,fetch(u)];case 1:return f=g.sent(),f.ok?[4,f.arrayBuffer()]:[3,3];case 2:return m=g.sent(),[2,new h(m)];case 3:throw new Error("Could not load '".concat(u,"'"))}})})},Object.defineProperty(h.prototype,"name",{get:function(){return this.header.name},set:function(u){this.header.name=u},enumerable:!1,configurable:!0}),Object.defineProperty(h.prototype,"duration",{get:function(){var u=this.tracks.map(function(f){return f.duration});return Math.max.apply(Math,u)},enumerable:!1,configurable:!0}),Object.defineProperty(h.prototype,"durationTicks",{get:function(){var u=this.tracks.map(function(f){return f.durationTicks});return Math.max.apply(Math,u)},enumerable:!1,configurable:!0}),h.prototype.addTrack=function(){var u=new n.Track(void 0,this.header);return this.tracks.push(u),u},h.prototype.toArray=function(){return(0,a.encode)(this)},h.prototype.toJSON=function(){return{header:this.header.toJSON(),tracks:this.tracks.map(function(u){return u.toJSON()})}},h.prototype.fromJSON=function(u){var f=this;this.header=new r.Header,this.header.fromJSON(u.header),this.tracks=u.tracks.map(function(m){var g=new n.Track(void 0,f.header);return g.fromJSON(m),g})},h.prototype.clone=function(){var u=new h;return u.fromJSON(this.toJSON()),u},h})();e.Midi=o;var l=Ia();Object.defineProperty(e,"Track",{enumerable:!0,get:function(){return l.Track}});var d=Us();Object.defineProperty(e,"Header",{enumerable:!0,get:function(){return d.Header}});function c(h){for(var u=[],f=0;f<h.length;f++)for(var m=u.length,g=new Map,y=Array(16).fill(0),v=0,E=h[f];v<E.length;v++){var T=E[v],S=m,A=T.channel;if(A!==void 0){T.type==="programChange"&&(y[A]=T.programNumber);var b=y[A],I="".concat(b," ").concat(A);g.has(I)?S=g.get(I):(S=m+g.size,g.set(I,S))}u[S]||u.push([]),u[S].push(T)}return u}})),Oh=Mt({default:()=>Fh});async function Fh(e,t,i,s){const r=(i||"mp3").toLowerCase();return r==="midi"||r==="mid"?wa(e,t,s):Pa(e,t,r,s)}var La,Ra,Z,Nt,Bs,Da,$s,Pa,wa,Nh=ee((()=>{Ns(),La={aac:"audio/aac",flac:"audio/flac",m4a:"audio/mp4",mp3:"audio/mpeg",mpeg:"audio/mpeg",oga:"audio/ogg",ogg:"audio/ogg",opus:"audio/ogg; codecs=opus",wav:"audio/wav",weba:"audio/webm"},Ra=`
|
|
12
|
+
`,aa=()=>{const e=document.createElement("style");return e.textContent=na,e},oa=e=>ra[(e||"").trim().toLowerCase()]||"image/*",la=async e=>await new Promise((t,i)=>{const s=new FileReader;s.onload=r=>{var n;const a=(n=r.target)===null||n===void 0?void 0:n.result;if(typeof a=="string"){t(a);return}i(new Error("Unable to read image data URL."))},s.onerror=()=>i(s.error||new Error("Unable to read image data URL.")),s.readAsDataURL(e)}),da=async(e,t)=>{const i=(t||"").trim().toLowerCase();if(i==="heic"||i==="heif")throw new Error("HEIC/HEIF image conversion has moved out of @file-viewer/core. Install and pass @file-viewer/renderer-image, or use @file-viewer/preset-all.");return la(new Blob([e],{type:oa(i)}))},ca=e=>Math.min(5,Math.max(.1,Number(e.toFixed(2)))),Os=(e,t,i)=>{if(t>0){e.style.height=`${Math.max(1,Math.round(t*i))}px`;return}e.style.height=`${i*100}%`},ha=e=>{const t=document.createElement("div");t.className="image-lightbox",t.hidden=!0,t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true");const i=document.createElement("img");i.alt="Preview image",i.src=e;const s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Close image preview"),s.textContent="x";const r=()=>{t.hidden=!0};return s.addEventListener("click",r),i.addEventListener("click",r),t.addEventListener("click",n=>{n.target===t&&r()}),t.append(i,s),{element:t,open(){t.hidden=!1},destroy(){s.removeEventListener("click",r),i.removeEventListener("click",r),t.remove()}}}})),ua,Ti,Fs,fa,ga,ma,pa,ya,va,Si,ph,yh,vh,Ea=ee((()=>{nt(),Ms(),Ps(),vi(),ua=e=>({$el:e,unmount(){}}),Ti=[{rendererId:"image",handler:async(e,t,i)=>{const{default:s}=await Promise.resolve().then(()=>(mh(),fh));return s(e,t,i)}}],Fs=["image"],fa=Ti.filter(e=>Fs.includes(e.rendererId)),ga=je.filter(e=>Fs.includes(e.id)),ma=e=>e==="none"?[]:e==="lite"?ga:je,pa=e=>e==="none"?[]:e==="lite"?fa:Ti,ya=async(e,t,i)=>{const s=Jn(i),r=document.createElement("div");r.style.textAlign="center",r.style.marginTop="80px";const n=document.createElement("div");if(n.textContent=s.message,r.appendChild(n),s.description){const a=document.createElement("div");a.textContent=s.description,r.appendChild(a)}return t.replaceChildren(r),ua(t)},va=(e={})=>{const t=e.builtinRenderers||"all",i=sa({definitions:ma(t),handlers:pa(t)});return{...i,dispatcher:ws({registry:i.registry,handlers:Ti,fallbackHandler:ya})}},Si=va(),ph=Si.registry,yh=Si.dispatcher,vh=Si.missingRendererIds})),Eh=ee((()=>{Et()})),Th=ee((()=>{Ft(),Ei()})),Sh=ee((()=>{Ft()})),bh=ee((()=>{Nn(),As(),Ds(),_s(),Ft(),yi(),Ms(),Ea(),Ei(),vi()})),Ns=ee((()=>{th(),nt(),Fn(),Nn(),As(),Ot(),Ds(),Et(),yi(),Ea(),_s(),Ft(),Eh(),Th(),Sh(),Ps(),Ms(),gi(),vi(),Ei(),bh()})),Ih=Ae(((e,t)=>{function i(a){var o=new n(a),l=o.readChunk();if(l.id!="MThd")throw"Bad MIDI file. Expected 'MHdr', got: '"+l.id+"'";for(var d=s(l.data),c=[],h=0;!o.eof()&&h<d.numTracks;h++){var u=o.readChunk();if(u.id!="MTrk")throw"Bad MIDI file. Expected 'MTrk', got: '"+u.id+"'";var f=r(u.data);c.push(f)}return{header:d,tracks:c}}function s(a){var o=new n(a),l={format:o.readUInt16(),numTracks:o.readUInt16()},d=o.readUInt16();return d&32768?(l.framesPerSecond=256-(d>>8),l.ticksPerFrame=d&255):l.ticksPerBeat=d,l}function r(a){for(var o=new n(a),l=[];!o.eof();){var d=c();l.push(d)}return l;function c(){var u={};u.deltaTime=o.readVarInt();var f=o.readUInt8();if((f&240)===240)if(f===255){u.meta=!0;var m=o.readUInt8(),g=o.readVarInt();switch(m){case 0:if(u.type="sequenceNumber",g!==2)throw"Expected length for sequenceNumber event is 2, got "+g;return u.number=o.readUInt16(),u;case 1:return u.type="text",u.text=o.readString(g),u;case 2:return u.type="copyrightNotice",u.text=o.readString(g),u;case 3:return u.type="trackName",u.text=o.readString(g),u;case 4:return u.type="instrumentName",u.text=o.readString(g),u;case 5:return u.type="lyrics",u.text=o.readString(g),u;case 6:return u.type="marker",u.text=o.readString(g),u;case 7:return u.type="cuePoint",u.text=o.readString(g),u;case 32:if(u.type="channelPrefix",g!=1)throw"Expected length for channelPrefix event is 1, got "+g;return u.channel=o.readUInt8(),u;case 33:if(u.type="portPrefix",g!=1)throw"Expected length for portPrefix event is 1, got "+g;return u.port=o.readUInt8(),u;case 47:if(u.type="endOfTrack",g!=0)throw"Expected length for endOfTrack event is 0, got "+g;return u;case 81:if(u.type="setTempo",g!=3)throw"Expected length for setTempo event is 3, got "+g;return u.microsecondsPerBeat=o.readUInt24(),u;case 84:if(u.type="smpteOffset",g!=5)throw"Expected length for smpteOffset event is 5, got "+g;var y=o.readUInt8();return u.frameRate={0:24,32:25,64:29,96:30}[y&96],u.hour=y&31,u.min=o.readUInt8(),u.sec=o.readUInt8(),u.frame=o.readUInt8(),u.subFrame=o.readUInt8(),u;case 88:if(u.type="timeSignature",g!=2&&g!=4)throw"Expected length for timeSignature event is 4 or 2, got "+g;return u.numerator=o.readUInt8(),u.denominator=1<<o.readUInt8(),g===4?(u.metronome=o.readUInt8(),u.thirtyseconds=o.readUInt8()):(u.metronome=36,u.thirtyseconds=8),u;case 89:if(u.type="keySignature",g!=2)throw"Expected length for keySignature event is 2, got "+g;return u.key=o.readInt8(),u.scale=o.readUInt8(),u;case 127:return u.type="sequencerSpecific",u.data=o.readBytes(g),u;default:return u.type="unknownMeta",u.data=o.readBytes(g),u.metatypeByte=m,u}}else if(f==240){u.type="sysEx";var g=o.readVarInt();return u.data=o.readBytes(g),u}else if(f==247){u.type="endSysEx";var g=o.readVarInt();return u.data=o.readBytes(g),u}else throw"Unrecognised MIDI event type byte: "+f;else{var v;if((f&128)===0){if(h===null)throw"Running status byte encountered before status byte";v=f,f=h,u.running=!0}else v=o.readUInt8(),h=f;var E=f>>4;switch(u.channel=f&15,E){case 8:return u.type="noteOff",u.noteNumber=v,u.velocity=o.readUInt8(),u;case 9:var T=o.readUInt8();return u.type=T===0?"noteOff":"noteOn",u.noteNumber=v,u.velocity=T,T===0&&(u.byte9=!0),u;case 10:return u.type="noteAftertouch",u.noteNumber=v,u.amount=o.readUInt8(),u;case 11:return u.type="controller",u.controllerType=v,u.value=o.readUInt8(),u;case 12:return u.type="programChange",u.programNumber=v,u;case 13:return u.type="channelAftertouch",u.amount=v,u;case 14:return u.type="pitchBend",u.value=v+(o.readUInt8()<<7)-8192,u;default:throw"Unrecognised MIDI event type: "+E}}}var h}function n(a){this.buffer=a,this.bufferLen=this.buffer.length,this.pos=0}n.prototype.eof=function(){return this.pos>=this.bufferLen},n.prototype.readUInt8=function(){var a=this.buffer[this.pos];return this.pos+=1,a},n.prototype.readInt8=function(){var a=this.readUInt8();return a&128?a-256:a},n.prototype.readUInt16=function(){var a=this.readUInt8(),o=this.readUInt8();return(a<<8)+o},n.prototype.readInt16=function(){var a=this.readUInt16();return a&32768?a-65536:a},n.prototype.readUInt24=function(){var a=this.readUInt8(),o=this.readUInt8(),l=this.readUInt8();return(a<<16)+(o<<8)+l},n.prototype.readInt24=function(){var a=this.readUInt24();return a&8388608?a-16777216:a},n.prototype.readUInt32=function(){var a=this.readUInt8(),o=this.readUInt8(),l=this.readUInt8(),d=this.readUInt8();return(a<<24)+(o<<16)+(l<<8)+d},n.prototype.readBytes=function(a){var o=this.buffer.slice(this.pos,this.pos+a);return this.pos+=a,o},n.prototype.readString=function(a){var o=this.readBytes(a);return String.fromCharCode.apply(null,o)},n.prototype.readVarInt=function(){for(var a=0;!this.eof();){var o=this.readUInt8();if(o&128)a+=o&127,a<<=7;else return a+o}return a},n.prototype.readChunk=function(){var a=this.readString(4),o=this.readUInt32();return{id:a,length:o,data:this.readBytes(o)}},t.exports=i})),Ah=Ae(((e,t)=>{function i(o,l){if(typeof o!="object")throw"Invalid MIDI data";l=l||{};var d=o.header||{},c=o.tracks||[],h,u=c.length,f=new a;for(s(f,d,u),h=0;h<u;h++)r(f,c[h],l);return f.buffer}function s(o,l,d){var c=l.format==null?1:l.format,h=128;l.timeDivision?h=l.timeDivision:l.ticksPerFrame&&l.framesPerSecond?h=-(l.framesPerSecond&255)<<8|l.ticksPerFrame&255:l.ticksPerBeat&&(h=l.ticksPerBeat&32767);var u=new a;u.writeUInt16(c),u.writeUInt16(d),u.writeUInt16(h),o.writeChunk("MThd",u.buffer)}function r(o,l,d){var c=new a,h,u=l.length,f=null;for(h=0;h<u;h++)(d.running===!1||!d.running&&!l[h].running)&&(f=null),f=n(c,l[h],f,d.useByte9ForNoteOff);o.writeChunk("MTrk",c.buffer)}function n(o,l,d,c){var h=l.type,u=l.deltaTime,f=l.text||"",m=l.data||[],g=null;switch(o.writeVarInt(u),h){case"sequenceNumber":o.writeUInt8(255),o.writeUInt8(0),o.writeVarInt(2),o.writeUInt16(l.number);break;case"text":o.writeUInt8(255),o.writeUInt8(1),o.writeVarInt(f.length),o.writeString(f);break;case"copyrightNotice":o.writeUInt8(255),o.writeUInt8(2),o.writeVarInt(f.length),o.writeString(f);break;case"trackName":o.writeUInt8(255),o.writeUInt8(3),o.writeVarInt(f.length),o.writeString(f);break;case"instrumentName":o.writeUInt8(255),o.writeUInt8(4),o.writeVarInt(f.length),o.writeString(f);break;case"lyrics":o.writeUInt8(255),o.writeUInt8(5),o.writeVarInt(f.length),o.writeString(f);break;case"marker":o.writeUInt8(255),o.writeUInt8(6),o.writeVarInt(f.length),o.writeString(f);break;case"cuePoint":o.writeUInt8(255),o.writeUInt8(7),o.writeVarInt(f.length),o.writeString(f);break;case"channelPrefix":o.writeUInt8(255),o.writeUInt8(32),o.writeVarInt(1),o.writeUInt8(l.channel);break;case"portPrefix":o.writeUInt8(255),o.writeUInt8(33),o.writeVarInt(1),o.writeUInt8(l.port);break;case"endOfTrack":o.writeUInt8(255),o.writeUInt8(47),o.writeVarInt(0);break;case"setTempo":o.writeUInt8(255),o.writeUInt8(81),o.writeVarInt(3),o.writeUInt24(l.microsecondsPerBeat);break;case"smpteOffset":o.writeUInt8(255),o.writeUInt8(84),o.writeVarInt(5);var y=l.hour&31|{24:0,25:32,29:64,30:96}[l.frameRate];o.writeUInt8(y),o.writeUInt8(l.min),o.writeUInt8(l.sec),o.writeUInt8(l.frame),o.writeUInt8(l.subFrame);break;case"timeSignature":o.writeUInt8(255),o.writeUInt8(88),o.writeVarInt(4),o.writeUInt8(l.numerator);var v=Math.floor(Math.log(l.denominator)/Math.LN2)&255;o.writeUInt8(v),o.writeUInt8(l.metronome),o.writeUInt8(l.thirtyseconds||8);break;case"keySignature":o.writeUInt8(255),o.writeUInt8(89),o.writeVarInt(2),o.writeInt8(l.key),o.writeUInt8(l.scale);break;case"sequencerSpecific":o.writeUInt8(255),o.writeUInt8(127),o.writeVarInt(m.length),o.writeBytes(m);break;case"unknownMeta":l.metatypeByte!=null&&(o.writeUInt8(255),o.writeUInt8(l.metatypeByte),o.writeVarInt(m.length),o.writeBytes(m));break;case"sysEx":o.writeUInt8(240),o.writeVarInt(m.length),o.writeBytes(m);break;case"endSysEx":o.writeUInt8(247),o.writeVarInt(m.length),o.writeBytes(m);break;case"noteOff":g=(c!==!1&&l.byte9||c&&l.velocity==0?144:128)|l.channel,g!==d&&o.writeUInt8(g),o.writeUInt8(l.noteNumber),o.writeUInt8(l.velocity);break;case"noteOn":g=144|l.channel,g!==d&&o.writeUInt8(g),o.writeUInt8(l.noteNumber),o.writeUInt8(l.velocity);break;case"noteAftertouch":g=160|l.channel,g!==d&&o.writeUInt8(g),o.writeUInt8(l.noteNumber),o.writeUInt8(l.amount);break;case"controller":g=176|l.channel,g!==d&&o.writeUInt8(g),o.writeUInt8(l.controllerType),o.writeUInt8(l.value);break;case"programChange":g=192|l.channel,g!==d&&o.writeUInt8(g),o.writeUInt8(l.programNumber);break;case"channelAftertouch":g=208|l.channel,g!==d&&o.writeUInt8(g),o.writeUInt8(l.amount);break;case"pitchBend":g=224|l.channel,g!==d&&o.writeUInt8(g);var E=8192+l.value,T=E&127,S=E>>7&127;o.writeUInt8(T),o.writeUInt8(S);break;default:throw"Unrecognized event type: "+h}return g}function a(){this.buffer=[]}a.prototype.writeUInt8=function(o){this.buffer.push(o&255)},a.prototype.writeInt8=a.prototype.writeUInt8,a.prototype.writeUInt16=function(o){var l=o>>8&255,d=o&255;this.writeUInt8(l),this.writeUInt8(d)},a.prototype.writeInt16=a.prototype.writeUInt16,a.prototype.writeUInt24=function(o){var l=o>>16&255,d=o>>8&255,c=o&255;this.writeUInt8(l),this.writeUInt8(d),this.writeUInt8(c)},a.prototype.writeInt24=a.prototype.writeUInt24,a.prototype.writeUInt32=function(o){var l=o>>24&255,d=o>>16&255,c=o>>8&255,h=o&255;this.writeUInt8(l),this.writeUInt8(d),this.writeUInt8(c),this.writeUInt8(h)},a.prototype.writeInt32=a.prototype.writeUInt32,a.prototype.writeBytes=function(o){this.buffer=this.buffer.concat(Array.prototype.slice.call(o,0))},a.prototype.writeString=function(o){var l,d=o.length,c=[];for(l=0;l<d;l++)c.push(o.codePointAt(l));this.writeBytes(c)},a.prototype.writeVarInt=function(o){if(o<0)throw"Cannot write negative variable-length integer";if(o<=127)this.writeUInt8(o);else{var l=o,d=[];for(d.push(l&127),l>>=7;l;){var c=l&127|128;d.push(c),l>>=7}this.writeBytes(d.reverse())}},a.prototype.writeChunk=function(o,l){this.writeString(o),this.writeUInt32(l.length),this.writeBytes(l)},t.exports=i})),Ta=Ae((e=>{e.parseMidi=Ih(),e.writeMidi=Ah()})),Sa=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.insert=e.search=void 0;function t(s,r,n){n===void 0&&(n="ticks");var a=0,o=s.length,l=o;if(o>0&&s[o-1][n]<=r)return o-1;for(;a<l;){var d=Math.floor(a+(l-a)/2),c=s[d],h=s[d+1];if(c[n]===r){for(var u=d;u<s.length;u++)s[u][n]===r&&(d=u);return d}else{if(c[n]<r&&h[n]>r)return d;c[n]>r?l=d:c[n]<r&&(a=d+1)}}return-1}e.search=t;function i(s,r,n){if(n===void 0&&(n="ticks"),s.length){var a=t(s,r[n],n);s.splice(a+1,0,r)}else s.push(r)}e.insert=i})),Us=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Header=e.keySignatureKeys=void 0;var t=Sa(),i=new WeakMap;e.keySignatureKeys=["Cb","Gb","Db","Ab","Eb","Bb","F","C","G","D","A","E","B","F#","C#"];var s=(function(){function r(n){var a=this;if(this.tempos=[],this.timeSignatures=[],this.keySignatures=[],this.meta=[],this.name="",i.set(this,480),n){i.set(this,n.header.ticksPerBeat),n.tracks.forEach(function(l){l.forEach(function(d){d.meta&&(d.type==="timeSignature"?a.timeSignatures.push({ticks:d.absoluteTime,timeSignature:[d.numerator,d.denominator]}):d.type==="setTempo"?a.tempos.push({bpm:6e7/d.microsecondsPerBeat,ticks:d.absoluteTime}):d.type==="keySignature"&&a.keySignatures.push({key:e.keySignatureKeys[d.key+7],scale:d.scale===0?"major":"minor",ticks:d.absoluteTime}))})});var o=0;n.tracks[0].forEach(function(l){o+=l.deltaTime,l.meta&&(l.type==="trackName"?a.name=l.text:(l.type==="text"||l.type==="cuePoint"||l.type==="marker"||l.type==="lyrics")&&a.meta.push({text:l.text,ticks:o,type:l.type}))}),this.update()}}return r.prototype.update=function(){var n=this,a=0,o=0;this.tempos.sort(function(l,d){return l.ticks-d.ticks}),this.tempos.forEach(function(l,d){var c=d>0?n.tempos[d-1].bpm:n.tempos[0].bpm,h=l.ticks/n.ppq-o;l.time=60/c*h+a,a=l.time,o+=h}),this.timeSignatures.sort(function(l,d){return l.ticks-d.ticks}),this.timeSignatures.forEach(function(l,d){var c=d>0?n.timeSignatures[d-1]:n.timeSignatures[0],h=(l.ticks-c.ticks)/n.ppq/c.timeSignature[0]/(c.timeSignature[1]/4);c.measures=c.measures||0,l.measures=h+c.measures})},r.prototype.ticksToSeconds=function(n){var a=(0,t.search)(this.tempos,n);if(a!==-1){var o=this.tempos[a],l=o.time,d=(n-o.ticks)/this.ppq;return l+60/o.bpm*d}else return 60/120*(n/this.ppq)},r.prototype.ticksToMeasures=function(n){var a=(0,t.search)(this.timeSignatures,n);if(a!==-1){var o=this.timeSignatures[a],l=(n-o.ticks)/this.ppq;return o.measures+l/(o.timeSignature[0]/o.timeSignature[1])/4}else return n/this.ppq/4},Object.defineProperty(r.prototype,"ppq",{get:function(){return i.get(this)},enumerable:!1,configurable:!0}),r.prototype.secondsToTicks=function(n){var a=(0,t.search)(this.tempos,n,"time");if(a!==-1){var o=this.tempos[a],l=(n-o.time)/(60/o.bpm);return Math.round(o.ticks+l*this.ppq)}else{var d=n/.5;return Math.round(d*this.ppq)}},r.prototype.toJSON=function(){return{keySignatures:this.keySignatures,meta:this.meta,name:this.name,ppq:this.ppq,tempos:this.tempos.map(function(n){return{bpm:n.bpm,ticks:n.ticks}}),timeSignatures:this.timeSignatures}},r.prototype.fromJSON=function(n){this.name=n.name,this.tempos=n.tempos.map(function(a){return Object.assign({},a)}),this.timeSignatures=n.timeSignatures.map(function(a){return Object.assign({},a)}),this.keySignatures=n.keySignatures.map(function(a){return Object.assign({},a)}),this.meta=n.meta.map(function(a){return Object.assign({},a)}),i.set(this,n.ppq),this.update()},r.prototype.setTempo=function(n){this.tempos=[{bpm:n,ticks:0}],this.update()},r})();e.Header=s})),ba=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ControlChange=e.controlChangeIds=e.controlChangeNames=void 0,e.controlChangeNames={1:"modulationWheel",2:"breath",4:"footController",5:"portamentoTime",7:"volume",8:"balance",10:"pan",64:"sustain",65:"portamentoTime",66:"sostenuto",67:"softPedal",68:"legatoFootswitch",84:"portamentoControl"},e.controlChangeIds=Object.keys(e.controlChangeNames).reduce(function(r,n){return r[e.controlChangeNames[n]]=n,r},{});var t=new WeakMap,i=new WeakMap,s=(function(){function r(n,a){t.set(this,a),i.set(this,n.controllerType),this.ticks=n.absoluteTime,this.value=n.value}return Object.defineProperty(r.prototype,"number",{get:function(){return i.get(this)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"name",{get:function(){return e.controlChangeNames[this.number]?e.controlChangeNames[this.number]:null},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"time",{get:function(){return t.get(this).ticksToSeconds(this.ticks)},set:function(n){var a=t.get(this);this.ticks=a.secondsToTicks(n)},enumerable:!1,configurable:!0}),r.prototype.toJSON=function(){return{number:this.number,ticks:this.ticks,time:this.time,value:this.value}},r})();e.ControlChange=s})),Lh=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createControlChanges=void 0;var t=ba();function i(){return new Proxy({},{get:function(s,r){if(s[r])return s[r];if(t.controlChangeIds.hasOwnProperty(r))return s[t.controlChangeIds[r]]},set:function(s,r,n){return t.controlChangeIds.hasOwnProperty(r)?s[t.controlChangeIds[r]]=n:s[r]=n,!0}})}e.createControlChanges=i})),Rh=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PitchBend=void 0;var t=new WeakMap,i=(function(){function s(r,n){t.set(this,n),this.ticks=r.absoluteTime,this.value=r.value}return Object.defineProperty(s.prototype,"time",{get:function(){return t.get(this).ticksToSeconds(this.ticks)},set:function(r){var n=t.get(this);this.ticks=n.secondsToTicks(r)},enumerable:!1,configurable:!0}),s.prototype.toJSON=function(){return{ticks:this.ticks,time:this.time,value:this.value}},s})();e.PitchBend=i})),Dh=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DrumKitByPatchID=e.InstrumentFamilyByID=e.instrumentByPatchID=void 0,e.instrumentByPatchID=["acoustic grand piano","bright acoustic piano","electric grand piano","honky-tonk piano","electric piano 1","electric piano 2","harpsichord","clavi","celesta","glockenspiel","music box","vibraphone","marimba","xylophone","tubular bells","dulcimer","drawbar organ","percussive organ","rock organ","church organ","reed organ","accordion","harmonica","tango accordion","acoustic guitar (nylon)","acoustic guitar (steel)","electric guitar (jazz)","electric guitar (clean)","electric guitar (muted)","overdriven guitar","distortion guitar","guitar harmonics","acoustic bass","electric bass (finger)","electric bass (pick)","fretless bass","slap bass 1","slap bass 2","synth bass 1","synth bass 2","violin","viola","cello","contrabass","tremolo strings","pizzicato strings","orchestral harp","timpani","string ensemble 1","string ensemble 2","synthstrings 1","synthstrings 2","choir aahs","voice oohs","synth voice","orchestra hit","trumpet","trombone","tuba","muted trumpet","french horn","brass section","synthbrass 1","synthbrass 2","soprano sax","alto sax","tenor sax","baritone sax","oboe","english horn","bassoon","clarinet","piccolo","flute","recorder","pan flute","blown bottle","shakuhachi","whistle","ocarina","lead 1 (square)","lead 2 (sawtooth)","lead 3 (calliope)","lead 4 (chiff)","lead 5 (charang)","lead 6 (voice)","lead 7 (fifths)","lead 8 (bass + lead)","pad 1 (new age)","pad 2 (warm)","pad 3 (polysynth)","pad 4 (choir)","pad 5 (bowed)","pad 6 (metallic)","pad 7 (halo)","pad 8 (sweep)","fx 1 (rain)","fx 2 (soundtrack)","fx 3 (crystal)","fx 4 (atmosphere)","fx 5 (brightness)","fx 6 (goblins)","fx 7 (echoes)","fx 8 (sci-fi)","sitar","banjo","shamisen","koto","kalimba","bag pipe","fiddle","shanai","tinkle bell","agogo","steel drums","woodblock","taiko drum","melodic tom","synth drum","reverse cymbal","guitar fret noise","breath noise","seashore","bird tweet","telephone ring","helicopter","applause","gunshot"],e.InstrumentFamilyByID=["piano","chromatic percussion","organ","guitar","bass","strings","ensemble","brass","reed","pipe","synth lead","synth pad","synth effects","world","percussive","sound effects"],e.DrumKitByPatchID={0:"standard kit",8:"room kit",16:"power kit",24:"electronic kit",25:"tr-808 kit",32:"jazz kit",40:"brush kit",48:"orchestra kit",56:"sound fx kit"}})),wh=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Instrument=void 0;var t=Dh(),i=new WeakMap,s=(function(){function r(n,a){if(this.number=0,i.set(this,a),this.number=0,n){var o=n.find(function(l){return l.type==="programChange"});o&&(this.number=o.programNumber)}}return Object.defineProperty(r.prototype,"name",{get:function(){return this.percussion?t.DrumKitByPatchID[this.number]:t.instrumentByPatchID[this.number]},set:function(n){var a=t.instrumentByPatchID.indexOf(n);a!==-1&&(this.number=a)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"family",{get:function(){return this.percussion?"drums":t.InstrumentFamilyByID[Math.floor(this.number/8)]},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"percussion",{get:function(){return i.get(this).channel===9},enumerable:!1,configurable:!0}),r.prototype.toJSON=function(){return{family:this.family,number:this.number,name:this.name}},r.prototype.fromJSON=function(n){this.number=n.number},r})();e.Instrument=s})),Ph=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Note=void 0;function t(o){var l=Math.floor(o/12)-1;return i(o)+l.toString()}function i(o){return["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"][o%12]}function s(o){return["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"].indexOf(o)}var r=(function(){var o=/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i,l={cbb:-2,cb:-1,c:0,"c#":1,cx:2,dbb:0,db:1,d:2,"d#":3,dx:4,ebb:2,eb:3,e:4,"e#":5,ex:6,fbb:3,fb:4,f:5,"f#":6,fx:7,gbb:5,gb:6,g:7,"g#":8,gx:9,abb:7,ab:8,a:9,"a#":10,ax:11,bbb:9,bb:10,b:11,"b#":12,bx:13};return function(d){var c=o.exec(d),h=c[1],u=c[2];return l[h.toLowerCase()]+(parseInt(u,10)+1)*12}})(),n=new WeakMap,a=(function(){function o(l,d,c){n.set(this,c),this.midi=l.midi,this.velocity=l.velocity,this.noteOffVelocity=d.velocity,this.ticks=l.ticks,this.durationTicks=d.ticks-l.ticks}return Object.defineProperty(o.prototype,"name",{get:function(){return t(this.midi)},set:function(l){this.midi=r(l)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"octave",{get:function(){return Math.floor(this.midi/12)-1},set:function(l){var d=l-this.octave;this.midi+=d*12},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"pitch",{get:function(){return i(this.midi)},set:function(l){this.midi=12*(this.octave+1)+s(l)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"duration",{get:function(){var l=n.get(this);return l.ticksToSeconds(this.ticks+this.durationTicks)-l.ticksToSeconds(this.ticks)},set:function(l){var d=n.get(this).secondsToTicks(this.time+l);this.durationTicks=d-this.ticks},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"time",{get:function(){return n.get(this).ticksToSeconds(this.ticks)},set:function(l){var d=n.get(this);this.ticks=d.secondsToTicks(l)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"bars",{get:function(){return n.get(this).ticksToMeasures(this.ticks)},enumerable:!1,configurable:!0}),o.prototype.toJSON=function(){return{duration:this.duration,durationTicks:this.durationTicks,midi:this.midi,name:this.name,ticks:this.ticks,time:this.time,velocity:this.velocity}},o})();e.Note=a})),Ia=Ae((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Track=void 0;var t=Sa(),i=ba(),s=Lh(),r=Rh(),n=wh(),a=Ph(),o=new WeakMap,l=(function(){function d(c,h){var u=this;if(this.name="",this.notes=[],this.controlChanges=(0,s.createControlChanges)(),this.pitchBends=[],o.set(this,h),c){var f=c.find(function(T){return T.type==="trackName"});this.name=f?f.text:""}if(this.instrument=new n.Instrument(c,this),this.channel=0,c){for(var m=c.filter(function(T){return T.type==="noteOn"}),g=c.filter(function(T){return T.type==="noteOff"}),y=function(){var T=m.shift();v.channel=T.channel;var S=g.findIndex(function(b){return b.noteNumber===T.noteNumber&&b.absoluteTime>=T.absoluteTime});if(S!==-1){var A=g.splice(S,1)[0];v.addNote({durationTicks:A.absoluteTime-T.absoluteTime,midi:T.noteNumber,noteOffVelocity:A.velocity/127,ticks:T.absoluteTime,velocity:T.velocity/127})}},v=this;m.length;)y();c.filter(function(T){return T.type==="controller"}).forEach(function(T){u.addCC({number:T.controllerType,ticks:T.absoluteTime,value:T.value/127})}),c.filter(function(T){return T.type==="pitchBend"}).forEach(function(T){u.addPitchBend({ticks:T.absoluteTime,value:T.value/Math.pow(2,13)})});var E=c.find(function(T){return T.type==="endOfTrack"});this.endOfTrackTicks=E!==void 0?E.absoluteTime:void 0}}return d.prototype.addNote=function(c){var h=o.get(this),u=new a.Note({midi:0,ticks:0,velocity:1},{ticks:0,velocity:0},h);return Object.assign(u,c),(0,t.insert)(this.notes,u,"ticks"),this},d.prototype.addCC=function(c){var h=o.get(this),u=new i.ControlChange({controllerType:c.number},h);return delete c.number,Object.assign(u,c),Array.isArray(this.controlChanges[u.number])||(this.controlChanges[u.number]=[]),(0,t.insert)(this.controlChanges[u.number],u,"ticks"),this},d.prototype.addPitchBend=function(c){var h=o.get(this),u=new r.PitchBend({},h);return Object.assign(u,c),(0,t.insert)(this.pitchBends,u,"ticks"),this},Object.defineProperty(d.prototype,"duration",{get:function(){if(!this.notes.length)return 0;for(var c=this.notes[this.notes.length-1].time+this.notes[this.notes.length-1].duration,h=0;h<this.notes.length-1;h++){var u=this.notes[h].time+this.notes[h].duration;c<u&&(c=u)}return c},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"durationTicks",{get:function(){if(!this.notes.length)return 0;for(var c=this.notes[this.notes.length-1].ticks+this.notes[this.notes.length-1].durationTicks,h=0;h<this.notes.length-1;h++){var u=this.notes[h].ticks+this.notes[h].durationTicks;c<u&&(c=u)}return c},enumerable:!1,configurable:!0}),d.prototype.fromJSON=function(c){var h=this;this.name=c.name,this.channel=c.channel,this.instrument=new n.Instrument(void 0,this),this.instrument.fromJSON(c.instrument),c.endOfTrackTicks!==void 0&&(this.endOfTrackTicks=c.endOfTrackTicks);for(var u in c.controlChanges)c.controlChanges[u]&&c.controlChanges[u].forEach(function(f){h.addCC({number:f.number,ticks:f.ticks,value:f.value})});c.notes.forEach(function(f){h.addNote({durationTicks:f.durationTicks,midi:f.midi,ticks:f.ticks,velocity:f.velocity})})},d.prototype.toJSON=function(){for(var c={},h=0;h<127;h++)this.controlChanges.hasOwnProperty(h)&&(c[h]=this.controlChanges[h].map(function(f){return f.toJSON()}));var u={channel:this.channel,controlChanges:c,pitchBends:this.pitchBends.map(function(f){return f.toJSON()}),instrument:this.instrument.toJSON(),name:this.name,notes:this.notes.map(function(f){return f.toJSON()})};return this.endOfTrackTicks!==void 0&&(u.endOfTrackTicks=this.endOfTrackTicks),u},d})();e.Track=l})),_h=Mt({flatten:()=>kh});function kh(e){var t=[];return Aa(e,t),t}function Aa(e,t){for(var i=0;i<e.length;i++){var s=e[i];Array.isArray(s)?Aa(s,t):t.push(s)}}var Ch=ee((()=>{})),xh=Ae((e=>{var t=e&&e.__spreadArray||function(E,T,S){if(S||arguments.length===2)for(var A=0,b=T.length,I;A<b;A++)(I||!(A in T))&&(I||(I=Array.prototype.slice.call(T,0,A)),I[A]=T[A]);return E.concat(I||Array.prototype.slice.call(T))};Object.defineProperty(e,"__esModule",{value:!0}),e.encode=void 0;var i=Ta(),s=Us(),r=(Ch(),Jc(_h));function n(E,T){return[{absoluteTime:E.ticks,channel:T,deltaTime:0,noteNumber:E.midi,type:"noteOn",velocity:Math.floor(E.velocity*127)},{absoluteTime:E.ticks+E.durationTicks,channel:T,deltaTime:0,noteNumber:E.midi,type:"noteOff",velocity:Math.floor(E.noteOffVelocity*127)}]}function a(E){return(0,r.flatten)(E.notes.map(function(T){return n(T,E.channel)}))}function o(E,T){return{absoluteTime:E.ticks,channel:T,controllerType:E.number,deltaTime:0,type:"controller",value:Math.floor(E.value*127)}}function l(E){for(var T=[],S=0;S<127;S++)E.controlChanges.hasOwnProperty(S)&&E.controlChanges[S].forEach(function(A){T.push(o(A,E.channel))});return T}function d(E,T){return{absoluteTime:E.ticks,channel:T,deltaTime:0,type:"pitchBend",value:E.value}}function c(E){var T=[];return E.pitchBends.forEach(function(S){T.push(d(S,E.channel))}),T}function h(E){return{absoluteTime:0,channel:E.channel,deltaTime:0,programNumber:E.instrument.number,type:"programChange"}}function u(E){return{absoluteTime:0,deltaTime:0,meta:!0,text:E,type:"trackName"}}function f(E){return{absoluteTime:E.ticks,deltaTime:0,meta:!0,microsecondsPerBeat:Math.floor(6e7/E.bpm),type:"setTempo"}}function m(E){return{absoluteTime:E.ticks,deltaTime:0,denominator:E.timeSignature[1],meta:!0,metronome:24,numerator:E.timeSignature[0],thirtyseconds:8,type:"timeSignature"}}function g(E){var T=s.keySignatureKeys.indexOf(E.key);return{absoluteTime:E.ticks,deltaTime:0,key:T+7,meta:!0,scale:E.scale==="major"?0:1,type:"keySignature"}}function y(E){return{absoluteTime:E.ticks,deltaTime:0,meta:!0,text:E.text,type:E.type}}function v(E){var T={header:{format:1,numTracks:E.tracks.length+1,ticksPerBeat:E.header.ppq},tracks:t([t(t(t(t([{absoluteTime:0,deltaTime:0,meta:!0,text:E.header.name,type:"trackName"}],E.header.keySignatures.map(function(S){return g(S)}),!0),E.header.meta.map(function(S){return y(S)}),!0),E.header.tempos.map(function(S){return f(S)}),!0),E.header.timeSignatures.map(function(S){return m(S)}),!0)],E.tracks.map(function(S){return t(t(t([u(S.name),h(S)],a(S),!0),l(S),!0),c(S),!0)}),!0)};return T.tracks=T.tracks.map(function(S){S=S.sort(function(b,I){return b.absoluteTime-I.absoluteTime});var A=0;return S.forEach(function(b){b.deltaTime=b.absoluteTime-A,A=b.absoluteTime,delete b.absoluteTime}),S.push({deltaTime:0,meta:!0,type:"endOfTrack"}),S}),new Uint8Array((0,i.writeMidi)(T))}e.encode=v})),Mh=Ae((e=>{var t=e&&e.__awaiter||function(h,u,f,m){function g(y){return y instanceof f?y:new f(function(v){v(y)})}return new(f||(f=Promise))(function(y,v){function E(A){try{S(m.next(A))}catch(b){v(b)}}function T(A){try{S(m.throw(A))}catch(b){v(b)}}function S(A){A.done?y(A.value):g(A.value).then(E,T)}S((m=m.apply(h,u||[])).next())})},i=e&&e.__generator||function(h,u){var f={label:0,sent:function(){if(y[0]&1)throw y[1];return y[1]},trys:[],ops:[]},m,g,y,v;return v={next:E(0),throw:E(1),return:E(2)},typeof Symbol=="function"&&(v[Symbol.iterator]=function(){return this}),v;function E(S){return function(A){return T([S,A])}}function T(S){if(m)throw new TypeError("Generator is already executing.");for(;f;)try{if(m=1,g&&(y=S[0]&2?g.return:S[0]?g.throw||((y=g.return)&&y.call(g),0):g.next)&&!(y=y.call(g,S[1])).done)return y;switch(g=0,y&&(S=[S[0]&2,y.value]),S[0]){case 0:case 1:y=S;break;case 4:return f.label++,{value:S[1],done:!1};case 5:f.label++,g=S[1],S=[0];continue;case 7:S=f.ops.pop(),f.trys.pop();continue;default:if(y=f.trys,!(y=y.length>0&&y[y.length-1])&&(S[0]===6||S[0]===2)){f=0;continue}if(S[0]===3&&(!y||S[1]>y[0]&&S[1]<y[3])){f.label=S[1];break}if(S[0]===6&&f.label<y[1]){f.label=y[1],y=S;break}if(y&&f.label<y[2]){f.label=y[2],f.ops.push(S);break}y[2]&&f.ops.pop(),f.trys.pop();continue}S=u.call(h,f)}catch(A){S=[6,A],g=0}finally{m=y=0}if(S[0]&5)throw S[1];return{value:S[0]?S[1]:void 0,done:!0}}};Object.defineProperty(e,"__esModule",{value:!0}),e.Header=e.Track=e.Midi=void 0;var s=Ta(),r=Us(),n=Ia(),a=xh(),o=(function(){function h(u){var f=this,m=null;if(u){var g=u instanceof ArrayBuffer?new Uint8Array(u):u;m=(0,s.parseMidi)(g),m.tracks.forEach(function(y){var v=0;y.forEach(function(E){v+=E.deltaTime,E.absoluteTime=v})}),m.tracks=c(m.tracks)}this.header=new r.Header(m),this.tracks=[],u&&(this.tracks=m.tracks.map(function(y){return new n.Track(y,f.header)}),m.header.format===1&&this.tracks[0].duration===0&&this.tracks.shift())}return h.fromUrl=function(u){return t(this,void 0,void 0,function(){var f,m;return i(this,function(g){switch(g.label){case 0:return[4,fetch(u)];case 1:return f=g.sent(),f.ok?[4,f.arrayBuffer()]:[3,3];case 2:return m=g.sent(),[2,new h(m)];case 3:throw new Error("Could not load '".concat(u,"'"))}})})},Object.defineProperty(h.prototype,"name",{get:function(){return this.header.name},set:function(u){this.header.name=u},enumerable:!1,configurable:!0}),Object.defineProperty(h.prototype,"duration",{get:function(){var u=this.tracks.map(function(f){return f.duration});return Math.max.apply(Math,u)},enumerable:!1,configurable:!0}),Object.defineProperty(h.prototype,"durationTicks",{get:function(){var u=this.tracks.map(function(f){return f.durationTicks});return Math.max.apply(Math,u)},enumerable:!1,configurable:!0}),h.prototype.addTrack=function(){var u=new n.Track(void 0,this.header);return this.tracks.push(u),u},h.prototype.toArray=function(){return(0,a.encode)(this)},h.prototype.toJSON=function(){return{header:this.header.toJSON(),tracks:this.tracks.map(function(u){return u.toJSON()})}},h.prototype.fromJSON=function(u){var f=this;this.header=new r.Header,this.header.fromJSON(u.header),this.tracks=u.tracks.map(function(m){var g=new n.Track(void 0,f.header);return g.fromJSON(m),g})},h.prototype.clone=function(){var u=new h;return u.fromJSON(this.toJSON()),u},h})();e.Midi=o;var l=Ia();Object.defineProperty(e,"Track",{enumerable:!0,get:function(){return l.Track}});var d=Us();Object.defineProperty(e,"Header",{enumerable:!0,get:function(){return d.Header}});function c(h){for(var u=[],f=0;f<h.length;f++)for(var m=u.length,g=new Map,y=Array(16).fill(0),v=0,E=h[f];v<E.length;v++){var T=E[v],S=m,A=T.channel;if(A!==void 0){T.type==="programChange"&&(y[A]=T.programNumber);var b=y[A],I="".concat(b," ").concat(A);g.has(I)?S=g.get(I):(S=m+g.size,g.set(I,S))}u[S]||u.push([]),u[S].push(T)}return u}})),Oh=Mt({default:()=>Fh});async function Fh(e,t,i,s){const r=(i||"mp3").toLowerCase();return r==="midi"||r==="mid"?Pa(e,t,s):wa(e,t,r,s)}var La,Ra,Z,Nt,Bs,Da,$s,wa,Pa,Nh=ee((()=>{Ns(),La={aac:"audio/aac",flac:"audio/flac",m4a:"audio/mp4",mp3:"audio/mpeg",mpeg:"audio/mpeg",oga:"audio/ogg",ogg:"audio/ogg",opus:"audio/ogg; codecs=opus",wav:"audio/wav",weba:"audio/webm"},Ra=`
|
|
13
13
|
.fv-audio-viewer{width:100%;min-height:100%;display:flex;align-items:center;justify-content:center;padding:28px;background:linear-gradient(135deg,rgba(14,116,144,.1),transparent 34%),linear-gradient(180deg,#f5f8fb 0%,#edf2f7 100%);box-sizing:border-box}
|
|
14
14
|
.fv-audio-card{width:min(100%,640px);display:grid;grid-template-columns:86px minmax(0,1fr);gap:18px;align-items:center;padding:24px;border-radius:8px;border:1px solid rgba(15,23,42,.08);background:rgba(255,255,255,.92);box-shadow:0 20px 52px rgba(15,23,42,.13);box-sizing:border-box}
|
|
15
15
|
.fv-audio-art{position:relative;width:86px;height:86px;border-radius:8px;background:linear-gradient(135deg,#0f766e,#2dd4bf);box-shadow:inset 0 0 0 1px rgba(255,255,255,.24)}
|
|
@@ -39,17 +39,17 @@
|
|
|
39
39
|
.fv-midi-table th,.fv-midi-table td{padding:12px 16px;border-top:1px solid rgba(15,23,42,.08);text-align:left}
|
|
40
40
|
.fv-midi-table th{color:#64748b;background:#f8fafc;font-weight:700}
|
|
41
41
|
@media (max-width:700px){.fv-midi-stats{grid-template-columns:repeat(2,minmax(0,1fr))}}
|
|
42
|
-
`,Z=(e,t,i)=>{const s=document.createElement(e);return t&&(s.className=t),typeof i=="string"&&(s.textContent=i),s},Nt=e=>{if(!Number.isFinite(e)||e<=0)return"00:00";const t=Math.floor(e/60),i=Math.round(e%60);return`${String(t).padStart(2,"0")}:${String(i).padStart(2,"0")}`},Bs=()=>{const e=document.createElement("style");return e.textContent=Ra,e},Da=e=>{e.replaceChildren()},$s=(e,t)=>({$el:e,unmount(){t(),Da(e)}}),Pa=(e,t,i,s)=>{const r=mi(s?.options),n=i.trim().toLowerCase()||"mp3",a=La[n]||"audio/*",o=URL.createObjectURL(new Blob([e],{type:a})),l=Z("div","fv-audio-viewer"),d=Z("section","fv-audio-card"),c=Z("div","fv-audio-art");c.append(Z("span"),Z("i"));const h=Z("div","fv-audio-copy");h.append(Z("span","fv-audio-kicker",n.toUpperCase()||"AUDIO"),Z("strong","",r("media.audio.title")),Z("p","",r("media.audio.description")));const u=Z("span","","00:00"),f=Z("span","","--:--"),m=Z("i"),g=Z("div","fv-audio-progress");g.setAttribute("aria-hidden","true"),g.append(m);const y=Z("div","fv-audio-meter");y.append(u,g,f);const v=Z("audio","fv-audio-control");v.src=o,v.controls=!0,v.preload="metadata",v.textContent=r("media.audio.unsupported");const E=()=>{f.textContent=Number.isFinite(v.duration)&&v.duration>0?Nt(v.duration):"--:--"},T=()=>{u.textContent=Nt(v.currentTime);const S=Number.isFinite(v.duration)&&v.duration>0?Math.min(100,Math.max(0,v.currentTime/v.duration*100)):0;m.style.width=`${S}%`};return v.addEventListener("loadedmetadata",E),v.addEventListener("timeupdate",T),d.append(c,h,y,v),l.append(d),t.replaceChildren(Bs(),l),$s(t,()=>{v.pause(),v.removeEventListener("loadedmetadata",E),v.removeEventListener("timeupdate",T),URL.revokeObjectURL(o)})},wa=(e,t,i)=>{const s=mi(i?.options);let r=!1;const n=Z("div","fv-midi-viewer"),a=Z("section","fv-midi-card"),o=document.createElement("header"),l=Z("strong","",s("media.midi.title"));o.append(Z("span","","MIDI"),l);const d=Z("div","fv-midi-state",s("media.midi.loading"));a.append(o,d),n.append(a),t.replaceChildren(Bs(),n);const c=f=>{d.className="fv-midi-state fv-midi-error",d.textContent=f},h=f=>{const m=Z("div","fv-midi-table-wrap"),g=Z("table","fv-midi-table"),y=document.createElement("thead"),v=document.createElement("tr");for(const T of[s("media.midi.trackHeader"),s("media.midi.instrumentHeader"),s("media.midi.channelHeader"),s("media.midi.noteCountHeader"),s("media.midi.durationHeader")])v.append(Z("th","",T));y.append(v);const E=document.createElement("tbody");for(const T of f){const S=document.createElement("tr");S.append(Z("td","",T.name),Z("td","",T.instrument),Z("td","",String(T.channel+1)),Z("td","",String(T.notes)),Z("td","",Nt(T.duration))),E.append(S)}return g.append(y,E),m.append(g),m},u=f=>{l.textContent=f.name;const m=f.tracks.reduce((y,v)=>y+v.notes,0),g=Z("div","fv-midi-stats");for(const[y,v]of[[s("media.midi.durationStat"),Nt(f.duration)],["PPQ",String(f.ppq)],[s("media.midi.trackStat"),String(f.tracks.length)],[s("media.midi.noteStat"),String(m)]]){const E=document.createElement("div");E.append(Z("span","",y),Z("strong","",v)),g.append(E)}d.replaceWith(g,h(f.tracks))};return(async()=>{try{const{Midi:f}=await Promise.resolve().then(()=>Zc(Mh(),1)),m=new f(e);if(r)return;u({name:m.name||s("media.midi.title"),duration:m.duration,ppq:m.header.ppq,tracks:m.tracks.map((g,y)=>{var v,E;return{name:g.name||`Track ${y+1}`,instrument:((v=g.instrument)===null||v===void 0?void 0:v.name)||((E=g.instrument)===null||E===void 0?void 0:E.family)||"Unknown",channel:g.channel,notes:g.notes.length,duration:g.duration}})})}catch(f){r||c(f instanceof Error?f.message:s("media.midi.parseFailed"))}})(),$s(t,()=>{r=!0})}})),Uh=Mt({AbrController:()=>Or,AttrList:()=>oe,AudioStreamController:()=>en,AudioTrackController:()=>tn,BasePlaylistController:()=>si,BaseSegment:()=>Yi,BaseStreamController:()=>Zt,BufferController:()=>nn,CMCDController:()=>gn,CapLevelController:()=>an,ChunkMetadata:()=>Xt,ContentSteeringController:()=>mn,Cues:()=>Pn,DateRange:()=>Zi,EMEController:()=>ls,ErrorActionFlags:()=>Te,ErrorController:()=>Nr,ErrorDetails:()=>L,ErrorTypes:()=>$,Events:()=>p,FPSController:()=>pn,FetchLoader:()=>gs,Fragment:()=>zt,Hls:()=>ps,HlsSkip:()=>Dt,HlsUrlParameters:()=>Xi,KeySystemFormats:()=>fe,KeySystems:()=>ae,Level:()=>ht,LevelDetails:()=>Kr,LevelKey:()=>Pt,LoadStats:()=>Yt,M3U8Parser:()=>ft,MetadataSchema:()=>Se,NetworkErrorAction:()=>ce,Part:()=>_r,PlaylistLevelType:()=>B,SubtitleStreamController:()=>Tn,SubtitleTrackController:()=>yn,TimelineController:()=>Dn,XhrLoader:()=>ms,default:()=>ps,fetchSupported:()=>Pl,getMediaSource:()=>Ye,isMSESupported:()=>Dr,isSupported:()=>xl,requestMediaKeySystemAccess:()=>Ji});function Bh(e,t,i){return(t=Gh(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function se(){return se=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var s in i)({}).hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},se.apply(null,arguments)}function _a(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),i.push.apply(i,s)}return i}function ie(e){for(var t=1;t<arguments.length;t++){var i=arguments[t]!=null?arguments[t]:{};t%2?_a(Object(i),!0).forEach(function(s){Bh(e,s,i[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):_a(Object(i)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(i,s))})}return e}function $h(e,t){if(typeof e!="object"||!e)return e;var i=e[Symbol.toPrimitive];if(i!==void 0){var s=i.call(e,t);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Gh(e){var t=$h(e,"string");return typeof t=="symbol"?t:t+""}function Gs(){return se({},Ul)}function Vh(e,t){const i=self.console[e];return i?i.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):qe}function ka(e,t,i){return t[e]?t[e].bind(t):Vh(e,i)}function Kh(e,t,i){const s=Gs();if(typeof console=="object"&&e===!0||typeof e=="object"){const r=["debug","log","info","warn","error"];r.forEach(n=>{s[n]=ka(n,e,i)});try{s.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return Gs()}r.forEach(n=>{Hi[n]=ka(n,e)})}else se(Hi,s);return s}function Ye(e=!0){if(!(typeof self>"u"))return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Hh(e){return typeof self<"u"&&e===self.ManagedMediaSource}function Ca(e,t){const i=Object.keys(e),s=Object.keys(t),r=i.length,n=s.length;return!r||!n||r===n&&!i.some(a=>s.indexOf(a)===-1)}function De(e,t=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(e);if(t){const d=l.indexOf("\0");return d!==-1?l.substring(0,d):l}return l.replace(/\0/g,"")}const i=e.length;let s,r,n,a="",o=0;for(;o<i;){if(s=e[o++],s===0&&t)return a;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:r=e[o++],a+=String.fromCharCode((s&31)<<6|r&63);break;case 14:r=e[o++],n=e[o++],a+=String.fromCharCode((s&15)<<12|(r&63)<<6|(n&63)<<0);break}}return a}function ye(e){let t="";for(let i=0;i<e.length;i++){let s=e[i].toString(16);s.length<2&&(s="0"+s),t+=s}return t}function xa(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Wh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function jh(){return Bl||(Bl=1,(function(e,t){(function(i){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,d,c){if(c=c||{},l=l.trim(),d=d.trim(),!d){if(!c.alwaysNormalize)return l;var h=o.parseURL(l);if(!h)throw new Error("Error trying to parse base URL.");return h.path=o.normalizePath(h.path),o.buildURLFromParts(h)}var u=o.parseURL(d);if(!u)throw new Error("Error trying to parse relative URL.");if(u.scheme)return c.alwaysNormalize?(u.path=o.normalizePath(u.path),o.buildURLFromParts(u)):d;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var m=r.exec(f.path);f.netLoc=m[1],f.path=m[2]}f.netLoc&&!f.path&&(f.path="/");var g={scheme:f.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(g.netLoc=f.netLoc,u.path[0]!=="/"))if(!u.path)g.path=f.path,u.params||(g.params=f.params,u.query||(g.query=f.query));else{var y=f.path,v=y.substring(0,y.lastIndexOf("/")+1)+u.path;g.path=o.normalizePath(v)}return g.path===null&&(g.path=c.alwaysNormalize?o.normalizePath(u.path):u.path),o.buildURLFromParts(g)},parseURL:function(l){var d=s.exec(l);return d?{scheme:d[1]||"",netLoc:d[2]||"",path:d[3]||"",params:d[4]||"",query:d[5]||"",fragment:d[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};e.exports=o})()})(Wi)),Wi.exports}function de(e){return e.sn!=="initSegment"}function Ma(e,t){const i=Object.getPrototypeOf(e);if(i){const s=Object.getOwnPropertyDescriptor(i,t);return s||Ma(i,t)}}function Yh(e,t){const i=Ma(e,t);i&&(i.enumerable=!0,Object.defineProperty(e,t,i))}function ue(e){return String.fromCharCode.apply(null,e)}function Oa(e,t){const i=e[t]<<8|e[t+1];return i<0?65536+i:i}function K(e,t){const i=Na(e,t);return i<0?4294967296+i:i}function Fa(e,t){let i=K(e,t);return i*=Math.pow(2,32),i+=K(e,t+4),i}function Na(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function zh(e){const t=e.byteLength;for(let i=0;i<t;){const s=K(e,i);if(s>8&&e[i+4]===109&&e[i+5]===111&&e[i+6]===111&&e[i+7]===102)return!0;i=s>1?i+s:t}return!1}function z(e,t){const i=[];if(!t.length)return i;const s=e.byteLength;for(let r=0;r<s;){const n=K(e,r),a=ue(e.subarray(r+4,r+8)),o=n>1?r+n:s;if(a===t[0])if(t.length===1)i.push(e.subarray(r+8,o));else{const l=z(e.subarray(r+8,o),t.slice(1));l.length&&$l.apply(i,l)}r=o}return i}function qh(e){const t=[],i=e[0];let s=8;const r=K(e,s);s+=4;let n=0,a=0;i===0?(n=K(e,s),a=K(e,s+4),s+=8):(n=Fa(e,s),a=Fa(e,s+8),s+=16),s+=2;let o=e.length+a;const l=Oa(e,s);s+=2;for(let d=0;d<l;d++){let c=s;const h=K(e,c);c+=4;const u=h&2147483647;if((h&2147483648)>>>31===1)return te.warn("SIDX has hierarchical references (not supported)"),null;const f=K(e,c);c+=4,t.push({referenceSize:u,subsegmentDuration:f,info:{duration:f/r,start:o,end:o+u-1}}),o+=u,c+=4,s=c}return{earliestPresentationTime:n,timescale:r,version:i,referencesCount:l,references:t}}function Ua(e){const t=[],i=z(e,["moov","trak"]);for(let s=0;s<i.length;s++){const r=i[s],n=z(r,["tkhd"])[0];if(n){let a=n[0];const o=K(n,a===0?12:20),l=z(r,["mdia","mdhd"])[0];if(l){a=l[0];const d=K(l,a===0?12:20),c=z(r,["mdia","hdlr"])[0];if(c){const h=ue(c.subarray(8,12)),u={soun:re.AUDIO,vide:re.VIDEO}[h],f=z(r,["mdia","minf","stbl","stsd"])[0],m=Xh(f);u?(t[o]={timescale:d,type:u,stsd:m},t[u]=ie({timescale:d,id:o},m)):t[o]={timescale:d,type:h,stsd:m}}}}}return z(e,["moov","mvex","trex"]).forEach(s=>{const r=t[K(s,4)];r&&(r.default={duration:K(s,12),flags:K(s,20)})}),t}function Xh(e){const t=e.subarray(8),i=t.subarray(86),s=ue(t.subarray(4,8));let r=s,n;const a=s==="enca"||s==="encv";a&&z(z(t,[s])[0].subarray(s==="enca"?28:78),["sinf"]).forEach(l=>{const d=z(l,["schm"])[0];if(d){const c=ue(d.subarray(4,8));if(c==="cbcs"||c==="cenc"){const h=z(l,["frma"])[0];h&&(r=ue(h))}}});const o=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{const l=z(i,["avcC"])[0];l&&l.length>3&&(r+="."+Ii(l[1])+Ii(l[2])+Ii(l[3]),n=bi(o==="avc1"?"dva1":"dvav",i));break}case"mp4a":{const l=z(t,[s])[0],d=z(l.subarray(28),["esds"])[0];if(d&&d.length>7){let c=4;if(d[c++]!==3)break;c=Vs(d,c),c+=2;const h=d[c++];if(h&128&&(c+=2),h&64&&(c+=d[c++]),d[c++]!==4)break;c=Vs(d,c);const u=d[c++];if(u===64)r+="."+Ii(u);else break;if(c+=12,d[c++]!==5)break;c=Vs(d,c);const f=d[c++];let m=(f&248)>>3;m===31&&(m+=1+((f&7)<<3)+((d[c]&224)>>5)),r+="."+m}break}case"hvc1":case"hev1":{const l=z(i,["hvcC"])[0];if(l&&l.length>12){const d=l[1],c=["","A","B","C"][d>>6],h=d&31,u=K(l,2),f=(d&32)>>5?"H":"L",m=l[12],g=l.subarray(6,12);r+="."+c+h,r+="."+Qh(u).toString(16).toUpperCase(),r+="."+f+m;let y="";for(let v=g.length;v--;){const E=g[v];(E||y)&&(y="."+E.toString(16).toUpperCase()+y)}r+=y}n=bi(o=="hev1"?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":r=bi(r,i)||r;break;case"vp09":{const l=z(i,["vpcC"])[0];if(l&&l.length>6){const d=l[4],c=l[5],h=l[6]>>4&15;r+="."+Ne(d)+"."+Ne(c)+"."+Ne(h)}break}case"av01":{const l=z(i,["av1C"])[0];if(l&&l.length>2){const d=l[1]>>>5,c=l[1]&31,h=l[2]>>>7?"H":"M",u=(l[2]&64)>>6,f=(l[2]&32)>>5,m=d===2&&u?f?12:10:u?10:8,g=(l[2]&16)>>4,y=(l[2]&8)>>3,v=(l[2]&4)>>2,E=l[2]&3;r+="."+d+"."+Ne(c)+h+"."+Ne(m)+"."+g+"."+y+v+E+"."+Ne(1)+"."+Ne(1)+"."+Ne(1)+".0",n=bi("dav1",i)}break}}return{codec:r,encrypted:a,supplemental:n}}function bi(e,t){const i=z(t,["dvvC"]),s=i.length?i[0]:z(t,["dvcC"])[0];if(s){const r=s[2]>>1&127,n=s[2]<<5&32|s[3]>>3&31;return e+"."+Ne(r)+"."+Ne(n)}}function Qh(e){let t=0;for(let i=0;i<32;i++)t|=(e>>i&1)<<31-i;return t>>>0}function Vs(e,t){const i=t+5;for(;e[t++]&128&&t<i;);return t}function Ii(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Ne(e){return(e<10?"0":"")+e}function Zh(e,t){if(!e||!t)return;const i=t.keyId;i&&t.isCommonEncryption&&Ba(e,(s,r)=>{const n=s.subarray(8,24);n.some(a=>a!==0)||(te.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${ye(n)} -> ${ye(i)}`),s.set(i,8))})}function Jh(e){const t=[];return Ba(e,i=>t.push(i.subarray(8,24))),t}function Ba(e,t){z(e,["moov","trak"]).forEach(i=>{const s=z(i,["mdia","minf","stbl","stsd"])[0];if(!s)return;const r=s.subarray(8);let n=z(r,["enca"]);const a=n.length>0;a||(n=z(r,["encv"])),n.forEach(o=>{z(a?o.subarray(28):o.subarray(78),["sinf"]).forEach(l=>{const d=$a(l);d&&t(d,a)})})})}function $a(e){const t=z(e,["schm"])[0];if(t){const i=ue(t.subarray(4,8));if(i==="cbcs"||i==="cenc"){const s=z(e,["schi","tenc"])[0];if(s)return s}}}function eu(e,t,i){const s={},r=z(e,["moof","traf"]);for(let n=0;n<r.length;n++){const a=r[n],o=z(a,["tfhd"])[0],l=K(o,4),d=t[l];if(!d)continue;s[l]||(s[l]={start:NaN,duration:0,sampleCount:0,timescale:d.timescale,type:d.type});const c=s[l],h=z(a,["tfdt"])[0];if(h){const T=h[0];let S=K(h,4);T===1&&(S===kr?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=kr+1,S+=K(h,8))),N(S)&&(!N(c.start)||S<c.start)&&(c.start=S)}const u=d.default,f=K(o,0)|u?.flags;let m=u?.duration||0;f&8&&(f&2?m=K(o,12):m=K(o,8));const g=z(a,["trun"]);let y=c.start||0,v=0,E=m;for(let T=0;T<g.length;T++){const S=g[T],A=K(S,4),b=c.sampleCount;c.sampleCount+=A;const I=S[3]&1,D=S[3]&4,w=S[2]&1,P=S[2]&2,x=S[2]&4,U=S[2]&8;let O=8,V=A;for(I&&(O+=4),D&&A&&(!(S[O+1]&1)&&c.keyFrameIndex===void 0&&(c.keyFrameIndex=b),O+=4,w?(E=K(S,O),O+=4):E=m,P&&(O+=4),U&&(O+=4),y+=E,v+=E,V--);V--;)w?(E=K(S,O),O+=4):E=m,P&&(O+=4),x&&(S[O+1]&1||c.keyFrameIndex===void 0&&(c.keyFrameIndex=c.sampleCount-(V+1),c.keyFrameStart=y),O+=4),U&&(O+=4),y+=E,v+=E;!v&&m&&(v+=m*A)}c.duration+=v}if(!Object.keys(s).some(n=>s[n].duration)){let n=1/0,a=0;const o=z(e,["sidx"]);for(let l=0;l<o.length;l++){const d=qh(o[l]);if(d!=null&&d.references){n=Math.min(n,d.earliestPresentationTime/d.timescale);const c=d.references.reduce((h,u)=>h+u.info.duration||0,0);a=Math.max(a,c+d.earliestPresentationTime/d.timescale)}}a&&N(a)&&Object.keys(s).forEach(l=>{s[l].duration||(s[l].duration=a*s[l].timescale-s[l].start)})}return s}function tu(e){const t={valid:null,remainder:null},i=z(e,["moof"]);if(i.length<2)return t.remainder=e,t;const s=i[i.length-1];return t.valid=e.slice(0,s.byteOffset-8),t.remainder=e.slice(s.byteOffset-8),t}function Ce(e,t){const i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function Ga(e,t){const i=[],s=t.samples,r=t.timescale,n=t.id;let a=!1;return z(s,["moof"]).map(o=>{const l=o.byteOffset-8;z(o,["traf"]).map(d=>{const c=z(d,["tfdt"]).map(h=>{const u=h[0];let f=K(h,4);return u===1&&(f*=Math.pow(2,32),f+=K(h,8)),f/r})[0];return c!==void 0&&(e=c),z(d,["tfhd"]).map(h=>{const u=K(h,4),f=K(h,0)&16777215,m=(f&1)!==0,g=(f&2)!==0,y=(f&8)!==0;let v=0;const E=(f&16)!==0;let T=0;const S=(f&32)!==0;let A=8;u===n&&(m&&(A+=8),g&&(A+=4),y&&(v=K(h,A),A+=4),E&&(T=K(h,A),A+=4),S&&(A+=4),t.type==="video"&&(a=Ai(t.codec)),z(d,["trun"]).map(b=>{const I=b[0],D=K(b,0)&16777215,w=(D&1)!==0;let P=0;const x=(D&4)!==0,U=(D&256)!==0;let O=0;const V=(D&512)!==0;let F=0;const M=(D&1024)!==0,W=(D&2048)!==0;let k=0;const C=K(b,4);let G=8;w&&(P=K(b,G),G+=4),x&&(G+=4);let j=P+l;for(let J=0;J<C;J++){if(U?(O=K(b,G),G+=4):O=v,V?(F=K(b,G),G+=4):F=T,M&&(G+=4),W&&(I===0?k=K(b,G):k=Na(b,G),G+=4),t.type===re.VIDEO){let X=0;for(;X<F;){const Q=K(s,j);j+=4,iu(a,s[j])&&Ks(s.subarray(j,j+Q),a?2:1,e+k/r,i),j+=Q,X+=Q+4}}e+=O/r}}))})})}),i}function Ai(e){if(!e)return!1;const t=e.substring(0,4);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function iu(e,t){if(e){const i=t>>1&63;return i===39||i===40}else return(t&31)===6}function Ks(e,t,i,s){const r=Va(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(l===255);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(l===255);const d=r.length-n;let c=n;if(o<d)n+=o;else if(o>d){te.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(a===4){if(r[c++]===181){const h=Oa(r,c);if(c+=2,h===49){const u=K(r,c);if(c+=4,u===1195456820){const f=r[c++];if(f===3){const m=r[c++],g=31&m,y=64&m,v=y?2+g*3:0,E=new Uint8Array(v);if(y){E[0]=m;for(let T=1;T<v;T++)E[T]=r[c++]}s.push({type:f,payloadType:a,pts:i,bytes:E})}}}}}else if(a===5&&o>16){const h=[];for(let m=0;m<16;m++){const g=r[c++].toString(16);h.push(g.length==1?"0"+g:g),(m===3||m===5||m===7||m===9)&&h.push("-")}const u=o-16,f=new Uint8Array(u);for(let m=0;m<u;m++)f[m]=r[c++];s.push({payloadType:a,pts:i,uuid:h.join(""),userData:De(f),userDataBytes:f})}}}function Va(e){const t=e.byteLength,i=[];let s=1;for(;s<t-2;)e[s]===0&&e[s+1]===0&&e[s+2]===3?(i.push(s+2),s+=2):s++;if(i.length===0)return e;const r=t-i.length,n=new Uint8Array(r);let a=0;for(s=0;s<r;a++,s++)a===i[0]&&(a++,i.shift()),n[s]=e[a];return n}function su(e){const t=e[0];let i="",s="",r=0,n=0,a=0,o=0,l=0,d=0;if(t===0){for(;ue(e.subarray(d,d+1))!=="\0";)i+=ue(e.subarray(d,d+1)),d+=1;for(i+=ue(e.subarray(d,d+1)),d+=1;ue(e.subarray(d,d+1))!=="\0";)s+=ue(e.subarray(d,d+1)),d+=1;s+=ue(e.subarray(d,d+1)),d+=1,r=K(e,12),n=K(e,16),o=K(e,20),l=K(e,24),d=28}else if(t===1){d+=4,r=K(e,d),d+=4;const h=K(e,d);d+=4;const u=K(e,d);for(d+=4,a=2**32*h+u,Ol(a)||(a=Number.MAX_SAFE_INTEGER,te.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=K(e,d),d+=4,l=K(e,d),d+=4;ue(e.subarray(d,d+1))!=="\0";)i+=ue(e.subarray(d,d+1)),d+=1;for(i+=ue(e.subarray(d,d+1)),d+=1;ue(e.subarray(d,d+1))!=="\0";)s+=ue(e.subarray(d,d+1)),d+=1;s+=ue(e.subarray(d,d+1)),d+=1}const c=e.subarray(d,e.byteLength);return{schemeIdUri:i,value:s,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:c}}function ru(e,...t){const i=t.length;let s=8,r=i;for(;r--;)s+=t[r].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(e,4),r=0,s=8;r<i;r++)n.set(t[r],s),s+=t[r].byteLength;return n}function nu(e,t,i){if(e.byteLength!==16)throw new RangeError("Invalid system id");let s,r;s=0,r=new Uint8Array;let n;s>0?(n=new Uint8Array(4),t.length>0&&new DataView(n.buffer).setUint32(0,t.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),ru([112,115,115,104],new Uint8Array([s,0,0,0]),e,n,r,a,i)}function au(e){const t=[];if(e instanceof ArrayBuffer){const i=e.byteLength;let s=0;for(;s+32<i;){const r=ou(new DataView(e,s));t.push(r),s+=r.size}}return t}function ou(e){const t=e.getUint32(0),i=e.byteOffset,s=e.byteLength;if(s<t)return{offset:i,size:s};if(e.getUint32(4)!==1886614376)return{offset:i,size:t};const r=e.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:i,size:t};const n=e.buffer,a=ye(new Uint8Array(n,i+12,16));let o=null,l=null,d=0;if(r===0)d=28;else{const h=e.getUint32(28);if(!h||s<32+h*16)return{offset:i,size:t};o=[];for(let u=0;u<h;u++)o.push(new Uint8Array(n,i+32+u*16,16));d=32+h*16}if(!d)return{offset:i,size:t};const c=e.getUint32(d);return t-32<c?{offset:i,size:t}:(l=new Uint8Array(n,i+d+4,c),{version:r,systemId:a,kids:o,data:l,offset:i,size:t})}function Hs(e,t){const i=ct[t];return!!i&&!!i[e.slice(0,4)]}function Ut(e,t,i=!0){return!e.split(",").some(s=>!Ws(s,t,i))}function Ws(e,t,i=!0){var s;const r=Ye(i);return(s=r?.isTypeSupported(Bt(e,t)))!=null?s:!1}function Bt(e,t){return`${t}/mp4;codecs=${e}`}function Ka(e){if(e){const t=e.substring(0,4);return ct.video[t]}return 2}function Li(e){const t=xr();return e.split(",").reduce((i,s)=>{const r=t&&Ai(s)?9:ct.video[s];return r?(r*2+i)/(i?3:2):(ct.audio[s]+i)/(i?2:1)},0)}function lu(e,t=!0){if(zi[e])return zi[e];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let r=0;r<i.length;r++){var s;if(Ws(i[r],"audio",t))return zi[e]=i[r],i[r];if(i[r]==="mp3"&&(s=Ye(t))!=null&&s.isTypeSupported("audio/mpeg"))return""}return e}function Ri(e,t=!0){return e.replace(Gl,i=>lu(i.toLowerCase(),t))}function du(e,t){const i=[];if(e){const s=e.split(",");for(let r=0;r<s.length;r++)Hs(s[r],"video")||i.push(s[r])}return t&&i.push(t),i.join(",")}function Di(e,t){if(e&&(e.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e)!==-1)&&(Ha(e,"audio")||Ha(e,"video")))return e;if(t){const i=t.split(",");if(i.length>1){if(e){for(let s=i.length;s--;)if(i[s].substring(0,4)===e.substring(0,4))return i[s]}return i[0]}}return t||e}function Ha(e,t){return Hs(e,t)&&Ws(e,t)}function cu(e){const t=e.split(",");for(let i=0;i<t.length;i++){const s=t[i].split(".");s.length>2&&s[0]==="avc1"&&(t[i]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return t.join(",")}function hu(e){if(e.startsWith("av01.")){const t=e.split("."),i=["0","111","01","01","01","0"];for(let s=t.length;s>4&&s<10;s++)t[s]=i[s-4];return t.join(".")}return e}function Wa(e){const t=Ye(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function js(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}function ja(e,t){return{supported:!1,configurations:t,decodingInfoResults:[Kl],error:e}}function uu(e,t,i,s,r,n){const a=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=n?.audioCodec,d=n?.channels,c=d?parseInt(d):l?1/0:2;let h=null;if(o!=null&&o.length)try{o.length===1&&o[0]?h=t.groups[o[0]].channels:h=o.reduce((u,f)=>{if(f){const m=t.groups[f];if(!m)throw new Error(`Audio track group ${f} not found`);Object.keys(m.channels).forEach(g=>{u[g]=(u[g]||0)+m.channels[g]})}return u},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(u=>Ai(u))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(s,30)||e.videoRange!=="SDR"&&e.videoRange!==i||e.bitrate>Math.max(r,8e6))||!!h&&N(c)&&Object.keys(h).some(u=>parseInt(u)>c)}function Ya(e,t,i,s={}){const r=e.videoCodec;if(!r&&!e.audioCodec||!i)return Promise.resolve(Mr);const n=[],a=fu(e),o=a.length,l=gu(e,t,o>0),d=l.length;for(let c=o||1*d||1;c--;){const h={type:"media-source"};if(o&&(h.video=a[c%o]),d){h.audio=l[c%d];const u=h.audio.bitrate;h.video&&u&&(h.video.bitrate-=u)}n.push(h)}if(r){const c=navigator.userAgent;if(r.split(",").some(h=>Ai(h))&&xr())return Promise.resolve(ja(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${c})`),n))}return Promise.all(n.map(c=>{const h=pu(c);return s[h]||(s[h]=i.decodingInfo(c))})).then(c=>({supported:!c.some(h=>!h.supported),configurations:n,decodingInfoResults:c})).catch(c=>({supported:!1,configurations:n,decodingInfoResults:[],error:c}))}function fu(e){var t;const i=(t=e.videoCodec)==null?void 0:t.split(","),s=za(e),r=e.width||640,n=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return i?i.map(l=>{const d={contentType:Bt(hu(l),"video"),width:r,height:n,bitrate:s,framerate:a};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function gu(e,t,i){var s;const r=(s=e.audioCodec)==null?void 0:s.split(","),n=za(e);return r&&e.audioGroups?e.audioGroups.reduce((a,o)=>{var l;const d=o?(l=t.groups[o])==null?void 0:l.tracks:null;return d?d.reduce((c,h)=>{if(h.groupId===o){const u=parseFloat(h.channels||"");r.forEach(f=>{const m={contentType:Bt(f,"audio"),bitrate:i?mu(f,n):n};u&&(m.channels=""+u),c.push(m)})}return c},a):a},[]):[]}function mu(e,t){if(t<=1)return 1;let i=128e3;return e==="ec-3"?i=768e3:e==="ac-3"&&(i=64e4),Math.min(t/2,i)}function za(e){return Math.ceil(Math.max(e.bitrate*.9,e.averageBitrate)/1e3)*1e3||1}function pu(e){let t="";const{audio:i,video:s}=e;if(s){const r=js(s.contentType);t+=`${r}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(i){const r=js(i.contentType);t+=`${s?"_":""}${r}_c${i.channels}`}return t}function yu(e){return qi.indexOf(e)>-1}function vu(e){return!!e&&qt.indexOf(e)>-1}function qa(e){const{canSkipUntil:t,canSkipDateRanges:i,age:s}=e,r=s<t/2;return t&&r?i?Dt.v2:Dt.Yes:Dt.No}function Xa(e,t){return!t||!e?!1:e.indexOf(t)!==-1}function Eu(){if(typeof matchMedia=="function"){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return e.matches===!0}return!1}function Tu(e,t){let i=!1,s=[];if(e&&(i=e!=="SDR",s=[e]),t){s=t.allowedVideoRanges||qt.slice(0);const r=s.join("")!=="SDR"&&!t.videoCodec;i=t.preferHDR!==void 0?t.preferHDR:r&&Eu(),i||(s=["SDR"])}return{preferHDR:i,allowedVideoRanges:s}}function Su(e,t,i,s,r){const n=Object.keys(e),a=s?.channels,o=s?.audioCodec,l=r?.videoCodec,d=a&&parseInt(a)===2;let c=!1,h=!1,u=1/0,f=1/0,m=1/0,g=1/0,y=0,v=[];const{preferHDR:E,allowedVideoRanges:T}=Tu(t,r);for(let I=n.length;I--;){const D=e[n[I]];c||(c=D.channels[2]>0),u=Math.min(u,D.minHeight),f=Math.min(f,D.minFramerate),m=Math.min(m,D.minBitrate),T.filter(w=>D.videoRanges[w]>0).length>0&&(h=!0)}u=N(u)?u:0,f=N(f)?f:0;const S=Math.max(1080,u),A=Math.max(30,f);m=N(m)?m:i,i=Math.max(m,i),h||(t=void 0);const b=n.length>1;return{codecSet:n.reduce((I,D)=>{const w=e[D];if(D===I)return I;if(v=h?T.filter(P=>w.videoRanges[P]>0):[],b){if(w.minBitrate>i)return Ue(D,`min bitrate of ${w.minBitrate} > current estimate of ${i}`),I;if(!w.hasDefaultAudio)return Ue(D,"no renditions with default or auto-select sound found"),I;if(o&&D.indexOf(o.substring(0,4))%5!==0)return Ue(D,`audio codec preference "${o}" not found`),I;if(a&&!d){if(!w.channels[a])return Ue(D,`no renditions with ${a} channel sound found (channels options: ${Object.keys(w.channels)})`),I}else if((!o||d)&&c&&w.channels[2]===0)return Ue(D,"no renditions with stereo sound found"),I;if(w.minHeight>S)return Ue(D,`min resolution of ${w.minHeight} > maximum of ${S}`),I;if(w.minFramerate>A)return Ue(D,`min framerate of ${w.minFramerate} > maximum of ${A}`),I;if(!v.some(P=>w.videoRanges[P]>0))return Ue(D,`no variants with VIDEO-RANGE of ${ne(v)} found`),I;if(l&&D.indexOf(l.substring(0,4))%5!==0)return Ue(D,`video codec preference "${l}" not found`),I;if(w.maxScore<y)return Ue(D,`max score of ${w.maxScore} < selected max of ${y}`),I}return I&&(Li(D)>=Li(I)||w.fragmentError>e[I].fragmentError)?I:(g=w.minIndex,y=w.maxScore,D)},void 0),videoRanges:v,preferHDR:E,minFramerate:f,minBitrate:m,minIndex:g}}function Ue(e,t){te.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function Qa(e){return e.reduce((t,i)=>{let s=t.groups[i.groupId];s||(s=t.groups[i.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(i);const r=i.channels||"2";return s.channels[r]=(s.channels[r]||0)+1,s.hasDefault=s.hasDefault||i.default,s.hasAutoSelect=s.hasAutoSelect||i.autoselect,s.hasDefault&&(t.hasDefaultAudio=!0),s.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function bu(e,t,i,s){return e.slice(i,s+1).reduce((r,n,a)=>{if(!n.codecSet)return r;const o=n.audioGroups;let l=r[n.codecSet];l||(r[n.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,n.bitrate);const d=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,d),l.minFramerate=Math.min(l.minFramerate,n.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,n.score),l.fragmentError+=n.fragmentError,l.videoRanges[n.videoRange]=(l.videoRanges[n.videoRange]||0)+1,o&&o.forEach(c=>{if(!c)return;const h=t.groups[c];h&&(l.hasDefaultAudio=l.hasDefaultAudio||t.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(h.channels).forEach(u=>{l.channels[u]=(l.channels[u]||0)+h.channels[u]}))}),r},{})}function Za(e){if(!e)return e;const{lang:t,assocLang:i,characteristics:s,channels:r,audioCodec:n}=e;return{lang:t,assocLang:i,characteristics:s,channels:r,audioCodec:n}}function Be(e,t,i){if("attrs"in e){const s=t.indexOf(e);if(s!==-1)return s}for(let s=0;s<t.length;s++){const r=t[s];if(at(e,r,i))return s}return-1}function at(e,t,i){const{groupId:s,name:r,lang:n,assocLang:a,default:o}=e,l=e.forced;return(s===void 0||t.groupId===s)&&(r===void 0||t.name===r)&&(n===void 0||Iu(n,t.lang))&&(n===void 0||t.assocLang===a)&&(o===void 0||t.default===o)&&(l===void 0||t.forced===l)&&(!("characteristics"in e)||Au(e.characteristics||"",t.characteristics))&&(i===void 0||i(e,t))}function Iu(e,t="--"){return e.length===t.length?e===t:e.startsWith(t)||t.startsWith(e)}function Au(e,t=""){const i=e.split(","),s=t.split(",");return i.length===s.length&&!i.some(r=>s.indexOf(r)===-1)}function ot(e,t){const{audioCodec:i,channels:s}=e;return(i===void 0||(t.audioCodec||"").substring(0,4)===i.substring(0,4))&&(s===void 0||s===(t.channels||"2"))}function Lu(e,t,i,s,r){const n=t[s],a=t.reduce((h,u,f)=>{const m=u.uri;return(h[m]||(h[m]=[])).push(f),h},{})[n.uri];a.length>1&&(s=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,d=n.codecSet.substring(0,4),c=Ja(t,s,h=>{if(h.videoRange!==o||h.frameRate!==l||h.codecSet.substring(0,4)!==d)return!1;const u=h.audioGroups;return Be(e,i.filter(f=>!u||u.indexOf(f.groupId)!==-1),r)>-1});return c>-1?c:Ja(t,s,h=>{const u=h.audioGroups;return Be(e,i.filter(f=>!u||u.indexOf(f.groupId)!==-1),r)>-1})}function Ja(e,t,i){for(let s=t;s>-1;s--)if(i(e[s]))return s;for(let s=t+1;s<e.length;s++)if(i(e[s]))return s;return-1}function Pi(e,t){var i;return!!e&&e!==((i=t.loadLevelObj)==null?void 0:i.uri)}function Ru(e,t,i){if(t===null||!Array.isArray(e)||!e.length||!N(t)||t<(e[0].programDateTime||0)||t>=(e[e.length-1].endProgramDateTime||0))return null;for(let s=0;s<e.length;++s){const r=e[s];if(Pu(t,i,r))return r}return null}function lt(e,t,i=0,s=0,r=.005){let n=null;if(e){n=t[1+e.sn-t[0].sn]||null;const o=e.endDTS-i;o>0&&o<15e-7&&(i+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else i===0&&t[0].start===0&&(n=t[0]);if(n&&((!e||e.level===n.level)&&eo(i,s,n)===0||Du(n,e,Math.min(r,s))))return n;const a=Fr.search(t,eo.bind(null,i,s));return a&&(a!==e||!n)?a:n}function Du(e,t,i){if(t&&t.start===0&&t.level<e.level&&(t.endPTS||0)>0){const s=t.tagList.reduce((r,n)=>(n[0]==="INF"&&(r+=parseFloat(n[1])),r),i);return e.start<=s}return!1}function eo(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;const s=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-s<=e?1:i.start-s>e&&i.start?-1:0}function Pu(e,t,i){const s=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0))*1e3;return(i.endProgramDateTime||0)-s>e}function to(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){let s=e.fragments;const{fragmentHint:r}=e;r&&(s=s.concat(r));let n;return Fr.search(s,a=>a.cc<t?1:a.cc>t?-1:(n=a,a.end<=i?1:a.start>i?-1:0)),n||null}return null}function wi(e){switch(e.details){case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_TIMEOUT:case L.LEVEL_LOAD_TIMEOUT:case L.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function io(e){return e.details.startsWith("key")}function so(e){return io(e)&&!!e.frag&&!e.frag.decryptdata}function ro(e,t){const i=wi(t);return e.default[`${i?"timeout":"error"}Retry`]}function Ys(e,t){const i=e.backoff==="linear"?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function no(e){return ie(ie({},e),{errorRetry:null,timeoutRetry:null})}function _i(e,t,i,s){if(!e)return!1;const r=s?.code,n=t<e.maxNumRetry&&(wu(r)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,s,n):n}function wu(e){return zs(e)||!!e&&(e<400||e>499)}function zs(e){return e===0&&navigator.onLine===!1}function Tt(e){const t={action:ce.DoNothing,flags:Te.None};return e&&(t.resolved=!0),t}function ki(e){var t,i,s;return e.buffered&&!!(e.body.gap||(t=e.range.video)!=null&&t.partial||(i=e.range.audio)!=null&&i.partial||(s=e.range.audiovideo)!=null&&s.partial)}function St(e){return`${e.type}_${e.level}_${e.sn}`}function ao(e,t){return e.filter(i=>{const s=t(i);return s||i.clearElementaryStreamInfo(),s})}function _u(e){const t=e.byteLength,i=t&&new DataView(e.buffer).getUint8(t-1);return i?e.slice(0,t-i):e}function ku(e){switch(e){case Xe.cbc:return"AES-CBC";case Xe.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}function oo(e,t=null){const i=t||e,s={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},r=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(N(r)&&N(n)){var a;let o=r,l=n;if(e.sn==="initSegment"&&Cu((a=e.decryptdata)==null?void 0:a.method)){const d=n-r;d%16&&(l=n+(16-d%16)),r!==0&&(s.resetIV=!0,o=r-16)}s.rangeStart=o,s.rangeEnd=l}return s}function lo(e,t){const i=new Error(`GAP ${e.gap?"tag":"attribute"} found`),s={type:$.MEDIA_ERROR,details:L.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(s.part=t),(t||e).stats.aborted=!0,new Ve(s)}function Cu(e){return e==="AES-128"||e==="AES-256"}function Ci(){return{start:0,executeStart:0,executeEnd:0,end:0}}function co(e){return Gr.test(e)}function qs(e,t){if(e.variableList!==null||e.hasVariableRefs){const i=e.variableList;return t.replace(Gr,s=>{const r=s.substring(2,s.length-1),n=i?.[r];return n===void 0?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),s):n})}return t}function ho(e,t,i){let s=e.variableList;s||(e.variableList=s={});let r,n;if("QUERYPARAM"in t){r=t.QUERYPARAM;try{const a=new self.URL(i).searchParams;if(a.has(r))n=a.get(r);else throw new Error(`"${r}" does not match any query parameter in URI: "${i}"`)}catch(a){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else r=t.NAME,n=t.VALUE;r in s?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):s[r]=n||""}function xu(e,t,i){const s=t.IMPORT;if(i&&s in i){let r=e.variableList;r||(e.variableList=r={}),r[s]=i[s]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}function Mu(e){return e!=="ID"&&e!=="CLASS"&&e!=="CUE"&&e!=="START-DATE"&&e!=="DURATION"&&e!=="END-DATE"&&e!=="END-ON-NEXT"}function Ou(e){return e==="SCTE35-OUT"||e==="SCTE35-IN"||e==="SCTE35-CMD"}function xi(e,t){return e.length===t.length?!e.some((i,s)=>i!==t[s]):!1}function uo(e,t){return!e&&!t?!0:!e||!t?!1:xi(e,t)}function bt(e){return e==="AES-128"||e==="AES-256"||e==="AES-256-CTR"}function Xs(e){switch(e){case"AES-128":case"AES-256":return Xe.cbc;case"AES-256-CTR":return Xe.ctr;default:throw new Error(`invalid full segment method ${e}`)}}function Qs(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}function Zs(e){return Uint8Array.from(unescape(encodeURIComponent(e)),t=>t.charCodeAt(0))}function Fu(e){const t=Zs(e).subarray(0,16),i=new Uint8Array(16);return i.set(t,16-t.length),i}function fo(e){const t=function(s,r,n){const a=s[r];s[r]=s[n],s[n]=a};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function go(e){const t=e.split(":");let i=null;if(t[0]==="data"&&t.length===2){const s=t[1].split(";"),r=s[s.length-1].split(",");if(r.length===2){const n=r[0]==="base64",a=r[1];n?(s.splice(-1,1),i=Qs(a)):i=Fu(a)}}return i}function Mi(e){switch(e){case fe.FAIRPLAY:return ae.FAIRPLAY;case fe.PLAYREADY:return ae.PLAYREADY;case fe.WIDEVINE:return ae.WIDEVINE;case fe.CLEARKEY:return ae.CLEARKEY}}function Js(e){switch(e){case ae.FAIRPLAY:return fe.FAIRPLAY;case ae.PLAYREADY:return fe.PLAYREADY;case ae.WIDEVINE:return fe.WIDEVINE;case ae.CLEARKEY:return fe.CLEARKEY}}function $t(e){const{drmSystems:t,widevineLicenseUrl:i}=e,s=t?[ae.FAIRPLAY,ae.WIDEVINE,ae.PLAYREADY,ae.CLEARKEY].filter(r=>!!t[r]):[];return!s[ae.WIDEVINE]&&i&&s.push(ae.WIDEVINE),s}function Nu(e,t,i,s){let r;switch(e){case ae.FAIRPLAY:r=["cenc","sinf"];break;case ae.WIDEVINE:case ae.PLAYREADY:r=["cenc"];break;case ae.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return Uu(r,t,i,s)}function Uu(e,t,i,s){return[{initDataTypes:e,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:t.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:i.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function Bu(e){var t;return!!e&&(e.sessionType==="persistent-license"||!!((t=e.sessionTypes)!=null&&t.some(i=>i==="persistent-license")))}function mo(e){const t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),s=i.substring(i.indexOf("<"),i.length),r=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(r){const n=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(n){const a=Qs(n).subarray(0,16);return fo(a),a}}return null}function $u(e){const t=e?.[fe.WIDEVINE];return t?t.keyId:null}function po(e){const t=e?.[fe.PLAYREADY];if(t){const i=go(t.uri);if(i)return mo(i)}return null}function Gu(e){const t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}function yo(e,t){let i=e.length;if(!i)if(t.hasProgramDateTime){const o=t.fragments[t.fragments.length-1];e.push(o),i++}else return;const s=e[i-1],r=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let o=n.length;o--;){const l=t.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=s.ref;for(let c=i;c--;){var a;if(((a=e[c])==null?void 0:a.sn)<t.startSN)break;const h=Vu(t,d,e,c,r);if(h!==-1){l.tagAnchor=t.fragments[h].ref;break}}}}function Vu(e,t,i,s,r){const n=i[s];if(n){const o=n.programDateTime;if(t>=o||s===0){var a;if(t<=o+((((a=i[s+1])==null?void 0:a.start)||r)-n.start)*1e3){const l=i[s].sn-e.startSN;if(l<0)return-1;const d=e.fragments;if(d.length>i.length){const c=(i[s+1]||d[d.length-1]).sn-e.startSN;for(let h=c;h>l;h--){const u=d[h].programDateTime;if(t>=u&&t<u+d[h].duration*1e3)return h}}return l}}}return-1}function vo(e,t,i){var s,r;const n=new oe(e,i),a=(s=n.METHOD)!=null?s:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,c=(r=n.KEYFORMAT)!=null?r:"identity";return o&&n.IV&&!l&&te.error(`Invalid IV: ${n.IV}`),new Pt(a,o?ft.resolve(o,t):"",c,(d||"1").split("/").map(Number).filter(Number.isFinite),l,n.KEYID)}function Eo(e){const t=new oe(e).decimalFloatingPoint("TIME-OFFSET");return N(t)?t:null}function To(e,t){let i=(e||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const r=i.filter(n=>Hs(n,s));r.length&&(t[`${s}Codec`]=r.map(n=>n.split("/")[0]).join(","),i=i.filter(n=>r.indexOf(n)===-1))}),t.unknownCodecs=i}function So(e,t,i){const s=t[i];s&&(e[i]=s)}function Ku(e,t){let i=e[t];for(let s=t;s--;){const r=e[s];if(!r)return;r.programDateTime=i.programDateTime-r.duration*1e3,i=r}}function er(e,t,i){e.rawProgramDateTime?i.push(e):t!=null&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function bo(e,t,i,s){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",s&&(e.levelkeys=s),e.initSegment=null}function Io(e,t,i){e.levelkeys=t;const{encryptedFragments:s}=i;(!s.length||s[s.length-1].levelkeys!==t)&&Object.keys(t).some(r=>t[r].isCommonEncryption)&&s.push(e)}function ze(e,t,i){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${i[0]})`)}function Ao(e,t,i){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${i[0]})`)}function tr(e,t){const i=t.startPTS;if(N(i)){let s=0,r;t.sn>e.sn?(s=i-e.start,r=e):(s=e.start-i,r=t),r.duration!==s&&r.setDuration(s)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function Lo(e,t,i,s,r,n,a){s-i<=0&&(a.warn("Fragment should have a positive duration",t),s=i+t.duration,n=r+t.duration);let o=i,l=s;const d=t.startPTS,c=t.endPTS;if(N(d)){const y=Math.abs(d-i);e&&y>e.totalduration?a.warn(`media timestamps and playlist times differ by ${y}s for level ${t.level} ${e.url}`):N(t.deltaPTS)?t.deltaPTS=Math.max(y,t.deltaPTS):t.deltaPTS=y,o=Math.max(i,d),i=Math.min(i,d),r=t.startDTS!==void 0?Math.min(r,t.startDTS):r,l=Math.min(s,c),s=Math.max(s,c),n=t.endDTS!==void 0?Math.max(n,t.endDTS):n}const h=i-t.start;t.start!==0&&t.setStart(i),t.setDuration(s-t.start),t.startPTS=i,t.maxStartPTS=o,t.startDTS=r,t.endPTS=s,t.minEndPTS=l,t.endDTS=n;const u=t.sn;if(!e||u<e.startSN||u>e.endSN)return 0;let f;const m=u-e.startSN,g=e.fragments;for(g[m]=t,f=m;f>0;f--)tr(g[f],g[f-1]);for(f=m;f<g.length-1;f++)tr(g[f],g[f+1]);return e.fragmentHint&&tr(g[g.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,h}function Hu(e,t,i){if(e===t)return;let s=null;const r=e.fragments;for(let c=r.length-1;c>=0;c--){const h=r[c].initSegment;if(h){s=h;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let n;Yu(e,t,(c,h,u,f)=>{if((!t.startCC||t.skippedSegments)&&h.cc!==c.cc){const m=c.cc-h.cc;for(let g=u;g<f.length;g++)f[g].cc+=m;t.endCC=f[f.length-1].cc}N(c.startPTS)&&N(c.endPTS)&&(h.setStart(h.startPTS=c.startPTS),h.startDTS=c.startDTS,h.maxStartPTS=c.maxStartPTS,h.endPTS=c.endPTS,h.endDTS=c.endDTS,h.minEndPTS=c.minEndPTS,h.setDuration(c.endPTS-c.startPTS),h.duration&&(n=h),t.PTSKnown=t.alignedSliding=!0),c.hasStreams&&(h.elementaryStreams=c.elementaryStreams),h.loader=c.loader,c.hasStats&&(h.stats=c.stats),c.initSegment&&(h.initSegment=c.initSegment,s=c.initSegment)});const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(s&&o.forEach(c=>{var h;c&&(!c.initSegment||c.initSegment.relurl===((h=s)==null?void 0:h.relurl))&&(c.initSegment=s)}),t.skippedSegments){if(t.deltaUpdateFailed=a.some(c=>!c),t.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let c=t.skippedSegments;c--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=Wu(e.dateRanges,t,i));const c=e.fragments.filter(h=>h.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let h=1;h<o.length;h++)o[h].programDateTime===null&&er(o[h],o[h-1],c);yo(c,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var l;const c=wo(e,t.startSN-1);t.startCC=(l=c?.cc)!=null?l:a[0].cc}ju(e.partList,t.partList,(c,h)=>{h.elementaryStreams=c.elementaryStreams,h.stats=c.stats}),n?Lo(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,i):Do(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const d=t.advancedDateTime;if(t.advanced&&d){const c=t.edge;t.driftStart||(t.driftStartTime=d,t.driftStart=c),t.driftEndTime=d,t.driftEnd=c}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=e.requestScheduled)}function Wu(e,t,i){const{dateRanges:s,recentlyRemovedDateranges:r}=t,n=se({},e);r&&r.forEach(o=>{delete n[o]});const a=Object.keys(n).length;return a?(Object.keys(s).forEach(o=>{const l=n[o],d=new Zi(s[o].attr,l);d.isValid?(n[o]=d,l||(d.tagOrder+=a)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ne(s[o].attr)}"`)}),n):s}function ju(e,t,i){if(e&&t){let s=0;for(let r=0,n=e.length;r<=n;r++){const a=e[r],o=t[r+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?i(a,o):s--}}}function Yu(e,t,i){const s=t.skippedSegments,r=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(s?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let d=r;d<=n;d++){const c=l[a+d];let h=o[d];if(s&&!h&&c&&(h=t.fragments[d]=c),c&&h){i(c,h,d,o);const u=c.relurl,f=h.relurl;if(u&&zu(u,f)){t.playlistParsingError=Ro(`media sequence mismatch ${h.sn}:`,e,t,c,h);return}else if(c.cc!==h.cc){t.playlistParsingError=Ro(`discontinuity sequence mismatch (${c.cc}!=${h.cc})`,e,t,c,h);return}}}}function Ro(e,t,i,s,r){return new Error(`${e} ${r.url}
|
|
42
|
+
`,Z=(e,t,i)=>{const s=document.createElement(e);return t&&(s.className=t),typeof i=="string"&&(s.textContent=i),s},Nt=e=>{if(!Number.isFinite(e)||e<=0)return"00:00";const t=Math.floor(e/60),i=Math.round(e%60);return`${String(t).padStart(2,"0")}:${String(i).padStart(2,"0")}`},Bs=()=>{const e=document.createElement("style");return e.textContent=Ra,e},Da=e=>{e.replaceChildren()},$s=(e,t)=>({$el:e,unmount(){t(),Da(e)}}),wa=(e,t,i,s)=>{const r=mi(s?.options),n=i.trim().toLowerCase()||"mp3",a=La[n]||"audio/*",o=URL.createObjectURL(new Blob([e],{type:a})),l=Z("div","fv-audio-viewer"),d=Z("section","fv-audio-card"),c=Z("div","fv-audio-art");c.append(Z("span"),Z("i"));const h=Z("div","fv-audio-copy");h.append(Z("span","fv-audio-kicker",n.toUpperCase()||"AUDIO"),Z("strong","",r("media.audio.title")),Z("p","",r("media.audio.description")));const u=Z("span","","00:00"),f=Z("span","","--:--"),m=Z("i"),g=Z("div","fv-audio-progress");g.setAttribute("aria-hidden","true"),g.append(m);const y=Z("div","fv-audio-meter");y.append(u,g,f);const v=Z("audio","fv-audio-control");v.src=o,v.controls=!0,v.preload="metadata",v.textContent=r("media.audio.unsupported");const E=()=>{f.textContent=Number.isFinite(v.duration)&&v.duration>0?Nt(v.duration):"--:--"},T=()=>{u.textContent=Nt(v.currentTime);const S=Number.isFinite(v.duration)&&v.duration>0?Math.min(100,Math.max(0,v.currentTime/v.duration*100)):0;m.style.width=`${S}%`};return v.addEventListener("loadedmetadata",E),v.addEventListener("timeupdate",T),d.append(c,h,y,v),l.append(d),t.replaceChildren(Bs(),l),$s(t,()=>{v.pause(),v.removeEventListener("loadedmetadata",E),v.removeEventListener("timeupdate",T),URL.revokeObjectURL(o)})},Pa=(e,t,i)=>{const s=mi(i?.options);let r=!1;const n=Z("div","fv-midi-viewer"),a=Z("section","fv-midi-card"),o=document.createElement("header"),l=Z("strong","",s("media.midi.title"));o.append(Z("span","","MIDI"),l);const d=Z("div","fv-midi-state",s("media.midi.loading"));a.append(o,d),n.append(a),t.replaceChildren(Bs(),n);const c=f=>{d.className="fv-midi-state fv-midi-error",d.textContent=f},h=f=>{const m=Z("div","fv-midi-table-wrap"),g=Z("table","fv-midi-table"),y=document.createElement("thead"),v=document.createElement("tr");for(const T of[s("media.midi.trackHeader"),s("media.midi.instrumentHeader"),s("media.midi.channelHeader"),s("media.midi.noteCountHeader"),s("media.midi.durationHeader")])v.append(Z("th","",T));y.append(v);const E=document.createElement("tbody");for(const T of f){const S=document.createElement("tr");S.append(Z("td","",T.name),Z("td","",T.instrument),Z("td","",String(T.channel+1)),Z("td","",String(T.notes)),Z("td","",Nt(T.duration))),E.append(S)}return g.append(y,E),m.append(g),m},u=f=>{l.textContent=f.name;const m=f.tracks.reduce((y,v)=>y+v.notes,0),g=Z("div","fv-midi-stats");for(const[y,v]of[[s("media.midi.durationStat"),Nt(f.duration)],["PPQ",String(f.ppq)],[s("media.midi.trackStat"),String(f.tracks.length)],[s("media.midi.noteStat"),String(m)]]){const E=document.createElement("div");E.append(Z("span","",y),Z("strong","",v)),g.append(E)}d.replaceWith(g,h(f.tracks))};return(async()=>{try{const{Midi:f}=await Promise.resolve().then(()=>Zc(Mh(),1)),m=new f(e);if(r)return;u({name:m.name||s("media.midi.title"),duration:m.duration,ppq:m.header.ppq,tracks:m.tracks.map((g,y)=>{var v,E;return{name:g.name||`Track ${y+1}`,instrument:((v=g.instrument)===null||v===void 0?void 0:v.name)||((E=g.instrument)===null||E===void 0?void 0:E.family)||"Unknown",channel:g.channel,notes:g.notes.length,duration:g.duration}})})}catch(f){r||c(f instanceof Error?f.message:s("media.midi.parseFailed"))}})(),$s(t,()=>{r=!0})}})),Uh=Mt({AbrController:()=>Or,AttrList:()=>oe,AudioStreamController:()=>en,AudioTrackController:()=>tn,BasePlaylistController:()=>si,BaseSegment:()=>Yi,BaseStreamController:()=>Zt,BufferController:()=>nn,CMCDController:()=>gn,CapLevelController:()=>an,ChunkMetadata:()=>Xt,ContentSteeringController:()=>mn,Cues:()=>wn,DateRange:()=>Zi,EMEController:()=>ls,ErrorActionFlags:()=>Te,ErrorController:()=>Nr,ErrorDetails:()=>L,ErrorTypes:()=>$,Events:()=>p,FPSController:()=>pn,FetchLoader:()=>gs,Fragment:()=>zt,Hls:()=>ps,HlsSkip:()=>Dt,HlsUrlParameters:()=>Xi,KeySystemFormats:()=>fe,KeySystems:()=>ae,Level:()=>ht,LevelDetails:()=>Kr,LevelKey:()=>wt,LoadStats:()=>Yt,M3U8Parser:()=>ft,MetadataSchema:()=>Se,NetworkErrorAction:()=>ce,Part:()=>_r,PlaylistLevelType:()=>B,SubtitleStreamController:()=>Tn,SubtitleTrackController:()=>yn,TimelineController:()=>Dn,XhrLoader:()=>ms,default:()=>ps,fetchSupported:()=>wl,getMediaSource:()=>Ye,isMSESupported:()=>Dr,isSupported:()=>xl,requestMediaKeySystemAccess:()=>Ji});function Bh(e,t,i){return(t=Gh(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function se(){return se=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var s in i)({}).hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},se.apply(null,arguments)}function _a(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),i.push.apply(i,s)}return i}function ie(e){for(var t=1;t<arguments.length;t++){var i=arguments[t]!=null?arguments[t]:{};t%2?_a(Object(i),!0).forEach(function(s){Bh(e,s,i[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):_a(Object(i)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(i,s))})}return e}function $h(e,t){if(typeof e!="object"||!e)return e;var i=e[Symbol.toPrimitive];if(i!==void 0){var s=i.call(e,t);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Gh(e){var t=$h(e,"string");return typeof t=="symbol"?t:t+""}function Gs(){return se({},Ul)}function Vh(e,t){const i=self.console[e];return i?i.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):qe}function ka(e,t,i){return t[e]?t[e].bind(t):Vh(e,i)}function Kh(e,t,i){const s=Gs();if(typeof console=="object"&&e===!0||typeof e=="object"){const r=["debug","log","info","warn","error"];r.forEach(n=>{s[n]=ka(n,e,i)});try{s.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return Gs()}r.forEach(n=>{Hi[n]=ka(n,e)})}else se(Hi,s);return s}function Ye(e=!0){if(!(typeof self>"u"))return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Hh(e){return typeof self<"u"&&e===self.ManagedMediaSource}function Ca(e,t){const i=Object.keys(e),s=Object.keys(t),r=i.length,n=s.length;return!r||!n||r===n&&!i.some(a=>s.indexOf(a)===-1)}function De(e,t=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(e);if(t){const d=l.indexOf("\0");return d!==-1?l.substring(0,d):l}return l.replace(/\0/g,"")}const i=e.length;let s,r,n,a="",o=0;for(;o<i;){if(s=e[o++],s===0&&t)return a;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:r=e[o++],a+=String.fromCharCode((s&31)<<6|r&63);break;case 14:r=e[o++],n=e[o++],a+=String.fromCharCode((s&15)<<12|(r&63)<<6|(n&63)<<0);break}}return a}function ye(e){let t="";for(let i=0;i<e.length;i++){let s=e[i].toString(16);s.length<2&&(s="0"+s),t+=s}return t}function xa(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Wh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function jh(){return Bl||(Bl=1,(function(e,t){(function(i){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,d,c){if(c=c||{},l=l.trim(),d=d.trim(),!d){if(!c.alwaysNormalize)return l;var h=o.parseURL(l);if(!h)throw new Error("Error trying to parse base URL.");return h.path=o.normalizePath(h.path),o.buildURLFromParts(h)}var u=o.parseURL(d);if(!u)throw new Error("Error trying to parse relative URL.");if(u.scheme)return c.alwaysNormalize?(u.path=o.normalizePath(u.path),o.buildURLFromParts(u)):d;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var m=r.exec(f.path);f.netLoc=m[1],f.path=m[2]}f.netLoc&&!f.path&&(f.path="/");var g={scheme:f.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(g.netLoc=f.netLoc,u.path[0]!=="/"))if(!u.path)g.path=f.path,u.params||(g.params=f.params,u.query||(g.query=f.query));else{var y=f.path,v=y.substring(0,y.lastIndexOf("/")+1)+u.path;g.path=o.normalizePath(v)}return g.path===null&&(g.path=c.alwaysNormalize?o.normalizePath(u.path):u.path),o.buildURLFromParts(g)},parseURL:function(l){var d=s.exec(l);return d?{scheme:d[1]||"",netLoc:d[2]||"",path:d[3]||"",params:d[4]||"",query:d[5]||"",fragment:d[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};e.exports=o})()})(Wi)),Wi.exports}function de(e){return e.sn!=="initSegment"}function Ma(e,t){const i=Object.getPrototypeOf(e);if(i){const s=Object.getOwnPropertyDescriptor(i,t);return s||Ma(i,t)}}function Yh(e,t){const i=Ma(e,t);i&&(i.enumerable=!0,Object.defineProperty(e,t,i))}function ue(e){return String.fromCharCode.apply(null,e)}function Oa(e,t){const i=e[t]<<8|e[t+1];return i<0?65536+i:i}function K(e,t){const i=Na(e,t);return i<0?4294967296+i:i}function Fa(e,t){let i=K(e,t);return i*=Math.pow(2,32),i+=K(e,t+4),i}function Na(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function zh(e){const t=e.byteLength;for(let i=0;i<t;){const s=K(e,i);if(s>8&&e[i+4]===109&&e[i+5]===111&&e[i+6]===111&&e[i+7]===102)return!0;i=s>1?i+s:t}return!1}function z(e,t){const i=[];if(!t.length)return i;const s=e.byteLength;for(let r=0;r<s;){const n=K(e,r),a=ue(e.subarray(r+4,r+8)),o=n>1?r+n:s;if(a===t[0])if(t.length===1)i.push(e.subarray(r+8,o));else{const l=z(e.subarray(r+8,o),t.slice(1));l.length&&$l.apply(i,l)}r=o}return i}function qh(e){const t=[],i=e[0];let s=8;const r=K(e,s);s+=4;let n=0,a=0;i===0?(n=K(e,s),a=K(e,s+4),s+=8):(n=Fa(e,s),a=Fa(e,s+8),s+=16),s+=2;let o=e.length+a;const l=Oa(e,s);s+=2;for(let d=0;d<l;d++){let c=s;const h=K(e,c);c+=4;const u=h&2147483647;if((h&2147483648)>>>31===1)return te.warn("SIDX has hierarchical references (not supported)"),null;const f=K(e,c);c+=4,t.push({referenceSize:u,subsegmentDuration:f,info:{duration:f/r,start:o,end:o+u-1}}),o+=u,c+=4,s=c}return{earliestPresentationTime:n,timescale:r,version:i,referencesCount:l,references:t}}function Ua(e){const t=[],i=z(e,["moov","trak"]);for(let s=0;s<i.length;s++){const r=i[s],n=z(r,["tkhd"])[0];if(n){let a=n[0];const o=K(n,a===0?12:20),l=z(r,["mdia","mdhd"])[0];if(l){a=l[0];const d=K(l,a===0?12:20),c=z(r,["mdia","hdlr"])[0];if(c){const h=ue(c.subarray(8,12)),u={soun:re.AUDIO,vide:re.VIDEO}[h],f=z(r,["mdia","minf","stbl","stsd"])[0],m=Xh(f);u?(t[o]={timescale:d,type:u,stsd:m},t[u]=ie({timescale:d,id:o},m)):t[o]={timescale:d,type:h,stsd:m}}}}}return z(e,["moov","mvex","trex"]).forEach(s=>{const r=t[K(s,4)];r&&(r.default={duration:K(s,12),flags:K(s,20)})}),t}function Xh(e){const t=e.subarray(8),i=t.subarray(86),s=ue(t.subarray(4,8));let r=s,n;const a=s==="enca"||s==="encv";a&&z(z(t,[s])[0].subarray(s==="enca"?28:78),["sinf"]).forEach(l=>{const d=z(l,["schm"])[0];if(d){const c=ue(d.subarray(4,8));if(c==="cbcs"||c==="cenc"){const h=z(l,["frma"])[0];h&&(r=ue(h))}}});const o=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{const l=z(i,["avcC"])[0];l&&l.length>3&&(r+="."+Ii(l[1])+Ii(l[2])+Ii(l[3]),n=bi(o==="avc1"?"dva1":"dvav",i));break}case"mp4a":{const l=z(t,[s])[0],d=z(l.subarray(28),["esds"])[0];if(d&&d.length>7){let c=4;if(d[c++]!==3)break;c=Vs(d,c),c+=2;const h=d[c++];if(h&128&&(c+=2),h&64&&(c+=d[c++]),d[c++]!==4)break;c=Vs(d,c);const u=d[c++];if(u===64)r+="."+Ii(u);else break;if(c+=12,d[c++]!==5)break;c=Vs(d,c);const f=d[c++];let m=(f&248)>>3;m===31&&(m+=1+((f&7)<<3)+((d[c]&224)>>5)),r+="."+m}break}case"hvc1":case"hev1":{const l=z(i,["hvcC"])[0];if(l&&l.length>12){const d=l[1],c=["","A","B","C"][d>>6],h=d&31,u=K(l,2),f=(d&32)>>5?"H":"L",m=l[12],g=l.subarray(6,12);r+="."+c+h,r+="."+Qh(u).toString(16).toUpperCase(),r+="."+f+m;let y="";for(let v=g.length;v--;){const E=g[v];(E||y)&&(y="."+E.toString(16).toUpperCase()+y)}r+=y}n=bi(o=="hev1"?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":r=bi(r,i)||r;break;case"vp09":{const l=z(i,["vpcC"])[0];if(l&&l.length>6){const d=l[4],c=l[5],h=l[6]>>4&15;r+="."+Ne(d)+"."+Ne(c)+"."+Ne(h)}break}case"av01":{const l=z(i,["av1C"])[0];if(l&&l.length>2){const d=l[1]>>>5,c=l[1]&31,h=l[2]>>>7?"H":"M",u=(l[2]&64)>>6,f=(l[2]&32)>>5,m=d===2&&u?f?12:10:u?10:8,g=(l[2]&16)>>4,y=(l[2]&8)>>3,v=(l[2]&4)>>2,E=l[2]&3;r+="."+d+"."+Ne(c)+h+"."+Ne(m)+"."+g+"."+y+v+E+"."+Ne(1)+"."+Ne(1)+"."+Ne(1)+".0",n=bi("dav1",i)}break}}return{codec:r,encrypted:a,supplemental:n}}function bi(e,t){const i=z(t,["dvvC"]),s=i.length?i[0]:z(t,["dvcC"])[0];if(s){const r=s[2]>>1&127,n=s[2]<<5&32|s[3]>>3&31;return e+"."+Ne(r)+"."+Ne(n)}}function Qh(e){let t=0;for(let i=0;i<32;i++)t|=(e>>i&1)<<31-i;return t>>>0}function Vs(e,t){const i=t+5;for(;e[t++]&128&&t<i;);return t}function Ii(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Ne(e){return(e<10?"0":"")+e}function Zh(e,t){if(!e||!t)return;const i=t.keyId;i&&t.isCommonEncryption&&Ba(e,(s,r)=>{const n=s.subarray(8,24);n.some(a=>a!==0)||(te.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${ye(n)} -> ${ye(i)}`),s.set(i,8))})}function Jh(e){const t=[];return Ba(e,i=>t.push(i.subarray(8,24))),t}function Ba(e,t){z(e,["moov","trak"]).forEach(i=>{const s=z(i,["mdia","minf","stbl","stsd"])[0];if(!s)return;const r=s.subarray(8);let n=z(r,["enca"]);const a=n.length>0;a||(n=z(r,["encv"])),n.forEach(o=>{z(a?o.subarray(28):o.subarray(78),["sinf"]).forEach(l=>{const d=$a(l);d&&t(d,a)})})})}function $a(e){const t=z(e,["schm"])[0];if(t){const i=ue(t.subarray(4,8));if(i==="cbcs"||i==="cenc"){const s=z(e,["schi","tenc"])[0];if(s)return s}}}function eu(e,t,i){const s={},r=z(e,["moof","traf"]);for(let n=0;n<r.length;n++){const a=r[n],o=z(a,["tfhd"])[0],l=K(o,4),d=t[l];if(!d)continue;s[l]||(s[l]={start:NaN,duration:0,sampleCount:0,timescale:d.timescale,type:d.type});const c=s[l],h=z(a,["tfdt"])[0];if(h){const T=h[0];let S=K(h,4);T===1&&(S===kr?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=kr+1,S+=K(h,8))),N(S)&&(!N(c.start)||S<c.start)&&(c.start=S)}const u=d.default,f=K(o,0)|u?.flags;let m=u?.duration||0;f&8&&(f&2?m=K(o,12):m=K(o,8));const g=z(a,["trun"]);let y=c.start||0,v=0,E=m;for(let T=0;T<g.length;T++){const S=g[T],A=K(S,4),b=c.sampleCount;c.sampleCount+=A;const I=S[3]&1,D=S[3]&4,P=S[2]&1,w=S[2]&2,x=S[2]&4,U=S[2]&8;let O=8,V=A;for(I&&(O+=4),D&&A&&(!(S[O+1]&1)&&c.keyFrameIndex===void 0&&(c.keyFrameIndex=b),O+=4,P?(E=K(S,O),O+=4):E=m,w&&(O+=4),U&&(O+=4),y+=E,v+=E,V--);V--;)P?(E=K(S,O),O+=4):E=m,w&&(O+=4),x&&(S[O+1]&1||c.keyFrameIndex===void 0&&(c.keyFrameIndex=c.sampleCount-(V+1),c.keyFrameStart=y),O+=4),U&&(O+=4),y+=E,v+=E;!v&&m&&(v+=m*A)}c.duration+=v}if(!Object.keys(s).some(n=>s[n].duration)){let n=1/0,a=0;const o=z(e,["sidx"]);for(let l=0;l<o.length;l++){const d=qh(o[l]);if(d!=null&&d.references){n=Math.min(n,d.earliestPresentationTime/d.timescale);const c=d.references.reduce((h,u)=>h+u.info.duration||0,0);a=Math.max(a,c+d.earliestPresentationTime/d.timescale)}}a&&N(a)&&Object.keys(s).forEach(l=>{s[l].duration||(s[l].duration=a*s[l].timescale-s[l].start)})}return s}function tu(e){const t={valid:null,remainder:null},i=z(e,["moof"]);if(i.length<2)return t.remainder=e,t;const s=i[i.length-1];return t.valid=e.slice(0,s.byteOffset-8),t.remainder=e.slice(s.byteOffset-8),t}function Ce(e,t){const i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function Ga(e,t){const i=[],s=t.samples,r=t.timescale,n=t.id;let a=!1;return z(s,["moof"]).map(o=>{const l=o.byteOffset-8;z(o,["traf"]).map(d=>{const c=z(d,["tfdt"]).map(h=>{const u=h[0];let f=K(h,4);return u===1&&(f*=Math.pow(2,32),f+=K(h,8)),f/r})[0];return c!==void 0&&(e=c),z(d,["tfhd"]).map(h=>{const u=K(h,4),f=K(h,0)&16777215,m=(f&1)!==0,g=(f&2)!==0,y=(f&8)!==0;let v=0;const E=(f&16)!==0;let T=0;const S=(f&32)!==0;let A=8;u===n&&(m&&(A+=8),g&&(A+=4),y&&(v=K(h,A),A+=4),E&&(T=K(h,A),A+=4),S&&(A+=4),t.type==="video"&&(a=Ai(t.codec)),z(d,["trun"]).map(b=>{const I=b[0],D=K(b,0)&16777215,P=(D&1)!==0;let w=0;const x=(D&4)!==0,U=(D&256)!==0;let O=0;const V=(D&512)!==0;let F=0;const M=(D&1024)!==0,W=(D&2048)!==0;let k=0;const C=K(b,4);let G=8;P&&(w=K(b,G),G+=4),x&&(G+=4);let j=w+l;for(let J=0;J<C;J++){if(U?(O=K(b,G),G+=4):O=v,V?(F=K(b,G),G+=4):F=T,M&&(G+=4),W&&(I===0?k=K(b,G):k=Na(b,G),G+=4),t.type===re.VIDEO){let X=0;for(;X<F;){const Q=K(s,j);j+=4,iu(a,s[j])&&Ks(s.subarray(j,j+Q),a?2:1,e+k/r,i),j+=Q,X+=Q+4}}e+=O/r}}))})})}),i}function Ai(e){if(!e)return!1;const t=e.substring(0,4);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function iu(e,t){if(e){const i=t>>1&63;return i===39||i===40}else return(t&31)===6}function Ks(e,t,i,s){const r=Va(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(l===255);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(l===255);const d=r.length-n;let c=n;if(o<d)n+=o;else if(o>d){te.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(a===4){if(r[c++]===181){const h=Oa(r,c);if(c+=2,h===49){const u=K(r,c);if(c+=4,u===1195456820){const f=r[c++];if(f===3){const m=r[c++],g=31&m,y=64&m,v=y?2+g*3:0,E=new Uint8Array(v);if(y){E[0]=m;for(let T=1;T<v;T++)E[T]=r[c++]}s.push({type:f,payloadType:a,pts:i,bytes:E})}}}}}else if(a===5&&o>16){const h=[];for(let m=0;m<16;m++){const g=r[c++].toString(16);h.push(g.length==1?"0"+g:g),(m===3||m===5||m===7||m===9)&&h.push("-")}const u=o-16,f=new Uint8Array(u);for(let m=0;m<u;m++)f[m]=r[c++];s.push({payloadType:a,pts:i,uuid:h.join(""),userData:De(f),userDataBytes:f})}}}function Va(e){const t=e.byteLength,i=[];let s=1;for(;s<t-2;)e[s]===0&&e[s+1]===0&&e[s+2]===3?(i.push(s+2),s+=2):s++;if(i.length===0)return e;const r=t-i.length,n=new Uint8Array(r);let a=0;for(s=0;s<r;a++,s++)a===i[0]&&(a++,i.shift()),n[s]=e[a];return n}function su(e){const t=e[0];let i="",s="",r=0,n=0,a=0,o=0,l=0,d=0;if(t===0){for(;ue(e.subarray(d,d+1))!=="\0";)i+=ue(e.subarray(d,d+1)),d+=1;for(i+=ue(e.subarray(d,d+1)),d+=1;ue(e.subarray(d,d+1))!=="\0";)s+=ue(e.subarray(d,d+1)),d+=1;s+=ue(e.subarray(d,d+1)),d+=1,r=K(e,12),n=K(e,16),o=K(e,20),l=K(e,24),d=28}else if(t===1){d+=4,r=K(e,d),d+=4;const h=K(e,d);d+=4;const u=K(e,d);for(d+=4,a=2**32*h+u,Ol(a)||(a=Number.MAX_SAFE_INTEGER,te.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=K(e,d),d+=4,l=K(e,d),d+=4;ue(e.subarray(d,d+1))!=="\0";)i+=ue(e.subarray(d,d+1)),d+=1;for(i+=ue(e.subarray(d,d+1)),d+=1;ue(e.subarray(d,d+1))!=="\0";)s+=ue(e.subarray(d,d+1)),d+=1;s+=ue(e.subarray(d,d+1)),d+=1}const c=e.subarray(d,e.byteLength);return{schemeIdUri:i,value:s,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:c}}function ru(e,...t){const i=t.length;let s=8,r=i;for(;r--;)s+=t[r].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(e,4),r=0,s=8;r<i;r++)n.set(t[r],s),s+=t[r].byteLength;return n}function nu(e,t,i){if(e.byteLength!==16)throw new RangeError("Invalid system id");let s,r;s=0,r=new Uint8Array;let n;s>0?(n=new Uint8Array(4),t.length>0&&new DataView(n.buffer).setUint32(0,t.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),ru([112,115,115,104],new Uint8Array([s,0,0,0]),e,n,r,a,i)}function au(e){const t=[];if(e instanceof ArrayBuffer){const i=e.byteLength;let s=0;for(;s+32<i;){const r=ou(new DataView(e,s));t.push(r),s+=r.size}}return t}function ou(e){const t=e.getUint32(0),i=e.byteOffset,s=e.byteLength;if(s<t)return{offset:i,size:s};if(e.getUint32(4)!==1886614376)return{offset:i,size:t};const r=e.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:i,size:t};const n=e.buffer,a=ye(new Uint8Array(n,i+12,16));let o=null,l=null,d=0;if(r===0)d=28;else{const h=e.getUint32(28);if(!h||s<32+h*16)return{offset:i,size:t};o=[];for(let u=0;u<h;u++)o.push(new Uint8Array(n,i+32+u*16,16));d=32+h*16}if(!d)return{offset:i,size:t};const c=e.getUint32(d);return t-32<c?{offset:i,size:t}:(l=new Uint8Array(n,i+d+4,c),{version:r,systemId:a,kids:o,data:l,offset:i,size:t})}function Hs(e,t){const i=ct[t];return!!i&&!!i[e.slice(0,4)]}function Ut(e,t,i=!0){return!e.split(",").some(s=>!Ws(s,t,i))}function Ws(e,t,i=!0){var s;const r=Ye(i);return(s=r?.isTypeSupported(Bt(e,t)))!=null?s:!1}function Bt(e,t){return`${t}/mp4;codecs=${e}`}function Ka(e){if(e){const t=e.substring(0,4);return ct.video[t]}return 2}function Li(e){const t=xr();return e.split(",").reduce((i,s)=>{const r=t&&Ai(s)?9:ct.video[s];return r?(r*2+i)/(i?3:2):(ct.audio[s]+i)/(i?2:1)},0)}function lu(e,t=!0){if(zi[e])return zi[e];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let r=0;r<i.length;r++){var s;if(Ws(i[r],"audio",t))return zi[e]=i[r],i[r];if(i[r]==="mp3"&&(s=Ye(t))!=null&&s.isTypeSupported("audio/mpeg"))return""}return e}function Ri(e,t=!0){return e.replace(Gl,i=>lu(i.toLowerCase(),t))}function du(e,t){const i=[];if(e){const s=e.split(",");for(let r=0;r<s.length;r++)Hs(s[r],"video")||i.push(s[r])}return t&&i.push(t),i.join(",")}function Di(e,t){if(e&&(e.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e)!==-1)&&(Ha(e,"audio")||Ha(e,"video")))return e;if(t){const i=t.split(",");if(i.length>1){if(e){for(let s=i.length;s--;)if(i[s].substring(0,4)===e.substring(0,4))return i[s]}return i[0]}}return t||e}function Ha(e,t){return Hs(e,t)&&Ws(e,t)}function cu(e){const t=e.split(",");for(let i=0;i<t.length;i++){const s=t[i].split(".");s.length>2&&s[0]==="avc1"&&(t[i]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return t.join(",")}function hu(e){if(e.startsWith("av01.")){const t=e.split("."),i=["0","111","01","01","01","0"];for(let s=t.length;s>4&&s<10;s++)t[s]=i[s-4];return t.join(".")}return e}function Wa(e){const t=Ye(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function js(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}function ja(e,t){return{supported:!1,configurations:t,decodingInfoResults:[Kl],error:e}}function uu(e,t,i,s,r,n){const a=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=n?.audioCodec,d=n?.channels,c=d?parseInt(d):l?1/0:2;let h=null;if(o!=null&&o.length)try{o.length===1&&o[0]?h=t.groups[o[0]].channels:h=o.reduce((u,f)=>{if(f){const m=t.groups[f];if(!m)throw new Error(`Audio track group ${f} not found`);Object.keys(m.channels).forEach(g=>{u[g]=(u[g]||0)+m.channels[g]})}return u},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(u=>Ai(u))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(s,30)||e.videoRange!=="SDR"&&e.videoRange!==i||e.bitrate>Math.max(r,8e6))||!!h&&N(c)&&Object.keys(h).some(u=>parseInt(u)>c)}function Ya(e,t,i,s={}){const r=e.videoCodec;if(!r&&!e.audioCodec||!i)return Promise.resolve(Mr);const n=[],a=fu(e),o=a.length,l=gu(e,t,o>0),d=l.length;for(let c=o||1*d||1;c--;){const h={type:"media-source"};if(o&&(h.video=a[c%o]),d){h.audio=l[c%d];const u=h.audio.bitrate;h.video&&u&&(h.video.bitrate-=u)}n.push(h)}if(r){const c=navigator.userAgent;if(r.split(",").some(h=>Ai(h))&&xr())return Promise.resolve(ja(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${c})`),n))}return Promise.all(n.map(c=>{const h=pu(c);return s[h]||(s[h]=i.decodingInfo(c))})).then(c=>({supported:!c.some(h=>!h.supported),configurations:n,decodingInfoResults:c})).catch(c=>({supported:!1,configurations:n,decodingInfoResults:[],error:c}))}function fu(e){var t;const i=(t=e.videoCodec)==null?void 0:t.split(","),s=za(e),r=e.width||640,n=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return i?i.map(l=>{const d={contentType:Bt(hu(l),"video"),width:r,height:n,bitrate:s,framerate:a};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function gu(e,t,i){var s;const r=(s=e.audioCodec)==null?void 0:s.split(","),n=za(e);return r&&e.audioGroups?e.audioGroups.reduce((a,o)=>{var l;const d=o?(l=t.groups[o])==null?void 0:l.tracks:null;return d?d.reduce((c,h)=>{if(h.groupId===o){const u=parseFloat(h.channels||"");r.forEach(f=>{const m={contentType:Bt(f,"audio"),bitrate:i?mu(f,n):n};u&&(m.channels=""+u),c.push(m)})}return c},a):a},[]):[]}function mu(e,t){if(t<=1)return 1;let i=128e3;return e==="ec-3"?i=768e3:e==="ac-3"&&(i=64e4),Math.min(t/2,i)}function za(e){return Math.ceil(Math.max(e.bitrate*.9,e.averageBitrate)/1e3)*1e3||1}function pu(e){let t="";const{audio:i,video:s}=e;if(s){const r=js(s.contentType);t+=`${r}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(i){const r=js(i.contentType);t+=`${s?"_":""}${r}_c${i.channels}`}return t}function yu(e){return qi.indexOf(e)>-1}function vu(e){return!!e&&qt.indexOf(e)>-1}function qa(e){const{canSkipUntil:t,canSkipDateRanges:i,age:s}=e,r=s<t/2;return t&&r?i?Dt.v2:Dt.Yes:Dt.No}function Xa(e,t){return!t||!e?!1:e.indexOf(t)!==-1}function Eu(){if(typeof matchMedia=="function"){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return e.matches===!0}return!1}function Tu(e,t){let i=!1,s=[];if(e&&(i=e!=="SDR",s=[e]),t){s=t.allowedVideoRanges||qt.slice(0);const r=s.join("")!=="SDR"&&!t.videoCodec;i=t.preferHDR!==void 0?t.preferHDR:r&&Eu(),i||(s=["SDR"])}return{preferHDR:i,allowedVideoRanges:s}}function Su(e,t,i,s,r){const n=Object.keys(e),a=s?.channels,o=s?.audioCodec,l=r?.videoCodec,d=a&&parseInt(a)===2;let c=!1,h=!1,u=1/0,f=1/0,m=1/0,g=1/0,y=0,v=[];const{preferHDR:E,allowedVideoRanges:T}=Tu(t,r);for(let I=n.length;I--;){const D=e[n[I]];c||(c=D.channels[2]>0),u=Math.min(u,D.minHeight),f=Math.min(f,D.minFramerate),m=Math.min(m,D.minBitrate),T.filter(P=>D.videoRanges[P]>0).length>0&&(h=!0)}u=N(u)?u:0,f=N(f)?f:0;const S=Math.max(1080,u),A=Math.max(30,f);m=N(m)?m:i,i=Math.max(m,i),h||(t=void 0);const b=n.length>1;return{codecSet:n.reduce((I,D)=>{const P=e[D];if(D===I)return I;if(v=h?T.filter(w=>P.videoRanges[w]>0):[],b){if(P.minBitrate>i)return Ue(D,`min bitrate of ${P.minBitrate} > current estimate of ${i}`),I;if(!P.hasDefaultAudio)return Ue(D,"no renditions with default or auto-select sound found"),I;if(o&&D.indexOf(o.substring(0,4))%5!==0)return Ue(D,`audio codec preference "${o}" not found`),I;if(a&&!d){if(!P.channels[a])return Ue(D,`no renditions with ${a} channel sound found (channels options: ${Object.keys(P.channels)})`),I}else if((!o||d)&&c&&P.channels[2]===0)return Ue(D,"no renditions with stereo sound found"),I;if(P.minHeight>S)return Ue(D,`min resolution of ${P.minHeight} > maximum of ${S}`),I;if(P.minFramerate>A)return Ue(D,`min framerate of ${P.minFramerate} > maximum of ${A}`),I;if(!v.some(w=>P.videoRanges[w]>0))return Ue(D,`no variants with VIDEO-RANGE of ${ne(v)} found`),I;if(l&&D.indexOf(l.substring(0,4))%5!==0)return Ue(D,`video codec preference "${l}" not found`),I;if(P.maxScore<y)return Ue(D,`max score of ${P.maxScore} < selected max of ${y}`),I}return I&&(Li(D)>=Li(I)||P.fragmentError>e[I].fragmentError)?I:(g=P.minIndex,y=P.maxScore,D)},void 0),videoRanges:v,preferHDR:E,minFramerate:f,minBitrate:m,minIndex:g}}function Ue(e,t){te.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function Qa(e){return e.reduce((t,i)=>{let s=t.groups[i.groupId];s||(s=t.groups[i.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(i);const r=i.channels||"2";return s.channels[r]=(s.channels[r]||0)+1,s.hasDefault=s.hasDefault||i.default,s.hasAutoSelect=s.hasAutoSelect||i.autoselect,s.hasDefault&&(t.hasDefaultAudio=!0),s.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function bu(e,t,i,s){return e.slice(i,s+1).reduce((r,n,a)=>{if(!n.codecSet)return r;const o=n.audioGroups;let l=r[n.codecSet];l||(r[n.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,n.bitrate);const d=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,d),l.minFramerate=Math.min(l.minFramerate,n.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,n.score),l.fragmentError+=n.fragmentError,l.videoRanges[n.videoRange]=(l.videoRanges[n.videoRange]||0)+1,o&&o.forEach(c=>{if(!c)return;const h=t.groups[c];h&&(l.hasDefaultAudio=l.hasDefaultAudio||t.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(h.channels).forEach(u=>{l.channels[u]=(l.channels[u]||0)+h.channels[u]}))}),r},{})}function Za(e){if(!e)return e;const{lang:t,assocLang:i,characteristics:s,channels:r,audioCodec:n}=e;return{lang:t,assocLang:i,characteristics:s,channels:r,audioCodec:n}}function Be(e,t,i){if("attrs"in e){const s=t.indexOf(e);if(s!==-1)return s}for(let s=0;s<t.length;s++){const r=t[s];if(at(e,r,i))return s}return-1}function at(e,t,i){const{groupId:s,name:r,lang:n,assocLang:a,default:o}=e,l=e.forced;return(s===void 0||t.groupId===s)&&(r===void 0||t.name===r)&&(n===void 0||Iu(n,t.lang))&&(n===void 0||t.assocLang===a)&&(o===void 0||t.default===o)&&(l===void 0||t.forced===l)&&(!("characteristics"in e)||Au(e.characteristics||"",t.characteristics))&&(i===void 0||i(e,t))}function Iu(e,t="--"){return e.length===t.length?e===t:e.startsWith(t)||t.startsWith(e)}function Au(e,t=""){const i=e.split(","),s=t.split(",");return i.length===s.length&&!i.some(r=>s.indexOf(r)===-1)}function ot(e,t){const{audioCodec:i,channels:s}=e;return(i===void 0||(t.audioCodec||"").substring(0,4)===i.substring(0,4))&&(s===void 0||s===(t.channels||"2"))}function Lu(e,t,i,s,r){const n=t[s],a=t.reduce((h,u,f)=>{const m=u.uri;return(h[m]||(h[m]=[])).push(f),h},{})[n.uri];a.length>1&&(s=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,d=n.codecSet.substring(0,4),c=Ja(t,s,h=>{if(h.videoRange!==o||h.frameRate!==l||h.codecSet.substring(0,4)!==d)return!1;const u=h.audioGroups;return Be(e,i.filter(f=>!u||u.indexOf(f.groupId)!==-1),r)>-1});return c>-1?c:Ja(t,s,h=>{const u=h.audioGroups;return Be(e,i.filter(f=>!u||u.indexOf(f.groupId)!==-1),r)>-1})}function Ja(e,t,i){for(let s=t;s>-1;s--)if(i(e[s]))return s;for(let s=t+1;s<e.length;s++)if(i(e[s]))return s;return-1}function wi(e,t){var i;return!!e&&e!==((i=t.loadLevelObj)==null?void 0:i.uri)}function Ru(e,t,i){if(t===null||!Array.isArray(e)||!e.length||!N(t)||t<(e[0].programDateTime||0)||t>=(e[e.length-1].endProgramDateTime||0))return null;for(let s=0;s<e.length;++s){const r=e[s];if(wu(t,i,r))return r}return null}function lt(e,t,i=0,s=0,r=.005){let n=null;if(e){n=t[1+e.sn-t[0].sn]||null;const o=e.endDTS-i;o>0&&o<15e-7&&(i+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else i===0&&t[0].start===0&&(n=t[0]);if(n&&((!e||e.level===n.level)&&eo(i,s,n)===0||Du(n,e,Math.min(r,s))))return n;const a=Fr.search(t,eo.bind(null,i,s));return a&&(a!==e||!n)?a:n}function Du(e,t,i){if(t&&t.start===0&&t.level<e.level&&(t.endPTS||0)>0){const s=t.tagList.reduce((r,n)=>(n[0]==="INF"&&(r+=parseFloat(n[1])),r),i);return e.start<=s}return!1}function eo(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;const s=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-s<=e?1:i.start-s>e&&i.start?-1:0}function wu(e,t,i){const s=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0))*1e3;return(i.endProgramDateTime||0)-s>e}function to(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){let s=e.fragments;const{fragmentHint:r}=e;r&&(s=s.concat(r));let n;return Fr.search(s,a=>a.cc<t?1:a.cc>t?-1:(n=a,a.end<=i?1:a.start>i?-1:0)),n||null}return null}function Pi(e){switch(e.details){case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_TIMEOUT:case L.LEVEL_LOAD_TIMEOUT:case L.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function io(e){return e.details.startsWith("key")}function so(e){return io(e)&&!!e.frag&&!e.frag.decryptdata}function ro(e,t){const i=Pi(t);return e.default[`${i?"timeout":"error"}Retry`]}function Ys(e,t){const i=e.backoff==="linear"?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function no(e){return ie(ie({},e),{errorRetry:null,timeoutRetry:null})}function _i(e,t,i,s){if(!e)return!1;const r=s?.code,n=t<e.maxNumRetry&&(Pu(r)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,s,n):n}function Pu(e){return zs(e)||!!e&&(e<400||e>499)}function zs(e){return e===0&&navigator.onLine===!1}function Tt(e){const t={action:ce.DoNothing,flags:Te.None};return e&&(t.resolved=!0),t}function ki(e){var t,i,s;return e.buffered&&!!(e.body.gap||(t=e.range.video)!=null&&t.partial||(i=e.range.audio)!=null&&i.partial||(s=e.range.audiovideo)!=null&&s.partial)}function St(e){return`${e.type}_${e.level}_${e.sn}`}function ao(e,t){return e.filter(i=>{const s=t(i);return s||i.clearElementaryStreamInfo(),s})}function _u(e){const t=e.byteLength,i=t&&new DataView(e.buffer).getUint8(t-1);return i?e.slice(0,t-i):e}function ku(e){switch(e){case Xe.cbc:return"AES-CBC";case Xe.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}function oo(e,t=null){const i=t||e,s={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},r=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(N(r)&&N(n)){var a;let o=r,l=n;if(e.sn==="initSegment"&&Cu((a=e.decryptdata)==null?void 0:a.method)){const d=n-r;d%16&&(l=n+(16-d%16)),r!==0&&(s.resetIV=!0,o=r-16)}s.rangeStart=o,s.rangeEnd=l}return s}function lo(e,t){const i=new Error(`GAP ${e.gap?"tag":"attribute"} found`),s={type:$.MEDIA_ERROR,details:L.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(s.part=t),(t||e).stats.aborted=!0,new Ve(s)}function Cu(e){return e==="AES-128"||e==="AES-256"}function Ci(){return{start:0,executeStart:0,executeEnd:0,end:0}}function co(e){return Gr.test(e)}function qs(e,t){if(e.variableList!==null||e.hasVariableRefs){const i=e.variableList;return t.replace(Gr,s=>{const r=s.substring(2,s.length-1),n=i?.[r];return n===void 0?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),s):n})}return t}function ho(e,t,i){let s=e.variableList;s||(e.variableList=s={});let r,n;if("QUERYPARAM"in t){r=t.QUERYPARAM;try{const a=new self.URL(i).searchParams;if(a.has(r))n=a.get(r);else throw new Error(`"${r}" does not match any query parameter in URI: "${i}"`)}catch(a){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else r=t.NAME,n=t.VALUE;r in s?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):s[r]=n||""}function xu(e,t,i){const s=t.IMPORT;if(i&&s in i){let r=e.variableList;r||(e.variableList=r={}),r[s]=i[s]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}function Mu(e){return e!=="ID"&&e!=="CLASS"&&e!=="CUE"&&e!=="START-DATE"&&e!=="DURATION"&&e!=="END-DATE"&&e!=="END-ON-NEXT"}function Ou(e){return e==="SCTE35-OUT"||e==="SCTE35-IN"||e==="SCTE35-CMD"}function xi(e,t){return e.length===t.length?!e.some((i,s)=>i!==t[s]):!1}function uo(e,t){return!e&&!t?!0:!e||!t?!1:xi(e,t)}function bt(e){return e==="AES-128"||e==="AES-256"||e==="AES-256-CTR"}function Xs(e){switch(e){case"AES-128":case"AES-256":return Xe.cbc;case"AES-256-CTR":return Xe.ctr;default:throw new Error(`invalid full segment method ${e}`)}}function Qs(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}function Zs(e){return Uint8Array.from(unescape(encodeURIComponent(e)),t=>t.charCodeAt(0))}function Fu(e){const t=Zs(e).subarray(0,16),i=new Uint8Array(16);return i.set(t,16-t.length),i}function fo(e){const t=function(s,r,n){const a=s[r];s[r]=s[n],s[n]=a};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function go(e){const t=e.split(":");let i=null;if(t[0]==="data"&&t.length===2){const s=t[1].split(";"),r=s[s.length-1].split(",");if(r.length===2){const n=r[0]==="base64",a=r[1];n?(s.splice(-1,1),i=Qs(a)):i=Fu(a)}}return i}function Mi(e){switch(e){case fe.FAIRPLAY:return ae.FAIRPLAY;case fe.PLAYREADY:return ae.PLAYREADY;case fe.WIDEVINE:return ae.WIDEVINE;case fe.CLEARKEY:return ae.CLEARKEY}}function Js(e){switch(e){case ae.FAIRPLAY:return fe.FAIRPLAY;case ae.PLAYREADY:return fe.PLAYREADY;case ae.WIDEVINE:return fe.WIDEVINE;case ae.CLEARKEY:return fe.CLEARKEY}}function $t(e){const{drmSystems:t,widevineLicenseUrl:i}=e,s=t?[ae.FAIRPLAY,ae.WIDEVINE,ae.PLAYREADY,ae.CLEARKEY].filter(r=>!!t[r]):[];return!s[ae.WIDEVINE]&&i&&s.push(ae.WIDEVINE),s}function Nu(e,t,i,s){let r;switch(e){case ae.FAIRPLAY:r=["cenc","sinf"];break;case ae.WIDEVINE:case ae.PLAYREADY:r=["cenc"];break;case ae.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return Uu(r,t,i,s)}function Uu(e,t,i,s){return[{initDataTypes:e,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:t.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:i.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function Bu(e){var t;return!!e&&(e.sessionType==="persistent-license"||!!((t=e.sessionTypes)!=null&&t.some(i=>i==="persistent-license")))}function mo(e){const t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),s=i.substring(i.indexOf("<"),i.length),r=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(r){const n=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(n){const a=Qs(n).subarray(0,16);return fo(a),a}}return null}function $u(e){const t=e?.[fe.WIDEVINE];return t?t.keyId:null}function po(e){const t=e?.[fe.PLAYREADY];if(t){const i=go(t.uri);if(i)return mo(i)}return null}function Gu(e){const t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}function yo(e,t){let i=e.length;if(!i)if(t.hasProgramDateTime){const o=t.fragments[t.fragments.length-1];e.push(o),i++}else return;const s=e[i-1],r=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let o=n.length;o--;){const l=t.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=s.ref;for(let c=i;c--;){var a;if(((a=e[c])==null?void 0:a.sn)<t.startSN)break;const h=Vu(t,d,e,c,r);if(h!==-1){l.tagAnchor=t.fragments[h].ref;break}}}}function Vu(e,t,i,s,r){const n=i[s];if(n){const o=n.programDateTime;if(t>=o||s===0){var a;if(t<=o+((((a=i[s+1])==null?void 0:a.start)||r)-n.start)*1e3){const l=i[s].sn-e.startSN;if(l<0)return-1;const d=e.fragments;if(d.length>i.length){const c=(i[s+1]||d[d.length-1]).sn-e.startSN;for(let h=c;h>l;h--){const u=d[h].programDateTime;if(t>=u&&t<u+d[h].duration*1e3)return h}}return l}}}return-1}function vo(e,t,i){var s,r;const n=new oe(e,i),a=(s=n.METHOD)!=null?s:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,c=(r=n.KEYFORMAT)!=null?r:"identity";return o&&n.IV&&!l&&te.error(`Invalid IV: ${n.IV}`),new wt(a,o?ft.resolve(o,t):"",c,(d||"1").split("/").map(Number).filter(Number.isFinite),l,n.KEYID)}function Eo(e){const t=new oe(e).decimalFloatingPoint("TIME-OFFSET");return N(t)?t:null}function To(e,t){let i=(e||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const r=i.filter(n=>Hs(n,s));r.length&&(t[`${s}Codec`]=r.map(n=>n.split("/")[0]).join(","),i=i.filter(n=>r.indexOf(n)===-1))}),t.unknownCodecs=i}function So(e,t,i){const s=t[i];s&&(e[i]=s)}function Ku(e,t){let i=e[t];for(let s=t;s--;){const r=e[s];if(!r)return;r.programDateTime=i.programDateTime-r.duration*1e3,i=r}}function er(e,t,i){e.rawProgramDateTime?i.push(e):t!=null&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function bo(e,t,i,s){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",s&&(e.levelkeys=s),e.initSegment=null}function Io(e,t,i){e.levelkeys=t;const{encryptedFragments:s}=i;(!s.length||s[s.length-1].levelkeys!==t)&&Object.keys(t).some(r=>t[r].isCommonEncryption)&&s.push(e)}function ze(e,t,i){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${i[0]})`)}function Ao(e,t,i){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${i[0]})`)}function tr(e,t){const i=t.startPTS;if(N(i)){let s=0,r;t.sn>e.sn?(s=i-e.start,r=e):(s=e.start-i,r=t),r.duration!==s&&r.setDuration(s)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function Lo(e,t,i,s,r,n,a){s-i<=0&&(a.warn("Fragment should have a positive duration",t),s=i+t.duration,n=r+t.duration);let o=i,l=s;const d=t.startPTS,c=t.endPTS;if(N(d)){const y=Math.abs(d-i);e&&y>e.totalduration?a.warn(`media timestamps and playlist times differ by ${y}s for level ${t.level} ${e.url}`):N(t.deltaPTS)?t.deltaPTS=Math.max(y,t.deltaPTS):t.deltaPTS=y,o=Math.max(i,d),i=Math.min(i,d),r=t.startDTS!==void 0?Math.min(r,t.startDTS):r,l=Math.min(s,c),s=Math.max(s,c),n=t.endDTS!==void 0?Math.max(n,t.endDTS):n}const h=i-t.start;t.start!==0&&t.setStart(i),t.setDuration(s-t.start),t.startPTS=i,t.maxStartPTS=o,t.startDTS=r,t.endPTS=s,t.minEndPTS=l,t.endDTS=n;const u=t.sn;if(!e||u<e.startSN||u>e.endSN)return 0;let f;const m=u-e.startSN,g=e.fragments;for(g[m]=t,f=m;f>0;f--)tr(g[f],g[f-1]);for(f=m;f<g.length-1;f++)tr(g[f],g[f+1]);return e.fragmentHint&&tr(g[g.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,h}function Hu(e,t,i){if(e===t)return;let s=null;const r=e.fragments;for(let c=r.length-1;c>=0;c--){const h=r[c].initSegment;if(h){s=h;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let n;Yu(e,t,(c,h,u,f)=>{if((!t.startCC||t.skippedSegments)&&h.cc!==c.cc){const m=c.cc-h.cc;for(let g=u;g<f.length;g++)f[g].cc+=m;t.endCC=f[f.length-1].cc}N(c.startPTS)&&N(c.endPTS)&&(h.setStart(h.startPTS=c.startPTS),h.startDTS=c.startDTS,h.maxStartPTS=c.maxStartPTS,h.endPTS=c.endPTS,h.endDTS=c.endDTS,h.minEndPTS=c.minEndPTS,h.setDuration(c.endPTS-c.startPTS),h.duration&&(n=h),t.PTSKnown=t.alignedSliding=!0),c.hasStreams&&(h.elementaryStreams=c.elementaryStreams),h.loader=c.loader,c.hasStats&&(h.stats=c.stats),c.initSegment&&(h.initSegment=c.initSegment,s=c.initSegment)});const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(s&&o.forEach(c=>{var h;c&&(!c.initSegment||c.initSegment.relurl===((h=s)==null?void 0:h.relurl))&&(c.initSegment=s)}),t.skippedSegments){if(t.deltaUpdateFailed=a.some(c=>!c),t.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let c=t.skippedSegments;c--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=Wu(e.dateRanges,t,i));const c=e.fragments.filter(h=>h.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let h=1;h<o.length;h++)o[h].programDateTime===null&&er(o[h],o[h-1],c);yo(c,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var l;const c=Po(e,t.startSN-1);t.startCC=(l=c?.cc)!=null?l:a[0].cc}ju(e.partList,t.partList,(c,h)=>{h.elementaryStreams=c.elementaryStreams,h.stats=c.stats}),n?Lo(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,i):Do(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const d=t.advancedDateTime;if(t.advanced&&d){const c=t.edge;t.driftStart||(t.driftStartTime=d,t.driftStart=c),t.driftEndTime=d,t.driftEnd=c}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=e.requestScheduled)}function Wu(e,t,i){const{dateRanges:s,recentlyRemovedDateranges:r}=t,n=se({},e);r&&r.forEach(o=>{delete n[o]});const a=Object.keys(n).length;return a?(Object.keys(s).forEach(o=>{const l=n[o],d=new Zi(s[o].attr,l);d.isValid?(n[o]=d,l||(d.tagOrder+=a)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ne(s[o].attr)}"`)}),n):s}function ju(e,t,i){if(e&&t){let s=0;for(let r=0,n=e.length;r<=n;r++){const a=e[r],o=t[r+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?i(a,o):s--}}}function Yu(e,t,i){const s=t.skippedSegments,r=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(s?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let d=r;d<=n;d++){const c=l[a+d];let h=o[d];if(s&&!h&&c&&(h=t.fragments[d]=c),c&&h){i(c,h,d,o);const u=c.relurl,f=h.relurl;if(u&&zu(u,f)){t.playlistParsingError=Ro(`media sequence mismatch ${h.sn}:`,e,t,c,h);return}else if(c.cc!==h.cc){t.playlistParsingError=Ro(`discontinuity sequence mismatch (${c.cc}!=${h.cc})`,e,t,c,h);return}}}}function Ro(e,t,i,s,r){return new Error(`${e} ${r.url}
|
|
43
43
|
Playlist starting @${t.startSN}
|
|
44
44
|
${t.m3u8}
|
|
45
45
|
|
|
46
46
|
Playlist starting @${i.startSN}
|
|
47
|
-
${i.m3u8}`)}function Do(e,t,i=!0){const s=t.startSN+t.skippedSegments-e.startSN,r=e.fragments,n=s>=0;let a=0;if(n&&s<r.length)a=r[s].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&i)a=e.fragmentStart+s*t.levelTargetDuration;else if(!t.skippedSegments&&t.fragmentStart===0)a=e.fragmentStart;else return;ir(t,a)}function ir(e,t){if(t){const i=e.fragments;for(let s=e.skippedSegments;s<i.length;s++)i[s].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function Po(e,t=1/0){let i=1e3*e.targetduration;if(e.updated){const s=e.fragments;if(s.length&&i*4>t){const r=s[s.length-1].duration*1e3;r<i&&(i=r)}}else i/=2;return Math.round(i)}function wo(e,t,i){if(!e)return null;let s=e.fragments[t-e.startSN];return s||(s=e.fragmentHint,s&&s.sn===t)?s:t<e.startSN&&i&&i.sn===t?i:null}function _o(e,t,i){return e?ko(e.partList,t,i):null}function ko(e,t,i){if(e)for(let s=e.length;s--;){const r=e[s];if(r.index===i&&r.fragment.sn===t)return r}return null}function Co(e){e.forEach((t,i)=>{var s;(s=t.details)==null||s.fragments.forEach(r=>{r.level=i,r.initSegment&&(r.initSegment.level=i)})})}function zu(e,t){return e!==t&&t?xo(e)!==xo(t):!1}function xo(e){return e.replace(/\?[^?]*$/,"")}function Gt(e,t){for(let s=0,r=e.length;s<r;s++){var i;if(((i=e[s])==null?void 0:i.cc)===t)return e[s]}return null}function qu(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}function Mo(e,t){const i=e.start+t;e.startPTS=i,e.setStart(i),e.endPTS=i+e.duration}function Oo(e,t){const i=t.fragments;for(let s=0,r=i.length;s<r;s++)Mo(i[s],e);t.fragmentHint&&Mo(t.fragmentHint,e),t.alignedSliding=!0}function Xu(e,t){e&&(Fo(t,e),t.alignedSliding||Oi(t,e),!t.alignedSliding&&!t.skippedSegments&&Do(e,t,!1))}function Fo(e,t){if(!qu(t,e))return;const i=Math.min(t.endCC,e.endCC),s=Gt(t.fragments,i),r=Gt(e.fragments,i);!s||!r||(te.log(`Aligning playlist at start of dicontinuity sequence ${i}`),Oo(s.start-r.start,e))}function Oi(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const i=e.fragments,s=t.fragments;if(!i.length||!s.length)return;let r,n;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(r=Gt(s,a),n=Gt(i,a)),(!r||!n)&&(r=s[Math.floor(s.length/2)],n=Gt(i,r.cc)||i[Math.floor(i.length/2)]);const o=r.programDateTime,l=n.programDateTime;!o||!l||Oo((l-o)/1e3-(n.start-r.start),e)}function Ee(e,t,i){Le(e,t,i),e.addEventListener(t,i)}function Le(e,t,i){e.removeEventListener(t,i)}function No(e){return!!e.interstitialsController&&e.enableInterstitialPlayback!==!1}function Qu(e,t){const i=new Uint8Array(t);let s=0;for(let r=0;r<e.length;r++){const n=e[r];i.set(n,s),s+=n.length}return i}function Zu(){return sd||(sd=1,(function(e){var t=Object.prototype.hasOwnProperty,i="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(i=!1));function r(l,d,c){this.fn=l,this.context=d,this.once=c||!1}function n(l,d,c,h,u){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new r(c,h||l,u),m=i?i+d:d;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],f]:l._events[m].push(f):(l._events[m]=f,l._eventsCount++),l}function a(l,d){--l._eventsCount===0?l._events=new s:delete l._events[d]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],c,h;if(this._eventsCount===0)return d;for(h in c=this._events)t.call(c,h)&&d.push(i?h.slice(1):h);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(c)):d},o.prototype.listeners=function(d){var c=i?i+d:d,h=this._events[c];if(!h)return[];if(h.fn)return[h.fn];for(var u=0,f=h.length,m=new Array(f);u<f;u++)m[u]=h[u].fn;return m},o.prototype.listenerCount=function(d){var c=i?i+d:d,h=this._events[c];return h?h.fn?1:h.length:0},o.prototype.emit=function(d,c,h,u,f,m){var g=i?i+d:d;if(!this._events[g])return!1;var y=this._events[g],v=arguments.length,E,T;if(y.fn){switch(y.once&&this.removeListener(d,y.fn,void 0,!0),v){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,c),!0;case 3:return y.fn.call(y.context,c,h),!0;case 4:return y.fn.call(y.context,c,h,u),!0;case 5:return y.fn.call(y.context,c,h,u,f),!0;case 6:return y.fn.call(y.context,c,h,u,f,m),!0}for(T=1,E=new Array(v-1);T<v;T++)E[T-1]=arguments[T];y.fn.apply(y.context,E)}else{var S=y.length,A;for(T=0;T<S;T++)switch(y[T].once&&this.removeListener(d,y[T].fn,void 0,!0),v){case 1:y[T].fn.call(y[T].context);break;case 2:y[T].fn.call(y[T].context,c);break;case 3:y[T].fn.call(y[T].context,c,h);break;case 4:y[T].fn.call(y[T].context,c,h,u);break;default:if(!E)for(A=1,E=new Array(v-1);A<v;A++)E[A-1]=arguments[A];y[T].fn.apply(y[T].context,E)}}return!0},o.prototype.on=function(d,c,h){return n(this,d,c,h,!1)},o.prototype.once=function(d,c,h){return n(this,d,c,h,!0)},o.prototype.removeListener=function(d,c,h,u){var f=i?i+d:d;if(!this._events[f])return this;if(!c)return a(this,f),this;var m=this._events[f];if(m.fn)m.fn===c&&(!u||m.once)&&(!h||m.context===h)&&a(this,f);else{for(var g=0,y=[],v=m.length;g<v;g++)(m[g].fn!==c||u&&!m[g].once||h&&m[g].context!==h)&&y.push(m[g]);y.length?this._events[f]=y.length===1?y[0]:y:a(this,f)}return this},o.prototype.removeAllListeners=function(d){var c;return d?(c=i?i+d:d,this._events[c]&&a(this,c)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,e.exports=o})(ts)),ts.exports}function Ju(){return typeof __HLS_WORKER_BUNDLE__=="function"}function ef(){const e=gt[wt];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(t),s={worker:new self.Worker(i),objectURL:i,clientCount:1};return gt[wt]=s,s}function tf(e){const t=gt[e];if(t)return t.clientCount++,t;const i=new self.URL(e,self.location.href).href,s={worker:new self.Worker(i),scriptURL:i,clientCount:1};return gt[e]=s,s}function sf(e){const t=gt[e||wt];if(t&&t.clientCount--===1){const{worker:i,objectURL:s}=t;delete gt[e||wt],s&&self.URL.revokeObjectURL(s),i.terminate()}}function Uo(e,t){return t+10<=e.length&&e[t]===51&&e[t+1]===68&&e[t+2]===73&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function sr(e,t){return t+10<=e.length&&e[t]===73&&e[t+1]===68&&e[t+2]===51&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function Fi(e,t){let i=0;return i=(e[t]&127)<<21,i|=(e[t+1]&127)<<14,i|=(e[t+2]&127)<<7,i|=e[t+3]&127,i}function Vt(e,t){const i=t;let s=0;for(;sr(e,t);){s+=10;const r=Fi(e,t+6);s+=r,Uo(e,t+10)&&(s+=10),t+=s}if(s>0)return e.subarray(i,i+s)}function rf(e,t,i,s){const r=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=t[i+2],a=n>>2&15;if(a>12){const f=new Error(`invalid ADTS sampling index:${a}`);e.emit(p.ERROR,p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(n>>6&3)+1,l=t[i+3]>>6&3|(n&1)<<2,d="mp4a.40."+o,c=r[a];let h=a;(o===5||o===29)&&(h-=3);const u=[o<<3|(h&14)>>1,(h&1)<<7|l<<3];return te.log(`manifest codec:${s}, parsed codec:${d}, channels:${l}, rate:${c} (ADTS object type:${o} sampling index:${a})`),{config:u,samplerate:c,channelCount:l,codec:d,parsedCodec:d,manifestCodec:s}}function Bo(e,t){return e[t]===255&&(e[t+1]&246)===240}function $o(e,t){return e[t+1]&1?7:9}function rr(e,t){return(e[t+3]&3)<<11|e[t+4]<<3|(e[t+5]&224)>>>5}function nf(e,t){return t+5<e.length}function Ni(e,t){return t+1<e.length&&Bo(e,t)}function af(e,t){return nf(e,t)&&Bo(e,t)&&rr(e,t)<=e.length-t}function of(e,t){if(Ni(e,t)){const i=$o(e,t);if(t+i>=e.length)return!1;const s=rr(e,t);if(s<=i)return!1;const r=t+s;return r===e.length||Ni(e,r)}return!1}function Go(e,t,i,s,r){if(!e.samplerate){const n=rf(t,i,s,r);if(!n)return;se(e,n)}}function Vo(e){return 1024*9e4/e}function lf(e,t){const i=$o(e,t);if(t+i<=e.length){const s=rr(e,t)-i;if(s>0)return{headerLength:i,frameLength:s}}}function Ko(e,t,i,s,r){const n=s+r*Vo(e.samplerate),a=lf(t,i);let o;if(a){const{frameLength:d,headerLength:c}=a,h=c+d,u=Math.max(0,i+h-t.length);u?(o=new Uint8Array(h-c),o.set(t.subarray(i+c,t.length),0)):o=t.subarray(i+c,i+h);const f={unit:o,pts:n};return u||e.samples.push(f),{sample:f,length:h,missing:u}}const l=t.length-i;return o=new Uint8Array(l),o.set(t.subarray(i,t.length),0),{sample:{unit:o,pts:n},length:l,missing:-1}}function df(e,t){return sr(e,t)&&Fi(e,t+6)+10<=e.length-t}function cf(e){return e instanceof ArrayBuffer?e:e.byteOffset==0&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function nr(e,t=0,i=1/0){return hf(e,t,i,Uint8Array)}function hf(e,t,i,s){const r=uf(e);let n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);const a=ff(e)?e.byteOffset:0,o=(a+e.byteLength)/n,l=(a+t)/n,d=Math.floor(Math.max(0,Math.min(l,o)));return new s(r,d,Math.floor(Math.min(d+Math.max(i,0),o))-d)}function uf(e){return e instanceof ArrayBuffer?e:e.buffer}function ff(e){return e&&e.buffer instanceof ArrayBuffer&&e.byteLength!==void 0&&e.byteOffset!==void 0}function gf(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null},i=3;if(e.size<2)return;if(e.data[0]!==i){console.log("Ignore frame with unrecognized character encoding");return}const s=e.data.subarray(1).indexOf(0);if(s===-1)return;const r=De(nr(e.data,1,s)),n=e.data[2+s],a=e.data.subarray(3+s).indexOf(0);if(a===-1)return;const o=De(nr(e.data,3+s,a));let l;return r==="-->"?l=De(nr(e.data,4+s+a)):l=cf(e.data.subarray(4+s+a)),t.mimeType=r,t.pictureType=n,t.description=o,t.data=l,t}function mf(e){if(e.size<2)return;const t=De(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}function pf(e){if(e.size<2)return;if(e.type==="TXXX"){let i=1;const s=De(e.data.subarray(i),!0);i+=s.length+1;const r=De(e.data.subarray(i));return{key:e.type,info:s,data:r}}const t=De(e.data.subarray(1));return{key:e.type,info:"",data:t}}function yf(e){if(e.type==="WXXX"){if(e.size<2)return;let i=1;const s=De(e.data.subarray(i),!0);i+=s.length+1;const r=De(e.data.subarray(i));return{key:e.type,info:s,data:r}}const t=De(e.data);return{key:e.type,info:"",data:t}}function vf(e){return e.type==="PRIV"?mf(e):e.type[0]==="W"?yf(e):e.type==="APIC"?gf(e):pf(e)}function Ef(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=Fi(e,4),s=10;return{type:t,size:i,data:e.subarray(s,s+i)}}function Ho(e){let t=0;const i=[];for(;sr(e,t);){const s=Fi(e,t+6);e[t+5]>>6&1&&(t+=Jt),t+=Jt;const r=t+s;for(;t+rd<r;){const n=Ef(e.subarray(t)),a=vf(n);a&&i.push(a),t+=n.size+Jt}Uo(e,t)&&(t+=Jt)}return i}function Wo(e){return e&&e.key==="PRIV"&&e.info==="com.apple.streaming.transportStreamTimestamp"}function Tf(e){if(e.data.byteLength===8){const t=new Uint8Array(e.data),i=t[3]&1;let s=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return s/=45,i&&(s+=4772185884e-2),Math.round(s)}}function ar(e){const t=Ho(e);for(let i=0;i<t.length;i++){const s=t[i];if(Wo(s))return Tf(s)}}function $e(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}function jo(e,t,i,s,r){if(i+24>t.length)return;const n=Yo(t,i);if(n&&i+n.frameLength<=t.length){const a=s+r*(n.samplesPerFrame*9e4/n.sampleRate),o={unit:t.subarray(i,i+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function Yo(e,t){const i=e[t+1]>>3&3,s=e[t+1]>>1&3,r=e[t+2]>>4&15,n=e[t+2]>>2&3;if(i!==1&&r!==0&&r!==15&&n!==3){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=ad[(i===3?3-s:s===3?3:4)*14+r-1]*1e3,d=od[(i===3?0:i===2?1:2)*3+n],c=o===3?1:2,h=ld[i][s],u=dd[s],f=h*8*u,m=Math.floor(h*l/d+a)*u;if(ei===null){const g=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ei=g?parseInt(g[1]):0}return ei&&ei<=87&&s===2&&l>=224e3&&o===0&&(e[t+3]=e[t+3]|128),{sampleRate:d,channelCount:c,frameLength:m,samplesPerFrame:f}}}function or(e,t){return e[t]===255&&(e[t+1]&224)===224&&(e[t+1]&6)!==0}function zo(e,t){return t+1<e.length&&or(e,t)}function Sf(e,t){return or(e,t)&&4<=e.length-t}function qo(e,t){if(t+1<e.length&&or(e,t)){const s=Yo(e,t);let r=4;s!=null&&s.frameLength&&(r=s.frameLength);const n=t+r;return n===e.length||zo(e,n)}return!1}function Xo(e,t,i,s,r){if(i+8>t.length||t[i]!==11||t[i+1]!==119)return-1;const n=t[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=t[i+4]&63,l=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][o*3+n]*2;if(i+l>t.length)return-1;const d=t[i+6]>>5;let c=0;d===2?c+=2:(d&1&&d!==1&&(c+=2),d&4&&(c+=2));const h=(t[i+6]<<8|t[i+7])>>12-c&1,u=[2,1,2,3,3,4,4,5][d]+h,f=t[i+5]>>3,m=t[i+5]&7,g=new Uint8Array([n<<6|f<<1|m>>2,(m&3)<<6|d<<3|h<<2|o>>4,o<<4&224]),y=s+r*(1536/a*9e4),v=t.subarray(i,i+l);return e.config=g,e.channelCount=u,e.samplerate=a,e.samples.push({unit:v,pts:y}),l}function Qo(e,t){return N(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}function lr(e,t){return((e[t+1]&31)<<8)+e[t+2]}function bf(e,t){return(e[t+10]&31)<<8|e[t+11]}function If(e,t,i,s,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(e[t+1]&15)<<8|e[t+2],l=t+3+o-4,d=(e[t+10]&15)<<8|e[t+11];for(t+=12+d;t<l;){const c=lr(e,t),h=(e[t+3]&15)<<8|e[t+4];switch(e[t]){case 207:if(!s){cr("ADTS AAC",n);break}case 15:a.audioPid===-1&&(a.audioPid=c);break;case 21:a.id3Pid===-1&&(a.id3Pid=c);break;case 219:if(!s){cr("H.264",n);break}case 27:a.videoPid===-1&&(a.videoPid=c);break;case 3:case 4:!i.mpeg&&!i.mp3?n.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=c,a.segmentAudioCodec="mp3");break;case 193:if(!s){cr("AC-3",n);break}case 129:i.ac3?a.audioPid===-1&&(a.audioPid=c,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&h>0){let u=t+5,f=h;for(;f>2;){e[u]===106&&(i.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=c,a.segmentAudioCodec="ac3"));const m=e[u+1]+2;u+=m,f-=m}}break;case 194:case 135:return dr(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:a.videoPid===-1&&(a.videoPid=c,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}t+=h+5}return a}function dr(e,t,i,s){s.warn(`parsing error: ${t.message}`),e.emit(p.ERROR,p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function cr(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function It(e,t){let i=0,s,r,n,a,o;const l=e.data;if(!e||e.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=Ce(l[0],l[1]),l.splice(1,1);if(s=l[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(r=(s[4]<<8)+s[5],r&&r>e.size-6)return null;const d=s[7];d&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,d&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,a-o>60*9e4&&(t.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),n=s[8];let c=n+9;if(e.size<=c)return null;e.size-=c;const h=new Uint8Array(e.size);for(let u=0,f=l.length;u<f;u++){s=l[u];let m=s.byteLength;if(c)if(c>m){c-=m;continue}else s=s.subarray(c),m-=c,c=0;h.set(s,i),i+=m}return r&&(r-=n+3),{data:h,pts:a,dts:o,len:r}}return null}function hr(e,t,i=1,s=!1){const r=e*t*i;return s?Math.round(r):r}function Af(e,t,i=1,s=!1){return hr(e,t,1/i,s)}function Kt(e,t=!1){return hr(e,1e3,1/qr,t)}function Lf(e,t=1){return hr(e,qr,1/t)}function Zo(e){const{baseTime:t,timescale:i,trackId:s}=e;return`${t/i} (${t}/${i}) trackId: ${s}`}function Jo(e,t,i,s){return{duration:t,size:i,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}function Pe(e,t){let i;if(t===null)return e;for(t<e?i=-8589934592:i=8589934592;Math.abs(e-t)>4294967296;)e+=i;return e}function Rf(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}function el(e,t,i,s){const r=e.samples.length;if(!r)return;const n=e.inputTimeScale;for(let o=0;o<r;o++){const l=e.samples[o];l.pts=Pe(l.pts-i.baseTime*n/i.timescale,t*n)/n,l.dts=Pe(l.dts-s.baseTime*n/s.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function tl(e,t,i){const s=e.samples.length;if(!s)return;const r=e.inputTimeScale;for(let a=0;a<s;a++){const o=e.samples[a];o.pts=Pe(o.pts-i.baseTime*r/i.timescale,t*r)/r}e.samples.sort((a,o)=>a.pts-o.pts);const n=e.samples;return e.samples=[],{samples:n}}function Ui(e,t,i=!1){return e?.start!==void 0?(e.start+(i?e.duration:0))/e.timescale:t}function Df(e,t,i,s){if(e===null)return!0;const r=Math.max(s,1),n=t-e.baseTime/e.timescale;return Math.abs(n-i)>r}function il(e,t,i){const s=e.codec;return s&&s.length>4?s:t===re.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?Ri(s,!1):(i.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(i.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}function Pf(e,t){let i=null;return e.byteLength>0&&t?.key!=null&&t.iv!==null&&t.method!=null&&(i=t),i}function Ht(e){return"then"in e&&e.then instanceof Function}function sl(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!Wt(e[i].attrs,t[i].attrs))return!1;return!0}function Wt(e,t,i){const s=e["STABLE-RENDITION-ID"];return s&&!i?s===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>e[r]!==t[r])}function ur(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}function rl(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach(i=>{e.removeChild(i)})}function wf(e,t){const i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}function fr(e){return e==="audio"?1:0}function _f(e){return Array.isArray(e)?JSON.stringify(e):e instanceof Map?"Map{}":e instanceof Set?"Set{}":typeof e=="object"?JSON.stringify(e):String(e)}function kf(e,t,i,s){return new Error(`failed to ${e} "${_f(t)}" as ${i}`,{cause:s})}function Ge(e,t,i){return kf("serialize",e,t,i)}function Cf(e){if(typeof e!="boolean")throw Ge(e,kd);return e?"?1":"?0"}function xf(e){return btoa(String.fromCharCode(...e))}function Mf(e){if(ArrayBuffer.isView(e)===!1)throw Ge(e,Cd);return`:${xf(e)}:`}function Of(e){return e<-999999999999999||999999999999999<e}function nl(e){if(Of(e))throw Ge(e,xd);return e.toString()}function Ff(e){return`@${nl(e.getTime()/1e3)}`}function al(e,t){if(e<0)return-al(-e,t);const i=Math.pow(10,t);if(Math.abs(e*i%1-.5)<Number.EPSILON){const s=Math.floor(e*i);return(s%2===0?s:s+1)/i}else return Math.round(e*i)/i}function Nf(e){const t=al(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Ge(e,Md);const i=t.toString();return i.includes(".")?i:`${i}.0`}function Uf(e){if(Fd.test(e))throw Ge(e,Od);return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Bf(e){return e.description||e.toString().slice(7,-1)}function ol(e){const t=Bf(e);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw Ge(t,Nd);return t}function gr(e){switch(typeof e){case"number":if(!N(e))throw Ge(e,ln);return Number.isInteger(e)?nl(e):Nf(e);case"string":return Uf(e);case"symbol":return ol(e);case"boolean":return Cf(e);case"object":if(e instanceof Date)return Ff(e);if(e instanceof Uint8Array)return Mf(e);if(e instanceof on)return ol(e);default:throw Ge(e,ln)}}function mr(e){if(/^[a-z*][a-z0-9\-_.*]*$/.test(e)===!1)throw Ge(e,Ud);return e}function pr(e){return e==null?"":Object.entries(e).map(([t,i])=>i===!0?`;${mr(t)}`:`;${mr(t)}=${gr(i)}`).join("")}function ll(e){return e instanceof tt?`${gr(e.value)}${pr(e.params)}`:gr(e)}function $f(e){return`(${e.value.map(ll).join(" ")})${pr(e.params)}`}function Gf(e,t={whitespace:!0}){if(typeof e!="object"||e==null)throw Ge(e,_d);const i=e instanceof Map?e.entries():Object.entries(e),s=t?.whitespace?" ":"";return Array.from(i).map(([r,n])=>{n instanceof tt||(n=new tt(n));let a=mr(r);return n.value===!0?a+=pr(n.params):(a+="=",Array.isArray(n.value)?a+=$f(n):a+=ll(n)),a}).join(`,${s}`)}function dl(e,t){return Gf(e,t)}function Vf(e){return Object.keys(e).reduce((t,i)=>{var s;return(s=e[i])===null||s===void 0||s.forEach(r=>t[r]=i),t},{})}function Kf(e,t){const i={};if(!e)return i;const s=Object.keys(e),r=t?Vf(t):{};return s.reduce((n,a)=>{var o;const l=Bd[a]||r[a]||$d.REQUEST,d=(o=n[l])!==null&&o!==void 0?o:n[l]={};return d[a]=e[a],n},i)}function Hf(e){return["ot","sf","st","e","sta"].includes(e)}function Wf(e){return typeof e=="number"?N(e):e!=null&&e!==""&&e!==!1}function jf(e,t){const i=new URL(e),s=new URL(t);if(i.origin!==s.origin)return e;const r=i.pathname.split("/").slice(1),n=s.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+i.search+i.hash}function Bi(e){return Hd.test(e)}function Yf(e){return os.includes(e)||Kd.includes(e)||Bi(e)}function zf(e){return os.includes(e)||un.includes(e)||Bi(e)}function qf(e){return os.includes(e)||un.includes(e)||Wd.includes(e)||Bi(e)}function Xf(e){return jd.includes(e)||Bi(e)}function cl(e,t={}){const i={};if(e==null||typeof e!="object")return i;const s=t.version||e.v||1,r=t.reportingMode||cn,n=s===1?Xf:Yd[r];let a=Object.keys(e).filter(n);const o=t.filter;typeof o=="function"&&(a=a.filter(o));const l=r===hn||r===dn;l&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");const d=se({},Vd,t.formatters),c={version:s,reportingMode:r,baseUrl:t.baseUrl};return a.sort().forEach(h=>{let u=e[h];const f=d[h];if(typeof f=="function"&&(u=f(u,c)),h==="v"){if(s===1)return;u=s}h=="pr"&&u===1||(l&&h==="ts"&&!N(u)&&(u=Date.now()),Wf(u)&&(Hf(h)&&typeof u=="string"&&(u=new on(u)),i[h]=u))}),i}function Qf(e,t={}){const i={};if(!e)return i;const s=Kf(cl(e,t),t?.customHeaderMap);return Object.entries(s).reduce((r,[n,a])=>{const o=dl(a,{whitespace:!1});return o&&(r[n]=o),r},i)}function Zf(e,t,i){return se(e,Qf(t,i))}function Jf(e,t={}){return e?dl(cl(e,t),{whitespace:!1}):""}function eg(e,t={}){if(!e)return"";const i=Jf(e,t);return encodeURIComponent(i)}function tg(e,t={}){return e?`${zd}=${eg(e,t)}`:""}function ig(e,t,i){const s=tg(t,i);return s?fn.test(e)?e.replace(fn,s):`${e}${e.includes("?")?"&":"?"}${s}`:e}function hl(e,t,i,s){e&&Object.keys(t).forEach(r=>{const n=e.filter(a=>a.groupId===r).map(a=>{const o=se({},a);return o.details=void 0,o.attrs=new oe(o.attrs),o.url=o.attrs.URI=ul(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),o.groupId=o.attrs["GROUP-ID"]=t[r],o.attrs["PATHWAY-ID"]=s,o});e.push(...n)})}function ul(e,t,i,s){const{HOST:r,PARAMS:n,[i]:a}=s;let o;t&&(o=a?.[t],o&&(e=o));const l=new self.URL(e);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(d=>{d&&l.searchParams.set(d,n[d])}),l.href}function $i(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return ye(e.keyId)}function sg(e,t){if(e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId))return t.mediaKeysSession.keyStatuses.get(e.keyId);if(e.matches(t.decryptdata))return t.keyStatus}function fl(e,t){const i=e==="output-restricted",s=i?L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:L.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Re({type:$.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:t},i?"HDCP level output restricted":`key status changed to "${e}"`)}function gl(e,t){let i;try{i=new Event("addtrack")}catch{i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function ml(e,t){const i=e.mode;if(i==="disabled"&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(s){te.debug(`[texttrack-utils]: ${s}`);try{const r=new self.TextTrackCue(t.startTime,t.endTime,t.text);r.id=t.id,e.addCue(r)}catch(r){te.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}i==="disabled"&&(e.mode=i)}function At(e,t){const i=e.mode;if(i==="disabled"&&(e.mode="hidden"),e.cues)for(let s=e.cues.length;s--;)t&&e.cues[s].removeEventListener("enter",t),e.removeCue(e.cues[s]);i==="disabled"&&(e.mode=i)}function yr(e,t,i,s){const r=e.mode;if(r==="disabled"&&(e.mode="hidden"),e.cues&&e.cues.length>0){const n=ng(e.cues,t,i);for(let a=0;a<n.length;a++)(!s||s(n[a]))&&e.removeCue(n[a])}r==="disabled"&&(e.mode=r)}function rg(e,t){if(t<=e[0].startTime)return 0;const i=e.length-1;if(t>e[i].endTime)return-1;let s=0,r=i,n;for(;s<=r;)if(n=Math.floor((r+s)/2),t<e[n].startTime)r=n-1;else if(t>e[n].startTime&&s<i)s=n+1;else return n;return e[s].startTime-t<t-e[r].startTime?s:r}function ng(e,t,i){const s=[],r=rg(e,t);if(r>-1)for(let n=r,a=e.length;n<a;n++){const o=e[n];if(o.startTime>=t&&o.endTime<=i)s.push(o);else if(o.startTime>i)return s}return s}function Gi(e){const t=[];for(let i=0;i<e.length;i++){const s=e[i];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&t.push(e[i])}return t}function ag(){try{return crypto.randomUUID()}catch{try{const t=URL.createObjectURL(new Blob),i=t.toString();return URL.revokeObjectURL(t),i.slice(i.lastIndexOf("/")+1)}catch{let i=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const r=(i+Math.random()*16)%16|0;return i=Math.floor(i/16),(s=="x"?r:r&3|8).toString(16)})}}}function jt(e){let t=5381,i=e.length;for(;i;)t=t*33^e.charCodeAt(--i);return(t>>>0).toString()}function og(e,t,i){return`${e.identifier}-${i+1}-${jt(t)}`}function vr(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<pt)?t.start:t.start+t.duration}function pl(e,t,i){const s=new self.URL(e,i);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",t),s}function Er(e,t){for(;(i=e.assetList[++t])!=null&&i.error;)var i;return t}function lg(e){return`["${e.identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}function Lt(e){const t=e.timelineStart,i=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+i).toFixed(2)}]`}function Me(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}function yl(e){var t;e==null||(t=e.play())==null||t.catch(()=>{})}function Rt(e,t){return`[${e}] Advancing timeline position to ${t}`}function Vi(e,t,i){i.a=e,i.b=t}function dg(e,t,i){return i.a===e&&i.b===t}function cg(){return{a:null,b:null}}function vl(e){function t(s,r,n,a){return(s|0)*3600+(r|0)*60+(n|0)+parseFloat(a||0)}const i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}function El(e,t,i,s){const r=s?e.split(s):[e];for(const n in r){if(typeof r[n]!="string")continue;const a=r[n].split(i);if(a.length!==2)continue;const o=a[0],l=a[1];t(o,l)}}function hg(e,t,i){const s=e;function r(){const o=vl(e);if(o===null)throw new Error("Malformed timestamp: "+s);return e=e.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){const d=new uc;El(o,function(u,f){let m;switch(u){case"region":for(let g=i.length-1;g>=0;g--)if(i[g].id===f){d.set(u,i[g].region);break}break;case"vertical":d.alt(u,f,["rl","lr"]);break;case"line":m=f.split(","),d.integer(u,m[0]),d.percent(u,m[0])&&d.set("snapToLines",!1),d.alt(u,m[0],["auto"]),m.length===2&&d.alt("lineAlign",m[1],["start",oi,"end"]);break;case"position":m=f.split(","),d.percent(u,m[0]),m.length===2&&d.alt("positionAlign",m[1],["start",oi,"end","line-left","line-right","auto"]);break;case"size":d.percent(u,f);break;case"align":d.alt(u,f,["start",oi,"end","left","right"]);break}},/:/,/\s/),l.region=d.get("region",null),l.vertical=d.get("vertical","");let c=d.get("line","auto");c==="auto"&&hs.line===-1&&(c=-1),l.line=c,l.lineAlign=d.get("lineAlign","start"),l.snapToLines=d.get("snapToLines",!0),l.size=d.get("size",100),l.align=d.get("align",oi);let h=d.get("position","auto");h==="auto"&&hs.position===50&&(h=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=h}function a(){e=e.replace(/^\s+/,"")}if(a(),t.startTime=r(),a(),e.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);e=e.slice(3),a(),t.endTime=r(),a(),n(e,t)}function Tl(e){return e.replace(/<br(?: \/)?>/gi,`
|
|
47
|
+
${i.m3u8}`)}function Do(e,t,i=!0){const s=t.startSN+t.skippedSegments-e.startSN,r=e.fragments,n=s>=0;let a=0;if(n&&s<r.length)a=r[s].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&i)a=e.fragmentStart+s*t.levelTargetDuration;else if(!t.skippedSegments&&t.fragmentStart===0)a=e.fragmentStart;else return;ir(t,a)}function ir(e,t){if(t){const i=e.fragments;for(let s=e.skippedSegments;s<i.length;s++)i[s].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function wo(e,t=1/0){let i=1e3*e.targetduration;if(e.updated){const s=e.fragments;if(s.length&&i*4>t){const r=s[s.length-1].duration*1e3;r<i&&(i=r)}}else i/=2;return Math.round(i)}function Po(e,t,i){if(!e)return null;let s=e.fragments[t-e.startSN];return s||(s=e.fragmentHint,s&&s.sn===t)?s:t<e.startSN&&i&&i.sn===t?i:null}function _o(e,t,i){return e?ko(e.partList,t,i):null}function ko(e,t,i){if(e)for(let s=e.length;s--;){const r=e[s];if(r.index===i&&r.fragment.sn===t)return r}return null}function Co(e){e.forEach((t,i)=>{var s;(s=t.details)==null||s.fragments.forEach(r=>{r.level=i,r.initSegment&&(r.initSegment.level=i)})})}function zu(e,t){return e!==t&&t?xo(e)!==xo(t):!1}function xo(e){return e.replace(/\?[^?]*$/,"")}function Gt(e,t){for(let s=0,r=e.length;s<r;s++){var i;if(((i=e[s])==null?void 0:i.cc)===t)return e[s]}return null}function qu(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}function Mo(e,t){const i=e.start+t;e.startPTS=i,e.setStart(i),e.endPTS=i+e.duration}function Oo(e,t){const i=t.fragments;for(let s=0,r=i.length;s<r;s++)Mo(i[s],e);t.fragmentHint&&Mo(t.fragmentHint,e),t.alignedSliding=!0}function Xu(e,t){e&&(Fo(t,e),t.alignedSliding||Oi(t,e),!t.alignedSliding&&!t.skippedSegments&&Do(e,t,!1))}function Fo(e,t){if(!qu(t,e))return;const i=Math.min(t.endCC,e.endCC),s=Gt(t.fragments,i),r=Gt(e.fragments,i);!s||!r||(te.log(`Aligning playlist at start of dicontinuity sequence ${i}`),Oo(s.start-r.start,e))}function Oi(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const i=e.fragments,s=t.fragments;if(!i.length||!s.length)return;let r,n;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(r=Gt(s,a),n=Gt(i,a)),(!r||!n)&&(r=s[Math.floor(s.length/2)],n=Gt(i,r.cc)||i[Math.floor(i.length/2)]);const o=r.programDateTime,l=n.programDateTime;!o||!l||Oo((l-o)/1e3-(n.start-r.start),e)}function Ee(e,t,i){Le(e,t,i),e.addEventListener(t,i)}function Le(e,t,i){e.removeEventListener(t,i)}function No(e){return!!e.interstitialsController&&e.enableInterstitialPlayback!==!1}function Qu(e,t){const i=new Uint8Array(t);let s=0;for(let r=0;r<e.length;r++){const n=e[r];i.set(n,s),s+=n.length}return i}function Zu(){return sd||(sd=1,(function(e){var t=Object.prototype.hasOwnProperty,i="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(i=!1));function r(l,d,c){this.fn=l,this.context=d,this.once=c||!1}function n(l,d,c,h,u){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new r(c,h||l,u),m=i?i+d:d;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],f]:l._events[m].push(f):(l._events[m]=f,l._eventsCount++),l}function a(l,d){--l._eventsCount===0?l._events=new s:delete l._events[d]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],c,h;if(this._eventsCount===0)return d;for(h in c=this._events)t.call(c,h)&&d.push(i?h.slice(1):h);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(c)):d},o.prototype.listeners=function(d){var c=i?i+d:d,h=this._events[c];if(!h)return[];if(h.fn)return[h.fn];for(var u=0,f=h.length,m=new Array(f);u<f;u++)m[u]=h[u].fn;return m},o.prototype.listenerCount=function(d){var c=i?i+d:d,h=this._events[c];return h?h.fn?1:h.length:0},o.prototype.emit=function(d,c,h,u,f,m){var g=i?i+d:d;if(!this._events[g])return!1;var y=this._events[g],v=arguments.length,E,T;if(y.fn){switch(y.once&&this.removeListener(d,y.fn,void 0,!0),v){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,c),!0;case 3:return y.fn.call(y.context,c,h),!0;case 4:return y.fn.call(y.context,c,h,u),!0;case 5:return y.fn.call(y.context,c,h,u,f),!0;case 6:return y.fn.call(y.context,c,h,u,f,m),!0}for(T=1,E=new Array(v-1);T<v;T++)E[T-1]=arguments[T];y.fn.apply(y.context,E)}else{var S=y.length,A;for(T=0;T<S;T++)switch(y[T].once&&this.removeListener(d,y[T].fn,void 0,!0),v){case 1:y[T].fn.call(y[T].context);break;case 2:y[T].fn.call(y[T].context,c);break;case 3:y[T].fn.call(y[T].context,c,h);break;case 4:y[T].fn.call(y[T].context,c,h,u);break;default:if(!E)for(A=1,E=new Array(v-1);A<v;A++)E[A-1]=arguments[A];y[T].fn.apply(y[T].context,E)}}return!0},o.prototype.on=function(d,c,h){return n(this,d,c,h,!1)},o.prototype.once=function(d,c,h){return n(this,d,c,h,!0)},o.prototype.removeListener=function(d,c,h,u){var f=i?i+d:d;if(!this._events[f])return this;if(!c)return a(this,f),this;var m=this._events[f];if(m.fn)m.fn===c&&(!u||m.once)&&(!h||m.context===h)&&a(this,f);else{for(var g=0,y=[],v=m.length;g<v;g++)(m[g].fn!==c||u&&!m[g].once||h&&m[g].context!==h)&&y.push(m[g]);y.length?this._events[f]=y.length===1?y[0]:y:a(this,f)}return this},o.prototype.removeAllListeners=function(d){var c;return d?(c=i?i+d:d,this._events[c]&&a(this,c)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,e.exports=o})(ts)),ts.exports}function Ju(){return typeof __HLS_WORKER_BUNDLE__=="function"}function ef(){const e=gt[Pt];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(t),s={worker:new self.Worker(i),objectURL:i,clientCount:1};return gt[Pt]=s,s}function tf(e){const t=gt[e];if(t)return t.clientCount++,t;const i=new self.URL(e,self.location.href).href,s={worker:new self.Worker(i),scriptURL:i,clientCount:1};return gt[e]=s,s}function sf(e){const t=gt[e||Pt];if(t&&t.clientCount--===1){const{worker:i,objectURL:s}=t;delete gt[e||Pt],s&&self.URL.revokeObjectURL(s),i.terminate()}}function Uo(e,t){return t+10<=e.length&&e[t]===51&&e[t+1]===68&&e[t+2]===73&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function sr(e,t){return t+10<=e.length&&e[t]===73&&e[t+1]===68&&e[t+2]===51&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function Fi(e,t){let i=0;return i=(e[t]&127)<<21,i|=(e[t+1]&127)<<14,i|=(e[t+2]&127)<<7,i|=e[t+3]&127,i}function Vt(e,t){const i=t;let s=0;for(;sr(e,t);){s+=10;const r=Fi(e,t+6);s+=r,Uo(e,t+10)&&(s+=10),t+=s}if(s>0)return e.subarray(i,i+s)}function rf(e,t,i,s){const r=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=t[i+2],a=n>>2&15;if(a>12){const f=new Error(`invalid ADTS sampling index:${a}`);e.emit(p.ERROR,p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(n>>6&3)+1,l=t[i+3]>>6&3|(n&1)<<2,d="mp4a.40."+o,c=r[a];let h=a;(o===5||o===29)&&(h-=3);const u=[o<<3|(h&14)>>1,(h&1)<<7|l<<3];return te.log(`manifest codec:${s}, parsed codec:${d}, channels:${l}, rate:${c} (ADTS object type:${o} sampling index:${a})`),{config:u,samplerate:c,channelCount:l,codec:d,parsedCodec:d,manifestCodec:s}}function Bo(e,t){return e[t]===255&&(e[t+1]&246)===240}function $o(e,t){return e[t+1]&1?7:9}function rr(e,t){return(e[t+3]&3)<<11|e[t+4]<<3|(e[t+5]&224)>>>5}function nf(e,t){return t+5<e.length}function Ni(e,t){return t+1<e.length&&Bo(e,t)}function af(e,t){return nf(e,t)&&Bo(e,t)&&rr(e,t)<=e.length-t}function of(e,t){if(Ni(e,t)){const i=$o(e,t);if(t+i>=e.length)return!1;const s=rr(e,t);if(s<=i)return!1;const r=t+s;return r===e.length||Ni(e,r)}return!1}function Go(e,t,i,s,r){if(!e.samplerate){const n=rf(t,i,s,r);if(!n)return;se(e,n)}}function Vo(e){return 1024*9e4/e}function lf(e,t){const i=$o(e,t);if(t+i<=e.length){const s=rr(e,t)-i;if(s>0)return{headerLength:i,frameLength:s}}}function Ko(e,t,i,s,r){const n=s+r*Vo(e.samplerate),a=lf(t,i);let o;if(a){const{frameLength:d,headerLength:c}=a,h=c+d,u=Math.max(0,i+h-t.length);u?(o=new Uint8Array(h-c),o.set(t.subarray(i+c,t.length),0)):o=t.subarray(i+c,i+h);const f={unit:o,pts:n};return u||e.samples.push(f),{sample:f,length:h,missing:u}}const l=t.length-i;return o=new Uint8Array(l),o.set(t.subarray(i,t.length),0),{sample:{unit:o,pts:n},length:l,missing:-1}}function df(e,t){return sr(e,t)&&Fi(e,t+6)+10<=e.length-t}function cf(e){return e instanceof ArrayBuffer?e:e.byteOffset==0&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function nr(e,t=0,i=1/0){return hf(e,t,i,Uint8Array)}function hf(e,t,i,s){const r=uf(e);let n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);const a=ff(e)?e.byteOffset:0,o=(a+e.byteLength)/n,l=(a+t)/n,d=Math.floor(Math.max(0,Math.min(l,o)));return new s(r,d,Math.floor(Math.min(d+Math.max(i,0),o))-d)}function uf(e){return e instanceof ArrayBuffer?e:e.buffer}function ff(e){return e&&e.buffer instanceof ArrayBuffer&&e.byteLength!==void 0&&e.byteOffset!==void 0}function gf(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null},i=3;if(e.size<2)return;if(e.data[0]!==i){console.log("Ignore frame with unrecognized character encoding");return}const s=e.data.subarray(1).indexOf(0);if(s===-1)return;const r=De(nr(e.data,1,s)),n=e.data[2+s],a=e.data.subarray(3+s).indexOf(0);if(a===-1)return;const o=De(nr(e.data,3+s,a));let l;return r==="-->"?l=De(nr(e.data,4+s+a)):l=cf(e.data.subarray(4+s+a)),t.mimeType=r,t.pictureType=n,t.description=o,t.data=l,t}function mf(e){if(e.size<2)return;const t=De(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}function pf(e){if(e.size<2)return;if(e.type==="TXXX"){let i=1;const s=De(e.data.subarray(i),!0);i+=s.length+1;const r=De(e.data.subarray(i));return{key:e.type,info:s,data:r}}const t=De(e.data.subarray(1));return{key:e.type,info:"",data:t}}function yf(e){if(e.type==="WXXX"){if(e.size<2)return;let i=1;const s=De(e.data.subarray(i),!0);i+=s.length+1;const r=De(e.data.subarray(i));return{key:e.type,info:s,data:r}}const t=De(e.data);return{key:e.type,info:"",data:t}}function vf(e){return e.type==="PRIV"?mf(e):e.type[0]==="W"?yf(e):e.type==="APIC"?gf(e):pf(e)}function Ef(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=Fi(e,4),s=10;return{type:t,size:i,data:e.subarray(s,s+i)}}function Ho(e){let t=0;const i=[];for(;sr(e,t);){const s=Fi(e,t+6);e[t+5]>>6&1&&(t+=Jt),t+=Jt;const r=t+s;for(;t+rd<r;){const n=Ef(e.subarray(t)),a=vf(n);a&&i.push(a),t+=n.size+Jt}Uo(e,t)&&(t+=Jt)}return i}function Wo(e){return e&&e.key==="PRIV"&&e.info==="com.apple.streaming.transportStreamTimestamp"}function Tf(e){if(e.data.byteLength===8){const t=new Uint8Array(e.data),i=t[3]&1;let s=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return s/=45,i&&(s+=4772185884e-2),Math.round(s)}}function ar(e){const t=Ho(e);for(let i=0;i<t.length;i++){const s=t[i];if(Wo(s))return Tf(s)}}function $e(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}function jo(e,t,i,s,r){if(i+24>t.length)return;const n=Yo(t,i);if(n&&i+n.frameLength<=t.length){const a=s+r*(n.samplesPerFrame*9e4/n.sampleRate),o={unit:t.subarray(i,i+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function Yo(e,t){const i=e[t+1]>>3&3,s=e[t+1]>>1&3,r=e[t+2]>>4&15,n=e[t+2]>>2&3;if(i!==1&&r!==0&&r!==15&&n!==3){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=ad[(i===3?3-s:s===3?3:4)*14+r-1]*1e3,d=od[(i===3?0:i===2?1:2)*3+n],c=o===3?1:2,h=ld[i][s],u=dd[s],f=h*8*u,m=Math.floor(h*l/d+a)*u;if(ei===null){const g=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ei=g?parseInt(g[1]):0}return ei&&ei<=87&&s===2&&l>=224e3&&o===0&&(e[t+3]=e[t+3]|128),{sampleRate:d,channelCount:c,frameLength:m,samplesPerFrame:f}}}function or(e,t){return e[t]===255&&(e[t+1]&224)===224&&(e[t+1]&6)!==0}function zo(e,t){return t+1<e.length&&or(e,t)}function Sf(e,t){return or(e,t)&&4<=e.length-t}function qo(e,t){if(t+1<e.length&&or(e,t)){const s=Yo(e,t);let r=4;s!=null&&s.frameLength&&(r=s.frameLength);const n=t+r;return n===e.length||zo(e,n)}return!1}function Xo(e,t,i,s,r){if(i+8>t.length||t[i]!==11||t[i+1]!==119)return-1;const n=t[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=t[i+4]&63,l=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][o*3+n]*2;if(i+l>t.length)return-1;const d=t[i+6]>>5;let c=0;d===2?c+=2:(d&1&&d!==1&&(c+=2),d&4&&(c+=2));const h=(t[i+6]<<8|t[i+7])>>12-c&1,u=[2,1,2,3,3,4,4,5][d]+h,f=t[i+5]>>3,m=t[i+5]&7,g=new Uint8Array([n<<6|f<<1|m>>2,(m&3)<<6|d<<3|h<<2|o>>4,o<<4&224]),y=s+r*(1536/a*9e4),v=t.subarray(i,i+l);return e.config=g,e.channelCount=u,e.samplerate=a,e.samples.push({unit:v,pts:y}),l}function Qo(e,t){return N(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}function lr(e,t){return((e[t+1]&31)<<8)+e[t+2]}function bf(e,t){return(e[t+10]&31)<<8|e[t+11]}function If(e,t,i,s,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(e[t+1]&15)<<8|e[t+2],l=t+3+o-4,d=(e[t+10]&15)<<8|e[t+11];for(t+=12+d;t<l;){const c=lr(e,t),h=(e[t+3]&15)<<8|e[t+4];switch(e[t]){case 207:if(!s){cr("ADTS AAC",n);break}case 15:a.audioPid===-1&&(a.audioPid=c);break;case 21:a.id3Pid===-1&&(a.id3Pid=c);break;case 219:if(!s){cr("H.264",n);break}case 27:a.videoPid===-1&&(a.videoPid=c);break;case 3:case 4:!i.mpeg&&!i.mp3?n.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=c,a.segmentAudioCodec="mp3");break;case 193:if(!s){cr("AC-3",n);break}case 129:i.ac3?a.audioPid===-1&&(a.audioPid=c,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&h>0){let u=t+5,f=h;for(;f>2;){e[u]===106&&(i.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=c,a.segmentAudioCodec="ac3"));const m=e[u+1]+2;u+=m,f-=m}}break;case 194:case 135:return dr(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:a.videoPid===-1&&(a.videoPid=c,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}t+=h+5}return a}function dr(e,t,i,s){s.warn(`parsing error: ${t.message}`),e.emit(p.ERROR,p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function cr(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function It(e,t){let i=0,s,r,n,a,o;const l=e.data;if(!e||e.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=Ce(l[0],l[1]),l.splice(1,1);if(s=l[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(r=(s[4]<<8)+s[5],r&&r>e.size-6)return null;const d=s[7];d&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,d&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,a-o>60*9e4&&(t.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),n=s[8];let c=n+9;if(e.size<=c)return null;e.size-=c;const h=new Uint8Array(e.size);for(let u=0,f=l.length;u<f;u++){s=l[u];let m=s.byteLength;if(c)if(c>m){c-=m;continue}else s=s.subarray(c),m-=c,c=0;h.set(s,i),i+=m}return r&&(r-=n+3),{data:h,pts:a,dts:o,len:r}}return null}function hr(e,t,i=1,s=!1){const r=e*t*i;return s?Math.round(r):r}function Af(e,t,i=1,s=!1){return hr(e,t,1/i,s)}function Kt(e,t=!1){return hr(e,1e3,1/qr,t)}function Lf(e,t=1){return hr(e,qr,1/t)}function Zo(e){const{baseTime:t,timescale:i,trackId:s}=e;return`${t/i} (${t}/${i}) trackId: ${s}`}function Jo(e,t,i,s){return{duration:t,size:i,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}function we(e,t){let i;if(t===null)return e;for(t<e?i=-8589934592:i=8589934592;Math.abs(e-t)>4294967296;)e+=i;return e}function Rf(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}function el(e,t,i,s){const r=e.samples.length;if(!r)return;const n=e.inputTimeScale;for(let o=0;o<r;o++){const l=e.samples[o];l.pts=we(l.pts-i.baseTime*n/i.timescale,t*n)/n,l.dts=we(l.dts-s.baseTime*n/s.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function tl(e,t,i){const s=e.samples.length;if(!s)return;const r=e.inputTimeScale;for(let a=0;a<s;a++){const o=e.samples[a];o.pts=we(o.pts-i.baseTime*r/i.timescale,t*r)/r}e.samples.sort((a,o)=>a.pts-o.pts);const n=e.samples;return e.samples=[],{samples:n}}function Ui(e,t,i=!1){return e?.start!==void 0?(e.start+(i?e.duration:0))/e.timescale:t}function Df(e,t,i,s){if(e===null)return!0;const r=Math.max(s,1),n=t-e.baseTime/e.timescale;return Math.abs(n-i)>r}function il(e,t,i){const s=e.codec;return s&&s.length>4?s:t===re.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?Ri(s,!1):(i.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(i.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}function wf(e,t){let i=null;return e.byteLength>0&&t?.key!=null&&t.iv!==null&&t.method!=null&&(i=t),i}function Ht(e){return"then"in e&&e.then instanceof Function}function sl(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!Wt(e[i].attrs,t[i].attrs))return!1;return!0}function Wt(e,t,i){const s=e["STABLE-RENDITION-ID"];return s&&!i?s===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>e[r]!==t[r])}function ur(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}function rl(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach(i=>{e.removeChild(i)})}function Pf(e,t){const i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}function fr(e){return e==="audio"?1:0}function _f(e){return Array.isArray(e)?JSON.stringify(e):e instanceof Map?"Map{}":e instanceof Set?"Set{}":typeof e=="object"?JSON.stringify(e):String(e)}function kf(e,t,i,s){return new Error(`failed to ${e} "${_f(t)}" as ${i}`,{cause:s})}function Ge(e,t,i){return kf("serialize",e,t,i)}function Cf(e){if(typeof e!="boolean")throw Ge(e,kd);return e?"?1":"?0"}function xf(e){return btoa(String.fromCharCode(...e))}function Mf(e){if(ArrayBuffer.isView(e)===!1)throw Ge(e,Cd);return`:${xf(e)}:`}function Of(e){return e<-999999999999999||999999999999999<e}function nl(e){if(Of(e))throw Ge(e,xd);return e.toString()}function Ff(e){return`@${nl(e.getTime()/1e3)}`}function al(e,t){if(e<0)return-al(-e,t);const i=Math.pow(10,t);if(Math.abs(e*i%1-.5)<Number.EPSILON){const s=Math.floor(e*i);return(s%2===0?s:s+1)/i}else return Math.round(e*i)/i}function Nf(e){const t=al(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Ge(e,Md);const i=t.toString();return i.includes(".")?i:`${i}.0`}function Uf(e){if(Fd.test(e))throw Ge(e,Od);return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Bf(e){return e.description||e.toString().slice(7,-1)}function ol(e){const t=Bf(e);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw Ge(t,Nd);return t}function gr(e){switch(typeof e){case"number":if(!N(e))throw Ge(e,ln);return Number.isInteger(e)?nl(e):Nf(e);case"string":return Uf(e);case"symbol":return ol(e);case"boolean":return Cf(e);case"object":if(e instanceof Date)return Ff(e);if(e instanceof Uint8Array)return Mf(e);if(e instanceof on)return ol(e);default:throw Ge(e,ln)}}function mr(e){if(/^[a-z*][a-z0-9\-_.*]*$/.test(e)===!1)throw Ge(e,Ud);return e}function pr(e){return e==null?"":Object.entries(e).map(([t,i])=>i===!0?`;${mr(t)}`:`;${mr(t)}=${gr(i)}`).join("")}function ll(e){return e instanceof tt?`${gr(e.value)}${pr(e.params)}`:gr(e)}function $f(e){return`(${e.value.map(ll).join(" ")})${pr(e.params)}`}function Gf(e,t={whitespace:!0}){if(typeof e!="object"||e==null)throw Ge(e,_d);const i=e instanceof Map?e.entries():Object.entries(e),s=t?.whitespace?" ":"";return Array.from(i).map(([r,n])=>{n instanceof tt||(n=new tt(n));let a=mr(r);return n.value===!0?a+=pr(n.params):(a+="=",Array.isArray(n.value)?a+=$f(n):a+=ll(n)),a}).join(`,${s}`)}function dl(e,t){return Gf(e,t)}function Vf(e){return Object.keys(e).reduce((t,i)=>{var s;return(s=e[i])===null||s===void 0||s.forEach(r=>t[r]=i),t},{})}function Kf(e,t){const i={};if(!e)return i;const s=Object.keys(e),r=t?Vf(t):{};return s.reduce((n,a)=>{var o;const l=Bd[a]||r[a]||$d.REQUEST,d=(o=n[l])!==null&&o!==void 0?o:n[l]={};return d[a]=e[a],n},i)}function Hf(e){return["ot","sf","st","e","sta"].includes(e)}function Wf(e){return typeof e=="number"?N(e):e!=null&&e!==""&&e!==!1}function jf(e,t){const i=new URL(e),s=new URL(t);if(i.origin!==s.origin)return e;const r=i.pathname.split("/").slice(1),n=s.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+i.search+i.hash}function Bi(e){return Hd.test(e)}function Yf(e){return os.includes(e)||Kd.includes(e)||Bi(e)}function zf(e){return os.includes(e)||un.includes(e)||Bi(e)}function qf(e){return os.includes(e)||un.includes(e)||Wd.includes(e)||Bi(e)}function Xf(e){return jd.includes(e)||Bi(e)}function cl(e,t={}){const i={};if(e==null||typeof e!="object")return i;const s=t.version||e.v||1,r=t.reportingMode||cn,n=s===1?Xf:Yd[r];let a=Object.keys(e).filter(n);const o=t.filter;typeof o=="function"&&(a=a.filter(o));const l=r===hn||r===dn;l&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");const d=se({},Vd,t.formatters),c={version:s,reportingMode:r,baseUrl:t.baseUrl};return a.sort().forEach(h=>{let u=e[h];const f=d[h];if(typeof f=="function"&&(u=f(u,c)),h==="v"){if(s===1)return;u=s}h=="pr"&&u===1||(l&&h==="ts"&&!N(u)&&(u=Date.now()),Wf(u)&&(Hf(h)&&typeof u=="string"&&(u=new on(u)),i[h]=u))}),i}function Qf(e,t={}){const i={};if(!e)return i;const s=Kf(cl(e,t),t?.customHeaderMap);return Object.entries(s).reduce((r,[n,a])=>{const o=dl(a,{whitespace:!1});return o&&(r[n]=o),r},i)}function Zf(e,t,i){return se(e,Qf(t,i))}function Jf(e,t={}){return e?dl(cl(e,t),{whitespace:!1}):""}function eg(e,t={}){if(!e)return"";const i=Jf(e,t);return encodeURIComponent(i)}function tg(e,t={}){return e?`${zd}=${eg(e,t)}`:""}function ig(e,t,i){const s=tg(t,i);return s?fn.test(e)?e.replace(fn,s):`${e}${e.includes("?")?"&":"?"}${s}`:e}function hl(e,t,i,s){e&&Object.keys(t).forEach(r=>{const n=e.filter(a=>a.groupId===r).map(a=>{const o=se({},a);return o.details=void 0,o.attrs=new oe(o.attrs),o.url=o.attrs.URI=ul(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),o.groupId=o.attrs["GROUP-ID"]=t[r],o.attrs["PATHWAY-ID"]=s,o});e.push(...n)})}function ul(e,t,i,s){const{HOST:r,PARAMS:n,[i]:a}=s;let o;t&&(o=a?.[t],o&&(e=o));const l=new self.URL(e);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(d=>{d&&l.searchParams.set(d,n[d])}),l.href}function $i(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return ye(e.keyId)}function sg(e,t){if(e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId))return t.mediaKeysSession.keyStatuses.get(e.keyId);if(e.matches(t.decryptdata))return t.keyStatus}function fl(e,t){const i=e==="output-restricted",s=i?L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:L.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Re({type:$.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:t},i?"HDCP level output restricted":`key status changed to "${e}"`)}function gl(e,t){let i;try{i=new Event("addtrack")}catch{i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function ml(e,t){const i=e.mode;if(i==="disabled"&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(s){te.debug(`[texttrack-utils]: ${s}`);try{const r=new self.TextTrackCue(t.startTime,t.endTime,t.text);r.id=t.id,e.addCue(r)}catch(r){te.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}i==="disabled"&&(e.mode=i)}function At(e,t){const i=e.mode;if(i==="disabled"&&(e.mode="hidden"),e.cues)for(let s=e.cues.length;s--;)t&&e.cues[s].removeEventListener("enter",t),e.removeCue(e.cues[s]);i==="disabled"&&(e.mode=i)}function yr(e,t,i,s){const r=e.mode;if(r==="disabled"&&(e.mode="hidden"),e.cues&&e.cues.length>0){const n=ng(e.cues,t,i);for(let a=0;a<n.length;a++)(!s||s(n[a]))&&e.removeCue(n[a])}r==="disabled"&&(e.mode=r)}function rg(e,t){if(t<=e[0].startTime)return 0;const i=e.length-1;if(t>e[i].endTime)return-1;let s=0,r=i,n;for(;s<=r;)if(n=Math.floor((r+s)/2),t<e[n].startTime)r=n-1;else if(t>e[n].startTime&&s<i)s=n+1;else return n;return e[s].startTime-t<t-e[r].startTime?s:r}function ng(e,t,i){const s=[],r=rg(e,t);if(r>-1)for(let n=r,a=e.length;n<a;n++){const o=e[n];if(o.startTime>=t&&o.endTime<=i)s.push(o);else if(o.startTime>i)return s}return s}function Gi(e){const t=[];for(let i=0;i<e.length;i++){const s=e[i];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&t.push(e[i])}return t}function ag(){try{return crypto.randomUUID()}catch{try{const t=URL.createObjectURL(new Blob),i=t.toString();return URL.revokeObjectURL(t),i.slice(i.lastIndexOf("/")+1)}catch{let i=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const r=(i+Math.random()*16)%16|0;return i=Math.floor(i/16),(s=="x"?r:r&3|8).toString(16)})}}}function jt(e){let t=5381,i=e.length;for(;i;)t=t*33^e.charCodeAt(--i);return(t>>>0).toString()}function og(e,t,i){return`${e.identifier}-${i+1}-${jt(t)}`}function vr(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<pt)?t.start:t.start+t.duration}function pl(e,t,i){const s=new self.URL(e,i);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",t),s}function Er(e,t){for(;(i=e.assetList[++t])!=null&&i.error;)var i;return t}function lg(e){return`["${e.identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}function Lt(e){const t=e.timelineStart,i=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+i).toFixed(2)}]`}function Me(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}function yl(e){var t;e==null||(t=e.play())==null||t.catch(()=>{})}function Rt(e,t){return`[${e}] Advancing timeline position to ${t}`}function Vi(e,t,i){i.a=e,i.b=t}function dg(e,t,i){return i.a===e&&i.b===t}function cg(){return{a:null,b:null}}function vl(e){function t(s,r,n,a){return(s|0)*3600+(r|0)*60+(n|0)+parseFloat(a||0)}const i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}function El(e,t,i,s){const r=s?e.split(s):[e];for(const n in r){if(typeof r[n]!="string")continue;const a=r[n].split(i);if(a.length!==2)continue;const o=a[0],l=a[1];t(o,l)}}function hg(e,t,i){const s=e;function r(){const o=vl(e);if(o===null)throw new Error("Malformed timestamp: "+s);return e=e.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){const d=new uc;El(o,function(u,f){let m;switch(u){case"region":for(let g=i.length-1;g>=0;g--)if(i[g].id===f){d.set(u,i[g].region);break}break;case"vertical":d.alt(u,f,["rl","lr"]);break;case"line":m=f.split(","),d.integer(u,m[0]),d.percent(u,m[0])&&d.set("snapToLines",!1),d.alt(u,m[0],["auto"]),m.length===2&&d.alt("lineAlign",m[1],["start",oi,"end"]);break;case"position":m=f.split(","),d.percent(u,m[0]),m.length===2&&d.alt("positionAlign",m[1],["start",oi,"end","line-left","line-right","auto"]);break;case"size":d.percent(u,f);break;case"align":d.alt(u,f,["start",oi,"end","left","right"]);break}},/:/,/\s/),l.region=d.get("region",null),l.vertical=d.get("vertical","");let c=d.get("line","auto");c==="auto"&&hs.line===-1&&(c=-1),l.line=c,l.lineAlign=d.get("lineAlign","start"),l.snapToLines=d.get("snapToLines",!0),l.size=d.get("size",100),l.align=d.get("align",oi);let h=d.get("position","auto");h==="auto"&&hs.position===50&&(h=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=h}function a(){e=e.replace(/^\s+/,"")}if(a(),t.startTime=r(),a(),e.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);e=e.slice(3),a(),t.endTime=r(),a(),n(e,t)}function Tl(e){return e.replace(/<br(?: \/)?>/gi,`
|
|
48
48
|
`)}function Tr(e,t,i){return jt(e.toString())+jt(t.toString())+jt(i)}function ug(e,t,i,s,r,n,a){const o=new fc,l=De(new Uint8Array(e)).trim().replace(gc,`
|
|
49
49
|
`).split(`
|
|
50
|
-
`),d=[],c=t?Lf(t.baseTime,t.timescale):0;let h="00:00.000",u=0,f=0,m,g=!0;o.oncue=function(y){const v=i[s];let E=i.ccOffset;const T=(u-c)/9e4;if(v!=null&&v.new&&(f!==void 0?E=i.ccOffset=v.start:pc(i,s,T)),T){if(!t){m=new Error("Missing initPTS for VTT MPEGTS");return}E=T-i.presentationOffset}const S=y.endTime-y.startTime,A=
|
|
50
|
+
`),d=[],c=t?Lf(t.baseTime,t.timescale):0;let h="00:00.000",u=0,f=0,m,g=!0;o.oncue=function(y){const v=i[s];let E=i.ccOffset;const T=(u-c)/9e4;if(v!=null&&v.new&&(f!==void 0?E=i.ccOffset=v.start:pc(i,s,T)),T){if(!t){m=new Error("Missing initPTS for VTT MPEGTS");return}E=T-i.presentationOffset}const S=y.endTime-y.startTime,A=we((y.startTime+E-f)*9e4,r*9e4)/9e4;y.startTime=Math.max(A,0),y.endTime=Math.max(A+S,0);const b=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(b)),y.id||(y.id=Tr(y.startTime,y.endTime,b)),y.endTime>0&&d.push(y)},o.onparsingerror=function(y){m=y},o.onflush=function(){if(m){a(m);return}n(d)},l.forEach(y=>{if(g)if(us(y,"X-TIMESTAMP-MAP=")){g=!1,y.slice(16).split(",").forEach(v=>{us(v,"LOCAL:")?h=v.slice(6):us(v,"MPEGTS:")&&(u=parseInt(v.slice(7)))});try{f=mc(h)/1e3}catch(v){m=v}return}else y===""&&(g=!1);o.parse(y+`
|
|
51
51
|
`)}),o.flush()}function Sl(e,t,i,s){const r=z(new Uint8Array(e),["mdat"]);if(r.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const n=r.map(o=>De(o)),a=Af(t.baseTime,1,t.timescale);try{n.forEach(o=>i(fg(o,a)))}catch(o){s(o)}}function fg(e,t){const i=new DOMParser().parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},r=Object.keys(s).reduce((d,c)=>(d[c]=i.getAttribute(`ttp:${c}`)||s[c],d),{}),n=i.getAttribute("xml:space")!=="preserve",a=bl(Sr(i,"styling","style")),o=bl(Sr(i,"layout","region")),l=Sr(i,"body","[begin]");return[].map.call(l,d=>{const c=Il(d,n);if(!c||!d.hasAttribute("begin"))return null;const h=Ir(d.getAttribute("begin"),r),u=Ir(d.getAttribute("dur"),r);let f=Ir(d.getAttribute("end"),r);if(h===null)throw Al(d);if(f===null){if(u===null)throw Al(d);f=h+u}const m=new cs(h-t,f-t,c);m.id=Tr(m.startTime,m.endTime,m.text);const g=o[d.getAttribute("region")],y=a[d.getAttribute("style")],v=gg(g,y,a),{textAlign:E}=v;if(E){const T=yc[E];T&&(m.lineAlign=T),m.align=E}return se(m,v),m}).filter(d=>d!==null)}function Sr(e,t,i){const s=e.getElementsByTagName(t)[0];return s?[].slice.call(s.querySelectorAll(i)):[]}function bl(e){return e.reduce((t,i)=>{const s=i.getAttribute("xml:id");return s&&(t[s]=i),t},{})}function Il(e,t){return[].slice.call(e.childNodes).reduce((i,s,r)=>{var n;return s.nodeName==="br"&&r?i+`
|
|
52
|
-
`:(n=s.childNodes)!=null&&n.length?Il(s,t):t?i+s.textContent.trim().replace(/\s+/g," "):i+s.textContent},"")}function gg(e,t,i){const s="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=e!=null&&e.hasAttribute("style")?e.getAttribute("style"):null;return a&&i.hasOwnProperty(a)&&(r=i[a]),n.reduce((o,l)=>{const d=br(t,s,l)||br(e,s,l)||br(r,s,l);return d&&(o[l]=d),o},{})}function br(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function Al(e){return new Error(`Could not parse ttml timestamp ${e}`)}function Ir(e,t){if(!e)return null;let i=vl(e);return i===null&&(Ln.test(e)?i=mg(e,t):Rn.test(e)&&(i=pg(e,t))),i}function mg(e,t){const i=Ln.exec(e),s=(i[4]|0)+(i[5]|0)/t.subFrameRate;return(i[1]|0)*3600+(i[2]|0)*60+(i[3]|0)+s/t.frameRate}function pg(e,t){const i=Rn.exec(e),s=Number(i[1]);switch(i[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/t.frameRate;case"t":return s/t.tickRate}return s}function Ll(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function Rl(e,t){return!!e&&e.kind===Ll(t)&&ur(t,e)}function yg(e,t,i,s){return Math.min(t,s)-Math.max(e,i)}function Dl(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}function Pl(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}function vg(e,t){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(se({},e.headers))};return e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),i}function Eg(e){const t=Ec.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function Tg(e){const t=e.get("Content-Range");if(t){const s=Eg(t);if(N(s))return s}const i=e.get("Content-Length");if(i)return parseInt(i)}function Sg(e,t){return new self.Request(e.url,t)}function bg(){return{cueHandler:Pn,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 Ig(e,t,i){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=Ar(e),r=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return r.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,l=t[o]===void 0,d=[];n.forEach(c=>{const h=`${a}Loading${c}`,u=t[h];if(u!==void 0&&l){d.push(h);const f=s[o].default;switch(t[o]={default:f},c){case"TimeOut":f.maxLoadTimeMs=u,f.maxTimeToFirstByteMs=u;break;case"MaxRetry":f.errorRetry.maxNumRetry=u,f.timeoutRetry.maxNumRetry=u;break;case"RetryDelay":f.errorRetry.retryDelayMs=u,f.timeoutRetry.retryDelayMs=u;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=u,f.timeoutRetry.maxRetryDelayMs=u;break}}}),d.length&&i.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${ne(t[o])}`)}),ie(ie({},s),t)}function Ar(e){return e&&typeof e=="object"?Array.isArray(e)?e.map(Ar):Object.keys(e).reduce((t,i)=>(t[i]=Ar(e[i]),t),{}):e}function Ag(e,t){const i=e.loader;i!==gs&&i!==ms?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):Pl()&&(e.loader=gs,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}function wl(e,t){const i=_l(e.main);if(i&&i.start<=t)return i;const s=_l(e.audio);return s&&s.start<=t?s:null}function _l(e){if(!e)return null;switch(e.state){case _.IDLE:case _.STOPPED:case _.ENDED:case _.ERROR:return null}return e.frag}function Ki(e,t){return t.getAppendedFrag(e,B.MAIN)||t.getPartialFragment(e)}function Lr(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Rr(e,t,i,s,r){let n=new e(t,i,"");try{n.value=s,r&&(n.type=r)}catch{n=new e(t,i,ne(r?ie({type:r},s):s))}return n}function kl(e){const t={};e.forEach(i=>{const s=i.groupId||"";i.id=t[s]=t[s]||0,t[s]++})}function Cl(){return self.SourceBuffer||self.WebKitSourceBuffer}function Dr(){if(!Ye())return!1;const e=Cl();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function xl(){if(!Dr())return!1;const e=Ye();return typeof e?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(Bt(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(Bt(t,"audio"))))}function Lg(){var e;const t=Cl();return typeof(t==null||(e=t.prototype)==null?void 0:e.changeType)=="function"}function Pr(e){if(e.keyFormat!==fe.FAIRPLAY){const t=e.keyId;if(t)return ye(t)}return e.uri}function Ml(e){const{type:t}=e;switch(t){case q.AUDIO_TRACK:return B.AUDIO;case q.SUBTITLE_TRACK:return B.SUBTITLE;default:return B.MAIN}}function wr(e,t){let i=e.url;return(i===void 0||i.indexOf("data:")===0)&&(i=t.url),i}var N,Ol,Fl,$,L,p,q,B,dt,Nl,we,qe,Ul,Hi,te,Wi,Bl,ji,Yt,re,Yi,zt,_r,kr,$l,Cr,xr,ct,zi,Gl,Vl,Kl,Mr,qi,qt,Dt,Xi,ht,Hl,ne,Or,Fr,ce,Te,Nr,he,Wl,Xe,jl,Yl,zl,ql,Qi,Ur,Xl,Ve,Br,Xt,$r,Y,Gr,Ql,Vr,oe,Zl,Zi,Jl,Kr,Qt,ae,fe,Ji,ut,Pt,Hr,Wr,ed,es,td,ft,id,_,Zt,jr,ts,sd,is,wt,gt,Jt,rd,Se,ss,nd,ei,ad,od,ld,dd,cd,Yr,hd,ud,fd,gd,md,zr,_t,pd,yd,ge,vd,Ed,Qe,me,qr,Td,Sd,bd,Id,mt,rs,ti,Ad,Ze,ii,Xr,ns,Ld,Rd,Qr,Zr,Jr,en,si,tn,Dd,sn,rn,Pd,nn,an,be,wd,tt,_d,on,ln,kd,Cd,xd,Md,Od,Fd,Nd,Ud,Oe,le,it,Je,Bd,$d,dn,ri,as,ni,Gd,Vd,cn,hn,os,Kd,Hd,un,Wd,jd,Yd,zd,fn,gn,qd,mn,ls,Re,pn,yn,pt,ai,Xd,Qd,vn,Zd,Jd,ec,En,Tn,tc,ic,Sn,xe,Ke,sc,rc,nc,ac,oc,lc,st,bn,dc,cc,ds,In,An,cs,hc,uc,hs,oi,fc,gc,us,mc,pc,fs,Ln,Rn,yc,li,Dn,vc,Pn,Ec,gs,Tc,Sc,ms,bc,di,Ic,Ac,Lc,Rc,Dc,ci,Pc,wc,_c,kc,Cc,xc,Mc,ps,Rg=ee((()=>{N=Number.isFinite||function(e){return typeof e=="number"&&isFinite(e)},Ol=Number.isSafeInteger||function(e){return typeof e=="number"&&Math.abs(e)<=Fl},Fl=Number.MAX_SAFE_INTEGER||9007199254740991,$=(function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e})({}),L=(function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e})({}),p=(function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e})({}),q={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},B={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},dt=class{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},Nl=class{constructor(e,t,i,s=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new dt(e),this.fast_=new dt(t),this.defaultTTFB_=s,this.ttfb_=new dt(e)}update(e,t){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new dt(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new dt(t,s.getEstimate(),s.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new dt(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const i=8*t,s=e/1e3,r=i/s;this.fast_.sample(s,r),this.slow_.sample(s,r)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}},we=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${e}]:`;this.trace=qe,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)}},qe=function(){},Ul={trace:qe,debug:qe,log:qe,warn:qe,info:qe,error:qe},Hi=Gs(),te=Hi,Wi={exports:{}},ji=jh(),Yt=class{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}},re={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},Yi=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,Yh(this,"stats")}setByteRange(e,t){const i=e.split("@",2);let s;i.length===1?s=t?.byteRangeEndOffset||0:s=parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[re.AUDIO]:null,[re.VIDEO]:null,[re.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Yt),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=ji.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[re.AUDIO]=null,e[re.VIDEO]=null,e[re.AUDIOVIDEO]=null}},zt=class extends Yi{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(N(e)&&N(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const i=Object.keys(t);if(i.length===1){const s=this._decryptdata=t[i[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=N(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const i=Object.keys(this.levelkeys),s=i.length;if(s>1||s===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!N(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return de(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var i;const s=t[e];s&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=s.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,s,r,n=!1){const{elementaryStreams:a}=this,o=a[e];if(!o){a[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:r,partial:n};return}o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,s),o.endDTS=Math.max(o.endDTS,r)}},_r=class extends Yi{constructor(e,t,i,s,r){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}},kr=Math.pow(2,32)-1,$l=[].push,Cr={video:1,audio:2,id3:3,text:4},xr=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),ct={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}},zi={},Gl=/flac|opus|mp4a\.40\.34/i,Vl={supported:!0,powerEfficient:!0,smooth:!0},Kl={supported:!1,smooth:!1,powerEfficient:!1},Mr={supported:!0,configurations:[],decodingInfoResults:[Vl]},qi=["NONE","TYPE-0","TYPE-1",null],qt=["SDR","PQ","HLG"],Dt={No:"",Yes:"YES",v2:"v2"},Xi=class{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}},ht=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(i=>!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Xa(this._audioGroups,e)}hasSubtitleGroup(e){return Xa(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}},Hl=e=>{const t=new WeakSet;return(i,s)=>{if(e&&(s=e(i,s)),typeof s=="object"&&s!==null){if(t.has(s))return;t.add(s)}return s}},ne=(e,t)=>JSON.stringify(e,Hl(t)),Or=class extends we{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;const{fragCurrent:s,partCurrent:r,hls:n}=this,{autoLevelEnabled:a,media:o}=n;if(!s||!o)return;const l=performance.now(),d=r?r.stats:s.stats,c=r?r.duration:s.duration,h=l-d.loading.start,u=n.minAutoLevel,f=s.level,m=this._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||f<=u){this.clearTimer(),this._nextAutoLevel=-1;return}if(!a)return;const g=m>-1&&m!==f,y=!!t||g;if(!y&&(o.paused||!o.playbackRate||!o.readyState))return;const v=n.mainForwardBufferInfo;if(!y&&v===null)return;const E=this.bwEstimator.getEstimateTTFB(),T=Math.abs(o.playbackRate);if(h<=Math.max(E,1e3*(c/(T*2))))return;const S=v?v.len/T:0,A=d.loading.first?d.loading.first-d.loading.start:-1,b=d.loaded&&A>-1,I=this.getBwEstimate(),D=n.levels,w=D[f],P=Math.max(d.loaded,Math.round(c*(s.bitrate||w.averageBitrate)/8));let x=b?h-A:h;x<1&&b&&(x=Math.min(h,d.loaded*8/I));const U=b?d.loaded*1e3/x:0,O=E/1e3,V=U?(P-d.loaded)/U:P*8/I+O;if(V<=S)return;const F=U?U*8:I,M=((i=t?.details||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,W=this.hls.config.abrBandWidthUpFactor;let k=Number.POSITIVE_INFINITY,C;for(C=f-1;C>u;C--){const X=D[C].maxBitrate,Q=!D[C].details||M;if(k=this.getTimeToLoadFrag(O,F,c*X,Q),k<Math.min(S,c+O))break}if(k>=V||k>c*10)return;b?this.bwEstimator.sample(h-Math.min(E,A),d.loaded):this.bwEstimator.sampleTTFB(h);const G=D[C].maxBitrate;this.getBwEstimate()*W>G&&this.resetEstimator(G);const j=this.findBestLevel(G,u,C,0,S,1,1);j>-1&&(C=j),this.warn(`Fragment ${s.sn}${r?" part "+r.index:""} of level ${f} is loading too slowly;
|
|
52
|
+
`:(n=s.childNodes)!=null&&n.length?Il(s,t):t?i+s.textContent.trim().replace(/\s+/g," "):i+s.textContent},"")}function gg(e,t,i){const s="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=e!=null&&e.hasAttribute("style")?e.getAttribute("style"):null;return a&&i.hasOwnProperty(a)&&(r=i[a]),n.reduce((o,l)=>{const d=br(t,s,l)||br(e,s,l)||br(r,s,l);return d&&(o[l]=d),o},{})}function br(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function Al(e){return new Error(`Could not parse ttml timestamp ${e}`)}function Ir(e,t){if(!e)return null;let i=vl(e);return i===null&&(Ln.test(e)?i=mg(e,t):Rn.test(e)&&(i=pg(e,t))),i}function mg(e,t){const i=Ln.exec(e),s=(i[4]|0)+(i[5]|0)/t.subFrameRate;return(i[1]|0)*3600+(i[2]|0)*60+(i[3]|0)+s/t.frameRate}function pg(e,t){const i=Rn.exec(e),s=Number(i[1]);switch(i[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/t.frameRate;case"t":return s/t.tickRate}return s}function Ll(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function Rl(e,t){return!!e&&e.kind===Ll(t)&&ur(t,e)}function yg(e,t,i,s){return Math.min(t,s)-Math.max(e,i)}function Dl(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}function wl(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}function vg(e,t){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(se({},e.headers))};return e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),i}function Eg(e){const t=Ec.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function Tg(e){const t=e.get("Content-Range");if(t){const s=Eg(t);if(N(s))return s}const i=e.get("Content-Length");if(i)return parseInt(i)}function Sg(e,t){return new self.Request(e.url,t)}function bg(){return{cueHandler:wn,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 Ig(e,t,i){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=Ar(e),r=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return r.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,l=t[o]===void 0,d=[];n.forEach(c=>{const h=`${a}Loading${c}`,u=t[h];if(u!==void 0&&l){d.push(h);const f=s[o].default;switch(t[o]={default:f},c){case"TimeOut":f.maxLoadTimeMs=u,f.maxTimeToFirstByteMs=u;break;case"MaxRetry":f.errorRetry.maxNumRetry=u,f.timeoutRetry.maxNumRetry=u;break;case"RetryDelay":f.errorRetry.retryDelayMs=u,f.timeoutRetry.retryDelayMs=u;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=u,f.timeoutRetry.maxRetryDelayMs=u;break}}}),d.length&&i.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${ne(t[o])}`)}),ie(ie({},s),t)}function Ar(e){return e&&typeof e=="object"?Array.isArray(e)?e.map(Ar):Object.keys(e).reduce((t,i)=>(t[i]=Ar(e[i]),t),{}):e}function Ag(e,t){const i=e.loader;i!==gs&&i!==ms?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):wl()&&(e.loader=gs,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}function Pl(e,t){const i=_l(e.main);if(i&&i.start<=t)return i;const s=_l(e.audio);return s&&s.start<=t?s:null}function _l(e){if(!e)return null;switch(e.state){case _.IDLE:case _.STOPPED:case _.ENDED:case _.ERROR:return null}return e.frag}function Ki(e,t){return t.getAppendedFrag(e,B.MAIN)||t.getPartialFragment(e)}function Lr(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Rr(e,t,i,s,r){let n=new e(t,i,"");try{n.value=s,r&&(n.type=r)}catch{n=new e(t,i,ne(r?ie({type:r},s):s))}return n}function kl(e){const t={};e.forEach(i=>{const s=i.groupId||"";i.id=t[s]=t[s]||0,t[s]++})}function Cl(){return self.SourceBuffer||self.WebKitSourceBuffer}function Dr(){if(!Ye())return!1;const e=Cl();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function xl(){if(!Dr())return!1;const e=Ye();return typeof e?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(Bt(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(Bt(t,"audio"))))}function Lg(){var e;const t=Cl();return typeof(t==null||(e=t.prototype)==null?void 0:e.changeType)=="function"}function wr(e){if(e.keyFormat!==fe.FAIRPLAY){const t=e.keyId;if(t)return ye(t)}return e.uri}function Ml(e){const{type:t}=e;switch(t){case q.AUDIO_TRACK:return B.AUDIO;case q.SUBTITLE_TRACK:return B.SUBTITLE;default:return B.MAIN}}function Pr(e,t){let i=e.url;return(i===void 0||i.indexOf("data:")===0)&&(i=t.url),i}var N,Ol,Fl,$,L,p,q,B,dt,Nl,Pe,qe,Ul,Hi,te,Wi,Bl,ji,Yt,re,Yi,zt,_r,kr,$l,Cr,xr,ct,zi,Gl,Vl,Kl,Mr,qi,qt,Dt,Xi,ht,Hl,ne,Or,Fr,ce,Te,Nr,he,Wl,Xe,jl,Yl,zl,ql,Qi,Ur,Xl,Ve,Br,Xt,$r,Y,Gr,Ql,Vr,oe,Zl,Zi,Jl,Kr,Qt,ae,fe,Ji,ut,wt,Hr,Wr,ed,es,td,ft,id,_,Zt,jr,ts,sd,is,Pt,gt,Jt,rd,Se,ss,nd,ei,ad,od,ld,dd,cd,Yr,hd,ud,fd,gd,md,zr,_t,pd,yd,ge,vd,Ed,Qe,me,qr,Td,Sd,bd,Id,mt,rs,ti,Ad,Ze,ii,Xr,ns,Ld,Rd,Qr,Zr,Jr,en,si,tn,Dd,sn,rn,wd,nn,an,be,Pd,tt,_d,on,ln,kd,Cd,xd,Md,Od,Fd,Nd,Ud,Oe,le,it,Je,Bd,$d,dn,ri,as,ni,Gd,Vd,cn,hn,os,Kd,Hd,un,Wd,jd,Yd,zd,fn,gn,qd,mn,ls,Re,pn,yn,pt,ai,Xd,Qd,vn,Zd,Jd,ec,En,Tn,tc,ic,Sn,xe,Ke,sc,rc,nc,ac,oc,lc,st,bn,dc,cc,ds,In,An,cs,hc,uc,hs,oi,fc,gc,us,mc,pc,fs,Ln,Rn,yc,li,Dn,vc,wn,Ec,gs,Tc,Sc,ms,bc,di,Ic,Ac,Lc,Rc,Dc,ci,wc,Pc,_c,kc,Cc,xc,Mc,ps,Rg=ee((()=>{N=Number.isFinite||function(e){return typeof e=="number"&&isFinite(e)},Ol=Number.isSafeInteger||function(e){return typeof e=="number"&&Math.abs(e)<=Fl},Fl=Number.MAX_SAFE_INTEGER||9007199254740991,$=(function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e})({}),L=(function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e})({}),p=(function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e})({}),q={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},B={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},dt=class{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},Nl=class{constructor(e,t,i,s=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new dt(e),this.fast_=new dt(t),this.defaultTTFB_=s,this.ttfb_=new dt(e)}update(e,t){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new dt(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new dt(t,s.getEstimate(),s.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new dt(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const i=8*t,s=e/1e3,r=i/s;this.fast_.sample(s,r),this.slow_.sample(s,r)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}},Pe=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${e}]:`;this.trace=qe,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)}},qe=function(){},Ul={trace:qe,debug:qe,log:qe,warn:qe,info:qe,error:qe},Hi=Gs(),te=Hi,Wi={exports:{}},ji=jh(),Yt=class{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}},re={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},Yi=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,Yh(this,"stats")}setByteRange(e,t){const i=e.split("@",2);let s;i.length===1?s=t?.byteRangeEndOffset||0:s=parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[re.AUDIO]:null,[re.VIDEO]:null,[re.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Yt),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=ji.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[re.AUDIO]=null,e[re.VIDEO]=null,e[re.AUDIOVIDEO]=null}},zt=class extends Yi{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(N(e)&&N(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const i=Object.keys(t);if(i.length===1){const s=this._decryptdata=t[i[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=N(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const i=Object.keys(this.levelkeys),s=i.length;if(s>1||s===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!N(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return de(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var i;const s=t[e];s&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=s.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,s,r,n=!1){const{elementaryStreams:a}=this,o=a[e];if(!o){a[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:r,partial:n};return}o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,s),o.endDTS=Math.max(o.endDTS,r)}},_r=class extends Yi{constructor(e,t,i,s,r){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}},kr=Math.pow(2,32)-1,$l=[].push,Cr={video:1,audio:2,id3:3,text:4},xr=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),ct={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}},zi={},Gl=/flac|opus|mp4a\.40\.34/i,Vl={supported:!0,powerEfficient:!0,smooth:!0},Kl={supported:!1,smooth:!1,powerEfficient:!1},Mr={supported:!0,configurations:[],decodingInfoResults:[Vl]},qi=["NONE","TYPE-0","TYPE-1",null],qt=["SDR","PQ","HLG"],Dt={No:"",Yes:"YES",v2:"v2"},Xi=class{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}},ht=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(i=>!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Xa(this._audioGroups,e)}hasSubtitleGroup(e){return Xa(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}},Hl=e=>{const t=new WeakSet;return(i,s)=>{if(e&&(s=e(i,s)),typeof s=="object"&&s!==null){if(t.has(s))return;t.add(s)}return s}},ne=(e,t)=>JSON.stringify(e,Hl(t)),Or=class extends Pe{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;const{fragCurrent:s,partCurrent:r,hls:n}=this,{autoLevelEnabled:a,media:o}=n;if(!s||!o)return;const l=performance.now(),d=r?r.stats:s.stats,c=r?r.duration:s.duration,h=l-d.loading.start,u=n.minAutoLevel,f=s.level,m=this._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||f<=u){this.clearTimer(),this._nextAutoLevel=-1;return}if(!a)return;const g=m>-1&&m!==f,y=!!t||g;if(!y&&(o.paused||!o.playbackRate||!o.readyState))return;const v=n.mainForwardBufferInfo;if(!y&&v===null)return;const E=this.bwEstimator.getEstimateTTFB(),T=Math.abs(o.playbackRate);if(h<=Math.max(E,1e3*(c/(T*2))))return;const S=v?v.len/T:0,A=d.loading.first?d.loading.first-d.loading.start:-1,b=d.loaded&&A>-1,I=this.getBwEstimate(),D=n.levels,P=D[f],w=Math.max(d.loaded,Math.round(c*(s.bitrate||P.averageBitrate)/8));let x=b?h-A:h;x<1&&b&&(x=Math.min(h,d.loaded*8/I));const U=b?d.loaded*1e3/x:0,O=E/1e3,V=U?(w-d.loaded)/U:w*8/I+O;if(V<=S)return;const F=U?U*8:I,M=((i=t?.details||this.hls.latestLevelDetails)==null?void 0:i.live)===!0,W=this.hls.config.abrBandWidthUpFactor;let k=Number.POSITIVE_INFINITY,C;for(C=f-1;C>u;C--){const X=D[C].maxBitrate,Q=!D[C].details||M;if(k=this.getTimeToLoadFrag(O,F,c*X,Q),k<Math.min(S,c+O))break}if(k>=V||k>c*10)return;b?this.bwEstimator.sample(h-Math.min(E,A),d.loaded):this.bwEstimator.sampleTTFB(h);const G=D[C].maxBitrate;this.getBwEstimate()*W>G&&this.resetEstimator(G);const j=this.findBestLevel(G,u,C,0,S,1,1);j>-1&&(C=j),this.warn(`Fragment ${s.sn}${r?" part "+r.index:""} of level ${f} is loading too slowly;
|
|
53
53
|
Fragment duration: ${s.duration.toFixed(3)}
|
|
54
54
|
Time to underbuffer: ${S.toFixed(3)} s
|
|
55
55
|
Estimated load time for current fragment: ${V.toFixed(3)} s
|
|
@@ -59,26 +59,26 @@ ${i.m3u8}`)}function Do(e,t,i=!0){const s=t.startSN+t.skippedSegments-e.startSN,
|
|
|
59
59
|
New BW estimate: ${this.getBwEstimate()|0} bps
|
|
60
60
|
Switching to level ${C} @ ${G|0} bps`),n.nextLoadLevel=n.nextAutoLevel=C,this.clearTimer();const J=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===C&&C>0){const X=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${C>0?"and switching down":""}
|
|
61
61
|
Fragment duration: ${s.duration.toFixed(3)} s
|
|
62
|
-
Time to underbuffer: ${X.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,C>u){let Q=this.findBestLevel(this.hls.levels[u].bitrate,u,C,0,X,1,1);Q===-1&&(Q=u),this.hls.nextLoadLevel=this.hls.nextAutoLevel=Q,this.resetEstimator(this.hls.levels[Q].bitrate)}}};g||V>k*2?J():this.timer=self.setInterval(J,k*1e3),n.trigger(p.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:r,stats:d})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new Nl(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(p.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var s;this.fragCurrent=i,this.partCurrent=(s=t.part)!=null?s:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case L.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:s,partCurrent:r}=this;if(i&&s&&i.sn===s.sn&&i.level===s.level){const n=performance.now(),a=r?r.stats:i.stats,o=n-a.loading.start,l=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&l>-1){const d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(d,l),a.loaded)}else this.bwEstimator.sampleTTFB(o)}break}}}getTimeToLoadFrag(e,t,i,s){return e+i/t+(s?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const i=this.hls.config,{loading:s}=t.stats,r=s.end-s.first;N(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const s=i?i.stats:t.stats;if(t.type===B.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=i?i.duration:t.duration,n=this.hls.levels[t.level],a=(n.loaded?n.loaded.bytes:0)+s.loaded,o=(n.loaded?n.loaded.duration:0)+r;n.loaded={bytes:a,duration:o},n.realBitrate=Math.round(8*a/o)}if(t.bitrateTest){const r={stats:s,frag:t,part:i,id:t.type};this.onFragBuffered(p.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:s}=t,r=s!=null&&s.stats.loaded?s.stats:i.stats;if(r.aborted||this.ignoreFragment(i))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==B.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,t,e,0,s,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!t||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const s=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const r=this.hls.levels;if(r.length>Math.max(e,s)&&r[e].loadError<=r[s].loadError)return e}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:s,config:r,minAutoLevel:n}=i,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=r.abrBandWidthFactor,c=r.abrBandWidthUpFactor;if(l){const g=this.findBestLevel(o,n,s,l,0,d,c);if(g>=0)return this.rebufferNotice=-1,g}let h=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const g=this.bitrateTestDelay;g&&(h=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-g,this.info(`bitrate test took ${Math.round(1e3*g)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),d=c=1)}const u=this.findBestLevel(o,n,s,l,h,d,c);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=i.levels[n],m=i.loadLevelObj;return m&&f?.bitrate<m.bitrate?n:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,s,r,n,a){var o;const l=s+r,d=this.lastLoadedFragLevel,c=d===-1?this.hls.firstLevel:d,{fragCurrent:h,partCurrent:u}=this,{levels:f,allAudioTracks:m,loadLevel:g,config:y}=this.hls;if(f.length===1)return 0;const v=f[c],E=!!((o=this.hls.latestLevelDetails)!=null&&o.live),T=g===-1||d===-1;let S,A="SDR",b=v?.frameRate||0;const{audioPreference:I,videoPreference:D}=y,w=this.audioTracksByGroup||(this.audioTracksByGroup=Qa(m));let P=-1;if(T){if(this.firstSelection!==-1)return this.firstSelection;const F=Su(this.codecTiers||(this.codecTiers=bu(f,w,t,i)),A,e,I,D),{codecSet:M,videoRanges:W,minFramerate:k,minBitrate:C,minIndex:G,preferHDR:j}=F;P=G,S=M,A=j?W[W.length-1]:W[0],b=k,e=Math.max(e,C),this.log(`picked start tier ${ne(F)}`)}else S=v?.codecSet,A=v?.videoRange;const x=u?u.duration:h?h.duration:0,U=this.bwEstimator.getEstimateTTFB()/1e3,O=[];for(let F=i;F>=t;F--){var V;const M=f[F],W=F>c;if(!M)continue;if(y.useMediaCapabilities&&!M.supportedResult&&!M.supportedPromise){const X=navigator.mediaCapabilities;typeof X?.decodingInfo=="function"&&uu(M,w,A,b,e,I)?(M.supportedPromise=Ya(M,w,X,this.supportedCache),M.supportedPromise.then(Q=>{if(!this.hls)return;M.supportedResult=Q;const Ie=this.hls.levels,_e=Ie.indexOf(M);Q.error?this.warn(`MediaCapabilities decodingInfo error: "${Q.error}" for level ${_e} ${ne(Q)}`):Q.supported?Q.decodingInfoResults.some(He=>He.smooth===!1||He.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${_e} not smooth or powerEfficient: ${ne(Q)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${_e} ${ne(Q)}`),_e>-1&&Ie.length>1&&(this.log(`Removing unsupported level ${_e}`),this.hls.removeLevel(_e),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Q=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Q}`)})):M.supportedResult=Mr}if((S&&M.codecSet!==S||A&&M.videoRange!==A||W&&b>M.frameRate||!W&&b>0&&b<M.frameRate||(V=M.supportedResult)!=null&&(V=V.decodingInfoResults)!=null&&V.some(X=>X.smooth===!1))&&(!T||F!==P)){O.push(F);continue}const k=M.details,C=(u?k?.partTarget:k?.averagetargetduration)||x;let G;W?G=a*e:G=n*e;const j=x&&s>=x*2&&r===0?M.averageBitrate:M.maxBitrate,J=this.getTimeToLoadFrag(U,G,j*C,k===void 0);if(G>=j&&(F===d||M.loadError===0&&M.fragmentError===0)&&(J<=U||!N(J)||E&&!this.bitrateTestDelay||J<l)){const X=this.forcedAutoLevel;return F!==g&&(X===-1||X!==g)&&(O.length&&this.trace(`Skipped level(s) ${O.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[O[0]].codecs}" ${f[O[0]].videoRange}; not compatible with "${S}" ${A}`),this.info(`switch candidate:${c}->${F} adjustedbw(${Math.round(G)})-bitrate=${Math.round(G-j)} ttfb:${U.toFixed(1)} avgDuration:${C.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${J.toFixed(1)} firstSelection:${T} codecSet:${M.codecSet} videoRange:${M.videoRange} hls.loadLevel:${g}`)),T&&(this.firstSelection=F),F}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},Fr={search:function(e,t){let i=0,s=e.length-1,r=null,n=null;for(;i<=s;){r=(i+s)/2|0,n=e[r];const a=t(n);if(a>0)i=r+1;else if(a<0)s=r-1;else return n}return null}},ce={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Te={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8},Nr=class extends we{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.ERROR,this.onError,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.ERROR,this.onError,this),e.off(p.ERROR,this.onErrorOut,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===B.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,i=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return!0;const s=e.audioGroups;if(s)return this.hls.allAudioTracks.filter(r=>s.indexOf(r.groupId)>=0).some(r=>{var n;return(n=r.details)==null?void 0:n.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const s=this.hls,r=t.context;switch(t.details){case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case L.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=Tt();return}case L.FRAG_GAP:case L.FRAG_DECRYPT_ERROR:t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=ce.SendAlternateToPenaltyBox;return;case L.LEVEL_EMPTY_ERROR:case L.LEVEL_PARSING_ERROR:{var n;const o=t.parent===B.MAIN?t.level:s.loadLevel;t.details===L.LEVEL_EMPTY_ERROR&&((n=t.context)!=null&&(n=n.levelDetails)!=null&&n.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,o))}return;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.SUBTITLE_LOAD_ERROR:case L.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const o=s.loadLevelObj;if(o&&(r.type===q.AUDIO_TRACK&&o.hasAudioGroup(r.groupId)||r.type===q.SUBTITLE_TRACK&&o.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=ce.SendAlternateToPenaltyBox,t.errorAction.flags=Te.MoveAllAlternatesMatchingHost;return}}return;case L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:ce.SendAlternateToPenaltyBox,flags:Te.MoveAllAlternatesMatchingHDCP};return;case L.KEY_SYSTEM_SESSION_UPDATE_FAILED:case L.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case L.KEY_SYSTEM_NO_SESSION:t.errorAction={action:ce.SendAlternateToPenaltyBox,flags:Te.MoveAllAlternatesMatchingKey};return;case L.BUFFER_ADD_CODEC_ERROR:case L.REMUX_ALLOC_ERROR:case L.BUFFER_APPEND_ERROR:if(!t.errorAction){var a;t.errorAction=this.getLevelSwitchAction(t,(a=t.level)!=null?a:s.loadLevel)}return;case L.INTERNAL_EXCEPTION:case L.BUFFER_APPENDING_ERROR:case L.BUFFER_FULL_ERROR:case L.LEVEL_SWITCH_ERROR:case L.BUFFER_STALLED_ERROR:case L.BUFFER_SEEK_OVER_HOLE:case L.BUFFER_NUDGE_ON_STALL:t.errorAction=Tt();return}t.type===$.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Tt())}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,s=ro(i.config.playlistLoadPolicy,e),r=this.playlistError++;if(_i(s,r,wi(e),e.response))return{action:ce.RetryRequest,flags:Te.None,retryConfig:s,retryCount:r};const n=this.getLevelSwitchAction(e,t);return s&&(n.retryConfig=s,n.retryCount=r),n}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,a=ro(io(e)?n:r,e),o=t.levels.reduce((d,c)=>d+c.fragmentError,0);if(s&&(e.details!==L.FRAG_GAP&&s.fragmentError++,!so(e)&&_i(a,o,wi(e),e.response)))return{action:ce.RetryRequest,flags:Te.None,retryConfig:a,retryCount:o};const l=this.getLevelSwitchAction(e,i);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const s=this.hls.levels[t];if(s){var r,n;const l=e.details;s.loadError++,l===L.BUFFER_APPEND_ERROR&&s.fragmentError++;let d=-1;const{levels:c,loadLevel:h,minAutoLevel:u,maxAutoLevel:f}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);const m=(r=e.frag)==null?void 0:r.type,g=(m===B.AUDIO&&l===L.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===L.BUFFER_ADD_CODEC_ERROR||l===L.BUFFER_APPEND_ERROR))&&c.some(({audioCodec:T})=>s.audioCodec!==T),y=e.sourceBufferName==="video"&&(l===L.BUFFER_ADD_CODEC_ERROR||l===L.BUFFER_APPEND_ERROR)&&c.some(({codecSet:T,audioCodec:S})=>s.codecSet!==T&&s.audioCodec===S),{type:v,groupId:E}=(n=e.context)!=null?n:{};for(let T=c.length;T--;){const S=(T+h)%c.length;if(S!==h&&S>=u&&S<=f&&c[S].loadError===0){var a,o;const A=c[S];if(l===L.FRAG_GAP&&m===B.MAIN&&e.frag){const b=c[S].details;if(b){const I=lt(e.frag,b.fragments,e.frag.start);if(I!=null&&I.gap)continue}}else{if(v===q.AUDIO_TRACK&&A.hasAudioGroup(E)||v===q.SUBTITLE_TRACK&&A.hasSubtitleGroup(E))continue;if(m===B.AUDIO&&(a=s.audioGroups)!=null&&a.some(b=>A.hasAudioGroup(b))||m===B.SUBTITLE&&(o=s.subtitleGroups)!=null&&o.some(b=>A.hasSubtitleGroup(b))||g&&s.audioCodec===A.audioCodec||y&&s.codecSet===A.codecSet||!g&&s.codecSet!==A.codecSet)continue}d=S;break}}if(d>-1&&i.loadLevel!==d)return e.levelRetry=!0,this.playlistError=0,{action:ce.SendAlternateToPenaltyBox,flags:Te.None,nextAutoLevel:d}}return{action:ce.SendAlternateToPenaltyBox,flags:Te.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case ce.DoNothing:break;case ce.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==L.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;case ce.RetryRequest:break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:s}=i,r=i.nextAutoLevel;switch(s){case Te.None:this.switchLevel(e,r);break;case Te.MoveAllAlternatesMatchingHDCP:{const o=this.getVariantLevelIndex(e.frag),l=t.levels[o],d=l?.attrs["HDCP-LEVEL"];if(i.hdcpLevel=d,d==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(d){t.maxHdcpLevel=qi[qi.indexOf(d)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Te.MoveAllAlternatesMatchingKey:{const o=e.decryptdata;if(o){const l=this.hls.levels,d=l.length;for(let h=d;h--;)if(this.variantHasKey(l[h],o)){var n,a;this.log(`Banned key found in level ${h} (${l[h].bitrate}bps) or audio group "${(n=l[h].audioGroups)==null?void 0:n.join(",")}" (${(a=e.frag)==null?void 0:a.type} fragment) ${ye(o.keyId||[])}`),l[h].fragmentError++,l[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h)}const c=e.frag;if(this.hls.levels.length<d)i.resolved=!0;else if(c&&c.type!==B.MAIN){const h=c.decryptdata;h&&!o.matches(h)&&(i.resolved=!0)}}break}}i.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===L.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const i=js(e.mimeType),s=this.hls.levels;for(let r=s.length;r--;)s[r][`${e.sourceBufferName}Codec`]===i&&(this.log(`Removing level ${r} for ${e.details} ("${i}" not supported)`),this.hls.removeLevel(r))}}},he={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Wl=class{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let s=i.length;s--;){const r=i[s];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){const{fragments:s}=this,r=Object.keys(s);for(let n=r.length;n--;){const a=s[r[n]];if(a?.body.type===t&&(!i||a.buffered)){const o=a.body;if(o.start<=e&&e<=o.end)return o}}return null}detectEvictedFragments(e,t,i,s,r){this.timeRanges&&(this.timeRanges[e]=t);const n=s?.fragment.sn||-1;Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o||n>=o.body.sn)return;if(!o.buffered&&(!o.loaded||r)){o.body.type===i&&this.removeFragment(o.body);return}const l=o.range[e];if(l){if(l.time.length===0){this.removeFragment(o.body);return}l.time.some(d=>{const c=!this.isTimeBuffered(d.startPTS,d.endPTS,t);return c&&this.removeFragment(o.body),c})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const i=e.frag,s=St(i),r=this.fragments[s];if(!r||r.buffered&&i.gap)return;const n=!i.relurl;Object.keys(t).forEach(a=>{const o=i.elementaryStreams[a];if(!o)return;const l=t[a],d=n||o.partial===!0;r.range[a]=this.getBufferedTimes(i,e.part,d,l)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,i),ki(r)||this.removeParts(i.sn-1,i.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=ao(i,s=>s.fragment.sn>=e))}fragBuffered(e,t){const i=St(e);let s=this.fragments[i];!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,this.bufferedEnd(s,e))}getBufferedTimes(e,t,i,s){const r={time:[],partial:i},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let d=0;d<s.length;d++){const c=s.start(d)-this.bufferPadding,h=s.end(d)+this.bufferPadding;if(l>=c&&o<=h){r.time.push({startPTS:Math.max(n,s.start(d)),endPTS:Math.min(a,s.end(d))});break}else if(n<h&&a>c){const u=Math.max(n,s.start(d)),f=Math.min(a,s.end(d));f>u&&(r.partial=!0,r.time.push({startPTS:u,endPTS:f}))}else if(a<=c)break}return r}getPartialFragment(e){let t=null,i,s,r,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&ki(d)&&(s=d.body.start-a,r=d.body.end+a,e>=s&&e<=r&&(i=Math.min(e-s,r-e),n<=i&&(t=d.body,n=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||ki(t))}getState(e){const t=St(e),i=this.fragments[t];return i?i.buffered?ki(i)?he.PARTIAL:he.OK:he.APPENDING:he.NOT_LOADED}isTimeBuffered(e,t,i){let s,r;for(let n=0;n<i.length;n++){if(s=i.start(n)-this.bufferPadding,r=i.end(n)+this.bufferPadding,e>=s&&t<=r)return!0;if(t<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const i=t.frag,s=t.part?null:t,r=St(i);this.fragments[r]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:s,timeRanges:r,type:n}=t;if(i.sn==="initSegment")return;const a=i.type;if(s){let l=this.activePartLists[a];l||(this.activePartLists[a]=l=[]),l.push(s)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,s)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=St(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let s=i.length;s--;){const r=t[i[s]];if(r?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,s,r){s&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==i||s&&!o.gap||o.start<t&&o.end>e&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(e){const t=St(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const s=e.sn;this.activePartLists[e.type]=ao(i,r=>r.fragment.sn!==s)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo())}},Xe={cbc:0,ctr:1},jl=class{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case Xe.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Xe.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}},Yl=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=t.getUint32(s*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],r=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],d=o[1],c=o[2],h=o[3],u=new Uint32Array(256);let f=0,m=0,g=0;for(g=0;g<256;g++)g<128?u[g]=g<<1:u[g]=g<<1^283;for(g=0;g<256;g++){let y=m^m<<1^m<<2^m<<3^m<<4;y=y>>>8^y&255^99,e[f]=y,t[y]=f;const v=u[f],E=u[v],T=u[E];let S=u[y]*257^y*16843008;s[f]=S<<24|S>>>8,r[f]=S<<16|S>>>16,n[f]=S<<8|S>>>24,a[f]=S,S=T*16843009^E*65537^v*257^f*16843008,l[y]=S<<24|S>>>8,d[y]=S<<16|S>>>16,c[y]=S<<8|S>>>24,h[y]=S,f?(f=v^u[u[u[T^v]]],m^=u[u[m]]):f=m=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,s=0;for(;s<t.length&&i;)i=t[s]===this.key[s],s++;if(i)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const n=this.ksRows=(r+6+1)*4;let a,o;const l=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),c=this.sBox,h=this.rcon,u=this.invSubMix,f=u[0],m=u[1],g=u[2],y=u[3];let v,E;for(a=0;a<n;a++){if(a<r){v=l[a]=t[a];continue}E=v,a%r===0?(E=E<<8|E>>>24,E=c[E>>>24]<<24|c[E>>>16&255]<<16|c[E>>>8&255]<<8|c[E&255],E^=h[a/r|0]<<24):r>6&&a%r===4&&(E=c[E>>>24]<<24|c[E>>>16&255]<<16|c[E>>>8&255]<<8|c[E&255]),l[a]=v=(l[a-r]^E)>>>0}for(o=0;o<n;o++)a=n-o,o&3?E=l[a]:E=l[a-4],o<4||a<=4?d[o]=E:d[o]=f[c[E>>>24]]^m[c[E>>>16&255]]^g[c[E>>>8&255]]^y[c[E&255]],d[o]=d[o]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const s=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],c=a[3],h=this.uint8ArrayToUint32Array_(i);let u=h[0],f=h[1],m=h[2],g=h[3];const y=new Int32Array(e),v=new Int32Array(y.length);let E,T,S,A,b,I,D,w,P,x,U,O,V,F;const M=this.networkToHostOrderSwap;for(;t<y.length;){for(P=M(y[t]),x=M(y[t+1]),U=M(y[t+2]),O=M(y[t+3]),b=P^r[0],I=O^r[1],D=U^r[2],w=x^r[3],V=4,F=1;F<s;F++)E=o[b>>>24]^l[I>>16&255]^d[D>>8&255]^c[w&255]^r[V],T=o[I>>>24]^l[D>>16&255]^d[w>>8&255]^c[b&255]^r[V+1],S=o[D>>>24]^l[w>>16&255]^d[b>>8&255]^c[I&255]^r[V+2],A=o[w>>>24]^l[b>>16&255]^d[I>>8&255]^c[D&255]^r[V+3],b=E,I=T,D=S,w=A,V=V+4;E=n[b>>>24]<<24^n[I>>16&255]<<16^n[D>>8&255]<<8^n[w&255]^r[V],T=n[I>>>24]<<24^n[D>>16&255]<<16^n[w>>8&255]<<8^n[b&255]^r[V+1],S=n[D>>>24]<<24^n[w>>16&255]<<16^n[b>>8&255]<<8^n[I&255]^r[V+2],A=n[w>>>24]<<24^n[b>>16&255]<<16^n[I>>8&255]<<8^n[D&255]^r[V+3],v[t]=M(E^u),v[t+1]=M(A^f),v[t+2]=M(S^m),v[t+3]=M(T^g),u=P,f=x,m=U,g=O,t=t+4}return v.buffer}},zl=class{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){const e=ku(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}},ql=16,Qi=class{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?_u(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,s){return this.useSoftware?new Promise((r,n)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,i,s);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,s)}softwareDecrypt(e,t,i,s){const{currentIV:r,currentResult:n,remainderData:a}=this;if(s!==Xe.cbc||t.byteLength!==16)return te.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=Ce(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;r&&(i=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Yl),l.expandKey(t);const d=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,d||null}webCryptoDecrypt(e,t,i,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,s));this.key=t,this.fastAesKey=new zl(this.subtle,t,s)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new jl(this.subtle,new Uint8Array(i),s).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(te.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i,s)))}onWebCryptoError(e,t,i,s){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,s);const n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%ql;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(te.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},Ur=Math.pow(2,17),Xl=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const i=e.url;if(!i)return Promise.reject(new Ve({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const s=this.config,r=s.fLoader,n=s.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){o(lo(e));return}else e.gap=!1;const l=this.loader=r?new r(s):new n(s),d=oo(e);e.loader=l;const c=no(s.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Ur};e.stats=l.stats;const u={onSuccess:(f,m,g,y)=>{this.resetLoader(e,l);let v=f.data;g.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(v.slice(0,16)),v=v.slice(16)),a({frag:e,part:null,payload:v,networkDetails:y})},onError:(f,m,g,y)=>{this.resetLoader(e,l),o(new Ve({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:ie({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:y}))},onAbort:(f,m,g)=>{this.resetLoader(e,l),o(new Ve({type:$.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,m,g)=>{this.resetLoader(e,l),o(new Ve({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:f}))}};t&&(u.onProgress=(f,m,g,y)=>t({frag:e,part:null,payload:g,networkDetails:y})),l.load(d,h,u)})}loadPart(e,t,i){this.abort();const s=this.config,r=s.fLoader,n=s.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){o(lo(e,t));return}const l=this.loader=r?new r(s):new n(s),d=oo(e,t);e.loader=l;const c=no(s.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ur};t.stats=l.stats,l.load(d,h,{onSuccess:(u,f,m,g)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const y={frag:e,part:t,payload:u.data,networkDetails:g};i(y),a(y)},onError:(u,f,m,g)=>{this.resetLoader(e,l),o(new Ve({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:ie({url:d.url,data:void 0},u),error:new Error(`HTTP Error ${u.code} ${u.text}`),networkDetails:m,stats:g}))},onAbort:(u,f,m)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new Ve({type:$.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:m,stats:u}))},onTimeout:(u,f,m)=>{this.resetLoader(e,l),o(new Ve({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:m,stats:u}))}})})}updateStatsFromPart(e,t){const i=e.stats,s=t.stats,r=s.total;if(i.loaded+=s.loaded,r){const o=Math.round(e.duration/t.duration),l=Math.min(Math.round(i.loaded/r),o),d=(o-l)*Math.round(i.loaded/l);i.total=i.loaded+d}else i.total=Math.max(i.loaded,i.total);const n=i.loading,a=s.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}},Ve=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},Br=class extends we{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},Xt=class{constructor(e,t,i,s=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=Ci(),this.buffering={audio:Ci(),video:Ci(),audiovideo:Ci()},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=r,this.partial=n}},$r={length:0,start:()=>0,end:()=>0},Y=class kt{static isBuffered(t,i){if(t){const s=kt.getBuffered(t);for(let r=s.length;r--;)if(i>=s.start(r)&&i<=s.end(r))return!0}return!1}static bufferedRanges(t){if(t){const i=kt.getBuffered(t);return kt.timeRangesToArray(i)}return[]}static timeRangesToArray(t){const i=[];for(let s=0;s<t.length;s++)i.push({start:t.start(s),end:t.end(s)});return i}static bufferInfo(t,i,s){if(t){const r=kt.bufferedRanges(t);if(r.length)return kt.bufferedInfo(r,i,s)}return{len:0,start:i,end:i,bufferedIndex:-1}}static bufferedInfo(t,i,s){i=Math.max(0,i),t.length>1&&t.sort((c,h)=>c.start-h.start||h.end-c.end);let r=-1,n=[];if(s)for(let c=0;c<t.length;c++){i>=t[c].start&&i<=t[c].end&&(r=c);const h=n.length;if(h){const u=n[h-1].end;t[c].start-u<s?t[c].end>u&&(n[h-1].end=t[c].end):n.push(t[c])}else n.push(t[c])}else n=t;let a=0,o,l=i,d=i;for(let c=0;c<n.length;c++){const h=n[c].start,u=n[c].end;if(r===-1&&i>=h&&i<=u&&(r=c),i+s>=h&&i<u)l=h,d=u,a=d-i;else if(i+s<h){o=h;break}}return{len:a,start:l||0,end:d||0,nextStart:o,buffered:t,bufferedIndex:r}}static getBuffered(t){try{return t.buffered||$r}catch(i){return te.log("failed to get media.buffered",i),$r}}},Gr=/\{\$([a-zA-Z0-9-_]+)\}/g,Ql=/^(\d+)x(\d+)$/,Vr=/(.+?)=(".*?"|.*?)(?:,|$)/g,oe=class jc{constructor(t,i){typeof t=="string"&&(t=jc.parseAttrList(t,i)),se(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>t.substring(0,2)==="X-")}decimalInteger(t){const i=parseInt(this[t],10);return i>Number.MAX_SAFE_INTEGER?1/0:i}hexadecimalInteger(t){if(this[t]){let i=(this[t]||"0x").slice(2);i=(i.length&1?"0":"")+i;const s=new Uint8Array(i.length/2);for(let r=0;r<i.length/2;r++)s[r]=parseInt(i.slice(r*2,r*2+2),16);return s}return null}hexadecimalIntegerAsNumber(t){const i=parseInt(this[t],16);return i>Number.MAX_SAFE_INTEGER?1/0:i}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,i){const s=this[t];return s?parseFloat(s):i}enumeratedString(t){return this[t]}enumeratedStringList(t,i){const s=this[t];return(s?s.split(/[ ,]+/):[]).reduce((r,n)=>(r[n.toLowerCase()]=!0,r),i)}bool(t){return this[t]==="YES"}decimalResolution(t){const i=Ql.exec(this[t]);if(i!==null)return{width:parseInt(i[1],10),height:parseInt(i[2],10)}}static parseAttrList(t,i){let s;const r={};for(Vr.lastIndex=0;(s=Vr.exec(t))!==null;){const a=s[1].trim();let o=s[2];const l=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1;let d=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(i&&(l||d))o=qs(i,o);else if(!d&&!l)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":te.warn(`${t}: attribute ${a} is missing quotes`)}r[a]=o}return r}},Zl="com.apple.hls.interstitial",Zi=class{constructor(e,t,i=0){var s;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(s=t?.tagOrder)!=null?s:i,t){const r=t.attr;for(const n in r)if(Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==r[n]){te.warn(`DATERANGE tag attribute: "${n}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=n;break}e=se(new oe({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const r=t?.endDate||new Date(this.attr["END-DATE"]);N(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(te.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(N(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===Zl}get isValid(){return!!this.id&&!this._badValueForSameId&&N(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}},Jl=10,Kr=class{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?N(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Jl}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}},Qt=typeof self<"u"?self:void 0,ae={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},fe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"},Ji=(function(e){return Qt!=null&&(e=Qt.navigator)!=null&&e.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})(),ut={},Pt=class ys{static clearKeyUriToKeyIdMap(){ut={}}static setKeyIdForUri(t,i){ut[t]=i}static addKeyIdForUri(t){const i=Object.keys(ut).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,i),ut[t]=s,s}constructor(t,i,s,r=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=i,this.keyFormat=s,this.keyFormatVersions=r,this.iv=n,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!bt(t),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(xa(a)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&xi(t.keyFormatVersions,this.keyFormatVersions)&&uo(t.iv,this.iv)&&uo(t.keyId,this.keyId)}isSupported(){if(this.method){if(bt(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case fe.FAIRPLAY:case fe.WIDEVINE:case fe.PLAYREADY:case fe.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(t,i){if(!this.encrypted||!this.uri)return null;if(bt(this.method)){let n=this.iv;return n||(typeof t!="number"&&(te.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),n=Gu(t)),new ys(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){const n=ut[this.uri];if(n&&!xi(this.keyId,n)&&ys.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=go(this.uri);if(s)switch(this.keyFormat){case fe.WIDEVINE:if(this.pssh=s,!this.keyId){const n=au(s.buffer);if(n.length){var r;const a=n[0];this.keyId=(r=a.kids)!=null&&r.length?a.kids[0]:null}}this.keyId||(this.keyId=po(i));break;case fe.PLAYREADY:{const n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=nu(n,null,s),this.keyId=mo(s);break}default:{let n=s.subarray(0,16);if(n.length!==16){const a=new Uint8Array(16);a.set(n,16-n.length),n=a}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n;n=$u(i),n||(n=po(i),n||(n=ut[this.uri])),n&&(this.keyId=n,ys.setKeyIdForUri(this.uri,n))}return this}},Hr=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Wr=/#EXT-X-MEDIA:(.*)/g,ed=/^#EXT(?:INF|-X-TARGETDURATION):/m,es=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),td=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),ft=class fi{static findGroup(t,i){for(let s=0;s<t.length;s++){const r=t[s];if(r.id===i)return r}}static resolve(t,i){return ji.buildAbsoluteURL(i,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return ed.test(t)}static parseMasterPlaylist(t,i){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:co(t)},r=[];if(Hr.lastIndex=0,!t.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let n;for(;(n=Hr.exec(t))!=null;)if(n[1]){var a;const o=new oe(n[1],s),l=qs(s,n[2]),d={attrs:o,bitrate:o.decimalInteger("BANDWIDTH")||o.decimalInteger("AVERAGE-BANDWIDTH"),name:o.NAME,url:fi.resolve(l,i)},c=o.decimalResolution("RESOLUTION");c&&(d.width=c.width,d.height=c.height),To(o.CODECS,d);const h=o["SUPPLEMENTAL-CODECS"];h&&(d.supplemental={},To(h,d.supplemental)),(a=d.unknownCodecs)!=null&&a.length||r.push(d),s.levels.push(d)}else if(n[3]){const o=n[3],l=n[4];switch(o){case"SESSION-DATA":{const d=new oe(l,s),c=d["DATA-ID"];c&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[c]=d);break}case"SESSION-KEY":{const d=vo(l,i,s);d.encrypted&&d.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(d)):te.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${l}"`);break}case"DEFINE":ho(s,new oe(l,s),i);break;case"CONTENT-STEERING":{const d=new oe(l,s);s.contentSteering={uri:fi.resolve(d["SERVER-URI"],i),pathwayId:d["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=Eo(l);break}}return s.levels=r.length>0&&r.length<s.levels.length?r:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,i,s){let r;const n={},a=s.levels,o={AUDIO:a.map(d=>({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:a.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Wr.lastIndex=0;(r=Wr.exec(t))!==null;){const d=new oe(r[1],s),c=d.TYPE;if(c){const h=o[c],u=n[c]||[];n[c]=u;const f=d.LANGUAGE,m=d["ASSOC-LANGUAGE"],g=d.CHANNELS,y=d.CHARACTERISTICS,v=d["INSTREAM-ID"],E={attrs:d,bitrate:0,id:l++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:c,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?fi.resolve(d.URI,i):""};if(m&&(E.assocLang=m),g&&(E.channels=g),y&&(E.characteristics=y),v&&(E.instreamId=v),h!=null&&h.length){const T=fi.findGroup(h,E.groupId)||h[0];So(E,T,"audioCodec"),So(E,T,"textCodec")}u.push(E)}}return n}static parseLevelPlaylist(t,i,s,r,n,a){var o;const l={url:i},d=new Kr(i),c=d.fragments,h=[];let u=null,f=0,m=0,g=0,y=0,v=0,E=null,T=new zt(r,l),S,A,b,I=-1,D=!1,w=null,P;if(es.lastIndex=0,d.m3u8=t,d.hasVariableRefs=co(t),((o=es.exec(t))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(S=es.exec(t))!==null;){D&&(D=!1,T=new zt(r,l),T.playlistOffset=g,T.setStart(g),T.sn=f,T.cc=y,v&&(T.bitrate=v),T.level=s,u&&(T.initSegment=u,u.rawProgramDateTime&&(T.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null),w&&(T.setByteRange(w),w=null)));const V=S[1];if(V){T.duration=parseFloat(V);const F=(" "+S[2]).slice(1);T.title=F||null,T.tagList.push(F?["INF",V,F]:["INF",V])}else if(S[3]){if(N(T.duration)){T.playlistOffset=g,T.setStart(g),b&&Io(T,b,d),T.sn=f,T.level=s,T.cc=y,c.push(T);const F=(" "+S[3]).slice(1);T.relurl=qs(d,F),er(T,E,h),E=T,g+=T.duration,f++,m=0,D=!0}}else{if(S=S[0].match(td),!S){te.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A<S.length&&S[A]===void 0;A++);const F=(" "+S[A]).slice(1),M=(" "+S[A+1]).slice(1),W=S[A+2]?(" "+S[A+2]).slice(1):null;switch(F){case"BYTERANGE":E?T.setByteRange(M,E):T.setByteRange(M);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=M,T.tagList.push(["PROGRAM-DATE-TIME",M]),I===-1&&(I=c.length);break;case"PLAYLIST-TYPE":d.type&&ze(d,F,S),d.type=M.toUpperCase();break;case"MEDIA-SEQUENCE":d.startSN!==0?ze(d,F,S):c.length>0&&Ao(d,F,S),f=d.startSN=parseInt(M);break;case"SKIP":{d.skippedSegments&&ze(d,F,S);const k=new oe(M,d),C=k.decimalInteger("SKIPPED-SEGMENTS");if(N(C)){d.skippedSegments+=C;for(let j=C;j--;)c.push(null);f+=C}const G=k.enumeratedString("RECENTLY-REMOVED-DATERANGES");G&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(G.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&ze(d,F,S),d.targetduration=Math.max(parseInt(M),1);break;case"VERSION":d.version!==null&&ze(d,F,S),d.version=parseInt(M);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||ze(d,F,S),d.live=!1;break;case"#":(M||W)&&T.tagList.push(W?[M,W]:[M]);break;case"DISCONTINUITY":y++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([F]);break;case"BITRATE":T.tagList.push([F,M]),v=parseInt(M)*1e3,N(v)?T.bitrate=v:v=0;break;case"DATERANGE":{const k=new oe(M,d),C=new Zi(k,d.dateRanges[k.ID],d.dateRangeTagCount);d.dateRangeTagCount++,C.isValid||d.skippedSegments?d.dateRanges[C.id]=C:te.warn(`Ignoring invalid DATERANGE tag: "${M}"`),T.tagList.push(["EXT-X-DATERANGE",M]);break}case"DEFINE":{const k=new oe(M,d);"IMPORT"in k?xu(d,k,a):ho(d,k,i)}break;case"DISCONTINUITY-SEQUENCE":d.startCC!==0?ze(d,F,S):c.length>0&&Ao(d,F,S),d.startCC=y=parseInt(M);break;case"KEY":{const k=vo(M,i,d);if(k.isSupported()){if(k.method==="NONE"){b=void 0;break}b||(b={});const C=b[k.keyFormat];C!=null&&C.matches(k)||(C&&(b=se({},b)),b[k.keyFormat]=k)}else te.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${M}"`);break}case"START":d.startTimeOffset=Eo(M);break;case"MAP":{const k=new oe(M,d);if(T.duration){const C=new zt(r,l);bo(C,k,s,b),u=C,T.initSegment=u,u.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=u.rawProgramDateTime)}else{const C=T.byteRangeEndOffset;if(C){const G=T.byteRangeStartOffset;w=`${C-G}@${G}`}else w=null;bo(T,k,s,b),u=T,D=!0}u.cc=y;break}case"SERVER-CONTROL":P&&ze(d,F,S),P=new oe(M),d.canBlockReload=P.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=P.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&P.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=P.optionalFloat("PART-HOLD-BACK",0),d.holdBack=P.optionalFloat("HOLD-BACK",0);break;case"PART-INF":d.partTarget&&ze(d,F,S),d.partTarget=new oe(M).decimalFloatingPoint("PART-TARGET");break;case"PART":{let k=d.partList;k||(k=d.partList=[]);const C=m>0?k[k.length-1]:void 0,G=m++,j=new _r(new oe(M,d),T,l,G,C);k.push(j),T.duration+=j.duration;break}case"PRELOAD-HINT":d.preloadHint=new oe(M,d);break;case"RENDITION-REPORT":{const k=new oe(M,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(k);break}default:te.warn(`line parsed but not handled: ${S}`);break}}}E&&!E.relurl?(c.pop(),g-=E.duration,d.partList&&(d.fragmentHint=E)):d.partList&&(er(T,E,h),T.cc=y,d.fragmentHint=T,b&&Io(T,b,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const x=c.length,U=c[0],O=c[x-1];if(g+=d.skippedSegments*d.targetduration,g>0&&x&&O){d.averagetargetduration=g/x;const V=O.sn;d.endSN=V!=="initSegment"?V:0,d.live||(O.endList=!0),I>0&&(Ku(c,I),U&&h.unshift(U))}return d.fragmentHint&&(g+=d.fragmentHint.duration),d.totalduration=g,h.length&&d.dateRangeTagCount&&U&&yo(h,d),d.endCC=y,d}},id={toString:function(e){let t="";const i=e.length;for(let s=0;s<i;s++)t+=`[${e.start(s).toFixed(3)}-${e.end(s).toFixed(3)}]`;return t}},_={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},Zt=class extends Br{constructor(e,t,i,s,r){super(s,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=_.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:n,fragCurrent:a,media:o,mediaBuffer:l,state:d}=this,c=o?o.currentTime:0,h=Y.bufferInfo(l||o,c,n.maxBufferHole),u=!h.len;if(this.log(`Media seeking to ${N(c)?c.toFixed(3):c}, state: ${d}, ${u?"out of":"in"} buffer`),this.state===_.ENDED)this.resetLoadingState();else if(a){const f=n.maxFragLookUpTolerance,m=a.start-f,g=a.start+a.duration+f;if(u||g<h.start||m>h.end){const y=c>g;(c<m||y)&&(y&&a.loader&&(this.log(`Cancelling fragment load for seek (sn: ${a.sn})`),a.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(o&&(this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0),c>this.lastCurrentTime&&(this.lastCurrentTime=c),!this.loadingParts)){const f=Math.max(h.end,c),m=this.shouldLoadParts(this.getLevelDetails(),f);m&&(this.log(`LL-Part loading ON after seeking to ${c.toFixed(2)} with buffer @${f.toFixed(2)}`),this.loadingParts=m)}this.hls.hasEnoughToStart||(this.log(`Setting ${u?"startPosition":"nextLoadPosition"} to ${c} for seek without enough to start`),this.nextLoadPosition=c,u&&(this.startPosition=c)),u&&this.state===_.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new Xl(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Qi(e.config)}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===_.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=_.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=Y.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>s&&n<t.edge||this.media.currentTime<e.start)return!1;const a=t.partList;if(a!=null&&a.length){const l=a[a.length-1];return Y.isBuffered(this.media,l.start+l.duration/2)}const o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;Ee(i,"seeking",this.onMediaSeeking),Ee(i,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===_.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(e,t){const i=!!t.transferMedia,s=this.media;if(s!==null){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Le(s,"seeking",this.onMediaSeeking),Le(s,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=_.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const s=r=>{const n=r.frag;if(this.fragContextChanged(n)){this.warn(`${n.type} sn: ${n.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(n,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(n);return}n.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,i,s).then(r=>{if(!r)return;const n=this.state,a=r.frag;if(this.fragContextChanged(a)){(n===_.FRAG_LOADING||!this.fragCurrent&&n===_.PARSING)&&(this.fragmentTracker.removeFragment(a),this.state=_.IDLE);return}"payload"in r&&(this.log(`Loaded ${a.type} sn: ${a.sn} of ${this.playlistLabel()} ${a.level}`),this.hls.trigger(p.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===_.STOPPED||this.state===_.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===he.APPENDING){const s=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,s),n=Math.max(e.duration,r?r.len:this.config.maxBufferLength),a=this.backtrackFragment;((a?e.sn-a.sn:0)===1||this.reduceMaxBufferLength(n,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===he.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const s={startOffset:e,endOffset:t,type:i};this.hls.trigger(p.BUFFER_FLUSHING,s)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{const s=i?.frag;if(!s||this.fragContextChanged(s)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:s}=this,{frag:r,payload:n}=i,a=r.decryptdata;if(n&&n.byteLength>0&&a!=null&&a.key&&a.iv&&bt(a.method)){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,Xs(a.method)).catch(l=>{throw s.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:r}),l}).then(l=>{const d=self.performance.now();return s.trigger(p.FRAG_DECRYPTED,{frag:r,payload:l,stats:{tstart:o,tdecrypt:d}}),i.payload=l,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===_.STOPPED||this.state===_.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state!==_.STOPPED&&(this.state=_.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var i,s;const r=e.tracks;if(r&&!t.encrypted&&((i=r.audio)!=null&&i.encrypted||(s=r.video)!=null&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const n=this.media,a=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${n?"attached mediaKeys: "+n.mediaKeys:"detached"})`);return this.warn(a.message),!n||n.mediaKeys?!1:(this.hls.trigger(p.ERROR,{type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_KEYS,fatal:!1,error:a,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?id.toString(Y.getBuffered(i)):"(detached)"})`),de(e)){var s;if(e.type!==B.SUBTITLE){const n=e.elementaryStreams;if(!Object.keys(n).some(a=>!!n[a])){this.state=_.IDLE;return}}const r=(s=this.levels)==null?void 0:s[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=_.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:s,partsLoaded:r}=e,n=!r||r.length===0||r.some(o=>!o),a=new Xt(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,s){var r;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=_.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(p.KEY_LOADED,h),this.state===_.KEY_LOADING&&(this.state=_.IDLE),h}),this.hls.trigger(p.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(a=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));const o=this.fragPrevious;if(de(e)&&(!o||e.sn!==o.sn)){const h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${o?.sn}->${e.sn}`),this.loadingParts=h)}if(i=Math.max(e.start,i||0),this.loadingParts&&de(e)){const h=n.partList;if(h&&s){i>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const u=this.getNextPart(h,e,i);if(u>-1){const f=h[u];e=this.fragCurrent=f.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${f.index} (${u}/${h.length-1}) of ${this.fragInfo(e,!1,f)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=f.start+f.duration,this.state=_.FRAG_LOADING;let m;return a?m=a.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,f,t,s)).catch(g=>this.handleFragLoadError(g)):m=this.doFragPartsLoad(e,f,t,s).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(p.FRAG_LOADING,{frag:e,part:f,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):m}else if(!e.url||this.loadedEndOfParts(h,i))return Promise.resolve(null)}}if(de(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=n.partList)==null?void 0:l.filter(h=>h.loaded).map(h=>`[${h.start}-${h.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),N(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=_.FRAG_LOADING;const d=this.config.progressive&&e.type!==B.SUBTITLE;let c;return d&&a?c=a.then(h=>!h||this.fragContextChanged(h.frag)?null:this.fragmentLoader.load(e,s)).catch(h=>this.handleFragLoadError(h)):c=Promise.all([this.fragmentLoader.load(e,d?s:void 0),a]).then(([h])=>(!d&&s&&s(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(p.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,i,s){return new Promise((r,n)=>{var a;const o=[],l=(a=i.details)==null?void 0:a.partList,d=c=>{this.fragmentLoader.loadPart(e,c,s).then(h=>{o[c.index]=h;const u=h.part;this.hls.trigger(p.FRAG_LOADED,h);const f=_o(i.details,e.sn,c.index+1)||ko(l,e.sn,c.index+1);if(f)d(f);else return r({frag:e,part:u,partsLoaded:o})}).catch(n)};d(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===L.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===$.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(p.ERROR,t)}else this.hls.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==_.PARSING){!this.fragCurrent&&this.state!==_.STOPPED&&this.state!==_.ERROR&&(this.state=_.IDLE);return}const{frag:i,part:s,level:r}=t,n=self.performance.now();i.stats.parsing.end=n,s&&(s.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(i,s,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i;const r=e.partList[0];if(r.fragment.type===B.SUBTITLE)return!1;if(t>=r.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0)){var s;if((this.hls.hasEnoughToStart?((s=this.media)==null?void 0:s.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:s,sn:r,part:n}=e;if(!(t!=null&&t[s]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const a=t[s],o=a.details,l=n>-1?_o(o,r,n):null,d=l?l.fragment:wo(o,r,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(e,t,i,s,r){if(this.state!==_.PARSING)return;const{data1:n,data2:a}=e;let o=n;if(a&&(o=Ce(n,a)),!o.length)return;const l=this.initPTS[t.cc],d=l?-l.baseTime/l.timescale:void 0,c={type:e.type,frag:t,part:i,chunkMeta:s,offset:d,parent:t.type,data:o};if(this.hls.trigger(p.BUFFER_APPENDING,c),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Y.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,s=Y.bufferInfo(t,i,0),r=e.duration,n=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),a=Math.max(Math.min(e.start-n,s.end-n),i+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var i;const s=this.getLoadPosition();if(!N(s))return null;const r=this.lastCurrentTime>s||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,r)}getFwdBufferInfoAtPos(e,t,i,s){const r=Y.bufferInfo(e,t,s);if(r.len===0&&r.nextStart!==void 0){const n=this.fragmentTracker.getBufferedFrag(t,i);if(n&&(r.nextStart<=n.end||n.gap)){const a=Math.max(Math.min(r.nextStart,n.end)-t,s);return Y.bufferInfo(e,t,a)}}return r}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,i){const s=e.nextStart;if(s&&i.start>s){const r=e.buffered;if(r){let n=e.len;const a=e.bufferedIndex;for(let o=r.length-1;o>a;o--)r[o].start<i.start&&(n+=r[o].end-r[o].start);return n>=t}}return!1}reduceMaxBufferLength(e,t){const i=this.config,s=Math.max(Math.min(e-t,i.maxBufferLength),t),r=Math.max(e-t*3,i.maxMaxBufferLength/2,s);return r>=s?(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=B.MAIN){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,s=i.length;if(!s)return null;const{config:r}=this,n=t.fragmentStart,a=r.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const c=r.initialLiveManifestSize;if(s<c)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${c})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);const h=this.config.startPosition,u=this.hls.startPosition,f=this.hls.liveSyncPosition,m=((l=o)==null?void 0:l.start)||0;let g,y;u!==-1&&u>=n?(g=u,y=u===h?"config":"next load start"):f!==null?(g=f,y="live edge"):(g=e,y="buffer pos"),g<m&&(g=m,y="live frag start"),g<n&&(g=n,y="playlist start"),(this.startPosition!=g||this.nextLoadPosition!=g)&&(this.log(`Setting startPosition to ${g.toFixed(3)} ${u===-1?"":`(from ${h}) `}based on ${y}. live edge: ${f} live frag start: ${m.toFixed(3)} playlist start: ${n.toFixed(3)} buffer pos: ${e}`),this.startPosition=this.nextLoadPosition=g)}}else e<=n&&(o=i[0]);if(!o){const c=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,c,t)}let d=this.filterReplacedPrimary(o,t);if(!d&&o){const c=o.sn-t.startSN;d=this.filterReplacedPrimary(i[c+1]||null,t)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;const i=this.fragmentTracker.getState(e);return i===he.OK||i===he.PARTIAL&&!!e.gap}getNextFragmentLoopLoading(e,t,i,s,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&i.nextStart)){const a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(a!==null&&i.len+a.len>=r){const o=n.sn;return this.loopSn!==o&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${o}`),this.loopSn=o),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(No(this.config)){var e;if(!((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null)&&e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(No(this.config)&&e.type!==B.SUBTITLE){const i=this.hls.interstitialsManager,s=i?.bufferingItem;if(s){const n=s.event;if(n){if(n.appendInPlace||Math.abs(e.start-s.start)>1||s.start===0)return null}else if(e.end<=s.start&&t?.live===!1||e.start>s.end&&s.nextEvent&&(s.nextEvent.appendInPlace||e.start-s.end>1))return null}const r=i?.playerQueue;if(r)for(let n=r.length;n--;){const a=r[n].interstitial;if(a.appendInPlace&&e.start>=a.startTime&&e.end<=a.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let s=-1,r=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const l=e[a];if(n=n&&!l.independent,s>-1&&i<l.start)break;const d=l.loaded;d?s=-1:(r||(l.independent||n)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${l.start}`),s=a),r=d}return s}loadedEndOfParts(e,t){let i;for(let s=e.length;s--;){if(i=e[s],!i.loaded)return!1;if(t>i.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,i=this.fragPrevious;let s=null;if(i){if(e.hasProgramDateTime&&(s=Ru(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance),s&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`)),!s){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];i.cc===n.cc&&(s=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=to(e,i.cc,i.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(s=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){const{config:s}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=s,d=i.partList,c=!!(this.loadingParts&&d!=null&&d.length&&o);c&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn);let h;if(e<t){var u;const f=e<this.lastCurrentTime||e>t-l||(u=this.media)!=null&&u.paused||!this.startFragRequested?0:l;h=lt(r,n,e,f)}else h=n[n.length-1];if(h){const f=h.sn-i.startSN,m=this.fragmentTracker.getState(h);if((m===he.OK||m===he.PARTIAL&&h.gap)&&(r=h),r&&h.sn===r.sn&&(!c||d[0].fragment.sn>h.sn||!i.live)&&h.level===r.level){const g=n[f+1];h.sn<a&&this.fragmentTracker.getState(g)!==he.OK?h=g:h=null}}return h}alignPlaylists(e,t,i){const s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,a=e.alignedSliding&&N(r);if(n||!a&&!r){Xu(i,e);const o=e.fragmentStart;return this.log(`Live playlist sliding: ${o.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${s}`),o}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);const s=this.timelineOffset;if(i===-1){const r=this.startTimeOffset!==null,n=r?this.startTimeOffset:e.startTimeOffset;n!==null&&N(n)?(i=t+n,n<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+s}this.nextLoadPosition=i+s}getLoadPosition(){var e;const{media:t}=this;let i=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&de(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==_.FRAG_LOADING_WAITING_RETRY)&&(this.state=_.IDLE)}onFragmentOrKeyLoadError(e,t){var i;if(t.chunkMeta&&!t.frag){const y=this.getCurrentContext(t.chunkMeta);y&&(t.frag=y.frag)}const s=t.frag;if(!s||s.type!==e||!this.levels)return;if(this.fragContextChanged(s)){var r;this.warn(`Frag load error must match current frag to retry ${s.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const n=t.details===L.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(s,!0);const a=t.errorAction;if(!a){this.state=_.ERROR;return}const{action:o,flags:l,retryCount:d=0,retryConfig:c}=a,h=!!c,u=h&&o===ce.RetryRequest,f=h&&!a.resolved&&l===Te.MoveAllAlternatesMatchingHost,m=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!u&&f&&de(s)&&!s.endList&&m&&!so(t))this.resetFragmentErrors(e),this.treatAsGap(s),a.resolved=!0;else if((u||f)&&d<c.maxNumRetry){var g;const y=zs((g=t.response)==null?void 0:g.code),v=Ys(c,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+v,this.state=_.FRAG_LOADING_WAITING_RETRY,a.resolved=!0,y){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${d+1}/${c.maxNumRetry} in ${v}ms`)}else if(c)if(this.resetFragmentErrors(e),d<c.maxNumRetry)!n&&o!==ce.RemoveAlternatePermanently&&(a.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${d})`);return}else o===ce.SendAlternateToPenaltyBox?this.state=_.WAITING_LEVEL:this.state=_.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!zs(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=_.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===_.PARSING||this.state===_.PARSED){const t=e.frag,i=e.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len,t?.duration||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===B.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==_.STOPPED&&(this.state=_.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const s=Y.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,i),this.state===_.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==_.STOPPED&&(this.state=_.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){const r=i.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((a,o)=>{const l=e.elementaryStreams[o];if(l){const d=l.endPTS-l.startPTS;if(d<=0)return this.warn(`Could not parse fragment ${e.sn} ${o} duration reliably (${d})`),a||!1;const c=s?0:Lo(r,e,l.startPTS,l.endPTS,l.startDTS,l.endDTS,this);return this.hls.trigger(p.LEVEL_PTS_UPDATED,{details:r,level:i,drift:c,type:o,frag:e,start:l.startPTS,end:l.endPTS}),!0}return a},!1)){var n;const a=((n=this.transmuxer)==null?void 0:n.error)===null;if((i.fragmentError===0||a&&(i.fragmentError<2||e.endList))&&this.treatAsGap(e,i),a){const o=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(o.message),this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=_.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(p.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===B.MAIN?"level":"track"}fragInfo(e,t=!0,i){var s,r;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((s=t&&!i?e.startPTS:(i||e).start)!=null?s:NaN).toFixed(3)}-${((r=t&&!i?e.endPTS:(i||e).end)!=null?r:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}},jr=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=Qu(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}},ts={exports:{}},is=Wh(Zu()),wt="1.6.16",gt={},Jt=10,rd=10,Se=(function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e})({}),ss=class{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=Ce(this.cachedData,e),this.cachedData=null);let i=Vt(e,0),s=i?i.length:0,r;const n=this._audioTrack,a=this._id3Track,o=i?ar(i):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&N(o))&&(this.basePTS=nd(o,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Se.audioId3,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(e,s)){const d=this.appendFrame(n,e,s);d?(this.frameIndex++,this.lastPTS=d.sample.pts,s+=d.length,r=s):s=l}else df(e,s)?(i=Vt(e,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Se.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,r=s):s++;if(s===l&&r!==l){const d=e.slice(r);this.cachedData?this.cachedData=Ce(this.cachedData,d):this.cachedData=d}}return{audioTrack:n,videoTrack:$e(),id3Track:a,textTrack:$e()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:$e(),id3Track:this._id3Track,textTrack:$e()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},nd=(e,t,i)=>{if(N(e))return e*90;const s=i?i.baseTime*9e4/i.timescale:0;return t*9e4+s},ei=null,ad=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],od=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ld=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],dd=[0,1,1,4],cd=class extends ss{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const i=Vt(e,0);let s=i?.length||0;if(qo(e,s))return!1;for(let r=e.length;s<r;s++)if(of(e,s))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return af(e,t)}appendFrame(e,t,i){Go(e,this.observer,t,i,e.manifestCodec);const s=Ko(e,t,i,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}},Yr=(e,t)=>{let i=0,s=5;t+=s;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=e[t];const o=Math.min(s,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,i=i?i<<o|r[0]:r[0],t+=1,s-=o}return i},hd=class extends ss{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){const s=Xo(e,t,i,this.basePTS,this.frameIndex);if(s!==-1)return{sample:e.samples[e.samples.length-1],length:s,missing:0}}static probe(e){if(!e)return!1;const t=Vt(e,0);if(!t)return!1;const i=t.length;return e[i]===11&&e[i+1]===119&&ar(t)!==void 0&&Yr(e,i)<16}},ud=class extends ss{resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Vt(e,0);let i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&ar(t)!==void 0&&Yr(e,i)<=16)return!1;for(let s=e.length;i<s;i++)if(qo(e,i))return te.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Sf(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return jo(e,t,i,this.basePTS,this.frameIndex)}},fd=/\/emsg[-/]ID3/i,gd=class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,s){const r=this.videoTrack=$e("video",1),n=this.audioTrack=$e("audio",1),a=this.txtTrack=$e("text",1);if(this.id3Track=$e("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const o=Ua(e);if(o.video){const{id:l,timescale:d,codec:c,supplemental:h}=o.video;r.id=l,r.timescale=a.timescale=d,r.codec=c,r.supplemental=h}if(o.audio){const{id:l,timescale:d,codec:c}=o.audio;n.id=l,n.timescale=d,n.codec=c}a.id=Cr.text,r.sampleDuration=0,r.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return zh(e)}demux(e,t){this.timeOffset=t;let i=e;const s=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Ce(this.remainderData,e));const a=tu(i);this.remainderData=a.remainder,s.samples=a.valid||new Uint8Array}else s.samples=i;const n=this.extractID3Track(s,t);return r.samples=Ga(t,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(t,this.timeOffset);return i.samples=Ga(e,t),{videoTrack:t,audioTrack:$e(),id3Track:s,textTrack:$e()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const s=z(e.samples,["emsg"]);s&&s.forEach(r=>{const n=su(r);if(fd.test(n.schemeIdUri)){const a=Qo(n,t);let o=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;o<=.001&&(o=Number.POSITIVE_INFINITY);const l=n.payload;i.samples.push({data:l,len:l.byteLength,dts:a,pts:a,type:Se.emsg,duration:o})}else if(this.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const a=Qo(n,t);i.samples.push({data:n.payload,len:n.payload.byteLength,dts:a,pts:a,type:Se.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},md=class{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Qi(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Xe.cbc)}decryptAacSample(e,t,i){const s=e[t].unit;if(s.length<=16)return;const r=s.subarray(16,s.length-s.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(a=>{const o=new Uint8Array(a);s.set(o,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let s=0;for(let r=32;r<e.length-16;r+=160,s+=16)i.set(e.subarray(r,r+16),s);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let s=0;for(let r=32;r<e.length-16;r+=160,s+=16)e.set(i.subarray(s,s+16),r);return e}decryptAvcSample(e,t,i,s,r){const n=Va(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(o=>{r.data=this.getAvcDecryptedUnit(n,o),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,s)}).catch(s)}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){s();return}const r=e[t].units;for(;!(i>=r.length);i++){const n=r[i];if(!(n.data.length<=48||n.type!==1&&n.type!==5)&&(this.decryptAvcSample(e,t,i,s,n),!this.decrypter.isSync()))return}}}},zr=class{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,s;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const r=i.units;s=r[r.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,s=i.length;if(s){const r=i[s-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){const s=t.byteLength;let r=e.naluState||0;const n=r,a=[];let o=0,l,d,c,h=-1,u=0;for(r===-1&&(h=0,u=this.getNALuType(t,0),r=0,o=1);o<s;){if(l=t[o++],!r){r=l?0:1;continue}if(r===1){r=l?0:2;continue}if(!l)r=3;else if(l===1){if(d=o-r-1,h>=0){const f={data:t.subarray(h,d),type:u};a.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(n&&o<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),d>0&&(f.data=Ce(f.data,t.subarray(0,d)),f.state=0))}o<s?(c=this.getNALuType(t,o),h=o,u=c,r=0):r=-1}else r=0}if(h>=0&&r>=0){const f={data:t.subarray(h,s),type:u,state:r};a.push(f)}if(a.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=Ce(f.data,t))}return e.naluState=r,a}},_t=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,s=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");s.set(e.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&te.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}},pd=class extends zr{parsePES(e,t,i,s){const r=this.parseNALu(e,i.data,s);let n=this.VideoSample,a,o=!1;i.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(l=>{var d,c;switch(l.type){case 1:{let m=!1;a=!0;const g=l.data;if(o&&g.length>4){const y=this.readSliceType(g);(y===2||y===4||y===7||y===9)&&(m=!0)}if(m){var h;(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.frame=!0,n.key=m;break}case 5:a=!0,(d=n)!=null&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.key=!0,n.frame=!0;break;case 6:a=!0,Ks(l.data,1,i.pts,t.samples);break;case 7:{var u,f;a=!0,o=!0;const m=l.data,g=this.readSPS(m);if(!e.sps||e.width!==g.width||e.height!==g.height||((u=e.pixelRatio)==null?void 0:u[0])!==g.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==g.pixelRatio[1]){e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.sps=[m];const y=m.subarray(1,4);let v="avc1.";for(let E=0;E<3;E++){let T=y[E].toString(16);T.length<2&&(T="0"+T),v+=T}e.codec=v}break}case 8:a=!0,e.pps=[l.data];break;case 9:a=!0,e.audFound=!0,(c=n)!=null&&c.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:a=!0;break;default:a=!1;break}n&&a&&n.units.push(l)}),s&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new _t(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,s=8,r;for(let n=0;n<e;n++)s!==0&&(r=t.readEG(),s=(i+r+256)%256),i=s===0?i:s}readSPS(e){const t=new _t(e);let i=0,s=0,r=0,n=0,a,o,l;const d=t.readUByte.bind(t),c=t.readBits.bind(t),h=t.readUEG.bind(t),u=t.readBoolean.bind(t),f=t.skipBits.bind(t),m=t.skipEG.bind(t),g=t.skipUEG.bind(t),y=this.skipScalingList.bind(this);d();const v=d();if(c(5),f(3),d(),g(),v===100||v===110||v===122||v===244||v===44||v===83||v===86||v===118||v===128){const I=h();if(I===3&&f(1),g(),g(),f(1),u())for(o=I!==3?8:12,l=0;l<o;l++)u()&&(l<6?y(16,t):y(64,t))}g();const E=h();if(E===0)h();else if(E===1)for(f(1),m(),m(),a=h(),l=0;l<a;l++)m();g(),f(1);const T=h(),S=h(),A=c(1);A===0&&f(1),f(1),u()&&(i=h(),s=h(),r=h(),n=h());let b=[1,1];if(u()&&u())switch(d()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:b=[d()<<8|d(),d()<<8|d()];break}return{width:Math.ceil((T+1)*16-i*2-s*2),height:(2-A)*(S+1)*16-(A?2:4)*(r+n),pixelRatio:b}}},yd=class extends zr{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,s){const r=this.parseNALu(e,i.data,s);let n=this.VideoSample,a,o=!1;i.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(l=>{var d,c;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:n||(n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),n.frame=!0,a=!0;break;case 16:case 17:case 18:case 21:if(a=!0,o){var h;(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.key=!0,n.frame=!0;break;case 19:case 20:a=!0,(d=n)!=null&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.key=!0,n.frame=!0;break;case 39:a=!0,Ks(l.data,2,i.pts,t.samples);break;case 32:a=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=se(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(a=!0,o=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const u=this.readSPS(l.data);e.width=u.width,e.height=u.height,e.pixelRatio=u.pixelRatio,e.codec=u.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const f in u.params)e.params[f]=u.params[f]}this.pushParameterSet(e.sps,l.data,e.vps),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.key=!0;break;case 34:if(a=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const u=this.readPPS(l.data);for(const f in u)e.params[f]=u[f]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:a=!0,e.audFound=!0,(c=n)!=null&&c.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:a=!1;break}n&&a&&n.units.push(l)}),s&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let s=0;s<e.byteLength;s++)s>=2&&e[s]===3&&e[s-1]===0&&e[s-2]===0||(t[i]=e[s],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new _t(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const i=t.readBits(3),s=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:s}}readSPS(e){const t=new _t(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const s=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),d=t.readUByte(),c=t.readUByte(),h=t.readUByte(),u=t.readUByte(),f=t.readUByte(),m=t.readUByte(),g=t.readUByte(),y=t.readUByte(),v=[],E=[];for(let H=0;H<i;H++)v.push(t.readBoolean()),E.push(t.readBoolean());if(i>0)for(let H=i;H<8;H++)t.readBits(2);for(let H=0;H<i;H++)v[H]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),E[H]&&t.readUByte();t.readUEG();const T=t.readUEG();T==3&&t.skipBits(1);const S=t.readUEG(),A=t.readUEG(),b=t.readBoolean();let I=0,D=0,w=0,P=0;b&&(I+=t.readUEG(),D+=t.readUEG(),w+=t.readUEG(),P+=t.readUEG());const x=t.readUEG(),U=t.readUEG(),O=t.readUEG(),V=t.readBoolean();for(let H=V?0:i;H<=i;H++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let H=0;H<4;H++)for(let ve=0;ve<(H===3?2:6);ve++)if(!t.readBoolean())t.readUEG();else{const pe=Math.min(64,1<<4+(H<<1));H>1&&t.readEG();for(let Fe=0;Fe<pe;Fe++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const F=t.readUEG();let M=0;for(let H=0;H<F;H++){let ve=!1;if(H!==0&&(ve=t.readBoolean()),ve){H===F&&t.readUEG(),t.readBoolean(),t.readUEG();let pe=0;for(let Fe=0;Fe<=M;Fe++){const We=t.readBoolean();let hi=!1;We||(hi=t.readBoolean()),(We||hi)&&pe++}M=pe}else{const pe=t.readUEG(),Fe=t.readUEG();M=pe+Fe;for(let We=0;We<pe;We++)t.readUEG(),t.readBoolean();for(let We=0;We<Fe;We++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const H=t.readUEG();for(let ve=0;ve<H;ve++){for(let pe=0;pe<O+4;pe++)t.readBits(1);t.readBits(1)}}let W=0,k=1,C=1,G=!0,j=1,J=0;t.readBoolean(),t.readBoolean();let X=!1;if(t.readBoolean()){if(t.readBoolean()){const H=t.readUByte(),ve=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],pe=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];H>0&&H<16?(k=ve[H-1],C=pe[H-1]):H===255&&(k=t.readBits(16),C=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),X=t.readBoolean(),X&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(j=t.readBits(32),J=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const H=t.readBoolean(),ve=t.readBoolean();let pe=!1;(H||ve)&&(pe=t.readBoolean(),pe&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),pe&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Fe=0;Fe<=i;Fe++){G=t.readBoolean();const We=G||t.readBoolean();let hi=!1;We?t.readEG():hi=t.readBoolean();const Wc=hi?1:t.readUEG()+1;if(H)for(let ui=0;ui<Wc;ui++)t.readUEG(),t.readUEG(),pe&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(ve)for(let ui=0;ui<Wc;ui++)t.readUEG(),t.readUEG(),pe&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),W=t.readUEG())}let Q=S,Ie=A;if(b){let H=1,ve=1;T===1?H=ve=2:T==2&&(H=2),Q=S-H*D-H*I,Ie=A-ve*P-ve*w}const _e=s?["A","B","C"][s]:"",He=a<<24|o<<16|l<<8|d;let yt=0;for(let H=0;H<32;H++)yt=(yt|(He>>H&1)<<31-H)>>>0;let _n=yt.toString(16);return n===1&&_n==="2"&&(_n="6"),{codecString:`hvc1.${_e}${n}.${_n}.${r?"H":"L"}${y}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:s,general_profile_compatibility_flags:[a,o,l,d],general_constraint_indicator_flags:[c,h,u,f,m,g],general_level_idc:y,bit_depth:x+8,bit_depth_luma_minus8:x,bit_depth_chroma_minus8:U,min_spatial_segmentation_idc:W,chroma_format_idc:T,frame_rate:{fixed:G,fps:J/j}},width:Q,height:Ie,pixelRatio:[k,C]}}readPPS(e){const t=new _t(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const i=t.readBoolean(),s=t.readBoolean();let r=1;return s&&i?r=0:s?r=3:i&&(r=2),{parallelismType:r}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}},ge=188,vd=class vt{constructor(t,i,s,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=i,this.typeSupported=s,this.logger=r,this.videoParser=null}static probe(t,i){const s=vt.syncOffset(t);return s>0&&i.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(t){const i=t.length;let s=Math.min(ge*5,i-ge)+1,r=0;for(;r<s;){let n=!1,a=-1,o=0;for(let l=r;l<i;l+=ge)if(t[l]===71&&(i-l===ge||t[l+ge]===71)){if(o++,a===-1&&(a=l,a!==0&&(s=Math.min(a+ge*99,t.length-ge)+1)),n||(n=lr(t,l)===0),n&&o>1&&(a===0&&o>2||l+ge>s))return a}else{if(o)return-1;break}r++}return-1}static createTrack(t,i){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:Cr[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?i:void 0}}resetInitSegment(t,i,s,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=vt.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=vt.createTrack("audio",r),this._id3Track=vt.createTrack("id3"),this._txtTrack=vt.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=i,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:i,_id3Track:s}=this;t&&(t.pesData=null),i&&(i.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,i,s=!1,r=!1){s||(this.sampleAes=null);let n;const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,d=this._txtTrack;let c=a.pid,h=a.pesData,u=o.pid,f=l.pid,m=o.pesData,g=l.pesData,y=null,v=this.pmtParsed,E=this._pmtId,T=t.length;if(this.remainderData&&(t=Ce(this.remainderData,t),T=t.length,this.remainderData=null),T<ge&&!r)return this.remainderData=t,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};const S=Math.max(0,vt.syncOffset(t));T-=(T-S)%ge,T<t.byteLength&&!r&&(this.remainderData=new Uint8Array(t.buffer,T,t.buffer.byteLength-T));let A=0;for(let I=S;I<T;I+=ge)if(t[I]===71){const D=!!(t[I+1]&64),w=lr(t,I),P=(t[I+3]&48)>>4;let x;if(P>1){if(x=I+5+t[I+4],x===I+ge)continue}else x=I+4;switch(w){case c:D&&(h&&(n=It(h,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,d,n,!1)),h={data:[],size:0}),h&&(h.data.push(t.subarray(x,I+ge)),h.size+=I+ge-x);break;case u:if(D){if(m&&(n=It(m,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n);break}m={data:[],size:0}}m&&(m.data.push(t.subarray(x,I+ge)),m.size+=I+ge-x);break;case f:D&&(g&&(n=It(g,this.logger))&&this.parseID3PES(l,n),g={data:[],size:0}),g&&(g.data.push(t.subarray(x,I+ge)),g.size+=I+ge-x);break;case 0:D&&(x+=t[x]+1),E=this._pmtId=bf(t,x);break;case E:{D&&(x+=t[x]+1);const U=If(t,x,this.typeSupported,s,this.observer,this.logger);c=U.videoPid,c>0&&(a.pid=c,a.segmentCodec=U.segmentVideoCodec),u=U.audioPid,u>0&&(o.pid=u,o.segmentCodec=U.segmentAudioCodec),f=U.id3Pid,f>0&&(l.pid=f),y!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${I} after unknown PID '${y}'. Backtracking to sync byte @${S} to parse all TS packets.`),y=null,I=S-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=w;break}}else A++;A>0&&dr(this.observer,new Error(`Found ${A} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=h,o.pesData=m,l.pesData=g;const b={audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};return r&&this.extractRemainingSamples(b),b}flush(){const{remainderData:t}=this;this.remainderData=null;let i;return t?i=this.demux(t,-1,!1,!0):i={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(i),this.sampleAes?this.decrypt(i,this.sampleAes):i}extractRemainingSamples(t){const{audioTrack:i,videoTrack:s,id3Track:r,textTrack:n}=t,a=s.pesData,o=i.pesData,l=r.pesData;let d;if(a&&(d=It(a,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,n,d,!0),s.pesData=null)):s.pesData=a,o&&(d=It(o,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,d);break;case"mp3":this.parseMPEGPES(i,d);break;case"ac3":this.parseAC3PES(i,d);break}i.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=o;l&&(d=It(l,this.logger))?(this.parseID3PES(r,d),r.pesData=null):r.pesData=l}demuxSampleAes(t,i,s){const r=this.demux(t,s,!0,!this.config.progressive),n=this.sampleAes=new md(this.observer,this.config,i);return this.decrypt(r,n)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new pd:t==="hevc"&&(this.videoParser=new yd))}decrypt(t,i){return new Promise(s=>{const{audioTrack:r,videoTrack:n}=t;r.samples&&r.segmentCodec==="aac"?i.decryptAacSamples(r.samples,0,()=>{n.samples?i.decryptAvcSamples(n.samples,0,0,()=>{s(t)}):s(t)}):n.samples&&i.decryptAvcSamples(n.samples,0,0,()=>{s(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,i){let s=0;const r=this.aacOverFlow;let n=i.data;if(r){this.aacOverFlow=null;const h=r.missing,u=r.sample.unit.byteLength;if(h===-1)n=Ce(r.sample.unit,n);else{const f=u-h;r.sample.unit.set(n.subarray(0,h),f),t.samples.push(r.sample),s=r.missing}}let a,o;for(a=s,o=n.length;a<o-1&&!Ni(n,a);a++);if(a!==s){let h;const u=a<o-1;if(u?h=`AAC PES did not start with ADTS header,offset:${a}`:h="No ADTS header found in AAC PES",dr(this.observer,new Error(h),u,this.logger),!u)return}Go(t,this.observer,n,a,this.audioCodec);let l;if(i.pts!==void 0)l=i.pts;else if(r){const h=Vo(t.samplerate);l=r.sample.pts+h}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let d=0,c;for(;a<o;)if(c=Ko(t,n,a,l,d),a+=c.length,c.missing){this.aacOverFlow=c;break}else for(d++;a<o-1&&!Ni(n,a);a++);}parseMPEGPES(t,i){const s=i.data,r=s.length;let n=0,a=0;const o=i.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<r;)if(zo(s,a)){const l=jo(t,s,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseAC3PES(t,i){{const s=i.data,r=i.pts;if(r===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const n=s.length;let a=0,o=0,l;for(;o<n&&(l=Xo(t,s,o,r,a++))>0;)o+=l}}parseID3PES(t,i){if(i.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=se({},i,{type:this._videoTrack?Se.emsg:Se.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}},Ed=class{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}},Qe=Math.pow(2,32)-1,me=class R{static init(){R.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let t;for(t in R.types)R.types.hasOwnProperty(t)&&(R.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);R.HDLR_TYPES={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]);R.STTS=R.STSC=R.STCO=new Uint8Array([0,0,0,0,0,0,0,0]),R.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),R.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),R.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),R.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const s=new Uint8Array([105,115,111,109]),r=new Uint8Array([97,118,99,49]),n=new Uint8Array([0,0,0,1]);R.FTYP=R.box(R.types.ftyp,s,n,s,r),R.DINF=R.box(R.types.dinf,R.box(R.types.dref,i))}static box(t,...i){let s=8,r=i.length;const n=r;for(;r--;)s+=i[r].byteLength;const a=new Uint8Array(s);for(a[0]=s>>24&255,a[1]=s>>16&255,a[2]=s>>8&255,a[3]=s&255,a.set(t,4),r=0,s=8;r<n;r++)a.set(i[r],s),s+=i[r].byteLength;return a}static hdlr(t){return R.box(R.types.hdlr,R.HDLR_TYPES[t])}static mdat(t){return R.box(R.types.mdat,t)}static mdhd(t,i){i*=t;const s=Math.floor(i/(Qe+1)),r=Math.floor(i%(Qe+1));return R.box(R.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,s>>24,s>>16&255,s>>8&255,s&255,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(t){return R.box(R.types.mdia,R.mdhd(t.timescale||0,t.duration||0),R.hdlr(t.type),R.minf(t))}static mfhd(t){return R.box(R.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type==="audio"?R.box(R.types.minf,R.box(R.types.smhd,R.SMHD),R.DINF,R.stbl(t)):R.box(R.types.minf,R.box(R.types.vmhd,R.VMHD),R.DINF,R.stbl(t))}static moof(t,i,s){return R.box(R.types.moof,R.mfhd(t),R.traf(s,i))}static moov(t){let i=t.length;const s=[];for(;i--;)s[i]=R.trak(t[i]);return R.box.apply(null,[R.types.moov,R.mvhd(t[0].timescale||0,t[0].duration||0)].concat(s).concat(R.mvex(t)))}static mvex(t){let i=t.length;const s=[];for(;i--;)s[i]=R.trex(t[i]);return R.box.apply(null,[R.types.mvex,...s])}static mvhd(t,i){i*=t;const s=Math.floor(i/(Qe+1)),r=Math.floor(i%(Qe+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,s>>24,s>>16&255,s>>8&255,s&255,r>>24,r>>16&255,r>>8&255,r&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return R.box(R.types.mvhd,n)}static sdtp(t){const i=t.samples||[],s=new Uint8Array(4+i.length);let r,n;for(r=0;r<i.length;r++)n=i[r].flags,s[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return R.box(R.types.sdtp,s)}static stbl(t){return R.box(R.types.stbl,R.stsd(t),R.box(R.types.stts,R.STTS),R.box(R.types.stsc,R.STSC),R.box(R.types.stsz,R.STSZ),R.box(R.types.stco,R.STCO))}static avc1(t){let i=[],s=[],r,n,a;for(r=0;r<t.sps.length;r++)n=t.sps[r],a=n.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(n));for(r=0;r<t.pps.length;r++)n=t.pps[r],a=n.byteLength,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(n));const o=R.box(R.types.avcC,new Uint8Array([1,i[3],i[4],i[5],255,224|t.sps.length].concat(i).concat([t.pps.length]).concat(s))),l=t.width,d=t.height,c=t.pixelRatio[0],h=t.pixelRatio[1];return R.box(R.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,c&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(t){const i=t.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...i,6,1,2])}static audioStsd(t){const i=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,i>>8&255,i&255,0,0])}static mp4a(t){return R.box(R.types.mp4a,R.audioStsd(t),R.box(R.types.esds,R.esds(t)))}static mp3(t){return R.box(R.types[".mp3"],R.audioStsd(t))}static ac3(t){return R.box(R.types["ac-3"],R.audioStsd(t),R.box(R.types.dac3,t.config))}static stsd(t){const{segmentCodec:i}=t;if(t.type==="audio"){if(i==="aac")return R.box(R.types.stsd,R.STSD,R.mp4a(t));if(i==="ac3"&&t.config)return R.box(R.types.stsd,R.STSD,R.ac3(t));if(i==="mp3"&&t.codec==="mp3")return R.box(R.types.stsd,R.STSD,R.mp3(t))}else if(t.pps&&t.sps){if(i==="avc")return R.box(R.types.stsd,R.STSD,R.avc1(t));if(i==="hevc"&&t.vps)return R.box(R.types.stsd,R.STSD,R.hvc1(t))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${t.type} segment codec (${i}/${t.codec})`)}static tkhd(t){const i=t.id,s=(t.duration||0)*(t.timescale||0),r=t.width||0,n=t.height||0,a=Math.floor(s/(Qe+1)),o=Math.floor(s%(Qe+1));return R.box(R.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,i>>24&255,i>>16&255,i>>8&255,i&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,r&255,0,0,n>>8&255,n&255,0,0]))}static traf(t,i){const s=R.sdtp(t),r=t.id,n=Math.floor(i/(Qe+1)),a=Math.floor(i%(Qe+1));return R.box(R.types.traf,R.box(R.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),R.box(R.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),R.trun(t,s.length+16+20+8+16+8+8),s)}static trak(t){return t.duration=t.duration||4294967295,R.box(R.types.trak,R.tkhd(t),R.mdia(t))}static trex(t){const i=t.id;return R.box(R.types.trex,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,i){const s=t.samples||[],r=s.length,n=12+16*r,a=new Uint8Array(n);let o,l,d,c,h,u;for(i+=8+n,a.set([t.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255],0),o=0;o<r;o++)l=s[o],d=l.duration,c=l.size,h=l.flags,u=l.cts,a.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,u>>>24&255,u>>>16&255,u>>>8&255,u&255],12+16*o);return R.box(R.types.trun,a)}static initSegment(t){R.types||R.init();const i=R.moov(t);return Ce(R.FTYP,i)}static hvc1(t){const i=t.params,s=[t.vps,t.sps,t.pps],r=new Uint8Array([1,i.general_profile_space<<6|(i.general_tier_flag?32:0)|i.general_profile_idc,i.general_profile_compatibility_flags[0],i.general_profile_compatibility_flags[1],i.general_profile_compatibility_flags[2],i.general_profile_compatibility_flags[3],i.general_constraint_indicator_flags[0],i.general_constraint_indicator_flags[1],i.general_constraint_indicator_flags[2],i.general_constraint_indicator_flags[3],i.general_constraint_indicator_flags[4],i.general_constraint_indicator_flags[5],i.general_level_idc,240|i.min_spatial_segmentation_idc>>8,255&i.min_spatial_segmentation_idc,252|i.parallelismType,252|i.chroma_format_idc,248|i.bit_depth_luma_minus8,248|i.bit_depth_chroma_minus8,0,parseInt(i.frame_rate.fps),3|i.temporal_id_nested<<2|i.num_temporal_layers<<3|(i.frame_rate.fixed?64:0),s.length]);let n=r.length;for(let f=0;f<s.length;f+=1){n+=3;for(let m=0;m<s[f].length;m+=1)n+=2+s[f][m].length}const a=new Uint8Array(n);a.set(r,0),n=r.length;const o=s.length-1;for(let f=0;f<s.length;f+=1){a.set(new Uint8Array([32+f|(f===o?128:0),0,s[f].length]),n),n+=3;for(let m=0;m<s[f].length;m+=1)a.set(new Uint8Array([s[f][m].length>>8,s[f][m].length&255]),n),n+=2,a.set(s[f][m],n),n+=s[f][m].length}const l=R.box(R.types.hvcC,a),d=t.width,c=t.height,h=t.pixelRatio[0],u=t.pixelRatio[1];return R.box(R.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,d>>8&255,d&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&255])))}},me.types=void 0,me.HDLR_TYPES=void 0,me.STTS=void 0,me.STSC=void 0,me.STCO=void 0,me.STSZ=void 0,me.VMHD=void 0,me.SMHD=void 0,me.STSD=void 0,me.FTYP=void 0,me.DINF=void 0,qr=9e4,Td=10*1e3,Sd=1024,bd=1152,Id=1536,mt=null,rs=null,ti=class extends we{constructor(e,t,i,s){if(super("mp4-remuxer",s),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,mt===null){const r=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);mt=r?parseInt(r[1]):0}if(rs===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);rs=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&Zo(t)} > ${e&&Zo(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,s=e.reduce((r,n)=>{let a=n.pts,o=a-r;return o<-4294967296&&(t=!0,a=Pe(a,i),o=a-r),o>0?r:a},i);return t&&this.debug("PTS rollover detected"),s}remux(e,t,i,s,r,n,a,o){let l,d,c,h,u,f,m=r,g=r;const y=e.pid>-1,v=t.pid>-1,E=t.samples.length,T=e.samples.length>0,S=a&&E>0||E>1;if((!y||T)&&(!v||S)||this.ISGenerated||a){if(this.ISGenerated){var A,b,I,D;const U=this.videoTrackConfig;(U&&(t.width!==U.width||t.height!==U.height||((A=t.pixelRatio)==null?void 0:A[0])!==((b=U.pixelRatio)==null?void 0:b[0])||((I=t.pixelRatio)==null?void 0:I[1])!==((D=U.pixelRatio)==null?void 0:D[1]))||!U&&S||this.nextAudioTs===null&&T)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,r,n));const w=this.isVideoContiguous;let P=-1,x;if(S&&(P=Rf(t.samples),!w&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,P>0){this.warn(`Dropped ${P} out of ${E} video samples due to a missing keyframe`);const U=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(P),t.dropped+=P,g+=(t.samples[0].pts-U)/t.inputTimeScale,x=g}else P===-1&&(this.warn(`No keyframe found out of ${E} video samples`),f=!1);if(this.ISGenerated){if(T&&S){const U=this.getVideoStartPts(t.samples),O=(Pe(e.samples[0].pts,U)-U)/t.inputTimeScale;m+=Math.max(0,O),g+=Math.max(0,-O)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(e,t,r,n)),d=this.remuxAudio(e,m,this.isAudioContiguous,n,v||S||o===B.AUDIO?g:void 0),S){const U=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,g,w,U)}}else S&&(l=this.remuxVideo(t,g,w,0));l&&(l.firstKeyFrame=P,l.independent=P!==-1,l.firstKeyFramePTS=x)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(u=el(i,r,this._initPTS,this._initDTS)),s.samples.length&&(h=tl(s,r,this._initPTS))),{audio:d,video:l,initSegment:c,independent:f,text:h,id3:u}}computeInitPts(e,t,i,s){const r=Math.round(i*t);let n=Pe(e,r);if(n<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${s}`);n<r+t;)n+=8589934592;return n-r}generateIS(e,t,i,s){const r=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let d=!l||s,c="audio/mp4",h,u,f,m=-1;if(d&&(h=u=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(c="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}o.audio={id:"audio",container:c,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):me.initSegment([e]),metadata:{channelCount:e.channelCount}},d&&(m=e.id,f=e.inputTimeScale,!l||f!==l.timescale?h=u=this.computeInitPts(r[0].pts,f,i,"audio"):d=!1)}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:me.initSegment([t]),metadata:{width:t.width,height:t.height}},d)if(m=t.id,f=t.inputTimeScale,!l||f!==l.timescale){const g=this.getVideoStartPts(n),y=Pe(n[0].dts,g),v=this.computeInitPts(y,f,i,"video"),E=this.computeInitPts(g,f,i,"video");u=Math.min(u,v),h=Math.min(h,E)}else d=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,d?(l&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${i} ${h/f} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${h/f} (${h}/${f}) trackId: ${m}`),this._initPTS={baseTime:h,timescale:f,trackId:m},this._initDTS={baseTime:u,timescale:f,trackId:m}):h=f=void 0,{tracks:o,initPTS:h,timescale:f,trackId:m}}remuxVideo(e,t,i,s){const r=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS,d=l.baseTime*r/l.timescale;let c=this.nextVideoTs,h=8,u=this.videoSampleDuration,f,m,g=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,v=!1;if(!i||c===null){const k=d+t*r,C=n[0].pts-Pe(n[0].dts,n[0].pts);mt&&c!==null&&Math.abs(k-C-(c+d))<15e3?i=!0:c=k-C-d}const E=c+d;for(let k=0;k<o;k++){const C=n[k];C.pts=Pe(C.pts,E),C.dts=Pe(C.dts,E),C.dts<n[k>0?k-1:k].dts&&(v=!0)}v&&n.sort(function(k,C){const G=k.dts-C.dts,j=k.pts-C.pts;return G||j}),f=n[0].dts,m=n[n.length-1].dts;const T=m-f,S=T?Math.round(T/(o-1)):u||e.inputTimeScale/30;if(i){const k=f-E,C=k>S,G=k<-1;if((C||G)&&(C?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Kt(k,!0)} ms (${k}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Kt(-k,!0)} ms (${k}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!G||E>=n[0].pts||mt)){f=E;const j=n[0].pts-k;if(C)n[0].dts=f,n[0].pts=j;else{let J=!0;for(let X=0;X<n.length&&!(n[X].dts>j&&J);X++){const Q=n[X].pts;if(n[X].dts-=k,n[X].pts-=k,X<n.length-1){const Ie=n[X+1].pts;J=Ie<=n[X].pts==Ie<=Q}}}this.log(`Video: Initial PTS/DTS adjusted: ${Kt(j,!0)}/${Kt(f,!0)}, delta: ${Kt(k,!0)} ms`)}}f=Math.max(0,f);let A=0,b=0,I=f;for(let k=0;k<o;k++){const C=n[k],G=C.units,j=G.length;let J=0;for(let X=0;X<j;X++)J+=G[X].data.length;b+=J,A+=j,C.length=J,C.dts<I?(C.dts=I,I+=S/4|0||1):I=C.dts,g=Math.min(C.pts,g),y=Math.max(C.pts,y)}m=n[o-1].dts;const D=b+4*A+8;let w;try{w=new Uint8Array(D)}catch(k){this.observer.emit(p.ERROR,p.ERROR,{type:$.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,error:k,bytes:D,reason:`fail allocating video mdat ${D}`});return}const P=new DataView(w.buffer);P.setUint32(0,D),w.set(me.types.mdat,4);let x=!1,U=Number.POSITIVE_INFINITY,O=Number.POSITIVE_INFINITY,V=Number.NEGATIVE_INFINITY,F=Number.NEGATIVE_INFINITY;for(let k=0;k<o;k++){const C=n[k],G=C.units;let j=0;for(let Q=0,Ie=G.length;Q<Ie;Q++){const _e=G[Q],He=_e.data,yt=_e.data.byteLength;P.setUint32(h,yt),h+=4,w.set(He,h),h+=yt,j+=4+yt}let J;if(k<o-1)u=n[k+1].dts-C.dts,J=n[k+1].pts-C.pts;else{const Q=this.config,Ie=k>0?C.dts-n[k-1].dts:S;if(J=k>0?C.pts-n[k-1].pts:S,Q.stretchShortVideoTrack&&this.nextAudioTs!==null){const _e=Math.floor(Q.maxBufferHole*r),He=(s?g+s*r:this.nextAudioTs+d)-C.pts;He>_e?(u=He-Ie,u<0?u=Ie:x=!0,this.log(`It is approximately ${He/90} ms to the next segment; using duration ${u/90} ms for the last video frame.`)):u=Ie}else u=Ie}const X=Math.round(C.pts-C.dts);U=Math.min(U,u),V=Math.max(V,u),O=Math.min(O,J),F=Math.max(F,J),a.push(Jo(C.key,u,j,X))}if(a.length){if(mt){if(mt<70){const k=a[0].flags;k.dependsOn=2,k.isNonSync=0}}else if(rs&&F-O<V-U&&S/V<.025&&a[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let k=f;for(let C=0,G=a.length;C<G;C++){const j=k+a[C].duration,J=k+a[C].cts;if(C<G-1){const X=j+a[C+1].cts;a[C].duration=X-J}else a[C].duration=C?a[C-1].duration:S;a[C].cts=0,k=j}}}u=x||!u?S:u;const M=m+u;this.nextVideoTs=c=M-d,this.videoSampleDuration=u,this.isVideoContiguous=!0;const W={data1:me.moof(e.sequenceNumber++,f,se(e,{samples:a})),data2:w,startPTS:(g-d)/r,endPTS:(y+u-d)/r,startDTS:(f-d)/r,endDTS:c/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,W}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return bd;case"ac3":return Id;default:return Sd}}remuxAudio(e,t,i,s,r){const n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),l=o*a,d=this._initPTS,c=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,h=[],u=r!==void 0;let f=e.samples,m=c?0:8,g=this.nextAudioTs||-1;const y=d.baseTime*n/d.timescale,v=y+t*n;if(this.isAudioContiguous=i=i||f.length&&g>0&&(s&&Math.abs(v-(g+y))<9e3||Math.abs(Pe(f[0].pts,v)-(g+y))<20*l),f.forEach(function(O){O.pts=Pe(O.pts,v)}),!i||g<0){const O=f.length;if(f=f.filter(V=>V.pts>=0),O!==f.length&&this.warn(`Removed ${f.length-O} of ${O} samples (initPTS ${y} / ${n})`),!f.length)return;r===0?g=0:s&&!u?g=Math.max(0,v-y):g=f[0].pts-y}if(e.segmentCodec==="aac"){const O=this.config.maxAudioFramesDrift;for(let V=0,F=g+y;V<f.length;V++){const M=f[V],W=M.pts,k=W-F,C=Math.abs(1e3*k/n);if(k<=-O*l&&u)V===0&&(this.warn(`Audio frame @ ${(W/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*k/n)} ms.`),this.nextAudioTs=g=W-y,F=W);else if(k>=O*l&&C<Td&&u){let G=Math.round(k/l);for(F=W-G*l;F<0&&G&&l;)G--,F+=l;V===0&&(this.nextAudioTs=g=F-y),this.warn(`Injecting ${G} audio frames @ ${((F-y)/n).toFixed(3)}s due to ${Math.round(1e3*k/n)} ms gap.`);for(let j=0;j<G;j++){let J=Ed.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);J||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),J=M.unit.subarray()),f.splice(V,0,{unit:J,pts:F}),F+=l,V++}}M.pts=F,F+=l}}let E=null,T=null,S,A=0,b=f.length;for(;b--;)A+=f[b].unit.byteLength;for(let O=0,V=f.length;O<V;O++){const F=f[O],M=F.unit;let W=F.pts;if(T!==null){const C=h[O-1];C.duration=Math.round((W-T)/a)}else if(i&&e.segmentCodec==="aac"&&(W=g+y),E=W,A>0){A+=m;try{S=new Uint8Array(A)}catch(C){this.observer.emit(p.ERROR,p.ERROR,{type:$.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,error:C,bytes:A,reason:`fail allocating audio mdat ${A}`});return}c||(new DataView(S.buffer).setUint32(0,A),S.set(me.types.mdat,4))}else return;S.set(M,m);const k=M.byteLength;m+=k,h.push(Jo(!0,o,k,0)),T=W}const I=h.length;if(!I)return;const D=h[h.length-1];g=T-y,this.nextAudioTs=g+a*D.duration;const w=c?new Uint8Array(0):me.moof(e.sequenceNumber++,E/a,se({},e,{samples:h}));e.samples=[];const P=(E-y)/n,x=this.nextAudioTs/n,U={data1:w,data2:S,startPTS:P,endPTS:x,startDTS:P,endDTS:x,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,U}},Ad=class extends we{constructor(e,t,i,s){super("passthrough-remuxer",s),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,s){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,s),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:i,videoCodec:s}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:n}=this.initData=Ua(e);if(t)Zh(e,t);else{const o=r||n;o!=null&&o.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${o.codec}")!`)}r&&(i=il(r,re.AUDIO,this)),n&&(s=il(n,re.VIDEO,this));const a={};r&&n?a.audiovideo={container:"video/mp4",codec:i+","+s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:r?a.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:e,id:"audio"}:n?a.video={container:"video/mp4",codec:s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,i,s,r,n){var a,o;let{initPTS:l,lastEndTime:d}=this;const c={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};N(d)||(d=this.lastEndTime=r||0);const h=t.samples;if(!h.length)return c;const u={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if((a=f)!=null&&a.length||(this.generateInitSegment(h),f=this.initData),!((o=f)!=null&&o.length))return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const m=eu(h,f,this),g=f.audio?m[f.audio.id]:null,y=f.video?m[f.video.id]:null,v=Ui(y,1/0),E=Ui(g,1/0),T=Ui(y,0,!0),S=Ui(g,0,!0);let A=r,b=0;const I=g&&(!y||!l&&E<v||l&&l.trackId===f.audio.id),D=I?g:y;if(D){const W=D.timescale,k=D.start-r*W,C=I?f.audio.id:f.video.id;A=D.start/W,b=I?S-E:T-v,(n||!l)&&(Df(l,A,r,b)||W!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${k/W} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${A-r} (${k}/${W}) trackId: ${C}`),l=null,u.initPTS=k,u.timescale=W,u.trackId=C)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(u.initPTS=l.baseTime,u.timescale=l.timescale,u.trackId=l.trackId):((!u.timescale||u.trackId===void 0||u.initPTS===void 0)&&(this.warn("Could not set initPTS"),u.initPTS=A,u.timescale=1,u.trackId=-1),this.initPTS=l={baseTime:u.initPTS,timescale:u.timescale,trackId:u.trackId});const w=A-l.baseTime/l.timescale,P=w+b;b>0?this.lastEndTime=P:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const x=!!f.audio,U=!!f.video;let O="";x&&(O+="audio"),U&&(O+="video");const V=(f.audio?f.audio.encrypted:!1)||(f.video?f.video.encrypted:!1),F={data1:h,startPTS:w,startDTS:w,endPTS:P,endDTS:P,type:O,hasAudio:x,hasVideo:U,nb:1,dropped:0,encrypted:V};c.audio=x&&!U?F:void 0,c.video=U?F:void 0;const M=y?.sampleCount;if(M){const W=y.keyFrameIndex,k=W!==-1;F.nb=M,F.dropped=W===0||this.isVideoContiguous?0:k?W:M,F.independent=k,F.firstKeyFrame=W,k&&y.keyFrameStart&&(F.firstKeyFramePTS=(y.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(c.independent=k),this.isVideoContiguous||(this.isVideoContiguous=k),F.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${W}/${M} dropped: ${F.dropped} start: ${F.firstKeyFramePTS||"NA"}`)}return c.initSegment=u,c.id3=el(i,r,l,l),s.samples.length&&(c.text=tl(s,r,l)),c}};try{Ze=self.performance.now.bind(self.performance)}catch{Ze=Date.now}ii=[{demux:gd,remux:Ad},{demux:vd,remux:ti},{demux:cd,remux:ti},{demux:ud,remux:ti}],ii.splice(2,0,{demux:hd,remux:ti}),Xr=class{constructor(e,t,i,s,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){const r=i.transmuxing;r.executeStart=Ze();let n=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;s&&(this.currentTransmuxState=s);const{contiguous:l,discontinuity:d,trackSwitch:c,accurateTimeOffset:h,timeOffset:u,initSegmentChange:f}=s||a,{audioCodec:m,videoCodec:g,defaultInitPts:y,duration:v,initSegmentData:E}=o,T=Pf(n,t);if(T&&bt(T.method)){const I=this.getDecrypter(),D=Xs(T.method);if(I.isSync()){let w=I.softwareDecrypt(n,T.key.buffer,T.iv.buffer,D);if(i.part>-1){const P=I.flush();w=P&&P.buffer}if(!w)return r.executeEnd=Ze(),ns(i);n=new Uint8Array(w)}else return this.asyncResult=!0,this.decryptionPromise=I.webCryptoDecrypt(n,T.key.buffer,T.iv.buffer,D).then(w=>{const P=this.push(w,null,i);return this.decryptionPromise=null,P}),this.decryptionPromise}const S=this.needsProbing(d,c);if(S){const I=this.configureTransmuxer(n);if(I)return this.logger.warn(`[transmuxer] ${I.message}`),this.observer.emit(p.ERROR,p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),r.executeEnd=Ze(),ns(i)}(d||c||f||S)&&this.resetInitSegment(E,m,g,v,t),(d||f||S)&&this.resetInitialTimestamp(y),l||this.resetContiguity();const A=this.transmux(n,T,u,h,i);this.asyncResult=Ht(A);const b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,r.executeEnd=Ze(),A}flush(e){const t=e.transmuxing;t.executeStart=Ze();const{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:a}=s;if(i){const c=i.flush();c&&n.push(this.push(c.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=Ze();const c=[ns(e)];return this.asyncResult?Promise.resolve(c):c}const d=o.flush(a);return Ht(d)?(this.asyncResult=!0,d.then(c=>(this.flushRemux(n,c,e),n))):(this.flushRemux(n,d,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,i){const{audioTrack:s,videoTrack:r,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===B.MAIN?"level":"track"} ${i.level}`);const d=this.remuxer.remux(s,r,n,a,l,o,!0,this.id);e.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=Ze()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,s,r){const{demuxer:n,remuxer:a}=this;!n||!a||(n.resetInitSegment(e,t,i,s),a.resetInitSegment(e,t,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,s,r){let n;return t&&t.method==="SAMPLE-AES"?n=this.transmuxSampleAes(e,t,i,s,r):n=this.transmuxUnencrypted(e,i,s,r),n}transmuxUnencrypted(e,t,i,s){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,t,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,t,i,s,r){return this.demuxer.demuxSampleAes(e,t,i).then(n=>({remuxResult:this.remuxer.remux(n.audioTrack,n.videoTrack,n.id3Track,n.textTrack,i,s,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:s}=this;let r;for(let c=0,h=ii.length;c<h;c++){var n;if((n=ii[c].demux)!=null&&n.probe(e,this.logger)){r=ii[c];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.remux,d=r.demux;(!o||!(o instanceof l))&&(this.remuxer=new l(i,t,s,this.logger)),(!a||!(a instanceof d))&&(this.demuxer=new d(i,t,s,this.logger),this.probe=d.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Qi(this.config)),e}},ns=e=>({remuxResult:{},chunkMeta:e}),Ld=class{constructor(e,t,i,s,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}},Rd=class{constructor(e,t,i,s,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=n}},Qr=0,Zr=class{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Qr++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=o=>{const l=o.data,d=this.hls;if(!(!d||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var c;const h=(c=this.workerContext)==null?void 0:c.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":this.handleTransmuxComplete(l.data);break;case"flush":this.onFlush(l.data);break;case"workerLog":d.logger[l.data.logType]&&d.logger[l.data.logType](l.data.message);break;default:l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,d.trigger(l.event,l.data);break}},this.onWorkerError=o=>{if(!this.hls)return;const l=new Error(`${o.message} (${o.filename}:${o.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const n=(o,l)=>{l=l||{},l.frag=this.frag||void 0,o===p.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(o,l)};this.observer=new is,this.observer.on(p.FRAG_DECRYPTED,n),this.observer.on(p.ERROR,n);const a=Wa(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const o=this.hls.logger;if(r.workerPath||Ju()){try{r.workerPath?(o.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=tf(r.workerPath)):(o.log(`injecting Web Worker for "${t}"`),this.workerContext=ef());const{worker:l}=this.workerContext;l.addEventListener("message",this.onWorkerMessage),l.addEventListener("error",this.onWorkerError),l.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:ne(r)})}catch(l){o.warn(`Error setting up "${t}" Web Worker, fallback to inline`,l),this.terminateWorker(),this.error=null,this.transmuxer=new Xr(this.observer,a,r,"",t,e.logger)}return}}this.transmuxer=new Xr(this.observer,a,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Qr++;const t=this.hls.config,i=Wa(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:ne(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),sf(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,s,r,n,a,o,l,d){var c,h;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,m=n?n.start:r.start,g=r.decryptdata,y=this.frag,v=!(y&&r.cc===y.cc),E=!(y&&l.level===y.level),T=y?l.sn-y.sn:-1,S=this.part?l.part-this.part.index:-1,A=T===0&&l.id>1&&l.id===y?.stats.chunkCount,b=!E&&(T===1||T===0&&(S===1||A&&S<=0)),I=self.performance.now();(E||T||r.stats.parsing.start===0)&&(r.stats.parsing.start=I),n&&(S||!b)&&(n.stats.parsing.start=I);const D=!(y&&((c=r.initSegment)==null?void 0:c.url)===((h=y.initSegment)==null?void 0:h.url)),w=new Rd(v,b,o,E,m,D);if(!b||v||D){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===B.MAIN?"level":"track"}: ${l.level} id: ${l.id}
|
|
62
|
+
Time to underbuffer: ${X.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,C>u){let Q=this.findBestLevel(this.hls.levels[u].bitrate,u,C,0,X,1,1);Q===-1&&(Q=u),this.hls.nextLoadLevel=this.hls.nextAutoLevel=Q,this.resetEstimator(this.hls.levels[Q].bitrate)}}};g||V>k*2?J():this.timer=self.setInterval(J,k*1e3),n.trigger(p.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:r,stats:d})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new Nl(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(p.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var s;this.fragCurrent=i,this.partCurrent=(s=t.part)!=null?s:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case L.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:s,partCurrent:r}=this;if(i&&s&&i.sn===s.sn&&i.level===s.level){const n=performance.now(),a=r?r.stats:i.stats,o=n-a.loading.start,l=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&l>-1){const d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(d,l),a.loaded)}else this.bwEstimator.sampleTTFB(o)}break}}}getTimeToLoadFrag(e,t,i,s){return e+i/t+(s?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const i=this.hls.config,{loading:s}=t.stats,r=s.end-s.first;N(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const s=i?i.stats:t.stats;if(t.type===B.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=i?i.duration:t.duration,n=this.hls.levels[t.level],a=(n.loaded?n.loaded.bytes:0)+s.loaded,o=(n.loaded?n.loaded.duration:0)+r;n.loaded={bytes:a,duration:o},n.realBitrate=Math.round(8*a/o)}if(t.bitrateTest){const r={stats:s,frag:t,part:i,id:t.type};this.onFragBuffered(p.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:s}=t,r=s!=null&&s.stats.loaded?s.stats:i.stats;if(r.aborted||this.ignoreFragment(i))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==B.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,t,e,0,s,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!t||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const s=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const r=this.hls.levels;if(r.length>Math.max(e,s)&&r[e].loadError<=r[s].loadError)return e}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:s,config:r,minAutoLevel:n}=i,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=r.abrBandWidthFactor,c=r.abrBandWidthUpFactor;if(l){const g=this.findBestLevel(o,n,s,l,0,d,c);if(g>=0)return this.rebufferNotice=-1,g}let h=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const g=this.bitrateTestDelay;g&&(h=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-g,this.info(`bitrate test took ${Math.round(1e3*g)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),d=c=1)}const u=this.findBestLevel(o,n,s,l,h,d,c);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=i.levels[n],m=i.loadLevelObj;return m&&f?.bitrate<m.bitrate?n:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,s,r,n,a){var o;const l=s+r,d=this.lastLoadedFragLevel,c=d===-1?this.hls.firstLevel:d,{fragCurrent:h,partCurrent:u}=this,{levels:f,allAudioTracks:m,loadLevel:g,config:y}=this.hls;if(f.length===1)return 0;const v=f[c],E=!!((o=this.hls.latestLevelDetails)!=null&&o.live),T=g===-1||d===-1;let S,A="SDR",b=v?.frameRate||0;const{audioPreference:I,videoPreference:D}=y,P=this.audioTracksByGroup||(this.audioTracksByGroup=Qa(m));let w=-1;if(T){if(this.firstSelection!==-1)return this.firstSelection;const F=Su(this.codecTiers||(this.codecTiers=bu(f,P,t,i)),A,e,I,D),{codecSet:M,videoRanges:W,minFramerate:k,minBitrate:C,minIndex:G,preferHDR:j}=F;w=G,S=M,A=j?W[W.length-1]:W[0],b=k,e=Math.max(e,C),this.log(`picked start tier ${ne(F)}`)}else S=v?.codecSet,A=v?.videoRange;const x=u?u.duration:h?h.duration:0,U=this.bwEstimator.getEstimateTTFB()/1e3,O=[];for(let F=i;F>=t;F--){var V;const M=f[F],W=F>c;if(!M)continue;if(y.useMediaCapabilities&&!M.supportedResult&&!M.supportedPromise){const X=navigator.mediaCapabilities;typeof X?.decodingInfo=="function"&&uu(M,P,A,b,e,I)?(M.supportedPromise=Ya(M,P,X,this.supportedCache),M.supportedPromise.then(Q=>{if(!this.hls)return;M.supportedResult=Q;const Ie=this.hls.levels,_e=Ie.indexOf(M);Q.error?this.warn(`MediaCapabilities decodingInfo error: "${Q.error}" for level ${_e} ${ne(Q)}`):Q.supported?Q.decodingInfoResults.some(He=>He.smooth===!1||He.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${_e} not smooth or powerEfficient: ${ne(Q)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${_e} ${ne(Q)}`),_e>-1&&Ie.length>1&&(this.log(`Removing unsupported level ${_e}`),this.hls.removeLevel(_e),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Q=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Q}`)})):M.supportedResult=Mr}if((S&&M.codecSet!==S||A&&M.videoRange!==A||W&&b>M.frameRate||!W&&b>0&&b<M.frameRate||(V=M.supportedResult)!=null&&(V=V.decodingInfoResults)!=null&&V.some(X=>X.smooth===!1))&&(!T||F!==w)){O.push(F);continue}const k=M.details,C=(u?k?.partTarget:k?.averagetargetduration)||x;let G;W?G=a*e:G=n*e;const j=x&&s>=x*2&&r===0?M.averageBitrate:M.maxBitrate,J=this.getTimeToLoadFrag(U,G,j*C,k===void 0);if(G>=j&&(F===d||M.loadError===0&&M.fragmentError===0)&&(J<=U||!N(J)||E&&!this.bitrateTestDelay||J<l)){const X=this.forcedAutoLevel;return F!==g&&(X===-1||X!==g)&&(O.length&&this.trace(`Skipped level(s) ${O.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[O[0]].codecs}" ${f[O[0]].videoRange}; not compatible with "${S}" ${A}`),this.info(`switch candidate:${c}->${F} adjustedbw(${Math.round(G)})-bitrate=${Math.round(G-j)} ttfb:${U.toFixed(1)} avgDuration:${C.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${J.toFixed(1)} firstSelection:${T} codecSet:${M.codecSet} videoRange:${M.videoRange} hls.loadLevel:${g}`)),T&&(this.firstSelection=F),F}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},Fr={search:function(e,t){let i=0,s=e.length-1,r=null,n=null;for(;i<=s;){r=(i+s)/2|0,n=e[r];const a=t(n);if(a>0)i=r+1;else if(a<0)s=r-1;else return n}return null}},ce={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Te={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8},Nr=class extends Pe{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.ERROR,this.onError,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.ERROR,this.onError,this),e.off(p.ERROR,this.onErrorOut,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===B.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,i=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return!0;const s=e.audioGroups;if(s)return this.hls.allAudioTracks.filter(r=>s.indexOf(r.groupId)>=0).some(r=>{var n;return(n=r.details)==null?void 0:n.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const s=this.hls,r=t.context;switch(t.details){case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case L.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=Tt();return}case L.FRAG_GAP:case L.FRAG_DECRYPT_ERROR:t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=ce.SendAlternateToPenaltyBox;return;case L.LEVEL_EMPTY_ERROR:case L.LEVEL_PARSING_ERROR:{var n;const o=t.parent===B.MAIN?t.level:s.loadLevel;t.details===L.LEVEL_EMPTY_ERROR&&((n=t.context)!=null&&(n=n.levelDetails)!=null&&n.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,o))}return;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.SUBTITLE_LOAD_ERROR:case L.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const o=s.loadLevelObj;if(o&&(r.type===q.AUDIO_TRACK&&o.hasAudioGroup(r.groupId)||r.type===q.SUBTITLE_TRACK&&o.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=ce.SendAlternateToPenaltyBox,t.errorAction.flags=Te.MoveAllAlternatesMatchingHost;return}}return;case L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:ce.SendAlternateToPenaltyBox,flags:Te.MoveAllAlternatesMatchingHDCP};return;case L.KEY_SYSTEM_SESSION_UPDATE_FAILED:case L.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case L.KEY_SYSTEM_NO_SESSION:t.errorAction={action:ce.SendAlternateToPenaltyBox,flags:Te.MoveAllAlternatesMatchingKey};return;case L.BUFFER_ADD_CODEC_ERROR:case L.REMUX_ALLOC_ERROR:case L.BUFFER_APPEND_ERROR:if(!t.errorAction){var a;t.errorAction=this.getLevelSwitchAction(t,(a=t.level)!=null?a:s.loadLevel)}return;case L.INTERNAL_EXCEPTION:case L.BUFFER_APPENDING_ERROR:case L.BUFFER_FULL_ERROR:case L.LEVEL_SWITCH_ERROR:case L.BUFFER_STALLED_ERROR:case L.BUFFER_SEEK_OVER_HOLE:case L.BUFFER_NUDGE_ON_STALL:t.errorAction=Tt();return}t.type===$.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Tt())}getPlaylistRetryOrSwitchAction(e,t){const i=this.hls,s=ro(i.config.playlistLoadPolicy,e),r=this.playlistError++;if(_i(s,r,Pi(e),e.response))return{action:ce.RetryRequest,flags:Te.None,retryConfig:s,retryCount:r};const n=this.getLevelSwitchAction(e,t);return s&&(n.retryConfig=s,n.retryCount=r),n}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,a=ro(io(e)?n:r,e),o=t.levels.reduce((d,c)=>d+c.fragmentError,0);if(s&&(e.details!==L.FRAG_GAP&&s.fragmentError++,!so(e)&&_i(a,o,Pi(e),e.response)))return{action:ce.RetryRequest,flags:Te.None,retryConfig:a,retryCount:o};const l=this.getLevelSwitchAction(e,i);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const s=this.hls.levels[t];if(s){var r,n;const l=e.details;s.loadError++,l===L.BUFFER_APPEND_ERROR&&s.fragmentError++;let d=-1;const{levels:c,loadLevel:h,minAutoLevel:u,maxAutoLevel:f}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);const m=(r=e.frag)==null?void 0:r.type,g=(m===B.AUDIO&&l===L.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===L.BUFFER_ADD_CODEC_ERROR||l===L.BUFFER_APPEND_ERROR))&&c.some(({audioCodec:T})=>s.audioCodec!==T),y=e.sourceBufferName==="video"&&(l===L.BUFFER_ADD_CODEC_ERROR||l===L.BUFFER_APPEND_ERROR)&&c.some(({codecSet:T,audioCodec:S})=>s.codecSet!==T&&s.audioCodec===S),{type:v,groupId:E}=(n=e.context)!=null?n:{};for(let T=c.length;T--;){const S=(T+h)%c.length;if(S!==h&&S>=u&&S<=f&&c[S].loadError===0){var a,o;const A=c[S];if(l===L.FRAG_GAP&&m===B.MAIN&&e.frag){const b=c[S].details;if(b){const I=lt(e.frag,b.fragments,e.frag.start);if(I!=null&&I.gap)continue}}else{if(v===q.AUDIO_TRACK&&A.hasAudioGroup(E)||v===q.SUBTITLE_TRACK&&A.hasSubtitleGroup(E))continue;if(m===B.AUDIO&&(a=s.audioGroups)!=null&&a.some(b=>A.hasAudioGroup(b))||m===B.SUBTITLE&&(o=s.subtitleGroups)!=null&&o.some(b=>A.hasSubtitleGroup(b))||g&&s.audioCodec===A.audioCodec||y&&s.codecSet===A.codecSet||!g&&s.codecSet!==A.codecSet)continue}d=S;break}}if(d>-1&&i.loadLevel!==d)return e.levelRetry=!0,this.playlistError=0,{action:ce.SendAlternateToPenaltyBox,flags:Te.None,nextAutoLevel:d}}return{action:ce.SendAlternateToPenaltyBox,flags:Te.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case ce.DoNothing:break;case ce.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==L.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;case ce.RetryRequest:break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:s}=i,r=i.nextAutoLevel;switch(s){case Te.None:this.switchLevel(e,r);break;case Te.MoveAllAlternatesMatchingHDCP:{const o=this.getVariantLevelIndex(e.frag),l=t.levels[o],d=l?.attrs["HDCP-LEVEL"];if(i.hdcpLevel=d,d==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(d){t.maxHdcpLevel=qi[qi.indexOf(d)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Te.MoveAllAlternatesMatchingKey:{const o=e.decryptdata;if(o){const l=this.hls.levels,d=l.length;for(let h=d;h--;)if(this.variantHasKey(l[h],o)){var n,a;this.log(`Banned key found in level ${h} (${l[h].bitrate}bps) or audio group "${(n=l[h].audioGroups)==null?void 0:n.join(",")}" (${(a=e.frag)==null?void 0:a.type} fragment) ${ye(o.keyId||[])}`),l[h].fragmentError++,l[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h)}const c=e.frag;if(this.hls.levels.length<d)i.resolved=!0;else if(c&&c.type!==B.MAIN){const h=c.decryptdata;h&&!o.matches(h)&&(i.resolved=!0)}}break}}i.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===L.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const i=js(e.mimeType),s=this.hls.levels;for(let r=s.length;r--;)s[r][`${e.sourceBufferName}Codec`]===i&&(this.log(`Removing level ${r} for ${e.details} ("${i}" not supported)`),this.hls.removeLevel(r))}}},he={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Wl=class{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let s=i.length;s--;){const r=i[s];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){const{fragments:s}=this,r=Object.keys(s);for(let n=r.length;n--;){const a=s[r[n]];if(a?.body.type===t&&(!i||a.buffered)){const o=a.body;if(o.start<=e&&e<=o.end)return o}}return null}detectEvictedFragments(e,t,i,s,r){this.timeRanges&&(this.timeRanges[e]=t);const n=s?.fragment.sn||-1;Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o||n>=o.body.sn)return;if(!o.buffered&&(!o.loaded||r)){o.body.type===i&&this.removeFragment(o.body);return}const l=o.range[e];if(l){if(l.time.length===0){this.removeFragment(o.body);return}l.time.some(d=>{const c=!this.isTimeBuffered(d.startPTS,d.endPTS,t);return c&&this.removeFragment(o.body),c})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const i=e.frag,s=St(i),r=this.fragments[s];if(!r||r.buffered&&i.gap)return;const n=!i.relurl;Object.keys(t).forEach(a=>{const o=i.elementaryStreams[a];if(!o)return;const l=t[a],d=n||o.partial===!0;r.range[a]=this.getBufferedTimes(i,e.part,d,l)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,i),ki(r)||this.removeParts(i.sn-1,i.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=ao(i,s=>s.fragment.sn>=e))}fragBuffered(e,t){const i=St(e);let s=this.fragments[i];!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,this.bufferedEnd(s,e))}getBufferedTimes(e,t,i,s){const r={time:[],partial:i},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let d=0;d<s.length;d++){const c=s.start(d)-this.bufferPadding,h=s.end(d)+this.bufferPadding;if(l>=c&&o<=h){r.time.push({startPTS:Math.max(n,s.start(d)),endPTS:Math.min(a,s.end(d))});break}else if(n<h&&a>c){const u=Math.max(n,s.start(d)),f=Math.min(a,s.end(d));f>u&&(r.partial=!0,r.time.push({startPTS:u,endPTS:f}))}else if(a<=c)break}return r}getPartialFragment(e){let t=null,i,s,r,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&ki(d)&&(s=d.body.start-a,r=d.body.end+a,e>=s&&e<=r&&(i=Math.min(e-s,r-e),n<=i&&(t=d.body,n=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||ki(t))}getState(e){const t=St(e),i=this.fragments[t];return i?i.buffered?ki(i)?he.PARTIAL:he.OK:he.APPENDING:he.NOT_LOADED}isTimeBuffered(e,t,i){let s,r;for(let n=0;n<i.length;n++){if(s=i.start(n)-this.bufferPadding,r=i.end(n)+this.bufferPadding,e>=s&&t<=r)return!0;if(t<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const i=t.frag,s=t.part?null:t,r=St(i);this.fragments[r]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:s,timeRanges:r,type:n}=t;if(i.sn==="initSegment")return;const a=i.type;if(s){let l=this.activePartLists[a];l||(this.activePartLists[a]=l=[]),l.push(s)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,s)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=St(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let s=i.length;s--;){const r=t[i[s]];if(r?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,s,r){s&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==i||s&&!o.gap||o.start<t&&o.end>e&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(e){const t=St(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const s=e.sn;this.activePartLists[e.type]=ao(i,r=>r.fragment.sn!==s)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo())}},Xe={cbc:0,ctr:1},jl=class{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case Xe.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Xe.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}},Yl=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=t.getUint32(s*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],r=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],d=o[1],c=o[2],h=o[3],u=new Uint32Array(256);let f=0,m=0,g=0;for(g=0;g<256;g++)g<128?u[g]=g<<1:u[g]=g<<1^283;for(g=0;g<256;g++){let y=m^m<<1^m<<2^m<<3^m<<4;y=y>>>8^y&255^99,e[f]=y,t[y]=f;const v=u[f],E=u[v],T=u[E];let S=u[y]*257^y*16843008;s[f]=S<<24|S>>>8,r[f]=S<<16|S>>>16,n[f]=S<<8|S>>>24,a[f]=S,S=T*16843009^E*65537^v*257^f*16843008,l[y]=S<<24|S>>>8,d[y]=S<<16|S>>>16,c[y]=S<<8|S>>>24,h[y]=S,f?(f=v^u[u[u[T^v]]],m^=u[u[m]]):f=m=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,s=0;for(;s<t.length&&i;)i=t[s]===this.key[s],s++;if(i)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const n=this.ksRows=(r+6+1)*4;let a,o;const l=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),c=this.sBox,h=this.rcon,u=this.invSubMix,f=u[0],m=u[1],g=u[2],y=u[3];let v,E;for(a=0;a<n;a++){if(a<r){v=l[a]=t[a];continue}E=v,a%r===0?(E=E<<8|E>>>24,E=c[E>>>24]<<24|c[E>>>16&255]<<16|c[E>>>8&255]<<8|c[E&255],E^=h[a/r|0]<<24):r>6&&a%r===4&&(E=c[E>>>24]<<24|c[E>>>16&255]<<16|c[E>>>8&255]<<8|c[E&255]),l[a]=v=(l[a-r]^E)>>>0}for(o=0;o<n;o++)a=n-o,o&3?E=l[a]:E=l[a-4],o<4||a<=4?d[o]=E:d[o]=f[c[E>>>24]]^m[c[E>>>16&255]]^g[c[E>>>8&255]]^y[c[E&255]],d[o]=d[o]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const s=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],c=a[3],h=this.uint8ArrayToUint32Array_(i);let u=h[0],f=h[1],m=h[2],g=h[3];const y=new Int32Array(e),v=new Int32Array(y.length);let E,T,S,A,b,I,D,P,w,x,U,O,V,F;const M=this.networkToHostOrderSwap;for(;t<y.length;){for(w=M(y[t]),x=M(y[t+1]),U=M(y[t+2]),O=M(y[t+3]),b=w^r[0],I=O^r[1],D=U^r[2],P=x^r[3],V=4,F=1;F<s;F++)E=o[b>>>24]^l[I>>16&255]^d[D>>8&255]^c[P&255]^r[V],T=o[I>>>24]^l[D>>16&255]^d[P>>8&255]^c[b&255]^r[V+1],S=o[D>>>24]^l[P>>16&255]^d[b>>8&255]^c[I&255]^r[V+2],A=o[P>>>24]^l[b>>16&255]^d[I>>8&255]^c[D&255]^r[V+3],b=E,I=T,D=S,P=A,V=V+4;E=n[b>>>24]<<24^n[I>>16&255]<<16^n[D>>8&255]<<8^n[P&255]^r[V],T=n[I>>>24]<<24^n[D>>16&255]<<16^n[P>>8&255]<<8^n[b&255]^r[V+1],S=n[D>>>24]<<24^n[P>>16&255]<<16^n[b>>8&255]<<8^n[I&255]^r[V+2],A=n[P>>>24]<<24^n[b>>16&255]<<16^n[I>>8&255]<<8^n[D&255]^r[V+3],v[t]=M(E^u),v[t+1]=M(A^f),v[t+2]=M(S^m),v[t+3]=M(T^g),u=w,f=x,m=U,g=O,t=t+4}return v.buffer}},zl=class{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){const e=ku(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}},ql=16,Qi=class{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?_u(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,s){return this.useSoftware?new Promise((r,n)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,i,s);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,s)}softwareDecrypt(e,t,i,s){const{currentIV:r,currentResult:n,remainderData:a}=this;if(s!==Xe.cbc||t.byteLength!==16)return te.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=Ce(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;r&&(i=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Yl),l.expandKey(t);const d=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,d||null}webCryptoDecrypt(e,t,i,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,s));this.key=t,this.fastAesKey=new zl(this.subtle,t,s)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new jl(this.subtle,new Uint8Array(i),s).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(te.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i,s)))}onWebCryptoError(e,t,i,s){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,s);const n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%ql;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(te.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},Ur=Math.pow(2,17),Xl=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const i=e.url;if(!i)return Promise.reject(new Ve({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const s=this.config,r=s.fLoader,n=s.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){o(lo(e));return}else e.gap=!1;const l=this.loader=r?new r(s):new n(s),d=oo(e);e.loader=l;const c=no(s.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Ur};e.stats=l.stats;const u={onSuccess:(f,m,g,y)=>{this.resetLoader(e,l);let v=f.data;g.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(v.slice(0,16)),v=v.slice(16)),a({frag:e,part:null,payload:v,networkDetails:y})},onError:(f,m,g,y)=>{this.resetLoader(e,l),o(new Ve({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:ie({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:y}))},onAbort:(f,m,g)=>{this.resetLoader(e,l),o(new Ve({type:$.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,m,g)=>{this.resetLoader(e,l),o(new Ve({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:f}))}};t&&(u.onProgress=(f,m,g,y)=>t({frag:e,part:null,payload:g,networkDetails:y})),l.load(d,h,u)})}loadPart(e,t,i){this.abort();const s=this.config,r=s.fLoader,n=s.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){o(lo(e,t));return}const l=this.loader=r?new r(s):new n(s),d=oo(e,t);e.loader=l;const c=no(s.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ur};t.stats=l.stats,l.load(d,h,{onSuccess:(u,f,m,g)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const y={frag:e,part:t,payload:u.data,networkDetails:g};i(y),a(y)},onError:(u,f,m,g)=>{this.resetLoader(e,l),o(new Ve({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:ie({url:d.url,data:void 0},u),error:new Error(`HTTP Error ${u.code} ${u.text}`),networkDetails:m,stats:g}))},onAbort:(u,f,m)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new Ve({type:$.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:m,stats:u}))},onTimeout:(u,f,m)=>{this.resetLoader(e,l),o(new Ve({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:m,stats:u}))}})})}updateStatsFromPart(e,t){const i=e.stats,s=t.stats,r=s.total;if(i.loaded+=s.loaded,r){const o=Math.round(e.duration/t.duration),l=Math.min(Math.round(i.loaded/r),o),d=(o-l)*Math.round(i.loaded/l);i.total=i.loaded+d}else i.total=Math.max(i.loaded,i.total);const n=i.loading,a=s.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}},Ve=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},Br=class extends Pe{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},Xt=class{constructor(e,t,i,s=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=Ci(),this.buffering={audio:Ci(),video:Ci(),audiovideo:Ci()},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=r,this.partial=n}},$r={length:0,start:()=>0,end:()=>0},Y=class kt{static isBuffered(t,i){if(t){const s=kt.getBuffered(t);for(let r=s.length;r--;)if(i>=s.start(r)&&i<=s.end(r))return!0}return!1}static bufferedRanges(t){if(t){const i=kt.getBuffered(t);return kt.timeRangesToArray(i)}return[]}static timeRangesToArray(t){const i=[];for(let s=0;s<t.length;s++)i.push({start:t.start(s),end:t.end(s)});return i}static bufferInfo(t,i,s){if(t){const r=kt.bufferedRanges(t);if(r.length)return kt.bufferedInfo(r,i,s)}return{len:0,start:i,end:i,bufferedIndex:-1}}static bufferedInfo(t,i,s){i=Math.max(0,i),t.length>1&&t.sort((c,h)=>c.start-h.start||h.end-c.end);let r=-1,n=[];if(s)for(let c=0;c<t.length;c++){i>=t[c].start&&i<=t[c].end&&(r=c);const h=n.length;if(h){const u=n[h-1].end;t[c].start-u<s?t[c].end>u&&(n[h-1].end=t[c].end):n.push(t[c])}else n.push(t[c])}else n=t;let a=0,o,l=i,d=i;for(let c=0;c<n.length;c++){const h=n[c].start,u=n[c].end;if(r===-1&&i>=h&&i<=u&&(r=c),i+s>=h&&i<u)l=h,d=u,a=d-i;else if(i+s<h){o=h;break}}return{len:a,start:l||0,end:d||0,nextStart:o,buffered:t,bufferedIndex:r}}static getBuffered(t){try{return t.buffered||$r}catch(i){return te.log("failed to get media.buffered",i),$r}}},Gr=/\{\$([a-zA-Z0-9-_]+)\}/g,Ql=/^(\d+)x(\d+)$/,Vr=/(.+?)=(".*?"|.*?)(?:,|$)/g,oe=class jc{constructor(t,i){typeof t=="string"&&(t=jc.parseAttrList(t,i)),se(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>t.substring(0,2)==="X-")}decimalInteger(t){const i=parseInt(this[t],10);return i>Number.MAX_SAFE_INTEGER?1/0:i}hexadecimalInteger(t){if(this[t]){let i=(this[t]||"0x").slice(2);i=(i.length&1?"0":"")+i;const s=new Uint8Array(i.length/2);for(let r=0;r<i.length/2;r++)s[r]=parseInt(i.slice(r*2,r*2+2),16);return s}return null}hexadecimalIntegerAsNumber(t){const i=parseInt(this[t],16);return i>Number.MAX_SAFE_INTEGER?1/0:i}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,i){const s=this[t];return s?parseFloat(s):i}enumeratedString(t){return this[t]}enumeratedStringList(t,i){const s=this[t];return(s?s.split(/[ ,]+/):[]).reduce((r,n)=>(r[n.toLowerCase()]=!0,r),i)}bool(t){return this[t]==="YES"}decimalResolution(t){const i=Ql.exec(this[t]);if(i!==null)return{width:parseInt(i[1],10),height:parseInt(i[2],10)}}static parseAttrList(t,i){let s;const r={};for(Vr.lastIndex=0;(s=Vr.exec(t))!==null;){const a=s[1].trim();let o=s[2];const l=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1;let d=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(i&&(l||d))o=qs(i,o);else if(!d&&!l)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":te.warn(`${t}: attribute ${a} is missing quotes`)}r[a]=o}return r}},Zl="com.apple.hls.interstitial",Zi=class{constructor(e,t,i=0){var s;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(s=t?.tagOrder)!=null?s:i,t){const r=t.attr;for(const n in r)if(Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==r[n]){te.warn(`DATERANGE tag attribute: "${n}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=n;break}e=se(new oe({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const r=t?.endDate||new Date(this.attr["END-DATE"]);N(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(te.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(N(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===Zl}get isValid(){return!!this.id&&!this._badValueForSameId&&N(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}},Jl=10,Kr=class{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?N(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Jl}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}},Qt=typeof self<"u"?self:void 0,ae={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},fe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"},Ji=(function(e){return Qt!=null&&(e=Qt.navigator)!=null&&e.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})(),ut={},wt=class ys{static clearKeyUriToKeyIdMap(){ut={}}static setKeyIdForUri(t,i){ut[t]=i}static addKeyIdForUri(t){const i=Object.keys(ut).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,i),ut[t]=s,s}constructor(t,i,s,r=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=i,this.keyFormat=s,this.keyFormatVersions=r,this.iv=n,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!bt(t),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(xa(a)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&xi(t.keyFormatVersions,this.keyFormatVersions)&&uo(t.iv,this.iv)&&uo(t.keyId,this.keyId)}isSupported(){if(this.method){if(bt(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case fe.FAIRPLAY:case fe.WIDEVINE:case fe.PLAYREADY:case fe.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(t,i){if(!this.encrypted||!this.uri)return null;if(bt(this.method)){let n=this.iv;return n||(typeof t!="number"&&(te.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),n=Gu(t)),new ys(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){const n=ut[this.uri];if(n&&!xi(this.keyId,n)&&ys.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=go(this.uri);if(s)switch(this.keyFormat){case fe.WIDEVINE:if(this.pssh=s,!this.keyId){const n=au(s.buffer);if(n.length){var r;const a=n[0];this.keyId=(r=a.kids)!=null&&r.length?a.kids[0]:null}}this.keyId||(this.keyId=po(i));break;case fe.PLAYREADY:{const n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=nu(n,null,s),this.keyId=mo(s);break}default:{let n=s.subarray(0,16);if(n.length!==16){const a=new Uint8Array(16);a.set(n,16-n.length),n=a}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n;n=$u(i),n||(n=po(i),n||(n=ut[this.uri])),n&&(this.keyId=n,ys.setKeyIdForUri(this.uri,n))}return this}},Hr=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Wr=/#EXT-X-MEDIA:(.*)/g,ed=/^#EXT(?:INF|-X-TARGETDURATION):/m,es=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),td=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),ft=class fi{static findGroup(t,i){for(let s=0;s<t.length;s++){const r=t[s];if(r.id===i)return r}}static resolve(t,i){return ji.buildAbsoluteURL(i,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return ed.test(t)}static parseMasterPlaylist(t,i){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:co(t)},r=[];if(Hr.lastIndex=0,!t.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let n;for(;(n=Hr.exec(t))!=null;)if(n[1]){var a;const o=new oe(n[1],s),l=qs(s,n[2]),d={attrs:o,bitrate:o.decimalInteger("BANDWIDTH")||o.decimalInteger("AVERAGE-BANDWIDTH"),name:o.NAME,url:fi.resolve(l,i)},c=o.decimalResolution("RESOLUTION");c&&(d.width=c.width,d.height=c.height),To(o.CODECS,d);const h=o["SUPPLEMENTAL-CODECS"];h&&(d.supplemental={},To(h,d.supplemental)),(a=d.unknownCodecs)!=null&&a.length||r.push(d),s.levels.push(d)}else if(n[3]){const o=n[3],l=n[4];switch(o){case"SESSION-DATA":{const d=new oe(l,s),c=d["DATA-ID"];c&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[c]=d);break}case"SESSION-KEY":{const d=vo(l,i,s);d.encrypted&&d.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(d)):te.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${l}"`);break}case"DEFINE":ho(s,new oe(l,s),i);break;case"CONTENT-STEERING":{const d=new oe(l,s);s.contentSteering={uri:fi.resolve(d["SERVER-URI"],i),pathwayId:d["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=Eo(l);break}}return s.levels=r.length>0&&r.length<s.levels.length?r:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,i,s){let r;const n={},a=s.levels,o={AUDIO:a.map(d=>({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:a.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Wr.lastIndex=0;(r=Wr.exec(t))!==null;){const d=new oe(r[1],s),c=d.TYPE;if(c){const h=o[c],u=n[c]||[];n[c]=u;const f=d.LANGUAGE,m=d["ASSOC-LANGUAGE"],g=d.CHANNELS,y=d.CHARACTERISTICS,v=d["INSTREAM-ID"],E={attrs:d,bitrate:0,id:l++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:c,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?fi.resolve(d.URI,i):""};if(m&&(E.assocLang=m),g&&(E.channels=g),y&&(E.characteristics=y),v&&(E.instreamId=v),h!=null&&h.length){const T=fi.findGroup(h,E.groupId)||h[0];So(E,T,"audioCodec"),So(E,T,"textCodec")}u.push(E)}}return n}static parseLevelPlaylist(t,i,s,r,n,a){var o;const l={url:i},d=new Kr(i),c=d.fragments,h=[];let u=null,f=0,m=0,g=0,y=0,v=0,E=null,T=new zt(r,l),S,A,b,I=-1,D=!1,P=null,w;if(es.lastIndex=0,d.m3u8=t,d.hasVariableRefs=co(t),((o=es.exec(t))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(S=es.exec(t))!==null;){D&&(D=!1,T=new zt(r,l),T.playlistOffset=g,T.setStart(g),T.sn=f,T.cc=y,v&&(T.bitrate=v),T.level=s,u&&(T.initSegment=u,u.rawProgramDateTime&&(T.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null),P&&(T.setByteRange(P),P=null)));const V=S[1];if(V){T.duration=parseFloat(V);const F=(" "+S[2]).slice(1);T.title=F||null,T.tagList.push(F?["INF",V,F]:["INF",V])}else if(S[3]){if(N(T.duration)){T.playlistOffset=g,T.setStart(g),b&&Io(T,b,d),T.sn=f,T.level=s,T.cc=y,c.push(T);const F=(" "+S[3]).slice(1);T.relurl=qs(d,F),er(T,E,h),E=T,g+=T.duration,f++,m=0,D=!0}}else{if(S=S[0].match(td),!S){te.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A<S.length&&S[A]===void 0;A++);const F=(" "+S[A]).slice(1),M=(" "+S[A+1]).slice(1),W=S[A+2]?(" "+S[A+2]).slice(1):null;switch(F){case"BYTERANGE":E?T.setByteRange(M,E):T.setByteRange(M);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=M,T.tagList.push(["PROGRAM-DATE-TIME",M]),I===-1&&(I=c.length);break;case"PLAYLIST-TYPE":d.type&&ze(d,F,S),d.type=M.toUpperCase();break;case"MEDIA-SEQUENCE":d.startSN!==0?ze(d,F,S):c.length>0&&Ao(d,F,S),f=d.startSN=parseInt(M);break;case"SKIP":{d.skippedSegments&&ze(d,F,S);const k=new oe(M,d),C=k.decimalInteger("SKIPPED-SEGMENTS");if(N(C)){d.skippedSegments+=C;for(let j=C;j--;)c.push(null);f+=C}const G=k.enumeratedString("RECENTLY-REMOVED-DATERANGES");G&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(G.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&ze(d,F,S),d.targetduration=Math.max(parseInt(M),1);break;case"VERSION":d.version!==null&&ze(d,F,S),d.version=parseInt(M);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||ze(d,F,S),d.live=!1;break;case"#":(M||W)&&T.tagList.push(W?[M,W]:[M]);break;case"DISCONTINUITY":y++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([F]);break;case"BITRATE":T.tagList.push([F,M]),v=parseInt(M)*1e3,N(v)?T.bitrate=v:v=0;break;case"DATERANGE":{const k=new oe(M,d),C=new Zi(k,d.dateRanges[k.ID],d.dateRangeTagCount);d.dateRangeTagCount++,C.isValid||d.skippedSegments?d.dateRanges[C.id]=C:te.warn(`Ignoring invalid DATERANGE tag: "${M}"`),T.tagList.push(["EXT-X-DATERANGE",M]);break}case"DEFINE":{const k=new oe(M,d);"IMPORT"in k?xu(d,k,a):ho(d,k,i)}break;case"DISCONTINUITY-SEQUENCE":d.startCC!==0?ze(d,F,S):c.length>0&&Ao(d,F,S),d.startCC=y=parseInt(M);break;case"KEY":{const k=vo(M,i,d);if(k.isSupported()){if(k.method==="NONE"){b=void 0;break}b||(b={});const C=b[k.keyFormat];C!=null&&C.matches(k)||(C&&(b=se({},b)),b[k.keyFormat]=k)}else te.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${M}"`);break}case"START":d.startTimeOffset=Eo(M);break;case"MAP":{const k=new oe(M,d);if(T.duration){const C=new zt(r,l);bo(C,k,s,b),u=C,T.initSegment=u,u.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=u.rawProgramDateTime)}else{const C=T.byteRangeEndOffset;if(C){const G=T.byteRangeStartOffset;P=`${C-G}@${G}`}else P=null;bo(T,k,s,b),u=T,D=!0}u.cc=y;break}case"SERVER-CONTROL":w&&ze(d,F,S),w=new oe(M),d.canBlockReload=w.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=w.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&w.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=w.optionalFloat("PART-HOLD-BACK",0),d.holdBack=w.optionalFloat("HOLD-BACK",0);break;case"PART-INF":d.partTarget&&ze(d,F,S),d.partTarget=new oe(M).decimalFloatingPoint("PART-TARGET");break;case"PART":{let k=d.partList;k||(k=d.partList=[]);const C=m>0?k[k.length-1]:void 0,G=m++,j=new _r(new oe(M,d),T,l,G,C);k.push(j),T.duration+=j.duration;break}case"PRELOAD-HINT":d.preloadHint=new oe(M,d);break;case"RENDITION-REPORT":{const k=new oe(M,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(k);break}default:te.warn(`line parsed but not handled: ${S}`);break}}}E&&!E.relurl?(c.pop(),g-=E.duration,d.partList&&(d.fragmentHint=E)):d.partList&&(er(T,E,h),T.cc=y,d.fragmentHint=T,b&&Io(T,b,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const x=c.length,U=c[0],O=c[x-1];if(g+=d.skippedSegments*d.targetduration,g>0&&x&&O){d.averagetargetduration=g/x;const V=O.sn;d.endSN=V!=="initSegment"?V:0,d.live||(O.endList=!0),I>0&&(Ku(c,I),U&&h.unshift(U))}return d.fragmentHint&&(g+=d.fragmentHint.duration),d.totalduration=g,h.length&&d.dateRangeTagCount&&U&&yo(h,d),d.endCC=y,d}},id={toString:function(e){let t="";const i=e.length;for(let s=0;s<i;s++)t+=`[${e.start(s).toFixed(3)}-${e.end(s).toFixed(3)}]`;return t}},_={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},Zt=class extends Br{constructor(e,t,i,s,r){super(s,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=_.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:n,fragCurrent:a,media:o,mediaBuffer:l,state:d}=this,c=o?o.currentTime:0,h=Y.bufferInfo(l||o,c,n.maxBufferHole),u=!h.len;if(this.log(`Media seeking to ${N(c)?c.toFixed(3):c}, state: ${d}, ${u?"out of":"in"} buffer`),this.state===_.ENDED)this.resetLoadingState();else if(a){const f=n.maxFragLookUpTolerance,m=a.start-f,g=a.start+a.duration+f;if(u||g<h.start||m>h.end){const y=c>g;(c<m||y)&&(y&&a.loader&&(this.log(`Cancelling fragment load for seek (sn: ${a.sn})`),a.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(o&&(this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0),c>this.lastCurrentTime&&(this.lastCurrentTime=c),!this.loadingParts)){const f=Math.max(h.end,c),m=this.shouldLoadParts(this.getLevelDetails(),f);m&&(this.log(`LL-Part loading ON after seeking to ${c.toFixed(2)} with buffer @${f.toFixed(2)}`),this.loadingParts=m)}this.hls.hasEnoughToStart||(this.log(`Setting ${u?"startPosition":"nextLoadPosition"} to ${c} for seek without enough to start`),this.nextLoadPosition=c,u&&(this.startPosition=c)),u&&this.state===_.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new Xl(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Qi(e.config)}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===_.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=_.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=Y.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>s&&n<t.edge||this.media.currentTime<e.start)return!1;const a=t.partList;if(a!=null&&a.length){const l=a[a.length-1];return Y.isBuffered(this.media,l.start+l.duration/2)}const o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;Ee(i,"seeking",this.onMediaSeeking),Ee(i,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===_.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(e,t){const i=!!t.transferMedia,s=this.media;if(s!==null){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Le(s,"seeking",this.onMediaSeeking),Le(s,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=_.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const s=r=>{const n=r.frag;if(this.fragContextChanged(n)){this.warn(`${n.type} sn: ${n.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(n,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(n);return}n.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,i,s).then(r=>{if(!r)return;const n=this.state,a=r.frag;if(this.fragContextChanged(a)){(n===_.FRAG_LOADING||!this.fragCurrent&&n===_.PARSING)&&(this.fragmentTracker.removeFragment(a),this.state=_.IDLE);return}"payload"in r&&(this.log(`Loaded ${a.type} sn: ${a.sn} of ${this.playlistLabel()} ${a.level}`),this.hls.trigger(p.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===_.STOPPED||this.state===_.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===he.APPENDING){const s=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,s),n=Math.max(e.duration,r?r.len:this.config.maxBufferLength),a=this.backtrackFragment;((a?e.sn-a.sn:0)===1||this.reduceMaxBufferLength(n,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===he.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const s={startOffset:e,endOffset:t,type:i};this.hls.trigger(p.BUFFER_FLUSHING,s)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{const s=i?.frag;if(!s||this.fragContextChanged(s)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:s}=this,{frag:r,payload:n}=i,a=r.decryptdata;if(n&&n.byteLength>0&&a!=null&&a.key&&a.iv&&bt(a.method)){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,Xs(a.method)).catch(l=>{throw s.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:r}),l}).then(l=>{const d=self.performance.now();return s.trigger(p.FRAG_DECRYPTED,{frag:r,payload:l,stats:{tstart:o,tdecrypt:d}}),i.payload=l,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===_.STOPPED||this.state===_.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state!==_.STOPPED&&(this.state=_.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var i,s;const r=e.tracks;if(r&&!t.encrypted&&((i=r.audio)!=null&&i.encrypted||(s=r.video)!=null&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const n=this.media,a=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${n?"attached mediaKeys: "+n.mediaKeys:"detached"})`);return this.warn(a.message),!n||n.mediaKeys?!1:(this.hls.trigger(p.ERROR,{type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_KEYS,fatal:!1,error:a,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?id.toString(Y.getBuffered(i)):"(detached)"})`),de(e)){var s;if(e.type!==B.SUBTITLE){const n=e.elementaryStreams;if(!Object.keys(n).some(a=>!!n[a])){this.state=_.IDLE;return}}const r=(s=this.levels)==null?void 0:s[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=_.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:s,partsLoaded:r}=e,n=!r||r.length===0||r.some(o=>!o),a=new Xt(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,s){var r;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=_.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(p.KEY_LOADED,h),this.state===_.KEY_LOADING&&(this.state=_.IDLE),h}),this.hls.trigger(p.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(a=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));const o=this.fragPrevious;if(de(e)&&(!o||e.sn!==o.sn)){const h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${o?.sn}->${e.sn}`),this.loadingParts=h)}if(i=Math.max(e.start,i||0),this.loadingParts&&de(e)){const h=n.partList;if(h&&s){i>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const u=this.getNextPart(h,e,i);if(u>-1){const f=h[u];e=this.fragCurrent=f.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${f.index} (${u}/${h.length-1}) of ${this.fragInfo(e,!1,f)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=f.start+f.duration,this.state=_.FRAG_LOADING;let m;return a?m=a.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,f,t,s)).catch(g=>this.handleFragLoadError(g)):m=this.doFragPartsLoad(e,f,t,s).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(p.FRAG_LOADING,{frag:e,part:f,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):m}else if(!e.url||this.loadedEndOfParts(h,i))return Promise.resolve(null)}}if(de(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=n.partList)==null?void 0:l.filter(h=>h.loaded).map(h=>`[${h.start}-${h.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),N(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=_.FRAG_LOADING;const d=this.config.progressive&&e.type!==B.SUBTITLE;let c;return d&&a?c=a.then(h=>!h||this.fragContextChanged(h.frag)?null:this.fragmentLoader.load(e,s)).catch(h=>this.handleFragLoadError(h)):c=Promise.all([this.fragmentLoader.load(e,d?s:void 0),a]).then(([h])=>(!d&&s&&s(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(p.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,i,s){return new Promise((r,n)=>{var a;const o=[],l=(a=i.details)==null?void 0:a.partList,d=c=>{this.fragmentLoader.loadPart(e,c,s).then(h=>{o[c.index]=h;const u=h.part;this.hls.trigger(p.FRAG_LOADED,h);const f=_o(i.details,e.sn,c.index+1)||ko(l,e.sn,c.index+1);if(f)d(f);else return r({frag:e,part:u,partsLoaded:o})}).catch(n)};d(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===L.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===$.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(p.ERROR,t)}else this.hls.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==_.PARSING){!this.fragCurrent&&this.state!==_.STOPPED&&this.state!==_.ERROR&&(this.state=_.IDLE);return}const{frag:i,part:s,level:r}=t,n=self.performance.now();i.stats.parsing.end=n,s&&(s.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(i,s,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i;const r=e.partList[0];if(r.fragment.type===B.SUBTITLE)return!1;if(t>=r.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0)){var s;if((this.hls.hasEnoughToStart?((s=this.media)==null?void 0:s.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:s,sn:r,part:n}=e;if(!(t!=null&&t[s]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const a=t[s],o=a.details,l=n>-1?_o(o,r,n):null,d=l?l.fragment:Po(o,r,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(e,t,i,s,r){if(this.state!==_.PARSING)return;const{data1:n,data2:a}=e;let o=n;if(a&&(o=Ce(n,a)),!o.length)return;const l=this.initPTS[t.cc],d=l?-l.baseTime/l.timescale:void 0,c={type:e.type,frag:t,part:i,chunkMeta:s,offset:d,parent:t.type,data:o};if(this.hls.trigger(p.BUFFER_APPENDING,c),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Y.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,s=Y.bufferInfo(t,i,0),r=e.duration,n=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),a=Math.max(Math.min(e.start-n,s.end-n),i+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var i;const s=this.getLoadPosition();if(!N(s))return null;const r=this.lastCurrentTime>s||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,r)}getFwdBufferInfoAtPos(e,t,i,s){const r=Y.bufferInfo(e,t,s);if(r.len===0&&r.nextStart!==void 0){const n=this.fragmentTracker.getBufferedFrag(t,i);if(n&&(r.nextStart<=n.end||n.gap)){const a=Math.max(Math.min(r.nextStart,n.end)-t,s);return Y.bufferInfo(e,t,a)}}return r}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,i){const s=e.nextStart;if(s&&i.start>s){const r=e.buffered;if(r){let n=e.len;const a=e.bufferedIndex;for(let o=r.length-1;o>a;o--)r[o].start<i.start&&(n+=r[o].end-r[o].start);return n>=t}}return!1}reduceMaxBufferLength(e,t){const i=this.config,s=Math.max(Math.min(e-t,i.maxBufferLength),t),r=Math.max(e-t*3,i.maxMaxBufferLength/2,s);return r>=s?(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=B.MAIN){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,s=i.length;if(!s)return null;const{config:r}=this,n=t.fragmentStart,a=r.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const c=r.initialLiveManifestSize;if(s<c)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${c})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);const h=this.config.startPosition,u=this.hls.startPosition,f=this.hls.liveSyncPosition,m=((l=o)==null?void 0:l.start)||0;let g,y;u!==-1&&u>=n?(g=u,y=u===h?"config":"next load start"):f!==null?(g=f,y="live edge"):(g=e,y="buffer pos"),g<m&&(g=m,y="live frag start"),g<n&&(g=n,y="playlist start"),(this.startPosition!=g||this.nextLoadPosition!=g)&&(this.log(`Setting startPosition to ${g.toFixed(3)} ${u===-1?"":`(from ${h}) `}based on ${y}. live edge: ${f} live frag start: ${m.toFixed(3)} playlist start: ${n.toFixed(3)} buffer pos: ${e}`),this.startPosition=this.nextLoadPosition=g)}}else e<=n&&(o=i[0]);if(!o){const c=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,c,t)}let d=this.filterReplacedPrimary(o,t);if(!d&&o){const c=o.sn-t.startSN;d=this.filterReplacedPrimary(i[c+1]||null,t)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;const i=this.fragmentTracker.getState(e);return i===he.OK||i===he.PARTIAL&&!!e.gap}getNextFragmentLoopLoading(e,t,i,s,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&i.nextStart)){const a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(a!==null&&i.len+a.len>=r){const o=n.sn;return this.loopSn!==o&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${o}`),this.loopSn=o),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(No(this.config)){var e;if(!((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null)&&e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(No(this.config)&&e.type!==B.SUBTITLE){const i=this.hls.interstitialsManager,s=i?.bufferingItem;if(s){const n=s.event;if(n){if(n.appendInPlace||Math.abs(e.start-s.start)>1||s.start===0)return null}else if(e.end<=s.start&&t?.live===!1||e.start>s.end&&s.nextEvent&&(s.nextEvent.appendInPlace||e.start-s.end>1))return null}const r=i?.playerQueue;if(r)for(let n=r.length;n--;){const a=r[n].interstitial;if(a.appendInPlace&&e.start>=a.startTime&&e.end<=a.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let s=-1,r=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const l=e[a];if(n=n&&!l.independent,s>-1&&i<l.start)break;const d=l.loaded;d?s=-1:(r||(l.independent||n)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${l.start}`),s=a),r=d}return s}loadedEndOfParts(e,t){let i;for(let s=e.length;s--;){if(i=e[s],!i.loaded)return!1;if(t>i.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,i=this.fragPrevious;let s=null;if(i){if(e.hasProgramDateTime&&(s=Ru(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance),s&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`)),!s){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];i.cc===n.cc&&(s=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=to(e,i.cc,i.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(s=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){const{config:s}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=s,d=i.partList,c=!!(this.loadingParts&&d!=null&&d.length&&o);c&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn);let h;if(e<t){var u;const f=e<this.lastCurrentTime||e>t-l||(u=this.media)!=null&&u.paused||!this.startFragRequested?0:l;h=lt(r,n,e,f)}else h=n[n.length-1];if(h){const f=h.sn-i.startSN,m=this.fragmentTracker.getState(h);if((m===he.OK||m===he.PARTIAL&&h.gap)&&(r=h),r&&h.sn===r.sn&&(!c||d[0].fragment.sn>h.sn||!i.live)&&h.level===r.level){const g=n[f+1];h.sn<a&&this.fragmentTracker.getState(g)!==he.OK?h=g:h=null}}return h}alignPlaylists(e,t,i){const s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,a=e.alignedSliding&&N(r);if(n||!a&&!r){Xu(i,e);const o=e.fragmentStart;return this.log(`Live playlist sliding: ${o.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${s}`),o}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);const s=this.timelineOffset;if(i===-1){const r=this.startTimeOffset!==null,n=r?this.startTimeOffset:e.startTimeOffset;n!==null&&N(n)?(i=t+n,n<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+s}this.nextLoadPosition=i+s}getLoadPosition(){var e;const{media:t}=this;let i=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&de(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==_.FRAG_LOADING_WAITING_RETRY)&&(this.state=_.IDLE)}onFragmentOrKeyLoadError(e,t){var i;if(t.chunkMeta&&!t.frag){const y=this.getCurrentContext(t.chunkMeta);y&&(t.frag=y.frag)}const s=t.frag;if(!s||s.type!==e||!this.levels)return;if(this.fragContextChanged(s)){var r;this.warn(`Frag load error must match current frag to retry ${s.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const n=t.details===L.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(s,!0);const a=t.errorAction;if(!a){this.state=_.ERROR;return}const{action:o,flags:l,retryCount:d=0,retryConfig:c}=a,h=!!c,u=h&&o===ce.RetryRequest,f=h&&!a.resolved&&l===Te.MoveAllAlternatesMatchingHost,m=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!u&&f&&de(s)&&!s.endList&&m&&!so(t))this.resetFragmentErrors(e),this.treatAsGap(s),a.resolved=!0;else if((u||f)&&d<c.maxNumRetry){var g;const y=zs((g=t.response)==null?void 0:g.code),v=Ys(c,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+v,this.state=_.FRAG_LOADING_WAITING_RETRY,a.resolved=!0,y){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${d+1}/${c.maxNumRetry} in ${v}ms`)}else if(c)if(this.resetFragmentErrors(e),d<c.maxNumRetry)!n&&o!==ce.RemoveAlternatePermanently&&(a.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${d})`);return}else o===ce.SendAlternateToPenaltyBox?this.state=_.WAITING_LEVEL:this.state=_.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!zs(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=_.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===_.PARSING||this.state===_.PARSED){const t=e.frag,i=e.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len,t?.duration||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===B.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==_.STOPPED&&(this.state=_.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const s=Y.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,i),this.state===_.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==_.STOPPED&&(this.state=_.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){const r=i.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((a,o)=>{const l=e.elementaryStreams[o];if(l){const d=l.endPTS-l.startPTS;if(d<=0)return this.warn(`Could not parse fragment ${e.sn} ${o} duration reliably (${d})`),a||!1;const c=s?0:Lo(r,e,l.startPTS,l.endPTS,l.startDTS,l.endDTS,this);return this.hls.trigger(p.LEVEL_PTS_UPDATED,{details:r,level:i,drift:c,type:o,frag:e,start:l.startPTS,end:l.endPTS}),!0}return a},!1)){var n;const a=((n=this.transmuxer)==null?void 0:n.error)===null;if((i.fragmentError===0||a&&(i.fragmentError<2||e.endList))&&this.treatAsGap(e,i),a){const o=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(o.message),this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=_.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(p.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===B.MAIN?"level":"track"}fragInfo(e,t=!0,i){var s,r;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((s=t&&!i?e.startPTS:(i||e).start)!=null?s:NaN).toFixed(3)}-${((r=t&&!i?e.endPTS:(i||e).end)!=null?r:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}},jr=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=Qu(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}},ts={exports:{}},is=Wh(Zu()),Pt="1.6.16",gt={},Jt=10,rd=10,Se=(function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e})({}),ss=class{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=Ce(this.cachedData,e),this.cachedData=null);let i=Vt(e,0),s=i?i.length:0,r;const n=this._audioTrack,a=this._id3Track,o=i?ar(i):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&N(o))&&(this.basePTS=nd(o,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Se.audioId3,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(e,s)){const d=this.appendFrame(n,e,s);d?(this.frameIndex++,this.lastPTS=d.sample.pts,s+=d.length,r=s):s=l}else df(e,s)?(i=Vt(e,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Se.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,r=s):s++;if(s===l&&r!==l){const d=e.slice(r);this.cachedData?this.cachedData=Ce(this.cachedData,d):this.cachedData=d}}return{audioTrack:n,videoTrack:$e(),id3Track:a,textTrack:$e()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:$e(),id3Track:this._id3Track,textTrack:$e()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},nd=(e,t,i)=>{if(N(e))return e*90;const s=i?i.baseTime*9e4/i.timescale:0;return t*9e4+s},ei=null,ad=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],od=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ld=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],dd=[0,1,1,4],cd=class extends ss{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const i=Vt(e,0);let s=i?.length||0;if(qo(e,s))return!1;for(let r=e.length;s<r;s++)if(of(e,s))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return af(e,t)}appendFrame(e,t,i){Go(e,this.observer,t,i,e.manifestCodec);const s=Ko(e,t,i,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}},Yr=(e,t)=>{let i=0,s=5;t+=s;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=e[t];const o=Math.min(s,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,i=i?i<<o|r[0]:r[0],t+=1,s-=o}return i},hd=class extends ss{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){const s=Xo(e,t,i,this.basePTS,this.frameIndex);if(s!==-1)return{sample:e.samples[e.samples.length-1],length:s,missing:0}}static probe(e){if(!e)return!1;const t=Vt(e,0);if(!t)return!1;const i=t.length;return e[i]===11&&e[i+1]===119&&ar(t)!==void 0&&Yr(e,i)<16}},ud=class extends ss{resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Vt(e,0);let i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&ar(t)!==void 0&&Yr(e,i)<=16)return!1;for(let s=e.length;i<s;i++)if(qo(e,i))return te.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Sf(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return jo(e,t,i,this.basePTS,this.frameIndex)}},fd=/\/emsg[-/]ID3/i,gd=class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,s){const r=this.videoTrack=$e("video",1),n=this.audioTrack=$e("audio",1),a=this.txtTrack=$e("text",1);if(this.id3Track=$e("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const o=Ua(e);if(o.video){const{id:l,timescale:d,codec:c,supplemental:h}=o.video;r.id=l,r.timescale=a.timescale=d,r.codec=c,r.supplemental=h}if(o.audio){const{id:l,timescale:d,codec:c}=o.audio;n.id=l,n.timescale=d,n.codec=c}a.id=Cr.text,r.sampleDuration=0,r.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return zh(e)}demux(e,t){this.timeOffset=t;let i=e;const s=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Ce(this.remainderData,e));const a=tu(i);this.remainderData=a.remainder,s.samples=a.valid||new Uint8Array}else s.samples=i;const n=this.extractID3Track(s,t);return r.samples=Ga(t,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(t,this.timeOffset);return i.samples=Ga(e,t),{videoTrack:t,audioTrack:$e(),id3Track:s,textTrack:$e()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const s=z(e.samples,["emsg"]);s&&s.forEach(r=>{const n=su(r);if(fd.test(n.schemeIdUri)){const a=Qo(n,t);let o=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;o<=.001&&(o=Number.POSITIVE_INFINITY);const l=n.payload;i.samples.push({data:l,len:l.byteLength,dts:a,pts:a,type:Se.emsg,duration:o})}else if(this.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const a=Qo(n,t);i.samples.push({data:n.payload,len:n.payload.byteLength,dts:a,pts:a,type:Se.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},md=class{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Qi(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Xe.cbc)}decryptAacSample(e,t,i){const s=e[t].unit;if(s.length<=16)return;const r=s.subarray(16,s.length-s.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(a=>{const o=new Uint8Array(a);s.set(o,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let s=0;for(let r=32;r<e.length-16;r+=160,s+=16)i.set(e.subarray(r,r+16),s);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let s=0;for(let r=32;r<e.length-16;r+=160,s+=16)e.set(i.subarray(s,s+16),r);return e}decryptAvcSample(e,t,i,s,r){const n=Va(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(o=>{r.data=this.getAvcDecryptedUnit(n,o),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,s)}).catch(s)}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){s();return}const r=e[t].units;for(;!(i>=r.length);i++){const n=r[i];if(!(n.data.length<=48||n.type!==1&&n.type!==5)&&(this.decryptAvcSample(e,t,i,s,n),!this.decrypter.isSync()))return}}}},zr=class{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,s;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const r=i.units;s=r[r.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,s=i.length;if(s){const r=i[s-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){const s=t.byteLength;let r=e.naluState||0;const n=r,a=[];let o=0,l,d,c,h=-1,u=0;for(r===-1&&(h=0,u=this.getNALuType(t,0),r=0,o=1);o<s;){if(l=t[o++],!r){r=l?0:1;continue}if(r===1){r=l?0:2;continue}if(!l)r=3;else if(l===1){if(d=o-r-1,h>=0){const f={data:t.subarray(h,d),type:u};a.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(n&&o<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),d>0&&(f.data=Ce(f.data,t.subarray(0,d)),f.state=0))}o<s?(c=this.getNALuType(t,o),h=o,u=c,r=0):r=-1}else r=0}if(h>=0&&r>=0){const f={data:t.subarray(h,s),type:u,state:r};a.push(f)}if(a.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=Ce(f.data,t))}return e.naluState=r,a}},_t=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,s=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");s.set(e.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&te.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}},pd=class extends zr{parsePES(e,t,i,s){const r=this.parseNALu(e,i.data,s);let n=this.VideoSample,a,o=!1;i.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(l=>{var d,c;switch(l.type){case 1:{let m=!1;a=!0;const g=l.data;if(o&&g.length>4){const y=this.readSliceType(g);(y===2||y===4||y===7||y===9)&&(m=!0)}if(m){var h;(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.frame=!0,n.key=m;break}case 5:a=!0,(d=n)!=null&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.key=!0,n.frame=!0;break;case 6:a=!0,Ks(l.data,1,i.pts,t.samples);break;case 7:{var u,f;a=!0,o=!0;const m=l.data,g=this.readSPS(m);if(!e.sps||e.width!==g.width||e.height!==g.height||((u=e.pixelRatio)==null?void 0:u[0])!==g.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==g.pixelRatio[1]){e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.sps=[m];const y=m.subarray(1,4);let v="avc1.";for(let E=0;E<3;E++){let T=y[E].toString(16);T.length<2&&(T="0"+T),v+=T}e.codec=v}break}case 8:a=!0,e.pps=[l.data];break;case 9:a=!0,e.audFound=!0,(c=n)!=null&&c.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:a=!0;break;default:a=!1;break}n&&a&&n.units.push(l)}),s&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new _t(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,s=8,r;for(let n=0;n<e;n++)s!==0&&(r=t.readEG(),s=(i+r+256)%256),i=s===0?i:s}readSPS(e){const t=new _t(e);let i=0,s=0,r=0,n=0,a,o,l;const d=t.readUByte.bind(t),c=t.readBits.bind(t),h=t.readUEG.bind(t),u=t.readBoolean.bind(t),f=t.skipBits.bind(t),m=t.skipEG.bind(t),g=t.skipUEG.bind(t),y=this.skipScalingList.bind(this);d();const v=d();if(c(5),f(3),d(),g(),v===100||v===110||v===122||v===244||v===44||v===83||v===86||v===118||v===128){const I=h();if(I===3&&f(1),g(),g(),f(1),u())for(o=I!==3?8:12,l=0;l<o;l++)u()&&(l<6?y(16,t):y(64,t))}g();const E=h();if(E===0)h();else if(E===1)for(f(1),m(),m(),a=h(),l=0;l<a;l++)m();g(),f(1);const T=h(),S=h(),A=c(1);A===0&&f(1),f(1),u()&&(i=h(),s=h(),r=h(),n=h());let b=[1,1];if(u()&&u())switch(d()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:b=[d()<<8|d(),d()<<8|d()];break}return{width:Math.ceil((T+1)*16-i*2-s*2),height:(2-A)*(S+1)*16-(A?2:4)*(r+n),pixelRatio:b}}},yd=class extends zr{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,s){const r=this.parseNALu(e,i.data,s);let n=this.VideoSample,a,o=!1;i.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(l=>{var d,c;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:n||(n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),n.frame=!0,a=!0;break;case 16:case 17:case 18:case 21:if(a=!0,o){var h;(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.key=!0,n.frame=!0;break;case 19:case 20:a=!0,(d=n)!=null&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.key=!0,n.frame=!0;break;case 39:a=!0,Ks(l.data,2,i.pts,t.samples);break;case 32:a=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=se(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(a=!0,o=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const u=this.readSPS(l.data);e.width=u.width,e.height=u.height,e.pixelRatio=u.pixelRatio,e.codec=u.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const f in u.params)e.params[f]=u.params[f]}this.pushParameterSet(e.sps,l.data,e.vps),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.key=!0;break;case 34:if(a=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const u=this.readPPS(l.data);for(const f in u)e.params[f]=u[f]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:a=!0,e.audFound=!0,(c=n)!=null&&c.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:a=!1;break}n&&a&&n.units.push(l)}),s&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let s=0;s<e.byteLength;s++)s>=2&&e[s]===3&&e[s-1]===0&&e[s-2]===0||(t[i]=e[s],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new _t(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const i=t.readBits(3),s=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:s}}readSPS(e){const t=new _t(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const s=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),d=t.readUByte(),c=t.readUByte(),h=t.readUByte(),u=t.readUByte(),f=t.readUByte(),m=t.readUByte(),g=t.readUByte(),y=t.readUByte(),v=[],E=[];for(let H=0;H<i;H++)v.push(t.readBoolean()),E.push(t.readBoolean());if(i>0)for(let H=i;H<8;H++)t.readBits(2);for(let H=0;H<i;H++)v[H]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),E[H]&&t.readUByte();t.readUEG();const T=t.readUEG();T==3&&t.skipBits(1);const S=t.readUEG(),A=t.readUEG(),b=t.readBoolean();let I=0,D=0,P=0,w=0;b&&(I+=t.readUEG(),D+=t.readUEG(),P+=t.readUEG(),w+=t.readUEG());const x=t.readUEG(),U=t.readUEG(),O=t.readUEG(),V=t.readBoolean();for(let H=V?0:i;H<=i;H++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let H=0;H<4;H++)for(let ve=0;ve<(H===3?2:6);ve++)if(!t.readBoolean())t.readUEG();else{const pe=Math.min(64,1<<4+(H<<1));H>1&&t.readEG();for(let Fe=0;Fe<pe;Fe++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const F=t.readUEG();let M=0;for(let H=0;H<F;H++){let ve=!1;if(H!==0&&(ve=t.readBoolean()),ve){H===F&&t.readUEG(),t.readBoolean(),t.readUEG();let pe=0;for(let Fe=0;Fe<=M;Fe++){const We=t.readBoolean();let hi=!1;We||(hi=t.readBoolean()),(We||hi)&&pe++}M=pe}else{const pe=t.readUEG(),Fe=t.readUEG();M=pe+Fe;for(let We=0;We<pe;We++)t.readUEG(),t.readBoolean();for(let We=0;We<Fe;We++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const H=t.readUEG();for(let ve=0;ve<H;ve++){for(let pe=0;pe<O+4;pe++)t.readBits(1);t.readBits(1)}}let W=0,k=1,C=1,G=!0,j=1,J=0;t.readBoolean(),t.readBoolean();let X=!1;if(t.readBoolean()){if(t.readBoolean()){const H=t.readUByte(),ve=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],pe=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];H>0&&H<16?(k=ve[H-1],C=pe[H-1]):H===255&&(k=t.readBits(16),C=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),X=t.readBoolean(),X&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(j=t.readBits(32),J=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const H=t.readBoolean(),ve=t.readBoolean();let pe=!1;(H||ve)&&(pe=t.readBoolean(),pe&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),pe&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Fe=0;Fe<=i;Fe++){G=t.readBoolean();const We=G||t.readBoolean();let hi=!1;We?t.readEG():hi=t.readBoolean();const Wc=hi?1:t.readUEG()+1;if(H)for(let ui=0;ui<Wc;ui++)t.readUEG(),t.readUEG(),pe&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(ve)for(let ui=0;ui<Wc;ui++)t.readUEG(),t.readUEG(),pe&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),W=t.readUEG())}let Q=S,Ie=A;if(b){let H=1,ve=1;T===1?H=ve=2:T==2&&(H=2),Q=S-H*D-H*I,Ie=A-ve*w-ve*P}const _e=s?["A","B","C"][s]:"",He=a<<24|o<<16|l<<8|d;let yt=0;for(let H=0;H<32;H++)yt=(yt|(He>>H&1)<<31-H)>>>0;let _n=yt.toString(16);return n===1&&_n==="2"&&(_n="6"),{codecString:`hvc1.${_e}${n}.${_n}.${r?"H":"L"}${y}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:s,general_profile_compatibility_flags:[a,o,l,d],general_constraint_indicator_flags:[c,h,u,f,m,g],general_level_idc:y,bit_depth:x+8,bit_depth_luma_minus8:x,bit_depth_chroma_minus8:U,min_spatial_segmentation_idc:W,chroma_format_idc:T,frame_rate:{fixed:G,fps:J/j}},width:Q,height:Ie,pixelRatio:[k,C]}}readPPS(e){const t=new _t(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const i=t.readBoolean(),s=t.readBoolean();let r=1;return s&&i?r=0:s?r=3:i&&(r=2),{parallelismType:r}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}},ge=188,vd=class vt{constructor(t,i,s,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=i,this.typeSupported=s,this.logger=r,this.videoParser=null}static probe(t,i){const s=vt.syncOffset(t);return s>0&&i.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(t){const i=t.length;let s=Math.min(ge*5,i-ge)+1,r=0;for(;r<s;){let n=!1,a=-1,o=0;for(let l=r;l<i;l+=ge)if(t[l]===71&&(i-l===ge||t[l+ge]===71)){if(o++,a===-1&&(a=l,a!==0&&(s=Math.min(a+ge*99,t.length-ge)+1)),n||(n=lr(t,l)===0),n&&o>1&&(a===0&&o>2||l+ge>s))return a}else{if(o)return-1;break}r++}return-1}static createTrack(t,i){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:Cr[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?i:void 0}}resetInitSegment(t,i,s,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=vt.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=vt.createTrack("audio",r),this._id3Track=vt.createTrack("id3"),this._txtTrack=vt.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=i,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:i,_id3Track:s}=this;t&&(t.pesData=null),i&&(i.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,i,s=!1,r=!1){s||(this.sampleAes=null);let n;const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,d=this._txtTrack;let c=a.pid,h=a.pesData,u=o.pid,f=l.pid,m=o.pesData,g=l.pesData,y=null,v=this.pmtParsed,E=this._pmtId,T=t.length;if(this.remainderData&&(t=Ce(this.remainderData,t),T=t.length,this.remainderData=null),T<ge&&!r)return this.remainderData=t,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};const S=Math.max(0,vt.syncOffset(t));T-=(T-S)%ge,T<t.byteLength&&!r&&(this.remainderData=new Uint8Array(t.buffer,T,t.buffer.byteLength-T));let A=0;for(let I=S;I<T;I+=ge)if(t[I]===71){const D=!!(t[I+1]&64),P=lr(t,I),w=(t[I+3]&48)>>4;let x;if(w>1){if(x=I+5+t[I+4],x===I+ge)continue}else x=I+4;switch(P){case c:D&&(h&&(n=It(h,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,d,n,!1)),h={data:[],size:0}),h&&(h.data.push(t.subarray(x,I+ge)),h.size+=I+ge-x);break;case u:if(D){if(m&&(n=It(m,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n);break}m={data:[],size:0}}m&&(m.data.push(t.subarray(x,I+ge)),m.size+=I+ge-x);break;case f:D&&(g&&(n=It(g,this.logger))&&this.parseID3PES(l,n),g={data:[],size:0}),g&&(g.data.push(t.subarray(x,I+ge)),g.size+=I+ge-x);break;case 0:D&&(x+=t[x]+1),E=this._pmtId=bf(t,x);break;case E:{D&&(x+=t[x]+1);const U=If(t,x,this.typeSupported,s,this.observer,this.logger);c=U.videoPid,c>0&&(a.pid=c,a.segmentCodec=U.segmentVideoCodec),u=U.audioPid,u>0&&(o.pid=u,o.segmentCodec=U.segmentAudioCodec),f=U.id3Pid,f>0&&(l.pid=f),y!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${I} after unknown PID '${y}'. Backtracking to sync byte @${S} to parse all TS packets.`),y=null,I=S-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=P;break}}else A++;A>0&&dr(this.observer,new Error(`Found ${A} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=h,o.pesData=m,l.pesData=g;const b={audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};return r&&this.extractRemainingSamples(b),b}flush(){const{remainderData:t}=this;this.remainderData=null;let i;return t?i=this.demux(t,-1,!1,!0):i={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(i),this.sampleAes?this.decrypt(i,this.sampleAes):i}extractRemainingSamples(t){const{audioTrack:i,videoTrack:s,id3Track:r,textTrack:n}=t,a=s.pesData,o=i.pesData,l=r.pesData;let d;if(a&&(d=It(a,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,n,d,!0),s.pesData=null)):s.pesData=a,o&&(d=It(o,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,d);break;case"mp3":this.parseMPEGPES(i,d);break;case"ac3":this.parseAC3PES(i,d);break}i.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=o;l&&(d=It(l,this.logger))?(this.parseID3PES(r,d),r.pesData=null):r.pesData=l}demuxSampleAes(t,i,s){const r=this.demux(t,s,!0,!this.config.progressive),n=this.sampleAes=new md(this.observer,this.config,i);return this.decrypt(r,n)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new pd:t==="hevc"&&(this.videoParser=new yd))}decrypt(t,i){return new Promise(s=>{const{audioTrack:r,videoTrack:n}=t;r.samples&&r.segmentCodec==="aac"?i.decryptAacSamples(r.samples,0,()=>{n.samples?i.decryptAvcSamples(n.samples,0,0,()=>{s(t)}):s(t)}):n.samples&&i.decryptAvcSamples(n.samples,0,0,()=>{s(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,i){let s=0;const r=this.aacOverFlow;let n=i.data;if(r){this.aacOverFlow=null;const h=r.missing,u=r.sample.unit.byteLength;if(h===-1)n=Ce(r.sample.unit,n);else{const f=u-h;r.sample.unit.set(n.subarray(0,h),f),t.samples.push(r.sample),s=r.missing}}let a,o;for(a=s,o=n.length;a<o-1&&!Ni(n,a);a++);if(a!==s){let h;const u=a<o-1;if(u?h=`AAC PES did not start with ADTS header,offset:${a}`:h="No ADTS header found in AAC PES",dr(this.observer,new Error(h),u,this.logger),!u)return}Go(t,this.observer,n,a,this.audioCodec);let l;if(i.pts!==void 0)l=i.pts;else if(r){const h=Vo(t.samplerate);l=r.sample.pts+h}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let d=0,c;for(;a<o;)if(c=Ko(t,n,a,l,d),a+=c.length,c.missing){this.aacOverFlow=c;break}else for(d++;a<o-1&&!Ni(n,a);a++);}parseMPEGPES(t,i){const s=i.data,r=s.length;let n=0,a=0;const o=i.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<r;)if(zo(s,a)){const l=jo(t,s,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseAC3PES(t,i){{const s=i.data,r=i.pts;if(r===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const n=s.length;let a=0,o=0,l;for(;o<n&&(l=Xo(t,s,o,r,a++))>0;)o+=l}}parseID3PES(t,i){if(i.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=se({},i,{type:this._videoTrack?Se.emsg:Se.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}},Ed=class{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}},Qe=Math.pow(2,32)-1,me=class R{static init(){R.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let t;for(t in R.types)R.types.hasOwnProperty(t)&&(R.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);R.HDLR_TYPES={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]);R.STTS=R.STSC=R.STCO=new Uint8Array([0,0,0,0,0,0,0,0]),R.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),R.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),R.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),R.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const s=new Uint8Array([105,115,111,109]),r=new Uint8Array([97,118,99,49]),n=new Uint8Array([0,0,0,1]);R.FTYP=R.box(R.types.ftyp,s,n,s,r),R.DINF=R.box(R.types.dinf,R.box(R.types.dref,i))}static box(t,...i){let s=8,r=i.length;const n=r;for(;r--;)s+=i[r].byteLength;const a=new Uint8Array(s);for(a[0]=s>>24&255,a[1]=s>>16&255,a[2]=s>>8&255,a[3]=s&255,a.set(t,4),r=0,s=8;r<n;r++)a.set(i[r],s),s+=i[r].byteLength;return a}static hdlr(t){return R.box(R.types.hdlr,R.HDLR_TYPES[t])}static mdat(t){return R.box(R.types.mdat,t)}static mdhd(t,i){i*=t;const s=Math.floor(i/(Qe+1)),r=Math.floor(i%(Qe+1));return R.box(R.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,s>>24,s>>16&255,s>>8&255,s&255,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(t){return R.box(R.types.mdia,R.mdhd(t.timescale||0,t.duration||0),R.hdlr(t.type),R.minf(t))}static mfhd(t){return R.box(R.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type==="audio"?R.box(R.types.minf,R.box(R.types.smhd,R.SMHD),R.DINF,R.stbl(t)):R.box(R.types.minf,R.box(R.types.vmhd,R.VMHD),R.DINF,R.stbl(t))}static moof(t,i,s){return R.box(R.types.moof,R.mfhd(t),R.traf(s,i))}static moov(t){let i=t.length;const s=[];for(;i--;)s[i]=R.trak(t[i]);return R.box.apply(null,[R.types.moov,R.mvhd(t[0].timescale||0,t[0].duration||0)].concat(s).concat(R.mvex(t)))}static mvex(t){let i=t.length;const s=[];for(;i--;)s[i]=R.trex(t[i]);return R.box.apply(null,[R.types.mvex,...s])}static mvhd(t,i){i*=t;const s=Math.floor(i/(Qe+1)),r=Math.floor(i%(Qe+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,s>>24,s>>16&255,s>>8&255,s&255,r>>24,r>>16&255,r>>8&255,r&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return R.box(R.types.mvhd,n)}static sdtp(t){const i=t.samples||[],s=new Uint8Array(4+i.length);let r,n;for(r=0;r<i.length;r++)n=i[r].flags,s[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return R.box(R.types.sdtp,s)}static stbl(t){return R.box(R.types.stbl,R.stsd(t),R.box(R.types.stts,R.STTS),R.box(R.types.stsc,R.STSC),R.box(R.types.stsz,R.STSZ),R.box(R.types.stco,R.STCO))}static avc1(t){let i=[],s=[],r,n,a;for(r=0;r<t.sps.length;r++)n=t.sps[r],a=n.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(n));for(r=0;r<t.pps.length;r++)n=t.pps[r],a=n.byteLength,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(n));const o=R.box(R.types.avcC,new Uint8Array([1,i[3],i[4],i[5],255,224|t.sps.length].concat(i).concat([t.pps.length]).concat(s))),l=t.width,d=t.height,c=t.pixelRatio[0],h=t.pixelRatio[1];return R.box(R.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,c&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(t){const i=t.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...i,6,1,2])}static audioStsd(t){const i=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,i>>8&255,i&255,0,0])}static mp4a(t){return R.box(R.types.mp4a,R.audioStsd(t),R.box(R.types.esds,R.esds(t)))}static mp3(t){return R.box(R.types[".mp3"],R.audioStsd(t))}static ac3(t){return R.box(R.types["ac-3"],R.audioStsd(t),R.box(R.types.dac3,t.config))}static stsd(t){const{segmentCodec:i}=t;if(t.type==="audio"){if(i==="aac")return R.box(R.types.stsd,R.STSD,R.mp4a(t));if(i==="ac3"&&t.config)return R.box(R.types.stsd,R.STSD,R.ac3(t));if(i==="mp3"&&t.codec==="mp3")return R.box(R.types.stsd,R.STSD,R.mp3(t))}else if(t.pps&&t.sps){if(i==="avc")return R.box(R.types.stsd,R.STSD,R.avc1(t));if(i==="hevc"&&t.vps)return R.box(R.types.stsd,R.STSD,R.hvc1(t))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${t.type} segment codec (${i}/${t.codec})`)}static tkhd(t){const i=t.id,s=(t.duration||0)*(t.timescale||0),r=t.width||0,n=t.height||0,a=Math.floor(s/(Qe+1)),o=Math.floor(s%(Qe+1));return R.box(R.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,i>>24&255,i>>16&255,i>>8&255,i&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,r&255,0,0,n>>8&255,n&255,0,0]))}static traf(t,i){const s=R.sdtp(t),r=t.id,n=Math.floor(i/(Qe+1)),a=Math.floor(i%(Qe+1));return R.box(R.types.traf,R.box(R.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),R.box(R.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),R.trun(t,s.length+16+20+8+16+8+8),s)}static trak(t){return t.duration=t.duration||4294967295,R.box(R.types.trak,R.tkhd(t),R.mdia(t))}static trex(t){const i=t.id;return R.box(R.types.trex,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,i){const s=t.samples||[],r=s.length,n=12+16*r,a=new Uint8Array(n);let o,l,d,c,h,u;for(i+=8+n,a.set([t.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255],0),o=0;o<r;o++)l=s[o],d=l.duration,c=l.size,h=l.flags,u=l.cts,a.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,u>>>24&255,u>>>16&255,u>>>8&255,u&255],12+16*o);return R.box(R.types.trun,a)}static initSegment(t){R.types||R.init();const i=R.moov(t);return Ce(R.FTYP,i)}static hvc1(t){const i=t.params,s=[t.vps,t.sps,t.pps],r=new Uint8Array([1,i.general_profile_space<<6|(i.general_tier_flag?32:0)|i.general_profile_idc,i.general_profile_compatibility_flags[0],i.general_profile_compatibility_flags[1],i.general_profile_compatibility_flags[2],i.general_profile_compatibility_flags[3],i.general_constraint_indicator_flags[0],i.general_constraint_indicator_flags[1],i.general_constraint_indicator_flags[2],i.general_constraint_indicator_flags[3],i.general_constraint_indicator_flags[4],i.general_constraint_indicator_flags[5],i.general_level_idc,240|i.min_spatial_segmentation_idc>>8,255&i.min_spatial_segmentation_idc,252|i.parallelismType,252|i.chroma_format_idc,248|i.bit_depth_luma_minus8,248|i.bit_depth_chroma_minus8,0,parseInt(i.frame_rate.fps),3|i.temporal_id_nested<<2|i.num_temporal_layers<<3|(i.frame_rate.fixed?64:0),s.length]);let n=r.length;for(let f=0;f<s.length;f+=1){n+=3;for(let m=0;m<s[f].length;m+=1)n+=2+s[f][m].length}const a=new Uint8Array(n);a.set(r,0),n=r.length;const o=s.length-1;for(let f=0;f<s.length;f+=1){a.set(new Uint8Array([32+f|(f===o?128:0),0,s[f].length]),n),n+=3;for(let m=0;m<s[f].length;m+=1)a.set(new Uint8Array([s[f][m].length>>8,s[f][m].length&255]),n),n+=2,a.set(s[f][m],n),n+=s[f][m].length}const l=R.box(R.types.hvcC,a),d=t.width,c=t.height,h=t.pixelRatio[0],u=t.pixelRatio[1];return R.box(R.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,d>>8&255,d&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&255])))}},me.types=void 0,me.HDLR_TYPES=void 0,me.STTS=void 0,me.STSC=void 0,me.STCO=void 0,me.STSZ=void 0,me.VMHD=void 0,me.SMHD=void 0,me.STSD=void 0,me.FTYP=void 0,me.DINF=void 0,qr=9e4,Td=10*1e3,Sd=1024,bd=1152,Id=1536,mt=null,rs=null,ti=class extends Pe{constructor(e,t,i,s){if(super("mp4-remuxer",s),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,mt===null){const r=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);mt=r?parseInt(r[1]):0}if(rs===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);rs=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&Zo(t)} > ${e&&Zo(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,s=e.reduce((r,n)=>{let a=n.pts,o=a-r;return o<-4294967296&&(t=!0,a=we(a,i),o=a-r),o>0?r:a},i);return t&&this.debug("PTS rollover detected"),s}remux(e,t,i,s,r,n,a,o){let l,d,c,h,u,f,m=r,g=r;const y=e.pid>-1,v=t.pid>-1,E=t.samples.length,T=e.samples.length>0,S=a&&E>0||E>1;if((!y||T)&&(!v||S)||this.ISGenerated||a){if(this.ISGenerated){var A,b,I,D;const U=this.videoTrackConfig;(U&&(t.width!==U.width||t.height!==U.height||((A=t.pixelRatio)==null?void 0:A[0])!==((b=U.pixelRatio)==null?void 0:b[0])||((I=t.pixelRatio)==null?void 0:I[1])!==((D=U.pixelRatio)==null?void 0:D[1]))||!U&&S||this.nextAudioTs===null&&T)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,r,n));const P=this.isVideoContiguous;let w=-1,x;if(S&&(w=Rf(t.samples),!P&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,w>0){this.warn(`Dropped ${w} out of ${E} video samples due to a missing keyframe`);const U=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(w),t.dropped+=w,g+=(t.samples[0].pts-U)/t.inputTimeScale,x=g}else w===-1&&(this.warn(`No keyframe found out of ${E} video samples`),f=!1);if(this.ISGenerated){if(T&&S){const U=this.getVideoStartPts(t.samples),O=(we(e.samples[0].pts,U)-U)/t.inputTimeScale;m+=Math.max(0,O),g+=Math.max(0,-O)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(e,t,r,n)),d=this.remuxAudio(e,m,this.isAudioContiguous,n,v||S||o===B.AUDIO?g:void 0),S){const U=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,g,P,U)}}else S&&(l=this.remuxVideo(t,g,P,0));l&&(l.firstKeyFrame=w,l.independent=w!==-1,l.firstKeyFramePTS=x)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(u=el(i,r,this._initPTS,this._initDTS)),s.samples.length&&(h=tl(s,r,this._initPTS))),{audio:d,video:l,initSegment:c,independent:f,text:h,id3:u}}computeInitPts(e,t,i,s){const r=Math.round(i*t);let n=we(e,r);if(n<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${s}`);n<r+t;)n+=8589934592;return n-r}generateIS(e,t,i,s){const r=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let d=!l||s,c="audio/mp4",h,u,f,m=-1;if(d&&(h=u=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(c="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}o.audio={id:"audio",container:c,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):me.initSegment([e]),metadata:{channelCount:e.channelCount}},d&&(m=e.id,f=e.inputTimeScale,!l||f!==l.timescale?h=u=this.computeInitPts(r[0].pts,f,i,"audio"):d=!1)}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:me.initSegment([t]),metadata:{width:t.width,height:t.height}},d)if(m=t.id,f=t.inputTimeScale,!l||f!==l.timescale){const g=this.getVideoStartPts(n),y=we(n[0].dts,g),v=this.computeInitPts(y,f,i,"video"),E=this.computeInitPts(g,f,i,"video");u=Math.min(u,v),h=Math.min(h,E)}else d=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,d?(l&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${i} ${h/f} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${h/f} (${h}/${f}) trackId: ${m}`),this._initPTS={baseTime:h,timescale:f,trackId:m},this._initDTS={baseTime:u,timescale:f,trackId:m}):h=f=void 0,{tracks:o,initPTS:h,timescale:f,trackId:m}}remuxVideo(e,t,i,s){const r=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS,d=l.baseTime*r/l.timescale;let c=this.nextVideoTs,h=8,u=this.videoSampleDuration,f,m,g=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,v=!1;if(!i||c===null){const k=d+t*r,C=n[0].pts-we(n[0].dts,n[0].pts);mt&&c!==null&&Math.abs(k-C-(c+d))<15e3?i=!0:c=k-C-d}const E=c+d;for(let k=0;k<o;k++){const C=n[k];C.pts=we(C.pts,E),C.dts=we(C.dts,E),C.dts<n[k>0?k-1:k].dts&&(v=!0)}v&&n.sort(function(k,C){const G=k.dts-C.dts,j=k.pts-C.pts;return G||j}),f=n[0].dts,m=n[n.length-1].dts;const T=m-f,S=T?Math.round(T/(o-1)):u||e.inputTimeScale/30;if(i){const k=f-E,C=k>S,G=k<-1;if((C||G)&&(C?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Kt(k,!0)} ms (${k}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Kt(-k,!0)} ms (${k}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!G||E>=n[0].pts||mt)){f=E;const j=n[0].pts-k;if(C)n[0].dts=f,n[0].pts=j;else{let J=!0;for(let X=0;X<n.length&&!(n[X].dts>j&&J);X++){const Q=n[X].pts;if(n[X].dts-=k,n[X].pts-=k,X<n.length-1){const Ie=n[X+1].pts;J=Ie<=n[X].pts==Ie<=Q}}}this.log(`Video: Initial PTS/DTS adjusted: ${Kt(j,!0)}/${Kt(f,!0)}, delta: ${Kt(k,!0)} ms`)}}f=Math.max(0,f);let A=0,b=0,I=f;for(let k=0;k<o;k++){const C=n[k],G=C.units,j=G.length;let J=0;for(let X=0;X<j;X++)J+=G[X].data.length;b+=J,A+=j,C.length=J,C.dts<I?(C.dts=I,I+=S/4|0||1):I=C.dts,g=Math.min(C.pts,g),y=Math.max(C.pts,y)}m=n[o-1].dts;const D=b+4*A+8;let P;try{P=new Uint8Array(D)}catch(k){this.observer.emit(p.ERROR,p.ERROR,{type:$.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,error:k,bytes:D,reason:`fail allocating video mdat ${D}`});return}const w=new DataView(P.buffer);w.setUint32(0,D),P.set(me.types.mdat,4);let x=!1,U=Number.POSITIVE_INFINITY,O=Number.POSITIVE_INFINITY,V=Number.NEGATIVE_INFINITY,F=Number.NEGATIVE_INFINITY;for(let k=0;k<o;k++){const C=n[k],G=C.units;let j=0;for(let Q=0,Ie=G.length;Q<Ie;Q++){const _e=G[Q],He=_e.data,yt=_e.data.byteLength;w.setUint32(h,yt),h+=4,P.set(He,h),h+=yt,j+=4+yt}let J;if(k<o-1)u=n[k+1].dts-C.dts,J=n[k+1].pts-C.pts;else{const Q=this.config,Ie=k>0?C.dts-n[k-1].dts:S;if(J=k>0?C.pts-n[k-1].pts:S,Q.stretchShortVideoTrack&&this.nextAudioTs!==null){const _e=Math.floor(Q.maxBufferHole*r),He=(s?g+s*r:this.nextAudioTs+d)-C.pts;He>_e?(u=He-Ie,u<0?u=Ie:x=!0,this.log(`It is approximately ${He/90} ms to the next segment; using duration ${u/90} ms for the last video frame.`)):u=Ie}else u=Ie}const X=Math.round(C.pts-C.dts);U=Math.min(U,u),V=Math.max(V,u),O=Math.min(O,J),F=Math.max(F,J),a.push(Jo(C.key,u,j,X))}if(a.length){if(mt){if(mt<70){const k=a[0].flags;k.dependsOn=2,k.isNonSync=0}}else if(rs&&F-O<V-U&&S/V<.025&&a[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let k=f;for(let C=0,G=a.length;C<G;C++){const j=k+a[C].duration,J=k+a[C].cts;if(C<G-1){const X=j+a[C+1].cts;a[C].duration=X-J}else a[C].duration=C?a[C-1].duration:S;a[C].cts=0,k=j}}}u=x||!u?S:u;const M=m+u;this.nextVideoTs=c=M-d,this.videoSampleDuration=u,this.isVideoContiguous=!0;const W={data1:me.moof(e.sequenceNumber++,f,se(e,{samples:a})),data2:P,startPTS:(g-d)/r,endPTS:(y+u-d)/r,startDTS:(f-d)/r,endDTS:c/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,W}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return bd;case"ac3":return Id;default:return Sd}}remuxAudio(e,t,i,s,r){const n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),l=o*a,d=this._initPTS,c=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,h=[],u=r!==void 0;let f=e.samples,m=c?0:8,g=this.nextAudioTs||-1;const y=d.baseTime*n/d.timescale,v=y+t*n;if(this.isAudioContiguous=i=i||f.length&&g>0&&(s&&Math.abs(v-(g+y))<9e3||Math.abs(we(f[0].pts,v)-(g+y))<20*l),f.forEach(function(O){O.pts=we(O.pts,v)}),!i||g<0){const O=f.length;if(f=f.filter(V=>V.pts>=0),O!==f.length&&this.warn(`Removed ${f.length-O} of ${O} samples (initPTS ${y} / ${n})`),!f.length)return;r===0?g=0:s&&!u?g=Math.max(0,v-y):g=f[0].pts-y}if(e.segmentCodec==="aac"){const O=this.config.maxAudioFramesDrift;for(let V=0,F=g+y;V<f.length;V++){const M=f[V],W=M.pts,k=W-F,C=Math.abs(1e3*k/n);if(k<=-O*l&&u)V===0&&(this.warn(`Audio frame @ ${(W/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*k/n)} ms.`),this.nextAudioTs=g=W-y,F=W);else if(k>=O*l&&C<Td&&u){let G=Math.round(k/l);for(F=W-G*l;F<0&&G&&l;)G--,F+=l;V===0&&(this.nextAudioTs=g=F-y),this.warn(`Injecting ${G} audio frames @ ${((F-y)/n).toFixed(3)}s due to ${Math.round(1e3*k/n)} ms gap.`);for(let j=0;j<G;j++){let J=Ed.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);J||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),J=M.unit.subarray()),f.splice(V,0,{unit:J,pts:F}),F+=l,V++}}M.pts=F,F+=l}}let E=null,T=null,S,A=0,b=f.length;for(;b--;)A+=f[b].unit.byteLength;for(let O=0,V=f.length;O<V;O++){const F=f[O],M=F.unit;let W=F.pts;if(T!==null){const C=h[O-1];C.duration=Math.round((W-T)/a)}else if(i&&e.segmentCodec==="aac"&&(W=g+y),E=W,A>0){A+=m;try{S=new Uint8Array(A)}catch(C){this.observer.emit(p.ERROR,p.ERROR,{type:$.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,error:C,bytes:A,reason:`fail allocating audio mdat ${A}`});return}c||(new DataView(S.buffer).setUint32(0,A),S.set(me.types.mdat,4))}else return;S.set(M,m);const k=M.byteLength;m+=k,h.push(Jo(!0,o,k,0)),T=W}const I=h.length;if(!I)return;const D=h[h.length-1];g=T-y,this.nextAudioTs=g+a*D.duration;const P=c?new Uint8Array(0):me.moof(e.sequenceNumber++,E/a,se({},e,{samples:h}));e.samples=[];const w=(E-y)/n,x=this.nextAudioTs/n,U={data1:P,data2:S,startPTS:w,endPTS:x,startDTS:w,endDTS:x,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,U}},Ad=class extends Pe{constructor(e,t,i,s){super("passthrough-remuxer",s),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,s){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,s),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:i,videoCodec:s}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:n}=this.initData=Ua(e);if(t)Zh(e,t);else{const o=r||n;o!=null&&o.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${o.codec}")!`)}r&&(i=il(r,re.AUDIO,this)),n&&(s=il(n,re.VIDEO,this));const a={};r&&n?a.audiovideo={container:"video/mp4",codec:i+","+s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:r?a.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:e,id:"audio"}:n?a.video={container:"video/mp4",codec:s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,i,s,r,n){var a,o;let{initPTS:l,lastEndTime:d}=this;const c={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};N(d)||(d=this.lastEndTime=r||0);const h=t.samples;if(!h.length)return c;const u={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if((a=f)!=null&&a.length||(this.generateInitSegment(h),f=this.initData),!((o=f)!=null&&o.length))return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const m=eu(h,f,this),g=f.audio?m[f.audio.id]:null,y=f.video?m[f.video.id]:null,v=Ui(y,1/0),E=Ui(g,1/0),T=Ui(y,0,!0),S=Ui(g,0,!0);let A=r,b=0;const I=g&&(!y||!l&&E<v||l&&l.trackId===f.audio.id),D=I?g:y;if(D){const W=D.timescale,k=D.start-r*W,C=I?f.audio.id:f.video.id;A=D.start/W,b=I?S-E:T-v,(n||!l)&&(Df(l,A,r,b)||W!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${k/W} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${A-r} (${k}/${W}) trackId: ${C}`),l=null,u.initPTS=k,u.timescale=W,u.trackId=C)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(u.initPTS=l.baseTime,u.timescale=l.timescale,u.trackId=l.trackId):((!u.timescale||u.trackId===void 0||u.initPTS===void 0)&&(this.warn("Could not set initPTS"),u.initPTS=A,u.timescale=1,u.trackId=-1),this.initPTS=l={baseTime:u.initPTS,timescale:u.timescale,trackId:u.trackId});const P=A-l.baseTime/l.timescale,w=P+b;b>0?this.lastEndTime=w:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const x=!!f.audio,U=!!f.video;let O="";x&&(O+="audio"),U&&(O+="video");const V=(f.audio?f.audio.encrypted:!1)||(f.video?f.video.encrypted:!1),F={data1:h,startPTS:P,startDTS:P,endPTS:w,endDTS:w,type:O,hasAudio:x,hasVideo:U,nb:1,dropped:0,encrypted:V};c.audio=x&&!U?F:void 0,c.video=U?F:void 0;const M=y?.sampleCount;if(M){const W=y.keyFrameIndex,k=W!==-1;F.nb=M,F.dropped=W===0||this.isVideoContiguous?0:k?W:M,F.independent=k,F.firstKeyFrame=W,k&&y.keyFrameStart&&(F.firstKeyFramePTS=(y.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(c.independent=k),this.isVideoContiguous||(this.isVideoContiguous=k),F.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${W}/${M} dropped: ${F.dropped} start: ${F.firstKeyFramePTS||"NA"}`)}return c.initSegment=u,c.id3=el(i,r,l,l),s.samples.length&&(c.text=tl(s,r,l)),c}};try{Ze=self.performance.now.bind(self.performance)}catch{Ze=Date.now}ii=[{demux:gd,remux:Ad},{demux:vd,remux:ti},{demux:cd,remux:ti},{demux:ud,remux:ti}],ii.splice(2,0,{demux:hd,remux:ti}),Xr=class{constructor(e,t,i,s,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){const r=i.transmuxing;r.executeStart=Ze();let n=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;s&&(this.currentTransmuxState=s);const{contiguous:l,discontinuity:d,trackSwitch:c,accurateTimeOffset:h,timeOffset:u,initSegmentChange:f}=s||a,{audioCodec:m,videoCodec:g,defaultInitPts:y,duration:v,initSegmentData:E}=o,T=wf(n,t);if(T&&bt(T.method)){const I=this.getDecrypter(),D=Xs(T.method);if(I.isSync()){let P=I.softwareDecrypt(n,T.key.buffer,T.iv.buffer,D);if(i.part>-1){const w=I.flush();P=w&&w.buffer}if(!P)return r.executeEnd=Ze(),ns(i);n=new Uint8Array(P)}else return this.asyncResult=!0,this.decryptionPromise=I.webCryptoDecrypt(n,T.key.buffer,T.iv.buffer,D).then(P=>{const w=this.push(P,null,i);return this.decryptionPromise=null,w}),this.decryptionPromise}const S=this.needsProbing(d,c);if(S){const I=this.configureTransmuxer(n);if(I)return this.logger.warn(`[transmuxer] ${I.message}`),this.observer.emit(p.ERROR,p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),r.executeEnd=Ze(),ns(i)}(d||c||f||S)&&this.resetInitSegment(E,m,g,v,t),(d||f||S)&&this.resetInitialTimestamp(y),l||this.resetContiguity();const A=this.transmux(n,T,u,h,i);this.asyncResult=Ht(A);const b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,r.executeEnd=Ze(),A}flush(e){const t=e.transmuxing;t.executeStart=Ze();const{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:a}=s;if(i){const c=i.flush();c&&n.push(this.push(c.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=Ze();const c=[ns(e)];return this.asyncResult?Promise.resolve(c):c}const d=o.flush(a);return Ht(d)?(this.asyncResult=!0,d.then(c=>(this.flushRemux(n,c,e),n))):(this.flushRemux(n,d,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,i){const{audioTrack:s,videoTrack:r,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===B.MAIN?"level":"track"} ${i.level}`);const d=this.remuxer.remux(s,r,n,a,l,o,!0,this.id);e.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=Ze()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,s,r){const{demuxer:n,remuxer:a}=this;!n||!a||(n.resetInitSegment(e,t,i,s),a.resetInitSegment(e,t,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,s,r){let n;return t&&t.method==="SAMPLE-AES"?n=this.transmuxSampleAes(e,t,i,s,r):n=this.transmuxUnencrypted(e,i,s,r),n}transmuxUnencrypted(e,t,i,s){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,t,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,t,i,s,r){return this.demuxer.demuxSampleAes(e,t,i).then(n=>({remuxResult:this.remuxer.remux(n.audioTrack,n.videoTrack,n.id3Track,n.textTrack,i,s,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:s}=this;let r;for(let c=0,h=ii.length;c<h;c++){var n;if((n=ii[c].demux)!=null&&n.probe(e,this.logger)){r=ii[c];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.remux,d=r.demux;(!o||!(o instanceof l))&&(this.remuxer=new l(i,t,s,this.logger)),(!a||!(a instanceof d))&&(this.demuxer=new d(i,t,s,this.logger),this.probe=d.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Qi(this.config)),e}},ns=e=>({remuxResult:{},chunkMeta:e}),Ld=class{constructor(e,t,i,s,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}},Rd=class{constructor(e,t,i,s,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=n}},Qr=0,Zr=class{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Qr++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=o=>{const l=o.data,d=this.hls;if(!(!d||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var c;const h=(c=this.workerContext)==null?void 0:c.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":this.handleTransmuxComplete(l.data);break;case"flush":this.onFlush(l.data);break;case"workerLog":d.logger[l.data.logType]&&d.logger[l.data.logType](l.data.message);break;default:l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,d.trigger(l.event,l.data);break}},this.onWorkerError=o=>{if(!this.hls)return;const l=new Error(`${o.message} (${o.filename}:${o.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const n=(o,l)=>{l=l||{},l.frag=this.frag||void 0,o===p.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(o,l)};this.observer=new is,this.observer.on(p.FRAG_DECRYPTED,n),this.observer.on(p.ERROR,n);const a=Wa(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const o=this.hls.logger;if(r.workerPath||Ju()){try{r.workerPath?(o.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=tf(r.workerPath)):(o.log(`injecting Web Worker for "${t}"`),this.workerContext=ef());const{worker:l}=this.workerContext;l.addEventListener("message",this.onWorkerMessage),l.addEventListener("error",this.onWorkerError),l.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:ne(r)})}catch(l){o.warn(`Error setting up "${t}" Web Worker, fallback to inline`,l),this.terminateWorker(),this.error=null,this.transmuxer=new Xr(this.observer,a,r,"",t,e.logger)}return}}this.transmuxer=new Xr(this.observer,a,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Qr++;const t=this.hls.config,i=Wa(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:ne(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),sf(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,s,r,n,a,o,l,d){var c,h;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,m=n?n.start:r.start,g=r.decryptdata,y=this.frag,v=!(y&&r.cc===y.cc),E=!(y&&l.level===y.level),T=y?l.sn-y.sn:-1,S=this.part?l.part-this.part.index:-1,A=T===0&&l.id>1&&l.id===y?.stats.chunkCount,b=!E&&(T===1||T===0&&(S===1||A&&S<=0)),I=self.performance.now();(E||T||r.stats.parsing.start===0)&&(r.stats.parsing.start=I),n&&(S||!b)&&(n.stats.parsing.start=I);const D=!(y&&((c=r.initSegment)==null?void 0:c.url)===((h=y.initSegment)==null?void 0:h.url)),P=new Rd(v,b,o,E,m,D);if(!b||v||D){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===B.MAIN?"level":"track"}: ${l.level} id: ${l.id}
|
|
63
63
|
discontinuity: ${v}
|
|
64
64
|
trackSwitch: ${E}
|
|
65
65
|
contiguous: ${b}
|
|
66
66
|
accurateTimeOffset: ${o}
|
|
67
67
|
timeOffset: ${m}
|
|
68
|
-
initSegmentChange: ${D}`);const P=new Ld(i,s,t,a,d);this.configureTransmuxer(P)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:e,decryptdata:g,chunkMeta:l,state:w},e instanceof ArrayBuffer?[e]:[]);else if(f){const P=f.push(e,g,l,w);Ht(P)?P.then(x=>{this.handleTransmuxComplete(x)}).catch(x=>{this.transmuxerError(x,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(P)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const s=i.flush(e);Ht(s)?s.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(s,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},Jr=100,en=class extends Zt{constructor(e,t,i){super(e,t,i,"audio-stream-controller",B.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:r,trackId:n}){if(i===B.MAIN){const a=t.cc,o=this.fragCurrent;if(this.initPTS[a]={baseTime:s,timescale:r,trackId:n},this.log(`InitPTS for cc: ${a} found from main: ${s/r} (${s}/${r}) trackId: ${n}`),this.mainAnchor=t,this.state===_.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==a)&&this.syncWithAnchor(t,l?.frag)}else!this.hls.hasEnoughToStart&&o&&o.cc!==a?(o.abortRequests(),this.syncWithAnchor(t,o)):this.state===_.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;const s=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&s?.cc===t.cc)return;const r=(s||e).cc,n=to(this.getLevelDetails(),r,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===_.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=_.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(Jr),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=_.IDLE):this.state=_.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case _.IDLE:this.doTickIdle();break;case _.WAITING_TRACK:{const{levels:e,trackId:t}=this,i=e?.[t],s=i?.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=_.WAITING_INIT_PTS}break}case _.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case _.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:s,complete:r}=e,n=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=_.FRAG_LOADING;const a={frag:t,part:i,payload:s.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(a),r&&super._handleFragmentLoadComplete(a)}else n&&n.cc!==e.frag.cc&&this.syncWithAnchor(n,e.frag)}else this.state=_.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:s,trackId:r}=this,n=t.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||!(i!=null&&i[r]))return;const a=i[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o)){this.state=_.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,re.AUDIO,B.AUDIO));const d=this.getFwdBufferInfo(l,B.AUDIO);if(d===null)return;if(!this.switchingTrack&&this._streamEnded(d,o)){t.trigger(p.BUFFER_EOS,{type:"audio"}),this.state=_.ENDED;return}const c=d.len,h=t.maxBufferLength,u=o.fragments,f=u[0].start,m=this.getLoadPosition(),g=this.flushing?m:d.end;if(this.switchingTrack&&s){const E=m;o.PTSKnown&&E<f&&(d.end>f||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=f+.05)}if(c>=h&&!this.switchingTrack&&g<u[u.length-1].start)return;let y=this.getNextFragment(g,o);if(y&&this.isLoopLoading(y,g)&&(y=this.getNextFragmentLoopLoading(y,o,d,B.MAIN,h)),!y){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(d,h,y))return;let v=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&de(y)&&!y.endList&&(!o.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===he.OK&&(this.mainFragLoading=v=null),v&&de(v))){if(y.start>v.end){const E=this.fragmentTracker.getFragAtPos(g,B.MAIN);E&&E.end>v.end&&(v=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(y.start>v.end)return}this.loadFragment(y,a,g)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new ht(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==_.STOPPED&&(this.setInterval(Jr),this.state=_.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(p.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:s}=this,{details:r,id:n,groupId:a,track:o}=t;if(!s){this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);return}const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==_.STOPPED&&(this.state=_.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const d=s[n];let c=0;if(r.live||(i=d.details)!=null&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(d.details){var h;c=this.alignPlaylists(r,d.details,(h=this.levelLastLoaded)==null?void 0:h.details)}r.alignedSliding||(Fo(r,l),r.alignedSliding||Oi(r,l),c=r.fragmentStart)}d.details=r,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(p.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state===_.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=_.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:r}=e,{config:n,trackId:a,levels:o}=this;if(!o){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const l=o[a];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const d=l.details;if(!d){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const c=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new Zr(this.hls,B.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[i.cc],f=(t=i.initSegment)==null?void 0:t.data;if(u!==void 0){const g=s?s.index:-1,y=g!==-1,v=new Xt(i.level,i.sn,i.stats.chunkCount,r.byteLength,g,y);h.push(r,f,c,"",i,s,d.totalduration,!1,v,u)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:m}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new jr,complete:!1};m.push(new Uint8Array(r)),this.state!==_.STOPPED&&(this.state=_.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===B.MAIN&&de(t.frag)&&(this.mainFragLoading=t,this.state===_.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i.type!==B.AUDIO){!this.audioOnly&&i.type===B.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(de(i)){this.fragPrevious=i;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(p.AUDIO_TRACK_SWITCHED,ie({},r)))}this.fragBufferedComplete(i,s),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=_.ERROR;return}switch(t.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(B.AUDIO,t);break;case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===_.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===q.AUDIO_TRACK&&(this.state=_.IDLE);break;case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case L.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==re.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==re.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===_.ENDED&&(this.state=_.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,B.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:s}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}const{frag:o,part:l,level:d}=a,{details:c}=d,{audio:h,text:u,id3:f,initSegment:m}=r;if(this.fragContextChanged(o)||!c){this.fragmentTracker.removeFragment(o);return}if(this.state=_.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),m!=null&&m.tracks){const g=o.initSegment||o;if(this.unhandledEncryptionError(m,o))return;this._bufferInitSegment(d,m.tracks,g,n),s.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:i,tracks:m.tracks})}if(h){const{startPTS:g,endPTS:y,startDTS:v,endDTS:E}=h;l&&(l.elementaryStreams[re.AUDIO]={startPTS:g,endPTS:y,startDTS:v,endDTS:E}),o.setElementaryStreamInfo(re.AUDIO,g,y,v,E),this.bufferFragmentData(h,o,l,n)}if(f!=null&&(t=f.samples)!=null&&t.length){const g=se({id:i,frag:o,details:c},f);s.trigger(p.FRAG_PARSING_METADATA,g)}if(u){const g=se({id:i,frag:o,details:c},u);s.trigger(p.FRAG_PARSING_USERDATA,g)}}_bufferInitSegment(e,t,i,s){if(this.state!==_.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=B.AUDIO;const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&n.split(",").length===1&&(r.levelCodec=n),this.hls.trigger(p.BUFFER_CODECS,t);const a=r.initSegment;if(a!=null&&a.byteLength){const o={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:a};this.hls.trigger(p.BUFFER_APPENDING,o)}this.tickImmediate()}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);if(this.switchingTrack||s===he.NOT_LOADED||s===he.PARTIAL){var r;if(!de(e))this._loadInitSegment(e,t);else if((r=t.details)!=null&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=_.WAITING_INIT_PTS;const n=this.mainDetails;n&&n.fragmentStart!==t.details.fragmentStart&&Oi(t.details,n)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;at({name:t,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a},e,ot)||(Pi(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(p.AUDIO_TRACK_SWITCHED,ie({},e))}},si=class extends we{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const s=t?.renditionReports;if(s){let r=-1;for(let n=0;n<s.length;n++){const a=s[n];let o;try{o=new self.URL(a.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),o=a.URI||""}if(o===e){r=n;break}else o===e.substring(0,o.length)&&(r=n)}if(r!==-1){const n=s[r],a=parseInt(n["LAST-MSN"])||t.lastPartSn;let o=parseInt(n["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const d=Math.min(t.age-t.partTarget,t.targetduration);o>=0&&d>t.partTarget&&(o+=1)}const l=i&&qa(i);return new Xi(a,o>=0?o:void 0,l)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){const{details:s,stats:r}=t,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;s.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==s.appliedTimelineOffset){const d=Math.max(o||0,0);s.appliedTimelineOffset=d,s.fragments.forEach(c=>{c.setStart(c.playlistOffset+d)})}if(s.live||i!=null&&i.live){const d="levelInfo"in t?t.levelInfo:t.track;if(s.reloaded(i),i&&s.fragments.length>0){Hu(i,s,this);const y=s.playlistParsingError;if(y){this.warn(y);const v=this.hls;if(!v.config.ignorePlaylistParsingErrors){var l;const{networkDetails:E}=t;v.trigger(p.ERROR,{type:$.NETWORK_ERROR,details:L.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:y,reason:y.message,level:t.level||void 0,parent:(l=s.fragments[0])==null?void 0:l.type,networkDetails:E,stats:r});return}s.playlistParsingError=null}}s.requestScheduled===-1&&(s.requestScheduled=r.loading.start);const c=this.hls.mainForwardBufferInfo,h=c?c.end-c.len:0,u=Po(s,(s.edge-h)*1e3);if(s.requestScheduled+u<n?s.requestScheduled=n:s.requestScheduled+=u,this.log(`live playlist ${e} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),!this.canLoad||!s.live)return;let f,m,g;if(s.canBlockReload&&s.endSN&&s.advanced){const y=this.hls.config.lowLatencyMode,v=s.lastPartSn,E=s.endSN,T=s.lastPartIndex,S=T!==-1,A=v===E;S?A?(m=E+1,g=y?0:T):(m=v,g=y?T+1:s.maxPartIndex):m=E+1;const b=s.age,I=b+s.ageHeader;let D=Math.min(I-s.partTarget,s.targetduration*1.5);if(D>0){if(I>s.targetduration*3)this.log(`Playlist last advanced ${b.toFixed(2)}s ago. Omitting segment and part directives.`),m=void 0,g=void 0;else if(i!=null&&i.tuneInGoal&&I-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${D} with playlist age: ${s.age}`),D=0;else{const w=Math.floor(D/s.targetduration);if(m+=w,g!==void 0){const P=Math.round(D%s.targetduration/s.partTarget);g+=P}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${b.toFixed(2)}s goal: ${D} skip sn ${w} to part ${g}`)}s.tuneInGoal=D}if(f=this.getDeliveryDirectives(s,t.deliveryDirectives,m,g),y||!A){s.requestScheduled=n,this.loadingPlaylist(d,f);return}}else(s.canBlockReload||s.canSkipUntil)&&(f=this.getDeliveryDirectives(s,t.deliveryDirectives,m,g));f&&m!==void 0&&s.canBlockReload&&(s.requestScheduled=r.loading.first+Math.max(u-a*2,u/2)),this.scheduleLoading(d,f,s)}else this.clearTimer()}scheduleLoading(e,t,i){const s=i||e.details;if(!s){this.loadingPlaylist(e,t);return}const r=self.performance.now(),n=s.requestScheduled;if(r>=n){this.loadingPlaylist(e,t);return}const a=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,i,s){let r=qa(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,r=Dt.No),new Xi(i,s,r)}checkRetry(e){const t=e.details,i=wi(e),s=e.errorAction,{action:r,retryCount:n=0,retryConfig:a}=s||{},o=!!s&&!!a&&(r===ce.RetryRequest||!s.resolved&&r===ce.SendAlternateToPenaltyBox);if(o){var l;if(n>=a.maxNumRetry)return!1;if(i&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const d=Ys(a,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),d),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${d}ms`)}e.levelRetry=!0,s.resolved=!0}return o}},tn=class extends si{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:s,details:r}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==s){this.warn(`Audio track with id:${i} and group:${s} not found in active group ${n?.groupId}`);return}const a=n.details;n.details=t.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||s?.length!==i?.length||i!=null&&i.some(a=>s?.indexOf(a)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(h=>!i||i.indexOf(h.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),a.forEach((h,u)=>{h.id=u});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.audioPreference;if(!r&&o){const h=Be(o,a,ot);if(h>-1)r=a[h];else{const u=Be(o,this.tracks);r=this.tracks[u]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const d={audioTracks:a};this.log(`Updating audio tracks, ${a.length} track(s) found in group(s): ${i?.join(",")}`),this.hls.trigger(p.AUDIO_TRACKS_UPDATED,d);const c=this.trackId;if(l!==-1&&c===-1)this.setAudioTrack(l);else if(a.length&&c===-1){var n;const h=new Error(`No audio track selected for current audio group-ID(s): ${(n=this.groupIds)==null?void 0:n.join(",")} track count: ${a.length}`);this.warn(h.message),this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===q.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&at(e,s,ot))return s;const r=Be(e,this.tracksInGroup,ot);if(r>-1){const n=this.tracksInGroup[r];return this.setAudioTrack(r),n}else if(s){let n=t.loadLevel;n===-1&&(n=t.firstAutoLevel);const a=Lu(e,t.levels,i,n,ot);if(a===-1)return null;t.nextLoadLevel=a}if(e.channels||e.audioCodec){const n=Be(e,i);if(n>-1)return i[n]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e],r=s.details&&!s.details.live;if(e===this.trackId&&s===i&&r||(this.log(`Switching to audio-track ${e} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=e,this.currentTrack=s,this.hls.trigger(p.AUDIO_TRACK_SWITCHING,ie({},s)),r))return;const n=this.switchParams(s.url,i?.details,s.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if(!(this.selectDefaultTrack&&!s.default)&&(!e||at(e,s,ot)))return i}if(e){const{name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o}=e;for(let l=0;l<t.length;l++){const d=t[l];if(at({name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},d,ot))return l}for(let l=0;l<t.length;l++){const d=t[l];if(Wt(e.attrs,d.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const d=t[l];if(Wt(e.attrs,d.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Pi(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,s=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=n?.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(p.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null,track:e})}},Dd=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(this.queues===null||this.tracks===null)return;const s=this.queues[t];s.push(e),s.length===1&&!i&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){this.queues!==null&&this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const s=t[0];try{s.execute()}catch(r){var i;if(s.onError(r),this.queues===null||this.tracks===null)return;const n=(i=this.tracks[e])==null?void 0:i.buffer;n!=null&&n.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
|
|
68
|
+
initSegmentChange: ${D}`);const w=new Ld(i,s,t,a,d);this.configureTransmuxer(w)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:e,decryptdata:g,chunkMeta:l,state:P},e instanceof ArrayBuffer?[e]:[]);else if(f){const w=f.push(e,g,l,P);Ht(w)?w.then(x=>{this.handleTransmuxComplete(x)}).catch(x=>{this.transmuxerError(x,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(w)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const s=i.flush(e);Ht(s)?s.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(s,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},Jr=100,en=class extends Zt{constructor(e,t,i){super(e,t,i,"audio-stream-controller",B.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:r,trackId:n}){if(i===B.MAIN){const a=t.cc,o=this.fragCurrent;if(this.initPTS[a]={baseTime:s,timescale:r,trackId:n},this.log(`InitPTS for cc: ${a} found from main: ${s/r} (${s}/${r}) trackId: ${n}`),this.mainAnchor=t,this.state===_.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==a)&&this.syncWithAnchor(t,l?.frag)}else!this.hls.hasEnoughToStart&&o&&o.cc!==a?(o.abortRequests(),this.syncWithAnchor(t,o)):this.state===_.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;const s=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&s?.cc===t.cc)return;const r=(s||e).cc,n=to(this.getLevelDetails(),r,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===_.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=_.STOPPED;return}const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(Jr),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=_.IDLE):this.state=_.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case _.IDLE:this.doTickIdle();break;case _.WAITING_TRACK:{const{levels:e,trackId:t}=this,i=e?.[t],s=i?.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=_.WAITING_INIT_PTS}break}case _.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case _.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:s,complete:r}=e,n=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=_.FRAG_LOADING;const a={frag:t,part:i,payload:s.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(a),r&&super._handleFragmentLoadComplete(a)}else n&&n.cc!==e.frag.cc&&this.syncWithAnchor(n,e.frag)}else this.state=_.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:s,trackId:r}=this,n=t.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||!(i!=null&&i[r]))return;const a=i[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o)){this.state=_.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,re.AUDIO,B.AUDIO));const d=this.getFwdBufferInfo(l,B.AUDIO);if(d===null)return;if(!this.switchingTrack&&this._streamEnded(d,o)){t.trigger(p.BUFFER_EOS,{type:"audio"}),this.state=_.ENDED;return}const c=d.len,h=t.maxBufferLength,u=o.fragments,f=u[0].start,m=this.getLoadPosition(),g=this.flushing?m:d.end;if(this.switchingTrack&&s){const E=m;o.PTSKnown&&E<f&&(d.end>f||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=f+.05)}if(c>=h&&!this.switchingTrack&&g<u[u.length-1].start)return;let y=this.getNextFragment(g,o);if(y&&this.isLoopLoading(y,g)&&(y=this.getNextFragmentLoopLoading(y,o,d,B.MAIN,h)),!y){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(d,h,y))return;let v=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&de(y)&&!y.endList&&(!o.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===he.OK&&(this.mainFragLoading=v=null),v&&de(v))){if(y.start>v.end){const E=this.fragmentTracker.getFragAtPos(g,B.MAIN);E&&E.end>v.end&&(v=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(y.start>v.end)return}this.loadFragment(y,a,g)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new ht(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==_.STOPPED&&(this.setInterval(Jr),this.state=_.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(p.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:s}=this,{details:r,id:n,groupId:a,track:o}=t;if(!s){this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);return}const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==_.STOPPED&&(this.state=_.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const d=s[n];let c=0;if(r.live||(i=d.details)!=null&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(d.details){var h;c=this.alignPlaylists(r,d.details,(h=this.levelLastLoaded)==null?void 0:h.details)}r.alignedSliding||(Fo(r,l),r.alignedSliding||Oi(r,l),c=r.fragmentStart)}d.details=r,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(p.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state===_.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=_.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:r}=e,{config:n,trackId:a,levels:o}=this;if(!o){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const l=o[a];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const d=l.details;if(!d){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const c=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new Zr(this.hls,B.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[i.cc],f=(t=i.initSegment)==null?void 0:t.data;if(u!==void 0){const g=s?s.index:-1,y=g!==-1,v=new Xt(i.level,i.sn,i.stats.chunkCount,r.byteLength,g,y);h.push(r,f,c,"",i,s,d.totalduration,!1,v,u)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:m}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new jr,complete:!1};m.push(new Uint8Array(r)),this.state!==_.STOPPED&&(this.state=_.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===B.MAIN&&de(t.frag)&&(this.mainFragLoading=t,this.state===_.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i.type!==B.AUDIO){!this.audioOnly&&i.type===B.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(de(i)){this.fragPrevious=i;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(p.AUDIO_TRACK_SWITCHED,ie({},r)))}this.fragBufferedComplete(i,s),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=_.ERROR;return}switch(t.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(B.AUDIO,t);break;case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===_.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===q.AUDIO_TRACK&&(this.state=_.IDLE);break;case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case L.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==re.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==re.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===_.ENDED&&(this.state=_.IDLE);const i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,B.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:s}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}const{frag:o,part:l,level:d}=a,{details:c}=d,{audio:h,text:u,id3:f,initSegment:m}=r;if(this.fragContextChanged(o)||!c){this.fragmentTracker.removeFragment(o);return}if(this.state=_.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),m!=null&&m.tracks){const g=o.initSegment||o;if(this.unhandledEncryptionError(m,o))return;this._bufferInitSegment(d,m.tracks,g,n),s.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:i,tracks:m.tracks})}if(h){const{startPTS:g,endPTS:y,startDTS:v,endDTS:E}=h;l&&(l.elementaryStreams[re.AUDIO]={startPTS:g,endPTS:y,startDTS:v,endDTS:E}),o.setElementaryStreamInfo(re.AUDIO,g,y,v,E),this.bufferFragmentData(h,o,l,n)}if(f!=null&&(t=f.samples)!=null&&t.length){const g=se({id:i,frag:o,details:c},f);s.trigger(p.FRAG_PARSING_METADATA,g)}if(u){const g=se({id:i,frag:o,details:c},u);s.trigger(p.FRAG_PARSING_USERDATA,g)}}_bufferInitSegment(e,t,i,s){if(this.state!==_.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=B.AUDIO;const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&n.split(",").length===1&&(r.levelCodec=n),this.hls.trigger(p.BUFFER_CODECS,t);const a=r.initSegment;if(a!=null&&a.byteLength){const o={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:a};this.hls.trigger(p.BUFFER_APPENDING,o)}this.tickImmediate()}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);if(this.switchingTrack||s===he.NOT_LOADED||s===he.PARTIAL){var r;if(!de(e))this._loadInitSegment(e,t);else if((r=t.details)!=null&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=_.WAITING_INIT_PTS;const n=this.mainDetails;n&&n.fragmentStart!==t.details.fragmentStart&&Oi(t.details,n)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;at({name:t,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a},e,ot)||(wi(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(p.AUDIO_TRACK_SWITCHED,ie({},e))}},si=class extends Pe{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const s=t?.renditionReports;if(s){let r=-1;for(let n=0;n<s.length;n++){const a=s[n];let o;try{o=new self.URL(a.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),o=a.URI||""}if(o===e){r=n;break}else o===e.substring(0,o.length)&&(r=n)}if(r!==-1){const n=s[r],a=parseInt(n["LAST-MSN"])||t.lastPartSn;let o=parseInt(n["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const d=Math.min(t.age-t.partTarget,t.targetduration);o>=0&&d>t.partTarget&&(o+=1)}const l=i&&qa(i);return new Xi(a,o>=0?o:void 0,l)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){const{details:s,stats:r}=t,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;s.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==s.appliedTimelineOffset){const d=Math.max(o||0,0);s.appliedTimelineOffset=d,s.fragments.forEach(c=>{c.setStart(c.playlistOffset+d)})}if(s.live||i!=null&&i.live){const d="levelInfo"in t?t.levelInfo:t.track;if(s.reloaded(i),i&&s.fragments.length>0){Hu(i,s,this);const y=s.playlistParsingError;if(y){this.warn(y);const v=this.hls;if(!v.config.ignorePlaylistParsingErrors){var l;const{networkDetails:E}=t;v.trigger(p.ERROR,{type:$.NETWORK_ERROR,details:L.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:y,reason:y.message,level:t.level||void 0,parent:(l=s.fragments[0])==null?void 0:l.type,networkDetails:E,stats:r});return}s.playlistParsingError=null}}s.requestScheduled===-1&&(s.requestScheduled=r.loading.start);const c=this.hls.mainForwardBufferInfo,h=c?c.end-c.len:0,u=wo(s,(s.edge-h)*1e3);if(s.requestScheduled+u<n?s.requestScheduled=n:s.requestScheduled+=u,this.log(`live playlist ${e} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),!this.canLoad||!s.live)return;let f,m,g;if(s.canBlockReload&&s.endSN&&s.advanced){const y=this.hls.config.lowLatencyMode,v=s.lastPartSn,E=s.endSN,T=s.lastPartIndex,S=T!==-1,A=v===E;S?A?(m=E+1,g=y?0:T):(m=v,g=y?T+1:s.maxPartIndex):m=E+1;const b=s.age,I=b+s.ageHeader;let D=Math.min(I-s.partTarget,s.targetduration*1.5);if(D>0){if(I>s.targetduration*3)this.log(`Playlist last advanced ${b.toFixed(2)}s ago. Omitting segment and part directives.`),m=void 0,g=void 0;else if(i!=null&&i.tuneInGoal&&I-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${D} with playlist age: ${s.age}`),D=0;else{const P=Math.floor(D/s.targetduration);if(m+=P,g!==void 0){const w=Math.round(D%s.targetduration/s.partTarget);g+=w}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${b.toFixed(2)}s goal: ${D} skip sn ${P} to part ${g}`)}s.tuneInGoal=D}if(f=this.getDeliveryDirectives(s,t.deliveryDirectives,m,g),y||!A){s.requestScheduled=n,this.loadingPlaylist(d,f);return}}else(s.canBlockReload||s.canSkipUntil)&&(f=this.getDeliveryDirectives(s,t.deliveryDirectives,m,g));f&&m!==void 0&&s.canBlockReload&&(s.requestScheduled=r.loading.first+Math.max(u-a*2,u/2)),this.scheduleLoading(d,f,s)}else this.clearTimer()}scheduleLoading(e,t,i){const s=i||e.details;if(!s){this.loadingPlaylist(e,t);return}const r=self.performance.now(),n=s.requestScheduled;if(r>=n){this.loadingPlaylist(e,t);return}const a=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,i,s){let r=qa(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,r=Dt.No),new Xi(i,s,r)}checkRetry(e){const t=e.details,i=Pi(e),s=e.errorAction,{action:r,retryCount:n=0,retryConfig:a}=s||{},o=!!s&&!!a&&(r===ce.RetryRequest||!s.resolved&&r===ce.SendAlternateToPenaltyBox);if(o){var l;if(n>=a.maxNumRetry)return!1;if(i&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const d=Ys(a,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),d),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${d}ms`)}e.levelRetry=!0,s.resolved=!0}return o}},tn=class extends si{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:s,details:r}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==s){this.warn(`Audio track with id:${i} and group:${s} not found in active group ${n?.groupId}`);return}const a=n.details;n.details=t.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||s?.length!==i?.length||i!=null&&i.some(a=>s?.indexOf(a)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(h=>!i||i.indexOf(h.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),a.forEach((h,u)=>{h.id=u});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.audioPreference;if(!r&&o){const h=Be(o,a,ot);if(h>-1)r=a[h];else{const u=Be(o,this.tracks);r=this.tracks[u]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const d={audioTracks:a};this.log(`Updating audio tracks, ${a.length} track(s) found in group(s): ${i?.join(",")}`),this.hls.trigger(p.AUDIO_TRACKS_UPDATED,d);const c=this.trackId;if(l!==-1&&c===-1)this.setAudioTrack(l);else if(a.length&&c===-1){var n;const h=new Error(`No audio track selected for current audio group-ID(s): ${(n=this.groupIds)==null?void 0:n.join(",")} track count: ${a.length}`);this.warn(h.message),this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===q.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&at(e,s,ot))return s;const r=Be(e,this.tracksInGroup,ot);if(r>-1){const n=this.tracksInGroup[r];return this.setAudioTrack(r),n}else if(s){let n=t.loadLevel;n===-1&&(n=t.firstAutoLevel);const a=Lu(e,t.levels,i,n,ot);if(a===-1)return null;t.nextLoadLevel=a}if(e.channels||e.audioCodec){const n=Be(e,i);if(n>-1)return i[n]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e],r=s.details&&!s.details.live;if(e===this.trackId&&s===i&&r||(this.log(`Switching to audio-track ${e} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=e,this.currentTrack=s,this.hls.trigger(p.AUDIO_TRACK_SWITCHING,ie({},s)),r))return;const n=this.switchParams(s.url,i?.details,s.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if(!(this.selectDefaultTrack&&!s.default)&&(!e||at(e,s,ot)))return i}if(e){const{name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o}=e;for(let l=0;l<t.length;l++){const d=t[l];if(at({name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},d,ot))return l}for(let l=0;l<t.length;l++){const d=t[l];if(Wt(e.attrs,d.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const d=t[l];if(Wt(e.attrs,d.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&wi(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,s=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=n?.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(p.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null,track:e})}},Dd=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(this.queues===null||this.tracks===null)return;const s=this.queues[t];s.push(e),s.length===1&&!i&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){this.queues!==null&&this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const s=t[0];try{s.execute()}catch(r){var i;if(s.onError(r),this.queues===null||this.tracks===null)return;const n=(i=this.tracks[e])==null?void 0:i.buffer;n!=null&&n.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
|
|
69
69
|
${this.list("video")}
|
|
70
70
|
${this.list("audio")}
|
|
71
|
-
${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=(t=this.tracks)==null?void 0:t[e],s=i?.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}},sn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,rn="HlsJsTrackRemovedError",
|
|
71
|
+
${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=(t=this.tracks)==null?void 0:t[e],s=i?.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}},sn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,rn="HlsJsTrackRemovedError",wd=class extends Error{constructor(e){super(e),this.name=rn}},nn=class extends Pe{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=i=>{var s;this.hls&&((s=this.mediaSource)==null?void 0:s.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=i=>{const{media:s,mediaSource:r}=this;i&&this.log("Media source opened"),!(!s||!r)&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(p.MEDIA_ATTACHED,{media:s,mediaSource:r}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:i,_objectUrl:s}=this;i!==s&&this.error(`Media element src was set while attaching MediaSource (${s} > ${i})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=Hh(Ye(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_APPENDING,this.onBufferAppending,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.BUFFER_EOS,this.onBufferEos,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.FRAG_PARSED,this.onFragParsed,this),e.on(p.FRAG_CHANGED,this.onFragChanged,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_APPENDING,this.onBufferAppending,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_EOS,this.onBufferEos,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.FRAG_PARSED,this.onFragParsed,this),e.off(p.FRAG_CHANGED,this.onFragChanged,this),e.off(p.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const i={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const n=this.isQueued();(r||n)&&this.warn(`Transfering MediaSource with${n?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===t?se(i,s.tracks):this.sourceBuffers.forEach(r=>{const[n]=r;n&&(i[n]=se({},this.tracks[n]),this.removeBuffer(n)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var i;let s=2;(t.audio&&!t.video||!t.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(e,t){const i=this.media=t.media;this.transferData=this.overrides=void 0;const s=Ye(this.appendSource);if(s){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const n=this.mediaSource=t.mediaSource||new s;if(this.assignMediaSource(n),r)this._objectUrl=i.src,this.attachTransferred();else{const a=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{i.removeAttribute("src");const o=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||o&&n instanceof o,rl(i),Pf(i,a),i.load()}catch{i.src=a}else i.src=a}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const i=this.tracks,s=t.tracks,r=s?Object.keys(s):null,n=r?r.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&r&&n){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
|
|
72
72
|
required tracks: ${ne(i,(o,l)=>o==="initSegment"?void 0:l)};
|
|
73
|
-
transfer tracks: ${ne(s,(o,l)=>o==="initSegment"?void 0:l)}}`),!Ca(s,i)){t.mediaSource=null,t.tracks=void 0;const o=e.currentTime,l=this.details,d=Math.max(o,l?.fragments[0].start||0);if(d-o>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${o} -> ${d}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${d} currentTime: ${o}`),this.onMediaDetaching(p.MEDIA_DETACHING,{}),this.onMediaAttaching(p.MEDIA_ATTACHING,t),e.currentTime=d;return}this.transferData=void 0,r.forEach(o=>{const l=o,d=s[l];if(d){const c=d.buffer;if(c){const h=this.fragmentTracker,u=d.id;if(h.hasFragments(u)||h.hasParts(u)){const g=Y.getBuffered(c);h.detectEvictedFragments(l,g,u,null,!0)}const f=fr(l),m=[l,c];this.sourceBuffers[f]=m,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,d)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:s,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([a])=>{a&&this.removeBuffer(a)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const a=r.readyState==="open";try{const o=r.sourceBuffers;for(let l=o.length;l--;)a&&o[l].abort(),r.removeSourceBuffer(o[l]);a&&r.endOfStream()}catch(o){this.warn(`onMediaDetaching: ${o.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),i||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(s.removeAttribute("src"),this.appendSource&&rl(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(p.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var s;(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[fr(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Dd(this.tracks)}onBufferCodecs(e,t){var i;const s=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&r.some(o=>!s[o]);if(n||a){this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`);return}r.forEach(o=>{var l,d;const{id:c,codec:h,levelCodec:u,container:f,metadata:m,supplemental:g}=t[o];let y=s[o];const v=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[o],E=v!=null&&v.buffer?v:y,T=E?.pendingCodec||E?.codec,S=E?.levelCodec;y||(y=s[o]={buffer:void 0,listeners:[],codec:h,supplemental:g,container:f,levelCodec:u,metadata:m,id:c});const A=Di(T,S),b=A?.replace(sn,"$1");let I=Di(h,u);const D=(d=I)==null?void 0:d.replace(sn,"$1");I&&A&&b!==D&&(o.slice(0,5)==="audio"&&(I=Ri(I,this.appendSource)),this.log(`switching codec ${T} to ${I}`),I!==(y.pendingCodec||y.codec)&&(y.pendingCodec=I),y.container=f,this.appendChangeType(o,f,I))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){const s=`${t};codecs=${i}`,r={label:`change-type=${s}`,execute:()=>{const n=this.tracks[e];if(n){const a=n.buffer;a!=null&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${s}`),a.changeType(s),n.codec=i,n.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn(`Failed to change ${e} SourceBuffer type`,n)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,s=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,B.MAIN))==null?void 0:t.gap)===!0)return;const r={label:"block-audio",execute:()=>{var n;const a=this.tracks.video;(this.lastVideoAppendEnd>s||a!=null&&a.buffer&&Y.isBuffered(a.buffer,s)||((n=this.fragmentTracker.getAppendedFrag(s,B.MAIN))==null?void 0:n.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn("Error executing block-audio operation",n)}};this.blockedAudioAppend={op:r,frag:e},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:s,type:r,parent:n,frag:a,part:o,chunkMeta:l,offset:d}=t,c=l.buffering[r],{sn:h,cc:u}=a,f=self.performance.now();c.start=f;const m=a.stats.buffering,g=o?o.stats.buffering:null;m.start===0&&(m.start=f),g&&g.start===0&&(g.start=f);const y=i.audio;let v=!1;r==="audio"&&y?.container==="audio/mpeg"&&(v=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const E=i.video,T=E?.buffer;if(T&&h!=="initSegment"){const b=o||a,I=this.blockedAudioAppend;if(r==="audio"&&n!=="main"&&!this.blockedAudioAppend&&!(E.ending||E.ended)){const D=b.start+b.duration*.05,w=T.buffered,P=this.currentOp("video");!w.length&&!P?this.blockAudio(b):!P&&!Y.isBuffered(T,D)&&this.lastVideoAppendEnd<D&&this.blockAudio(b)}else if(r==="video"){const D=b.end;if(I){const w=I.frag.start;(D>w||D<this.lastVideoAppendEnd||Y.isBuffered(T,w))&&this.unblockAudio()}this.lastVideoAppendEnd=D}}const S=(o||a).start,A={label:`append-${r}`,execute:()=>{var b;c.executeStart=self.performance.now();const I=(b=this.tracks[r])==null?void 0:b.buffer;I&&(v?this.updateTimestampOffset(I,S,.1,r,h,u):d!==void 0&&N(d)&&this.updateTimestampOffset(I,d,1e-6,r,h,u)),this.appendExecutor(s,r)},onStart:()=>{},onComplete:()=>{const b=self.performance.now();c.executeEnd=c.end=b,m.first===0&&(m.first=b),g&&g.first===0&&(g.first=b);const I={};this.sourceBuffers.forEach(([D,w])=>{D&&(I[D]=Y.getBuffered(w))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(p.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:I})},onError:b=>{var I;const D={type:$.MEDIA_ERROR,parent:a.type,details:L.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:b,err:b,fatal:!1},w=(I=this.media)==null?void 0:I.error;if(b.code===DOMException.QUOTA_EXCEEDED_ERR||b.name=="QuotaExceededError"||"quota"in b)D.details=L.BUFFER_FULL_ERROR;else if(b.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!w)D.errorAction=Tt(!0);else if(b.name===rn&&this.sourceBufferCount===0)D.errorAction=Tt(!0);else{const P=++this.appendErrors[r];this.warn(`Failed ${P}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${w||"no media error"})`),(P>=this.hls.config.appendErrorMaxRetry||w)&&(D.fatal=!0)}this.hls.trigger(p.ERROR,D)}};this.log(`queuing "${r}" append sn: ${h}${o?" p: "+o.index:""} of ${a.type===B.MAIN?"level":"track"} ${a.level} cc: ${u}`),this.append(A,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(p.BUFFER_FLUSHED,{type:e})},onError:s=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,s)}}}onBufferFlushing(e,t){const{type:i,startOffset:s,endOffset:r}=t;i?this.append(this.getFlushOp(i,s,r),i):this.sourceBuffers.forEach(([n])=>{n&&this.append(this.getFlushOp(n,s,r),n)})}onFragParsed(e,t){const{frag:i,part:s}=t,r=[],n=s?s.elementaryStreams:i.elementaryStreams;n[re.AUDIOVIDEO]?r.push("audiovideo"):(n[re.AUDIO]&&r.push("audio"),n[re.VIDEO]&&r.push("video"));const a=()=>{const o=self.performance.now();i.stats.buffering.end=o,s&&(s.stats.buffering.end=o);const l=s?s.stats:i.stats;this.hls.trigger(p.FRAG_BUFFERED,{frag:i,part:s,stats:l,id:i.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(a,r).catch(o=>{this.warn(`Fragment buffered callback ${o}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([r])=>{if(r){const n=this.tracks[r];(!t.type||t.type===r)&&(n.ending=!0,n.ended||(n.ended=!0,this.log(`${r} buffer reached EOS`)))}});const s=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([r])=>{var n;return r&&!((n=this.tracks[r])!=null&&n.ended)})?s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:r}=this;if(!r||r.readyState!=="open"){r&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${r.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),r.endOfStream(),this.hls.trigger(p.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(p.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===L.BUFFER_APPEND_ERROR&&t.frag){var i;const s=(i=t.errorAction)==null?void 0:i.nextAutoLevel;N(s)&&s!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;const s=e.config,r=i.currentTime,n=t.levelTargetDuration,a=t.live&&s.liveBackBufferLength!==null?s.liveBackBufferLength:s.backBufferLength;if(N(a)&&a>=0){const l=Math.max(a,n),d=Math.floor(r/n)*n-l;this.flushBackBuffer(r,n,d)}const o=s.frontBufferFlushThreshold;if(N(o)&&o>0){const l=Math.max(s.maxBufferLength,o),d=Math.max(l,n),c=Math.floor(r/n)*n+d;this.flushFrontBuffer(r,n,c)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([s,r])=>{if(r){const a=Y.getBuffered(r);if(a.length>0&&i>a.start(0)){var n;this.hls.trigger(p.BACK_BUFFER_REACHED,{bufferEnd:i});const o=this.tracks[s];if((n=this.details)!=null&&n.live)this.hls.trigger(p.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(o!=null&&o.ended){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:s})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([s,r])=>{if(r){const n=Y.getBuffered(r),a=n.length;if(a<2)return;const o=n.start(a-1),l=n.end(a-1);if(i>o||e>=o&&e<=l)return;this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:s})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||i?.readyState!=="open")return null;const s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){const a=Math.max(0,t.fragmentStart);return{duration:1/0,start:a,end:Math.max(a,s)}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return N(r)?{duration:r}:null;const n=this.media.duration;return s>(N(i.duration)?i.duration:0)&&s>n||!N(n)?{duration:s}:null}updateMediaSource({duration:e,start:t,end:i}){const s=this.mediaSource;!this.media||!s||s.readyState!=="open"||(s.duration!==e&&(N(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),s.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${t}-${i}.`),s.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ne(i)}`),this.tracksReady){var s;const r=(s=this.transferData)==null?void 0:s.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,i])=>{if(t){const s=this.tracks[t];e[t]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(p.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const n=r,a=e[n];if(this.isPending(a)){const o=this.getTrackCodec(a,n),l=`${a.container};codecs=${o}`;a.codec=o,this.log(`creating sourceBuffer(${l})${this.currentOp(n)?" Queued":""} ${ne(a)}`);try{const d=i.addSourceBuffer(l),c=fr(n);t[c]=[n,d],a.buffer=d}catch(d){var s;this.error(`error while trying to add sourceBuffer: ${d.message}`),this.shiftAndExecuteNext(n),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[n],this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:d,sourceBufferName:n,mimeType:l,parent:a.id});return}this.trackSourceBuffer(n,a)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let s=e.codec;i&&(t==="video"||t==="audiovideo")&&Ut(i,"video")&&(s=du(s,i));const r=Di(s,e.levelCodec);return r?t.slice(0,5)==="audio"?Ri(r,this.appendSource):r:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const s=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:s,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,n)=>{const a=n.removedRanges;a!=null&&a.length&&this.hls.trigger(p.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;const i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i?.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const s=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${s}`,t),this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});const r=this.currentOp(e);r&&r.onError(s)}updateTimestampOffset(e,t,i,s,r,n){const a=t-e.timestampOffset;Math.abs(a)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,i){const{media:s,mediaSource:r}=this,n=this.tracks[e],a=n?.buffer;if(!s||!r||!a){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const o=N(s.duration)?s.duration:1/0,l=N(r.duration)?r.duration:1/0,d=Math.max(0,t),c=Math.min(i,o,l);c>d&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${d},${c}] from the ${e} SourceBuffer`),a.remove(d,c)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],s=i?.buffer;if(!s)throw new Pd(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,s.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,s=t.map(r=>this.appendBlocker(r));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then(r=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;const s=(i=this.tracks[t])==null?void 0:i.buffer;!s||s.updating||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const s=this.tracks[e];if(!s)return;const r=s.buffer;if(!r)return;const n=i.bind(this,e);s.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(s=>{i.removeEventListener(s.event,s.listener)}),t.listeners.length=0)}},an=class Yc{constructor(t){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=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(p.MANIFEST_PARSED,this.onManifestParsed,this),t.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(p.BUFFER_CODECS,this.onBufferCodecs,this),t.on(p.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(p.MANIFEST_PARSED,this.onManifestParsed,this),t.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(p.BUFFER_CODECS,this.onBufferCodecs,this),t.off(p.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,i){const s=this.hls.levels[i.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(t,i){this.media=i.media instanceof HTMLVideoElement?i.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,i){const s=this.hls;this.restrictedLevels=[],this.firstLevel=i.firstLevel,s.config.capLevelToPlayerSize&&i.video&&this.startCapping()}onLevelsUpdated(t,i){this.timer&&N(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,i){this.hls.config.capLevelToPlayerSize&&i.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const t=this.hls.levels;if(t.length){const i=this.hls,s=this.getMaxLevel(t.length-1);s!==this.autoLevelCapping&&i.logger.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),i.autoLevelCapping=s,i.autoLevelEnabled&&i.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=i.autoLevelCapping}}}getMaxLevel(t){const i=this.hls.levels;if(!i.length)return-1;const s=i.filter((r,n)=>this.isLevelAllowed(r)&&n<=t);return this.clientRect=null,Yc.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,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;const t=this.media,i={width:0,height:0};if(t){const s=t.getBoundingClientRect();i.width=s.width,i.height=s.height,!i.width&&!i.height&&(i.width=s.right-s.left||t.width||0,i.height=s.bottom-s.top||t.height||0)}return this.clientRect=i,i}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch{}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(i=>t.bitrate===i.bitrate&&t.width===i.width&&t.height===i.height)}static getMaxLevelByMediaSize(t,i,s){if(!(t!=null&&t.length))return-1;const r=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let n=t.length-1;const a=Math.max(i,s);for(let o=0;o<t.length;o+=1){const l=t[o];if((l.width>=a||l.height>=a)&&r(l,t[o+1])){n=o;break}}return n}},be={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},wd={HLS:"h"},tt=class kn{constructor(t,i){Array.isArray(t)&&(t=t.map(s=>s instanceof kn?s:new kn(s))),this.value=t,this.params=i}},_d="Dict",on=class{constructor(e){this.description=e}},ln="Bare Item",kd="Boolean",Cd="Byte Sequence",xd="Integer",Md="Decimal",Od="String",Fd=/[\x00-\x1f\x7f]+/,Nd="Token",Ud="Key",Oe="CMCD-Object",le="CMCD-Request",it="CMCD-Session",Je="CMCD-Status",Bd={br:Oe,ab:Oe,d:Oe,ot:Oe,tb:Oe,tpb:Oe,lb:Oe,tab:Oe,lab:Oe,url:Oe,pb:le,bl:le,tbl:le,dl:le,ltc:le,mtp:le,nor:le,nrr:le,rc:le,sn:le,sta:le,su:le,ttfb:le,ttfbb:le,ttlb:le,cmsdd:le,cmsds:le,smrt:le,df:le,cs:le,ts:le,cid:it,pr:it,sf:it,sid:it,st:it,v:it,msd:it,bs:Je,bsd:Je,cdn:Je,rtp:Je,bg:Je,pt:Je,ec:Je,e:Je},$d={REQUEST:le},dn="event",ri=e=>Math.round(e),as=(e,t)=>Array.isArray(e)?e.map(i=>as(i,t)):e instanceof tt&&typeof e.value=="string"?new tt(as(e.value,t),e.params):(t.baseUrl&&(e=jf(e,t.baseUrl)),t.version===1?encodeURIComponent(e):e),ni=e=>ri(e/100)*100,Gd=(e,t)=>{let i=e;return t.version>=2&&(e instanceof tt&&typeof e.value=="string"?i=new tt([e]):typeof e=="string"&&(i=[e])),as(i,t)},Vd={br:ri,d:ri,bl:ni,dl:ni,mtp:ni,nor:Gd,rtp:ni,tb:ri},cn="request",hn="response",os=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],Kd=["e"],Hd=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/,un=["d","dl","nor","ot","rtp","su"],Wd=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],jd=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Yd={[hn]:qf,[dn]:Yf,[cn]:zf},zd="CMCD",fn=/CMCD=[^&#]+/,gn=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.includeKeys=void 0,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=s=>{try{this.apply(s,{ot:be.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=s=>{try{const{frag:r,part:n}=s,a=this.hls.levels[r.level],o=this.getObjectType(r),l={d:(n||r).duration*1e3,ot:o};(o===be.VIDEO||o===be.AUDIO||o==be.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o));const d=n?this.getNextPart(n):this.getNextFrag(r);d!=null&&d.url&&d.url!==r.url&&(l.nor=d.url),this.apply(s,l)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=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,s;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(s=t.tracks.video)==null?void 0:s.buffer}createData(){var e;return{v:1,sf:wd.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){se(t,this.createData());const i=t.ot===be.INIT||t.ot===be.VIDEO||t.ot===be.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:s}=this;s&&(t=Object.keys(t).reduce((n,a)=>(s.includes(a)&&(n[a]=t[a]),n),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Zf(e.headers,t,r)):e.url=ig(e.url,t,r)}getNextFrag(e){var t;const i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){const s=e.sn-i.startSN;return i.fragments[s+1]}}getNextPart(e){var t;const{index:i,fragment:s}=e,r=(t=this.hls.levels[s.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:n}=s;for(let a=r.length-1;a>=0;a--){const o=r[a];if(o.index===i&&o.fragment.sn===n)return r[a+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return be.TIMED_TEXT;if(e.sn==="initSegment")return be.INIT;if(t==="audio")return be.AUDIO;if(t==="main")return this.hls.audioTracks.length?be.VIDEO:be.MUXED}getTopBandwidth(e){let t=0,i;const s=this.hls;if(e===be.AUDIO)i=s.audioTracks;else{const r=s.maxAutoLevel,n=r>-1?r+1:s.levels.length;i=s.levels.slice(0,n)}return i.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,i=e===be.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:Y.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,a){t(r),this.loader.load(r,n,a)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,a){t(r),this.loader.load(r,n,a)}}}},qd=3e5,mn=class extends we{constructor(e){super("content-steering",e.logger),this.hls=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.registerListeners()}registerListeners(){const e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const 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){const{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){const{errorAction:i}=t;if(i?.action===ce.SendAlternateToPenaltyBox&&i.flags===Te.MoveAllAlternatesMatchingHost){const s=this.levels;let r=this._pathwayPriority,n=this.pathwayId;if(t.context){const{groupId:a,pathwayId:o,type:l}=t.context;a&&s?n=this.getPathwayForGroupId(a,l,n):o&&(n=o)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!r&&s&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==n),t.details===L.BUFFER_APPEND_ERROR&&!t.fatal?i.resolved=!0:i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${n} levels: ${s&&s.length} priorities: ${ne(r)} penalized: ${ne(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const 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}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(r=>{s-i[r]>qd&&delete i[r]});for(let r=0;r<e.length;r++){const n=e[r];if(n in i)continue;if(n===this.pathwayId)return;const a=this.hls.nextLoadLevel,o=this.hls.levels[a];if(t=this.getLevelsForPathway(n),t.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,Co(t),this.hls.trigger(p.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[a];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let r=0;r<s.length;r++)if(t===q.AUDIO_TRACK&&s[r].hasAudioGroup(e)||t===q.SUBTITLE_TRACK&&s[r].hasSubtitleGroup(e))return s[r].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},s={};e.forEach(r=>{const{ID:n,"BASE-ID":a,"URI-REPLACEMENT":o}=r;if(t.some(d=>d.pathwayId===n))return;const l=this.getLevelsForPathway(a).map(d=>{const c=new oe(d.attrs);c["PATHWAY-ID"]=n;const h=c.AUDIO&&`${c.AUDIO}_clone_${n}`,u=c.SUBTITLES&&`${c.SUBTITLES}_clone_${n}`;h&&(i[c.AUDIO]=h,c.AUDIO=h),u&&(s[c.SUBTITLES]=u,c.SUBTITLES=u);const f=ul(d.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),m=new ht({attrs:c,audioCodec:d.audioCodec,bitrate:d.bitrate,height:d.height,name:d.name,url:f,videoCodec:d.videoCodec,width:d.width});if(d.audioGroups)for(let g=1;g<d.audioGroups.length;g++)m.addGroupId("audio",`${d.audioGroups[g]}_clone_${n}`);if(d.subtitleGroups)for(let g=1;g<d.subtitleGroups.length;g++)m.addGroupId("text",`${d.subtitleGroups[g]}_clone_${n}`);return m});t.push(...l),hl(this.audioTracks,i,o,n),hl(this.subtitleTracks,s,o,n)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let s;try{s=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(s.protocol!=="data:"){const d=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+d)}const r={responseType:"json",url:s.href},n=t.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(d,c,h,u)=>{this.log(`Loaded steering manifest: "${s}"`);const f=d.data;if(f?.VERSION!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":m,"PATHWAY-CLONES":g,"PATHWAY-PRIORITY":y}=f;if(m)try{this.uri=new self.URL(m,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||h.url),g&&this.clonePathways(g);const v={steeringManifest:f,url:s.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,v),y&&this.updatePathwayPriority(y)},onError:(d,c,h,u)=>{if(this.log(`Error loading steering manifest: ${d.code} ${d.text} (${c.url})`),this.stopLoad(),d.code===410){this.enabled=!1,this.log(`Steering manifest ${c.url} no longer available`);return}let f=this.timeToLoad*1e3;if(d.code===429){const m=this.loader;if(typeof m?.getResponseHeader=="function"){const g=m.getResponseHeader("Retry-After");g&&(f=parseFloat(g)*1e3)}this.log(`Steering manifest ${c.url} rate limited`);return}this.scheduleRefresh(this.uri||c.url,f)},onTimeout:(d,c,h)=>{this.log(`Timeout loading steering manifest (${c.url})`),this.scheduleRefresh(this.uri||c.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,o,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const s=(i=this.hls)==null?void 0:i.media;if(s&&!s.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}},ls=class vs extends we{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=vs.CDMCleanupPromise?[vs.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=i=>{const{initDataType:s,initData:r}=i,n=`"${i.type}" event: init data type: "${s}"`;if(this.debug(n),r!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=$t(this.config));const o=a.map(Js).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=Mi(a);if(s!=="sinf"||o!==ae.FAIRPLAY){this.log(`Ignoring "${i.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let l;try{const f=ue(new Uint8Array(r)),m=$a(Qs(JSON.parse(f).sinf));if(!m)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(m.subarray(8,24))}catch(f){this.warn(`${n} Failed to parse sinf: ${f}`);return}const d=ye(l),{keyIdToKeySessionPromise:c,mediaKeySessions:h}=this;let u=c[d];for(let f=0;f<h.length;f++){const m=h[f],g=m.decryptdata;if(!g.keyId)continue;const y=ye(g.keyId);if(xi(l,g.keyId)||g.uri.replace(/-/g,"").indexOf(d)!==-1){if(u=c[y],!u)continue;if(g.pssh)break;delete c[y],g.pssh=new Uint8Array(r),g.keyId=l,u=c[d]=u.then(()=>this.generateRequestWithPreferredKeySession(m,s,r,"encrypted-event-key-match")),u.catch(v=>this.handleError(v));break}}u||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${h.length}.`))}).catch(a=>this.handleError(a))}},this.onWaitingForKey=i=>{this.log(`"${i.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(p.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(p.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:i,widevineLicenseUrl:s}=this.config,r=i?.[t];if(r)return r.licenseUrl;if(t===ae.WIDEVINE&&s)return s}getLicenseServerUrlOrThrow(t){const i=this.getLicenseServerUrl(t);if(i===void 0)throw new Error(`no license server URL configured for key-system "${t}"`);return i}getServerCertificateUrl(t){const{drmSystems:i}=this.config,s=i?.[t];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const i=this.hls.levels,s=(a,o,l)=>!!a&&l.indexOf(a)===o,r=i.map(a=>a.audioCodec).filter(s),n=i.map(a=>a.videoCodec).filter(s);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{const l=d=>{const c=d.shift();this.getMediaKeysPromise(c,r,n).then(h=>a({keySystem:c,mediaKeys:h})).catch(h=>{d.length?l(d):h instanceof Re?o(h):o(new Re({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};l(t)})}requestMediaKeySystemAccess(t,i){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${s}`;return Ji===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return s(t,i)}getMediaKeysPromise(t,i,s){var r;const n=Nu(t,i,s,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[t],o=(r=a)==null?void 0:r.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${t}" key-system access with config: ${ne(n)}`),o=this.requestMediaKeySystemAccess(t,n);const l=a=this.keySystemAccessPromises[t]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${t}": ${d}`)}),o.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);const c=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const h=l.mediaKeys=d.createMediaKeys().then(u=>(this.log(`Media-keys created for "${t}"`),l.hasMediaKeys=!0,c.then(f=>f?this.setMediaKeysServerCertificate(u,t,f):u)));return h.catch(u=>{this.error(`Failed to create media-keys for "${t}"}: ${u}`)}),h})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:i,mediaKeys:s}){this.log(`Creating key-system session "${i}" keyId: ${ye(t.keyId||[])} keyUri: ${t.uri}`);const r={decryptdata:t,keySystem:i,mediaKeys:s,mediaKeysSession:s.createSession(),keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(t){const i=t.decryptdata;if(i.pssh){const s=this.createMediaKeySessionContext(t),r=$i(i),n="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(s,n,i.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,i){const s=t.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${ye(t.decryptdata.keyId||[])}
|
|
74
|
-
} (data length: ${i.byteLength})`),s.update(i)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>Js(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:i,mediaKeys:s})=>this.attemptSetMediaKeys(i,s))}selectKeySystem(t){return new Promise((i,s)=>{this.getKeySystemSelectionPromise(t).then(({keySystem:r})=>{const n=Js(r);n?i(n):s(new Error(`Unable to find format for key-system "${r}"`))}).catch(s)})}selectKeySystemFormat(t){const i=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)),this.keyFormatPromise}getKeyFormatPromise(t){const i=$t(this.config),s=t.map(Mi).filter(r=>!!r&&i.indexOf(r)!==-1);return this.selectKeySystem(s)}getKeyStatus(t){const{mediaKeySessions:i}=this;for(let s=0;s<i.length;s++){const r=sg(t,i[s]);if(r)return r}}loadKey(t){const i=t.keyInfo.decryptdata,s=$i(i),r=this.bannedKeyIds[s];if(r||this.getKeyStatus(i)==="internal-error"){const o=fl(r||"internal-error",i);return this.handleError(o,t.frag),Promise.reject(o)}const n=`(keyId: ${s} format: "${i.keyFormat}" method: ${i.method} uri: ${i.uri})`;this.log(`Starting session for key ${n}`);const a=this.keyIdToKeySessionPromise[s];if(!a){const o=this.getKeySystemForKeyPromise(i).then(({keySystem:l,mediaKeys:d})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${n}`),this.attemptSetMediaKeys(l,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:l,mediaKeys:d,decryptdata:i}))))).then(l=>{const d="cenc",c=i.pssh?i.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(l,d,c,"playlist-key")});return o.catch(l=>this.handleError(l,t.frag)),this.keyIdToKeySessionPromise[s]=o,o}return a.catch(o=>{if(o instanceof Re){const l=ie({},o.data);this.getKeyStatus(i)==="internal-error"&&(l.decryptdata=i);const d=new Re(l,o.message);this.handleError(d,t.frag)}}),a}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,i){if(this.hls)if(t instanceof Re){i&&(t.data.frag=i);const s=t.data.decryptdata;this.error(`${t.message}${s?` (${ye(s.keyId||[])})`:""}`),this.hls.trigger(p.ERROR,t.data)}else this.error(t.message),this.hls.trigger(p.ERROR,{type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const i=$i(t),s=this.keyIdToKeySessionPromise[i];if(!s){const r=Mi(t.keyFormat),n=r?[r]:$t(this.config);return this.attemptKeySystemAccess(n)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=$t(this.config)),t.length===0)throw new Re({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ne({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,i){if(this.mediaResolved=void 0,this.mediaKeys===i)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const r=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(i):new Promise((n,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=i,this.media.setMediaKeys(i).then(n).catch(a)}}));return this.mediaKeys=i,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${t}"`),s.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>s.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(t,i,s,r){var n;const a=(n=this.config.drmSystems)==null||(n=n[t.keySystem])==null?void 0:n.generateRequest;if(a)try{const m=a.call(this.hls,i,s,t);if(!m)throw new Error("Invalid response from configured generateRequest filter");i=m.initDataType,s=m.initData?m.initData:null,t.decryptdata.pssh=s?new Uint8Array(s):null}catch(m){if(this.warn(m.message),this.hls&&this.hls.config.debug)throw m}if(s===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t);const o=$i(t.decryptdata),l=t.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${o} URI: ${l} (init data type: ${i} length: ${s.byteLength})`);const d=new is,c=t._onmessage=m=>{const g=t.mediaKeysSession;if(!g){d.emit("error",new Error("invalid state"));return}const{messageType:y,message:v}=m;this.log(`"${y}" message event for session "${g.sessionId}" message size: ${v.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(t,v).catch(E=>{d.eventNames().length?d.emit("error",E):this.handleError(E)}):y==="license-release"?t.keySystem===ae.FAIRPLAY&&this.updateKeySession(t,Zs("acknowledged")).then(()=>this.removeSession(t)).catch(E=>this.handleError(E)):this.warn(`unhandled media key message type "${y}"`)},h=(m,g)=>{g.keyStatus=m;let y;m.startsWith("usable")?d.emit("resolved"):m==="internal-error"||m==="output-restricted"||m==="output-downscaled"?y=fl(m,g.decryptdata):m==="expired"?y=new Error(`key expired (keyId: ${o})`):m==="released"?y=new Error("key released"):m==="status-pending"||this.warn(`unhandled key status change "${m}" (keyId: ${o})`),y&&(d.eventNames().length?d.emit("error",y):this.handleError(y))},u=t._onkeystatuseschange=m=>{if(!t.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const g=this.getKeyStatuses(t);if(!Object.keys(g).some(E=>g[E]!=="status-pending"))return;if(g[o]==="expired"){this.log(`Expired key ${ne(g)} in key-session "${t.mediaKeysSession.sessionId}"`),this.renewKeySession(t);return}let y=g[o];if(y)h(y,t);else{var v;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(v=t.keyStatusTimeouts)[o]||(v[o]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const T=this.getKeyStatus(t.decryptdata);if(T&&T!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${T} from other session.`),h(T,t);this.log(`key status for ${o} in key-session "${t.mediaKeysSession.sessionId}" timed out after 1000ms`),y="internal-error",h(y,t)},1e3)),this.log(`No status for keyId ${o} (${ne(g)}).`)}};Ee(t.mediaKeysSession,"message",c),Ee(t.mediaKeysSession,"keystatuseschange",u);const f=new Promise((m,g)=>{d.on("error",g),d.on("resolved",m)});return t.mediaKeysSession.generateRequest(i,s).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${o} URI: ${l}`)}).catch(m=>{throw new Re({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_SESSION,error:m,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>(d.removeAllListeners(),this.removeSession(t).then(()=>{throw m}))).then(()=>(d.removeAllListeners(),t))}getKeyStatuses(t){const i={};return t.mediaKeysSession.keyStatuses.forEach((s,r)=>{if(typeof r=="string"&&typeof s=="object"){const o=r;r=s,s=o}const n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(t.keySystem===ae.PLAYREADY&&n.length===16){const o=ye(n);i[o]=s,fo(n)}const a=ye(n);s==="internal-error"&&(this.bannedKeyIds[a]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${a} key-session "${t.mediaKeysSession.sessionId}"`),i[a]=s}),i}fetchServerCertificate(t){const i=this.config,s=i.loader,r=new s(i),n=this.getServerCertificateUrl(t);return n?(this.log(`Fetching server certificate for "${t}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:n},d=i.certLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};r.load(l,c,{onSuccess:(h,u,f,m)=>{a(h.data)},onError:(h,u,f,m)=>{o(new Re({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:ie({url:l.url,data:void 0},h)},`"${t}" certificate request failed (${n}). Status: ${h.code} (${h.text})`))},onTimeout:(h,u,f)=>{o(new Re({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:l.url,data:void 0}},`"${t}" certificate request timed out (${n})`))},onAbort:(h,u,f)=>{o(new Error("aborted"))}})})):Promise.resolve()}setMediaKeysServerCertificate(t,i,s){return new Promise((r,n)=>{t.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${i}"`),r(t)}).catch(a=>{n(new Re({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(t,i){return this.requestLicense(t,new Uint8Array(i)).then(s=>this.updateKeySession(t,new Uint8Array(s)).catch(r=>{throw new Re({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:r,fatal:!1},r.message)}))}unpackPlayReadyKeyMessage(t,i){const s=String.fromCharCode.apply(null,new Uint16Array(i.buffer));if(!s.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),i;const r=new DOMParser().parseFromString(s,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let c;for(let h=0,u=n.length;h<u;h++){var a,o;c=n[h];const f=(a=c.querySelector("name"))==null?void 0:a.textContent,m=(o=c.querySelector("value"))==null?void 0:o.textContent;f&&m&&t.setRequestHeader(f,m)}}const l=r.querySelector("Challenge"),d=l?.textContent;if(!d)throw new Error("Cannot find <Challenge> in key message");return Zs(atob(d))}setupLicenseXHR(t,i,s,r){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return n.call(this.hls,t,i,s,r)}).catch(a=>{if(!s.decryptdata)throw a;return t.open("POST",i,!0),n.call(this.hls,t,i,s,r)}).then(a=>(t.readyState||t.open("POST",i,!0),{xhr:t,licenseChallenge:a||r})):(t.open("POST",i,!0),Promise.resolve({xhr:t,licenseChallenge:r}))}requestLicense(t,i){const s=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{const a=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return n(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}`);const d=this.config.licenseResponseCallback;if(d)try{l=d.call(this.hls,o,a,t)}catch(c){this.error(c)}r(l)}else{const l=s.errorRetry,d=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||o.status>=400&&o.status<500)n(new Re({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const c=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${c} attempts left`),this.requestLicense(t,i).then(r,n)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,this.setupLicenseXHR(o,a,t,i).then(({xhr:l,licenseChallenge:d})=>{t.keySystem==ae.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(l,d)),l.send(d)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,i){if(!this.config.emeEnabled)return;const s=i.media;this.media=s,Ee(s,"encrypted",this.onMediaEncrypted),Ee(s,"waitingforkey",this.onWaitingForKey);const r=this.mediaResolved;r?r():this.mediaKeys=s.mediaKeys}onMediaDetached(){const t=this.media;t&&(Le(t,"encrypted",this.onMediaEncrypted),Le(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const i=this.mediaResolved;if(i&&i(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Pt.clearKeyUriToKeyIdMap();const n=r.length;vs.CDMCleanupPromise=Promise.all(r.map(a=>this.removeSession(a)).concat((s==null||(t=s.setMediaKeys(null))==null?void 0:t.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(t,{sessionKeys:i}){if(!(!i||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=i.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(t){const{mediaKeysSession:i,licenseXhr:s,decryptdata:r}=t;if(i){this.log(`Remove licenses and keys and close session "${i.sessionId}" keyId: ${ye(r?.keyId||[])}`),t._onmessage&&(i.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(i.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const n=this.mediaKeySessions.indexOf(t);n>-1&&this.mediaKeySessions.splice(n,1);const{keyStatusTimeouts:a}=t;a&&Object.keys(a).forEach(l=>self.clearTimeout(a[l]));const{drmSystemOptions:o}=this.config;return(Bu(o)?new Promise((l,d)=>{self.setTimeout(()=>d(new Error("MediaKeySession.remove() timeout")),8e3),i.remove().then(l).catch(d)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>i.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}},ls.CDMCleanupPromise=void 0,Re=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}},pn=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(p.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(p.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(p.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const s=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){const s=performance.now();if(t){if(this.lastTime){const r=s-this.lastTime,n=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*n/r,l=this.hls;if(l.trigger(p.FPS_DROP,{currentDropped:n,currentDecoded:a,totalDroppedFrames:i}),o>0&&n>l.config.fpsDroppedMonitoringThreshold*a){let d=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=d)&&(d=d-1,l.trigger(p.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:l.currentLevel}),l.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},yn=class extends si{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const i=Gi(this.media.textTracks);for(let r=0;r<i.length;r++)if(i[r].mode==="hidden")t=i[r];else if(i[r].mode==="showing"){t=i[r];break}const s=this.findTrackForTextTrack(t);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const s=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,!s&&Gi(i.textTracks).forEach(r=>{At(r)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:s,details:r}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==s){this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${n?.groupId}`);return}const a=n.details;n.details=t.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||s?.length!==i?.length||i!=null&&i.some(n=>s?.indexOf(n)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const n=this.tracks.filter(d=>!i||i.indexOf(d.groupId)!==-1);if(n.length)this.selectDefaultTrack&&!n.some(d=>d.default)&&(this.selectDefaultTrack=!1),n.forEach((d,c)=>{d.id=c});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=n;const a=this.hls.config.subtitlePreference;if(!r&&a){this.selectDefaultTrack=!1;const d=Be(a,n);if(d>-1)r=n[d];else{const c=Be(a,this.tracks);r=this.tracks[c]}}let o=this.findTrackId(r);o===-1&&r&&(o=this.findTrackId(null));const l={subtitleTracks:n};this.log(`Updating subtitle tracks, ${n.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger(p.SUBTITLE_TRACKS_UPDATED,l),o!==-1&&this.trackId===-1&&this.setSubtitleTrack(o)}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<t.length;s++){const r=t[s];if(!(i&&!r.default||!i&&!e)&&(!e||at(r,e)))return s}if(e){for(let s=0;s<t.length;s++){const r=t[s];if(Wt(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const r=t[s];if(Wt(e.attrs,r.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if(ur(s,e))return i}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===q.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&at(e,i))return i;const s=Be(e,this.tracksInGroup);if(s>-1){const r=this.tracksInGroup[s];return this.setSubtitleTrack(s),r}else{if(i)return null;{const r=Be(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,s=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=n?.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(p.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Gi(e.textTracks),i=this.currentTrack;let s;if(i&&(s=t.filter(r=>ur(i,r))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==s&&(r.mode="disabled")}),s){const r=this.subtitleDisplay?"showing":"hidden";s.mode!==r&&(s.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!N(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e]||null;if(this.trackId=e,this.currentTrack=s,this.toggleTrackModes(),!s){this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!s.details&&!s.details.live;if(e===this.trackId&&s===i&&r)return;this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:d}=s;this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:d});const c=this.switchParams(s.url,i?.details,s.details);this.loadPlaylist(c)}},pt=.025,ai=(function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e})({}),Xd=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const i=this.playoutLimit;return e<=0||isNaN(i)?!1:i===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return vr(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-vr(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=N(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return vr(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<pt))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?ai.Range:ai.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return lg(this)}},Qd=class{constructor(e,t,i,s){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(p.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=i,this.assetItem=s;const n=()=>{this.hasDetails=!0};r.once(p.LEVEL_LOADED,n),r.once(p.AUDIO_TRACK_LOADED,n),r.once(p.SUBTITLE_TRACK_LOADED,n),r.on(p.MEDIA_ATTACHING,(a,{media:o})=>{this.removeMediaListeners(),this.mediaAttached=o,this.interstitial.playoutLimit&&(o.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(p.BUFFER_APPENDED,()=>{const l=this.bufferedEnd;this.reachedPlayout(l)&&(this._bufferedEosTime=l,r.trigger(p.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=pl(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),s=this.timelineOffset,r=Y.bufferInfo(e,s,0);return this.getAssetTime(r.end)>=i-.02}reachedPlayout(e){const t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=Y.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const i=e-t;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=i=>delete i.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var s;(s=this.hls)==null||s.on(e,t)}once(e,t,i){var s;(s=this.hls)==null||s.once(e,t)}off(e,t,i){var s;(s=this.hls)==null||s.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Lt(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},vn=.033,Zd=class extends we{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,s)=>e<=s.startOffset&&t>s.startOffset?(delete s.error,i+1):i,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);const s=this.items;if(s)for(s[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(r=s[i])!=null&&r.event;){var r;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let s=0;s<i.length;s++){let r=i[s];if(t&&t!=="primary"&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return s}return-1}findJumpRestrictedIndex(e,t){const i=this.items;if(i)for(let s=e;s<=t&&i[s];s++){const r=i[s].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return s}return-1}findEventIndex(e){const t=this.items;if(t)for(let s=t.length;s--;){var i;if(((i=t[s].event)==null?void 0:i.identifier)===e)return s}return-1}findAssetIndex(e,t){const i=e.assetList,s=i.length;if(s>1)for(let r=0;r<s;r++){const n=i[r];if(!n.error){const a=n.timelineStart;if(t===a||t>a&&(t<a+(n.duration||0)||r===s-1))return r}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const i=t.assetList,s=i[i.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t){const i=e.main.details,{dateRanges:s}=i,r=this.events,n=this.parseDateRanges(s,{url:i.url},t),a=Object.keys(s),o=r?r.filter(l=>!a.includes(l.identifier)):[];n.length&&n.sort((l,d)=>{const c=l.cue.pre,h=l.cue.post,u=d.cue.pre,f=d.cue.post;if(c&&!u)return-1;if(u&&!c||h&&!f)return 1;if(f&&!h)return-1;if(!c&&!u&&!h&&!f){const m=l.startTime,g=d.startTime;if(m!==g)return m-g}return l.dateRange.tagOrder-d.dateRange.tagOrder}),this.events=n,o.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,o)}updateSchedule(e,t=[],i=!1){const s=this.events||[];if(s.length||t.length||this.length<2){const r=this.items,n=this.parseSchedule(s,e);(i||t.length||r?.length!==n.length||n.some((a,o)=>Math.abs(a.playout.start-r[o].playout.start)>.005||Math.abs(a.playout.end-r[o].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,i){const s=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const a=r[n],o=e[a];if(o.isInterstitial){let l=this.eventMap[a];l?l.setDateRange(o):(l=new Xd(o,t),this.eventMap[a]=l,i===!1&&(l.appendInPlace=i)),s.push(l)}}return s}parseSchedule(e,t){const i=[],s=t.main.details,r=s.live?1/0:s.edge;let n=0;if(e=e.filter(o=>!o.error&&!(o.cue.once&&o.hasPlayed)),e.length){this.resolveOffsets(e,t);let o=0,l=0;if(e.forEach((d,c)=>{const h=d.cue.pre,u=d.cue.post,f=e[c-1]||null,m=d.appendInPlace,g=u?r:d.startOffset,y=d.duration,v=d.timelineOccupancy===ai.Range?y:0,E=d.resumptionOffset,T=f?.startTime===g,S=g+d.cumulativeDuration;let A=m?S+y:g+E;if(h||!u&&g<=0){const I=l;l+=v,d.timelineStart=S;const D=n;n+=y,i.push({event:d,start:S,end:A,playout:{start:D,end:n},integrated:{start:I,end:l}})}else if(g<=r){if(!T){const w=g-o;if(w>vn){const P=o,x=l;l+=w;const U=n;n+=w;const O={previousEvent:e[c-1]||null,nextEvent:d,start:P,end:P+w,playout:{start:U,end:n},integrated:{start:x,end:l}};i.push(O)}else w>0&&f&&(f.cumulativeDuration+=w,i[i.length-1].end=g)}u&&(A=S),d.timelineStart=S;const I=l;l+=v;const D=n;n+=y,i.push({event:d,start:S,end:A,playout:{start:D,end:n},integrated:{start:I,end:l}})}else return;const b=d.resumeTime;u||b>r?o=r:o=b}),o<r){var a;const d=o,c=l,h=r-o;l+=h;const u=n;n+=h,i.push({previousEvent:((a=i[i.length-1])==null?void 0:a.event)||null,nextEvent:null,start:o,end:d+h,playout:{start:u,end:n},integrated:{start:c,end:l}})}this.setDurations(r,n,l)}else i.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return i}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){const i=t.main.details,s=i.live?1/0:i.edge;let r=0,n=-1;e.forEach((a,o)=>{const l=a.cue.pre,d=a.cue.post,c=l?0:d?s:a.startTime;this.updateAssetDurations(a),n===c?a.cumulativeDuration=r:(r=0,n=c),!d&&a.snapOptions.in&&(a.resumeAnchor=lt(null,i.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)),!a.appendInPlace&&o+1<e.length&&e[o+1].startTime-e[o].resumeTime<vn&&(e[o+1].appendInPlace=!1,e[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`));const h=N(a.resumeOffset)?a.resumeOffset:a.duration;r+=h})}primaryCanResumeInPlaceAt(e,t){const i=e.resumeTime,s=e.startTime+e.resumptionOffset;return Math.abs(i-s)>pt?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1):!Object.keys(t).some(r=>{const n=t[r].details,a=n.edge;if(i>=a)return this.log(`"${e.identifier}" resumption ${i} past ${r} playlist end ${a}`),!1;const o=lt(null,n.fragments,i);if(!o)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${r} playlist (${n.fragStart}-${n.fragmentEnd})`),!0;const l=r==="audio"?.175:0;return Math.abs(o.start-i)<pt+l||Math.abs(o.end-i)<pt+l?!1:(this.log(`"${e.identifier}" resumption ${i} not aligned with ${r} fragment bounds (${o.start}-${o.end} sn: ${o.sn} cc: ${o.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let i=0,s=!1,r=!1;for(let n=0;n<e.assetList.length;n++){const a=e.assetList[n],o=t+i;a.startOffset=i,a.timelineStart=o,s||(s=a.duration===null),r||(r=!!a.error);const l=a.error?0:a.duration||0;i+=l}s&&!r?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}},Jd=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const i=e.assetListUrl;let s;try{s=pl(i,this.hls.sessionId,e.baseUrl)}catch(c){const h=this.assignAssetListError(e,L.ASSET_LIST_LOAD_ERROR,c,i);this.hls.trigger(p.ERROR,h);return}t&&s.protocol!=="data:"&&s.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,n=r.loader,a=new n(r),o={responseType:"json",url:s.href},l=r.interstitialAssetListLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};return a.load(o,d,{onSuccess:(c,h,u,f)=>{const m=c.data,g=m?.ASSETS;if(!Array.isArray(g)){const y=this.assignAssetListError(e,L.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),u.url,h,f);this.hls.trigger(p.ERROR,y);return}e.assetListResponse=m,this.hls.trigger(p.ASSET_LIST_LOADED,{event:e,assetListResponse:m,networkDetails:f})},onError:(c,h,u,f)=>{const m=this.assignAssetListError(e,L.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${c.code} ${c.text} (${h.url})`),h.url,f,u);this.hls.trigger(p.ERROR,m)},onTimeout:(c,h,u)=>{const f=this.assignAssetListError(e,L.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${h.url})`),h.url,c,u);this.hls.trigger(p.ERROR,f)}}),this.hls.trigger(p.ASSET_LIST_LOADING,{event:e}),a}assignAssetListError(e,t,i,s,r,n){return e.error=i,{type:$.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:s,error:i,networkDetails:n,stats:r}}},ec=class extends we{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;const s=i-this.timelinePos;if(Math.abs(s)<1/7056e5)return;const r=s<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=i,this.bufferedPos=i;const n=this.playingItem;if(!n){this.checkBuffer();return}if(r&&this.schedule.resetErrorsInRange(i,i-s)&&this.updateSchedule(!0),this.checkBuffer(),r&&i<n.start||i>=n.end){var a;const h=this.findItemIndex(n);let u=this.schedule.findItemIndexAtTime(i);if(u===-1&&(u=h+(r?-1:1),this.log(`seeked ${r?"back ":""}to position not covered by schedule ${i} (resolving from ${h} to ${u})`)),!this.isInterstitial(n)&&(a=this.media)!=null&&a.paused&&(this.shouldPlay=!1),!r&&u>h){const f=this.schedule.findJumpRestrictedIndex(h+1,u);if(f>h){this.setSchedulePosition(f);return}}this.setSchedulePosition(u);return}const o=this.playingAsset;if(!o){if(this.playingLastItem&&this.isInterstitial(n)){const h=n.event.assetList[0];h&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,h))}return}const l=o.timelineStart,d=o.duration||0;if(r&&i<l||i>=l+d){var c;(c=n.event)!=null&&c.appendInPlace&&(this.clearAssetPlayers(n.event,n),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,o)}},this.onTimeupdate=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;const s=this.playingItem;if(!s||this.playingLastItem)return;if(i>=s.end){this.timelinePos=s.end;const n=this.findItemIndex(s);this.setSchedulePosition(n+1)}const r=this.playingAsset;r&&i>=r.timelineStart+(r.duration||0)&&this.setScheduleToAssetAtTime(i,r)},this.onScheduleUpdate=(i,s)=>{const r=this.schedule;if(!r)return;const n=this.playingItem,a=r.events||[],o=r.items||[],l=r.durations,d=i.map(m=>m.identifier),c=!!(a.length||d.length);(c||s)&&this.log(`INTERSTITIALS_UPDATED (${a.length}): ${a}
|
|
75
|
-
Schedule: ${o.map(m=>Me(m))} pos: ${this.timelinePos}`),d.length&&this.log(`Removed events ${d}`);let h=null,u=null;n&&(h=this.updateItem(n,this.timelinePos),this.itemsMatch(n,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const f=this.bufferingItem;if(f&&(u=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,u)?this.bufferingItem=u:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),i.forEach(m=>{m.assetList.forEach(g=>{this.clearAssetPlayer(g.identifier,null)})}),this.playerQueue.forEach(m=>{if(m.interstitial.appendInPlace){const g=m.assetItem.timelineStart,y=m.timelineOffset-g;if(y)try{m.timelineOffset=g}catch(v){Math.abs(y)>pt&&this.warn(`${v} ("${m.assetId}" ${m.timelineOffset}->${g})`)}}}),c||s){if(this.hls.trigger(p.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:o.slice(0),durations:l,removedIds:d}),this.isInterstitial(n)&&d.includes(n.event.identifier)){this.warn(`Interstitial "${n.event.identifier}" removed while playing`),this.primaryFallback(n.event);return}n&&this.trimInPlace(h,n),f&&u!==h&&this.trimInPlace(u,f),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Jd(e),this.schedule=new Zd(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(p.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(p.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(p.MEDIA_ENDED,this.onMediaEnded,this),e.on(p.ERROR,this.onError,this),e.on(p.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(p.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(p.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(p.MEDIA_ENDED,this.onMediaEnded,this),e.off(p.ERROR,this.onError,this),e.off(p.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Le(e,"play",this.onPlay),Le(e,"pause",this.onPause),Le(e,"seeking",this.onSeeking),Le(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;Ee(i,"seeking",this.onSeeking),Ee(i,"timeupdate",this.onTimeupdate),Ee(i,"play",this.onPlay),Ee(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!s){this.clearScheduleState();const r=this.findItemIndex(i);this.setSchedulePosition(r)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const i=!!t.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){const r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,i=c=>c&&e.getAssetPlayer(c.identifier),s=(c,h,u,f,m)=>{if(c){let g=c[h].start;const y=c.event;if(y){if(h==="playout"||y.timelineOccupancy!==ai.Point){const v=i(u);v?.interstitial===y&&(g+=v.assetItem.startOffset+v[m])}}else{const v=f==="bufferedPos"?n():e[f];g+=v-c.start}return g}return 0},r=(c,h)=>{var u;if(c!==0&&h!=="primary"&&(u=e.schedule)!=null&&u.length){var f;const m=e.schedule.findItemIndexAtTime(c),g=(f=e.schedule.items)==null?void 0:f[m];if(g)return c+(g[h].start-g.start)}return c},n=()=>{const c=e.bufferedPos;return c===Number.MAX_VALUE?a("primary"):Math.max(c,0)},a=c=>{var h,u;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:((u=e.schedule)==null?void 0:u.durations[c])||0},o=(c,h)=>{var u,f;const m=e.effectivePlayingItem;if(m!=null&&(u=m.event)!=null&&u.restrictions.skip||!e.schedule)return;e.log(`seek to ${c} "${h}"`);const g=e.effectivePlayingItem,y=e.schedule.findItemIndexAtTime(c,h),v=(f=e.schedule.items)==null?void 0:f[y],E=e.getBufferingPlayer(),T=E?.interstitial,S=T?.appendInPlace,A=g&&e.itemsMatch(g,v);if(g&&(S||A)){const b=i(e.playingAsset),I=b?.media||e.primaryMedia;if(I){const D=h==="primary"?I.currentTime:s(g,h,e.playingAsset,"timelinePos","currentTime"),w=c-D,P=(S?D:I.currentTime)+w;if(P>=0&&(!b||S||P<=b.duration)){I.currentTime=P;return}}}if(v){let b=c;if(h!=="primary"){const D=c-v[h].start;b=v.start+D}const I=!e.isInterstitial(v);if((!e.isInterstitial(g)||g.event.appendInPlace)&&(I||v.event.appendInPlace)){const D=e.media||(S?E?.media:null);D&&(D.currentTime=b)}else if(g){const D=e.findItemIndex(g);if(y>D){const P=e.schedule.findJumpRestrictedIndex(D+1,y);if(P>D){e.setSchedulePosition(P);return}}let w=0;if(I)e.timelinePos=b,e.checkBuffer();else{const P=v.event.assetList,x=c-(v[h]||v).start;for(let U=P.length;U--;){const O=P[U];if(O.duration&&x>=O.startOffset&&x<O.startOffset+O.duration){w=U;break}}}e.setSchedulePosition(y,w)}}},l=()=>{const c=e.effectivePlayingItem;if(e.isInterstitial(c))return c;const h=t();return e.isInterstitial(h)?h:null},d={get bufferedEnd(){const c=t(),h=e.bufferingItem;if(h&&h===c){var u;return s(h,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-h.playout.start||((u=e.bufferingAsset)==null?void 0:u.startOffset)||0}return 0},get currentTime(){const c=l(),h=e.effectivePlayingItem;return h&&h===c?s(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(c){const h=l(),u=e.effectivePlayingItem;u&&u===h&&o(c+u.playout.start,"playout")},get duration(){const c=l();return c?c.playout.end-c.playout.start:0},get assetPlayers(){var c;const h=(c=l())==null?void 0:c.event.assetList;return h?h.map(u=>e.getAssetPlayer(u.identifier)):[]},get playingIndex(){var c;const h=(c=l())==null?void 0:c.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var c;return((c=e.schedule)==null||(c=c.events)==null?void 0:c.slice(0))||[]},get schedule(){var c;return((c=e.schedule)==null||(c=c.items)==null?void 0:c.slice(0))||[]},get interstitialPlayer(){return l()?d:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const c=t();return e.findItemIndex(c)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const c=e.effectivePlayingItem;return e.findItemIndex(c)},primary:{get bufferedEnd(){return n()},get currentTime(){const c=e.timelinePos;return c>0?c:0},set currentTime(c){o(c,"primary")},get duration(){return a("primary")},get seekableStart(){var c;return((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0}},integrated:{get bufferedEnd(){return s(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(c){o(c,"integrated")},get duration(){return a("integrated")},get seekableStart(){var c;return r(((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0,"integrated")}},skip:()=>{const c=e.effectivePlayingItem,h=c?.event;if(h&&!h.restrictions.skip){const u=e.findItemIndex(c);h.appendInPlace?o(c.playout.start+c.event.duration+.001,"playout"):e.advanceAfterAssetEnded(h,u,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!i?!1:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let s=this.media;!s&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(s=this.primaryMedia);const r=(t=s)==null?void 0:t.currentTime;if(!(r===void 0||!N(r)))return r}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){const i=e.interstitial.appendInPlace,s=e.media;if(i&&s===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&s){this.detachedData={media:s};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ne(r)}`),this.detachedData=r}else t&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(e,t){var i,s;if(e.media===t)return;let r=null;const n=this.hls,a=e!==n,o=a&&e.interstitial.appendInPlace,l=(i=this.detachedData)==null?void 0:i.mediaSource;let d;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),d="Primary";else if(l){const f=this.getBufferingPlayer();f?(r=f.transferMedia(),d=`${f}`):d="detached MediaSource"}else d="detached media";if(!r){if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${ne(r)}`);else if(!this.detachedData||n.media===t){const f=this.playerQueue;f.length>1&&f.forEach(m=>{if(a&&m.interstitial.appendInPlace!==o){const g=m.interstitial;this.clearInterstitial(m.interstitial,null),g.appendInPlace=!1,g.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${g}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const c=r&&"mediaSource"in r&&((s=r.mediaSource)==null?void 0:s.readyState)!=="closed",h=c&&r?r:t;this.log(`${c?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${d} (media.currentTime: ${t.currentTime})`);const u=this.schedule;if(h===r&&u){const f=a&&e.assetId===u.assetIdAtEnd;h.overrides={duration:u.duration,endOfStream:!a||f,cueRemoval:!a}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const i=this.timelinePos,s=this.effectivePlayingItem;if(i===-1){const r=this.hls.startPosition;if(this.timelinePos=r,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Rt("checkStart (preroll)",r));const n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(r>=0||!this.primaryLive){this.log(Rt("checkStart",r));const n=this.timelinePos=r>0?r:0,a=e.findItemIndexAtTime(n);this.setSchedulePosition(a)}else this.hls.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(s&&!this.playingItem){this.log(Rt("checkStart (playing item)",s.start));const r=e.findItemIndex(s);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){const i=e.event,s=Er(i,i.findAssetIndex(t));if(!i.isAssetPastPlayoutLimit(s))this.bufferedToEvent(e,s);else if(this.schedule){var r;const n=(r=this.schedule.items)==null?void 0:r[this.findItemIndex(e)+1];n&&this.bufferedToItem(n)}}advanceAfterAssetEnded(e,t,i){const s=Er(e,i);if(e.isAssetPastPlayoutLimit(s)){if(this.schedule){const r=this.schedule.items;if(r){const n=t+1;if(n>=r.length){this.setSchedulePosition(-1);return}const a=e.resumeTime;this.timelinePos<a&&(this.log(Rt("advanceAfterAssetEnded",a)),this.timelinePos=a,e.appendInPlace&&this.advanceInPlace(a),this.checkBuffer(this.bufferedPos<a)),this.setSchedulePosition(n)}}}else{if(e.appendInPlace){const r=e.assetList[s];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,s)}}setScheduleToAssetAtTime(e,t){const i=this.schedule;if(!i)return;const s=t.parentIdentifier,r=i.getEvent(s);if(r){const n=i.findEventIndex(s),a=i.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,n,a-1)}}setSchedulePosition(e,t){var i;const s=(i=this.schedule)==null?void 0:i.items;if(!s||this.playbackDisabled)return;const r=e>=0?s[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Me(r)}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const d=n.event,c=this.playingAsset,h=c?.identifier,u=h?this.getAssetPlayer(h):null;if(u&&h&&(!this.eventItemsMatch(n,r)||t!==void 0&&h!==d.assetList[t].identifier)){var o;const f=d.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${f+1}/${d.assetList.length} ${Lt(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(p.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:f,event:d,schedule:s.slice(0),scheduleIndex:e,player:u}),n!==this.playingItem){this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(d,this.findItemIndex(this.playingItem),f);return}this.retreiveMediaSource(h,r),u.media&&!((o=this.detachedData)!=null&&o.mediaSource)&&u.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${d} ${Me(n)}`),d.hasPlayed=!0,this.hls.trigger(p.INTERSTITIAL_ENDED,{event:d,schedule:s.slice(0),scheduleIndex:e}),d.cue.once)){var l;this.updateSchedule();const f=(l=this.schedule)==null?void 0:l.items;if(r&&f){const m=this.findItemIndex(r);this.advanceSchedule(m,f,t,n,a)}return}}this.advanceSchedule(e,s,t,n,a)}advanceSchedule(e,t,i,s,r){const n=this.schedule;if(!n)return;const a=t[e]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(d=>{const c=d.interstitial,h=n.findEventIndex(c.identifier);(h<e||h>e+1)&&this.clearInterstitial(c,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const d=a.event;if(i===void 0){i=n.findAssetIndex(d,this.timelinePos);const f=Er(d,i-1);if(d.isAssetPastPlayoutLimit(f)||d.appendInPlace&&this.timelinePos===a.end){this.advanceAfterAssetEnded(d,e,i);return}i=f}const c=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let h=this.preloadAssets(d,i);if(this.eventItemsMatch(a,c||s)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${Me(a)} ${d.appendInPlace?"append in place":""}`),this.hls.trigger(p.INTERSTITIAL_STARTED,{event:d,schedule:t.slice(0),scheduleIndex:e})),!d.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${d}`);return}if(d.assetListLoader&&(d.assetListLoader.destroy(),d.assetListLoader=void 0),!o){this.log(`Waiting for attachMedia to start Interstitial ${d}`);return}this.waitingItem=this.endedItem=null,this.playingItem=a;const u=d.assetList[i];if(!u){this.advanceAfterAssetEnded(d,e,i||0);return}if(h||(h=this.getAssetPlayer(u.identifier)),h===null||h.destroyed){const f=d.assetList.length;this.warn(`asset ${i+1}/${f} player destroyed ${d}`),h=this.createAssetPlayer(d,u,i),h.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&d.appendInPlace&&this.isAssetBuffered(u))return;this.startAssetPlayer(h,i,t,e,o),this.shouldPlay&&yl(h.media)}else a?(this.resumePrimary(a,e,s),this.shouldPlay&&yl(this.hls.media)):r&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var s,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Me(e)}`),!((s=this.detachedData)!=null&&s.mediaSource)){let a=this.timelinePos;(a<e.start||a>=e.end)&&(a=this.getPrimaryResumption(e,t),this.log(Rt("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)}if(!i)return;const n=(r=this.schedule)==null?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Me(e)}`),this.hls.trigger(p.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const s=this.primaryDetails;if(t===0)return this.hls.startPosition;if(s&&(i<s.fragmentStart||i>s.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:Y.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const s=this.primaryMedia;if(!s)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,s),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(Rt("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;const s=this.hls;!s.loadingEnabled||!s.media||Math.abs((((i=s.mainForwardBufferInfo)==null?void 0:i.start)||s.media.currentTime)-e)>.5?s.startLoad(e,t):s.bufferingEnabled||s.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(p.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(p.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const i=this.hls.levels[t.level];if(!i.details)return;const s=ie(ie({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s,this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=ie(ie({},this.altSelection),{},{audio:i});return}const r=ie(ie({},s),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=ie(ie({},this.altSelection),{},{subtitles:i});return}const r=ie(ie({},s),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(e,t){const i=Za(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setAudioOption(t)||s.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=Za(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setSubtitleOption(t)||t.id!==-1&&s.setSubtitleOption(i)))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const s=this.timelinePos;this.bufferedPos=s,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let s=0;s<t.length;s++){const r=t[s];if(r.cue.post){var i;const n=this.schedule.findEventIndex(r.identifier),a=(i=this.schedule.items)==null?void 0:i[n];this.isInterstitial(a)&&this.eventItemsMatch(a,this.bufferingItem)&&this.bufferedToItem(a,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1}updateItem(e,t){var i;const s=(i=this.schedule)==null?void 0:i.items;return e&&s&&s[this.findItemIndex(e,t)]||null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,n)=>{e.event.isAssetPastPlayoutLimit(n)&&this.clearAssetPlayer(r.identifier,null)});const i=e.end+.25,s=Y.bufferInfo(this.primaryMedia,i,0);(s.end>i||(s.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${Me(e)} (was ${Me(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const i=this.mediaSelection;i&&((t=this.schedule)==null||t.updateSchedule(i,[],e))}checkBuffer(e){var t;const i=(t=this.schedule)==null?void 0:t.items;if(!i)return;const s=Y.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=s.len<1),this.updateBufferedPos(s.end,i,e)}updateBufferedPos(e,t,i){const s=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!s)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const n=this.playingItem,a=this.findItemIndex(n);let o=s.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const d=this.findItemIndex(r),c=Math.min(d+1,t.length-1),h=t[c];if((o===-1&&r&&e>=r.end||(l=h.event)!=null&&l.appendInPlace&&e+.01>=h.start)&&(o=c),this.isInterstitial(r)){const u=r.event;if(c-a>1&&u.appendInPlace===!1||u.assetList.length===0&&u.assetListLoader)return}if(this.bufferedPos=e,o>d&&o>a)this.bufferedToItem(h);else{const u=this.primaryDetails;this.primaryLive&&u&&e>u.edge-u.targetduration&&h.start<u.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.event,0)}}else i&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(t[o]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{const s=this.getAssetPlayer(i.identifier);return!(s!=null&&s.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){const{items:s,events:r}=i;if(!s||!r)return t;const n=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const o=a?a.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Me(e)}`+(t?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const l=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((d,c)=>{const h=this.getAssetPlayer(d.identifier);h&&(c===l&&h.loadSource(),h.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(p.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;const s=this.detachedData;s?s.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,s=i.assetList.length===0&&!i.assetListLoader,r=i.cue.once;if(s||!r){const n=this.preloadAssets(i,t);if(n!=null&&n.interstitial.appendInPlace){const a=this.primaryMedia;a&&this.bufferAssetPlayer(n,a)}}}preloadAssets(e,t){const i=e.assetUrl,s=e.assetList.length,r=s===0&&!e.assetListLoader,n=e.cue.once;if(r){const o=e.timelineStart;if(e.appendInPlace){var a;const h=this.playingItem;!this.isInterstitial(h)&&(h==null||(a=h.nextEvent)==null?void 0:a.identifier)===e.identifier&&this.flushFrontBuffer(o+.25)}let l,d=0;if(!this.playingItem&&this.primaryLive&&(d=this.hls.startPosition,d===-1&&(d=this.hls.liveSyncPosition||0)),d&&!(e.cue.pre||e.cue.post)){const h=d-o;h>0&&(l=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:s} ${e}${l?` live-start: ${d} start-offset: ${l}`:""}`),i)return this.createAsset(e,0,0,o,e.duration,i);const c=this.assetListLoader.loadAssetList(e,l);c&&(e.assetListLoader=c)}else if(!n&&s){for(let l=t;l<s;l++){const d=e.assetList[l],c=this.getAssetPlayerQueueIndex(d.identifier);(c===-1||this.playerQueue[c].destroyed)&&!d.error&&this.createAssetPlayer(e,d,l)}const o=e.assetList[t];if(o){const l=this.getAssetPlayer(o.identifier);return l&&l.loadSource(),l}}return null}flushFrontBuffer(e){const t=this.requiredTracks;t&&(this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(i=>{this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})}))}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,s,r,n){const a={parentIdentifier:e.identifier,identifier:og(e,n,t),duration:r,startOffset:i,timelineStart:s,uri:n};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,i){const s=this.hls,r=s.userConfig;let n=r.videoPreference;const a=s.loadLevelObj||s.levels[s.currentLevel];(n||a)&&(n=se({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=s.audioTracks[s.audioTrack],l=s.subtitleTracks[s.subtitleTrack];let d=0;if(this.primaryLive||e.appendInPlace){const T=this.timelinePos-t.timelineStart;if(T>1){const S=t.duration;S&&T<S&&(d=T)}}const c=t.identifier,h=ie(ie({},r),{},{maxMaxBufferLength:Math.min(180,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(h.timelineOffset=t.timelineStart));const u=h.cmcd;u!=null&&u.sessionId&&u.contentId&&(h.cmcd=se({},u,{contentId:jt(t.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${e} and asset ${c}`);const f=new Qd(this.HlsPlayerClass,h,e,t);this.playerQueue.push(f),e.assetList[i]=t;let m=!0;const g=T=>{if(T.live){var S;const I=new Error(`Interstitials MUST be VOD assets ${e}`),D={fatal:!0,type:$.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:I},w=((S=this.schedule)==null?void 0:S.findEventIndex(e.identifier))||-1;this.handleAssetItemError(D,e,w,i,I.message);return}const A=T.edge-T.fragmentStart,b=t.duration;(m||b===null||A>b)&&(m=!1,this.log(`Interstitial asset "${c}" duration change ${b} > ${A}`),t.duration=A,this.updateSchedule())};f.on(p.LEVEL_UPDATED,(T,{details:S})=>g(S)),f.on(p.LEVEL_PTS_UPDATED,(T,{details:S})=>g(S)),f.on(p.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const y=(T,S)=>{const A=this.getAssetPlayer(c);if(A&&S.tracks){A.off(p.BUFFER_CODECS,y),A.tracks=S.tracks;const b=this.primaryMedia;this.bufferingAsset===A.assetItem&&b&&!A.media&&this.bufferAssetPlayer(A,b)}};f.on(p.BUFFER_CODECS,y);const v=()=>{var T;const S=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${S}`),!S||!this.schedule)return;const A=this.schedule.findEventIndex(e.identifier),b=(T=this.schedule.items)==null?void 0:T[A];this.isInterstitial(b)&&this.advanceAssetBuffering(b,t)};f.on(p.BUFFERED_TO_END,v);const E=T=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;const S=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,S,T)};return f.once(p.MEDIA_ENDED,E(i)),f.once(p.PLAYOUT_LIMIT_REACHED,E(1/0)),f.on(p.ERROR,(T,S)=>{if(!this.schedule)return;const A=this.getAssetPlayer(c);if(S.details===L.BUFFER_STALLED_ERROR){if(A!=null&&A.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(S,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${S.error} ${e}`)}),f.on(p.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;const T=new Error(`Asset player destroyed unexpectedly ${c}`),S={fatal:!0,type:$.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:T};this.handleAssetItemError(S,e,this.schedule.findEventIndex(e.identifier),i,T.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Lt(t)}`),this.hls.trigger(p.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){const i=this.getAssetPlayerQueueIndex(e);if(i!==-1){const s=this.playerQueue[i];this.log(`clear ${s} toSegment: ${t&&Me(t)}`),this.transferMediaFromPlayer(s,t),this.playerQueue.splice(i,1),s.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,s,r){const{interstitial:n,assetItem:a,assetId:o}=e,l=n.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=a,(!d||d.identifier!==o)&&(d&&(this.clearAssetPlayer(d.identifier,i[s]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${Lt(a)}`),this.hls.trigger(p.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:n,schedule:i.slice(0),scheduleIndex:s,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var i,s;if(!this.schedule)return;const{interstitial:r,assetItem:n}=e,a=this.schedule.findEventIndex(r.identifier),o=(i=this.schedule.items)==null?void 0:i[a];if(!o)return;e.loadSource(),this.setBufferingItem(o),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===e)return;const d=r.appendInPlace;if(d&&l?.interstitial.appendInPlace===!1)return;const c=l?.tracks||((s=this.detachedData)==null?void 0:s.tracks)||this.requiredTracks;if(d&&n!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(c&&!Ca(c,e.tracks)){const h=new Error(`Asset ${Lt(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),u={fatal:!0,type:$.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},f=r.findAssetIndex(n);this.handleAssetItemError(u,r,a,f,h.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,i=this.primaryMedia;if(!t||!i)return;const s=i.currentTime,r=t.findAssetIndex(e,s),n=e.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||s-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${e} (media.currentTime: ${s})`),o&&(l/i.playbackRate<.5||a.bufferedInPlaceToEnd(i))&&a.hls){const d=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,d,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,i,s,r){if(e.details===L.BUFFER_STALLED_ERROR)return;const n=t.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n&&Lt(n)} ${e.error}`),!this.schedule)return;const a=n?.identifier||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,d=this.schedule.items,c=se({},e,{fatal:!1,errorAction:Tt(!0),asset:n,assetListIndex:s,event:t,schedule:d,scheduleIndex:i,player:l});if(this.hls.trigger(p.INTERSTITIAL_ASSET_ERROR,c),!e.fatal)return;const h=this.playingAsset,u=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(a,null),n.error=f),!t.assetList.some(m=>!m.error))t.error=f;else for(let m=s;m<t.assetList.length;m++)this.resetAssetPlayer(t.assetList[m].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):h&&h.identifier===a?this.advanceAfterAssetEnded(t,i,s):u&&u.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,u)}primaryFallback(e){const t=e.timelineStart,i=this.effectivePlayingItem;let s=this.timelinePos;if(i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${s} playing: ${Me(i)} error: ${e.error}`),s===-1&&(s=this.hls.startPosition);const n=this.updateItem(i,s);this.itemsMatch(i,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(s===-1){this.checkStart();return}if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(r)}onAssetListLoaded(e,t){var i,s;const r=t.event,n=r.identifier,a=t.assetListResponse.ASSETS;if(!((i=this.schedule)!=null&&i.hasEvent(n)))return;const o=r.timelineStart,l=r.duration;let d=0;a.forEach((m,g)=>{const y=parseFloat(m.DURATION);this.createAsset(r,g,d,o+d,y,m.URI),d+=y}),r.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${l}) ${r}`);const c=this.waitingItem,h=c?.event.identifier===n;this.updateSchedule();const u=(s=this.bufferingItem)==null?void 0:s.event;if(h){var f;const m=this.schedule.findEventIndex(n),g=(f=this.schedule.items)==null?void 0:f[m];if(g){if(!this.playingItem&&this.timelinePos>g.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==m){r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(g)}this.setSchedulePosition(m)}else if(u?.identifier===n){const m=r.assetList[0];if(m){const g=this.getAssetPlayer(m.identifier);if(u.appendInPlace){const y=this.primaryMedia;g&&y&&this.bufferAssetPlayer(g,y)}else g&&g.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case L.ASSET_LIST_PARSING_ERROR:case L.ASSET_LIST_LOAD_ERROR:case L.ASSET_LIST_LOAD_TIMEOUT:{const i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case L.BUFFER_STALLED_ERROR:{const i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},En=500,Tn=class extends Zt{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",B.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=_.IDLE,this.setInterval(En),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:s}=t;if(this.fragContextChanged(i)||(de(i)&&(this.fragPrevious=i),this.state=_.IDLE),!s)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=i.start;for(let l=0;l<r.length;l++)if(a>=r[l].start&&a<=r[l].end){n=r[l];break}const o=i.start+i.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:i,endOffset:s}=t;if(i===0&&s!==Number.POSITIVE_INFINITY){const r=s-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(n=>{for(let a=0;a<n.length;){if(n[a].end<=r){n.shift();continue}else if(n[a].start<r)n[a].start=r;else break;a++}}),this.fragmentTracker.removeFragmentsInRange(i,r,B.SUBTITLE)}}onError(e,t){const i=t.frag;i?.type===B.SUBTITLE&&(t.details===L.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==_.STOPPED&&(this.state=_.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&sl(this.levels,t)){this.levels=t.map(i=>new ht(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const s=new ht(i);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,B.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}const s=this.levels[this.currentTrackId];s!=null&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.state!==_.STOPPED&&this.setInterval(En)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:s,levels:r}=this,{details:n,id:a}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${a}`);return}const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||(i=o.details)!=null&&i.live){if(n.deltaUpdateFailed)return;const c=this.mainDetails;if(!c){this.startFragRequested=!1;return}const h=c.fragments[0];if(!o.details)n.hasProgramDateTime&&c.hasProgramDateTime?(Oi(n,c),l=n.fragmentStart):h&&(l=h.start,ir(n,l));else{var d;l=this.alignPlaylists(n,o.details,(d=this.levelLastLoaded)==null?void 0:d.details),l===0&&h&&(l=h.start,ir(n,l))}c&&!this.startFragRequested&&this.setStartPosition(c,l)}o.details=n,this.levelLastLoaded=o,a===s&&(this.hls.trigger(p.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===_.IDLE&&(lt(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,s=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&s!=null&&s.key&&s.iv&&bt(s.method)){const n=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,Xs(s.method)).catch(a=>{throw r.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t}),a}).then(a=>{const o=performance.now();r.trigger(p.FRAG_DECRYPTED,{frag:t,payload:a,stats:{tstart:n,tdecrypt:o}})}).catch(a=>{this.warn(`${a.name}: ${a.message}`),this.state=_.IDLE})}}doTick(){if(!this.media){this.state=_.IDLE;return}if(this.state===_.IDLE){const{currentTrackId:e,levels:t}=this,i=t?.[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;const{config:s}=this,r=this.getLoadPosition(),{end:n,len:a}=Y.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,s.maxBufferHole),o=i.details;if(a>this.hls.maxBufferLength+o.levelTargetDuration)return;const l=o.fragments,d=l.length,c=o.edge;let h=null;const u=this.fragPrevious;if(n<c){const m=s.maxFragLookUpTolerance,g=n>c-m?0:m;h=lt(u,l,Math.max(l[0].start,n),g),!h&&u&&u.start<l[0].start&&(h=l[0])}else h=l[d-1];if(h=this.filterReplacedPrimary(h,i.details),!h)return;const f=l[h.sn-o.startSN-1];if(f&&f.cc===h.cc&&this.fragmentTracker.getState(f)===he.NOT_LOADED&&(h=f),this.fragmentTracker.getState(h)===he.NOT_LOADED){const m=this.mapToInitFragWhenRequired(h);m&&this.loadFragment(m,i,n)}}}loadFragment(e,t,i){de(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new tc(this.tracksBuffered[this.currentTrackId]||[])}},tc=class{constructor(e){this.buffered=void 0;const t=(i,s,r)=>{if(s=s>>>0,s>r-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${r})`);return e[s][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}},ic={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Sn=e=>String.fromCharCode(ic[e]||e),xe=15,Ke=100,sc={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},rc={17:2,18:4,21:6,22:8,23:10,19:13,20:15},nc={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},ac={25:2,26:4,29:6,30:8,31:10,27:13,28:15},oc=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],lc=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;te.log(`${this.time} [${e}] ${i}`)}}},st=function(t){const i=[];for(let s=0;s<t.length;s++)i.push(t[s].toString(16));return i},bn=class{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){const s=t[i];e.hasOwnProperty(s)&&(this[s]=e[s])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},dc=class{constructor(){this.uchar=" ",this.penState=new bn}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}},cc=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new bn,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ke;t++)this.chars.push(new dc);this.logger=e}equals(e){for(let t=0;t<Ke;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Ke;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Ke;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Ke&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ke)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Sn(e);if(this.pos>=Ke){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Ke;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let i=0;i<Ke;i++){const s=this.chars[i].uchar;s!==" "&&(t=!1),e.push(s)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},ds=class{constructor(e){this.rows=[],this.currRow=xe-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<xe;t++)this.rows.push(new cc(e));this.logger=e}reset(){for(let e=0;e<xe;e++)this.rows[e].clear();this.currRow=xe-1}equals(e){let t=!0;for(let i=0;i<xe;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<xe;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<xe;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+ne(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let a=0;a<xe;a++)this.rows[a].clear();const r=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){const a=n.rows[r].cueStartTime,o=this.logger.time;if(a!==null&&o!==null&&a<o)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(n.rows[r+l])}}this.currRow=t;const i=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,n=Math.max(r-1,0);i.setCursor(e.indent),e.color=i.chars[n].penState.foreground}const s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+ne(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",s=-1;for(let r=0;r<xe;r++){const n=this.rows[r].getTextString();n&&(s=r+1,e?t.push("Row "+s+": '"+n+"'"):t.push(n.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
|
|
76
|
-
`)),i}getTextAndFormat(){return this.rows}},In=class{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new ds(i),this.nonDisplayedMemory=new ds(i),this.lastOutputScreen=new ds(i),this.currRollUpRow=this.displayedMemory.rows[xe-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[xe-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};t.underline=e%2===1,t.italics=e>=46,t.italics?t.foreground="white":t.foreground=["white","green","blue","cyan","red","yellow","magenta"][Math.floor(e/2)-16],this.logger.log(2,"MIDROW: "+ne(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},An=class{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=cg(),this.logger=void 0;const s=this.logger=new lc;this.channels=[null,new In(e,t,s),new In(e+1,i,s)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){const s=t[i]&127,r=t[i+1]&127;let n=!1,a=null;if(s===0&&r===0)continue;this.logger.log(3,()=>"["+st([t[i],t[i+1]])+"] -> ("+st([s,r])+")");const o=this.cmdHistory;if(s>=16&&s<=31){if(dg(s,r,o)){Vi(null,null,o),this.logger.log(3,()=>"Repeated command ("+st([s,r])+") is dropped");continue}Vi(s,r,this.cmdHistory),n=this.parseCmd(s,r),n||(n=this.parseMidrow(s,r)),n||(n=this.parsePAC(s,r)),n||(n=this.parseBackgroundAttributes(s,r))}else Vi(null,null,o);if(!n&&(a=this.parseChars(s,r),a)){const l=this.currentChannel;l&&l>0?this.channels[l].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!n&&!a&&this.logger.log(2,()=>"Couldn't parse cleaned data "+st([s,r])+" orig: "+st([t[i],t[i+1]]))}}parseCmd(e,t){if(!((e===20||e===28||e===21||e===29)&&t>=32&&t<=47||(e===23||e===31)&&t>=33&&t<=35))return!1;const i=e===20||e===21||e===23?1:2,s=this.channels[i];return e===20||e===21||e===28||e===29?t===32?s.ccRCL():t===33?s.ccBS():t===34?s.ccAOF():t===35?s.ccAON():t===36?s.ccDER():t===37?s.ccRU(2):t===38?s.ccRU(3):t===39?s.ccRU(4):t===40?s.ccFON():t===41?s.ccRDC():t===42?s.ccTR():t===43?s.ccRTD():t===44?s.ccEDM():t===45?s.ccCR():t===46?s.ccENM():t===47&&s.ccEOC():s.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const s=this.channels[i];return s?(s.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+st([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(e===16||e===24)&&t>=64&&t<=95))return!1;const s=e<=23?1:2;t>=64&&t<=95?i=s===1?sc[e]:nc[e]:i=s===1?rc[e]:ac[e];const r=this.channels[s];return r?(r.setPAC(this.interpretPAC(i,t)),this.currentChannel=s,!0):!1}interpretPAC(e,t){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,s.underline=(i&1)===1,i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=Math.floor((i-16)/2)*4,s}parseChars(e,t){let i,s=null,r=null;if(e>=25?(i=2,r=e-8):(i=1,r=e),r>=17&&r<=19){let n;r===17?n=t+80:r===18?n=t+112:n=t+144,this.logger.log(2,()=>"Special char '"+Sn(n)+"' in channel "+i),s=[n]}else e>=32&&e<=127&&(s=t===0?[e]:[e,t]);return s&&this.logger.log(3,()=>"Char codes = "+st(s).join(",")),s}parseBackgroundAttributes(e,t){if(!((e===16||e===24)&&t>=32&&t<=47||(e===23||e===31)&&t>=45&&t<=47))return!1;let i;const s={};e===16||e===24?(i=Math.floor((t-32)/2),s.background=oc[i],t%2===1&&(s.background=s.background+"_semi")):t===45?s.background="transparent":(s.foreground="black",t===47&&(s.underline=!0));const r=e<=23?1:2;return this.channels[r].setBkgData(s),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Vi(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const i=this.channels[t];i&&i.cueSplitAtTime(e)}}},cs=(function(){if(Qt!=null&&Qt.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function i(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const d=l.toLowerCase();return~o.indexOf(d)?d:!1}function s(o){return i(e,o)}function r(o){return i(t,o)}function n(o,...l){let d=1;for(;d<arguments.length;d++){const c=arguments[d];for(const h in c)o[h]=c[h]}return o}function a(o,l,d){const c=this,h={enumerable:!0};c.hasBeenReset=!1;let u="",f=!1,m=o,g=l,y=d,v=null,E="",T=!0,S="auto",A="start",b=50,I="middle",D=50,w="middle";Object.defineProperty(c,"id",n({},h,{get:function(){return u},set:function(P){u=""+P}})),Object.defineProperty(c,"pauseOnExit",n({},h,{get:function(){return f},set:function(P){f=!!P}})),Object.defineProperty(c,"startTime",n({},h,{get:function(){return m},set:function(P){if(typeof P!="number")throw new TypeError("Start time must be set to a number.");m=P,this.hasBeenReset=!0}})),Object.defineProperty(c,"endTime",n({},h,{get:function(){return g},set:function(P){if(typeof P!="number")throw new TypeError("End time must be set to a number.");g=P,this.hasBeenReset=!0}})),Object.defineProperty(c,"text",n({},h,{get:function(){return y},set:function(P){y=""+P,this.hasBeenReset=!0}})),Object.defineProperty(c,"region",n({},h,{get:function(){return v},set:function(P){v=P,this.hasBeenReset=!0}})),Object.defineProperty(c,"vertical",n({},h,{get:function(){return E},set:function(P){const x=s(P);if(x===!1)throw new SyntaxError("An invalid or illegal string was specified.");E=x,this.hasBeenReset=!0}})),Object.defineProperty(c,"snapToLines",n({},h,{get:function(){return T},set:function(P){T=!!P,this.hasBeenReset=!0}})),Object.defineProperty(c,"line",n({},h,{get:function(){return S},set:function(P){if(typeof P!="number"&&P!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=P,this.hasBeenReset=!0}})),Object.defineProperty(c,"lineAlign",n({},h,{get:function(){return A},set:function(P){const x=r(P);if(!x)throw new SyntaxError("An invalid or illegal string was specified.");A=x,this.hasBeenReset=!0}})),Object.defineProperty(c,"position",n({},h,{get:function(){return b},set:function(P){if(P<0||P>100)throw new Error("Position must be between 0 and 100.");b=P,this.hasBeenReset=!0}})),Object.defineProperty(c,"positionAlign",n({},h,{get:function(){return I},set:function(P){const x=r(P);if(!x)throw new SyntaxError("An invalid or illegal string was specified.");I=x,this.hasBeenReset=!0}})),Object.defineProperty(c,"size",n({},h,{get:function(){return D},set:function(P){if(P<0||P>100)throw new Error("Size must be between 0 and 100.");D=P,this.hasBeenReset=!0}})),Object.defineProperty(c,"align",n({},h,{get:function(){return w},set:function(P){const x=r(P);if(!x)throw new SyntaxError("An invalid or illegal string was specified.");w=x,this.hasBeenReset=!0}})),c.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})(),hc=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}},uc=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let s=0;s<i.length;++s)if(t===i[s]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}},hs=new cs(0,0,""),oi=hs.align==="middle"?"middle":"center",fc=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new hc,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let r=t.buffer,n=0;for(r=Tl(r);n<r.length&&r[n]!=="\r"&&r[n]!==`
|
|
73
|
+
transfer tracks: ${ne(s,(o,l)=>o==="initSegment"?void 0:l)}}`),!Ca(s,i)){t.mediaSource=null,t.tracks=void 0;const o=e.currentTime,l=this.details,d=Math.max(o,l?.fragments[0].start||0);if(d-o>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${o} -> ${d}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${d} currentTime: ${o}`),this.onMediaDetaching(p.MEDIA_DETACHING,{}),this.onMediaAttaching(p.MEDIA_ATTACHING,t),e.currentTime=d;return}this.transferData=void 0,r.forEach(o=>{const l=o,d=s[l];if(d){const c=d.buffer;if(c){const h=this.fragmentTracker,u=d.id;if(h.hasFragments(u)||h.hasParts(u)){const g=Y.getBuffered(c);h.detectEvictedFragments(l,g,u,null,!0)}const f=fr(l),m=[l,c];this.sourceBuffers[f]=m,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,d)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:s,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([a])=>{a&&this.removeBuffer(a)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const a=r.readyState==="open";try{const o=r.sourceBuffers;for(let l=o.length;l--;)a&&o[l].abort(),r.removeSourceBuffer(o[l]);a&&r.endOfStream()}catch(o){this.warn(`onMediaDetaching: ${o.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),i||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(s.removeAttribute("src"),this.appendSource&&rl(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(p.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var s;(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[fr(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Dd(this.tracks)}onBufferCodecs(e,t){var i;const s=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&r.some(o=>!s[o]);if(n||a){this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`);return}r.forEach(o=>{var l,d;const{id:c,codec:h,levelCodec:u,container:f,metadata:m,supplemental:g}=t[o];let y=s[o];const v=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[o],E=v!=null&&v.buffer?v:y,T=E?.pendingCodec||E?.codec,S=E?.levelCodec;y||(y=s[o]={buffer:void 0,listeners:[],codec:h,supplemental:g,container:f,levelCodec:u,metadata:m,id:c});const A=Di(T,S),b=A?.replace(sn,"$1");let I=Di(h,u);const D=(d=I)==null?void 0:d.replace(sn,"$1");I&&A&&b!==D&&(o.slice(0,5)==="audio"&&(I=Ri(I,this.appendSource)),this.log(`switching codec ${T} to ${I}`),I!==(y.pendingCodec||y.codec)&&(y.pendingCodec=I),y.container=f,this.appendChangeType(o,f,I))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){const s=`${t};codecs=${i}`,r={label:`change-type=${s}`,execute:()=>{const n=this.tracks[e];if(n){const a=n.buffer;a!=null&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${s}`),a.changeType(s),n.codec=i,n.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn(`Failed to change ${e} SourceBuffer type`,n)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,s=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,B.MAIN))==null?void 0:t.gap)===!0)return;const r={label:"block-audio",execute:()=>{var n;const a=this.tracks.video;(this.lastVideoAppendEnd>s||a!=null&&a.buffer&&Y.isBuffered(a.buffer,s)||((n=this.fragmentTracker.getAppendedFrag(s,B.MAIN))==null?void 0:n.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn("Error executing block-audio operation",n)}};this.blockedAudioAppend={op:r,frag:e},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:s,type:r,parent:n,frag:a,part:o,chunkMeta:l,offset:d}=t,c=l.buffering[r],{sn:h,cc:u}=a,f=self.performance.now();c.start=f;const m=a.stats.buffering,g=o?o.stats.buffering:null;m.start===0&&(m.start=f),g&&g.start===0&&(g.start=f);const y=i.audio;let v=!1;r==="audio"&&y?.container==="audio/mpeg"&&(v=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const E=i.video,T=E?.buffer;if(T&&h!=="initSegment"){const b=o||a,I=this.blockedAudioAppend;if(r==="audio"&&n!=="main"&&!this.blockedAudioAppend&&!(E.ending||E.ended)){const D=b.start+b.duration*.05,P=T.buffered,w=this.currentOp("video");!P.length&&!w?this.blockAudio(b):!w&&!Y.isBuffered(T,D)&&this.lastVideoAppendEnd<D&&this.blockAudio(b)}else if(r==="video"){const D=b.end;if(I){const P=I.frag.start;(D>P||D<this.lastVideoAppendEnd||Y.isBuffered(T,P))&&this.unblockAudio()}this.lastVideoAppendEnd=D}}const S=(o||a).start,A={label:`append-${r}`,execute:()=>{var b;c.executeStart=self.performance.now();const I=(b=this.tracks[r])==null?void 0:b.buffer;I&&(v?this.updateTimestampOffset(I,S,.1,r,h,u):d!==void 0&&N(d)&&this.updateTimestampOffset(I,d,1e-6,r,h,u)),this.appendExecutor(s,r)},onStart:()=>{},onComplete:()=>{const b=self.performance.now();c.executeEnd=c.end=b,m.first===0&&(m.first=b),g&&g.first===0&&(g.first=b);const I={};this.sourceBuffers.forEach(([D,P])=>{D&&(I[D]=Y.getBuffered(P))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(p.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:I})},onError:b=>{var I;const D={type:$.MEDIA_ERROR,parent:a.type,details:L.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:b,err:b,fatal:!1},P=(I=this.media)==null?void 0:I.error;if(b.code===DOMException.QUOTA_EXCEEDED_ERR||b.name=="QuotaExceededError"||"quota"in b)D.details=L.BUFFER_FULL_ERROR;else if(b.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!P)D.errorAction=Tt(!0);else if(b.name===rn&&this.sourceBufferCount===0)D.errorAction=Tt(!0);else{const w=++this.appendErrors[r];this.warn(`Failed ${w}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${P||"no media error"})`),(w>=this.hls.config.appendErrorMaxRetry||P)&&(D.fatal=!0)}this.hls.trigger(p.ERROR,D)}};this.log(`queuing "${r}" append sn: ${h}${o?" p: "+o.index:""} of ${a.type===B.MAIN?"level":"track"} ${a.level} cc: ${u}`),this.append(A,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(p.BUFFER_FLUSHED,{type:e})},onError:s=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,s)}}}onBufferFlushing(e,t){const{type:i,startOffset:s,endOffset:r}=t;i?this.append(this.getFlushOp(i,s,r),i):this.sourceBuffers.forEach(([n])=>{n&&this.append(this.getFlushOp(n,s,r),n)})}onFragParsed(e,t){const{frag:i,part:s}=t,r=[],n=s?s.elementaryStreams:i.elementaryStreams;n[re.AUDIOVIDEO]?r.push("audiovideo"):(n[re.AUDIO]&&r.push("audio"),n[re.VIDEO]&&r.push("video"));const a=()=>{const o=self.performance.now();i.stats.buffering.end=o,s&&(s.stats.buffering.end=o);const l=s?s.stats:i.stats;this.hls.trigger(p.FRAG_BUFFERED,{frag:i,part:s,stats:l,id:i.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(a,r).catch(o=>{this.warn(`Fragment buffered callback ${o}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([r])=>{if(r){const n=this.tracks[r];(!t.type||t.type===r)&&(n.ending=!0,n.ended||(n.ended=!0,this.log(`${r} buffer reached EOS`)))}});const s=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([r])=>{var n;return r&&!((n=this.tracks[r])!=null&&n.ended)})?s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:r}=this;if(!r||r.readyState!=="open"){r&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${r.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),r.endOfStream(),this.hls.trigger(p.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(p.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===L.BUFFER_APPEND_ERROR&&t.frag){var i;const s=(i=t.errorAction)==null?void 0:i.nextAutoLevel;N(s)&&s!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;const s=e.config,r=i.currentTime,n=t.levelTargetDuration,a=t.live&&s.liveBackBufferLength!==null?s.liveBackBufferLength:s.backBufferLength;if(N(a)&&a>=0){const l=Math.max(a,n),d=Math.floor(r/n)*n-l;this.flushBackBuffer(r,n,d)}const o=s.frontBufferFlushThreshold;if(N(o)&&o>0){const l=Math.max(s.maxBufferLength,o),d=Math.max(l,n),c=Math.floor(r/n)*n+d;this.flushFrontBuffer(r,n,c)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([s,r])=>{if(r){const a=Y.getBuffered(r);if(a.length>0&&i>a.start(0)){var n;this.hls.trigger(p.BACK_BUFFER_REACHED,{bufferEnd:i});const o=this.tracks[s];if((n=this.details)!=null&&n.live)this.hls.trigger(p.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(o!=null&&o.ended){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:s})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([s,r])=>{if(r){const n=Y.getBuffered(r),a=n.length;if(a<2)return;const o=n.start(a-1),l=n.end(a-1);if(i>o||e>=o&&e<=l)return;this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:s})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||i?.readyState!=="open")return null;const s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){const a=Math.max(0,t.fragmentStart);return{duration:1/0,start:a,end:Math.max(a,s)}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return N(r)?{duration:r}:null;const n=this.media.duration;return s>(N(i.duration)?i.duration:0)&&s>n||!N(n)?{duration:s}:null}updateMediaSource({duration:e,start:t,end:i}){const s=this.mediaSource;!this.media||!s||s.readyState!=="open"||(s.duration!==e&&(N(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),s.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${t}-${i}.`),s.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ne(i)}`),this.tracksReady){var s;const r=(s=this.transferData)==null?void 0:s.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,i])=>{if(t){const s=this.tracks[t];e[t]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(p.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const n=r,a=e[n];if(this.isPending(a)){const o=this.getTrackCodec(a,n),l=`${a.container};codecs=${o}`;a.codec=o,this.log(`creating sourceBuffer(${l})${this.currentOp(n)?" Queued":""} ${ne(a)}`);try{const d=i.addSourceBuffer(l),c=fr(n);t[c]=[n,d],a.buffer=d}catch(d){var s;this.error(`error while trying to add sourceBuffer: ${d.message}`),this.shiftAndExecuteNext(n),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[n],this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:d,sourceBufferName:n,mimeType:l,parent:a.id});return}this.trackSourceBuffer(n,a)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let s=e.codec;i&&(t==="video"||t==="audiovideo")&&Ut(i,"video")&&(s=du(s,i));const r=Di(s,e.levelCodec);return r?t.slice(0,5)==="audio"?Ri(r,this.appendSource):r:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const s=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:s,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,n)=>{const a=n.removedRanges;a!=null&&a.length&&this.hls.trigger(p.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;const i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i?.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const s=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${s}`,t),this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});const r=this.currentOp(e);r&&r.onError(s)}updateTimestampOffset(e,t,i,s,r,n){const a=t-e.timestampOffset;Math.abs(a)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,i){const{media:s,mediaSource:r}=this,n=this.tracks[e],a=n?.buffer;if(!s||!r||!a){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const o=N(s.duration)?s.duration:1/0,l=N(r.duration)?r.duration:1/0,d=Math.max(0,t),c=Math.min(i,o,l);c>d&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${d},${c}] from the ${e} SourceBuffer`),a.remove(d,c)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],s=i?.buffer;if(!s)throw new wd(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,s.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,s=t.map(r=>this.appendBlocker(r));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then(r=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;const s=(i=this.tracks[t])==null?void 0:i.buffer;!s||s.updating||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const s=this.tracks[e];if(!s)return;const r=s.buffer;if(!r)return;const n=i.bind(this,e);s.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(s=>{i.removeEventListener(s.event,s.listener)}),t.listeners.length=0)}},an=class Yc{constructor(t){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=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(p.MANIFEST_PARSED,this.onManifestParsed,this),t.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(p.BUFFER_CODECS,this.onBufferCodecs,this),t.on(p.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(p.MANIFEST_PARSED,this.onManifestParsed,this),t.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(p.BUFFER_CODECS,this.onBufferCodecs,this),t.off(p.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,i){const s=this.hls.levels[i.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(t,i){this.media=i.media instanceof HTMLVideoElement?i.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,i){const s=this.hls;this.restrictedLevels=[],this.firstLevel=i.firstLevel,s.config.capLevelToPlayerSize&&i.video&&this.startCapping()}onLevelsUpdated(t,i){this.timer&&N(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,i){this.hls.config.capLevelToPlayerSize&&i.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const t=this.hls.levels;if(t.length){const i=this.hls,s=this.getMaxLevel(t.length-1);s!==this.autoLevelCapping&&i.logger.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),i.autoLevelCapping=s,i.autoLevelEnabled&&i.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=i.autoLevelCapping}}}getMaxLevel(t){const i=this.hls.levels;if(!i.length)return-1;const s=i.filter((r,n)=>this.isLevelAllowed(r)&&n<=t);return this.clientRect=null,Yc.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,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;const t=this.media,i={width:0,height:0};if(t){const s=t.getBoundingClientRect();i.width=s.width,i.height=s.height,!i.width&&!i.height&&(i.width=s.right-s.left||t.width||0,i.height=s.bottom-s.top||t.height||0)}return this.clientRect=i,i}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch{}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(i=>t.bitrate===i.bitrate&&t.width===i.width&&t.height===i.height)}static getMaxLevelByMediaSize(t,i,s){if(!(t!=null&&t.length))return-1;const r=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let n=t.length-1;const a=Math.max(i,s);for(let o=0;o<t.length;o+=1){const l=t[o];if((l.width>=a||l.height>=a)&&r(l,t[o+1])){n=o;break}}return n}},be={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Pd={HLS:"h"},tt=class kn{constructor(t,i){Array.isArray(t)&&(t=t.map(s=>s instanceof kn?s:new kn(s))),this.value=t,this.params=i}},_d="Dict",on=class{constructor(e){this.description=e}},ln="Bare Item",kd="Boolean",Cd="Byte Sequence",xd="Integer",Md="Decimal",Od="String",Fd=/[\x00-\x1f\x7f]+/,Nd="Token",Ud="Key",Oe="CMCD-Object",le="CMCD-Request",it="CMCD-Session",Je="CMCD-Status",Bd={br:Oe,ab:Oe,d:Oe,ot:Oe,tb:Oe,tpb:Oe,lb:Oe,tab:Oe,lab:Oe,url:Oe,pb:le,bl:le,tbl:le,dl:le,ltc:le,mtp:le,nor:le,nrr:le,rc:le,sn:le,sta:le,su:le,ttfb:le,ttfbb:le,ttlb:le,cmsdd:le,cmsds:le,smrt:le,df:le,cs:le,ts:le,cid:it,pr:it,sf:it,sid:it,st:it,v:it,msd:it,bs:Je,bsd:Je,cdn:Je,rtp:Je,bg:Je,pt:Je,ec:Je,e:Je},$d={REQUEST:le},dn="event",ri=e=>Math.round(e),as=(e,t)=>Array.isArray(e)?e.map(i=>as(i,t)):e instanceof tt&&typeof e.value=="string"?new tt(as(e.value,t),e.params):(t.baseUrl&&(e=jf(e,t.baseUrl)),t.version===1?encodeURIComponent(e):e),ni=e=>ri(e/100)*100,Gd=(e,t)=>{let i=e;return t.version>=2&&(e instanceof tt&&typeof e.value=="string"?i=new tt([e]):typeof e=="string"&&(i=[e])),as(i,t)},Vd={br:ri,d:ri,bl:ni,dl:ni,mtp:ni,nor:Gd,rtp:ni,tb:ri},cn="request",hn="response",os=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],Kd=["e"],Hd=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/,un=["d","dl","nor","ot","rtp","su"],Wd=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],jd=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Yd={[hn]:qf,[dn]:Yf,[cn]:zf},zd="CMCD",fn=/CMCD=[^&#]+/,gn=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.includeKeys=void 0,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=s=>{try{this.apply(s,{ot:be.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=s=>{try{const{frag:r,part:n}=s,a=this.hls.levels[r.level],o=this.getObjectType(r),l={d:(n||r).duration*1e3,ot:o};(o===be.VIDEO||o===be.AUDIO||o==be.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o));const d=n?this.getNextPart(n):this.getNextFrag(r);d!=null&&d.url&&d.url!==r.url&&(l.nor=d.url),this.apply(s,l)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=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,s;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(s=t.tracks.video)==null?void 0:s.buffer}createData(){var e;return{v:1,sf:Pd.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){se(t,this.createData());const i=t.ot===be.INIT||t.ot===be.VIDEO||t.ot===be.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:s}=this;s&&(t=Object.keys(t).reduce((n,a)=>(s.includes(a)&&(n[a]=t[a]),n),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Zf(e.headers,t,r)):e.url=ig(e.url,t,r)}getNextFrag(e){var t;const i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){const s=e.sn-i.startSN;return i.fragments[s+1]}}getNextPart(e){var t;const{index:i,fragment:s}=e,r=(t=this.hls.levels[s.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:n}=s;for(let a=r.length-1;a>=0;a--){const o=r[a];if(o.index===i&&o.fragment.sn===n)return r[a+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return be.TIMED_TEXT;if(e.sn==="initSegment")return be.INIT;if(t==="audio")return be.AUDIO;if(t==="main")return this.hls.audioTracks.length?be.VIDEO:be.MUXED}getTopBandwidth(e){let t=0,i;const s=this.hls;if(e===be.AUDIO)i=s.audioTracks;else{const r=s.maxAutoLevel,n=r>-1?r+1:s.levels.length;i=s.levels.slice(0,n)}return i.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,i=e===be.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:Y.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,a){t(r),this.loader.load(r,n,a)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,a){t(r),this.loader.load(r,n,a)}}}},qd=3e5,mn=class extends Pe{constructor(e){super("content-steering",e.logger),this.hls=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.registerListeners()}registerListeners(){const e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const 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){const{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){const{errorAction:i}=t;if(i?.action===ce.SendAlternateToPenaltyBox&&i.flags===Te.MoveAllAlternatesMatchingHost){const s=this.levels;let r=this._pathwayPriority,n=this.pathwayId;if(t.context){const{groupId:a,pathwayId:o,type:l}=t.context;a&&s?n=this.getPathwayForGroupId(a,l,n):o&&(n=o)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!r&&s&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==n),t.details===L.BUFFER_APPEND_ERROR&&!t.fatal?i.resolved=!0:i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${n} levels: ${s&&s.length} priorities: ${ne(r)} penalized: ${ne(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const 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}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(r=>{s-i[r]>qd&&delete i[r]});for(let r=0;r<e.length;r++){const n=e[r];if(n in i)continue;if(n===this.pathwayId)return;const a=this.hls.nextLoadLevel,o=this.hls.levels[a];if(t=this.getLevelsForPathway(n),t.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,Co(t),this.hls.trigger(p.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[a];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let r=0;r<s.length;r++)if(t===q.AUDIO_TRACK&&s[r].hasAudioGroup(e)||t===q.SUBTITLE_TRACK&&s[r].hasSubtitleGroup(e))return s[r].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},s={};e.forEach(r=>{const{ID:n,"BASE-ID":a,"URI-REPLACEMENT":o}=r;if(t.some(d=>d.pathwayId===n))return;const l=this.getLevelsForPathway(a).map(d=>{const c=new oe(d.attrs);c["PATHWAY-ID"]=n;const h=c.AUDIO&&`${c.AUDIO}_clone_${n}`,u=c.SUBTITLES&&`${c.SUBTITLES}_clone_${n}`;h&&(i[c.AUDIO]=h,c.AUDIO=h),u&&(s[c.SUBTITLES]=u,c.SUBTITLES=u);const f=ul(d.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),m=new ht({attrs:c,audioCodec:d.audioCodec,bitrate:d.bitrate,height:d.height,name:d.name,url:f,videoCodec:d.videoCodec,width:d.width});if(d.audioGroups)for(let g=1;g<d.audioGroups.length;g++)m.addGroupId("audio",`${d.audioGroups[g]}_clone_${n}`);if(d.subtitleGroups)for(let g=1;g<d.subtitleGroups.length;g++)m.addGroupId("text",`${d.subtitleGroups[g]}_clone_${n}`);return m});t.push(...l),hl(this.audioTracks,i,o,n),hl(this.subtitleTracks,s,o,n)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let s;try{s=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(s.protocol!=="data:"){const d=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+d)}const r={responseType:"json",url:s.href},n=t.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(d,c,h,u)=>{this.log(`Loaded steering manifest: "${s}"`);const f=d.data;if(f?.VERSION!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":m,"PATHWAY-CLONES":g,"PATHWAY-PRIORITY":y}=f;if(m)try{this.uri=new self.URL(m,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||h.url),g&&this.clonePathways(g);const v={steeringManifest:f,url:s.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,v),y&&this.updatePathwayPriority(y)},onError:(d,c,h,u)=>{if(this.log(`Error loading steering manifest: ${d.code} ${d.text} (${c.url})`),this.stopLoad(),d.code===410){this.enabled=!1,this.log(`Steering manifest ${c.url} no longer available`);return}let f=this.timeToLoad*1e3;if(d.code===429){const m=this.loader;if(typeof m?.getResponseHeader=="function"){const g=m.getResponseHeader("Retry-After");g&&(f=parseFloat(g)*1e3)}this.log(`Steering manifest ${c.url} rate limited`);return}this.scheduleRefresh(this.uri||c.url,f)},onTimeout:(d,c,h)=>{this.log(`Timeout loading steering manifest (${c.url})`),this.scheduleRefresh(this.uri||c.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,o,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const s=(i=this.hls)==null?void 0:i.media;if(s&&!s.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}},ls=class vs extends Pe{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=vs.CDMCleanupPromise?[vs.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=i=>{const{initDataType:s,initData:r}=i,n=`"${i.type}" event: init data type: "${s}"`;if(this.debug(n),r!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=$t(this.config));const o=a.map(Js).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=Mi(a);if(s!=="sinf"||o!==ae.FAIRPLAY){this.log(`Ignoring "${i.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let l;try{const f=ue(new Uint8Array(r)),m=$a(Qs(JSON.parse(f).sinf));if(!m)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(m.subarray(8,24))}catch(f){this.warn(`${n} Failed to parse sinf: ${f}`);return}const d=ye(l),{keyIdToKeySessionPromise:c,mediaKeySessions:h}=this;let u=c[d];for(let f=0;f<h.length;f++){const m=h[f],g=m.decryptdata;if(!g.keyId)continue;const y=ye(g.keyId);if(xi(l,g.keyId)||g.uri.replace(/-/g,"").indexOf(d)!==-1){if(u=c[y],!u)continue;if(g.pssh)break;delete c[y],g.pssh=new Uint8Array(r),g.keyId=l,u=c[d]=u.then(()=>this.generateRequestWithPreferredKeySession(m,s,r,"encrypted-event-key-match")),u.catch(v=>this.handleError(v));break}}u||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${h.length}.`))}).catch(a=>this.handleError(a))}},this.onWaitingForKey=i=>{this.log(`"${i.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(p.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(p.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:i,widevineLicenseUrl:s}=this.config,r=i?.[t];if(r)return r.licenseUrl;if(t===ae.WIDEVINE&&s)return s}getLicenseServerUrlOrThrow(t){const i=this.getLicenseServerUrl(t);if(i===void 0)throw new Error(`no license server URL configured for key-system "${t}"`);return i}getServerCertificateUrl(t){const{drmSystems:i}=this.config,s=i?.[t];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const i=this.hls.levels,s=(a,o,l)=>!!a&&l.indexOf(a)===o,r=i.map(a=>a.audioCodec).filter(s),n=i.map(a=>a.videoCodec).filter(s);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{const l=d=>{const c=d.shift();this.getMediaKeysPromise(c,r,n).then(h=>a({keySystem:c,mediaKeys:h})).catch(h=>{d.length?l(d):h instanceof Re?o(h):o(new Re({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};l(t)})}requestMediaKeySystemAccess(t,i){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${s}`;return Ji===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return s(t,i)}getMediaKeysPromise(t,i,s){var r;const n=Nu(t,i,s,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[t],o=(r=a)==null?void 0:r.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${t}" key-system access with config: ${ne(n)}`),o=this.requestMediaKeySystemAccess(t,n);const l=a=this.keySystemAccessPromises[t]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${t}": ${d}`)}),o.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);const c=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const h=l.mediaKeys=d.createMediaKeys().then(u=>(this.log(`Media-keys created for "${t}"`),l.hasMediaKeys=!0,c.then(f=>f?this.setMediaKeysServerCertificate(u,t,f):u)));return h.catch(u=>{this.error(`Failed to create media-keys for "${t}"}: ${u}`)}),h})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:i,mediaKeys:s}){this.log(`Creating key-system session "${i}" keyId: ${ye(t.keyId||[])} keyUri: ${t.uri}`);const r={decryptdata:t,keySystem:i,mediaKeys:s,mediaKeysSession:s.createSession(),keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(t){const i=t.decryptdata;if(i.pssh){const s=this.createMediaKeySessionContext(t),r=$i(i),n="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(s,n,i.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,i){const s=t.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${ye(t.decryptdata.keyId||[])}
|
|
74
|
+
} (data length: ${i.byteLength})`),s.update(i)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>Js(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:i,mediaKeys:s})=>this.attemptSetMediaKeys(i,s))}selectKeySystem(t){return new Promise((i,s)=>{this.getKeySystemSelectionPromise(t).then(({keySystem:r})=>{const n=Js(r);n?i(n):s(new Error(`Unable to find format for key-system "${r}"`))}).catch(s)})}selectKeySystemFormat(t){const i=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)),this.keyFormatPromise}getKeyFormatPromise(t){const i=$t(this.config),s=t.map(Mi).filter(r=>!!r&&i.indexOf(r)!==-1);return this.selectKeySystem(s)}getKeyStatus(t){const{mediaKeySessions:i}=this;for(let s=0;s<i.length;s++){const r=sg(t,i[s]);if(r)return r}}loadKey(t){const i=t.keyInfo.decryptdata,s=$i(i),r=this.bannedKeyIds[s];if(r||this.getKeyStatus(i)==="internal-error"){const o=fl(r||"internal-error",i);return this.handleError(o,t.frag),Promise.reject(o)}const n=`(keyId: ${s} format: "${i.keyFormat}" method: ${i.method} uri: ${i.uri})`;this.log(`Starting session for key ${n}`);const a=this.keyIdToKeySessionPromise[s];if(!a){const o=this.getKeySystemForKeyPromise(i).then(({keySystem:l,mediaKeys:d})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${n}`),this.attemptSetMediaKeys(l,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:l,mediaKeys:d,decryptdata:i}))))).then(l=>{const d="cenc",c=i.pssh?i.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(l,d,c,"playlist-key")});return o.catch(l=>this.handleError(l,t.frag)),this.keyIdToKeySessionPromise[s]=o,o}return a.catch(o=>{if(o instanceof Re){const l=ie({},o.data);this.getKeyStatus(i)==="internal-error"&&(l.decryptdata=i);const d=new Re(l,o.message);this.handleError(d,t.frag)}}),a}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,i){if(this.hls)if(t instanceof Re){i&&(t.data.frag=i);const s=t.data.decryptdata;this.error(`${t.message}${s?` (${ye(s.keyId||[])})`:""}`),this.hls.trigger(p.ERROR,t.data)}else this.error(t.message),this.hls.trigger(p.ERROR,{type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const i=$i(t),s=this.keyIdToKeySessionPromise[i];if(!s){const r=Mi(t.keyFormat),n=r?[r]:$t(this.config);return this.attemptKeySystemAccess(n)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=$t(this.config)),t.length===0)throw new Re({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ne({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,i){if(this.mediaResolved=void 0,this.mediaKeys===i)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const r=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(i):new Promise((n,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=i,this.media.setMediaKeys(i).then(n).catch(a)}}));return this.mediaKeys=i,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${t}"`),s.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>s.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(t,i,s,r){var n;const a=(n=this.config.drmSystems)==null||(n=n[t.keySystem])==null?void 0:n.generateRequest;if(a)try{const m=a.call(this.hls,i,s,t);if(!m)throw new Error("Invalid response from configured generateRequest filter");i=m.initDataType,s=m.initData?m.initData:null,t.decryptdata.pssh=s?new Uint8Array(s):null}catch(m){if(this.warn(m.message),this.hls&&this.hls.config.debug)throw m}if(s===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t);const o=$i(t.decryptdata),l=t.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${o} URI: ${l} (init data type: ${i} length: ${s.byteLength})`);const d=new is,c=t._onmessage=m=>{const g=t.mediaKeysSession;if(!g){d.emit("error",new Error("invalid state"));return}const{messageType:y,message:v}=m;this.log(`"${y}" message event for session "${g.sessionId}" message size: ${v.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(t,v).catch(E=>{d.eventNames().length?d.emit("error",E):this.handleError(E)}):y==="license-release"?t.keySystem===ae.FAIRPLAY&&this.updateKeySession(t,Zs("acknowledged")).then(()=>this.removeSession(t)).catch(E=>this.handleError(E)):this.warn(`unhandled media key message type "${y}"`)},h=(m,g)=>{g.keyStatus=m;let y;m.startsWith("usable")?d.emit("resolved"):m==="internal-error"||m==="output-restricted"||m==="output-downscaled"?y=fl(m,g.decryptdata):m==="expired"?y=new Error(`key expired (keyId: ${o})`):m==="released"?y=new Error("key released"):m==="status-pending"||this.warn(`unhandled key status change "${m}" (keyId: ${o})`),y&&(d.eventNames().length?d.emit("error",y):this.handleError(y))},u=t._onkeystatuseschange=m=>{if(!t.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const g=this.getKeyStatuses(t);if(!Object.keys(g).some(E=>g[E]!=="status-pending"))return;if(g[o]==="expired"){this.log(`Expired key ${ne(g)} in key-session "${t.mediaKeysSession.sessionId}"`),this.renewKeySession(t);return}let y=g[o];if(y)h(y,t);else{var v;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(v=t.keyStatusTimeouts)[o]||(v[o]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const T=this.getKeyStatus(t.decryptdata);if(T&&T!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${T} from other session.`),h(T,t);this.log(`key status for ${o} in key-session "${t.mediaKeysSession.sessionId}" timed out after 1000ms`),y="internal-error",h(y,t)},1e3)),this.log(`No status for keyId ${o} (${ne(g)}).`)}};Ee(t.mediaKeysSession,"message",c),Ee(t.mediaKeysSession,"keystatuseschange",u);const f=new Promise((m,g)=>{d.on("error",g),d.on("resolved",m)});return t.mediaKeysSession.generateRequest(i,s).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${o} URI: ${l}`)}).catch(m=>{throw new Re({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_SESSION,error:m,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>(d.removeAllListeners(),this.removeSession(t).then(()=>{throw m}))).then(()=>(d.removeAllListeners(),t))}getKeyStatuses(t){const i={};return t.mediaKeysSession.keyStatuses.forEach((s,r)=>{if(typeof r=="string"&&typeof s=="object"){const o=r;r=s,s=o}const n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(t.keySystem===ae.PLAYREADY&&n.length===16){const o=ye(n);i[o]=s,fo(n)}const a=ye(n);s==="internal-error"&&(this.bannedKeyIds[a]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${a} key-session "${t.mediaKeysSession.sessionId}"`),i[a]=s}),i}fetchServerCertificate(t){const i=this.config,s=i.loader,r=new s(i),n=this.getServerCertificateUrl(t);return n?(this.log(`Fetching server certificate for "${t}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:n},d=i.certLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};r.load(l,c,{onSuccess:(h,u,f,m)=>{a(h.data)},onError:(h,u,f,m)=>{o(new Re({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:ie({url:l.url,data:void 0},h)},`"${t}" certificate request failed (${n}). Status: ${h.code} (${h.text})`))},onTimeout:(h,u,f)=>{o(new Re({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:l.url,data:void 0}},`"${t}" certificate request timed out (${n})`))},onAbort:(h,u,f)=>{o(new Error("aborted"))}})})):Promise.resolve()}setMediaKeysServerCertificate(t,i,s){return new Promise((r,n)=>{t.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${i}"`),r(t)}).catch(a=>{n(new Re({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(t,i){return this.requestLicense(t,new Uint8Array(i)).then(s=>this.updateKeySession(t,new Uint8Array(s)).catch(r=>{throw new Re({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:r,fatal:!1},r.message)}))}unpackPlayReadyKeyMessage(t,i){const s=String.fromCharCode.apply(null,new Uint16Array(i.buffer));if(!s.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),i;const r=new DOMParser().parseFromString(s,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let c;for(let h=0,u=n.length;h<u;h++){var a,o;c=n[h];const f=(a=c.querySelector("name"))==null?void 0:a.textContent,m=(o=c.querySelector("value"))==null?void 0:o.textContent;f&&m&&t.setRequestHeader(f,m)}}const l=r.querySelector("Challenge"),d=l?.textContent;if(!d)throw new Error("Cannot find <Challenge> in key message");return Zs(atob(d))}setupLicenseXHR(t,i,s,r){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return n.call(this.hls,t,i,s,r)}).catch(a=>{if(!s.decryptdata)throw a;return t.open("POST",i,!0),n.call(this.hls,t,i,s,r)}).then(a=>(t.readyState||t.open("POST",i,!0),{xhr:t,licenseChallenge:a||r})):(t.open("POST",i,!0),Promise.resolve({xhr:t,licenseChallenge:r}))}requestLicense(t,i){const s=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{const a=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return n(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}`);const d=this.config.licenseResponseCallback;if(d)try{l=d.call(this.hls,o,a,t)}catch(c){this.error(c)}r(l)}else{const l=s.errorRetry,d=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||o.status>=400&&o.status<500)n(new Re({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const c=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${c} attempts left`),this.requestLicense(t,i).then(r,n)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,this.setupLicenseXHR(o,a,t,i).then(({xhr:l,licenseChallenge:d})=>{t.keySystem==ae.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(l,d)),l.send(d)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,i){if(!this.config.emeEnabled)return;const s=i.media;this.media=s,Ee(s,"encrypted",this.onMediaEncrypted),Ee(s,"waitingforkey",this.onWaitingForKey);const r=this.mediaResolved;r?r():this.mediaKeys=s.mediaKeys}onMediaDetached(){const t=this.media;t&&(Le(t,"encrypted",this.onMediaEncrypted),Le(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const i=this.mediaResolved;if(i&&i(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,wt.clearKeyUriToKeyIdMap();const n=r.length;vs.CDMCleanupPromise=Promise.all(r.map(a=>this.removeSession(a)).concat((s==null||(t=s.setMediaKeys(null))==null?void 0:t.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(t,{sessionKeys:i}){if(!(!i||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=i.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(t){const{mediaKeysSession:i,licenseXhr:s,decryptdata:r}=t;if(i){this.log(`Remove licenses and keys and close session "${i.sessionId}" keyId: ${ye(r?.keyId||[])}`),t._onmessage&&(i.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(i.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const n=this.mediaKeySessions.indexOf(t);n>-1&&this.mediaKeySessions.splice(n,1);const{keyStatusTimeouts:a}=t;a&&Object.keys(a).forEach(l=>self.clearTimeout(a[l]));const{drmSystemOptions:o}=this.config;return(Bu(o)?new Promise((l,d)=>{self.setTimeout(()=>d(new Error("MediaKeySession.remove() timeout")),8e3),i.remove().then(l).catch(d)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>i.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}},ls.CDMCleanupPromise=void 0,Re=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}},pn=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(p.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(p.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(p.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const s=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){const s=performance.now();if(t){if(this.lastTime){const r=s-this.lastTime,n=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*n/r,l=this.hls;if(l.trigger(p.FPS_DROP,{currentDropped:n,currentDecoded:a,totalDroppedFrames:i}),o>0&&n>l.config.fpsDroppedMonitoringThreshold*a){let d=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=d)&&(d=d-1,l.trigger(p.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:l.currentLevel}),l.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},yn=class extends si{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const i=Gi(this.media.textTracks);for(let r=0;r<i.length;r++)if(i[r].mode==="hidden")t=i[r];else if(i[r].mode==="showing"){t=i[r];break}const s=this.findTrackForTextTrack(t);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const s=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,!s&&Gi(i.textTracks).forEach(r=>{At(r)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:s,details:r}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==s){this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${n?.groupId}`);return}const a=n.details;n.details=t.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||s?.length!==i?.length||i!=null&&i.some(n=>s?.indexOf(n)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const n=this.tracks.filter(d=>!i||i.indexOf(d.groupId)!==-1);if(n.length)this.selectDefaultTrack&&!n.some(d=>d.default)&&(this.selectDefaultTrack=!1),n.forEach((d,c)=>{d.id=c});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=n;const a=this.hls.config.subtitlePreference;if(!r&&a){this.selectDefaultTrack=!1;const d=Be(a,n);if(d>-1)r=n[d];else{const c=Be(a,this.tracks);r=this.tracks[c]}}let o=this.findTrackId(r);o===-1&&r&&(o=this.findTrackId(null));const l={subtitleTracks:n};this.log(`Updating subtitle tracks, ${n.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger(p.SUBTITLE_TRACKS_UPDATED,l),o!==-1&&this.trackId===-1&&this.setSubtitleTrack(o)}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<t.length;s++){const r=t[s];if(!(i&&!r.default||!i&&!e)&&(!e||at(r,e)))return s}if(e){for(let s=0;s<t.length;s++){const r=t[s];if(Wt(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const r=t[s];if(Wt(e.attrs,r.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if(ur(s,e))return i}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===q.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&at(e,i))return i;const s=Be(e,this.tracksInGroup);if(s>-1){const r=this.tracksInGroup[s];return this.setSubtitleTrack(s),r}else{if(i)return null;{const r=Be(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,s=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=n?.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(p.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Gi(e.textTracks),i=this.currentTrack;let s;if(i&&(s=t.filter(r=>ur(i,r))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==s&&(r.mode="disabled")}),s){const r=this.subtitleDisplay?"showing":"hidden";s.mode!==r&&(s.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!N(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e]||null;if(this.trackId=e,this.currentTrack=s,this.toggleTrackModes(),!s){this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!s.details&&!s.details.live;if(e===this.trackId&&s===i&&r)return;this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:d}=s;this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:d});const c=this.switchParams(s.url,i?.details,s.details);this.loadPlaylist(c)}},pt=.025,ai=(function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e})({}),Xd=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const i=this.playoutLimit;return e<=0||isNaN(i)?!1:i===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return vr(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-vr(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=N(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return vr(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<pt))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?ai.Range:ai.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return lg(this)}},Qd=class{constructor(e,t,i,s){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(p.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=i,this.assetItem=s;const n=()=>{this.hasDetails=!0};r.once(p.LEVEL_LOADED,n),r.once(p.AUDIO_TRACK_LOADED,n),r.once(p.SUBTITLE_TRACK_LOADED,n),r.on(p.MEDIA_ATTACHING,(a,{media:o})=>{this.removeMediaListeners(),this.mediaAttached=o,this.interstitial.playoutLimit&&(o.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(p.BUFFER_APPENDED,()=>{const l=this.bufferedEnd;this.reachedPlayout(l)&&(this._bufferedEosTime=l,r.trigger(p.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=pl(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),s=this.timelineOffset,r=Y.bufferInfo(e,s,0);return this.getAssetTime(r.end)>=i-.02}reachedPlayout(e){const t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=Y.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const i=e-t;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=i=>delete i.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var s;(s=this.hls)==null||s.on(e,t)}once(e,t,i){var s;(s=this.hls)==null||s.once(e,t)}off(e,t,i){var s;(s=this.hls)==null||s.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Lt(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},vn=.033,Zd=class extends Pe{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,s)=>e<=s.startOffset&&t>s.startOffset?(delete s.error,i+1):i,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);const s=this.items;if(s)for(s[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(r=s[i])!=null&&r.event;){var r;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let s=0;s<i.length;s++){let r=i[s];if(t&&t!=="primary"&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return s}return-1}findJumpRestrictedIndex(e,t){const i=this.items;if(i)for(let s=e;s<=t&&i[s];s++){const r=i[s].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return s}return-1}findEventIndex(e){const t=this.items;if(t)for(let s=t.length;s--;){var i;if(((i=t[s].event)==null?void 0:i.identifier)===e)return s}return-1}findAssetIndex(e,t){const i=e.assetList,s=i.length;if(s>1)for(let r=0;r<s;r++){const n=i[r];if(!n.error){const a=n.timelineStart;if(t===a||t>a&&(t<a+(n.duration||0)||r===s-1))return r}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const i=t.assetList,s=i[i.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t){const i=e.main.details,{dateRanges:s}=i,r=this.events,n=this.parseDateRanges(s,{url:i.url},t),a=Object.keys(s),o=r?r.filter(l=>!a.includes(l.identifier)):[];n.length&&n.sort((l,d)=>{const c=l.cue.pre,h=l.cue.post,u=d.cue.pre,f=d.cue.post;if(c&&!u)return-1;if(u&&!c||h&&!f)return 1;if(f&&!h)return-1;if(!c&&!u&&!h&&!f){const m=l.startTime,g=d.startTime;if(m!==g)return m-g}return l.dateRange.tagOrder-d.dateRange.tagOrder}),this.events=n,o.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,o)}updateSchedule(e,t=[],i=!1){const s=this.events||[];if(s.length||t.length||this.length<2){const r=this.items,n=this.parseSchedule(s,e);(i||t.length||r?.length!==n.length||n.some((a,o)=>Math.abs(a.playout.start-r[o].playout.start)>.005||Math.abs(a.playout.end-r[o].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,i){const s=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const a=r[n],o=e[a];if(o.isInterstitial){let l=this.eventMap[a];l?l.setDateRange(o):(l=new Xd(o,t),this.eventMap[a]=l,i===!1&&(l.appendInPlace=i)),s.push(l)}}return s}parseSchedule(e,t){const i=[],s=t.main.details,r=s.live?1/0:s.edge;let n=0;if(e=e.filter(o=>!o.error&&!(o.cue.once&&o.hasPlayed)),e.length){this.resolveOffsets(e,t);let o=0,l=0;if(e.forEach((d,c)=>{const h=d.cue.pre,u=d.cue.post,f=e[c-1]||null,m=d.appendInPlace,g=u?r:d.startOffset,y=d.duration,v=d.timelineOccupancy===ai.Range?y:0,E=d.resumptionOffset,T=f?.startTime===g,S=g+d.cumulativeDuration;let A=m?S+y:g+E;if(h||!u&&g<=0){const I=l;l+=v,d.timelineStart=S;const D=n;n+=y,i.push({event:d,start:S,end:A,playout:{start:D,end:n},integrated:{start:I,end:l}})}else if(g<=r){if(!T){const P=g-o;if(P>vn){const w=o,x=l;l+=P;const U=n;n+=P;const O={previousEvent:e[c-1]||null,nextEvent:d,start:w,end:w+P,playout:{start:U,end:n},integrated:{start:x,end:l}};i.push(O)}else P>0&&f&&(f.cumulativeDuration+=P,i[i.length-1].end=g)}u&&(A=S),d.timelineStart=S;const I=l;l+=v;const D=n;n+=y,i.push({event:d,start:S,end:A,playout:{start:D,end:n},integrated:{start:I,end:l}})}else return;const b=d.resumeTime;u||b>r?o=r:o=b}),o<r){var a;const d=o,c=l,h=r-o;l+=h;const u=n;n+=h,i.push({previousEvent:((a=i[i.length-1])==null?void 0:a.event)||null,nextEvent:null,start:o,end:d+h,playout:{start:u,end:n},integrated:{start:c,end:l}})}this.setDurations(r,n,l)}else i.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return i}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){const i=t.main.details,s=i.live?1/0:i.edge;let r=0,n=-1;e.forEach((a,o)=>{const l=a.cue.pre,d=a.cue.post,c=l?0:d?s:a.startTime;this.updateAssetDurations(a),n===c?a.cumulativeDuration=r:(r=0,n=c),!d&&a.snapOptions.in&&(a.resumeAnchor=lt(null,i.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)),!a.appendInPlace&&o+1<e.length&&e[o+1].startTime-e[o].resumeTime<vn&&(e[o+1].appendInPlace=!1,e[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`));const h=N(a.resumeOffset)?a.resumeOffset:a.duration;r+=h})}primaryCanResumeInPlaceAt(e,t){const i=e.resumeTime,s=e.startTime+e.resumptionOffset;return Math.abs(i-s)>pt?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1):!Object.keys(t).some(r=>{const n=t[r].details,a=n.edge;if(i>=a)return this.log(`"${e.identifier}" resumption ${i} past ${r} playlist end ${a}`),!1;const o=lt(null,n.fragments,i);if(!o)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${r} playlist (${n.fragStart}-${n.fragmentEnd})`),!0;const l=r==="audio"?.175:0;return Math.abs(o.start-i)<pt+l||Math.abs(o.end-i)<pt+l?!1:(this.log(`"${e.identifier}" resumption ${i} not aligned with ${r} fragment bounds (${o.start}-${o.end} sn: ${o.sn} cc: ${o.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let i=0,s=!1,r=!1;for(let n=0;n<e.assetList.length;n++){const a=e.assetList[n],o=t+i;a.startOffset=i,a.timelineStart=o,s||(s=a.duration===null),r||(r=!!a.error);const l=a.error?0:a.duration||0;i+=l}s&&!r?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}},Jd=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const i=e.assetListUrl;let s;try{s=pl(i,this.hls.sessionId,e.baseUrl)}catch(c){const h=this.assignAssetListError(e,L.ASSET_LIST_LOAD_ERROR,c,i);this.hls.trigger(p.ERROR,h);return}t&&s.protocol!=="data:"&&s.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,n=r.loader,a=new n(r),o={responseType:"json",url:s.href},l=r.interstitialAssetListLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};return a.load(o,d,{onSuccess:(c,h,u,f)=>{const m=c.data,g=m?.ASSETS;if(!Array.isArray(g)){const y=this.assignAssetListError(e,L.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),u.url,h,f);this.hls.trigger(p.ERROR,y);return}e.assetListResponse=m,this.hls.trigger(p.ASSET_LIST_LOADED,{event:e,assetListResponse:m,networkDetails:f})},onError:(c,h,u,f)=>{const m=this.assignAssetListError(e,L.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${c.code} ${c.text} (${h.url})`),h.url,f,u);this.hls.trigger(p.ERROR,m)},onTimeout:(c,h,u)=>{const f=this.assignAssetListError(e,L.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${h.url})`),h.url,c,u);this.hls.trigger(p.ERROR,f)}}),this.hls.trigger(p.ASSET_LIST_LOADING,{event:e}),a}assignAssetListError(e,t,i,s,r,n){return e.error=i,{type:$.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:s,error:i,networkDetails:n,stats:r}}},ec=class extends Pe{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;const s=i-this.timelinePos;if(Math.abs(s)<1/7056e5)return;const r=s<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=i,this.bufferedPos=i;const n=this.playingItem;if(!n){this.checkBuffer();return}if(r&&this.schedule.resetErrorsInRange(i,i-s)&&this.updateSchedule(!0),this.checkBuffer(),r&&i<n.start||i>=n.end){var a;const h=this.findItemIndex(n);let u=this.schedule.findItemIndexAtTime(i);if(u===-1&&(u=h+(r?-1:1),this.log(`seeked ${r?"back ":""}to position not covered by schedule ${i} (resolving from ${h} to ${u})`)),!this.isInterstitial(n)&&(a=this.media)!=null&&a.paused&&(this.shouldPlay=!1),!r&&u>h){const f=this.schedule.findJumpRestrictedIndex(h+1,u);if(f>h){this.setSchedulePosition(f);return}}this.setSchedulePosition(u);return}const o=this.playingAsset;if(!o){if(this.playingLastItem&&this.isInterstitial(n)){const h=n.event.assetList[0];h&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,h))}return}const l=o.timelineStart,d=o.duration||0;if(r&&i<l||i>=l+d){var c;(c=n.event)!=null&&c.appendInPlace&&(this.clearAssetPlayers(n.event,n),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,o)}},this.onTimeupdate=()=>{const i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;const s=this.playingItem;if(!s||this.playingLastItem)return;if(i>=s.end){this.timelinePos=s.end;const n=this.findItemIndex(s);this.setSchedulePosition(n+1)}const r=this.playingAsset;r&&i>=r.timelineStart+(r.duration||0)&&this.setScheduleToAssetAtTime(i,r)},this.onScheduleUpdate=(i,s)=>{const r=this.schedule;if(!r)return;const n=this.playingItem,a=r.events||[],o=r.items||[],l=r.durations,d=i.map(m=>m.identifier),c=!!(a.length||d.length);(c||s)&&this.log(`INTERSTITIALS_UPDATED (${a.length}): ${a}
|
|
75
|
+
Schedule: ${o.map(m=>Me(m))} pos: ${this.timelinePos}`),d.length&&this.log(`Removed events ${d}`);let h=null,u=null;n&&(h=this.updateItem(n,this.timelinePos),this.itemsMatch(n,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const f=this.bufferingItem;if(f&&(u=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,u)?this.bufferingItem=u:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),i.forEach(m=>{m.assetList.forEach(g=>{this.clearAssetPlayer(g.identifier,null)})}),this.playerQueue.forEach(m=>{if(m.interstitial.appendInPlace){const g=m.assetItem.timelineStart,y=m.timelineOffset-g;if(y)try{m.timelineOffset=g}catch(v){Math.abs(y)>pt&&this.warn(`${v} ("${m.assetId}" ${m.timelineOffset}->${g})`)}}}),c||s){if(this.hls.trigger(p.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:o.slice(0),durations:l,removedIds:d}),this.isInterstitial(n)&&d.includes(n.event.identifier)){this.warn(`Interstitial "${n.event.identifier}" removed while playing`),this.primaryFallback(n.event);return}n&&this.trimInPlace(h,n),f&&u!==h&&this.trimInPlace(u,f),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Jd(e),this.schedule=new Zd(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(p.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(p.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(p.MEDIA_ENDED,this.onMediaEnded,this),e.on(p.ERROR,this.onError,this),e.on(p.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(p.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(p.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(p.MEDIA_ENDED,this.onMediaEnded,this),e.off(p.ERROR,this.onError,this),e.off(p.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Le(e,"play",this.onPlay),Le(e,"pause",this.onPause),Le(e,"seeking",this.onSeeking),Le(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;Ee(i,"seeking",this.onSeeking),Ee(i,"timeupdate",this.onTimeupdate),Ee(i,"play",this.onPlay),Ee(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!s){this.clearScheduleState();const r=this.findItemIndex(i);this.setSchedulePosition(r)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const i=!!t.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){const r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,i=c=>c&&e.getAssetPlayer(c.identifier),s=(c,h,u,f,m)=>{if(c){let g=c[h].start;const y=c.event;if(y){if(h==="playout"||y.timelineOccupancy!==ai.Point){const v=i(u);v?.interstitial===y&&(g+=v.assetItem.startOffset+v[m])}}else{const v=f==="bufferedPos"?n():e[f];g+=v-c.start}return g}return 0},r=(c,h)=>{var u;if(c!==0&&h!=="primary"&&(u=e.schedule)!=null&&u.length){var f;const m=e.schedule.findItemIndexAtTime(c),g=(f=e.schedule.items)==null?void 0:f[m];if(g)return c+(g[h].start-g.start)}return c},n=()=>{const c=e.bufferedPos;return c===Number.MAX_VALUE?a("primary"):Math.max(c,0)},a=c=>{var h,u;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:((u=e.schedule)==null?void 0:u.durations[c])||0},o=(c,h)=>{var u,f;const m=e.effectivePlayingItem;if(m!=null&&(u=m.event)!=null&&u.restrictions.skip||!e.schedule)return;e.log(`seek to ${c} "${h}"`);const g=e.effectivePlayingItem,y=e.schedule.findItemIndexAtTime(c,h),v=(f=e.schedule.items)==null?void 0:f[y],E=e.getBufferingPlayer(),T=E?.interstitial,S=T?.appendInPlace,A=g&&e.itemsMatch(g,v);if(g&&(S||A)){const b=i(e.playingAsset),I=b?.media||e.primaryMedia;if(I){const D=h==="primary"?I.currentTime:s(g,h,e.playingAsset,"timelinePos","currentTime"),P=c-D,w=(S?D:I.currentTime)+P;if(w>=0&&(!b||S||w<=b.duration)){I.currentTime=w;return}}}if(v){let b=c;if(h!=="primary"){const D=c-v[h].start;b=v.start+D}const I=!e.isInterstitial(v);if((!e.isInterstitial(g)||g.event.appendInPlace)&&(I||v.event.appendInPlace)){const D=e.media||(S?E?.media:null);D&&(D.currentTime=b)}else if(g){const D=e.findItemIndex(g);if(y>D){const w=e.schedule.findJumpRestrictedIndex(D+1,y);if(w>D){e.setSchedulePosition(w);return}}let P=0;if(I)e.timelinePos=b,e.checkBuffer();else{const w=v.event.assetList,x=c-(v[h]||v).start;for(let U=w.length;U--;){const O=w[U];if(O.duration&&x>=O.startOffset&&x<O.startOffset+O.duration){P=U;break}}}e.setSchedulePosition(y,P)}}},l=()=>{const c=e.effectivePlayingItem;if(e.isInterstitial(c))return c;const h=t();return e.isInterstitial(h)?h:null},d={get bufferedEnd(){const c=t(),h=e.bufferingItem;if(h&&h===c){var u;return s(h,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-h.playout.start||((u=e.bufferingAsset)==null?void 0:u.startOffset)||0}return 0},get currentTime(){const c=l(),h=e.effectivePlayingItem;return h&&h===c?s(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(c){const h=l(),u=e.effectivePlayingItem;u&&u===h&&o(c+u.playout.start,"playout")},get duration(){const c=l();return c?c.playout.end-c.playout.start:0},get assetPlayers(){var c;const h=(c=l())==null?void 0:c.event.assetList;return h?h.map(u=>e.getAssetPlayer(u.identifier)):[]},get playingIndex(){var c;const h=(c=l())==null?void 0:c.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var c;return((c=e.schedule)==null||(c=c.events)==null?void 0:c.slice(0))||[]},get schedule(){var c;return((c=e.schedule)==null||(c=c.items)==null?void 0:c.slice(0))||[]},get interstitialPlayer(){return l()?d:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const c=t();return e.findItemIndex(c)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const c=e.effectivePlayingItem;return e.findItemIndex(c)},primary:{get bufferedEnd(){return n()},get currentTime(){const c=e.timelinePos;return c>0?c:0},set currentTime(c){o(c,"primary")},get duration(){return a("primary")},get seekableStart(){var c;return((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0}},integrated:{get bufferedEnd(){return s(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(c){o(c,"integrated")},get duration(){return a("integrated")},get seekableStart(){var c;return r(((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0,"integrated")}},skip:()=>{const c=e.effectivePlayingItem,h=c?.event;if(h&&!h.restrictions.skip){const u=e.findItemIndex(c);h.appendInPlace?o(c.playout.start+c.event.duration+.001,"playout"):e.advanceAfterAssetEnded(h,u,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!i?!1:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let s=this.media;!s&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(s=this.primaryMedia);const r=(t=s)==null?void 0:t.currentTime;if(!(r===void 0||!N(r)))return r}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){const i=e.interstitial.appendInPlace,s=e.media;if(i&&s===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&s){this.detachedData={media:s};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ne(r)}`),this.detachedData=r}else t&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(e,t){var i,s;if(e.media===t)return;let r=null;const n=this.hls,a=e!==n,o=a&&e.interstitial.appendInPlace,l=(i=this.detachedData)==null?void 0:i.mediaSource;let d;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),d="Primary";else if(l){const f=this.getBufferingPlayer();f?(r=f.transferMedia(),d=`${f}`):d="detached MediaSource"}else d="detached media";if(!r){if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${ne(r)}`);else if(!this.detachedData||n.media===t){const f=this.playerQueue;f.length>1&&f.forEach(m=>{if(a&&m.interstitial.appendInPlace!==o){const g=m.interstitial;this.clearInterstitial(m.interstitial,null),g.appendInPlace=!1,g.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${g}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const c=r&&"mediaSource"in r&&((s=r.mediaSource)==null?void 0:s.readyState)!=="closed",h=c&&r?r:t;this.log(`${c?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${d} (media.currentTime: ${t.currentTime})`);const u=this.schedule;if(h===r&&u){const f=a&&e.assetId===u.assetIdAtEnd;h.overrides={duration:u.duration,endOfStream:!a||f,cueRemoval:!a}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const i=this.timelinePos,s=this.effectivePlayingItem;if(i===-1){const r=this.hls.startPosition;if(this.timelinePos=r,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Rt("checkStart (preroll)",r));const n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(r>=0||!this.primaryLive){this.log(Rt("checkStart",r));const n=this.timelinePos=r>0?r:0,a=e.findItemIndexAtTime(n);this.setSchedulePosition(a)}else this.hls.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(s&&!this.playingItem){this.log(Rt("checkStart (playing item)",s.start));const r=e.findItemIndex(s);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){const i=e.event,s=Er(i,i.findAssetIndex(t));if(!i.isAssetPastPlayoutLimit(s))this.bufferedToEvent(e,s);else if(this.schedule){var r;const n=(r=this.schedule.items)==null?void 0:r[this.findItemIndex(e)+1];n&&this.bufferedToItem(n)}}advanceAfterAssetEnded(e,t,i){const s=Er(e,i);if(e.isAssetPastPlayoutLimit(s)){if(this.schedule){const r=this.schedule.items;if(r){const n=t+1;if(n>=r.length){this.setSchedulePosition(-1);return}const a=e.resumeTime;this.timelinePos<a&&(this.log(Rt("advanceAfterAssetEnded",a)),this.timelinePos=a,e.appendInPlace&&this.advanceInPlace(a),this.checkBuffer(this.bufferedPos<a)),this.setSchedulePosition(n)}}}else{if(e.appendInPlace){const r=e.assetList[s];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,s)}}setScheduleToAssetAtTime(e,t){const i=this.schedule;if(!i)return;const s=t.parentIdentifier,r=i.getEvent(s);if(r){const n=i.findEventIndex(s),a=i.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,n,a-1)}}setSchedulePosition(e,t){var i;const s=(i=this.schedule)==null?void 0:i.items;if(!s||this.playbackDisabled)return;const r=e>=0?s[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Me(r)}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const d=n.event,c=this.playingAsset,h=c?.identifier,u=h?this.getAssetPlayer(h):null;if(u&&h&&(!this.eventItemsMatch(n,r)||t!==void 0&&h!==d.assetList[t].identifier)){var o;const f=d.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${f+1}/${d.assetList.length} ${Lt(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(p.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:f,event:d,schedule:s.slice(0),scheduleIndex:e,player:u}),n!==this.playingItem){this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(d,this.findItemIndex(this.playingItem),f);return}this.retreiveMediaSource(h,r),u.media&&!((o=this.detachedData)!=null&&o.mediaSource)&&u.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${d} ${Me(n)}`),d.hasPlayed=!0,this.hls.trigger(p.INTERSTITIAL_ENDED,{event:d,schedule:s.slice(0),scheduleIndex:e}),d.cue.once)){var l;this.updateSchedule();const f=(l=this.schedule)==null?void 0:l.items;if(r&&f){const m=this.findItemIndex(r);this.advanceSchedule(m,f,t,n,a)}return}}this.advanceSchedule(e,s,t,n,a)}advanceSchedule(e,t,i,s,r){const n=this.schedule;if(!n)return;const a=t[e]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(d=>{const c=d.interstitial,h=n.findEventIndex(c.identifier);(h<e||h>e+1)&&this.clearInterstitial(c,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const d=a.event;if(i===void 0){i=n.findAssetIndex(d,this.timelinePos);const f=Er(d,i-1);if(d.isAssetPastPlayoutLimit(f)||d.appendInPlace&&this.timelinePos===a.end){this.advanceAfterAssetEnded(d,e,i);return}i=f}const c=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let h=this.preloadAssets(d,i);if(this.eventItemsMatch(a,c||s)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${Me(a)} ${d.appendInPlace?"append in place":""}`),this.hls.trigger(p.INTERSTITIAL_STARTED,{event:d,schedule:t.slice(0),scheduleIndex:e})),!d.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${d}`);return}if(d.assetListLoader&&(d.assetListLoader.destroy(),d.assetListLoader=void 0),!o){this.log(`Waiting for attachMedia to start Interstitial ${d}`);return}this.waitingItem=this.endedItem=null,this.playingItem=a;const u=d.assetList[i];if(!u){this.advanceAfterAssetEnded(d,e,i||0);return}if(h||(h=this.getAssetPlayer(u.identifier)),h===null||h.destroyed){const f=d.assetList.length;this.warn(`asset ${i+1}/${f} player destroyed ${d}`),h=this.createAssetPlayer(d,u,i),h.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&d.appendInPlace&&this.isAssetBuffered(u))return;this.startAssetPlayer(h,i,t,e,o),this.shouldPlay&&yl(h.media)}else a?(this.resumePrimary(a,e,s),this.shouldPlay&&yl(this.hls.media)):r&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var s,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Me(e)}`),!((s=this.detachedData)!=null&&s.mediaSource)){let a=this.timelinePos;(a<e.start||a>=e.end)&&(a=this.getPrimaryResumption(e,t),this.log(Rt("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)}if(!i)return;const n=(r=this.schedule)==null?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Me(e)}`),this.hls.trigger(p.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const s=this.primaryDetails;if(t===0)return this.hls.startPosition;if(s&&(i<s.fragmentStart||i>s.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:Y.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const s=this.primaryMedia;if(!s)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,s),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(Rt("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;const s=this.hls;!s.loadingEnabled||!s.media||Math.abs((((i=s.mainForwardBufferInfo)==null?void 0:i.start)||s.media.currentTime)-e)>.5?s.startLoad(e,t):s.bufferingEnabled||s.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(p.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(p.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const i=this.hls.levels[t.level];if(!i.details)return;const s=ie(ie({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s,this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=ie(ie({},this.altSelection),{},{audio:i});return}const r=ie(ie({},s),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=ie(ie({},this.altSelection),{},{subtitles:i});return}const r=ie(ie({},s),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(e,t){const i=Za(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setAudioOption(t)||s.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=Za(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setSubtitleOption(t)||t.id!==-1&&s.setSubtitleOption(i)))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const s=this.timelinePos;this.bufferedPos=s,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let s=0;s<t.length;s++){const r=t[s];if(r.cue.post){var i;const n=this.schedule.findEventIndex(r.identifier),a=(i=this.schedule.items)==null?void 0:i[n];this.isInterstitial(a)&&this.eventItemsMatch(a,this.bufferingItem)&&this.bufferedToItem(a,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1}updateItem(e,t){var i;const s=(i=this.schedule)==null?void 0:i.items;return e&&s&&s[this.findItemIndex(e,t)]||null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,n)=>{e.event.isAssetPastPlayoutLimit(n)&&this.clearAssetPlayer(r.identifier,null)});const i=e.end+.25,s=Y.bufferInfo(this.primaryMedia,i,0);(s.end>i||(s.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${Me(e)} (was ${Me(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const i=this.mediaSelection;i&&((t=this.schedule)==null||t.updateSchedule(i,[],e))}checkBuffer(e){var t;const i=(t=this.schedule)==null?void 0:t.items;if(!i)return;const s=Y.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=s.len<1),this.updateBufferedPos(s.end,i,e)}updateBufferedPos(e,t,i){const s=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!s)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const n=this.playingItem,a=this.findItemIndex(n);let o=s.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const d=this.findItemIndex(r),c=Math.min(d+1,t.length-1),h=t[c];if((o===-1&&r&&e>=r.end||(l=h.event)!=null&&l.appendInPlace&&e+.01>=h.start)&&(o=c),this.isInterstitial(r)){const u=r.event;if(c-a>1&&u.appendInPlace===!1||u.assetList.length===0&&u.assetListLoader)return}if(this.bufferedPos=e,o>d&&o>a)this.bufferedToItem(h);else{const u=this.primaryDetails;this.primaryLive&&u&&e>u.edge-u.targetduration&&h.start<u.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.event,0)}}else i&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(t[o]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{const s=this.getAssetPlayer(i.identifier);return!(s!=null&&s.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){const{items:s,events:r}=i;if(!s||!r)return t;const n=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const o=a?a.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Me(e)}`+(t?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const l=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((d,c)=>{const h=this.getAssetPlayer(d.identifier);h&&(c===l&&h.loadSource(),h.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(p.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;const s=this.detachedData;s?s.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,s=i.assetList.length===0&&!i.assetListLoader,r=i.cue.once;if(s||!r){const n=this.preloadAssets(i,t);if(n!=null&&n.interstitial.appendInPlace){const a=this.primaryMedia;a&&this.bufferAssetPlayer(n,a)}}}preloadAssets(e,t){const i=e.assetUrl,s=e.assetList.length,r=s===0&&!e.assetListLoader,n=e.cue.once;if(r){const o=e.timelineStart;if(e.appendInPlace){var a;const h=this.playingItem;!this.isInterstitial(h)&&(h==null||(a=h.nextEvent)==null?void 0:a.identifier)===e.identifier&&this.flushFrontBuffer(o+.25)}let l,d=0;if(!this.playingItem&&this.primaryLive&&(d=this.hls.startPosition,d===-1&&(d=this.hls.liveSyncPosition||0)),d&&!(e.cue.pre||e.cue.post)){const h=d-o;h>0&&(l=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:s} ${e}${l?` live-start: ${d} start-offset: ${l}`:""}`),i)return this.createAsset(e,0,0,o,e.duration,i);const c=this.assetListLoader.loadAssetList(e,l);c&&(e.assetListLoader=c)}else if(!n&&s){for(let l=t;l<s;l++){const d=e.assetList[l],c=this.getAssetPlayerQueueIndex(d.identifier);(c===-1||this.playerQueue[c].destroyed)&&!d.error&&this.createAssetPlayer(e,d,l)}const o=e.assetList[t];if(o){const l=this.getAssetPlayer(o.identifier);return l&&l.loadSource(),l}}return null}flushFrontBuffer(e){const t=this.requiredTracks;t&&(this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(i=>{this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})}))}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,s,r,n){const a={parentIdentifier:e.identifier,identifier:og(e,n,t),duration:r,startOffset:i,timelineStart:s,uri:n};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,i){const s=this.hls,r=s.userConfig;let n=r.videoPreference;const a=s.loadLevelObj||s.levels[s.currentLevel];(n||a)&&(n=se({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=s.audioTracks[s.audioTrack],l=s.subtitleTracks[s.subtitleTrack];let d=0;if(this.primaryLive||e.appendInPlace){const T=this.timelinePos-t.timelineStart;if(T>1){const S=t.duration;S&&T<S&&(d=T)}}const c=t.identifier,h=ie(ie({},r),{},{maxMaxBufferLength:Math.min(180,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(h.timelineOffset=t.timelineStart));const u=h.cmcd;u!=null&&u.sessionId&&u.contentId&&(h.cmcd=se({},u,{contentId:jt(t.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${e} and asset ${c}`);const f=new Qd(this.HlsPlayerClass,h,e,t);this.playerQueue.push(f),e.assetList[i]=t;let m=!0;const g=T=>{if(T.live){var S;const I=new Error(`Interstitials MUST be VOD assets ${e}`),D={fatal:!0,type:$.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:I},P=((S=this.schedule)==null?void 0:S.findEventIndex(e.identifier))||-1;this.handleAssetItemError(D,e,P,i,I.message);return}const A=T.edge-T.fragmentStart,b=t.duration;(m||b===null||A>b)&&(m=!1,this.log(`Interstitial asset "${c}" duration change ${b} > ${A}`),t.duration=A,this.updateSchedule())};f.on(p.LEVEL_UPDATED,(T,{details:S})=>g(S)),f.on(p.LEVEL_PTS_UPDATED,(T,{details:S})=>g(S)),f.on(p.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const y=(T,S)=>{const A=this.getAssetPlayer(c);if(A&&S.tracks){A.off(p.BUFFER_CODECS,y),A.tracks=S.tracks;const b=this.primaryMedia;this.bufferingAsset===A.assetItem&&b&&!A.media&&this.bufferAssetPlayer(A,b)}};f.on(p.BUFFER_CODECS,y);const v=()=>{var T;const S=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${S}`),!S||!this.schedule)return;const A=this.schedule.findEventIndex(e.identifier),b=(T=this.schedule.items)==null?void 0:T[A];this.isInterstitial(b)&&this.advanceAssetBuffering(b,t)};f.on(p.BUFFERED_TO_END,v);const E=T=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;const S=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,S,T)};return f.once(p.MEDIA_ENDED,E(i)),f.once(p.PLAYOUT_LIMIT_REACHED,E(1/0)),f.on(p.ERROR,(T,S)=>{if(!this.schedule)return;const A=this.getAssetPlayer(c);if(S.details===L.BUFFER_STALLED_ERROR){if(A!=null&&A.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(S,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${S.error} ${e}`)}),f.on(p.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;const T=new Error(`Asset player destroyed unexpectedly ${c}`),S={fatal:!0,type:$.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:T};this.handleAssetItemError(S,e,this.schedule.findEventIndex(e.identifier),i,T.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Lt(t)}`),this.hls.trigger(p.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){const i=this.getAssetPlayerQueueIndex(e);if(i!==-1){const s=this.playerQueue[i];this.log(`clear ${s} toSegment: ${t&&Me(t)}`),this.transferMediaFromPlayer(s,t),this.playerQueue.splice(i,1),s.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,s,r){const{interstitial:n,assetItem:a,assetId:o}=e,l=n.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=a,(!d||d.identifier!==o)&&(d&&(this.clearAssetPlayer(d.identifier,i[s]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${Lt(a)}`),this.hls.trigger(p.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:n,schedule:i.slice(0),scheduleIndex:s,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var i,s;if(!this.schedule)return;const{interstitial:r,assetItem:n}=e,a=this.schedule.findEventIndex(r.identifier),o=(i=this.schedule.items)==null?void 0:i[a];if(!o)return;e.loadSource(),this.setBufferingItem(o),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===e)return;const d=r.appendInPlace;if(d&&l?.interstitial.appendInPlace===!1)return;const c=l?.tracks||((s=this.detachedData)==null?void 0:s.tracks)||this.requiredTracks;if(d&&n!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(c&&!Ca(c,e.tracks)){const h=new Error(`Asset ${Lt(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),u={fatal:!0,type:$.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},f=r.findAssetIndex(n);this.handleAssetItemError(u,r,a,f,h.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,i=this.primaryMedia;if(!t||!i)return;const s=i.currentTime,r=t.findAssetIndex(e,s),n=e.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||s-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${e} (media.currentTime: ${s})`),o&&(l/i.playbackRate<.5||a.bufferedInPlaceToEnd(i))&&a.hls){const d=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,d,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,i,s,r){if(e.details===L.BUFFER_STALLED_ERROR)return;const n=t.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n&&Lt(n)} ${e.error}`),!this.schedule)return;const a=n?.identifier||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,d=this.schedule.items,c=se({},e,{fatal:!1,errorAction:Tt(!0),asset:n,assetListIndex:s,event:t,schedule:d,scheduleIndex:i,player:l});if(this.hls.trigger(p.INTERSTITIAL_ASSET_ERROR,c),!e.fatal)return;const h=this.playingAsset,u=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(a,null),n.error=f),!t.assetList.some(m=>!m.error))t.error=f;else for(let m=s;m<t.assetList.length;m++)this.resetAssetPlayer(t.assetList[m].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):h&&h.identifier===a?this.advanceAfterAssetEnded(t,i,s):u&&u.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,u)}primaryFallback(e){const t=e.timelineStart,i=this.effectivePlayingItem;let s=this.timelinePos;if(i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${s} playing: ${Me(i)} error: ${e.error}`),s===-1&&(s=this.hls.startPosition);const n=this.updateItem(i,s);this.itemsMatch(i,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(s===-1){this.checkStart();return}if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(r)}onAssetListLoaded(e,t){var i,s;const r=t.event,n=r.identifier,a=t.assetListResponse.ASSETS;if(!((i=this.schedule)!=null&&i.hasEvent(n)))return;const o=r.timelineStart,l=r.duration;let d=0;a.forEach((m,g)=>{const y=parseFloat(m.DURATION);this.createAsset(r,g,d,o+d,y,m.URI),d+=y}),r.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${l}) ${r}`);const c=this.waitingItem,h=c?.event.identifier===n;this.updateSchedule();const u=(s=this.bufferingItem)==null?void 0:s.event;if(h){var f;const m=this.schedule.findEventIndex(n),g=(f=this.schedule.items)==null?void 0:f[m];if(g){if(!this.playingItem&&this.timelinePos>g.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==m){r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(g)}this.setSchedulePosition(m)}else if(u?.identifier===n){const m=r.assetList[0];if(m){const g=this.getAssetPlayer(m.identifier);if(u.appendInPlace){const y=this.primaryMedia;g&&y&&this.bufferAssetPlayer(g,y)}else g&&g.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case L.ASSET_LIST_PARSING_ERROR:case L.ASSET_LIST_LOAD_ERROR:case L.ASSET_LIST_LOAD_TIMEOUT:{const i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case L.BUFFER_STALLED_ERROR:{const i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},En=500,Tn=class extends Zt{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",B.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=_.IDLE,this.setInterval(En),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:s}=t;if(this.fragContextChanged(i)||(de(i)&&(this.fragPrevious=i),this.state=_.IDLE),!s)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=i.start;for(let l=0;l<r.length;l++)if(a>=r[l].start&&a<=r[l].end){n=r[l];break}const o=i.start+i.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:i,endOffset:s}=t;if(i===0&&s!==Number.POSITIVE_INFINITY){const r=s-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(n=>{for(let a=0;a<n.length;){if(n[a].end<=r){n.shift();continue}else if(n[a].start<r)n[a].start=r;else break;a++}}),this.fragmentTracker.removeFragmentsInRange(i,r,B.SUBTITLE)}}onError(e,t){const i=t.frag;i?.type===B.SUBTITLE&&(t.details===L.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==_.STOPPED&&(this.state=_.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&sl(this.levels,t)){this.levels=t.map(i=>new ht(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const s=new ht(i);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,B.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}const s=this.levels[this.currentTrackId];s!=null&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.state!==_.STOPPED&&this.setInterval(En)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:s,levels:r}=this,{details:n,id:a}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${a}`);return}const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||(i=o.details)!=null&&i.live){if(n.deltaUpdateFailed)return;const c=this.mainDetails;if(!c){this.startFragRequested=!1;return}const h=c.fragments[0];if(!o.details)n.hasProgramDateTime&&c.hasProgramDateTime?(Oi(n,c),l=n.fragmentStart):h&&(l=h.start,ir(n,l));else{var d;l=this.alignPlaylists(n,o.details,(d=this.levelLastLoaded)==null?void 0:d.details),l===0&&h&&(l=h.start,ir(n,l))}c&&!this.startFragRequested&&this.setStartPosition(c,l)}o.details=n,this.levelLastLoaded=o,a===s&&(this.hls.trigger(p.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===_.IDLE&&(lt(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,s=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&s!=null&&s.key&&s.iv&&bt(s.method)){const n=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,Xs(s.method)).catch(a=>{throw r.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t}),a}).then(a=>{const o=performance.now();r.trigger(p.FRAG_DECRYPTED,{frag:t,payload:a,stats:{tstart:n,tdecrypt:o}})}).catch(a=>{this.warn(`${a.name}: ${a.message}`),this.state=_.IDLE})}}doTick(){if(!this.media){this.state=_.IDLE;return}if(this.state===_.IDLE){const{currentTrackId:e,levels:t}=this,i=t?.[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;const{config:s}=this,r=this.getLoadPosition(),{end:n,len:a}=Y.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,s.maxBufferHole),o=i.details;if(a>this.hls.maxBufferLength+o.levelTargetDuration)return;const l=o.fragments,d=l.length,c=o.edge;let h=null;const u=this.fragPrevious;if(n<c){const m=s.maxFragLookUpTolerance,g=n>c-m?0:m;h=lt(u,l,Math.max(l[0].start,n),g),!h&&u&&u.start<l[0].start&&(h=l[0])}else h=l[d-1];if(h=this.filterReplacedPrimary(h,i.details),!h)return;const f=l[h.sn-o.startSN-1];if(f&&f.cc===h.cc&&this.fragmentTracker.getState(f)===he.NOT_LOADED&&(h=f),this.fragmentTracker.getState(h)===he.NOT_LOADED){const m=this.mapToInitFragWhenRequired(h);m&&this.loadFragment(m,i,n)}}}loadFragment(e,t,i){de(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new tc(this.tracksBuffered[this.currentTrackId]||[])}},tc=class{constructor(e){this.buffered=void 0;const t=(i,s,r)=>{if(s=s>>>0,s>r-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${r})`);return e[s][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}},ic={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Sn=e=>String.fromCharCode(ic[e]||e),xe=15,Ke=100,sc={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},rc={17:2,18:4,21:6,22:8,23:10,19:13,20:15},nc={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},ac={25:2,26:4,29:6,30:8,31:10,27:13,28:15},oc=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],lc=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;te.log(`${this.time} [${e}] ${i}`)}}},st=function(t){const i=[];for(let s=0;s<t.length;s++)i.push(t[s].toString(16));return i},bn=class{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){const s=t[i];e.hasOwnProperty(s)&&(this[s]=e[s])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},dc=class{constructor(){this.uchar=" ",this.penState=new bn}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}},cc=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new bn,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ke;t++)this.chars.push(new dc);this.logger=e}equals(e){for(let t=0;t<Ke;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Ke;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Ke;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Ke&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ke)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Sn(e);if(this.pos>=Ke){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Ke;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let i=0;i<Ke;i++){const s=this.chars[i].uchar;s!==" "&&(t=!1),e.push(s)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},ds=class{constructor(e){this.rows=[],this.currRow=xe-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<xe;t++)this.rows.push(new cc(e));this.logger=e}reset(){for(let e=0;e<xe;e++)this.rows[e].clear();this.currRow=xe-1}equals(e){let t=!0;for(let i=0;i<xe;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<xe;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<xe;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+ne(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let a=0;a<xe;a++)this.rows[a].clear();const r=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){const a=n.rows[r].cueStartTime,o=this.logger.time;if(a!==null&&o!==null&&a<o)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(n.rows[r+l])}}this.currRow=t;const i=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,n=Math.max(r-1,0);i.setCursor(e.indent),e.color=i.chars[n].penState.foreground}const s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+ne(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",s=-1;for(let r=0;r<xe;r++){const n=this.rows[r].getTextString();n&&(s=r+1,e?t.push("Row "+s+": '"+n+"'"):t.push(n.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
|
|
76
|
+
`)),i}getTextAndFormat(){return this.rows}},In=class{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new ds(i),this.nonDisplayedMemory=new ds(i),this.lastOutputScreen=new ds(i),this.currRollUpRow=this.displayedMemory.rows[xe-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[xe-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};t.underline=e%2===1,t.italics=e>=46,t.italics?t.foreground="white":t.foreground=["white","green","blue","cyan","red","yellow","magenta"][Math.floor(e/2)-16],this.logger.log(2,"MIDROW: "+ne(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},An=class{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=cg(),this.logger=void 0;const s=this.logger=new lc;this.channels=[null,new In(e,t,s),new In(e+1,i,s)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){const s=t[i]&127,r=t[i+1]&127;let n=!1,a=null;if(s===0&&r===0)continue;this.logger.log(3,()=>"["+st([t[i],t[i+1]])+"] -> ("+st([s,r])+")");const o=this.cmdHistory;if(s>=16&&s<=31){if(dg(s,r,o)){Vi(null,null,o),this.logger.log(3,()=>"Repeated command ("+st([s,r])+") is dropped");continue}Vi(s,r,this.cmdHistory),n=this.parseCmd(s,r),n||(n=this.parseMidrow(s,r)),n||(n=this.parsePAC(s,r)),n||(n=this.parseBackgroundAttributes(s,r))}else Vi(null,null,o);if(!n&&(a=this.parseChars(s,r),a)){const l=this.currentChannel;l&&l>0?this.channels[l].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!n&&!a&&this.logger.log(2,()=>"Couldn't parse cleaned data "+st([s,r])+" orig: "+st([t[i],t[i+1]]))}}parseCmd(e,t){if(!((e===20||e===28||e===21||e===29)&&t>=32&&t<=47||(e===23||e===31)&&t>=33&&t<=35))return!1;const i=e===20||e===21||e===23?1:2,s=this.channels[i];return e===20||e===21||e===28||e===29?t===32?s.ccRCL():t===33?s.ccBS():t===34?s.ccAOF():t===35?s.ccAON():t===36?s.ccDER():t===37?s.ccRU(2):t===38?s.ccRU(3):t===39?s.ccRU(4):t===40?s.ccFON():t===41?s.ccRDC():t===42?s.ccTR():t===43?s.ccRTD():t===44?s.ccEDM():t===45?s.ccCR():t===46?s.ccENM():t===47&&s.ccEOC():s.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const s=this.channels[i];return s?(s.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+st([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(e===16||e===24)&&t>=64&&t<=95))return!1;const s=e<=23?1:2;t>=64&&t<=95?i=s===1?sc[e]:nc[e]:i=s===1?rc[e]:ac[e];const r=this.channels[s];return r?(r.setPAC(this.interpretPAC(i,t)),this.currentChannel=s,!0):!1}interpretPAC(e,t){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,s.underline=(i&1)===1,i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=Math.floor((i-16)/2)*4,s}parseChars(e,t){let i,s=null,r=null;if(e>=25?(i=2,r=e-8):(i=1,r=e),r>=17&&r<=19){let n;r===17?n=t+80:r===18?n=t+112:n=t+144,this.logger.log(2,()=>"Special char '"+Sn(n)+"' in channel "+i),s=[n]}else e>=32&&e<=127&&(s=t===0?[e]:[e,t]);return s&&this.logger.log(3,()=>"Char codes = "+st(s).join(",")),s}parseBackgroundAttributes(e,t){if(!((e===16||e===24)&&t>=32&&t<=47||(e===23||e===31)&&t>=45&&t<=47))return!1;let i;const s={};e===16||e===24?(i=Math.floor((t-32)/2),s.background=oc[i],t%2===1&&(s.background=s.background+"_semi")):t===45?s.background="transparent":(s.foreground="black",t===47&&(s.underline=!0));const r=e<=23?1:2;return this.channels[r].setBkgData(s),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Vi(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const i=this.channels[t];i&&i.cueSplitAtTime(e)}}},cs=(function(){if(Qt!=null&&Qt.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function i(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const d=l.toLowerCase();return~o.indexOf(d)?d:!1}function s(o){return i(e,o)}function r(o){return i(t,o)}function n(o,...l){let d=1;for(;d<arguments.length;d++){const c=arguments[d];for(const h in c)o[h]=c[h]}return o}function a(o,l,d){const c=this,h={enumerable:!0};c.hasBeenReset=!1;let u="",f=!1,m=o,g=l,y=d,v=null,E="",T=!0,S="auto",A="start",b=50,I="middle",D=50,P="middle";Object.defineProperty(c,"id",n({},h,{get:function(){return u},set:function(w){u=""+w}})),Object.defineProperty(c,"pauseOnExit",n({},h,{get:function(){return f},set:function(w){f=!!w}})),Object.defineProperty(c,"startTime",n({},h,{get:function(){return m},set:function(w){if(typeof w!="number")throw new TypeError("Start time must be set to a number.");m=w,this.hasBeenReset=!0}})),Object.defineProperty(c,"endTime",n({},h,{get:function(){return g},set:function(w){if(typeof w!="number")throw new TypeError("End time must be set to a number.");g=w,this.hasBeenReset=!0}})),Object.defineProperty(c,"text",n({},h,{get:function(){return y},set:function(w){y=""+w,this.hasBeenReset=!0}})),Object.defineProperty(c,"region",n({},h,{get:function(){return v},set:function(w){v=w,this.hasBeenReset=!0}})),Object.defineProperty(c,"vertical",n({},h,{get:function(){return E},set:function(w){const x=s(w);if(x===!1)throw new SyntaxError("An invalid or illegal string was specified.");E=x,this.hasBeenReset=!0}})),Object.defineProperty(c,"snapToLines",n({},h,{get:function(){return T},set:function(w){T=!!w,this.hasBeenReset=!0}})),Object.defineProperty(c,"line",n({},h,{get:function(){return S},set:function(w){if(typeof w!="number"&&w!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=w,this.hasBeenReset=!0}})),Object.defineProperty(c,"lineAlign",n({},h,{get:function(){return A},set:function(w){const x=r(w);if(!x)throw new SyntaxError("An invalid or illegal string was specified.");A=x,this.hasBeenReset=!0}})),Object.defineProperty(c,"position",n({},h,{get:function(){return b},set:function(w){if(w<0||w>100)throw new Error("Position must be between 0 and 100.");b=w,this.hasBeenReset=!0}})),Object.defineProperty(c,"positionAlign",n({},h,{get:function(){return I},set:function(w){const x=r(w);if(!x)throw new SyntaxError("An invalid or illegal string was specified.");I=x,this.hasBeenReset=!0}})),Object.defineProperty(c,"size",n({},h,{get:function(){return D},set:function(w){if(w<0||w>100)throw new Error("Size must be between 0 and 100.");D=w,this.hasBeenReset=!0}})),Object.defineProperty(c,"align",n({},h,{get:function(){return P},set:function(w){const x=r(w);if(!x)throw new SyntaxError("An invalid or illegal string was specified.");P=x,this.hasBeenReset=!0}})),c.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})(),hc=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}},uc=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let s=0;s<i.length;++s)if(t===i[s]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}},hs=new cs(0,0,""),oi=hs.align==="middle"?"middle":"center",fc=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new hc,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let r=t.buffer,n=0;for(r=Tl(r);n<r.length&&r[n]!=="\r"&&r[n]!==`
|
|
77
77
|
`;)++n;const a=r.slice(0,n);return r[n]==="\r"&&++n,r[n]===`
|
|
78
78
|
`&&++n,t.buffer=r.slice(n),a}function s(r){El(r,function(n,a){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=i();const a=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(a!=null&&a[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let n=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(n?n=!1:r=i(),t.state){case"HEADER":/:/.test(r)?s(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new cs(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{hg(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const a=r.indexOf("-->")!==-1;if(!r||a&&(n=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
|
|
79
79
|
`),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
|
|
80
80
|
|
|
81
|
-
`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}},gc=/\r\n|\n\r|\n|\r/g,us=function(t,i,s=0){return t.slice(s,s+i.length)===i},mc=function(t){let i=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),r=parseInt(t.slice(-9,-7)),n=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!N(i)||!N(s)||!N(r)||!N(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return i+=1e3*s,i+=60*1e3*r,i+=3600*1e3*n,i},pc=function(t,i,s){let r=t[i],n=t[r.prevCC];if(!n||!n.new&&r.new){t.ccOffset=t.presentationOffset=r.start,r.new=!1;return}for(;(a=n)!=null&&a.new;){var a;t.ccOffset+=r.start-n.start,r.new=!1,r=n,n=t[r.prevCC]}t.presentationOffset=s},fs="stpp.ttml.im1t",Ln=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Rn=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,yc={left:"start",center:"center",right:"end",start:"start",end:"end"},li=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Dn=class{constructor(e){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.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Dl(),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}},e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new li(this,"textTrack1"),t=new li(this,"textTrack2"),i=new li(this,"textTrack3"),s=new li(this,"textTrack4");this.cea608Parser1=new An(1,e,t),this.cea608Parser2=new An(3,i,s)}addCues(e,t,i,s,r){let n=!1;for(let a=r.length;a--;){const o=r[a],l=yg(o[0],o[1],t,i);if(l>=0&&(o[0]=Math.min(o[0],t),o[1]=Math.max(o[1],i),n=!0,l/(i-t)>.5))return}if(n||r.push([t,i]),this.config.renderTextTracksNatively){const a=this.captionsTracks[e];this.Cues.newCue(a,t,i,s)}else{const a=this.Cues.newCue(null,t,i,s);this.hls.trigger(p.CUES_PARSED,{type:"captions",cues:a,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:r,trackId:n}){const{unparsedVttFrags:a}=this;i===B.MAIN&&(this.initPTS[t.cc]={baseTime:s,timescale:r,trackId:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.initPTS[o.frag.cc]?this.onFragLoaded(p.FRAG_LOADED,o):this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:o.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){const r=i.textTracks[s];if(Rl(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:s}=this,{label:r,languageCode:n}=t[e],a=this.getExistingTrack(r,n);if(a)i[e]=a,At(i[e]),gl(i[e],s);else{const o=this.createTextTrack("captions",r,n);o&&(o[e]=!0,i[e]=o)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i={_id:e,label:t.label,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,i){const s=this.media;if(s)return s.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const i=!!t.transferMedia;if(this.media=null,i)return;const{captionsTracks:s}=this;Object.keys(s).forEach(r=>{At(s[r]),delete s[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Dl(),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(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let i=0;i<t.length;i++)At(t[i])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],s=i.some(r=>r.textCodec===fs);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(sl(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const r=this.media,n=r?Gi(r.textTracks):null;if(this.tracks.forEach((a,o)=>{let l;if(n){let d=null;for(let c=0;c<n.length;c++)if(n[c]&&Rl(n[c],a)){d=n[c],n[c]=null;break}d&&(l=d)}if(l)At(l);else{const d=Ll(a);l=this.createTextTrack(d,a.name,a.lang),l&&(l.mode="disabled")}l&&this.textTracks.push(l)}),n!=null&&n.length){const a=n.filter(o=>o!==null).map(o=>o.label);a.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${a.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const r=this.tracks.map(n=>({label:n.name,kind:n.type.toLowerCase(),default:n.default,subtitleTrack:n}));this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:r})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;const r=`textTrack${s[1]}`,n=this.captionsProperties[r];n&&(n.label=i.name,i.lang&&(n.languageCode=i.lang),n.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===B.MAIN){var i,s;const{cea608Parser1:r,cea608Parser2:n,lastSn:a}=this,{cc:o,sn:l}=t.frag,d=(i=(s=t.part)==null?void 0:s.index)!=null?i:-1;r&&n&&(l!==a+1||l===a&&d!==this.lastPartIndex+1||o!==this.lastCc)&&(r.reset(),n.reset()),this.lastCc=o,this.lastSn=l,this.lastPartIndex=d}}onFragLoaded(e,t){const{frag:i,payload:s}=t;if(i.type===B.SUBTITLE)if(s.byteLength){const r=i.decryptdata,n="stats"in t;if(r==null||!r.encrypted||n){const a=this.tracks[i.level],o=this.vttCCs;o[i.cc]||(o[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),a&&a.textCodec===fs?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;Sl(t,this.initPTS[e.cc],s=>{this._appendCues(s,e.level),i.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},s=>{i.logger.log(`Failed to parse IMSC1: ${s}`),i.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:s})})}_parseVTTs(e){var t;const{frag:i,payload:s}=e,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[i.cc]&&a===-1){n.push(e);return}const o=this.hls;ug((t=i.initSegment)!=null&&t.data?Ce(i.initSegment.data,new Uint8Array(s)).buffer:s,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,l=>{this._appendCues(l,i.level),o.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},l=>{const d=l.message==="Missing initPTS for VTT MPEGTS";d?n.push(e):this._fallbackToIMSC1(i,s),o.logger.log(`Failed to parse VTT cue: ${l}`),!(d&&a>i.cc)&&o.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:l})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||Sl(t,this.initPTS[e.cc],()=>{i.textCodec=fs,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[t];if(!s||s.mode==="disabled")return;e.forEach(r=>ml(s,r))}else{const s=this.tracks[t];if(!s)return;const r=s.default?"default":"subtitles"+t;i.trigger(p.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===B.SUBTITLE&&this.onFragLoaded(p.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:s}=t;if(!(i.type===B.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let r=0;r<s.length;r++){const n=s[r].bytes;if(n){this.cea608Parser1||this.initCea608Parsers();const a=this.extractCea608Data(n);this.cea608Parser1.addData(s[r].pts,a[0]),this.cea608Parser2.addData(s[r].pts,a[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:s,type:r}){const{media:n}=this;if(!(!n||n.currentTime<i)){if(!r||r==="video"){const{captionsTracks:a}=this;Object.keys(a).forEach(o=>yr(a[o],t,i))}if(this.config.renderTextTracksNatively&&t===0&&s!==void 0){const{textTracks:a}=this;Object.keys(a).forEach(o=>yr(a[o],t,s))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let s=2;for(let r=0;r<i;r++){const n=e[s++],a=127&e[s++],o=127&e[s++];if(!(a===0&&o===0)&&(4&n)!==0){const l=3&n;(l===0||l===1)&&(t[l].push(a),t[l].push(o))}}return t}},vc=/\s/,Pn={newCue(e,t,i,s){const r=[];let n,a,o,l,d;const c=self.VTTCue||self.TextTrackCue;for(let u=0;u<s.rows.length;u++)if(n=s.rows[u],o=!0,l=0,d="",!n.isEmpty()){var h;for(let g=0;g<n.chars.length;g++)vc.test(n.chars[g].uchar)&&o?l++:(d+=n.chars[g].uchar,o=!1);n.cueStartTime=t,t===i&&(i+=1e-4),l>=16?l--:l++;const f=Tl(d.trim()),m=Tr(t,i,f);e!=null&&(h=e.cues)!=null&&h.getCueById(m)||(a=new c(t,i,f),a.id=m,a.line=u+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a))}return e&&r.length&&(r.sort((u,f)=>u.line==="auto"||f.line==="auto"?0:u.line>8&&f.line>8?f.line-u.line:u.line-f.line),r.forEach(u=>ml(e,u))),r}},Ec=/(\d+)-(\d+)\/(\d+)/,gs=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Sg,this.controller=new self.AbortController,this.stats=new Yt}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(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){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const r=vg(e,this.controller.signal),n=e.responseType==="arraybuffer",a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=o&&N(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},t.timeout),(Ht(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(d=>{var c;this.response=this.loader=d;const h=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},l-(h-s.loading.start)),!d.ok){const{status:f,statusText:m}=d;throw new Tc(m||"fetch, bad network response",f,d)}s.loading.first=h,s.total=Tg(d.headers)||s.total;const u=(c=this.callbacks)==null?void 0:c.onProgress;return u&&N(t.highWaterMark)?this.loadProgressively(d,s,e,t.highWaterMark,u):n?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{var c,h;const u=this.response;if(!u)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const f=d[a];f&&(s.loaded=s.total=f);const m={url:u.url,data:d,code:u.status},g=(c=this.callbacks)==null?void 0:c.onProgress;g&&!N(t.highWaterMark)&&g(s,e,d,u),(h=this.callbacks)==null||h.onSuccess(m,s,e,u)}).catch(d=>{var c;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const h=d&&d.code||0,u=d?d.message:null;(c=this.callbacks)==null||c.onError({code:h,text:u},e,d?d.details:null,s)})}getCacheAge(){let e=null;if(this.response){const 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,s=0,r){const n=new jr,a=e.body.getReader(),o=()=>a.read().then(l=>{if(l.done)return n.dataLength&&r(t,i,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const d=l.value,c=d.length;return t.loaded+=c,c<s||n.dataLength?(n.push(d),n.dataLength>=s&&r(t,i,n.flush().buffer,e)):r(t,i,d.buffer,e),o()}).catch(()=>Promise.reject());return o()}},Tc=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}},Sc=/^age:\s*[\d.]+\s*$/im,ms=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=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Yt,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const 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(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return r(i,t.url)}).catch(n=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),r(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(n=>{var a;(a=this.callbacks)==null||a.onError({code:i.status,text:n.message},t,i,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const s=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=i.loadPolicy;if(s)for(const a in s)e.setRequestHeader(a,s[a]);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=r&&N(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const s=t.readyState,r=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,d=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const u=d??t.response;if(u!=null){var n,a;i.loading.end=Math.max(self.performance.now(),i.loading.first),i.loaded=i.total=t.responseType==="arraybuffer"?u.byteLength:u.length,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const f=(n=this.callbacks)==null?void 0:n.onProgress;f&&f(i,e,u,t);const m={url:t.responseURL,data:u,code:l};(a=this.callbacks)==null||a.onSuccess(m,i,e,t);return}}const c=r.loadPolicy.errorRetry,h=i.retry;if(_i(c,h,!1,{url:e.url,data:void 0,code:l}))this.retry(c);else{var o;te.error(`${l} while loading ${e.url}`),(o=this.callbacks)==null||o.onError({code:l,text:t.statusText},e,t,i)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(_i(e,t,!0))this.retry(e);else{var i;te.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Ys(e,i.retry),i.retry++,te.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){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Sc.test(this.loader.getAllResponseHeaders())){const 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}},bc=ie(ie({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,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,ignorePlaylistParsingErrors:!1,loader:ms,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Or,bufferController:nn,capLevelController:an,errorController:Nr,fpsController:pn,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Ji,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},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}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,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},bg()),{},{subtitleStreamController:Tn,subtitleTrackController:yn,timelineController:Dn,audioStreamController:en,audioTrackController:tn,emeController:ls,cmcdController:gn,contentSteeringController:mn,interstitialsController:ec}),di=2,Ic=.1,Ac=.05,Lc=100,Rc=class extends Br{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(Lc),this.mediaSource=t.mediaSource;const i=this.media=t.media;Ee(i,"playing",this.onMediaPlaying),Ee(i,"waiting",this.onMediaWaiting),Ee(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(Le(i,"playing",this.onMediaPlaying),Le(i,"waiting",this.onMediaWaiting),Le(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,s;const r=(i=this.hls)==null?void 0:i.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,d=n.paused&&!a||n.ended||n.playbackRate===0;if(this.seeking=a,e!==t){t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!d&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||o){o&&this.stallResolved(e);return}if(d){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!1}));return}if(!Y.getBuffered(n).length){this.nudgeRetry=0;return}const c=Y.bufferInfo(n,e,0),h=c.nextStart||0,u=this.fragmentTracker;if(a&&u&&this.hls){const A=wl(this.hls.inFlightFragments,e),b=c.len>di,I=!h||A||h-e>di&&!u.getPartialFragment(e);if(b||I)return;this.moved=!1}const f=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&u){if(!(c.len>0)&&!h)return;const A=Math.max(h,c.start||0)-e,b=f!=null&&f.live?f.targetduration*2:di,I=Ki(e,u);if(A>0&&(A<=b||I)){n.paused||this._trySkipBufferHole(I);return}}const m=r.detectStallWithCurrentTimeMs,g=self.performance.now(),y=this.waiting;let v=this.stalled;if(v===null)if(y>0&&g-y<m)v=this.stalled=y;else{this.stalled=g;return}const E=g-v;if(!a&&(E>=m||y)&&this.hls){var T;if(((T=this.mediaSource)==null?void 0:T.readyState)==="ended"&&!(f!=null&&f.live)&&Math.abs(e-(f?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return}const S=Y.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(S,E,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(p.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&s&&s.length>1&&e>s.end(0)){const r=Y.bufferedInfo(Y.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const n=Y.timeRangesToArray(s),a=Y.bufferedInfo(n,t,0).bufferedIndex;if(a>-1&&a<n.length-1){const o=Y.bufferedInfo(n,e,0).bufferedIndex,l=n[a].end,d=n[a+1].start;if((o===-1||o>a)&&d-l<1&&e-l<2){const c=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${d} buffered index: ${o}`);this.warn(c.message),this.media.currentTime+=1e-6;let h=Ki(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);const u=Y.bufferInfo(this.media,e,0);this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:h,buffer:u.len,bufferInfo:u})}}}}}_tryFixBufferStall(e,t,i){var s,r;const{fragmentTracker:n,media:a}=this,o=(s=this.hls)==null?void 0:s.config;if(!a||!n||!o)return;const l=(r=this.hls)==null?void 0:r.latestLevelDetails,d=Ki(i,n);if((d||l!=null&&l.live&&i<l.fragmentStart)&&(this._trySkipBufferHole(d)||!this.media))return;const c=e.buffered,h=this.adjacentTraversal(e,i);(c&&c.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-i<o.maxBufferHole||h))&&(t>o.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const i=this.fragmentTracker,s=e.nextStart;if(i&&s){const r=i.getFragAtPos(t,B.MAIN),n=i.getFragAtPos(s,B.MAIN);if(r&&n)return n.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:i,stallReported:s,stalled:r}=this;if(!s&&r!==null&&i&&t){this.stallReported=!0;const n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${ne(e)})`);this.warn(n.message),t.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:s}=this,r=(t=this.hls)==null?void 0:t.config;if(!s||!i||!r)return 0;const n=s.currentTime,a=Y.bufferInfo(s,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const d=a.len<=r.maxBufferHole,c=a.len>0&&a.len<1&&s.readyState<3,h=o-n;if(h>0&&(d||c)){if(h>r.maxBufferHole){let f=!1;if(n===0){const m=i.getAppendedFrag(0,B.MAIN);m&&o<m.end&&(f=!0)}if(!f&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||wl(this.hls.inFlightFragments,o))return 0;let m=!1,g=e.end;for(;g<o;){const y=Ki(g,i);if(y)g+=y.duration;else{m=!0;break}}if(m)return 0}}const u=Math.max(o+Ac,n+Ic);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${u}`),this.moved=!0,s.currentTime=u,!(e!=null&&e.gap)){const f=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${u}`),m={type:$.MEDIA_ERROR,details:L.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:f,reason:f.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?m.part=e:m.frag=e),this.hls.trigger(p.ERROR,m)}return u}}return 0}_tryNudgeBuffer(e){const{hls:t,media:i,nudgeRetry:s}=this,r=t?.config;if(!i||!r)return 0;const n=i.currentTime;if(this.nudgeRetry++,s<r.nudgeMaxRetry){const a=n+(s+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),i.currentTime=a,t.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const a=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(a.message),t.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,error:a,fatal:!0,buffer:e.len,bufferInfo:e})}}},Dc=.25,ci=(()=>{const e=Lr();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),Pc=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(p.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,((i=t.overrides)==null?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&At(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const i=e[t];if(i.kind==="metadata"&&i.label==="id3")return gl(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Lr();if(n)for(let a=0;a<r.length;a++){const o=r[a].type;if(o===Se.emsg&&!i||!s)continue;const l=Ho(r[a].data),d=r[a].pts;let c=d+r[a].duration;c>ci&&(c=ci),c-d<=0&&(c=d+Dc);for(let h=0;h<l.length;h++){const u=l[h];if(!Wo(u)){this.updateId3CueEnds(d,o);const f=Rr(n,d,c,u,o);f&&this.id3Track.addCue(f)}}}}updateId3CueEnds(e,t){var i;const s=(i=this.id3Track)==null?void 0:i.cues;if(s)for(let r=s.length;r--;){const n=s[r];n.type===t&&n.startTime<e&&n.endTime===ci&&(n.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let l;s==="audio"?l=d=>d.type===Se.audioId3&&o:s==="video"?l=d=>d.type===Se.emsg&&a:l=d=>d.type===Se.audioId3&&o||d.type===Se.emsg&&a,yr(r,t,i,l)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:s,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const a=Lr();if(i&&s&&!n){const{fragmentStart:m,fragmentEnd:g}=e;let y=this.assetCue;y?(y.startTime=m,y.endTime=g):a&&(y=this.assetCue=Rr(a,m,g,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),y&&(y.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(y),y.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=e,d=Object.keys(l);let c=this.dateRangeCuesAppended;if(o&&t){var h;if((h=o.cues)!=null&&h.length){const m=Object.keys(c).filter(g=>!d.includes(g));for(let g=m.length;g--;){var u;const y=m[g],v=(u=c[y])==null?void 0:u.cues;delete c[y],v&&Object.keys(v).forEach(E=>{const T=v[E];if(T){T.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(T)}catch{}}})}}else c=this.dateRangeCuesAppended={}}const f=e.fragments[e.fragments.length-1];if(!(d.length===0||!N(f?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let m=0;m<d.length;m++){const g=d[m],y=l[g],v=y.startTime,E=c[g],T=E?.cues||{};let S=E?.durationKnown||!1,A=ci;const{duration:b,endDate:I}=y;if(I&&b!==null)A=v+b,S=!0;else if(y.endOnNext&&!S){const w=d.reduce((P,x)=>{if(x!==y.id){const U=l[x];if(U.class===y.class&&U.startDate>y.startDate&&(!P||y.startDate<P.startDate))return U}return P},null);w&&(A=w.startTime,S=!0)}const D=Object.keys(y.attr);for(let w=0;w<D.length;w++){const P=D[w];if(!Mu(P))continue;const x=T[P];if(x)S&&!(E!=null&&E.durationKnown)?x.endTime=A:Math.abs(x.startTime-v)>.01&&(x.startTime=v,x.endTime=A);else if(a){let U=y.attr[P];Ou(P)&&(U=xa(U));const O=Rr(a,v,A,{key:P,data:U},Se.dateRange);O&&(O.id=g,this.id3Track.addCue(O),T[P]=O,n&&(P==="X-ASSET-LIST"||P==="X-ASSET-URL")&&O.addEventListener("enter",this.onEventCueEnter))}}c[g]={cues:T,dateRange:y,durationKnown:S}}}}},wc=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.currentTime;const s=this.computeLatency();if(s===null)return;this._latency=s;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:n}=this.config;if(!r||n===1||!i.live)return;const a=this.targetLatency;if(a===null)return;const o=s-a;if(o<Math.min(this.maxLatency,a+i.targetduration)&&o>.05&&this.forwardBufferLength>1){const l=Math.min(2,Math.max(1,n)),d=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20,c=Math.min(l,Math.max(1,d));this.changeMediaPlaybackRate(t,c)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:i,targetduration:s}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||l===0)&&(l=r!==void 0?r:n*s);const d=s;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const i=this.levelDetails;if(i===null)return null;const s=i.edge,r=e-t-this.edgeStalled,n=s-i.totalduration,a=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===L.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,s;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},_c=class extends si{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,s=[],r={},n={};let a=!1,o=!1,l=!1;t.levels.forEach(d=>{const c=d.attrs;let{audioCodec:h,videoCodec:u}=d;h&&(d.audioCodec=h=Ri(h,i)||void 0),u&&(u=d.videoCodec=cu(u));const{width:f,height:m,unknownCodecs:g}=d,y=g?.length||0;if(a||(a=!!(f&&m)),o||(o=!!u),l||(l=!!h),y||h&&!this.isAudioSupported(h)||u&&!this.isVideoSupported(u)){this.log(`Some or all CODECS not supported "${c.CODECS}"`);return}const{CODECS:v,"FRAME-RATE":E,"HDCP-LEVEL":T,"PATHWAY-ID":S,RESOLUTION:A,"VIDEO-RANGE":b}=c,I=`${`${S||"."}-`}${d.bitrate}-${A}-${E}-${v}-${b}-${T}`;if(r[I])if(r[I].uri!==d.url&&!d.attrs["PATHWAY-ID"]){const D=n[I]+=1;d.attrs["PATHWAY-ID"]=new Array(D+1).join(".");const w=this.createLevel(d);r[I]=w,s.push(w)}else r[I].addGroupId("audio",c.AUDIO),r[I].addGroupId("text",c.SUBTITLES);else{const D=this.createLevel(d);r[I]=D,n[I]=1,s.push(D)}}),this.filterAndSortMediaOptions(s,t,a,o,l)}createLevel(e){const t=new ht(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const s=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(s.message),t.supportedResult=ja(s,[])}return t}isAudioSupported(e){return Ut(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Ut(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,s,r){var n;let a=[],o=[],l=e;const d=((n=t.stats)==null?void 0:n.parsing)||{};if((i||s)&&r&&(l=l.filter(({videoCodec:v,videoRange:E,width:T,height:S})=>(!!v||!!(T&&S))&&vu(E))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let v="no level with compatible codecs found in manifest",E=v;t.levels.length&&(E=`one or more CODECS in variant not supported: ${ne(t.levels.map(S=>S.attrs.CODECS).filter((S,A,b)=>b.indexOf(S)===A))}`,this.warn(E),v+=` (${E})`);const T=new Error(v);this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:T,reason:E})}}),d.end=performance.now();return}t.audioTracks&&(a=t.audioTracks.filter(v=>!v.audioCodec||this.isAudioSupported(v.audioCodec)),kl(a)),t.subtitles&&(o=t.subtitles,kl(o));const c=l.slice(0);l.sort((v,E)=>{if(v.attrs["HDCP-LEVEL"]!==E.attrs["HDCP-LEVEL"])return(v.attrs["HDCP-LEVEL"]||"")>(E.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&v.height!==E.height)return v.height-E.height;if(v.frameRate!==E.frameRate)return v.frameRate-E.frameRate;if(v.videoRange!==E.videoRange)return qt.indexOf(v.videoRange)-qt.indexOf(E.videoRange);if(v.videoCodec!==E.videoCodec){const T=Ka(v.videoCodec),S=Ka(E.videoCodec);if(T!==S)return S-T}if(v.uri===E.uri&&v.codecSet!==E.codecSet){const T=Li(v.codecSet),S=Li(E.codecSet);if(T!==S)return S-T}return v.averageBitrate!==E.averageBitrate?v.averageBitrate-E.averageBitrate:0});let h=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length)){for(let v=0;v<c.length;v++)if(c[v].pathwayId===l[0].pathwayId){h=c[v];break}}this._levels=l;for(let v=0;v<l.length;v++)if(l[v]===h){var u;this._firstLevel=v;const E=h.bitrate,T=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${E}`),((u=this.hls.userConfig)==null?void 0:u.abrEwmaDefaultEstimate)===void 0){const S=Math.min(E,this.hls.config.abrEwmaDefaultEstimateMax);S>T&&T===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=S)}break}const f=r&&!s,m=this.hls.config,g=!!(m.audioStreamController&&m.audioTrackController),y={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:s,altAudio:g&&!f&&a.some(v=>!!v.url)};d.end=performance.now(),this.hls.trigger(p.MANIFEST_PARSED,y)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const d=new Error("invalid level idx"),c=e<0;if(this.hls.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.LEVEL_SWITCH_ERROR,level:e,fatal:c,error:d,reason:d.message}),c)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,r=s?s.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,i===e&&s&&r===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${i}${r?" with Pathway "+r:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(p.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const d=this.switchParams(n.uri,s?.details,l);this.loadPlaylist(d)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),i=e.filter(s=>t.indexOf(s)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===q.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===B.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(r=>!!i[r]))return;const s=this._levels[t.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var i;const{level:s,details:r}=t,n=t.levelInfo;if(!n){var a;this.warn(`Invalid level index ${s}`),(a=t.deliveryDirectives)!=null&&a.skip&&(r.deltaUpdateFailed=!0);return}if(n===this.currentLevel||t.withoutMultiVariant){n.fragmentError===0&&(n.loadError=0);let o=n.details;o===t.details&&o.advanced&&(o=void 0),this.playlistLoaded(s,t,o)}else(i=t.deliveryDirectives)!=null&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,a=n?.age;this.log(`Loading level index ${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${i}`),this.hls.trigger(p.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const i=this._levels.filter((r,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(a=>a.level=-1)),!1));Co(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(p.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}},kc=100,Cc=class extends Zt{constructor(e,t,i){super(e,t,i,"stream-controller",B.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const s=this.media,r=s?s.currentTime:null;if(r===null||!N(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const n=this.getFwdBufferInfoAtPos(s,r,B.MAIN,0);if(n===null||n.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${n?n.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(kc),this.level=-1,!this.startFragRequested){let r=s.startLevel;r===-1&&(s.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=s.firstAutoLevel),s.nextLoadLevel=r,this.level=s.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=_.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=_.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case _.WAITING_LEVEL:{const{levels:e,level:t}=this,i=e?.[t],s=i?.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=_.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=_.IDLE;break}break}case _.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===_.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(t===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[r]))return;const n=i[r],a=this.getMainFwdBufferInfo();if(a===null)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const m={};this.altAudio===2&&(m.type="video"),this.hls.trigger(p.BUFFER_EOS,m),this.state=_.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const l=n.details;if(!l||this.state===_.WAITING_LEVEL||this.waitForLive(n)){this.level=r,this.state=_.WAITING_LEVEL,this.startFragRequested=!1;return}const d=a.len,c=this.getMaxBufferLength(n.maxBitrate);if(d>=c)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(h,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&de(u)&&this.fragmentTracker.getState(u)!==he.OK){var f;const m=((f=this.backtrackFragment)!=null?f:u).sn-l.startSN,g=l.fragments[m-1];g&&u.cc===g.cc&&(u=g,this.fragmentTracker.removeFragment(g))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,h)){if(!u.gap){const m=this.audioOnly&&!this.altAudio?re.AUDIO:re.VIDEO,g=(m===re.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;g&&this.afterBufferFlushed(g,m,B.MAIN)}u=this.getNextFragmentLoopLoading(u,l,a,B.MAIN,c)}u&&(this.exceedsMaxBuffer(a,c,u)||(u.initSegment&&!u.initSegment.data&&!this.bitrateTest&&(u=u.initSegment),this.loadFragment(u,n,h)))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);s===he.NOT_LOADED||s===he.PARTIAL?de(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,B.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==0){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let i;const s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const a=this.getMainFwdBufferInfo();if(!a||a.len<r.targetduration*2)return}if(!t.paused&&e){const a=e[this.hls.nextLoadLevel],o=this.fragLastKbps;o&&this.fragCurrent?i=this.fragCurrent.duration*a.maxBitrate/(1e3*o)+1:i=0}else i=0;const n=this.getBufferedFrag(t.currentTime+i);if(n){const a=this.followingBufferedFrag(n);if(a){this.abortCurrentFrag();const o=a.maxStartPTS?a.maxStartPTS:a.start,l=a.duration,d=Math.max(n.end,o+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case _.KEY_LOADING:case _.FRAG_LOADING:case _.FRAG_LOADING_WAITING_RETRY:case _.PARSING:case _.PARSED:this.state=_.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;Ee(i,"playing",this.onMediaPlaying),Ee(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:i}=this;i&&(Le(i,"playing",this.onMediaPlaying),Le(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(p.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1;for(let r=0;r<t.levels.length;r++){const n=t.levels[r].audioCodec;n&&(i=i||n.indexOf("mp4a.40.2")!==-1,s=s||n.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=i&&s&&!Lg(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==_.IDLE)return;const s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=_.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:s,startFragRequested:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!s){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,d=this.fragCurrent;d&&(this.state===_.FRAG_LOADING||this.state===_.FRAG_LOADING_WAITING_RETRY)&&d.level!==t.level&&d.loader&&this.abortCurrentFrag();let c=0;if(a.live||(i=l.details)!=null&&i.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,c),this.hls.trigger(p.LEVEL_UPDATED,{details:a,level:n}),this.state===_.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=_.IDLE}r&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=r>=n-t.maxFragLookUpTolerance&&r<=a;if(s!==null&&i.duration>s&&(r<s||!o)){const d=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&i.readyState<4||r<a-d)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${s.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;const c=Y.bufferInfo(i,s,0);if(!((l=c.buffered)!=null&&l.length)){i.currentTime=s;return}if(c.start<=r){i.currentTime=s;return}const{nextStart:h}=Y.bufferedInfo(c.buffered,r,0);h&&(i.currentTime=h)}else i.currentTime=s}}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:r}=e,{levels:n}=this;if(!n){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const a=n[i.level];if(!a){this.warn(`Level ${i.level} not found on progress`);return}const o=a.details;if(!o){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const l=a.videoCodec,d=o.PTSKnown||!o.live,c=(t=i.initSegment)==null?void 0:t.data,h=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new Zr(this.hls,B.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=s?s.index:-1,m=f!==-1,g=new Xt(i.level,i.sn,i.stats.chunkCount,r.byteLength,f,m),y=this.initPTS[i.cc];u.push(r,c,h,l,i,s,o.totalduration,d,g,y)}onAudioTrackSwitching(e,t){const i=this.hls,s=this.altAudio!==0;if(Pi(t.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const r=this.fragCurrent;r&&(this.log("Switching to main audio track, cancel main fragment load"),r.abortRequests(),this.fragmentTracker.removeFragment(r)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s){this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(p.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(p.AUDIO_TRACK_SWITCHED,t)}),i.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(p.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=Pi(t.url,this.hls);if(i){const s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=i?2:0,this.tick()}onBufferCreated(e,t){const i=t.tracks;let s,r,n=!1;for(const a in i){const o=i[a];if(o.id==="main"){if(r=a,s=o,a==="video"){const l=i[a];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&s?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:s}=t,r=i.type===B.MAIN;if(r){if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===_.PARSED&&(this.state=_.IDLE);return}const a=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),de(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}const n=this.media;n&&(!this._hasEnoughToStart&&Y.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=_.ERROR;return}switch(t.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(B.MAIN,t);break;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===_.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===q.LEVEL&&(this.state=_.IDLE);break;case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case L.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=_.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==re.AUDIO||!this.altAudio){const i=(t===re.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,B.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}const s=this.timelineOffset;s&&i&&(i+=s);const r=this.getLevelDetails(),n=Y.getBuffered(e),a=n.length?n.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*(r?.partTarget||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${a}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{const{hls:s}=this,r=i?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=_.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=r.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),s.trigger(p.FRAG_LOADED,i),r.bitrateTest=!1}).catch(i=>{this.state===_.STOPPED||this.state===_.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n){this.resetWhenMissingContext(r);return}const{frag:a,part:o,level:l}=n,{video:d,text:c,id3:h,initSegment:u}=s,{details:f}=l,m=this.altAudio?void 0:s.audio;if(this.fragContextChanged(a)){this.fragmentTracker.removeFragment(a);return}if(this.state=_.PARSING,u){const g=u.tracks;if(g){const T=a.initSegment||a;if(this.unhandledEncryptionError(u,a))return;this._bufferInitSegment(l,g,T,r),i.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:T,id:t,tracks:g})}const y=u.initPTS,v=u.timescale,E=this.initPTS[a.cc];if(N(y)&&(!E||E.baseTime!==y||E.timescale!==v)){const T=u.trackId;this.initPTS[a.cc]={baseTime:y,timescale:v,trackId:T},i.trigger(p.INIT_PTS_FOUND,{frag:a,id:t,initPTS:y,timescale:v,trackId:T})}}if(d&&f){m&&d.type==="audiovideo"&&this.logMuxedErr(a);const g=f.fragments[a.sn-1-f.startSN],y=a.sn===f.startSN,v=!g||a.cc>g.cc;if(s.independent!==!1){const{startPTS:E,endPTS:T,startDTS:S,endDTS:A}=d;if(o)o.elementaryStreams[d.type]={startPTS:E,endPTS:T,startDTS:S,endDTS:A};else if(d.firstKeyFrame&&d.independent&&r.id===1&&!v&&(this.couldBacktrack=!0),d.dropped&&d.independent){const b=this.getMainFwdBufferInfo(),I=(b?b.end:this.getLoadPosition())+this.config.maxBufferHole,D=d.firstKeyFramePTS?d.firstKeyFramePTS:E;if(!y&&I<D-this.config.maxBufferHole&&!v){this.backtrack(a);return}else v&&(a.gap=!0);a.setElementaryStreamInfo(d.type,a.start,T,a.start,A,!0)}else y&&E-(f.appliedTimelineOffset||0)>di&&(a.gap=!0);a.setElementaryStreamInfo(d.type,E,T,S,A),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(d,a,o,r,y||v)}else if(y||v)a.gap=!0;else{this.backtrack(a);return}}if(m){const{startPTS:g,endPTS:y,startDTS:v,endDTS:E}=m;o&&(o.elementaryStreams[re.AUDIO]={startPTS:g,endPTS:y,startDTS:v,endDTS:E}),a.setElementaryStreamInfo(re.AUDIO,g,y,v,E),this.bufferFragmentData(m,a,o,r)}if(f&&h!=null&&h.samples.length){const g={id:t,frag:a,details:f,samples:h.samples};i.trigger(p.FRAG_PARSING_METADATA,g)}if(f&&c){const g={id:t,frag:a,details:f,samples:c.samples};i.trigger(p.FRAG_PARSING_USERDATA,g)}}logMuxedErr(e){this.warn(`${de(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==_.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:r,video:n,audiovideo:a}=t;if(r){const l=e.audioCodec;let d=Di(r.codec,l);d==="mp4a"&&(d="mp4a.40.5");const c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){d&&(d.indexOf("mp4a.40.5")!==-1?d="mp4a.40.2":d="mp4a.40.5");const h=r.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&c.indexOf("firefox")===-1&&(d="mp4a.40.5")}d&&d.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(d="mp4a.40.2",this.log(`Android: force audio codec to ${d}`)),l&&l!==d&&this.log(`Swapping manifest audio codec "${l}" for "${d}"`),r.levelCodec=d,r.id=B.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${d||""}/${l||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=B.MAIN;const l=n.codec;if(l?.length===4)switch(l){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${n.codec!==l?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(p.BUFFER_CODECS,t),!this.hls)return;o.forEach(l=>{const d=t[l].initSegment;d!=null&&d.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:l,data:d,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,B.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,i=e?.[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=_.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(Y.isBuffered(e,i)?t=this.getAppendedFrag(i):Y.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const s=this.fragPlaying,r=t.level;(!s||t.sn!==s.sn||s.level!==r)&&(this.fragPlaying=t,this.hls.trigger(p.FRAG_CHANGED,{frag:t}),(!s||s.level!==r)&&this.hls.trigger(p.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return N(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(N(t)){const i=this.getLevelDetails(),s=this.currentFrag||(i?lt(null,i.fragments,t):null);if(s){const r=s.programDateTime;if(r!==null){const n=r+(t-s.start)*1e3;return new Date(n)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},xc=class extends we{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyIdToKeyInfo){const s=this.keyIdToKeyInfo[i].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=L.KEY_LOAD_ERROR,i,s,r){return new Ve({type:$.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:s})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let s=0,r=t.length;s<r;s++){const n=t[s];if(e.cc<=n.cc&&(!de(e)||!de(n)||e.sn<n.sn)||!i&&s==r-1)return this.emeController.selectKeySystemFormat(n).then(a=>{if(!this.emeController)return;n.setKeyFormat(a);const o=Mi(a);if(o)return this.emeController.getKeySystemAccess([o])})}if(this.config.requireKeySystemAccessOnStart){const s=$t(this.config);if(s.length)return this.emeController.getKeySystemAccess(s)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,s;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const l=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,L.KEY_LOAD_ERROR,l))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,L.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=Pr(r);let o=this.keyIdToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if(this.emeController&&(s=o)!=null&&s.keyLoadPromise)switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then(l=>{const{keyInfo:d}=l;return r.key=d.decryptdata.key,{frag:e,keyInfo:d}})}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${r.keyId?" keyId: "+ye(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,L.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var s;if(!e.decryptdata.keyId&&(s=t.initSegment)!=null&&s.data){const r=Jh(t.initSegment.data);if(r.length){let n=r[0];n.some(a=>a!==0)?(this.log(`Using keyId found in init segment ${ye(n)}`),Pt.setKeyIdForUri(e.decryptdata.uri,n)):(n=Pt.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${ye(n)}`)),e.decryptdata.keyId=n}}return!e.decryptdata.keyId&&!de(t)?Promise.resolve(i):(e.keyLoadPromise=this.emeController.loadKey(i).then(r=>(e.mediaKeySessionContext=r,i))).catch(r=>{throw e.keyLoadPromise=null,"data"in r&&(r.data.frag=t),r})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,s=i.loader,r=new s(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((n,a)=>{const o={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=i.keyLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};r.load(o,d,{onSuccess:(c,h,u,f)=>{const{frag:m,keyInfo:g}=u,y=Pr(g.decryptdata);if(!m.decryptdata||g!==this.keyIdToKeyInfo[y])return a(this.createKeyLoadError(m,L.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),f));g.decryptdata.key=m.decryptdata.key=new Uint8Array(c.data),m.keyLoader=null,g.loader=null,n({frag:m,keyInfo:g})},onError:(c,h,u,f)=>{this.resetLoader(h),a(this.createKeyLoadError(t,L.KEY_LOAD_ERROR,new Error(`HTTP Error ${c.code} loading key ${c.text}`),u,ie({url:o.url,data:void 0},c)))},onTimeout:(c,h,u)=>{this.resetLoader(h),a(this.createKeyLoadError(t,L.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),u))},onAbort:(c,h,u)=>{this.resetLoader(h),a(this.createKeyLoadError(t,L.INTERNAL_ABORTED,new Error("key loading aborted"),u))}})})}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=null,i.loader=null);const n=Pr(i.decryptdata)||s;delete this.keyIdToKeyInfo[n],r&&r.destroy()}},Mc=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,s=t.loader,r=new(i||s)(t);return this.loaders[e.type]=r,r}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:q.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:s,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=t;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:q.LEVEL,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:q.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:q.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){const i=this.loaders[q.LEVEL];if(i){const s=i.context;s&&!t.levels.some(r=>r===s.levelOrTrack)&&(i.abort(),delete this.loaders[q.LEVEL])}}load(e){var t;const i=this.hls.config;let s=this.getInternalLoader(e);if(s){const o=this.hls.logger,l=s.context;if(l&&l.levelOrTrack===e.levelOrTrack&&(l.url===e.url||l.deliveryDirectives&&!e.deliveryDirectives)){l.url===e.url?o.log(`[playlist-loader]: ignore ${e.url} ongoing request`):o.log(`[playlist-loader]: ignore ${e.url} in favor of ${l.url}`);return}o.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let r;if(e.type===q.MANIFEST?r=i.manifestLoadPolicy.default:r=se({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),N((t=e.deliveryDirectives)==null?void 0:t.part)){let o;if(e.type===q.LEVEL&&e.level!==null?o=this.hls.levels[e.level].details:e.type===q.AUDIO_TRACK&&e.id!==null?o=this.hls.audioTracks[e.id].details:e.type===q.SUBTITLE_TRACK&&e.id!==null&&(o=this.hls.subtitleTracks[e.id].details),o){const l=o.partTarget,d=o.targetduration;if(l&&d){const c=Math.max(l*3,d*.8)*1e3;r=se({},r,{maxTimeToFirstByteMs:Math.min(c,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(c,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0};s.load(e,a,{onSuccess:(o,l,d,c)=>{const h=this.getInternalLoader(d);this.resetInternalLoader(d.type);const u=o.data;l.parsing.start=performance.now(),ft.isMediaPlaylist(u)||d.type!==q.MANIFEST?this.handleTrackOrLevelPlaylist(o,l,d,c||null,h):this.handleMasterPlaylist(o,l,d,c)},onError:(o,l,d,c)=>{this.handleNetworkError(l,d,!1,o,c)},onTimeout:(o,l,d)=>{this.handleNetworkError(l,d,!0,void 0,o)}})}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,s){const r=this.hls,n=e.data,a=wr(e,i),o=ft.parseMasterPlaylist(n,a);if(o.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,o.playlistParsingError,s,t);return}const{contentSteering:l,levels:d,sessionData:c,sessionKeys:h,startTimeOffset:u,variableList:f}=o;this.variableList=f,d.forEach(v=>{const{unknownCodecs:E}=v;if(E){const{preferManagedMediaSource:T}=this.hls.config;let{audioCodec:S,videoCodec:A}=v;for(let b=E.length;b--;){const I=E[b];Ut(I,"audio",T)?(v.audioCodec=S=S?`${S},${I}`:I,ct.audio[S.substring(0,4)]=2,E.splice(b,1)):Ut(I,"video",T)&&(v.videoCodec=A=A?`${A},${I}`:I,ct.video[A.substring(0,4)]=2,E.splice(b,1))}}});const{AUDIO:m=[],SUBTITLES:g,"CLOSED-CAPTIONS":y}=ft.parseMasterPlaylistMedia(n,a,o);m.length&&!m.some(v=>!v.url)&&d[0].audioCodec&&!d[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new oe({}),bitrate:0,url:""})),r.trigger(p.MANIFEST_LOADED,{levels:d,audioTracks:m,subtitles:g,captions:y,contentSteering:l,url:a,stats:t,networkDetails:s,sessionData:c,sessionKeys:h,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(e,t,i,s,r){const n=this.hls,{id:a,level:o,type:l}=i,d=wr(e,i),c=N(o)?o:N(a)?a:0,h=Ml(i),u=ft.parseLevelPlaylist(e.data,d,c,h,0,this.variableList);if(l===q.MANIFEST){const f={attrs:new oe({}),bitrate:0,details:u,name:"",url:d};u.requestScheduled=t.loading.start+Po(u,0),n.trigger(p.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:d,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=u,this.handlePlaylistLoaded(u,e,t,i,s,r)}handleManifestParsingError(e,t,i,s,r){this.hls.trigger(p.ERROR,{type:$.NETWORK_ERROR,details:L.MANIFEST_PARSING_ERROR,fatal:t.type===q.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:r})}handleNetworkError(e,t,i=!1,s,r){let n=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===q.LEVEL?n+=`: ${e.level} id: ${e.id}`:(e.type===q.AUDIO_TRACK||e.type===q.SUBTITLE_TRACK)&&(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=L.UNKNOWN,l=!1;const d=this.getInternalLoader(e);switch(e.type){case q.MANIFEST:o=i?L.MANIFEST_LOAD_TIMEOUT:L.MANIFEST_LOAD_ERROR,l=!0;break;case q.LEVEL:o=i?L.LEVEL_LOAD_TIMEOUT:L.LEVEL_LOAD_ERROR,l=!1;break;case q.AUDIO_TRACK:o=i?L.AUDIO_TRACK_LOAD_TIMEOUT:L.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case q.SUBTITLE_TRACK:o=i?L.SUBTITLE_TRACK_LOAD_TIMEOUT:L.SUBTITLE_LOAD_ERROR,l=!1;break}d&&this.resetInternalLoader(e.type);const c={type:$.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:d,context:e,error:a,networkDetails:t,stats:r};s&&(c.response=ie({url:t?.url||e.url,data:void 0},s)),this.hls.trigger(p.ERROR,c)}handlePlaylistLoaded(e,t,i,s,r,n){const a=this.hls,{type:o,level:l,levelOrTrack:d,id:c,groupId:h,deliveryDirectives:u}=s,f=wr(t,s),m=Ml(s);let g=typeof s.level=="number"&&m===B.MAIN?l:void 0;const y=e.playlistParsingError;if(y){if(this.hls.logger.warn(`${y} ${e.url}`),!a.config.ignorePlaylistParsingErrors){a.trigger(p.ERROR,{type:$.NETWORK_ERROR,details:L.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:t,context:s,level:g,parent:m,networkDetails:r,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){const v=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(p.ERROR,{type:$.NETWORK_ERROR,details:L.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:t,context:s,level:g,parent:m,networkDetails:r,stats:i});return}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),(!n.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),o){case q.MANIFEST:case q.LEVEL:if(g){if(!d)g=0;else if(d!==a.levels[g]){const v=a.levels.indexOf(d);v>-1&&(g=v)}}a.trigger(p.LEVEL_LOADED,{details:e,levelInfo:d||a.levels[0],level:g||0,id:c||0,stats:i,networkDetails:r,deliveryDirectives:u,withoutMultiVariant:o===q.MANIFEST});break;case q.AUDIO_TRACK:a.trigger(p.AUDIO_TRACK_LOADED,{details:e,track:d,id:c||0,groupId:h||"",stats:i,networkDetails:r,deliveryDirectives:u});break;case q.SUBTITLE_TRACK:a.trigger(p.SUBTITLE_TRACK_LOADED,{details:e,track:d,id:c||0,groupId:h||"",stats:i,networkDetails:r,deliveryDirectives:u});break}}},ps=class Ct{static get version(){return wt}static isMSESupported(){return Dr()}static isSupported(){return xl()}static getMediaSource(){return Ye()}static get Events(){return p}static get MetadataSchema(){return Se}static get ErrorTypes(){return $}static get ErrorDetails(){return L}static get DefaultConfig(){return Ct.defaultConfig?Ct.defaultConfig:bc}static set DefaultConfig(t){Ct.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new is,this._autoLevelCapping=-1,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const i=this.logger=Kh(t.debug||!1,"Hls instance",t.assetPlayerId),s=this.config=Ig(Ct.DefaultConfig,t,i);this.userConfig=t,s.progressive&&Ag(s,i);const{abrController:r,bufferController:n,capLevelController:a,errorController:o,fpsController:l}=s,d=new o(this),c=this.abrController=new r(this),h=new Wl(this),u=s.interstitialsController,f=u?this.interstitialsController=new u(this,Ct):null,m=this.bufferController=new n(this,h),g=this.capLevelController=new a(this),y=new l(this),v=new Mc(this),E=s.contentSteeringController,T=E?new E(this):null,S=this.levelController=new _c(this,T),A=new Pc(this),b=new xc(this.config,this.logger),I=this.streamController=new Cc(this,h,b),D=this.gapController=new Rc(this,h);g.setStreamController(I),y.setStreamController(I);const w=[v,S,I];f&&w.splice(1,0,f),T&&w.splice(1,0,T),this.networkControllers=w;const P=[c,m,D,g,y,A,h];this.audioTrackController=this.createController(s.audioTrackController,w);const x=s.audioStreamController;x&&w.push(this.audioStreamController=new x(this,h,b)),this.subtitleTrackController=this.createController(s.subtitleTrackController,w);const U=s.subtitleStreamController;U&&w.push(this.subtititleStreamController=new U(this,h,b)),this.createController(s.timelineController,P),b.emeController=this.emeController=this.createController(s.emeController,P),this.cmcdController=this.createController(s.cmcdController,P),this.latencyController=this.createController(wc,P),this.coreComponents=P,w.push(d);const O=d.onErrorOut;typeof O=="function"&&this.on(p.ERROR,O,d),this.on(p.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(t,i){if(t){const s=new t(this);return i&&i.push(s),s}return null}on(t,i,s=this){this._emitter.on(t,i,s)}once(t,i,s=this){this._emitter.once(t,i,s)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,i,s=this,r){this._emitter.off(t,i,s,r)}listeners(t){return this._emitter.listeners(t)}emit(t,i,s){return this._emitter.emit(t,i,s)}trigger(t,i){if(this.config.debug)return this.emit(t,t,i);try{return this.emit(t,t,i)}catch(s){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const r=t===p.ERROR;this.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:r,event:t,error:s}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(p.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(i=>i.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(i=>i.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const n=new Error(`attachMedia failed: invalid argument (${t})`);this.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const i="media"in t,s=i?t.media:t,r=i?t:{media:s};this._media=s,this.trigger(p.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia"),this.trigger(p.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(p.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const i=this.media,s=this._url,r=this._url=ji.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),i&&s&&(s!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(i)),this.trigger(p.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,i){this.logger.log(`startLoad(${t+(i?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(t,i),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!(this.started||!this.networkControllers));t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[B.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[B.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[B.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,i=t?.currentTime;this.detachMedia(),t&&(this.attachMedia(t),i&&this.startLoad(i))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=ag()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return t===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),t!==-1&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const i=!!t;i!==this.config.capLevelToPlayerSize&&(i?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=i)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){yu(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:i}}=this;if(!t)return 0;const s=t.length;for(let r=0;r<s;r++)if(t[r].maxBitrate>=i)return r;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:i,maxHdcpLevel:s}=this;let r;if(i===-1&&t!=null&&t.length?r=t.length-1:r=i,s)for(let n=r;n--;){const a=t[n].attrs["HDCP-LEVEL"];if(a&&a<=s)return n}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var i;return((i=this.audioTrackController)==null?void 0:i.setAudioOption(t))||null}setSubtitleOption(t){var i;return((i=this.subtitleTrackController)==null?void 0:i.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const i=this.audioTrackController;i&&(i.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const i=this.subtitleTrackController;i&&(i.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return t?t.subtitleDisplay:!1}set subtitleDisplay(t){const i=this.subtitleTrackController;i&&(i.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!!((t=this.bufferController)!=null&&t.bufferedToEnd)}get interstitialsManager(){var t;return((t=this.interstitialsController)==null?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,i=this.allAudioTracks){return Ya(t,Qa(i),navigator.mediaCapabilities)}},ps.defaultConfig=void 0})),Dg=Mt({default:()=>Pg});async function Pg(e,t,i,s){const r=mi(s?.options),n=(i||"mp4").toLowerCase();let a=!1,o="",l=null;const d=rt("div","fv-video-viewer"),c=rt("section","fv-video-shell"),h=rt("div","fv-video-heading");h.append(rt("span","",n.toUpperCase()||"VIDEO"),rt("strong","",r("media.video.title")));const u=rt("video","fv-video-player");u.controls=!0,u.preload="metadata",u.textContent=r("media.video.unsupported"),c.append(h,u),n==="m3u8"&&c.append(rt("p","fv-video-hint",r("media.video.hlsHint"))),d.append(c),t.replaceChildren(Nc(),d);const f=()=>n==="m3u8"&&s?.url?s.url:(o=$c(e,n),o);return(async()=>{const g=f();if(n==="m3u8"){if(u.canPlayType("application/vnd.apple.mpegurl")){u.src=g;return}const{default:y}=await Promise.resolve().then(()=>(Rg(),Uh));if(a)return;if(y.isSupported()){l=new y({enableWorker:!0,lowLatencyMode:!1}),l.loadSource(g),l.attachMedia(u);return}}u.src=g})(),Uc(t,()=>{a=!0,l?.destroy(),l=null,u.pause(),u.removeAttribute("src"),u.load(),o&&(URL.revokeObjectURL(o),o="")})}var Oc,Fc,rt,Nc,Uc,Bc,$c,wg=ee((()=>{Ns(),Oc=`
|
|
81
|
+
`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}},gc=/\r\n|\n\r|\n|\r/g,us=function(t,i,s=0){return t.slice(s,s+i.length)===i},mc=function(t){let i=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),r=parseInt(t.slice(-9,-7)),n=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!N(i)||!N(s)||!N(r)||!N(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return i+=1e3*s,i+=60*1e3*r,i+=3600*1e3*n,i},pc=function(t,i,s){let r=t[i],n=t[r.prevCC];if(!n||!n.new&&r.new){t.ccOffset=t.presentationOffset=r.start,r.new=!1;return}for(;(a=n)!=null&&a.new;){var a;t.ccOffset+=r.start-n.start,r.new=!1,r=n,n=t[r.prevCC]}t.presentationOffset=s},fs="stpp.ttml.im1t",Ln=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Rn=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,yc={left:"start",center:"center",right:"end",start:"start",end:"end"},li=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Dn=class{constructor(e){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.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Dl(),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}},e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new li(this,"textTrack1"),t=new li(this,"textTrack2"),i=new li(this,"textTrack3"),s=new li(this,"textTrack4");this.cea608Parser1=new An(1,e,t),this.cea608Parser2=new An(3,i,s)}addCues(e,t,i,s,r){let n=!1;for(let a=r.length;a--;){const o=r[a],l=yg(o[0],o[1],t,i);if(l>=0&&(o[0]=Math.min(o[0],t),o[1]=Math.max(o[1],i),n=!0,l/(i-t)>.5))return}if(n||r.push([t,i]),this.config.renderTextTracksNatively){const a=this.captionsTracks[e];this.Cues.newCue(a,t,i,s)}else{const a=this.Cues.newCue(null,t,i,s);this.hls.trigger(p.CUES_PARSED,{type:"captions",cues:a,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:r,trackId:n}){const{unparsedVttFrags:a}=this;i===B.MAIN&&(this.initPTS[t.cc]={baseTime:s,timescale:r,trackId:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.initPTS[o.frag.cc]?this.onFragLoaded(p.FRAG_LOADED,o):this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:o.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){const r=i.textTracks[s];if(Rl(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:s}=this,{label:r,languageCode:n}=t[e],a=this.getExistingTrack(r,n);if(a)i[e]=a,At(i[e]),gl(i[e],s);else{const o=this.createTextTrack("captions",r,n);o&&(o[e]=!0,i[e]=o)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i={_id:e,label:t.label,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,i){const s=this.media;if(s)return s.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const i=!!t.transferMedia;if(this.media=null,i)return;const{captionsTracks:s}=this;Object.keys(s).forEach(r=>{At(s[r]),delete s[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Dl(),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(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let i=0;i<t.length;i++)At(t[i])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],s=i.some(r=>r.textCodec===fs);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(sl(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const r=this.media,n=r?Gi(r.textTracks):null;if(this.tracks.forEach((a,o)=>{let l;if(n){let d=null;for(let c=0;c<n.length;c++)if(n[c]&&Rl(n[c],a)){d=n[c],n[c]=null;break}d&&(l=d)}if(l)At(l);else{const d=Ll(a);l=this.createTextTrack(d,a.name,a.lang),l&&(l.mode="disabled")}l&&this.textTracks.push(l)}),n!=null&&n.length){const a=n.filter(o=>o!==null).map(o=>o.label);a.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${a.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const r=this.tracks.map(n=>({label:n.name,kind:n.type.toLowerCase(),default:n.default,subtitleTrack:n}));this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:r})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;const r=`textTrack${s[1]}`,n=this.captionsProperties[r];n&&(n.label=i.name,i.lang&&(n.languageCode=i.lang),n.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===B.MAIN){var i,s;const{cea608Parser1:r,cea608Parser2:n,lastSn:a}=this,{cc:o,sn:l}=t.frag,d=(i=(s=t.part)==null?void 0:s.index)!=null?i:-1;r&&n&&(l!==a+1||l===a&&d!==this.lastPartIndex+1||o!==this.lastCc)&&(r.reset(),n.reset()),this.lastCc=o,this.lastSn=l,this.lastPartIndex=d}}onFragLoaded(e,t){const{frag:i,payload:s}=t;if(i.type===B.SUBTITLE)if(s.byteLength){const r=i.decryptdata,n="stats"in t;if(r==null||!r.encrypted||n){const a=this.tracks[i.level],o=this.vttCCs;o[i.cc]||(o[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),a&&a.textCodec===fs?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;Sl(t,this.initPTS[e.cc],s=>{this._appendCues(s,e.level),i.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},s=>{i.logger.log(`Failed to parse IMSC1: ${s}`),i.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:s})})}_parseVTTs(e){var t;const{frag:i,payload:s}=e,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[i.cc]&&a===-1){n.push(e);return}const o=this.hls;ug((t=i.initSegment)!=null&&t.data?Ce(i.initSegment.data,new Uint8Array(s)).buffer:s,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,l=>{this._appendCues(l,i.level),o.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},l=>{const d=l.message==="Missing initPTS for VTT MPEGTS";d?n.push(e):this._fallbackToIMSC1(i,s),o.logger.log(`Failed to parse VTT cue: ${l}`),!(d&&a>i.cc)&&o.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:l})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||Sl(t,this.initPTS[e.cc],()=>{i.textCodec=fs,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[t];if(!s||s.mode==="disabled")return;e.forEach(r=>ml(s,r))}else{const s=this.tracks[t];if(!s)return;const r=s.default?"default":"subtitles"+t;i.trigger(p.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===B.SUBTITLE&&this.onFragLoaded(p.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:s}=t;if(!(i.type===B.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let r=0;r<s.length;r++){const n=s[r].bytes;if(n){this.cea608Parser1||this.initCea608Parsers();const a=this.extractCea608Data(n);this.cea608Parser1.addData(s[r].pts,a[0]),this.cea608Parser2.addData(s[r].pts,a[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:s,type:r}){const{media:n}=this;if(!(!n||n.currentTime<i)){if(!r||r==="video"){const{captionsTracks:a}=this;Object.keys(a).forEach(o=>yr(a[o],t,i))}if(this.config.renderTextTracksNatively&&t===0&&s!==void 0){const{textTracks:a}=this;Object.keys(a).forEach(o=>yr(a[o],t,s))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let s=2;for(let r=0;r<i;r++){const n=e[s++],a=127&e[s++],o=127&e[s++];if(!(a===0&&o===0)&&(4&n)!==0){const l=3&n;(l===0||l===1)&&(t[l].push(a),t[l].push(o))}}return t}},vc=/\s/,wn={newCue(e,t,i,s){const r=[];let n,a,o,l,d;const c=self.VTTCue||self.TextTrackCue;for(let u=0;u<s.rows.length;u++)if(n=s.rows[u],o=!0,l=0,d="",!n.isEmpty()){var h;for(let g=0;g<n.chars.length;g++)vc.test(n.chars[g].uchar)&&o?l++:(d+=n.chars[g].uchar,o=!1);n.cueStartTime=t,t===i&&(i+=1e-4),l>=16?l--:l++;const f=Tl(d.trim()),m=Tr(t,i,f);e!=null&&(h=e.cues)!=null&&h.getCueById(m)||(a=new c(t,i,f),a.id=m,a.line=u+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a))}return e&&r.length&&(r.sort((u,f)=>u.line==="auto"||f.line==="auto"?0:u.line>8&&f.line>8?f.line-u.line:u.line-f.line),r.forEach(u=>ml(e,u))),r}},Ec=/(\d+)-(\d+)\/(\d+)/,gs=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Sg,this.controller=new self.AbortController,this.stats=new Yt}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(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){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const r=vg(e,this.controller.signal),n=e.responseType==="arraybuffer",a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=o&&N(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},t.timeout),(Ht(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(d=>{var c;this.response=this.loader=d;const h=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},l-(h-s.loading.start)),!d.ok){const{status:f,statusText:m}=d;throw new Tc(m||"fetch, bad network response",f,d)}s.loading.first=h,s.total=Tg(d.headers)||s.total;const u=(c=this.callbacks)==null?void 0:c.onProgress;return u&&N(t.highWaterMark)?this.loadProgressively(d,s,e,t.highWaterMark,u):n?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{var c,h;const u=this.response;if(!u)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const f=d[a];f&&(s.loaded=s.total=f);const m={url:u.url,data:d,code:u.status},g=(c=this.callbacks)==null?void 0:c.onProgress;g&&!N(t.highWaterMark)&&g(s,e,d,u),(h=this.callbacks)==null||h.onSuccess(m,s,e,u)}).catch(d=>{var c;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const h=d&&d.code||0,u=d?d.message:null;(c=this.callbacks)==null||c.onError({code:h,text:u},e,d?d.details:null,s)})}getCacheAge(){let e=null;if(this.response){const 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,s=0,r){const n=new jr,a=e.body.getReader(),o=()=>a.read().then(l=>{if(l.done)return n.dataLength&&r(t,i,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const d=l.value,c=d.length;return t.loaded+=c,c<s||n.dataLength?(n.push(d),n.dataLength>=s&&r(t,i,n.flush().buffer,e)):r(t,i,d.buffer,e),o()}).catch(()=>Promise.reject());return o()}},Tc=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}},Sc=/^age:\s*[\d.]+\s*$/im,ms=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=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Yt,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const 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(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return r(i,t.url)}).catch(n=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),r(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(n=>{var a;(a=this.callbacks)==null||a.onError({code:i.status,text:n.message},t,i,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const s=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=i.loadPolicy;if(s)for(const a in s)e.setRequestHeader(a,s[a]);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=r&&N(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const s=t.readyState,r=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,d=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const u=d??t.response;if(u!=null){var n,a;i.loading.end=Math.max(self.performance.now(),i.loading.first),i.loaded=i.total=t.responseType==="arraybuffer"?u.byteLength:u.length,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const f=(n=this.callbacks)==null?void 0:n.onProgress;f&&f(i,e,u,t);const m={url:t.responseURL,data:u,code:l};(a=this.callbacks)==null||a.onSuccess(m,i,e,t);return}}const c=r.loadPolicy.errorRetry,h=i.retry;if(_i(c,h,!1,{url:e.url,data:void 0,code:l}))this.retry(c);else{var o;te.error(`${l} while loading ${e.url}`),(o=this.callbacks)==null||o.onError({code:l,text:t.statusText},e,t,i)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(_i(e,t,!0))this.retry(e);else{var i;te.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Ys(e,i.retry),i.retry++,te.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){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Sc.test(this.loader.getAllResponseHeaders())){const 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}},bc=ie(ie({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,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,ignorePlaylistParsingErrors:!1,loader:ms,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Or,bufferController:nn,capLevelController:an,errorController:Nr,fpsController:pn,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Ji,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},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}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,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},bg()),{},{subtitleStreamController:Tn,subtitleTrackController:yn,timelineController:Dn,audioStreamController:en,audioTrackController:tn,emeController:ls,cmcdController:gn,contentSteeringController:mn,interstitialsController:ec}),di=2,Ic=.1,Ac=.05,Lc=100,Rc=class extends Br{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(Lc),this.mediaSource=t.mediaSource;const i=this.media=t.media;Ee(i,"playing",this.onMediaPlaying),Ee(i,"waiting",this.onMediaWaiting),Ee(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(Le(i,"playing",this.onMediaPlaying),Le(i,"waiting",this.onMediaWaiting),Le(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,s;const r=(i=this.hls)==null?void 0:i.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,d=n.paused&&!a||n.ended||n.playbackRate===0;if(this.seeking=a,e!==t){t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!d&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||o){o&&this.stallResolved(e);return}if(d){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!1}));return}if(!Y.getBuffered(n).length){this.nudgeRetry=0;return}const c=Y.bufferInfo(n,e,0),h=c.nextStart||0,u=this.fragmentTracker;if(a&&u&&this.hls){const A=Pl(this.hls.inFlightFragments,e),b=c.len>di,I=!h||A||h-e>di&&!u.getPartialFragment(e);if(b||I)return;this.moved=!1}const f=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&u){if(!(c.len>0)&&!h)return;const A=Math.max(h,c.start||0)-e,b=f!=null&&f.live?f.targetduration*2:di,I=Ki(e,u);if(A>0&&(A<=b||I)){n.paused||this._trySkipBufferHole(I);return}}const m=r.detectStallWithCurrentTimeMs,g=self.performance.now(),y=this.waiting;let v=this.stalled;if(v===null)if(y>0&&g-y<m)v=this.stalled=y;else{this.stalled=g;return}const E=g-v;if(!a&&(E>=m||y)&&this.hls){var T;if(((T=this.mediaSource)==null?void 0:T.readyState)==="ended"&&!(f!=null&&f.live)&&Math.abs(e-(f?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return}const S=Y.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(S,E,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(p.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&s&&s.length>1&&e>s.end(0)){const r=Y.bufferedInfo(Y.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const n=Y.timeRangesToArray(s),a=Y.bufferedInfo(n,t,0).bufferedIndex;if(a>-1&&a<n.length-1){const o=Y.bufferedInfo(n,e,0).bufferedIndex,l=n[a].end,d=n[a+1].start;if((o===-1||o>a)&&d-l<1&&e-l<2){const c=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${d} buffered index: ${o}`);this.warn(c.message),this.media.currentTime+=1e-6;let h=Ki(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);const u=Y.bufferInfo(this.media,e,0);this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:h,buffer:u.len,bufferInfo:u})}}}}}_tryFixBufferStall(e,t,i){var s,r;const{fragmentTracker:n,media:a}=this,o=(s=this.hls)==null?void 0:s.config;if(!a||!n||!o)return;const l=(r=this.hls)==null?void 0:r.latestLevelDetails,d=Ki(i,n);if((d||l!=null&&l.live&&i<l.fragmentStart)&&(this._trySkipBufferHole(d)||!this.media))return;const c=e.buffered,h=this.adjacentTraversal(e,i);(c&&c.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-i<o.maxBufferHole||h))&&(t>o.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const i=this.fragmentTracker,s=e.nextStart;if(i&&s){const r=i.getFragAtPos(t,B.MAIN),n=i.getFragAtPos(s,B.MAIN);if(r&&n)return n.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:i,stallReported:s,stalled:r}=this;if(!s&&r!==null&&i&&t){this.stallReported=!0;const n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${ne(e)})`);this.warn(n.message),t.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:s}=this,r=(t=this.hls)==null?void 0:t.config;if(!s||!i||!r)return 0;const n=s.currentTime,a=Y.bufferInfo(s,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const d=a.len<=r.maxBufferHole,c=a.len>0&&a.len<1&&s.readyState<3,h=o-n;if(h>0&&(d||c)){if(h>r.maxBufferHole){let f=!1;if(n===0){const m=i.getAppendedFrag(0,B.MAIN);m&&o<m.end&&(f=!0)}if(!f&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||Pl(this.hls.inFlightFragments,o))return 0;let m=!1,g=e.end;for(;g<o;){const y=Ki(g,i);if(y)g+=y.duration;else{m=!0;break}}if(m)return 0}}const u=Math.max(o+Ac,n+Ic);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${u}`),this.moved=!0,s.currentTime=u,!(e!=null&&e.gap)){const f=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${u}`),m={type:$.MEDIA_ERROR,details:L.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:f,reason:f.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?m.part=e:m.frag=e),this.hls.trigger(p.ERROR,m)}return u}}return 0}_tryNudgeBuffer(e){const{hls:t,media:i,nudgeRetry:s}=this,r=t?.config;if(!i||!r)return 0;const n=i.currentTime;if(this.nudgeRetry++,s<r.nudgeMaxRetry){const a=n+(s+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),i.currentTime=a,t.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const a=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(a.message),t.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,error:a,fatal:!0,buffer:e.len,bufferInfo:e})}}},Dc=.25,ci=(()=>{const e=Lr();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),wc=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(p.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,((i=t.overrides)==null?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&At(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const i=e[t];if(i.kind==="metadata"&&i.label==="id3")return gl(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Lr();if(n)for(let a=0;a<r.length;a++){const o=r[a].type;if(o===Se.emsg&&!i||!s)continue;const l=Ho(r[a].data),d=r[a].pts;let c=d+r[a].duration;c>ci&&(c=ci),c-d<=0&&(c=d+Dc);for(let h=0;h<l.length;h++){const u=l[h];if(!Wo(u)){this.updateId3CueEnds(d,o);const f=Rr(n,d,c,u,o);f&&this.id3Track.addCue(f)}}}}updateId3CueEnds(e,t){var i;const s=(i=this.id3Track)==null?void 0:i.cues;if(s)for(let r=s.length;r--;){const n=s[r];n.type===t&&n.startTime<e&&n.endTime===ci&&(n.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let l;s==="audio"?l=d=>d.type===Se.audioId3&&o:s==="video"?l=d=>d.type===Se.emsg&&a:l=d=>d.type===Se.audioId3&&o||d.type===Se.emsg&&a,yr(r,t,i,l)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:s,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const a=Lr();if(i&&s&&!n){const{fragmentStart:m,fragmentEnd:g}=e;let y=this.assetCue;y?(y.startTime=m,y.endTime=g):a&&(y=this.assetCue=Rr(a,m,g,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),y&&(y.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(y),y.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=e,d=Object.keys(l);let c=this.dateRangeCuesAppended;if(o&&t){var h;if((h=o.cues)!=null&&h.length){const m=Object.keys(c).filter(g=>!d.includes(g));for(let g=m.length;g--;){var u;const y=m[g],v=(u=c[y])==null?void 0:u.cues;delete c[y],v&&Object.keys(v).forEach(E=>{const T=v[E];if(T){T.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(T)}catch{}}})}}else c=this.dateRangeCuesAppended={}}const f=e.fragments[e.fragments.length-1];if(!(d.length===0||!N(f?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let m=0;m<d.length;m++){const g=d[m],y=l[g],v=y.startTime,E=c[g],T=E?.cues||{};let S=E?.durationKnown||!1,A=ci;const{duration:b,endDate:I}=y;if(I&&b!==null)A=v+b,S=!0;else if(y.endOnNext&&!S){const P=d.reduce((w,x)=>{if(x!==y.id){const U=l[x];if(U.class===y.class&&U.startDate>y.startDate&&(!w||y.startDate<w.startDate))return U}return w},null);P&&(A=P.startTime,S=!0)}const D=Object.keys(y.attr);for(let P=0;P<D.length;P++){const w=D[P];if(!Mu(w))continue;const x=T[w];if(x)S&&!(E!=null&&E.durationKnown)?x.endTime=A:Math.abs(x.startTime-v)>.01&&(x.startTime=v,x.endTime=A);else if(a){let U=y.attr[w];Ou(w)&&(U=xa(U));const O=Rr(a,v,A,{key:w,data:U},Se.dateRange);O&&(O.id=g,this.id3Track.addCue(O),T[w]=O,n&&(w==="X-ASSET-LIST"||w==="X-ASSET-URL")&&O.addEventListener("enter",this.onEventCueEnter))}}c[g]={cues:T,dateRange:y,durationKnown:S}}}}},Pc=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.currentTime;const s=this.computeLatency();if(s===null)return;this._latency=s;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:n}=this.config;if(!r||n===1||!i.live)return;const a=this.targetLatency;if(a===null)return;const o=s-a;if(o<Math.min(this.maxLatency,a+i.targetduration)&&o>.05&&this.forwardBufferLength>1){const l=Math.min(2,Math.max(1,n)),d=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20,c=Math.min(l,Math.max(1,d));this.changeMediaPlaybackRate(t,c)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:i,targetduration:s}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||l===0)&&(l=r!==void 0?r:n*s);const d=s;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const i=this.levelDetails;if(i===null)return null;const s=i.edge,r=e-t-this.edgeStalled,n=s-i.totalduration,a=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===L.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,s;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},_c=class extends si{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,s=[],r={},n={};let a=!1,o=!1,l=!1;t.levels.forEach(d=>{const c=d.attrs;let{audioCodec:h,videoCodec:u}=d;h&&(d.audioCodec=h=Ri(h,i)||void 0),u&&(u=d.videoCodec=cu(u));const{width:f,height:m,unknownCodecs:g}=d,y=g?.length||0;if(a||(a=!!(f&&m)),o||(o=!!u),l||(l=!!h),y||h&&!this.isAudioSupported(h)||u&&!this.isVideoSupported(u)){this.log(`Some or all CODECS not supported "${c.CODECS}"`);return}const{CODECS:v,"FRAME-RATE":E,"HDCP-LEVEL":T,"PATHWAY-ID":S,RESOLUTION:A,"VIDEO-RANGE":b}=c,I=`${`${S||"."}-`}${d.bitrate}-${A}-${E}-${v}-${b}-${T}`;if(r[I])if(r[I].uri!==d.url&&!d.attrs["PATHWAY-ID"]){const D=n[I]+=1;d.attrs["PATHWAY-ID"]=new Array(D+1).join(".");const P=this.createLevel(d);r[I]=P,s.push(P)}else r[I].addGroupId("audio",c.AUDIO),r[I].addGroupId("text",c.SUBTITLES);else{const D=this.createLevel(d);r[I]=D,n[I]=1,s.push(D)}}),this.filterAndSortMediaOptions(s,t,a,o,l)}createLevel(e){const t=new ht(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const s=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(s.message),t.supportedResult=ja(s,[])}return t}isAudioSupported(e){return Ut(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Ut(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,s,r){var n;let a=[],o=[],l=e;const d=((n=t.stats)==null?void 0:n.parsing)||{};if((i||s)&&r&&(l=l.filter(({videoCodec:v,videoRange:E,width:T,height:S})=>(!!v||!!(T&&S))&&vu(E))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let v="no level with compatible codecs found in manifest",E=v;t.levels.length&&(E=`one or more CODECS in variant not supported: ${ne(t.levels.map(S=>S.attrs.CODECS).filter((S,A,b)=>b.indexOf(S)===A))}`,this.warn(E),v+=` (${E})`);const T=new Error(v);this.hls.trigger(p.ERROR,{type:$.MEDIA_ERROR,details:L.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:T,reason:E})}}),d.end=performance.now();return}t.audioTracks&&(a=t.audioTracks.filter(v=>!v.audioCodec||this.isAudioSupported(v.audioCodec)),kl(a)),t.subtitles&&(o=t.subtitles,kl(o));const c=l.slice(0);l.sort((v,E)=>{if(v.attrs["HDCP-LEVEL"]!==E.attrs["HDCP-LEVEL"])return(v.attrs["HDCP-LEVEL"]||"")>(E.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&v.height!==E.height)return v.height-E.height;if(v.frameRate!==E.frameRate)return v.frameRate-E.frameRate;if(v.videoRange!==E.videoRange)return qt.indexOf(v.videoRange)-qt.indexOf(E.videoRange);if(v.videoCodec!==E.videoCodec){const T=Ka(v.videoCodec),S=Ka(E.videoCodec);if(T!==S)return S-T}if(v.uri===E.uri&&v.codecSet!==E.codecSet){const T=Li(v.codecSet),S=Li(E.codecSet);if(T!==S)return S-T}return v.averageBitrate!==E.averageBitrate?v.averageBitrate-E.averageBitrate:0});let h=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length)){for(let v=0;v<c.length;v++)if(c[v].pathwayId===l[0].pathwayId){h=c[v];break}}this._levels=l;for(let v=0;v<l.length;v++)if(l[v]===h){var u;this._firstLevel=v;const E=h.bitrate,T=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${E}`),((u=this.hls.userConfig)==null?void 0:u.abrEwmaDefaultEstimate)===void 0){const S=Math.min(E,this.hls.config.abrEwmaDefaultEstimateMax);S>T&&T===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=S)}break}const f=r&&!s,m=this.hls.config,g=!!(m.audioStreamController&&m.audioTrackController),y={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:s,altAudio:g&&!f&&a.some(v=>!!v.url)};d.end=performance.now(),this.hls.trigger(p.MANIFEST_PARSED,y)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const d=new Error("invalid level idx"),c=e<0;if(this.hls.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.LEVEL_SWITCH_ERROR,level:e,fatal:c,error:d,reason:d.message}),c)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,r=s?s.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,i===e&&s&&r===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${i}${r?" with Pathway "+r:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(p.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const d=this.switchParams(n.uri,s?.details,l);this.loadPlaylist(d)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),i=e.filter(s=>t.indexOf(s)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===q.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===B.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(r=>!!i[r]))return;const s=this._levels[t.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var i;const{level:s,details:r}=t,n=t.levelInfo;if(!n){var a;this.warn(`Invalid level index ${s}`),(a=t.deliveryDirectives)!=null&&a.skip&&(r.deltaUpdateFailed=!0);return}if(n===this.currentLevel||t.withoutMultiVariant){n.fragmentError===0&&(n.loadError=0);let o=n.details;o===t.details&&o.advanced&&(o=void 0),this.playlistLoaded(s,t,o)}else(i=t.deliveryDirectives)!=null&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,a=n?.age;this.log(`Loading level index ${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${i}`),this.hls.trigger(p.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const i=this._levels.filter((r,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(a=>a.level=-1)),!1));Co(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(p.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}},kc=100,Cc=class extends Zt{constructor(e,t,i){super(e,t,i,"stream-controller",B.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const s=this.media,r=s?s.currentTime:null;if(r===null||!N(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const n=this.getFwdBufferInfoAtPos(s,r,B.MAIN,0);if(n===null||n.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${n?n.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(kc),this.level=-1,!this.startFragRequested){let r=s.startLevel;r===-1&&(s.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=s.firstAutoLevel),s.nextLoadLevel=r,this.level=s.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=_.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=_.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case _.WAITING_LEVEL:{const{levels:e,level:t}=this,i=e?.[t],s=i?.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=_.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=_.IDLE;break}break}case _.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===_.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(t===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[r]))return;const n=i[r],a=this.getMainFwdBufferInfo();if(a===null)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const m={};this.altAudio===2&&(m.type="video"),this.hls.trigger(p.BUFFER_EOS,m),this.state=_.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const l=n.details;if(!l||this.state===_.WAITING_LEVEL||this.waitForLive(n)){this.level=r,this.state=_.WAITING_LEVEL,this.startFragRequested=!1;return}const d=a.len,c=this.getMaxBufferLength(n.maxBitrate);if(d>=c)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(h,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&de(u)&&this.fragmentTracker.getState(u)!==he.OK){var f;const m=((f=this.backtrackFragment)!=null?f:u).sn-l.startSN,g=l.fragments[m-1];g&&u.cc===g.cc&&(u=g,this.fragmentTracker.removeFragment(g))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,h)){if(!u.gap){const m=this.audioOnly&&!this.altAudio?re.AUDIO:re.VIDEO,g=(m===re.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;g&&this.afterBufferFlushed(g,m,B.MAIN)}u=this.getNextFragmentLoopLoading(u,l,a,B.MAIN,c)}u&&(this.exceedsMaxBuffer(a,c,u)||(u.initSegment&&!u.initSegment.data&&!this.bitrateTest&&(u=u.initSegment),this.loadFragment(u,n,h)))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);s===he.NOT_LOADED||s===he.PARTIAL?de(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,B.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==0){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let i;const s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const a=this.getMainFwdBufferInfo();if(!a||a.len<r.targetduration*2)return}if(!t.paused&&e){const a=e[this.hls.nextLoadLevel],o=this.fragLastKbps;o&&this.fragCurrent?i=this.fragCurrent.duration*a.maxBitrate/(1e3*o)+1:i=0}else i=0;const n=this.getBufferedFrag(t.currentTime+i);if(n){const a=this.followingBufferedFrag(n);if(a){this.abortCurrentFrag();const o=a.maxStartPTS?a.maxStartPTS:a.start,l=a.duration,d=Math.max(n.end,o+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case _.KEY_LOADING:case _.FRAG_LOADING:case _.FRAG_LOADING_WAITING_RETRY:case _.PARSING:case _.PARSED:this.state=_.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;Ee(i,"playing",this.onMediaPlaying),Ee(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:i}=this;i&&(Le(i,"playing",this.onMediaPlaying),Le(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(p.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1;for(let r=0;r<t.levels.length;r++){const n=t.levels[r].audioCodec;n&&(i=i||n.indexOf("mp4a.40.2")!==-1,s=s||n.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=i&&s&&!Lg(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==_.IDLE)return;const s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=_.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:s,startFragRequested:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!s){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,d=this.fragCurrent;d&&(this.state===_.FRAG_LOADING||this.state===_.FRAG_LOADING_WAITING_RETRY)&&d.level!==t.level&&d.loader&&this.abortCurrentFrag();let c=0;if(a.live||(i=l.details)!=null&&i.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,c),this.hls.trigger(p.LEVEL_UPDATED,{details:a,level:n}),this.state===_.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=_.IDLE}r&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=r>=n-t.maxFragLookUpTolerance&&r<=a;if(s!==null&&i.duration>s&&(r<s||!o)){const d=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&i.readyState<4||r<a-d)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${s.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;const c=Y.bufferInfo(i,s,0);if(!((l=c.buffered)!=null&&l.length)){i.currentTime=s;return}if(c.start<=r){i.currentTime=s;return}const{nextStart:h}=Y.bufferedInfo(c.buffered,r,0);h&&(i.currentTime=h)}else i.currentTime=s}}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:r}=e,{levels:n}=this;if(!n){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const a=n[i.level];if(!a){this.warn(`Level ${i.level} not found on progress`);return}const o=a.details;if(!o){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const l=a.videoCodec,d=o.PTSKnown||!o.live,c=(t=i.initSegment)==null?void 0:t.data,h=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new Zr(this.hls,B.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=s?s.index:-1,m=f!==-1,g=new Xt(i.level,i.sn,i.stats.chunkCount,r.byteLength,f,m),y=this.initPTS[i.cc];u.push(r,c,h,l,i,s,o.totalduration,d,g,y)}onAudioTrackSwitching(e,t){const i=this.hls,s=this.altAudio!==0;if(wi(t.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const r=this.fragCurrent;r&&(this.log("Switching to main audio track, cancel main fragment load"),r.abortRequests(),this.fragmentTracker.removeFragment(r)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s){this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(p.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(p.AUDIO_TRACK_SWITCHED,t)}),i.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(p.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=wi(t.url,this.hls);if(i){const s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=i?2:0,this.tick()}onBufferCreated(e,t){const i=t.tracks;let s,r,n=!1;for(const a in i){const o=i[a];if(o.id==="main"){if(r=a,s=o,a==="video"){const l=i[a];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&s?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:s}=t,r=i.type===B.MAIN;if(r){if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===_.PARSED&&(this.state=_.IDLE);return}const a=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),de(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}const n=this.media;n&&(!this._hasEnoughToStart&&Y.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=_.ERROR;return}switch(t.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(B.MAIN,t);break;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===_.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===q.LEVEL&&(this.state=_.IDLE);break;case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case L.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=_.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==re.AUDIO||!this.altAudio){const i=(t===re.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,B.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}const s=this.timelineOffset;s&&i&&(i+=s);const r=this.getLevelDetails(),n=Y.getBuffered(e),a=n.length?n.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*(r?.partTarget||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${a}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{const{hls:s}=this,r=i?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=_.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=r.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),s.trigger(p.FRAG_LOADED,i),r.bitrateTest=!1}).catch(i=>{this.state===_.STOPPED||this.state===_.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n){this.resetWhenMissingContext(r);return}const{frag:a,part:o,level:l}=n,{video:d,text:c,id3:h,initSegment:u}=s,{details:f}=l,m=this.altAudio?void 0:s.audio;if(this.fragContextChanged(a)){this.fragmentTracker.removeFragment(a);return}if(this.state=_.PARSING,u){const g=u.tracks;if(g){const T=a.initSegment||a;if(this.unhandledEncryptionError(u,a))return;this._bufferInitSegment(l,g,T,r),i.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:T,id:t,tracks:g})}const y=u.initPTS,v=u.timescale,E=this.initPTS[a.cc];if(N(y)&&(!E||E.baseTime!==y||E.timescale!==v)){const T=u.trackId;this.initPTS[a.cc]={baseTime:y,timescale:v,trackId:T},i.trigger(p.INIT_PTS_FOUND,{frag:a,id:t,initPTS:y,timescale:v,trackId:T})}}if(d&&f){m&&d.type==="audiovideo"&&this.logMuxedErr(a);const g=f.fragments[a.sn-1-f.startSN],y=a.sn===f.startSN,v=!g||a.cc>g.cc;if(s.independent!==!1){const{startPTS:E,endPTS:T,startDTS:S,endDTS:A}=d;if(o)o.elementaryStreams[d.type]={startPTS:E,endPTS:T,startDTS:S,endDTS:A};else if(d.firstKeyFrame&&d.independent&&r.id===1&&!v&&(this.couldBacktrack=!0),d.dropped&&d.independent){const b=this.getMainFwdBufferInfo(),I=(b?b.end:this.getLoadPosition())+this.config.maxBufferHole,D=d.firstKeyFramePTS?d.firstKeyFramePTS:E;if(!y&&I<D-this.config.maxBufferHole&&!v){this.backtrack(a);return}else v&&(a.gap=!0);a.setElementaryStreamInfo(d.type,a.start,T,a.start,A,!0)}else y&&E-(f.appliedTimelineOffset||0)>di&&(a.gap=!0);a.setElementaryStreamInfo(d.type,E,T,S,A),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(d,a,o,r,y||v)}else if(y||v)a.gap=!0;else{this.backtrack(a);return}}if(m){const{startPTS:g,endPTS:y,startDTS:v,endDTS:E}=m;o&&(o.elementaryStreams[re.AUDIO]={startPTS:g,endPTS:y,startDTS:v,endDTS:E}),a.setElementaryStreamInfo(re.AUDIO,g,y,v,E),this.bufferFragmentData(m,a,o,r)}if(f&&h!=null&&h.samples.length){const g={id:t,frag:a,details:f,samples:h.samples};i.trigger(p.FRAG_PARSING_METADATA,g)}if(f&&c){const g={id:t,frag:a,details:f,samples:c.samples};i.trigger(p.FRAG_PARSING_USERDATA,g)}}logMuxedErr(e){this.warn(`${de(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==_.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:r,video:n,audiovideo:a}=t;if(r){const l=e.audioCodec;let d=Di(r.codec,l);d==="mp4a"&&(d="mp4a.40.5");const c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){d&&(d.indexOf("mp4a.40.5")!==-1?d="mp4a.40.2":d="mp4a.40.5");const h=r.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&c.indexOf("firefox")===-1&&(d="mp4a.40.5")}d&&d.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(d="mp4a.40.2",this.log(`Android: force audio codec to ${d}`)),l&&l!==d&&this.log(`Swapping manifest audio codec "${l}" for "${d}"`),r.levelCodec=d,r.id=B.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${d||""}/${l||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=B.MAIN;const l=n.codec;if(l?.length===4)switch(l){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${n.codec!==l?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(p.BUFFER_CODECS,t),!this.hls)return;o.forEach(l=>{const d=t[l].initSegment;d!=null&&d.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:l,data:d,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,B.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,i=e?.[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=_.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(Y.isBuffered(e,i)?t=this.getAppendedFrag(i):Y.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const s=this.fragPlaying,r=t.level;(!s||t.sn!==s.sn||s.level!==r)&&(this.fragPlaying=t,this.hls.trigger(p.FRAG_CHANGED,{frag:t}),(!s||s.level!==r)&&this.hls.trigger(p.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return N(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(N(t)){const i=this.getLevelDetails(),s=this.currentFrag||(i?lt(null,i.fragments,t):null);if(s){const r=s.programDateTime;if(r!==null){const n=r+(t-s.start)*1e3;return new Date(n)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},xc=class extends Pe{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyIdToKeyInfo){const s=this.keyIdToKeyInfo[i].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=L.KEY_LOAD_ERROR,i,s,r){return new Ve({type:$.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:s})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let s=0,r=t.length;s<r;s++){const n=t[s];if(e.cc<=n.cc&&(!de(e)||!de(n)||e.sn<n.sn)||!i&&s==r-1)return this.emeController.selectKeySystemFormat(n).then(a=>{if(!this.emeController)return;n.setKeyFormat(a);const o=Mi(a);if(o)return this.emeController.getKeySystemAccess([o])})}if(this.config.requireKeySystemAccessOnStart){const s=$t(this.config);if(s.length)return this.emeController.getKeySystemAccess(s)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,s;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const l=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,L.KEY_LOAD_ERROR,l))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,L.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=wr(r);let o=this.keyIdToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if(this.emeController&&(s=o)!=null&&s.keyLoadPromise)switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then(l=>{const{keyInfo:d}=l;return r.key=d.decryptdata.key,{frag:e,keyInfo:d}})}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${r.keyId?" keyId: "+ye(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,L.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var s;if(!e.decryptdata.keyId&&(s=t.initSegment)!=null&&s.data){const r=Jh(t.initSegment.data);if(r.length){let n=r[0];n.some(a=>a!==0)?(this.log(`Using keyId found in init segment ${ye(n)}`),wt.setKeyIdForUri(e.decryptdata.uri,n)):(n=wt.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${ye(n)}`)),e.decryptdata.keyId=n}}return!e.decryptdata.keyId&&!de(t)?Promise.resolve(i):(e.keyLoadPromise=this.emeController.loadKey(i).then(r=>(e.mediaKeySessionContext=r,i))).catch(r=>{throw e.keyLoadPromise=null,"data"in r&&(r.data.frag=t),r})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,s=i.loader,r=new s(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((n,a)=>{const o={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=i.keyLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};r.load(o,d,{onSuccess:(c,h,u,f)=>{const{frag:m,keyInfo:g}=u,y=wr(g.decryptdata);if(!m.decryptdata||g!==this.keyIdToKeyInfo[y])return a(this.createKeyLoadError(m,L.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),f));g.decryptdata.key=m.decryptdata.key=new Uint8Array(c.data),m.keyLoader=null,g.loader=null,n({frag:m,keyInfo:g})},onError:(c,h,u,f)=>{this.resetLoader(h),a(this.createKeyLoadError(t,L.KEY_LOAD_ERROR,new Error(`HTTP Error ${c.code} loading key ${c.text}`),u,ie({url:o.url,data:void 0},c)))},onTimeout:(c,h,u)=>{this.resetLoader(h),a(this.createKeyLoadError(t,L.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),u))},onAbort:(c,h,u)=>{this.resetLoader(h),a(this.createKeyLoadError(t,L.INTERNAL_ABORTED,new Error("key loading aborted"),u))}})})}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=null,i.loader=null);const n=wr(i.decryptdata)||s;delete this.keyIdToKeyInfo[n],r&&r.destroy()}},Mc=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,s=t.loader,r=new(i||s)(t);return this.loaders[e.type]=r,r}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:q.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:s,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=t;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:q.LEVEL,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:q.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:q.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){const i=this.loaders[q.LEVEL];if(i){const s=i.context;s&&!t.levels.some(r=>r===s.levelOrTrack)&&(i.abort(),delete this.loaders[q.LEVEL])}}load(e){var t;const i=this.hls.config;let s=this.getInternalLoader(e);if(s){const o=this.hls.logger,l=s.context;if(l&&l.levelOrTrack===e.levelOrTrack&&(l.url===e.url||l.deliveryDirectives&&!e.deliveryDirectives)){l.url===e.url?o.log(`[playlist-loader]: ignore ${e.url} ongoing request`):o.log(`[playlist-loader]: ignore ${e.url} in favor of ${l.url}`);return}o.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let r;if(e.type===q.MANIFEST?r=i.manifestLoadPolicy.default:r=se({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),N((t=e.deliveryDirectives)==null?void 0:t.part)){let o;if(e.type===q.LEVEL&&e.level!==null?o=this.hls.levels[e.level].details:e.type===q.AUDIO_TRACK&&e.id!==null?o=this.hls.audioTracks[e.id].details:e.type===q.SUBTITLE_TRACK&&e.id!==null&&(o=this.hls.subtitleTracks[e.id].details),o){const l=o.partTarget,d=o.targetduration;if(l&&d){const c=Math.max(l*3,d*.8)*1e3;r=se({},r,{maxTimeToFirstByteMs:Math.min(c,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(c,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0};s.load(e,a,{onSuccess:(o,l,d,c)=>{const h=this.getInternalLoader(d);this.resetInternalLoader(d.type);const u=o.data;l.parsing.start=performance.now(),ft.isMediaPlaylist(u)||d.type!==q.MANIFEST?this.handleTrackOrLevelPlaylist(o,l,d,c||null,h):this.handleMasterPlaylist(o,l,d,c)},onError:(o,l,d,c)=>{this.handleNetworkError(l,d,!1,o,c)},onTimeout:(o,l,d)=>{this.handleNetworkError(l,d,!0,void 0,o)}})}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,s){const r=this.hls,n=e.data,a=Pr(e,i),o=ft.parseMasterPlaylist(n,a);if(o.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,o.playlistParsingError,s,t);return}const{contentSteering:l,levels:d,sessionData:c,sessionKeys:h,startTimeOffset:u,variableList:f}=o;this.variableList=f,d.forEach(v=>{const{unknownCodecs:E}=v;if(E){const{preferManagedMediaSource:T}=this.hls.config;let{audioCodec:S,videoCodec:A}=v;for(let b=E.length;b--;){const I=E[b];Ut(I,"audio",T)?(v.audioCodec=S=S?`${S},${I}`:I,ct.audio[S.substring(0,4)]=2,E.splice(b,1)):Ut(I,"video",T)&&(v.videoCodec=A=A?`${A},${I}`:I,ct.video[A.substring(0,4)]=2,E.splice(b,1))}}});const{AUDIO:m=[],SUBTITLES:g,"CLOSED-CAPTIONS":y}=ft.parseMasterPlaylistMedia(n,a,o);m.length&&!m.some(v=>!v.url)&&d[0].audioCodec&&!d[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new oe({}),bitrate:0,url:""})),r.trigger(p.MANIFEST_LOADED,{levels:d,audioTracks:m,subtitles:g,captions:y,contentSteering:l,url:a,stats:t,networkDetails:s,sessionData:c,sessionKeys:h,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(e,t,i,s,r){const n=this.hls,{id:a,level:o,type:l}=i,d=Pr(e,i),c=N(o)?o:N(a)?a:0,h=Ml(i),u=ft.parseLevelPlaylist(e.data,d,c,h,0,this.variableList);if(l===q.MANIFEST){const f={attrs:new oe({}),bitrate:0,details:u,name:"",url:d};u.requestScheduled=t.loading.start+wo(u,0),n.trigger(p.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:d,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=u,this.handlePlaylistLoaded(u,e,t,i,s,r)}handleManifestParsingError(e,t,i,s,r){this.hls.trigger(p.ERROR,{type:$.NETWORK_ERROR,details:L.MANIFEST_PARSING_ERROR,fatal:t.type===q.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:r})}handleNetworkError(e,t,i=!1,s,r){let n=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===q.LEVEL?n+=`: ${e.level} id: ${e.id}`:(e.type===q.AUDIO_TRACK||e.type===q.SUBTITLE_TRACK)&&(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=L.UNKNOWN,l=!1;const d=this.getInternalLoader(e);switch(e.type){case q.MANIFEST:o=i?L.MANIFEST_LOAD_TIMEOUT:L.MANIFEST_LOAD_ERROR,l=!0;break;case q.LEVEL:o=i?L.LEVEL_LOAD_TIMEOUT:L.LEVEL_LOAD_ERROR,l=!1;break;case q.AUDIO_TRACK:o=i?L.AUDIO_TRACK_LOAD_TIMEOUT:L.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case q.SUBTITLE_TRACK:o=i?L.SUBTITLE_TRACK_LOAD_TIMEOUT:L.SUBTITLE_LOAD_ERROR,l=!1;break}d&&this.resetInternalLoader(e.type);const c={type:$.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:d,context:e,error:a,networkDetails:t,stats:r};s&&(c.response=ie({url:t?.url||e.url,data:void 0},s)),this.hls.trigger(p.ERROR,c)}handlePlaylistLoaded(e,t,i,s,r,n){const a=this.hls,{type:o,level:l,levelOrTrack:d,id:c,groupId:h,deliveryDirectives:u}=s,f=Pr(t,s),m=Ml(s);let g=typeof s.level=="number"&&m===B.MAIN?l:void 0;const y=e.playlistParsingError;if(y){if(this.hls.logger.warn(`${y} ${e.url}`),!a.config.ignorePlaylistParsingErrors){a.trigger(p.ERROR,{type:$.NETWORK_ERROR,details:L.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:t,context:s,level:g,parent:m,networkDetails:r,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){const v=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(p.ERROR,{type:$.NETWORK_ERROR,details:L.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:t,context:s,level:g,parent:m,networkDetails:r,stats:i});return}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),(!n.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),o){case q.MANIFEST:case q.LEVEL:if(g){if(!d)g=0;else if(d!==a.levels[g]){const v=a.levels.indexOf(d);v>-1&&(g=v)}}a.trigger(p.LEVEL_LOADED,{details:e,levelInfo:d||a.levels[0],level:g||0,id:c||0,stats:i,networkDetails:r,deliveryDirectives:u,withoutMultiVariant:o===q.MANIFEST});break;case q.AUDIO_TRACK:a.trigger(p.AUDIO_TRACK_LOADED,{details:e,track:d,id:c||0,groupId:h||"",stats:i,networkDetails:r,deliveryDirectives:u});break;case q.SUBTITLE_TRACK:a.trigger(p.SUBTITLE_TRACK_LOADED,{details:e,track:d,id:c||0,groupId:h||"",stats:i,networkDetails:r,deliveryDirectives:u});break}}},ps=class Ct{static get version(){return Pt}static isMSESupported(){return Dr()}static isSupported(){return xl()}static getMediaSource(){return Ye()}static get Events(){return p}static get MetadataSchema(){return Se}static get ErrorTypes(){return $}static get ErrorDetails(){return L}static get DefaultConfig(){return Ct.defaultConfig?Ct.defaultConfig:bc}static set DefaultConfig(t){Ct.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new is,this._autoLevelCapping=-1,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const i=this.logger=Kh(t.debug||!1,"Hls instance",t.assetPlayerId),s=this.config=Ig(Ct.DefaultConfig,t,i);this.userConfig=t,s.progressive&&Ag(s,i);const{abrController:r,bufferController:n,capLevelController:a,errorController:o,fpsController:l}=s,d=new o(this),c=this.abrController=new r(this),h=new Wl(this),u=s.interstitialsController,f=u?this.interstitialsController=new u(this,Ct):null,m=this.bufferController=new n(this,h),g=this.capLevelController=new a(this),y=new l(this),v=new Mc(this),E=s.contentSteeringController,T=E?new E(this):null,S=this.levelController=new _c(this,T),A=new wc(this),b=new xc(this.config,this.logger),I=this.streamController=new Cc(this,h,b),D=this.gapController=new Rc(this,h);g.setStreamController(I),y.setStreamController(I);const P=[v,S,I];f&&P.splice(1,0,f),T&&P.splice(1,0,T),this.networkControllers=P;const w=[c,m,D,g,y,A,h];this.audioTrackController=this.createController(s.audioTrackController,P);const x=s.audioStreamController;x&&P.push(this.audioStreamController=new x(this,h,b)),this.subtitleTrackController=this.createController(s.subtitleTrackController,P);const U=s.subtitleStreamController;U&&P.push(this.subtititleStreamController=new U(this,h,b)),this.createController(s.timelineController,w),b.emeController=this.emeController=this.createController(s.emeController,w),this.cmcdController=this.createController(s.cmcdController,w),this.latencyController=this.createController(Pc,w),this.coreComponents=w,P.push(d);const O=d.onErrorOut;typeof O=="function"&&this.on(p.ERROR,O,d),this.on(p.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(t,i){if(t){const s=new t(this);return i&&i.push(s),s}return null}on(t,i,s=this){this._emitter.on(t,i,s)}once(t,i,s=this){this._emitter.once(t,i,s)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,i,s=this,r){this._emitter.off(t,i,s,r)}listeners(t){return this._emitter.listeners(t)}emit(t,i,s){return this._emitter.emit(t,i,s)}trigger(t,i){if(this.config.debug)return this.emit(t,t,i);try{return this.emit(t,t,i)}catch(s){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const r=t===p.ERROR;this.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:r,event:t,error:s}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(p.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(i=>i.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(i=>i.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const n=new Error(`attachMedia failed: invalid argument (${t})`);this.trigger(p.ERROR,{type:$.OTHER_ERROR,details:L.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const i="media"in t,s=i?t.media:t,r=i?t:{media:s};this._media=s,this.trigger(p.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia"),this.trigger(p.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(p.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const i=this.media,s=this._url,r=this._url=ji.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),i&&s&&(s!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(i)),this.trigger(p.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,i){this.logger.log(`startLoad(${t+(i?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(t,i),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!(this.started||!this.networkControllers));t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[B.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[B.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[B.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,i=t?.currentTime;this.detachMedia(),t&&(this.attachMedia(t),i&&this.startLoad(i))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=ag()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return t===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),t!==-1&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const i=!!t;i!==this.config.capLevelToPlayerSize&&(i?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=i)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){yu(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:i}}=this;if(!t)return 0;const s=t.length;for(let r=0;r<s;r++)if(t[r].maxBitrate>=i)return r;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:i,maxHdcpLevel:s}=this;let r;if(i===-1&&t!=null&&t.length?r=t.length-1:r=i,s)for(let n=r;n--;){const a=t[n].attrs["HDCP-LEVEL"];if(a&&a<=s)return n}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var i;return((i=this.audioTrackController)==null?void 0:i.setAudioOption(t))||null}setSubtitleOption(t){var i;return((i=this.subtitleTrackController)==null?void 0:i.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const i=this.audioTrackController;i&&(i.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const i=this.subtitleTrackController;i&&(i.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return t?t.subtitleDisplay:!1}set subtitleDisplay(t){const i=this.subtitleTrackController;i&&(i.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!!((t=this.bufferController)!=null&&t.bufferedToEnd)}get interstitialsManager(){var t;return((t=this.interstitialsController)==null?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,i=this.allAudioTracks){return Ya(t,Qa(i),navigator.mediaCapabilities)}},ps.defaultConfig=void 0})),Dg=Mt({default:()=>wg});async function wg(e,t,i,s){const r=mi(s?.options),n=(i||"mp4").toLowerCase();let a=!1,o="",l=null;const d=rt("div","fv-video-viewer"),c=rt("section","fv-video-shell"),h=rt("div","fv-video-heading");h.append(rt("span","",n.toUpperCase()||"VIDEO"),rt("strong","",r("media.video.title")));const u=rt("video","fv-video-player");u.controls=!0,u.preload="metadata",u.textContent=r("media.video.unsupported"),c.append(h,u),n==="m3u8"&&c.append(rt("p","fv-video-hint",r("media.video.hlsHint"))),d.append(c),t.replaceChildren(Nc(),d);const f=()=>n==="m3u8"&&s?.url?s.url:(o=$c(e,n),o);return(async()=>{const g=f();if(n==="m3u8"){if(u.canPlayType("application/vnd.apple.mpegurl")){u.src=g;return}const{default:y}=await Promise.resolve().then(()=>(Rg(),Uh));if(a)return;if(y.isSupported()){l=new y({enableWorker:!0,lowLatencyMode:!1}),l.loadSource(g),l.attachMedia(u);return}}u.src=g})(),Uc(t,()=>{a=!0,l?.destroy(),l=null,u.pause(),u.removeAttribute("src"),u.load(),o&&(URL.revokeObjectURL(o),o="")})}var Oc,Fc,rt,Nc,Uc,Bc,$c,Pg=ee((()=>{Ns(),Oc=`
|
|
82
82
|
.fv-video-viewer{width:100%;min-height:100%;display:flex;align-items:center;justify-content:center;padding:28px;background:#eef1f4;box-sizing:border-box}
|
|
83
83
|
.fv-video-shell{width:min(100%,960px);border-radius:8px;border:1px solid rgba(15,23,42,.1);background:#fff;box-shadow:0 18px 48px rgba(15,23,42,.14);overflow:hidden}
|
|
84
84
|
.fv-video-heading{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px 18px;border-bottom:1px solid rgba(15,23,42,.08)}
|
|
@@ -86,4 +86,4 @@ Schedule: ${o.map(m=>Me(m))} pos: ${this.timelinePos}`),d.length&&this.log(`Remo
|
|
|
86
86
|
.fv-video-heading strong{color:#132235;font-size:16px}
|
|
87
87
|
.fv-video-player{display:block;width:100%;aspect-ratio:16/9;background:#05070a}
|
|
88
88
|
.fv-video-hint{margin:0;padding:12px 18px 16px;color:#64748b;font-size:13px;line-height:1.7}
|
|
89
|
-
`,Fc={m3u8:"application/vnd.apple.mpegurl",mp4:"video/mp4",webm:"video/webm"},rt=(e,t,i)=>{const s=document.createElement(e);return t&&(s.className=t),typeof i=="string"&&(s.textContent=i),s},Nc=()=>{const e=document.createElement("style");return e.textContent=Oc,e},Uc=(e,t)=>({$el:e,unmount(){t(),e.replaceChildren()}}),Bc=e=>Fc[e]||"video/*",$c=(e,t)=>URL.createObjectURL(new Blob([e],{type:Bc(t)}))}));Ns();var Gc=["audio","video"],Vc=je.filter(e=>Gc.includes(e.id));if(Vc.length!==Gc.length)throw new Error("@file-viewer/renderer-media could not locate the shared audio/video format definitions.");var _g=Vc,kg=(e,t,i,s)=>Promise.resolve().then(()=>(Nh(),Oh)).then(({default:r})=>r(e,t,i,s)),Cg=(e,t,i,s)=>Promise.resolve().then(()=>(
|
|
89
|
+
`,Fc={m3u8:"application/vnd.apple.mpegurl",mp4:"video/mp4",webm:"video/webm"},rt=(e,t,i)=>{const s=document.createElement(e);return t&&(s.className=t),typeof i=="string"&&(s.textContent=i),s},Nc=()=>{const e=document.createElement("style");return e.textContent=Oc,e},Uc=(e,t)=>({$el:e,unmount(){t(),e.replaceChildren()}}),Bc=e=>Fc[e]||"video/*",$c=(e,t)=>URL.createObjectURL(new Blob([e],{type:Bc(t)}))}));Ns();var Gc=["audio","video"],Vc=je.filter(e=>Gc.includes(e.id));if(Vc.length!==Gc.length)throw new Error("@file-viewer/renderer-media could not locate the shared audio/video format definitions.");var _g=Vc,kg=(e,t,i,s)=>Promise.resolve().then(()=>(Nh(),Oh)).then(({default:r})=>r(e,t,i,s)),Cg=(e,t,i,s)=>Promise.resolve().then(()=>(Pg(),Dg)).then(({default:r})=>r(e,t,i,s)),Pn={id:"file-viewer-renderer-media",label:"Flyfish File Viewer media renderer",definitions:_g,handlers:[{rendererId:"audio",handler:kg},{rendererId:"video",handler:Cg}]},Kc=globalThis,Hc=Kc.FlyfishFileViewerWebFullRenderers||(Kc.FlyfishFileViewerWebFullRenderers={});Hc.media=Pn,Hc[Pn.id]=Pn})();
|