Skip to content

Spot it. Save it. Free, local-first Chrome extension for images, videos and prompts. Explore 2,000+ curated cases and connect your library to AI Agents via MCP. 提示词导演

Preserve captured media and clear saved drafts in 1.20.6

MigenAI95c1faf5ac0e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b297e45..a8f8695 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,13 @@
# Changelog
+## 1.20.6
+
+- 采集、保存及补充素材均为纯程序处理;保留预览确认流程,文章与媒体提示词按内容用途呈现,逐素材提示词随分享导入保留。
+- 修复部分媒体下载失败时案例已保存、侧栏却未清空的问题;真正未保存的内容继续保留,媒体问题可在来源信息中检查。
+- X 视频按当前帖匹配正常页面加载的媒体地址,优先保存完整 MP4;移除整帖网页嵌入,支持独立视频与 HLS 播放、时间定位和关闭回收。
+- 补全 ArtStation 项目播放器、Krea 原图和风格参考的采集;通用结构化图片与视频读取保留原件地址,视频封面不再替代视频。各平台范围见 [采集说明](docs/CAPTURE_SUPPORT.md)。
+- 合并前端简化:分享包下载与公开投稿分开,设置中的规则保存和恢复就近排列,收紧 Skill、创作台与维护任务的日常界面。
+
## 1.20.5
- 案例库项目侧栏支持直接拖动、搜索定位和移动到指定项目;保持项目关系及案例归属,提供移动撤销。
diff --git a/README.md b/README.md
index ed4586c..047cb73 100644
--- a/README.md
+++ b/README.md
@@ -17,6 +17,8 @@ PromptDirector 是一个免费、开源、本地优先的 Chrome 扩展。它把
- 为选定案例生成分享 ZIP;导入时逐项隔离坏文件,单个不兼容媒体不会阻断其他健康案例;
- 创建可换电脑恢复的完整资料夹备份(包含回收站,并在备份时复制可读取的本机链接原件),可选择安全合并或带回退点的精确恢复,也可通过加密同步文件夹在自己的设备间恢复资料。
+采集保留预览、调整和保存步骤,不调用 AI。视频优先保存本地,可用的独立播放器与 HLS 流可在库内播放;平台登录、原地址有效期和当前页面结构会影响结果。详见[采集说明](docs/CAPTURE_SUPPORT.md)。
+
## 隐私与数据
资料、媒体、标签和设置默认保存在当前浏览器。不会创建账号、投放广告或收集使用统计。
@@ -54,6 +56,8 @@ npm run verify
欢迎其他开发者共同维护 PromptDirector,包括修复问题、补充测试与文档、改善交互和完善跨浏览器体验。提交前请运行 `npm run verify`。
+界面改动先阅读[当前设计与验收原则](design-qa.md#当前设计与验收原则),以用户已确认的页面效果为基线,同时验证视觉和原有操作流程。
+
提交 issue 或代码时请说明用户可观察到的行为、复现方式和验证结果。请不要在 issue、日志、测试样本或提交中包含 API Key、私人来源、未授权素材或用户资料。
本项目采用 [Apache License 2.0](LICENSE)。第三方组件说明见 [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 8bef713..4d20ec6 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -31,3 +31,36 @@ PromptDirector includes Mozilla Readability for local article extraction. It is
## @noble/hashes
Incremental SHA-256 for library file integrity verification. MIT licensed. Source: https://github.com/paulmillr/noble-hashes . The pinned version is recorded in package-lock.json; its license is included in vendor/noble-hashes/LICENSE.
+
+## hls.js
+
+Bundled local video playback runtime. Exact version: package-lock.json. Source: https://github.com/video-dev/hls.js
+
+Copyright (c) 2017 Dailymotion (http://www.dailymotion.com)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+src/remux/mp4-generator.js and src/demux/exp-golomb.ts implementation in this project
+are derived from the HLS library for video.js (https://github.com/videojs/videojs-contrib-hls)
+
+That work is also covered by the Apache 2 License, following copyright:
+Copyright (c) 2013-2015 Brightcove
+
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/background.js b/background.js
index a91e8dd..9909dce 100644
--- a/background.js
+++ b/background.js
@@ -313,7 +313,9 @@ import {
} from "./page-capture-site-adapters.js";
import { boundedMediaBlobFromResponse, fetchBoundedMedia, isSupportedDocumentMimeType } from "./bounded-media.js";
import { downloadPageCaptureVideo } from "./page-capture-video.js";
-import { planPageCaptureRepair, mergePageCaptureRepair } from "./page-capture-repair.js";
+import { resolveXVideoSources } from "./x-video-capture.js";
+import { PAGE_CAPTURE_VIDEO_FRAME_RULES, resolvePageCaptureVideoFrames } from "./page-capture-frames.js";
+import { planPageCaptureRepair, mergePageCaptureRepair, capturedMediaPrompts } from "./page-capture-repair.js";
import { collectPageCaptureDownloads } from "./page-capture-downloads.js";
import {
discardPageSessionMedia,
@@ -347,7 +349,7 @@ import {
VIDEO_ANALYSIS_REQUEST_TIMEOUT_MS,
VIDEO_RECONSTRUCTION_CONTRACT_VERSION
} from "./video-analysis.js";
-import { detectMediaReferenceProvider } from "./media-reference-resolver.js";
+import { detectMediaReferenceProvider, officialMediaEmbedUrl } from "./media-reference-resolver.js";
import {
createCompoundCase,
normalizeCompoundCases,
@@ -1313,6 +1315,7 @@ async function collectPageCaptureTab(tab, options) {
maxInlinePixelDataCharacters: PAGE_CAPTURE_LIMITS.maxInlinePixelDataCharacters,
editedRegion: options.editedRegion || null,
downloads,
+ videoFrameRules: PAGE_CAPTURE_VIDEO_FRAME_RULES,
siteData
}]
});
@@ -1321,6 +1324,8 @@ async function collectPageCaptureTab(tab, options) {
siteData = await readPageCaptureSiteData(tab, { installObserver: false }) || siteData;
snapshot = { ...snapshot, candidates: siteData.candidates, siteStatus: siteData.completeness };
}
+ snapshot = await resolvePageCaptureVideoFrames(snapshot, tab.id, chrome.scripting);
+ snapshot = await resolveXVideoSources(snapshot, tab, chrome, { cancelled: () => Boolean(activePageCapture?.cancelled) });
return addVisiblePageCaptureFallbacks(snapshot, tab);
}
@@ -1774,7 +1779,7 @@ async function commitPageCapture(batchValue, metadata = {}) {
const repair = duplicate ? await planPageCaptureRepair(duplicate, candidate, async id => Boolean(await getMediaBlob(id))) : null;
const refreshedClassification = duplicate ? classifyContent({ ...duplicate, sourceFacts: candidate.sourceFacts }, state.classificationRules, state.taxonomy) : null;
const classificationChanged = duplicate && JSON.stringify(duplicate.classification?.pathIds) !== JSON.stringify(refreshedClassification.pathIds);
- if (duplicate && !repair.pending.length && !repair.obsoleteReferences.size && duplicate.sourceFacts?.pageType === candidate.pageType && !classificationChanged) {
+ if (duplicate && !repair.pending.length && !repair.obsoleteReferences.size && !repair.promptsChanged && duplicate.sourceFacts?.pageType === candidate.pageType && !classificationChanged) {
results.push({ candidateId: candidate.id, status: "duplicate", entryId: duplicate.id, title: duplicate.title });
continue;
}
@@ -1839,9 +1844,11 @@ async function commitPageCapture(batchValue, metadata = {}) {
continue;
}
if (media.kind === "video") {
- const referenceUrl = media.url || candidate.canonicalUrl;
+ const referenceUrl = officialMediaEmbedUrl(media.url) ? media.url
+ : candidate.media.filter(item => item.kind === "video").length === 1 && officialMediaEmbedUrl(candidate.canonicalUrl)
+ ? candidate.canonicalUrl : media.originalWorkUrl || media.url || candidate.canonicalUrl;
const provider = detectMediaReferenceProvider(referenceUrl);
- const playbackMode = ["youtube", "vimeo", "bilibili", "douyin", "x"].includes(provider) ? "embed" : "source";
+ const playbackMode = officialMediaEmbedUrl(referenceUrl, provider) ? "embed" : "source";
const videoAsset = {
id: repair?.matched.get(media.id)?.id || crypto.randomUUID(),
kind: "video",
@@ -1854,7 +1861,10 @@ async function commitPageCapture(batchValue, metadata = {}) {
height: media.height,
capturedAt: new Date().toISOString(),
playbackCapability: playbackMode === "embed" ? "embedded" : "external",
- reference: { url: referenceUrl, provider, playbackMode },
+ reference: { url: referenceUrl, provider, playbackMode,
+ ...(media.streamUrl ? { streamUrl: media.streamUrl } : {}),
+ ...(/^https?:/iu.test(media.url) && ["site-original", "video-element"].includes(media.sourceKind)
+ ? { playbackUrl: media.url } : {}) },
reviewStatus: "verified"
};
try {
@@ -1982,8 +1992,10 @@ async function commitPageCapture(batchValue, metadata = {}) {
warnings.push(`${media.alt || media.url}:${userMessage(error)}`);
}
}
+ const captureFacts = { ...candidate.sourceFacts, captureWarnings: [...new Set(warnings)],
+ status: warnings.length ? "partial" : candidate.sourceFacts.status };
if (duplicate) {
- const repaired = mergePageCaptureRepair(duplicate, candidate, repair, mediaAssets, articleAssetIds);
+ const repaired = mergePageCaptureRepair(duplicate, { ...candidate, sourceFacts: captureFacts }, repair, mediaAssets, articleAssetIds);
const entry = normalizeEntryMedia({ ...repaired,
classification: classifyContent(repaired, state.classificationRules, state.taxonomy)
});
@@ -2002,18 +2014,20 @@ async function commitPageCapture(batchValue, metadata = {}) {
results.push({ candidateId: candidate.id, status: "failed", title: candidate.title, warnings: [...warnings, "没有可保存的正文或媒体"] });
continue;
}
+ const mediaPrompts = capturedMediaPrompts(candidate, articleAssetIds);
const entry = normalizeEntryMedia({
...base,
schemaVersion: SCHEMA_VERSION,
+ mediaPrompts,
articleDocument: finalizeArticleDocumentAssets(candidate.articleDocument, articleAssetIds),
- sourceFacts: candidate.sourceFacts,
+ sourceFacts: captureFacts,
sourcePages: [{ url: candidate.canonicalUrl, title: candidate.title }],
mediaAssets,
primaryMediaId: (candidate.pageType === "video"
? mediaAssets.find((asset) => asset.kind === "video")
: mediaAssets.find((asset) => asset.kind === "image" && asset.usage !== "poster"))?.id
|| mediaAssets.find((asset) => asset.usage !== "poster")?.id || "",
- classification: classifyContent({ ...base, sourceFacts: candidate.sourceFacts, mediaAssets }, state.classificationRules, state.taxonomy),
+ classification: classifyContent({ ...base, sourceFacts: candidate.sourceFacts, mediaAssets, mediaPrompts }, state.classificationRules, state.taxonomy),
customLabels: [], metadataLabels: [], facetAssignments: [], analysisCandidates: [], analysisBreakdown: [],
rejectedCandidateKeys: [], negativeTerms: [], legacyFacetCandidates: [], analysisPending: false
});
@@ -2037,12 +2051,6 @@ async function commitPageCapture(batchValue, metadata = {}) {
const postCommitWarnings = [];
try { await notifySaved(entries.length); }
catch (error) { postCommitWarnings.push(`保存成功,但状态提示更新失败:${userMessage(error)}`); }
- const newImageEntries = results.filter((item) => ["saved", "partial"].includes(item.status)).map((item) => item.entryId)
- .filter((entryId) => entries.find((entry) => entry.id === entryId)?.mediaAssets?.some((asset) => asset.kind === "image"));
- if (newImageEntries.length) {
- try { await queueAutomaticVisionAnalysis(newImageEntries); }
- catch (error) { postCommitWarnings.push(`案例已保存,但自动画面分析没有加入队列:${userMessage(error)}`); }
- }
const savedCount = results.filter((item) => ["saved", "partial"].includes(item.status)).length;
const duplicateCount = results.filter((item) => item.status === "duplicate").length;
return {
@@ -2229,7 +2237,6 @@ async function addUploadedVisual(entryId, visualValue) {
}));
const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
- await queueAutomaticVisionAnalysis([updated.id]);
return { ok: true, message: `图片已加入案例 · 共 ${updated.visuals.length} 张`, entry: updated };
}
@@ -2352,7 +2359,6 @@ async function addUploadedMedia(entryId, assetValue, posterValue = null) {
updated = touchEntry(updated);
const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
- if (assetValue?.kind === "image") await queueAutomaticVisionAnalysis([updated.id]);
const contentCount = updated.mediaAssets.filter((item) => item.usage !== "poster").length;
return { ok: true, message: `资料已加入案例 · 共 ${contentCount} 项`, entry: updated };
}
@@ -2562,7 +2568,6 @@ async function commitCaptureDraft(duplicateAction = "", placementValue = {}) {
...(created ? { [STORAGE_KEYS.lastSaveUndo]: createEntrySaveUndo(entry.id) } : {})
});
await notifySaved(entries.length);
- if (draft.visuals.length) await queueAutomaticVisionAnalysis([entry.id]);
return { ok: true, message: target ? "内容已加入明确选择的案例" : "多段文字和截图已保存为新案例", entry, draft: nextDraft };
}
@@ -2610,10 +2615,6 @@ async function commitCaptureIntoCompound(draft, parts, state, targetCompound, pl
...captureCommitState(draft, nextDraft)
});
await notifySaved(entries.length);
- const affectedEntryIds = entries
- .filter((entry) => entryMediaAssets(entry).some((asset) => parts.some((part) => part.visuals.some((visual) => visual.id === asset.id))))
- .map((entry) => entry.id);
- if (affectedEntryIds.length) await queueAutomaticVisionAnalysis(affectedEntryIds);
return {
ok: true,
message: `内容已加入组合案例 · 共 ${compoundCase.memberEntryIds.length} 个部分`,
diff --git a/capture-additions.js b/capture-additions.js
index 1872cb8..dfb501e 100644
--- a/capture-additions.js
+++ b/capture-additions.js
@@ -71,3 +71,11 @@ export function savedDraftCaptureItems(draft, candidates, consumed) {
function comparableText(value) {
return String(value || "").replace(/\s+/gu, " ").trim();
}
+
+export function savedPageCaptureCandidateIds(batch, candidates, results) {
+ const persisted = results.filter(item => item.entryId && ["saved", "partial", "duplicate"].includes(item.status));
+ if (batch.captureMode === "list" && batch.saveMode === "combined" && persisted.length === 1) {
+ return new Set(candidates.map(candidate => candidate.id));
+ }
+ return new Set(persisted.map(item => item.candidateId));
+}
diff --git a/classifier.js b/classifier.js
index ed05632..2cdcc77 100644
--- a/classifier.js
+++ b/classifier.js
@@ -7,10 +7,10 @@ import {
import { entryHasMedia, normalizeEntryMedia } from "./media.js";
import { entryHasVisual } from "./visuals.js";
-export const CLASSIFIER_VERSION = 4;
+export const CLASSIFIER_VERSION = 5;
const WEIGHT = Object.freeze({ weak: 1, supporting: 2, format: 3, strong: 4, modelBody: 5, decisive: 6 });
-const THRESHOLD = Object.freeze({ tutorial: 6, tutorialTie: 8, videoPrompt: 4, imagePrompt: 5, imageCaseText: 360 });
+const THRESHOLD = Object.freeze({ tutorial: 6, tutorialTie: 8, imageCaseText: 360 });
const SIGNALS = Object.freeze({
tutorialWrapper: /(?:教程|攻略|教学|如何|方法|步骤|第一步|第二步|然后|最后|参数说明|注意事项|\b(?:tutorial|guide|how to|step-by-step)\b)/i,
@@ -40,14 +40,20 @@ export function classifyContent(entry = {}, rules = [], taxonomy = createDefault
}
const facts = entry.sourceFacts;
+ if (facts?.pageType === "article" && ["structured", "readability"].includes(facts.extractionMethod)) {
+ const tutorial = scoreTutorial(String(entry.text || ""), String(entry.title || ""), String(entry.url || "")) >= THRESHOLD.tutorial;
+ return classificationForRole(taxonomy, tutorial ? CONTENT_ROLES.tutorial : CONTENT_ROLES.reference, "完整文章按正文阅读");
+ }
if (facts?.extractionMethod === "structured" && ["video", "artwork"].includes(facts.pageType)) {
const video = facts.pageType === "video";
const kind = video ? "video" : "image";
if (entryHasMedia(entry, kind)) {
- const hasText = Boolean(String(entry.text || "").trim());
+ const hasPrompt = entry.mediaPrompts?.some(item => item.source !== "ai-suggestion" && String(item.text || "").trim())
+ || facts.originalPromptAvailable === true
+ || (facts.originalPromptAvailable !== false && scorePromptShape(String(entry.text || ""), "") >= WEIGHT.supporting);
return classificationForRole(taxonomy, video
- ? hasText ? CONTENT_ROLES.promptVideo : CONTENT_ROLES.videoCase
- : hasText ? CONTENT_ROLES.promptImage : CONTENT_ROLES.imageCase, "网页明确声明的作品类型与原始内容");
+ ? hasPrompt ? CONTENT_ROLES.promptVideo : CONTENT_ROLES.videoCase
+ : hasPrompt ? CONTENT_ROLES.promptImage : CONTENT_ROLES.imageCase, "作品类型及原始提示词证据");
}
}
@@ -66,22 +72,29 @@ export function classifyContent(entry = {}, rules = [], taxonomy = createDefault
const tutorialScore = scoreTutorial(body, title, url);
const videoScore = scoreMedium(body, title, url, "video");
const imageScore = scoreMedium(body, title, url, "image");
- const medium = chooseMedium(videoScore, imageScore, SIGNALS.videoTimeline.test(body));
+ const medium = chooseMedium(videoScore, imageScore, SIGNALS.videoTimeline.test(body))
+ || (entryHasMedia(entry, "video") ? "video" : entryHasMedia(entry, "image") ? "image" : null);
if (tutorialScore >= THRESHOLD.tutorial &&
(tutorialScore > promptScore || (tutorialScore >= THRESHOLD.tutorialTie && tutorialScore === promptScore))) {
return classificationForRole(taxonomy, CONTENT_ROLES.tutorial, "存在可迁移的教学或风格元信息");
}
- if (medium === "video" && (promptScore >= WEIGHT.supporting || videoScore >= THRESHOLD.videoPrompt)) {
+ if (facts?.originalPromptAvailable !== false && medium === "video" && promptScore >= WEIGHT.supporting) {
return classificationForRole(taxonomy, CONTENT_ROLES.promptVideo, "具体视频生成指令");
}
- if (medium === "image" && (promptScore >= WEIGHT.supporting || imageScore >= THRESHOLD.imagePrompt)) {
+ if (facts?.originalPromptAvailable !== false && medium === "image" && promptScore >= WEIGHT.supporting) {
return classificationForRole(taxonomy, CONTENT_ROLES.promptImage, "具体图片生成指令");
}
if (entryHasMedia(entry, "document") || entry.sourceKind === "quick_note") {
return classificationForRole(taxonomy, CONTENT_ROLES.reference, "本地文档或创作笔记");
}
+ if (entryHasMedia(entry, "video")) {
+ return classificationForRole(taxonomy, CONTENT_ROLES.videoCase, "已采集视频,未发现对应生成指令");
+ }
+ if (entryHasMedia(entry, "image")) {
+ return classificationForRole(taxonomy, CONTENT_ROLES.imageCase, "已采集图片,未发现对应生成指令");
+ }
if (entryHasVisual(entry) && body.trim().length <= THRESHOLD.imageCaseText) {
return classificationForRole(taxonomy, CONTENT_ROLES.imageCase, "短文字配图默认作为可编辑图片案例");
}
diff --git a/collector-page-capture-view.js b/collector-page-capture-view.js
index 31c1a61..22b076b 100644
--- a/collector-page-capture-view.js
+++ b/collector-page-capture-view.js
@@ -49,7 +49,7 @@ export function createPageCaptureCard(candidate, {
strip.className = "page-capture-thumbnails";
strip.classList.toggle("photo-group", candidate.pageType === "post" && candidate.media.filter(m => m.kind === "image" && m.originalWorkUrl).length > 1);
candidate.media.forEach((media, index) => {
- if (!["image", "video"].includes(media.kind) || media.placement !== "inline" || (selected || media.quotedPostUrl) && !selectedMediaIds.includes(media.id)) return;
+ if (!["image", "video"].includes(media.kind) || media.placement !== "inline" || (selected || media.isQuoted || media.quotedPostUrl) && !selectedMediaIds.includes(media.id)) return;
const button = document.createElement("button");
button.type = "button";
button.title = media.alt || t(media.kind === "video" ? "视频" : "图片");
@@ -76,12 +76,13 @@ export function createPageCaptureCard(candidate, {
strip.append(thumbnail);
});
if (strip.childElementCount) card.append(strip);
- if (selected) for (const groupUrl of new Set(candidate.media.map(m => m.quotedPostUrl).filter(Boolean))) {
- const group = candidate.media.filter(m => m.quotedPostUrl === groupUrl);
+ const quoteGroup = media => media.quotedPostUrl || (media.isQuoted ? "unresolved-quote" : "");
+ if (selected) for (const groupUrl of new Set(candidate.media.map(quoteGroup).filter(Boolean))) {
+ const group = candidate.media.filter(m => quoteGroup(m) === groupUrl);
const row = document.createElement("div");
row.className = "page-capture-media-group";
const label = document.createElement("span");
- label.textContent = t("引用帖 · {count} 张图", { count: group.length });
+ label.textContent = t(group.every(media => media.kind === "image") ? "引用帖 · {count} 张图" : "引用帖 · {count} 个素材", { count: group.length });
const add = document.createElement("button");
add.type = "button";
const included = group.every(m => selectedMediaIds.includes(m.id));
diff --git a/collector.js b/collector.js
index 941d6ec..e53efb5 100644
--- a/collector.js
+++ b/collector.js
@@ -1,4 +1,4 @@
-import { appendCaptureCandidate, draftCaptureAddition, savedDraftCaptureItems } from "./capture-additions.js";
+import { appendCaptureCandidate, draftCaptureAddition, savedDraftCaptureItems, savedPageCaptureCandidateIds } from "./capture-additions.js";
import { createPageCaptureCard } from "./collector-page-capture-view.js";
import { deleteScreenshotBlob, getScreenshotBlob, saveScreenshotBlob } from "./image-store.js";
import { addDraftFragment, addDraftVisual } from "./capture-draft.js";
@@ -1273,8 +1273,7 @@ async function cancelPageCapture() {
}
}
-async function clearPageCaptureMarkers() {
- const tabId = pageCaptureBatch?.tabId;
+async function clearPageCaptureMarkers(tabId = pageCaptureBatch?.tabId) {
if (!Number.isInteger(tabId)) return;
await chrome.runtime.sendMessage({ type: "CLEAR_PAGE_CAPTURE_MARKERS", tabId, removeRegionMarkers: true }).catch(() => undefined);
}
@@ -1589,37 +1588,44 @@ async function savePageCapture(textOnly = false) {
...metadata
});
if (!response?.ok) throw new Error(response?.message || t("网页内容保存失败"));
- const partial = response.results?.filter((item) => item.status === "partial" || item.status === "failed") || [];
- if (partial.length) {
- if (metadata.newCollectionName && response.collectionId) {
- creatingCollection = false;
- await updateDraft({ ...draft, collectionId: response.collectionId, newCollectionName: "" });
- }
- const reasons = [...new Set(partial.flatMap(item => item.warnings || []))];
- pageCaptureBatch = normalizePageCaptureBatch({ ...saveBatch, status: "preview", error: reasons.join(";") });
- elements.pageCaptureMediaReview.open = true;
- showFeedback(t("{message};{count} 项存在媒体下载问题", { message: response.message, count: partial.length }), true);
- await refresh();
- return;
+ const results = response.results || [];
+ const savedCandidateIds = savedPageCaptureCandidateIds(saveBatch, selected, results);
+ const remainingIds = new Set(selected.filter(candidate => !savedCandidateIds.has(candidate.id)).map(candidate => candidate.id));
+ const incomplete = results.filter(item => item.status === "partial");
+ const cleanupErrors = [];
+ if (metadata.newCollectionName && response.collectionId) {
+ creatingCollection = false;
+ try { await updateDraft({ ...draft, collectionId: response.collectionId, newCollectionName: "" }); }
+ catch (error) { cleanupErrors.push(error.message); }
}
- await clearPageCaptureMarkers();
- const savedCandidateIds = new Set(response.results.filter(item => item.status === "saved").map(item => item.candidateId));
const savedDraftItems = savedDraftCaptureItems(draft, selected.filter(c => savedCandidateIds.has(c.id)), pageCaptureDraftIds);
- const cleanupErrors = [];
for (const item of savedDraftItems) {
try {
const cleanup = await chrome.runtime.sendMessage(item.kind === "image"
? { type: "REMOVE_CAPTURE_VISUAL", visualId: item.id }
: { type: "REMOVE_CAPTURE_FRAGMENT", fragmentId: item.id });
if (!cleanup?.ok) throw new Error(cleanup?.message || t("待保存内容没有更新"));
+ pageCaptureDraftIds.delete(`${item.kind}:${item.id}`);
} catch (error) { cleanupErrors.push(error.message); }
}
- pageCaptureDraftIds = new Set();
- pageCaptureBatch = null;
+ const failures = results.filter(item => !item.entryId || !["saved", "partial", "duplicate"].includes(item.status));
+ const failureReasons = [...new Set(failures.flatMap(item => item.warnings || []))];
+ pageCaptureBatch = remainingIds.size ? normalizePageCaptureBatch({
+ ...saveBatch, status: "preview", error: failureReasons.join(";"),
+ candidates: saveBatch.candidates.filter(candidate => remainingIds.has(candidate.id)),
+ selections: saveBatch.selections.filter(selection => remainingIds.has(selection.candidateId))
+ }) : null;
pageCaptureEditHistory = [];
pageCaptureOriginalCandidates = new Map();
- showFeedback(cleanupErrors.length ? `${response.message};${cleanupErrors.join(";")}` : response.message, Boolean(cleanupErrors.length));
- await refresh();
+ if (!remainingIds.size) {
+ pageCaptureDraftIds = new Set();
+ await clearPageCaptureMarkers(saveBatch.tabId);
+ } else elements.pageCaptureMediaReview.open = true;
+ const notice = incomplete.length ? t("{message};部分媒体未完整保存,请在案例库检查", { message: response.message }) : response.message;
+ const message = [notice, ...failureReasons, ...cleanupErrors].filter(Boolean).join(";");
+ showFeedback(message, Boolean(remainingIds.size || cleanupErrors.length));
+ try { await refresh(); }
+ catch (error) { showFeedback(`${message};${error.message}`, true); render(); }
} catch (error) {
pageCaptureBatch = normalizePageCaptureBatch({ ...reviewBatch, status: "preview", error: error.message });
showFeedback(error.message || t("网页内容保存失败"), true);
diff --git a/composer-page.js b/composer-page.js
index a0137fb..e1b0a33 100644
--- a/composer-page.js
+++ b/composer-page.js
@@ -886,10 +886,7 @@ function createWelcome() {
image.alt = "";
body.append(
image,
- rawTextEl("h1", "", currentLocale() === "en" ? "What do you want to create?" : "你想创作什么画面?"),
- rawTextEl("p", "", currentLocale() === "en"
- ? "Start with the default method, or add creative Skills and selected references when useful."
- : "可以直接使用默认创作方法,也可以按需应用创作 Skill 或加入私人案例。")
+ rawTextEl("h1", "", currentLocale() === "en" ? "What do you want to create?" : "你想创作什么画面?")
);
const suggestions = el("div", "composer-welcome-suggestions");
const values = composerSession.targetType === "video"
diff --git a/composer.html b/composer.html
index 5f1d529..c7a4611 100644
--- a/composer.html
+++ b/composer.html
@@ -24,9 +24,6 @@
<div class="composer-nav-heading"><strong id="drafts-heading" data-i18n="最近对话">最近对话</strong></div>
<div id="composer-session-list" class="composer-session-list"></div>
</nav>
- <div class="composer-nav-footer">
- <p data-i18n="草稿与案例只保存在本机。">草稿与案例只保存在本机。</p>
- </div>
</aside>
<main class="composer-chat">
diff --git a/design-qa.md b/design-qa.md
index 5aabf01..a9aa79a 100644
--- a/design-qa.md
+++ b/design-qa.md
@@ -1,5 +1,21 @@
# PromptDirector UX visual QA
+## 当前设计与验收原则
+
+以下原则依据用户已确认的设计反馈维护;后文按历史任务保存的尺寸、布局和通过结论只适用于各自范围,不作为当前所有页面的统一模板。
+
+- **先保留构图,再做减法。** 以已认可页面为基线,保留品牌、字体、图标和有层级价值的英文装饰标题。精简重复文案时,同时保留原有居中容器、分栏比例和视觉重心。
+- **组内紧邻,整页均衡。** 名称、状态和对应操作组成完整功能组;根据内容使用均衡分栏或就地排列。同级按钮尺寸与对齐一致,避免对象与操作被大片空白隔开,也避免全部控件堆在左侧。
+- **区分控件与正文。** 短按钮文字保持单行;空间不足时调整整组布局。用户正文、名称和标签保持完整可读,不靠缩小字体或截断内容制造简洁。图标、状态徽标文字和相邻按钮分别检查垂直中心。
+- **按熟悉程度使用图标。** 复制、编辑、保存、刷新等使用现有图标、明确提示、无障碍名称和键盘操作;陌生功能保留简短文字。当前主要任务突出一个主动作,辅助操作保持轻量。
+- **减少说明,保留判断依据。** 删除重复标题、无内容提示框和常驻的显然说明;帮助与诊断按需展开。权限、付费、公开发送、失败与不可逆后果在相关操作触发处明确展示。
+- **高频操作直接可达。** 人工标签输入与确认直接可见;来源不同的采集动作清楚区分。补充内容、取消和重试围绕同一草稿继续,保留用户已选内容和编辑。
+- **先确认效果,再实施。** 展示同一基准的当前版与优化版,覆盖受影响页面的桌面、窄屏、明暗主题、中英文、长名称及适用任务状态。整批已确认的页面按稿实施,局部反馈只调整相关区域;改变方案时再确认。
+- **视觉与行为分别验证。** 无溢出不等于排版合格;对照最终实现实屏,检查视觉重心、按钮一致性、徽标居中和阅读路径。再验证原候选、提交参数、错误反馈,以及切换、关闭、取消后的草稿、选择和阅读位置;页面重载另列测试与结论。
+- **边界与证据可追溯。** 实施前列明可改与保留区域,限定样式影响范围。前端整理沿用原业务流程,资料连续性遵循[数据兼容说明](docs/DATA_COMPATIBILITY.md)。原型、源码验证、隔离安装、日用安装及最终发布包分别记录,截图关联实际源码状态;后续修改使相关截图失效时重新核验。
+
+## 历史验收记录
+
## Evidence
- Source visual truth:
diff --git a/docs/CAPTURE_SUPPORT.md b/docs/CAPTURE_SUPPORT.md
new file mode 100644
index 0000000..e141e05
--- /dev/null
+++ b/docs/CAPTURE_SUPPORT.md
@@ -0,0 +1,32 @@
+# 网页采集
+
+在想保存的作品、帖子或文章中打开扩展,点击网页采集,检查正文和媒体后保存。选区、选图、剪贴板和截图可以继续补充当前草稿。采集、保存、补采均不调用 AI;手动分析是另一个独立操作。
+
+文章保留文字与媒体顺序;作品说明不自动充当原始提示词。来源明确提供的逐张提示词与相应素材一起保存。视频封面只用于预览,不能代表视频已经保存或可以播放。
+
+## 当前路径
+
+| 平台 | 提取和播放路径 |
+|---|---|
+| X | 当前帖正文、媒体和可选引用组;未取得直链的视频,在本次主动采集期间刷新当前帖一次,读取该帖正常加载的媒体响应。优先保存完整 MP4,保留独立播放地址;不会嵌入整条帖子。 |
+| 即梦、Higgsfield、LiblibAI、LibTV、Krea | 专门的当前作品或公开内容提取,结合页面媒体与明确的原始提示词。Krea 区分成品与风格参考;LibTV 保留可读取的节点素材,不恢复可运行工程。 |
+| ArtStation、Pinterest、Behance | 作品结构与页面媒体结合提取;ArtStation 的可访问官方视频子页面可读取实际视频文件。Pinterest 的已解析图片使用原件候选。 |
+| Reddit、微博、小红书 | 当前页面的帖子、正文、图片和可读媒体。登录弹层、折叠评论、不可读的播放器或未加载轮播仍可能需要在原页面处理后补采。 |
+| YouTube、Bilibili、TikTok、抖音 | 可读的媒体文件优先保存;来源支持时使用官方独立播放器。Bilibili 保留当前分 P;TikTok 使用视频播放器地址。 |
+| 花瓣、Dribbble、DeviantArt、站酷 | 当前作品页面的可见内容及页面提供的结构化媒体。 |
+| TapNow、Lovart、Midjourney、Civitai、Runway、可灵 | 通用可见内容与结构化图片/视频提取。是否提供提示词、原图、可访问节点或完整视频,取决于当前作品页面;没有提供的内容不会推断生成。 |
+
+平台名称表示适用路径,不表示该站全部页面已通过真实账号验收。通用提取仍适用于其他网页;不要将首页推荐流误当作已经打开的单个作品。
+
+## 视频与保存结果
+
+- 能取得有效完整视频文件时保存本地;独立在线播放保留原作品地址与单独的播放地址。分段 HLS 使用随扩展打包的开源播放器,音视频在浏览器内处理,不使用外部解析服务。
+- 在线视频仍依赖来源可用性。登录失效、链接过期、限流或禁止播放时会显示问题,可回到原作品重新采集;不会用封面或网页嵌套冒充视频播放。
+- 案例已保存但部分媒体未完整取得时,已保存内容从采集侧栏清除,具体媒体问题保留在案例的来源信息中。真正保存失败的内容留在草稿中。
+- 日常使用不需要卸载扩展或重建案例库。本地版在原目录更新程序,既有案例与媒体继续留在当前浏览器。
+
+## 验证范围
+
+自动回归使用隔离浏览器与明确的合成页面,覆盖保存和重开、文章路由、逐素材提示词、原件字节、独立视频音画与拖动、播放器回收、失败与补采。合成测试不能替代真实账号验收。
+
+当前真实账号验收存在限制:小红书样本打开时要求登录;本次自动化工具不能操作用户日常扩展页面。因此新版本的真实 X 视频、受登录限制的页面和各平台全部页面形态尚未取得完整安装版验收证据。
diff --git a/hls-runtime.js b/hls-runtime.js
new file mode 100644
index 0000000..47dac85
--- /dev/null
+++ b/hls-runtime.js
@@ -0,0 +1,4 @@
+!function e(t){var r,i;r=this,i=function(){"use strict";function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function i(e,t,r,i,n,a,s){try{var o=e[a](s),l=o.value}catch(e){return void r(e)}o.done?t(l):Promise.resolve(l).then(i,n)}function n(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,y(i.key),i)}}function a(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function s(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(i)return(i=i.call(e)).next.bind(i);if(Array.isArray(e)||(i=function(e,t){if(e){if("string"==typeof e)return r(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?r(e,t):void 0}}(e))||t){i&&(e=i);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function o(e,t,r){return(t=y(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function l(){return l=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)({}).hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},l.apply(null,arguments)}function u(e){return u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},u(e)}function d(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,p(e,t)}function h(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(h=function(){return!!e})()}function f(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function c(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?f(Object(r),!0).forEach((function(t){o(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):f(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function g(e,t){if(null==e)return{};var r={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;r[i]=e[i]}return r}function v(){
+/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
+var e,t,r="function"==typeof Symbol?Symbol:{},i=r.iterator||"@@iterator",n=r.toStringTag||"@@toStringTag";function a(r,i,n,a){var l=i&&i.prototype instanceof o?i:o,u=Object.create(l.prototype);return m(u,"_invoke",function(r,i,n){var a,o,l,u=0,d=n||[],h=!1,f={p:0,n:0,v:e,a:c,f:c.bind(e,4),d:function(t,r){return a=t,o=0,l=e,f.n=r,s}};function c(r,i){for(o=r,l=i,t=0;!h&&u&&!n&&t<d.length;t++){var n,a=d[t],c=f.p,g=a[2];r>3?(n=g===i)&&(l=a[(o=a[4])?5:(o=3,3)],a[4]=a[5]=e):a[0]<=c&&((n=r<2&&c<a[1])?(o=0,f.v=i,f.n=a[1]):c<g&&(n=r<3||a[0]>i||i>g)&&(a[4]=r,a[5]=i,f.n=g,o=0))}if(n||r>1)return s;throw h=!0,i}return function(n,d,g){if(u>1)throw TypeError("Generator is already running");for(h&&1===d&&c(d,g),o=d,l=g;(t=o<2?e:l)||!h;){a||(o?o<3?(o>1&&(f.n=-1),c(o,l)):f.n=l:f.v=l);try{if(u=2,a){if(o||(n="next"),t=a[n]){if(!(t=t.call(a,l)))throw TypeError("iterator result is not an object");if(!t.done)return t;l=t.value,o<2&&(o=0)}else 1===o&&(t=a.return)&&t.call(a),o<2&&(l=TypeError("The iterator does not provide a '"+n+"' method"),o=1);a=e}else if((t=(h=f.n<0)?l:r.call(i,f))!==s)break}catch(t){a=e,o=1,l=t}finally{u=1}}return{value:t,done:h}}}(r,n,a),!0),u}var s={};function o(){}function l(){}function u(){}t=Object.getPrototypeOf;var d=[][i]?t(t([][i]())):(m(t={},i,(function(){return this})),t),h=u.prototype=o.prototype=Object.create(d);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,m(e,n,"GeneratorFunction")),e.prototype=Object.create(h),e}return l.prototype=u,m(h,"constructor",u),m(u,"constructor",l),l.displayName="GeneratorFunction",m(u,n,"GeneratorFunction"),m(h),m(h,n,"Generator"),m(h,i,(function(){return this})),m(h,"toString",(function(){return"[object Generator]"})),(v=function(){return{w:a,m:f}})()}function m(e,t,r,i){var n=Object.defineProperty;try{n({},"",{})}catch(e){n=0}m=function(e,t,r,i){function a(t,r){m(e,t,(function(e){return this._invoke(t,r,e)}))}t?n?n(e,t,{value:r,enumerable:!i,configurable:!i,writable:!i}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},m(e,t,r,i)}function p(e,t){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},p(e,t)}function y(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function E(e){var t="function"==typeof Map?new Map:void 0;return E=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return function(e,t,r){if(h())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var n=new(e.bind.apply(e,i));return r&&p(n,r.prototype),n}(e,arguments,u(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),p(r,e)},E(e)}function T(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}var S="utf-16",A="utf-16be",I="utf-16le",L="utf-8";function R(e,t){if(e<0)return-R(-e,t);var r=Math.pow(10,t);if(Math.abs(e*r%1-.5)<Number.EPSILON){var i=Math.floor(e*r);return(i%2==0?i:i+1)/r}return Math.round(e*r)/r}function b(){try{return crypto.randomUUID()}catch(i){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){var r=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=(r+16*Math.random())%16|0;return r=Math.floor(r/16),("x"==e?t:3&t|8).toString(16)}))}}}function k(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var D,P,_={exports:{}},C=(D||(D=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function n(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function a(e,t,i,a,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new n(i,a||e,s),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function s(e,t){0==--e._eventsCount?e._events=new i:delete e._events[t]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,i,n=[];if(0===this._eventsCount)return n;for(i in e=this._events)t.call(e,i)&&n.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},o.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,a=i.length,s=new Array(a);n<a;n++)s[n]=i[n].fn;return s},o.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},o.prototype.emit=function(e,t,i,n,a,s){var o=r?r+e:e;if(!this._events[o])return!1;var l,u,d=this._events[o],h=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),h){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,n),!0;case 5:return d.fn.call(d.context,t,i,n,a),!0;case 6:return d.fn.call(d.context,t,i,n,a,s),!0}for(u=1,l=new Array(h-1);u<h;u++)l[u-1]=arguments[u];d.fn.apply(d.context,l)}else{var f,c=d.length;for(u=0;u<c;u++)switch(d[u].once&&this.removeListener(e,d[u].fn,void 0,!0),h){case 1:d[u].fn.call(d[u].context);break;case 2:d[u].fn.call(d[u].context,t);break;case 3:d[u].fn.call(d[u].context,t,i);break;case 4:d[u].fn.call(d[u].context,t,i,n);break;default:if(!l)for(f=1,l=new Array(h-1);f<h;f++)l[f-1]=arguments[f];d[u].fn.apply(d[u].context,l)}}return!0},o.prototype.on=function(e,t,r){return a(this,e,t,r,!1)},o.prototype.once=function(e,t,r){return a(this,e,t,r,!0)},o.prototype.removeListener=function(e,t,i,n){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn!==t||n&&!o.once||i&&o.context!==i||s(this,a);else{for(var l=0,u=[],d=o.length;l<d;l++)(o[l].fn!==t||n&&!o[l].once||i&&o[l].context!==i)&&u.push(o[l]);u.length?this._events[a]=1===u.length?u[0]:u:s(this,a)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,e.exports=o}(_)),_.exports),w=k(C),O={exports:{}},M=(P||(P=1,function(e,t){var r,i,n,a,s;r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,s={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var n=s.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=s.normalizePath(n.path),s.buildURLFromParts(n)}var a=s.parseURL(t);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return r.alwaysNormalize?(a.path=s.normalizePath(a.path),s.buildURLFromParts(a)):t;var o=s.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var u={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(u.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var d=o.path,h=d.substring(0,d.lastIndexOf("/")+1)+a.path;u.path=s.normalizePath(h)}else u.path=o.path,a.params||(u.params=o.params,a.query||(u.query=o.query));return null===u.path&&(u.path=r.alwaysNormalize?s.normalizePath(a.path):a.path),s.buildURLFromParts(u)},parseURL:function(e){var t=r.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(n,"");e.length!==(e=e.replace(a,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=s}(O)),O.exports),x=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},F=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=N},N=Number.MAX_SAFE_INTEGER||9007199254740991,B=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}({}),U=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.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",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_APPEND_NO_PROGRESS="bufferAppendNoProgress",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.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",e.UNKNOWN="unknown",e}({}),G=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}({}),K=function(){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}},V="manifest",H="level",Y="audioTrack",j="subtitleTrack",W="media-fragment",q="key",X="steering-manifest",z="server-certificate",Q="interstitial-asset-list",$={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},Z={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},J=function(){function e(e){var t,r,i;this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,(i=ae(t=this,r="stats"))&&(i.enumerable=!0,Object.defineProperty(t,r,i))}var t=e.prototype;return t.setByteRange=function(e,t){var r,i=e.split("@",2);r=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]},t.clearElementaryStreamInfo=function(){var e=this.elementaryStreams;e[Z.AUDIO]=null,e[Z.VIDEO]=null,e[Z.AUDIOVIDEO]=null,this.url=null},a(e,[{key:"baseurl",get:function(){return this.base.url}},{key:"byteRange",get:function(){return null===this._byteRange?[]:this._byteRange}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"elementaryStreams",get:function(){var e;return null===this._streams&&(this._streams=((e={})[Z.AUDIO]=null,e[Z.VIDEO]=null,e[Z.AUDIOVIDEO]=null,e)),this._streams},set:function(e){this._streams=e}},{key:"hasStats",get:function(){return null!==this._stats}},{key:"hasStreams",get:function(){return null!==this._streams}},{key:"stats",get:function(){return null===this._stats&&(this._stats=new K),this._stats},set:function(e){this._stats=e}},{key:"url",get:function(){return!this._url&&this.relurl&&(this._url=M.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}}])}();function ee(e){return"initSegment"!==e.sn}function te(e,t){return e.sn===(null==t?void 0:t.sn)&&e.level===t.level}function re(e,t){return e.sn===(null==t?void 0:t.sn)&&e.level===t.level&&e.cc===t.cc}var ie=function(e){function t(t,r){var i;return(i=e.call(this,r)||this)._decryptdata=null,i._programDateTime=null,i._ref=null,i._bitrate=void 0,i.rawProgramDateTime=null,i.tagList=[],i.duration=0,i.sn=0,i.levelkeys=void 0,i.type=void 0,i.loader=null,i.keyLoader=null,i.level=-1,i.cc=0,i.startPTS=void 0,i.endPTS=void 0,i.startDTS=void 0,i.endDTS=void 0,i.start=0,i.playlistOffset=0,i.deltaPTS=void 0,i.maxStartPTS=void 0,i.minEndPTS=void 0,i.data=void 0,i.bitrateTest=!1,i.title=null,i.initSegment=null,i.endList=void 0,i.gap=void 0,i.urlId=0,i.type=t,i}d(t,e);var r=t.prototype;return r.addStart=function(e){this.setStart(this.start+e)},r.setStart=function(e){this.start=e,this._ref&&(this._ref.start=e)},r.setDuration=function(e){this.duration=e,this._ref&&(this._ref.duration=e)},r.setKeyFormat=function(e){var t=this.levelkeys;if(t){var r,i=t[e];!i||null!=(r=this._decryptdata)&&r.keyId||(this._decryptdata=i.getDecryptData(this.sn,t))}},r.abortRequests=function(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()},r.setElementaryStreamInfo=function(e,t,r,i,n,a){void 0===a&&(a=!1);var s=this.elementaryStreams,o=s[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,n)):s[e]={startPTS:t,endPTS:r,startDTS:i,endDTS:n,partial:a}},a(t,[{key:"byteLength",get:function(){if(this.hasStats){var e=this.stats.total;if(e)return e}if(this.byteRange.length){var t=this.byteRange[0],r=this.byteRange[1];if(x(t)&&x(r))return r-t}return null}},{key:"bitrate",get:function(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null},set:function(e){this._bitrate=e}},{key:"decryptdata",get:function(){var e,t=this.levelkeys;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(null==(e=this._decryptdata)||!e.keyId){var r=Object.keys(t);if(1===r.length){var i=this._decryptdata=t[r[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;var e=x(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t,r=Object.keys(this.levelkeys),i=r.length;if(i>1||1===i&&null!=(t=this.levelkeys[r[0]])&&t.encrypted)return!0}return!1}},{key:"programDateTime",get:function(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime},set:function(e){x(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}},{key:"ref",get:function(){return ee(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}}])}(J),ne=function(e){function t(t,r,i,n,a){var s;(s=e.call(this,i)||this).fragOffset=0,s.duration=0,s.independent=!1,s.relurl=void 0,s.fragment=void 0,s.index=void 0,s.gap=!1,s.duration=t.decimalFloatingPoint("DURATION"),s.gap=t.bool("GAP"),s.independent=t.bool("INDEPENDENT"),s.relurl=t.enumeratedString("URI"),s.fragment=r,s.index=n;var o=t.enumeratedString("BYTERANGE");return o&&s.setByteRange(o,a),a&&(s.fragOffset=a.fragOffset+a.duration),s}return d(t,e),a(t,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var e=this.elementaryStreams;return!!(e.audio||e.video||e.audiovideo||this.fragment.type===$.SUBTITLE&&this.stats.loading.end>0)}}])}(J);function ae(e,t){var r=Object.getPrototypeOf(e);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i||ae(r,t)}}function se(e){switch(e.details){case U.FRAG_LOAD_TIMEOUT:case U.KEY_LOAD_TIMEOUT:case U.LEVEL_LOAD_TIMEOUT:case U.MANIFEST_LOAD_TIMEOUT:case U.AUDIO_TRACK_LOAD_TIMEOUT:case U.SUBTITLE_TRACK_LOAD_TIMEOUT:case U.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function oe(e){return e.details.startsWith("key")}function le(e){return oe(e)&&!!e.frag&&!e.frag.decryptdata}function ue(e,t){var r=se(t);return e.default[(r?"timeout":"error")+"Retry"]}function de(e,t){var r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function he(e){return c(c({},e),{errorRetry:null,timeoutRetry:null})}function fe(e,t,r,i){if(!e)return!1;var n=null==i?void 0:i.code,a=t<e.maxNumRetry&&(function(e){return ce(e)||!!e&&(e<400||e>499)}(n)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,i,a):a}function ce(e){return 0===e&&!1===navigator.onLine}function ge(e,t){return t>0&&e.loadError>0&&0!==e.loadErrorTime&&self.performance.now()-e.loadErrorTime>t}var ve=function(){function e(e,t,r){void 0===t&&(t=0),void 0===r&&(r=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_=r}var t=e.prototype;return t.sample=function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e},t.getTotalWeight=function(){return this.totalWeight_},t.getEstimate=function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_},e}(),me=function(){function e(e,t,r,i){void 0===i&&(i=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_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new ve(e),this.fast_=new ve(t),this.defaultTTFB_=i,this.ttfb_=new ve(e)}var t=e.prototype;return t.update=function(e,t){var r=this.slow_,i=this.fast_,n=this.ttfb_;r.halfLife!==e&&(this.slow_=new ve(e,r.getEstimate(),r.getTotalWeight())),i.halfLife!==t&&(this.fast_=new ve(t,i.getEstimate(),i.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new ve(e,n.getEstimate(),n.getTotalWeight()))},t.sample=function(e,t){if(!(t<=0)){var r=Math.min(this.minDelayMs_,t/1e5),i=8*t,n=Math.max(e,r)/1e3,a=i/n;this.fast_.sample(n,a),this.slow_.sample(n,a)}},t.sampleTTFB=function(e){var t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))},t.canEstimate=function(){return this.fast_.getTotalWeight()>=this.minWeight_},t.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},t.getEstimateTTFB=function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_},t.destroy=function(){},a(e,[{key:"defaultEstimate",get:function(){return this.defaultEstimate_}}])}(),pe=function(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;var r="["+e+"]:";this.trace=ye,this.debug=t.debug.bind(null,r),this.log=t.log.bind(null,r),this.warn=t.warn.bind(null,r),this.info=t.info.bind(null,r),this.error=t.error.bind(null,r)},ye=function(){},Ee={trace:ye,debug:ye,log:ye,warn:ye,info:ye,error:ye};function Te(){return l({},Ee)}function Se(e,t,r){return t[e]?t[e].bind(t):function(e,t){var r=self.console[e];return r?r.bind(self.console,(t?"["+t+"] ":"")+"["+e+"] >"):ye}(e,r)}var Ae=Te();function Ie(e,t,r){var i=Te();if("object"==typeof console&&!0===e||"object"==typeof e){var n=["debug","log","info","warn","error"];n.forEach((function(t){i[t]=Se(t,e,r)}));try{i.log('Debug logs enabled for "'+t+'" in hls.js version 1.7.2')}catch(e){return Te()}n.forEach((function(t){Ae[t]=Se(t,e)}))}else l(Ae,i);return i}var Le=Ae;function Re(e){if(void 0===e&&(e=!0),"undefined"!=typeof self)return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function be(e,t){var r=Object.keys(e),i=Object.keys(t),n=r.length,a=i.length;return!n||!a||n===a&&!r.some((function(e){return-1===i.indexOf(e)}))}function ke(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&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 De(e,t){var r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3]}function Pe(e,t){return ke(e,t)&&De(e,t+6)+10<=e.length-t}function _e(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&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 Ce(e,t){for(var r=t,i=0;ke(e,t);)i+=10,i+=De(e,t+6),_e(e,t+10)&&(i+=10),t+=i;if(i>0)return e.subarray(r,r+i)}function we(e,t,r){return void 0===t&&(t=0),void 0===r&&(r=1/0),function(e,t,r,i){var n,a=T(n=e)?n:n.buffer,s=1;"BYTES_PER_ELEMENT"in i&&(s=i.BYTES_PER_ELEMENT);var o,l=(o=e)&&T(o.buffer)&&void 0!==o.byteLength&&void 0!==o.byteOffset?e.byteOffset:0,u=(l+e.byteLength)/s,d=(l+t)/s,h=Math.floor(Math.max(0,Math.min(d,u)));return new i(a,h,Math.floor(Math.min(h+Math.max(r,0),u))-h)}(e,t,r,Uint8Array)}function Oe(e,t){void 0===t&&(t=!1);var r=t?e.indexOf(0):e.length,i=function(e,t){var r;void 0===t&&(t={}),r=T(e)?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength);var i=0,n=t.encoding;if(!n){var a=r.getUint8(0),s=r.getUint8(1);239==a&&187==s&&191==r.getUint8(2)?(n=L,i=3):254==a&&255==s?(n=A,i=2):255==a&&254==s?(n=I,i=2):n=L}if("undefined"!=typeof TextDecoder)return new TextDecoder(n).decode(r);for(var o,l=r.byteLength,u=n!==A,d="";i<l;){switch(n){case L:if((o=r.getUint8(i))<128)i++;else if(o>=194&&o<=223)if(i+1<l){var h=r.getUint8(i+1);h>=128&&h<=191?(o=(31&o)<<6|63&h,i+=2):i++}else i++;else if(o>=224&&o<=239)if(i+2<=l-1){var f=r.getUint8(i+1),c=r.getUint8(i+2);f>=128&&f<=191&&c>=128&&c<=191?(o=(15&o)<<12|(63&f)<<6|63&c,i+=3):i++}else i++;else if(o>=240&&o<=244)if(i+3<=l-1){var g=r.getUint8(i+1),v=r.getUint8(i+2),m=r.getUint8(i+3);g>=128&&g<=191&&v>=128&&v<=191&&m>=128&&m<=191?(o=(7&o)<<18|(63&g)<<12|(63&v)<<6|63&m,i+=4):i++}else i++;else i++;break;case A:case S:case I:o=r.getUint16(i,u),i+=2}d+=String.fromCodePoint(o)}return d}(new DataView(e.buffer,e.byteOffset,r),{encoding:L});return t?i:i.replace(/\0/g,"")}function Me(e){var t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(!(e.size<2))if(3===e.data[0]){var r=e.data.subarray(1).indexOf(0);if(-1!==r){var i=Oe(we(e.data,1,r)),n=e.data[2+r],a=e.data.subarray(3+r).indexOf(0);if(-1!==a){var s,o,l=Oe(we(e.data,3+r,a));return s="--\x3e"===i?Oe(we(e.data,4+r+a)):T(o=e.data.subarray(4+r+a))?o:0==o.byteOffset&&o.byteLength==o.buffer.byteLength?o.buffer:new Uint8Array(o).buffer,t.mimeType=i,t.pictureType=n,t.description=l,t.data=s,t}}}else console.log("Ignore frame with unrecognized character encoding")}function xe(e){return"PRIV"===e.type?function(e){if(!(e.size<2)){var t=Oe(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,r=Oe(e.data.subarray(t),!0);t+=r.length+1;var i=Oe(e.data.subarray(t));return{key:e.type,info:r,data:i}}var n=Oe(e.data);return{key:e.type,info:"",data:n}}(e):"APIC"===e.type?Me(e):function(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,r=e.data,i=Oe(r.subarray(t),!0);t+=i.length+1;var n=Oe(r.subarray(t));return{key:e.type,info:i,data:n}}var a=Oe(e.data.subarray(1));return{key:e.type,info:"",data:a}}}(e)}function Fe(e){var t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=De(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}}var Ne=10,Be=10;function Ue(e){for(var t=0,r=[];ke(e,t);){var i=De(e,t+6);e[t+5]>>6&1&&(t+=Ne);for(var n=(t+=Ne)+i;t+Be<n;){var a=Fe(e.subarray(t)),s=xe(a);s&&r.push(s),t+=a.size+Ne}_e(e,t)&&(t+=Ne)}return r}function Ge(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function Ke(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),r=1&t[3],i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}}function Ve(e){for(var t,r=s(Ue(e));!(t=r()).done;){var i=t.value;if(Ge(i))return Ke(i)}}function He(e){for(var t="",r=0;r<e.length;r++){var i=e[r].toString(16);i.length<2&&(i="0"+i),t+=i}return t}function Ye(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function je(e){return Uint8Array.from(atob(e),(function(e){return e.charCodeAt(0)}))}function We(e){return String.fromCharCode.apply(null,e)}var qe,Xe=Math.pow(2,32)-1,ze={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},Qe={video:1,audio:2,id3:3,text:4};function $e(e,t){var r=e[t]<<8|e[t+1];return r<0?65536+r:r}function Ze(e,t){var r=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];return r<0?4294967296+r:r}function Je(e,t){var r=Ze(e,t);return r*=Math.pow(2,32),r+=Ze(e,t+4)}function et(e,t){for(var r="",i=t;i<e.length;i++)if(r+=String.fromCharCode(e[i]),0===e[i])return r;return null}function tt(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function rt(e,t,r){e[t]=r>>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r}function it(e,t,r){var i=t.byteOffset-e.byteOffset-8,n=8+r,a=t.byteLength+8-n;a<8||(rt(e,i,n),rt(e,i+n,a),rt(e,i+n+4,ze.free))}function nt(e,t){return[e.byteOffset-t-8,e.byteOffset-t+e.byteLength]}function at(e,t){t.sort((function(e,t){return e[0]-t[0]}));for(var r=t.reduce((function(e,t){var r=t[0];return e+t[1]-r}),0),i=new Uint8Array(e.byteLength-r),n=0,a=0,s=0;s<t.length;s++){var o=t[s],l=o[0],u=o[1];i.set(e.subarray(n,l),a),a+=l-n,n=u}return i.set(e.subarray(n),a),{result:i,dropped:r,droppedBefore:function(e){return t.reduce((function(t,r){var i=r[0],n=r[1];return n<=e?t+n-i:t}),0)}}}function st(e,t){var r=[];return t.length?(ot(e,t,0,0,e.byteLength,r),r):r}function ot(e,t,r,i,n,a){var s=t[r];if(4===(null==s?void 0:s.length))for(var o=s.charCodeAt(0),l=s.charCodeAt(1),u=s.charCodeAt(2),d=s.charCodeAt(3),h=t.length-1,f=i;f<n;){var c=f+8<=n,g=f+4<=n?16777216*e[f]+(e[f+1]<<16|e[f+2]<<8|e[f+3]):Ze(e,f),v=g>1?f+g:n;if(c&&e[f+4]===o&&e[f+5]===l&&e[f+6]===u&&e[f+7]===d){var m=Math.min(v,n);r===h?a.push(e.subarray(f+8,m)):ot(e,t,r+1,f+8,m,a)}f=v}}function lt(e){var t=[],r=e[0],i=8,n=Ze(e,i);i+=4;var a=0,s=0;0===r?(a=Ze(e,i),s=Ze(e,i+4),i+=8):(a=Je(e,i),s=Je(e,i+8),i+=16),i+=2;var o=e.length+s,l=$e(e,i);i+=2;for(var u=0;u<l;u++){var d=i,h=Ze(e,d);d+=4;var f=2147483647&h;if(1==(2147483648&h)>>>31)return Le.warn("SIDX has hierarchical references (not supported)"),null;var c=Ze(e,d);d+=4,t.push({referenceSize:f,subsegmentDuration:c,info:{duration:c/n,start:o,end:o+f-1}}),o+=f,i=d+=4}return{earliestPresentationTime:a,timescale:n,version:r,referencesCount:l,references:t}}function ut(e){for(var t=[],r=st(e,["moov","trak"]),i=0;i<r.length;i++){var n=r[i],a=st(n,["tkhd"])[0];if(a){var s=a[0],o=Ze(a,0===s?12:20),l=st(n,["mdia","mdhd"])[0];if(l){var u=Ze(l,0===(s=l[0])?12:20),d=st(n,["mdia","hdlr"])[0];if(d){var h=We(d.subarray(8,12)),f={soun:Z.AUDIO,vide:Z.VIDEO}[h],g=dt(st(n,["mdia","minf","stbl","stsd"])[0]);f?(t[o]={timescale:u,type:f,stsd:g},t[f]=c({timescale:u,id:o},g)):t[o]={timescale:u,type:h,stsd:g}}}}}return st(e,["moov","mvex","trex"]).forEach((function(e){var r=Ze(e,4),i=t[r];i&&(i.default={duration:Ze(e,12),sampleSize:Ze(e,16),flags:Ze(e,20)})})),t}function dt(e){var t,r=e.subarray(8),i=r.subarray(86),n=We(r.subarray(4,8)),a=n,s="enca"===n||"encv"===n;if(s){var o=st(r,[n])[0];st(o.subarray("enca"===n?28:78),["sinf"]).forEach((function(e){var t=st(e,["schm"])[0];if(t){var r=We(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var i=st(e,["frma"])[0];i&&(a=We(i))}}}))}var l=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":var u=st(i,["avcC"])[0];u&&u.length>3&&(a+="."+ct(u[1])+ct(u[2])+ct(u[3]),t=ht("avc1"===l?"dva1":"dvav",i));break;case"mp4a":var d=st(r,[n])[0],h=st(d.subarray(28),["esds"])[0];if(h&&h.length>7){var f=4;if(3!==h[f++])break;f=ft(h,f),f+=2;var c=h[f++];if(128&c&&(f+=2),64&c&&(f+=h[f++]),4!==h[f++])break;f=ft(h,f);var g=h[f++];if(64!==g)break;if(a+="."+ct(g),f+=12,5!==h[f++])break;f=ft(h,f);var v=h[f++],m=(248&v)>>3;31===m&&(m+=1+((7&v)<<3)+((224&h[f])>>5)),a+="."+m}break;case"hvc1":case"hev1":var p=st(i,["hvcC"])[0];if(p&&p.length>12){var y=p[1],E=["","A","B","C"][y>>6],T=31&y,S=Ze(p,2),A=(32&y)>>5?"H":"L",I=p[12],L=p.subarray(6,12);a+="."+E+T,a+="."+function(e){for(var t=0,r=0;r<32;r++)t|=(e>>r&1)<<31-r;return t>>>0}(S).toString(16).toUpperCase(),a+="."+A+I;for(var R="",b=L.length;b--;){var k=L[b];(k||R)&&(R="."+k.toString(16).toUpperCase()+R)}a+=R}t=ht("hev1"==l?"dvhe":"dvh1",i);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":a=ht(a,i)||a;break;case"vp09":var D=st(i,["vpcC"])[0];if(D&&D.length>6){var P=D[4],_=D[5],C=D[6]>>4&15;a+="."+gt(P)+"."+gt(_)+"."+gt(C)}break;case"av01":var w=st(i,["av1C"])[0];if(w&&w.length>2){var O=w[1]>>>5,M=31&w[1],x=w[2]>>>7?"H":"M",F=(64&w[2])>>6,N=(32&w[2])>>5,B=2===O&&F?N?12:10:F?10:8,U=(16&w[2])>>4,G=(8&w[2])>>3,K=(4&w[2])>>2,V=3&w[2];a+="."+O+"."+gt(M)+x+"."+gt(B)+"."+U+"."+G+K+V+"."+gt(1)+"."+gt(1)+"."+gt(1)+".0",t=ht("dav1",i)}}return{codec:a,encrypted:s,supplemental:t}}function ht(e,t){var r=st(t,["dvvC"]),i=r.length?r[0]:st(t,["dvcC"])[0];if(i){var n=i[2]>>1&127,a=i[2]<<5&32|i[3]>>3&31;return e+"."+gt(n)+"."+gt(a)}}function ft(e,t){for(var r=t+5;128&e[t++]&&t<r;);return t}function ct(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function gt(e){return(e<10?"0":"")+e}function vt(e,t){st(e,["moov","trak"]).forEach((function(e){var r=st(e,["mdia","minf","stbl","stsd"])[0];if(r){var i=r.subarray(8),n=st(i,["enca"]),a=n.length>0;a||(n=st(i,["encv"])),n.forEach((function(e){st(a?e.subarray(28):e.subarray(78),["sinf"]).forEach((function(e){var r=mt(e);r&&t(r,a)}))}))}}))}function mt(e){var t=st(e,["schm"])[0];if(t){var r=We(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var i=st(e,["schi","tenc"])[0];if(i)return i}}}function pt(e){return"undefined"==typeof TextDecoder?Oe(e):(qe||(qe=new TextDecoder("utf-8"))).decode(e).replace(/\0/g,"")}function yt(e,t,r,i,n){for(var a={},s=!1,o=function(e){for(var t=e.byteLength,r=[],i=0;i<t;){var n=i+8<=t,a=i+4<=t?16777216*e[i]+(e[i+1]<<16|e[i+2]<<8|e[i+3]):Ze(e,i),s=a>1?i+a:t;if(n&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])for(var o=Math.min(s,t),l=i+8;l<o;){var u=l+8<=o,d=l+4<=o?16777216*e[l]+(e[l+1]<<16|e[l+2]<<8|e[l+3]):Ze(e,l),h=d>1?l+d:o;if(u&&116===e[l+4]&&114===e[l+5]&&97===e[l+6]&&102===e[l+7]){for(var f=Math.min(h,o),c=void 0,g=void 0,v=[],m=l+8;m<f;){var p=m+8<=f,y=m+4<=f?16777216*e[m]+(e[m+1]<<16|e[m+2]<<8|e[m+3]):Ze(e,m),E=y>1?m+y:f;if(p&&116===e[m+4]){var T=Math.min(E,f);102===e[m+5]&&104===e[m+6]&&100===e[m+7]?g||(g=e.subarray(m+8,T)):102===e[m+5]&&100===e[m+6]&&116===e[m+7]?c||(c=e.subarray(m+8,T)):114===e[m+5]&&117===e[m+6]&&110===e[m+7]&&v.push(e.subarray(m+8,T))}m=E}r.push({moofOffset:e.byteOffset+i,tfdt:c,tfhd:g,truns:v})}l=h}i=s}return r}(e),l=e.byteLength,u=0;u<o.length;u++){var d=o[u],h=d.moofOffset,f=d.tfdt,c=d.tfhd,g=d.truns,v=Ze(c,4),m=t[v];if(m){var p=a[v]||(a[v]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:m.timescale,type:m.type}),y=void 0;if(f){var E=f[0];y=Ze(f,4),1===E&&(y===Xe?r.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(y*=Xe+1,y+=Ze(f,8))),x(y)&&(!x(p.start)||y<p.start)&&(p.start=y),n&&x(y)&&(n.timeOffset=y/n.timescale)}var T=(null==n?void 0:n.trackId)===v&&m.type===Z.VIDEO,S=m.default,A=16777215&Ze(c,0),I=(null==S?void 0:S.duration)||0,L=void 0,R=(null==S?void 0:S.sampleSize)||0,b=8;1&A&&(b+=8),2&A&&(b+=4),8&A&&(I=Ze(c,b),L=c.byteOffset-e.byteOffset+b,b+=4),16&A&&(R=Ze(c,b));var k=0,D=0!=(1&A),P=!D&&0!=(131072&A);D?(k=Ze(c,8),k*=Math.pow(2,32),k+=Ze(c,12)):P&&(k=h);for(var _=y||0,C=0,w=I,O=0;O<g.length;O++){var M=g[O],F=Ze(M,4),N=p.sampleCount;p.sampleCount+=F;var B=1&M[3],U=0,G=4&M[3],K=1&M[2],V=2&M[2],H=4&M[2],Y=8&M[2],j=8;B&&(U=tt(M,j),j+=4),G&&(1&M[j+1]||void 0!==p.keyFrameIndex||(p.keyFrameIndex=N),j+=4);var W=k+U;if(i||0!==M[1]||6!==M[2]||1!==M[3]){var q=void 0,X=void 0;i&&(X={sampleOffset:W,samples:q=[],defaultSampleDurationOffset:L},W<=l&&p.trun.push(X));for(var z=void 0,Q=0;Q<F;Q++){var $=void 0;K?(i&&($=M.byteOffset-e.byteOffset+j),w=Ze(M,j),j+=4):w=I,V?(z=Ze(M,j),j+=4):z=R;var J=void 0,ee=void 0;H&&(ee=1&M[j+1]?1:0,i&&(J={isNonSync:ee,dependsOn:1==(3&M[j])?1:2}),j+=4);var te=0;if(Y&&(te=0===M[0]?Ze(M,j):tt(M,j),j+=4),T){for(var re=W,ie=0;ie<z;){var ne=Ze(e,re);re+=4,St(n.isHEVCFlavor,e[re])&&At(e.subarray(re,re+ne),n.isHEVCFlavor?2:1,n.timeOffset+te/n.timescale,n.samples),re+=ne,ie+=ne+4}n.timeOffset+=w/n.timescale}if((W+=z)<=l){X&&void 0!==$&&(X.lastSampleDurationOffset=$),0===ee&&void 0===p.keyFrameIndex&&(p.keyFrameIndex=Q,p.keyFrameStart=_);var ae=_+te;(!x(p.ptsMin)||ae<p.ptsMin)&&(p.ptsMin=ae),(!x(p.ptsMax)||ae+w>p.ptsMax)&&(p.ptsMax=ae+w),q&&(q[Q]={cts:te,duration:w,flags:J,size:z})}_+=w,C+=w}!C&&I&&(C+=I*F)}else{for(var se,oe,le=_,ue=W,de=j,he=-1,fe=0,ce=0,ge=null!=(se=null==n?void 0:n.timeOffset)?se:0,ve=I/(null!=(oe=null==n?void 0:n.timescale)?oe:1),me=!0===(null==n?void 0:n.isHEVCFlavor),pe=me?2:1,ye=0;ye<F;ye++){var Ee=0===M[j]?M[j+1]<<16|M[j+2]<<8|M[j+3]:Ze(M,j),Te=-1===he&&void 0===p.keyFrameIndex&&0==(1&M[j+5]);j+=8;var Se=W+Ee;if(T){if(Ee>0){var Ae=W;do{var Ie=0===e[Ae]?e[Ae+1]<<16|e[Ae+2]<<8|e[Ae+3]:Ze(e,Ae),Le=e[Ae+=4],Re=me?Le>>1&63:31&Le;(me?39===Re||40===Re:6===Re)&&At(e.subarray(Ae,Ae+Ie),pe,ge,n.samples),Ae+=Ie}while(Ae<Se)}ge+=ve}W=Se,Te&&(he=ye,fe=W)}if(W<=l)ce=F;else for(var be=ue,ke=de,De=0;De<F&&!((be+=0===M[ke]?M[ke+1]<<16|M[ke+2]<<8|M[ke+3]:Ze(M,ke))>l);De++)ce=De+1,ke+=8;if(T&&(n.timeOffset=ge),-1!==he&&fe<=l&&void 0===p.keyFrameIndex&&(p.keyFrameIndex=he,p.keyFrameStart=le+he*I),ce){(!x(p.ptsMin)||le<p.ptsMin)&&(p.ptsMin=le);var Pe=le+ce*I;(!x(p.ptsMax)||Pe>p.ptsMax)&&(p.ptsMax=Pe)}var _e=I*F;_=le+_e,C+=_e}}p.duration+=C,p.duration&&(s=!0)}}if(!s){for(var Ce=1/0,we=0,Oe=st(e,["sidx"]),Me=0;Me<Oe.length;Me++){var xe=lt(Oe[Me]);if(null!=xe&&xe.references){Ce=Math.min(Ce,xe.earliestPresentationTime/xe.timescale);var Fe=xe.references.reduce((function(e,t){return e+t.info.duration||0}),0);we=Math.max(we,Fe+xe.earliestPresentationTime/xe.timescale)}}we&&x(we)&&Object.keys(a).forEach((function(e){a[e].duration||(a[e].duration=we*a[e].timescale-a[e].start)}))}return a}function Et(e,t){var r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function Tt(e){if(!e)return!1;var t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function St(e,t){if(e){var r=t>>1&63;return 39===r||40===r}return 6==(31&t)}function At(e,t,r,i){var n=It(e),a=0;a+=t;for(var s=0,o=0,l=0;a<n.length;){s=0;do{if(a>=n.length)break;s+=l=n[a++]}while(255===l);o=0;do{if(a>=n.length)break;o+=l=n[a++]}while(255===l);var u=n.length-a,d=a;if(o<u)a+=o;else if(o>u){Le.error("Malformed SEI payload. "+o+" is too small, only "+u+" bytes left to parse.");break}if(4===s){if(181===n[d++]){var h=$e(n,d);if(d+=2,49===h){var f=Ze(n,d);if(d+=4,1195456820===f){var c=n[d++];if(3===c){var g=n[d++],v=64&g,m=v?2+3*(31&g):0,p=new Uint8Array(m);if(v){p[0]=g;for(var y=1;y<m;y++)p[y]=n[d++]}i.push({type:c,payloadType:s,pts:r,bytes:p})}}}}}else if(5===s&&o>16){for(var E=[],T=0;T<16;T++){var S=n[d++].toString(16);E.push(1==S.length?"0"+S:S),3!==T&&5!==T&&7!==T&&9!==T||E.push("-")}for(var A=o-16,I=new Uint8Array(A),L=0;L<A;L++)I[L]=n[d++];i.push({payloadType:s,pts:r,uuid:E.join(""),userData:pt(I),userDataBytes:I})}}}function It(e){for(var t,r=e.byteLength,i=e.indexOf(3,3);-1!==i;)0===e[i-1]&&0===e[i-2]&&(t||(t=[])).push(i),i=e.indexOf(3,i+1);if(!t)return e;for(var n=r-t.length,a=new Uint8Array(n),s=0,o=0,l=0;l<n;o++,l++)o===t[s]&&(o++,s++),a[l]=e[o];return a}function Lt(e,t,r){if(16!==e.byteLength)throw new RangeError("Invalid system id");var i,n;i=new Uint8Array,n=new Uint8Array;var a=new Uint8Array(4);return r.byteLength>0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];for(var n=r.length,a=8,s=n;s--;)a+=r[s].byteLength;var o=new Uint8Array(a);for(o[0]=a>>24&255,o[1]=a>>16&255,o[2]=a>>8&255,o[3]=255&a,o.set(e,4),s=0,a=8;s<n;s++)o.set(r[s],a),a+=r[s].byteLength;return o}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,i,a,r)}function Rt(e){var t=[];if(e instanceof ArrayBuffer)for(var r=e.byteLength,i=0;i+32<r;){var n=bt(new DataView(e,i));t.push(n),i+=n.size}return t}function bt(e){var t=e.getUint32(0),r=e.byteOffset,i=e.byteLength;if(i<t)return{offset:r,size:i};if(1886614376!==e.getUint32(4))return{offset:r,size:t};var n=e.getUint32(8)>>>24;if(0!==n&&1!==n)return{offset:r,size:t};var a,s=e.buffer,o=He(new Uint8Array(s,r+12,16)),l=null,u=0;if(0===n)u=28;else{var d=e.getUint32(28);if(!d||i<32+16*d)return{offset:r,size:t};l=[];for(var h=0;h<d;h++)l.push(new Uint8Array(s,r+32+16*h,16));u=32+16*d}if(!u)return{offset:r,size:t};var f=e.getUint32(u);return t-32<f?{offset:r,size:t}:(a=new Uint8Array(s,r+u+4,f),0===n&&(l=function(e){for(var t=[],r=0;r<e.length;){var i=e[r++],n=7&i;if(0!==n)if(2===n){for(var a=0,s=0,o=128;128&o;s+=7)a|=(127&(o=e[r++]))<<s;if(i>>3==2)if(32===a){for(var l=new Uint8Array(16),u=0;u<16;u++)l[u]=parseInt(String.fromCharCode(e[r+2*u],e[r+2*u+1]),16);t.push(l)}else 16===a&&t.push(e.subarray(r,r+16));r+=a}else r+=1===n?8:4;else for(;128&e[r++];);}return t}(a)),{version:n,systemId:o,kids:l,data:a,offset:r,size:t})}var kt,Dt,Pt,_t=wt("userAgent"),Ct=wt("vendor");function wt(e){try{return navigator[e]||""}catch(e){}return""}function Ot(){if(void 0===kt){var e=_t.match(/Chrome\/(\d+)/i);kt=e?parseInt(e[1]):0}return kt}function Mt(){return/\(Windows.+Firefox\//i.test(_t)}var xt={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},image:{mjpg:1}};function Ft(e,t){var r=xt[t];return!!r&&!!r[e.slice(0,4)]}function Nt(e,t,r){return void 0===r&&(r=!0),!e.split(",").some((function(e){return!Bt(e,t,r)}))}function Bt(e,t,r){var i;void 0===r&&(r=!0);var n=Re(r);return null!=(i=null==n?void 0:n.isTypeSupported(Ut(e,t)))&&i}function Ut(e,t){return t+"/mp4;codecs="+e}function Gt(e){if(e){var t=e.substring(0,4);return xt.video[t]}return 2}function Kt(e){var t=Mt();return e.split(",").reduce((function(e,r){var i=t&&Tt(r)?9:xt.video[r];return i?(2*i+e)/(e?3:2):(xt.audio[r]+e)/(e?2:1)}),0)}var Vt={},Ht=/flac|opus|mp4a\.40\.34/i;function Yt(e,t){return void 0===t&&(t=!0),e.replace(Ht,(function(e){return function(e,t){if(void 0===t&&(t=!0),Vt[e])return Vt[e];for(var r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],i=0;i<r.length;i++){var n;if(Bt(r[i],"audio",t))return Vt[e]=r[i],r[i];if("mp3"===r[i]&&null!=(n=Re(t))&&n.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t)}))}function jt(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(Wt(e,"audio")||Wt(e,"video")))return e;if(t){var r=t.split(",");if(r.length>1){if(e)for(var i=r.length;i--;)if(r[i].substring(0,4)===e.substring(0,4))return r[i];return r[0]}}return t||e}function Wt(e,t){return Ft(e,t)&&Bt(e,t)}function qt(e){if(e.startsWith("av01.")){for(var t=e.split("."),r=["0","111","01","01","01","0"],i=t.length;i>4&&i<10;i++)t[i]=r[i-4];return t.join(".")}return e}function Xt(e){var t=Re(e)||{isTypeSupported:function(){return!1}};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function zt(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var Qt={supported:!1,smooth:!1,powerEfficient:!1},$t={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Zt(e,t){return{supported:!1,configurations:t,decodingInfoResults:[Qt],error:e}}function Jt(e,t,r,i){void 0===i&&(i={});var n=e.videoCodec;if(!n&&!e.audioCodec||!r)return Promise.resolve($t);for(var a=[],s=function(e){var t,r=null==(t=e.videoCodec)?void 0:t.split(","),i=tr(e),n=e.width||640,a=e.height||480,s=e.frameRate||30,o=e.videoRange.toLowerCase();return r?r.map((function(e){var t={contentType:Ut(qt(e),"video"),width:n,height:a,bitrate:i,framerate:s};return"sdr"!==o&&(t.transferFunction=o),t})):[]}(e),o=s.length,l=function(e,t,r){var i,n=null==(i=e.audioCodec)?void 0:i.split(","),a=tr(e);return n&&e.audioGroups?e.audioGroups.reduce((function(e,i){var s,o=i?null==(s=t.groups[i])?void 0:s.tracks:null;return o?o.reduce((function(e,t){if(t.groupId===i){var s=parseFloat(t.channels||"");n.forEach((function(t){var i={contentType:Ut(t,"audio"),bitrate:r?er(t,a):a};s&&(i.channels=""+s),e.push(i)}))}return e}),e):e}),[]):[]}(e,t,o>0),u=l.length,d=o||1*u||1;d--;){var h={type:"media-source"};if(o&&(h.video=s[d%o]),u){h.audio=l[d%u];var f=h.audio.bitrate;h.video&&f&&(h.video.bitrate-=f)}a.push(h)}if(n){var c=navigator.userAgent;if(n.split(",").some((function(e){return Tt(e)}))&&Mt())return Promise.resolve(Zt(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: ("+c+")"),a))}return Promise.all(a.map((function(e){var t,n,a,s,o=(n="",a=(t=e).audio,(s=t.video)&&(n+=zt(s.contentType)+"_r"+s.height+"x"+s.width+"f"+Math.ceil(s.framerate)+(s.transferFunction||"sd")+"_"+Math.ceil(s.bitrate/1e5)),a&&(n+=(s?"_":"")+zt(a.contentType)+"_c"+a.channels),n);return i[o]||(i[o]=r.decodingInfo(e))}))).then((function(e){return{supported:!e.some((function(e){return!e.supported})),configurations:a,decodingInfoResults:e}})).catch((function(e){return{supported:!1,configurations:a,decodingInfoResults:[],error:e}}))}function er(e,t){if(t<=1)return 1;var r=128e3;return"ec-3"===e?r=768e3:"ac-3"===e&&(r=64e4),Math.min(t/2,r)}function tr(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}function rr(e,t,r){var i=encodeURIComponent(t),n=i+"="+encodeURIComponent(r),a=!1,s=[];e.search.substring(1).split("&").forEach((function(e){e===i||e.startsWith(i+"=")?a||(s.push(n),a=!0):e&&s.push(e)})),a||s.push(n),e.search=s.join("&")}var ir=["NONE","TYPE-0","TYPE-1",null],nr=["SDR","PQ","HLG"],ar="",sr="YES",or="v2";function lr(e){var t=e.canSkipUntil,r=e.canSkipDateRanges,i=e.age;return t&&i<t/2?r?or:sr:ar}var ur=function(){function e(e,t,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=r}return e.prototype.addDirectives=function(e){var t=new self.URL(e);return void 0!==this.msn&&rr(t,"_HLS_msn",this.msn.toString()),void 0!==this.part&&rr(t,"_HLS_part",this.part.toString()),this.skip&&rr(t,"_HLS_skip",this.skip),t.href},e}(),dr=function(){function e(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.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=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,"imageCodec"in e&&(this.imageCodec=e.imageCodec),this.codecSet=[e.videoCodec,e.audioCodec].filter((function(e){return!!e})).map((function(e){return e.substring(0,4)})).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;var r=null==(t=e.supplemental)?void 0:t.videoCodec;r&&r!==e.videoCodec&&(this.codecSet+=","+r.substring(0,4))}"iframes"in e&&e.iframes?this.iframes=!0:(this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES))}var t=e.prototype;return t.hasAudioGroup=function(e){return hr(this._audioGroups,e)},t.hasSubtitleGroup=function(e){return hr(this._subtitleGroups,e)},t.addGroupId=function(e,t){if(t)if("audio"===e){var r=this._audioGroups;r||(r=this._audioGroups=[]),-1===r.indexOf(t)&&r.push(t)}else if("text"===e){var i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),-1===i.indexOf(t)&&i.push(t)}},t.addFallback=function(){},a(e,[{key:"maxBitrate",get:function(){return Math.max(this.realBitrate,this.bitrate)}},{key:"averageBitrate",get:function(){return this._avgBitrate||this.realBitrate||this.bitrate}},{key:"attrs",get:function(){return this._attrs[0]}},{key:"codecs",get:function(){return this.attrs.CODECS||""}},{key:"pathwayId",get:function(){return this.attrs["PATHWAY-ID"]||"."}},{key:"videoRange",get:function(){return this.attrs["VIDEO-RANGE"]||"SDR"}},{key:"score",get:function(){return this.attrs.optionalFloat("SCORE",0)}},{key:"uri",get:function(){return this.url[0]||""}},{key:"audioGroups",get:function(){return this._audioGroups}},{key:"subtitleGroups",get:function(){return this._subtitleGroups}},{key:"urlId",get:function(){return 0},set:function(e){}},{key:"audioGroupIds",get:function(){return this.audioGroups?[this.audioGroupId]:void 0}},{key:"textGroupIds",get:function(){return this.subtitleGroups?[this.textGroupId]:void 0}},{key:"audioGroupId",get:function(){var e;return null==(e=this.audioGroups)?void 0:e[0]}},{key:"textGroupId",get:function(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}}])}();function hr(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function fr(e,t){var r=!1,i=[];if(e&&(r="SDR"!==e,i=[e]),t){var n="SDR"!==(i=t.allowedVideoRanges||nr.slice(0)).join("")&&!t.videoCodec;(r=void 0!==t.preferHDR?t.preferHDR:n&&function(){if("function"==typeof matchMedia){var e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}())||(i=["SDR"])}return{preferHDR:r,allowedVideoRanges:i}}var cr=function(e,t){return JSON.stringify(e,function(e){var t=new WeakSet;return function(r,i){if(e&&(i=e(r,i)),"object"==typeof i&&null!==i){if(t.has(i))return;t.add(i)}return i}}(t))};function gr(e,t){Le.log('[abr] start candidates with "'+e+'" ignored because '+t)}function vr(e){return e.reduce((function(e,t){var r=e.groups[t.groupId];r||(r=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(t);var i=t.channels||"2";return r.channels[i]=(r.channels[i]||0)+1,r.hasDefault=r.hasDefault||t.default,r.hasAutoSelect=r.hasAutoSelect||t.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function mr(e){if(!e)return e;var t=e;return{lang:t.lang,assocLang:t.assocLang,characteristics:t.characteristics,channels:t.channels,audioCodec:t.audioCodec}}function pr(e,t,r){if("attrs"in e){var i=t.indexOf(e);if(-1!==i)return i}for(var n=0;n<t.length;n++)if(yr(e,t[n],r))return n;return-1}function yr(e,t,r){var i,n,a=e.groupId,s=e.name,o=e.lang,l=e.assocLang,u=e.default,d=e.forced;return(void 0===a||t.groupId===a)&&(void 0===s||t.name===s)&&(void 0===o||(i=o,void 0===(n=t.lang)&&(n="--"),i.length===n.length?i===n:i.startsWith(n)||n.startsWith(i)))&&(void 0===o||t.assocLang===l)&&(void 0===u||t.default===u)&&(void 0===d||t.forced===d)&&(!("characteristics"in e)||function(e,t){void 0===t&&(t="");var r=e.split(","),i=t.split(",");return r.length===i.length&&!r.some((function(e){return-1===i.indexOf(e)}))}(e.characteristics||"",t.characteristics))&&(void 0===r||r(e,t))}function Er(e,t){var r=e.audioCodec,i=e.channels;return!(void 0!==r&&(t.audioCodec||"").substring(0,4)!==r.substring(0,4)||void 0!==i&&i!==(t.channels||"2"))}function Tr(e,t,r){for(var i=t;i>-1;i--)if(r(e[i]))return i;for(var n=t+1;n<e.length;n++)if(r(e[n]))return n;return-1}function Sr(e,t){var r;return!!e&&e!==(null==(r=t.loadLevelObj)?void 0:r.uri)}function Ar(e,t){return!t||-1!==t.indexOf(e)}function Ir(e,t){if(t||e){var r=l({},t);return e&&(e.videoCodec&&(r.videoCodec=e.videoCodec),e.videoRange&&(r.allowedVideoRanges=[e.videoRange])),r}}var Lr=function(e){function t(t){var r;return(r=e.call(this,"abr",t.logger)||this).hls=void 0,r.lastLevelLoadSec=0,r.lastLoadedFragLevel=-1,r.firstSelection=-1,r.firstAutoFloor=-1,r._nextAutoLevel=-1,r.nextAutoLevelKey="",r.audioTracksByGroup=null,r.codecTiers=null,r.timer=-1,r.fragCurrent=null,r.partCurrent=null,r.bitrateTestDelay=0,r.rebufferNotice=-1,r.supportedCache={},r.bwEstimator=void 0,r._abandonRulesCheck=function(e){var t,i=r,n=i.fragCurrent,a=i.partCurrent,s=i.hls;if(s){var o=s.autoLevelEnabled,l=s.media;if(n&&l){var u=performance.now(),d=a?a.stats:n.stats,h=a?a.duration:n.duration,f=u-d.loading.start,c=s.minAutoLevel,g=n.level,v=r._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||g<=c)return r.clearTimer(),void(r._nextAutoLevel=-1);if(o){var m=v>-1&&v!==g,p=!!e||m;if(p||!l.paused&&l.playbackRate&&l.readyState){var y=s.mainForwardBufferInfo;if(p||null!==y){var E=r.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(!(f<=Math.max(E,h/(2*T)*1e3))){var S=y?y.len/T:0,A=d.loading.first?d.loading.first-d.loading.start:-1,I=d.loaded&&A>-1,L=r.getBwEstimate(),R=s.levels,b=R[g],k=Math.max(d.loaded,Math.round(h*(n.bitrate||b.averageBitrate)/8)),D=I?f-A:f;D<1&&I&&(D=Math.min(f,8*d.loaded/L));var P=I?1e3*d.loaded/D:0,_=E/1e3,C=P?(k-d.loaded)/P:8*k/L+_;if(!(C<=S)){var w,O=P?8*P:L,M=!0===(null==(t=(null==e?void 0:e.details)||s.latestLevelDetails)?void 0:t.live),F=s.config.abrBandWidthUpFactor,N=Number.POSITIVE_INFINITY;for(w=g-1;w>c;w--){var B=R[w].maxBitrate,U=!R[w].details||M;if((N=r.getTimeToLoadFrag(_,O,h*B,U))<Math.min(S,h+_))break}if(!(N>=C||N>10*h)){I?r.bwEstimator.sample(f-Math.min(E,A),d.loaded):r.bwEstimator.sampleTTFB(f);var K=R[w].maxBitrate;r.getBwEstimate()*F>K&&(r.firstAutoFloor=Math.min(w,s.firstLevel),r.resetEstimator(K));var V=r.findBestLevel(K,c,w,0,S,1,1);V>-1&&(w=V),r.warn("Fragment "+n.sn+(a?" part "+a.index:"")+" of level "+g+" is loading too slowly;\n Fragment duration: "+n.duration.toFixed(3)+"\n Time to underbuffer: "+S.toFixed(3)+" s\n Estimated load time for current fragment: "+C.toFixed(3)+" s\n Estimated load time for down switch fragment: "+N.toFixed(3)+" s\n TTFB estimate: "+(0|A)+" ms\n Current BW estimate: "+(x(L)?0|L:"Unknown")+" bps\n New BW estimate: "+(0|r.getBwEstimate())+" bps\n Switching to level "+w+" @ "+(0|K)+" bps"),s.nextLoadLevel=s.nextAutoLevel=w,r.clearTimer();var H=function(){r.clearTimer();var e=r.hls;if(r.fragCurrent===n&&e.loadLevel===w&&w>0){var t=r.getStarvationDelay();if(r.warn("Aborting inflight request "+(w>0?"and switching down":"")+"\n Fragment duration: "+n.duration.toFixed(3)+" s\n Time to underbuffer: "+t.toFixed(3)+" s"),n.abortRequests(),r.fragCurrent=r.partCurrent=null,w>c){var i=r.findBestLevel(e.levels[c].bitrate,c,w,0,t,1,1);-1===i&&(i=c),e.nextLoadLevel=e.nextAutoLevel=i,r.firstAutoFloor=Math.min(i,e.firstLevel),r.resetEstimator(e.levels[i].bitrate)}}};m||C>2*N?H():r.timer=self.setInterval(H,1e3*N),s.trigger(G.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:a,stats:d})}}}}}}}}},r.hls=t,r.bwEstimator=r.initEstimator(),r.registerListeners(),r}d(t,e);var r=t.prototype;return r.resetEstimator=function(e){this.hls&&(e&&(this.log("setting initial bwe to "+e),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator())},r.initEstimator=function(){var e=this.hls.config;return new me(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)},r.registerListeners=function(){var e=this.hls;e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.FRAG_LOADING,this.onFragLoading,this),e.on(G.FRAG_LOADED,this.onFragLoaded,this),e.on(G.FRAG_BUFFERED,this.onFragBuffered,this),e.on(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(G.LEVEL_LOADED,this.onLevelLoaded,this),e.on(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(G.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(G.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.FRAG_LOADING,this.onFragLoading,this),e.off(G.FRAG_LOADED,this.onFragLoaded,this),e.off(G.FRAG_BUFFERED,this.onFragBuffered,this),e.off(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(G.LEVEL_LOADED,this.onLevelLoaded,this),e.off(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(G.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(G.ERROR,this.onError,this))},r.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null},r.onManifestLoading=function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()},r.onLevelsUpdated=function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null},r.onMaxAutoLevelUpdated=function(){this.firstSelection=-1,this.nextAutoLevelKey=""},r.onFragLoading=function(e,t){var r,i=t.frag;this.ignoreFragment(i)||(i.bitrateTest||(this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))},r.onLevelSwitching=function(e,t){this.clearTimer()},r.onError=function(e,t){if(!t.fatal)switch(t.details){case U.BUFFER_ADD_CODEC_ERROR:case U.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case U.FRAG_LOAD_TIMEOUT:var r=t.frag,i=this.fragCurrent,n=this.partCurrent;if(r&&re(r,i)){var a=performance.now(),s=n?n.stats:r.stats,o=a-s.loading.start,l=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&l>-1){var u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(u,l),s.loaded)}else this.bwEstimator.sampleTTFB(o)}}},r.getTimeToLoadFrag=function(e,t,r,i){return e+r/t+(i?e+this.lastLevelLoadSec:0)},r.onLevelLoaded=function(e,t){var r=this.hls.config,i=t.stats.loading,n=i.end-i.first;x(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)},r.onFragLoaded=function(e,t){var r,i=t.frag,n=t.part,a=n?n.stats:i.stats;if(i.type===$.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,null!=(r=this.hls)&&r.config.abrMaxWithRealBitrate){var s=n?n.duration:i.duration,o=this.hls.levels[i.level],l=(o.loaded?o.loaded.bytes:0)+a.loaded,u=(o.loaded?o.loaded.duration:0)+s;o.loaded={bytes:l,duration:u},o.realBitrate=Math.round(8*l/u)}if(i.bitrateTest){var d={stats:a,frag:i,part:n,id:i.type};this.onFragBuffered(G.FRAG_BUFFERED,d),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}},r.onFragBuffered=function(e,t){var r=t.frag,i=t.part,n=null!=i&&i.stats.loaded?i.stats:r.stats;if(!n.aborted&&!this.ignoreFragment(r)){var a=((r.bitrate||0)>=1e5?n.parsing.end:n.loading.end)-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}},r.ignoreFragment=function(e){return e.type!==$.MAIN||"initSegment"===e.sn},r.clearTimer=function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)},r.getAutoLevelKey=function(){return this.getBwEstimate()+"_"+this.getStarvationDelay().toFixed(2)},r.getNextABRAutoLevel=function(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls;if(!r)return-1;if(r.levels.length<=1)return r.loadLevel;var i=r.maxAutoLevel,n=r.config,a=r.minAutoLevel,s=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),u=n.abrBandWidthFactor,d=n.abrBandWidthUpFactor;if(l){var h=this.findBestLevel(o,a,i,l,0,u,d);if(h>=0)return this.rebufferNotice=-1,h}var f=s?Math.min(s,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){var c=this.bitrateTestDelay;c&&(f=(s?Math.min(s,n.maxLoadingDelay):n.maxLoadingDelay)-c,this.info("bitrate test took "+Math.round(1e3*c)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*f)+" ms"),u=d=1)}var g=this.findBestLevel(o,a,i,l,f,u,d);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info((l?"rebuffering expected":"buffer is empty")+", optimal quality level "+g)),g>-1)return g;var v=r.levels[a],m=r.loadLevelObj;return m&&(null==v?void 0:v.bitrate)<m.bitrate?a:r.loadLevel},r.getStarvationDelay=function(){var e=this.hls,t=null==e?void 0:e.media;if(!t)return 1/0;var r=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/r},r.getBwEstimate=function(){return this.bwEstimator.getEstimate()},r.findBestLevel=function(e,t,r,i,n,a,s){var o=this,l=this.hls,u=this.lastLoadedFragLevel,d=this.fragCurrent,h=this.partCurrent;if(!l)return-1;var f=i+n,c=-1===u?l.firstLevel:u,g=l.levels,v=l.allAudioTracks,m=l.loadLevel,p=l.latestLevelDetails,y=l.config;if(1===g.length)return 0;var E,T=g[c],S=!(null==p||!p.live),A=-1===m||-1===u,I="SDR",L=(null==T?void 0:T.frameRate)||0,R=y.audioPreference,b=y.videoPreference,k=this.audioTracksByGroup||(this.audioTracksByGroup=vr(v)),D=-1;if(A){if(-1!==this.firstSelection)return this.firstSelection;var P=this.codecTiers||(this.codecTiers=function(e,t,r,i){return e.slice(r,i+1).reduce((function(e,r,i){if(!r.codecSet)return e;var n=r.audioGroups,a=e[r.codecSet];a||(e[r.codecSet]=a={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!n,fragmentError:0}),a.minBitrate=Math.min(a.minBitrate,r.bitrate);var s=Math.min(r.height,r.width);return a.minHeight=Math.min(a.minHeight,s),a.minFramerate=Math.min(a.minFramerate,r.frameRate),a.minIndex=Math.min(a.minIndex,i),a.maxScore=Math.max(a.maxScore,r.score),a.fragmentError+=r.fragmentError,a.videoRanges[r.videoRange]=(a.videoRanges[r.videoRange]||0)+1,n&&n.forEach((function(e){if(e){var r=t.groups[e];r&&(a.hasDefaultAudio=a.hasDefaultAudio||t.hasDefaultAudio?r.hasDefault:r.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(r.channels).forEach((function(e){a.channels[e]=(a.channels[e]||0)+r.channels[e]})))}})),e}),{})}(g,k,t,r)),_=function(e,t,r,i,n){for(var a=Object.keys(e),s=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=null==n?void 0:n.videoCodec,u=s&&2===parseInt(s),d=!1,h=!1,f=1/0,c=1/0,g=1/0,v=1/0,m=0,p=[],y=fr(t,n),E=y.preferHDR,T=y.allowedVideoRanges,S=function(){var t=e[a[A]];d||(d=t.channels[2]>0),f=Math.min(f,t.minHeight),c=Math.min(c,t.minFramerate),g=Math.min(g,t.minBitrate),T.filter((function(e){return t.videoRanges[e]>0})).length>0&&(h=!0)},A=a.length;A--;)S();f=x(f)?f:0,c=x(c)?c:0;var I=Math.max(1080,f),L=Math.max(30,c);g=x(g)?g:r,r=Math.max(g,r),h||(t=void 0);var R=a.length>1;return{codecSet:a.reduce((function(t,i){var n=e[i];if(i===t)return t;if(p=h?T.filter((function(e){return n.videoRanges[e]>0})):[],R){if(n.minBitrate>r)return gr(i,"min bitrate of "+n.minBitrate+" > current estimate of "+r),t;if(!n.hasDefaultAudio)return gr(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return gr(i,'audio codec preference "'+o+'" not found'),t;if(s&&!u){if(!n.channels[s])return gr(i,"no renditions with "+s+" channel sound found (channels options: "+Object.keys(n.channels)+")"),t}else if((!o||u)&&d&&0===n.channels[2])return gr(i,"no renditions with stereo sound found"),t;if(n.minHeight>I)return gr(i,"min resolution of "+n.minHeight+" > maximum of "+I),t;if(n.minFramerate>L)return gr(i,"min framerate of "+n.minFramerate+" > maximum of "+L),t;if(!p.some((function(e){return n.videoRanges[e]>0})))return gr(i,"no variants with VIDEO-RANGE of "+cr(p)+" found"),t;if(l&&i.indexOf(l.substring(0,4))%5!=0)return gr(i,'video codec preference "'+l+'" not found'),t;if(n.maxScore<m)return gr(i,"max score of "+n.maxScore+" < selected max of "+m),t}return t&&(Kt(i)>=Kt(t)||n.fragmentError>e[t].fragmentError)?t:(v=n.minIndex,m=n.maxScore,i)}),void 0),videoRanges:p,preferHDR:E,minFramerate:c,minBitrate:g,minIndex:v}}(P,I,e,R,b),C=_.codecSet,w=_.videoRanges,O=_.minFramerate,M=_.minBitrate,F=_.minIndex,N=_.preferHDR;D=F,E=C,I=N?w[w.length-1]:w[0],L=O,e=Math.max(e,M),this.log("picked start tier "+cr(_))}else E=null==T?void 0:T.codecSet,I=null==T?void 0:T.videoRange;for(var B,U=h?h.duration:d?d.duration:0,G=this.bwEstimator.getEstimateTTFB()/1e3,K=[],V=function(){var t,l=g[H],d=H>c;if(!l)return 0;if(y.useMediaCapabilities&&!l.supportedResult&&!l.supportedPromise){var v=navigator.mediaCapabilities;"function"==typeof(null==v?void 0:v.decodingInfo)&&function(e,t,r,i,n,a){var s=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==a?void 0:a.audioCodec,u=null==a?void 0:a.channels,d=u?parseInt(u):l?1/0:2,h=null;if(null!=o&&o.length)try{h=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce((function(e,r){if(r){var i=t.groups[r];if(!i)throw new Error("Audio track group "+r+" not found");Object.keys(i.channels).forEach((function(t){e[t]=(e[t]||0)+i.channels[t]}))}return e}),{2:0})}catch(e){return!0}return void 0!==s&&(s.split(",").some((function(e){return Tt(e)}))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(i,30)||"SDR"!==e.videoRange&&e.videoRange!==r||e.bitrate>Math.max(n,8e6))||!!h&&x(d)&&Object.keys(h).some((function(e){return parseInt(e)>d}))}(l,k,I,L,e,R)?(l.supportedPromise=Jt(l,k,v,o.supportedCache),l.supportedPromise.then((function(e){if(o.hls){l.supportedResult=e;var t=o.hls.levels,r=t.indexOf(l);e.error?o.warn('MediaCapabilities decodingInfo error: "'+e.error+'" for level '+r+" "+cr(e)):e.supported?e.decodingInfoResults.some((function(e){return!1===e.smooth||!1===e.powerEfficient}))&&o.log("MediaCapabilities decodingInfo for level "+r+" not smooth or powerEfficient: "+cr(e)):(o.warn("Unsupported MediaCapabilities decodingInfo result for level "+r+" "+cr(e)),r>-1&&t.length>1&&(o.log("Removing unsupported level "+r),o.hls.removeLevel(r),-1===o.hls.loadLevel&&(o.hls.nextLoadLevel=0)))}})).catch((function(e){o.warn("Error handling MediaCapabilities decodingInfo: "+e)}))):l.supportedResult=$t}if((E&&l.codecSet!==E||I&&l.videoRange!==I||d&&L>l.frameRate||!d&&L>0&&L<l.frameRate||null!=(t=l.supportedResult)&&null!=(t=t.decodingInfoResults)&&t.some((function(e){return!1===e.smooth})))&&(!A||H!==D))return K.push(H),0;var p,T=l.details,b=(h?null==T?void 0:T.partTarget:null==T?void 0:T.averagetargetduration)||U||1;p=d?s*e:a*e;var P=U&&i>=2*U&&0===n?l.averageBitrate:l.maxBitrate,_=o.getTimeToLoadFrag(G,p,P*b,!T||T.live);if(p>=P&&(H===u||0===l.loadError&&0===l.fragmentError||ge(l,y.errorPenaltyExpireMs))&&(_<=G||!x(_)||S&&!o.bitrateTestDelay||_<f)){var C=o.forcedAutoLevel;return H===m||-1!==C&&C===m||(K.length&&o.trace("Skipped level(s) "+K.join(",")+" of "+r+' max with CODECS and VIDEO-RANGE:"'+g[K[0]].codecs+'" '+g[K[0]].videoRange+'; not compatible with "'+E+'" '+I),o.info("switch candidate:"+c+"->"+H+" adjustedbw("+Math.round(p)+")-bitrate="+Math.round(p-P)+" ttfb:"+G.toFixed(1)+" avgDuration:"+b.toFixed(1)+" maxFetchDuration:"+f.toFixed(1)+" fetchDuration:"+_.toFixed(1)+" firstSelection:"+A+" codecSet:"+l.codecSet+" videoRange:"+l.videoRange+" hls.loadLevel:"+m)),A&&(o.firstSelection=H),{v:H}}},H=r;H>=t;H--)if(0!==(B=V())&&B)return B.v;return-1},r.deriveNextAutoLevel=function(e){if(!this.hls)return-1;var t=this.hls,r=t.maxAutoLevel,i=t.minAutoLevel;return Math.min(Math.max(e,i),r)},a(t,[{key:"firstAutoLevel",get:function(){var e=this.hls;if(!e)return 0;var t=e.maxAutoLevel,r=e.minAutoLevel,i=this.getBwEstimate(),n=this.getStarvationDelay(),a=e.config.maxStarvationDelay,s=this.findBestLevel(i,r,t,n/2,a,1,1);if(s>-1)return s;var o=e.firstLevel,l=-1===this.firstAutoFloor?1/0:this.firstAutoFloor,u=Math.min(Math.max(o,r),t,l);return this.warn("Could not find best starting auto level. Defaulting to first in playlist "+o+" clamped to "+u),u}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){if(!this.hls)return-1;var e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var i=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var n=this.hls.levels;if(n.length>Math.max(e,i)&&n[e].loadError<=n[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i},set:function(e){var t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}}])}(pe),Rr=function(e,t){for(var r=0,i=e.length-1,n=null,a=null;r<=i;){var s=t(a=e[n=(r+i)/2|0]);if(s>0)r=n+1;else{if(!(s<0))return a;i=n-1}}return null};function br(e,t,r,i,n){void 0===r&&(r=0),void 0===i&&(i=0),void 0===n&&(n=.005);var a=null;if(e){a=t[1+e.sn-t[0].sn]||null;var s=e.endDTS-r;s>0&&s<15e-7&&(r+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else 0===r&&0===t[0].start&&(a=t[0]);if(a&&((!e||e.level===a.level)&&0===kr(r,i,a)||function(e,t,r){if(0===(null==t?void 0:t.start)&&t.level<e.level&&(t.endPTS||0)>0){var i=t.tagList.reduce((function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e}),r);return e.start<=i}return!1}(a,e,Math.min(n,i))))return a;var o=Rr(t,kr.bind(null,r,i));return!o||o===e&&a?a:o}function kr(e,t,r){if(void 0===e&&(e=0),void 0===t&&(t=0),r.start<=e&&r.start+r.duration>e)return 0;var i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function Dr(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}function Pr(e,t,r){if(e&&e.startCC<=t&&e.endCC>=t){var i,n=e.fragments,a=e.fragmentHint;return a&&(n=n.concat(a)),Rr(n,(function(e){return e.cc<t?1:e.cc>t?-1:(i=e,e.end<=r?1:e.start>r?-1:0)})),i||null}return null}function _r(e,t){return t===e.endSN&&e.fragmentHint?e.fragmentHint:e.fragments[1+t-e.startSN]||null}var Cr=0,wr=2,Or=3,Mr=5,xr=0,Fr=1,Nr=2,Br=4,Ur=8,Gr=16,Kr=function(e){function t(t){var r;return(r=e.call(this,"error-controller",t.logger)||this).hls=void 0,r.playlistError=0,r.hls=t,r.registerListeners(),r}d(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e.on(G.ERROR,this.onError,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.LEVEL_UPDATED,this.onLevelUpdated,this)},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(G.ERROR,this.onError,this),e.off(G.ERROR,this.onErrorOut,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.LEVEL_UPDATED,this.onLevelUpdated,this))},r.destroy=function(){this.unregisterListeners(),this.hls=null},r.startLoad=function(e){},r.stopLoad=function(){this.playlistError=0},r.getVariantLevelIndex=function(e){return(null==e?void 0:e.type)===$.MAIN?e.level:this.getVariantIndex()},r.getVariantIndex=function(){var e,t=this.hls,r=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===r?t.loadLevel:r},r.variantHasKey=function(e,t){if(e){var r;if(null!=(r=e.details)&&r.hasKey(t))return!0;var i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter((function(e){return i.indexOf(e.groupId)>=0})).some((function(e){var r;return null==(r=e.details)?void 0:r.hasKey(t)}))}return!1},r.onManifestLoading=function(){this.playlistError=0},r.onLevelUpdated=function(){this.playlistError=0},r.onError=function(e,t){var r;if(!t.fatal){var i=this.hls,n=t.context;switch(t.details){case U.FRAG_LOAD_ERROR:case U.FRAG_LOAD_TIMEOUT:case U.KEY_LOAD_ERROR:case U.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case U.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction=Yr());case U.FRAG_GAP:case U.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=wr);case U.PLAYLIST_UNCHANGED_ERROR:case U.LEVEL_EMPTY_ERROR:case U.LEVEL_PARSING_ERROR:var a,s=t.parent===$.MAIN?t.level:i.loadLevel;return void(t.details===U.LEVEL_EMPTY_ERROR&&null!=(a=t.context)&&null!=(a=a.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,s)));case U.LEVEL_LOAD_ERROR:case U.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level)));case U.AUDIO_TRACK_LOAD_ERROR:case U.AUDIO_TRACK_LOAD_TIMEOUT:case U.SUBTITLE_LOAD_ERROR:case U.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){var o=i.loadLevelObj;if(o&&(n.type===Y&&o.hasAudioGroup(n.groupId)||n.type===j&&o.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=wr,void(t.errorAction.flags=Fr)}return;case U.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:wr,flags:Nr});case U.KEY_SYSTEM_SESSION_UPDATE_FAILED:case U.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case U.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:wr,flags:Br});case U.BUFFER_ADD_CODEC_ERROR:case U.REMUX_ALLOC_ERROR:case U.BUFFER_APPEND_ERROR:return void(t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)));case U.MEDIA_SOURCE_REQUIRES_RESET:return t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),void(t.errorAction.flags|=Gr|Ur);case U.INTERNAL_EXCEPTION:case U.BUFFER_APPENDING_ERROR:case U.BUFFER_APPEND_NO_PROGRESS:case U.BUFFER_FULL_ERROR:case U.LEVEL_SWITCH_ERROR:case U.BUFFER_STALLED_ERROR:case U.BUFFER_SEEK_OVER_HOLE:case U.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=Yr())}t.type===B.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Yr())}},r.getPlaylistRetryOrSwitchAction=function(e,t){var r=ue(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(fe(r,i,se(e),e.response))return{action:Mr,flags:xr,retryConfig:r,retryCount:i};var n=this.getLevelSwitchAction(e,t);return r&&(n.retryConfig=r,n.retryCount=i),n},r.getFragRetryOrSwitchAction=function(e){var t=this.hls,r=this.getVariantLevelIndex(e.frag),i=t.levels[r],n=t.config,a=n.fragLoadPolicy,s=n.keyLoadPolicy,o=ue(oe(e)?s:a,e),l=t.levels.reduce((function(e,t){return e+t.fragmentError}),0);if(i&&(e.details!==U.FRAG_GAP&&i.fragmentError++,!le(e)&&fe(o,l,se(e),e.response)))return{action:Mr,flags:xr,retryConfig:o,retryCount:l};var u=this.getLevelSwitchAction(e,r);return o&&(u.retryConfig=o,u.retryCount=l),u},r.getLevelSwitchAction=function(e,t){var r=this.hls;null==t&&(t=r.loadLevel);var i=this.hls.levels[t];if(i){var n,a,s=e.details;i.loadError++,i.loadErrorTime=self.performance.now(),s===U.BUFFER_APPEND_ERROR&&i.fragmentError++;var o=-1,l=r.levels,u=r.loadLevel,d=r.minAutoLevel,h=r.maxAutoLevel;r.autoLevelEnabled||r.config.preserveManualLevelOnError||(r.loadLevel=-1);for(var f,c=null==(n=e.frag)?void 0:n.type,g=(c===$.AUDIO&&s===U.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&Vr(e))&&l.some((function(e){var t=e.audioCodec;return i.audioCodec!==t})),v="video"===e.sourceBufferName&&Vr(e)&&l.some((function(e){var t=e.codecSet,r=e.audioCodec;return i.codecSet!==t&&i.audioCodec===r})),m=null!=(a=e.context)?a:{},p=m.type,y=m.groupId,E=function(){var t=(T+u)%l.length;if(t!==u&&t>=d&&t<=h&&(0===l[t].loadError||ge(l[t],r.config.errorPenaltyExpireMs))){var n,a,f=l[t];if(s===U.FRAG_GAP&&c===$.MAIN&&e.frag){var m=l[t].details;if(m){var E=br(e.frag,m.fragments,e.frag.start);if(null!=E&&E.gap)return 0}}else{if(p===Y&&f.hasAudioGroup(y)||p===j&&f.hasSubtitleGroup(y))return 0;if(c===$.AUDIO&&null!=(n=i.audioGroups)&&n.some((function(e){return f.hasAudioGroup(e)}))||c===$.SUBTITLE&&null!=(a=i.subtitleGroups)&&a.some((function(e){return f.hasSubtitleGroup(e)}))||g&&i.audioCodec===f.audioCodec||v&&i.codecSet===f.codecSet||!g&&i.audioCodec!==f.audioCodec)return 0}return o=t,1}},T=l.length;T--&&(0===(f=E())||1!==f););if(o>-1&&r.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:wr,flags:xr,nextAutoLevel:o}}return{action:wr,flags:Fr}},r.onErrorOut=function(e,t){var r,i;switch(null==(r=t.errorAction)?void 0:r.action){case Cr:break;case wr:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===U.FRAG_GAP||t.details===U.PLAYLIST_UNCHANGED_ERROR||Hr(t)||(t.fatal=!0)}((null==(i=t.errorAction)?void 0:i.flags)||0)&Gr&&this.hls.recoverMediaError(),t.fatal&&this.hls.stopLoad()},r.sendAlternateToPenaltyBox=function(e){var t=this.hls,r=e.errorAction;if(r){var i=r.nextAutoLevel;if(r.flags===xr)this.switchLevel(e,i);else if(r.flags&Ur)for(var n=this.hls.levels,a=n.length;a--;)"SDR"!==n[a].videoRange?(n[a].fragmentError++,n[a].loadError++):void 0===i&&(i=a);else if(r.flags&Nr){var s=this.getVariantLevelIndex(e.frag),o=t.levels[s],l=null==o?void 0:o.attrs["HDCP-LEVEL"];r.hdcpLevel=l;var u="NONE"===l;l&&!u?(t.maxHdcpLevel=ir[ir.indexOf(l)-1],r.resolved=!0,this.warn('Restricting playback to HDCP-LEVEL of "'+t.maxHdcpLevel+'" or lower')):(u&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),r.flags|=Br)}if(r.flags&Br){var d=e.decryptdata;if(d){for(var h=this.hls.levels,f=h.length,c=f;c--;){var g,v;this.variantHasKey(h[c],d)&&(this.log("Banned key found in level "+c+" ("+h[c].bitrate+'bps) or audio group "'+(null==(g=h[c].audioGroups)?void 0:g.join(","))+'" ('+(null==(v=e.frag)?void 0:v.type)+" fragment) "+He(d.keyId||[])),h[c].fragmentError++,h[c].loadError++,this.log("Removing level "+c+" with key error ("+e.error+")"),this.hls.removeLevel(c))}var m=e.frag;if(this.hls.levels.length<f)r.resolved=!0;else if(m&&m.type!==$.MAIN){var p=m.decryptdata;p&&!d.matches(p)&&(r.resolved=!0)}}}r.resolved||this.switchLevel(e,i)}},r.switchLevel=function(e,t){if(void 0!==t&&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===U.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName))for(var r=zt(e.mimeType),i=this.hls.levels,n=i.length;n--;)i[n][e.sourceBufferName+"Codec"]===r&&(this.log("Removing level "+n+" for "+e.details+' ("'+r+'" not supported)'),this.hls.removeLevel(n))},t}(pe);function Vr(e){var t=e.details;return t===U.BUFFER_ADD_CODEC_ERROR||t===U.MEDIA_SOURCE_REQUIRES_RESET||t===U.BUFFER_APPEND_ERROR&&!Hr(e)}function Hr(e){return e.details===U.BUFFER_APPEND_ERROR&&("QuotaExceededError"===e.error.name||"InvalidStateError"===e.error.name)}function Yr(e){var t={action:Cr,flags:xr};return e&&(t.resolved=!0),t}var jr="NOT_LOADED",Wr="APPENDING",qr="PARTIAL",Xr="OK",zr=function(){function e(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()}var t=e.prototype;return t._registerListeners=function(){var e=this.hls;e&&(e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.BUFFER_APPENDED,this.onBufferAppended,this),e.on(G.FRAG_BUFFERED,this.onFragBuffered,this),e.on(G.FRAG_LOADED,this.onFragLoaded,this))},t._unregisterListeners=function(){var e=this.hls;e&&(e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.BUFFER_APPENDED,this.onBufferAppended,this),e.off(G.FRAG_BUFFERED,this.onFragBuffered,this),e.off(G.FRAG_LOADED,this.onFragLoaded,this))},t.destroy=function(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null},t.getAppendedFrag=function(e,t){var r=this.activePartLists[t];if(r)for(var i=r.length;i--;){var n=r[i];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)},t.getBufferedFrag=function(e,t){return this.getFragAtPos(e,t,!0)},t.getFragAtPos=function(e,t,r){for(var i=this.fragments,n=Object.keys(i),a=n.length;a--;){var s=i[n[a]];if((null==s?void 0:s.body.type)===t&&(!r||s.buffered)){var o=s.body;if(o.start<=e&&e<=o.end)return o}}return null},t.detectEvictedFragments=function(e,t,r,i,n,a){var s=this;this.timeRanges&&(this.timeRanges[e]=t);var o=(null==n?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach((function(n){var l=s.fragments[n];if(l&&s.hls){var u=l.body;if(!(o>=u.sn))if(l.buffered||l.loaded&&!a){var d=l.range[e];if(d)if(0!==d.time.length){if(d.time.some((function(e){var r=!s.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&s.removeFragment(u),r})),i&&i!==u&&Ot()){var h=i.endPTS,f=u.startPTS;if(h&&f&&l.range.video){var c=f-h;c<0&&c>-.1&&(s.removeFragment(u),s.hls.trigger(G.BUFFER_FLUSHING,{startOffset:h+.004,endOffset:1/0,type:"video"}))}}}else s.removeFragment(u)}else u.type===r&&s.removeFragment(u)}}))},t.detectPartialFragments=function(e){var t=this,r=this.timeRanges,i=e.frag,n=e.part,a=e.id;if(r&&ee(i)){var s=$r(i),o=this.fragments[s];if(!(!o||o.buffered&&i.gap)){var l=!i.relurl;Object.keys(r).forEach((function(e){var s=i.elementaryStreams[e];if(s){var u=r[e],d=l||!0===s.partial;o.range[e]=t.getBufferedTimes(i,n,d,u),t.detectEvictedFragments(e,u,a,i,n)}})),o.loaded=null;var u=Object.keys(o.range);if(u.length){if(this.bufferedEnd(o,i),Qr(o)||this.removeParts(i.sn-1,i.type),!n){var d=Math.min(.004,i.duration);u.some((function(e){var r,n=null==(r=o.range[e])?void 0:r.time,a=0===n.length||1===n.length&&n[0].endPTS-n[0].startPTS<d;return a&&t.addAsGap(i),a}))}}else this.removeFragment(i)}}},t.addAsGap=function(e){e.gap=!0,this.removeFragment(e),this.fragBuffered(e,!0)},t.bufferedEnd=function(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&!t.gap&&(this.endListFragments[e.body.type]=e)},t.removeParts=function(e,t){var r=this.activePartLists[t];r&&(this.activePartLists[t]=Zr(r,(function(t){return t.fragment.sn>=e})))},t.fragBuffered=function(e,t){var r=$r(e),i=this.fragments[r];return!i&&t&&(i=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e)),i},t.getBufferedTimes=function(e,t,r,i){for(var n={time:[],partial:r},a=e.start,s=e.end,o=e.minEndPTS||s,l=e.maxStartPTS||a,u=0;u<i.length;u++){var d=i.start(u)-this.bufferPadding,h=i.end(u)+this.bufferPadding;if(l>=d&&o<=h){n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(a<h&&s>d){var f=Math.max(a,i.start(u)),c=Math.min(s,i.end(u));c>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:c}))}else if(s<=d)break}return n},t.getPartialFragment=function(e){var t,r,i,n=null,a=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var u=o[l];u&&Qr(u)&&(r=u.body.start-s,i=u.body.end+s,e>=r&&e<=i&&(t=Math.min(e-r,i-e),a<=t&&(n=u.body,a=t)))})),n},t.isEndListAppended=function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||Qr(t))},t.getState=function(e){var t=$r(e),r=this.fragments[t];return r?r.buffered?Qr(r)?qr:Xr:Wr:jr},t.isTimeBuffered=function(e,t,r){for(var i,n,a=0;a<r.length;a++){if(i=r.start(a)-this.bufferPadding,n=r.end(a)+this.bufferPadding,e>=i&&t<=n)return!0;if(t<=i)return!1}return!1},t.onManifestLoading=function(){this.removeAllFragments()},t.onFragLoaded=function(e,t){if(ee(t.frag)&&!t.frag.bitrateTest){var r=t.frag,i=t.part?null:t,n=$r(r);this.fragments[n]={body:r,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}},t.onBufferAppended=function(e,t){var r=t.frag,i=t.part,n=t.timeRanges;if(ee(r)){var a=r.type;if(i){var s=this.activePartLists[a];s||(this.activePartLists[a]=s=[]),s.push(i)}this.timeRanges=n}},t.onFragBuffered=function(e,t){this.detectPartialFragments(t)},t.hasFragment=function(e){var t=$r(e);return!!this.fragments[t]},t.hasFragments=function(e){var t=this.fragments,r=Object.keys(t);if(!e)return r.length>0;for(var i=r.length;i--;){var n=t[r[i]];if((null==n?void 0:n.body.type)===e)return!0}return!1},t.hasParts=function(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)},t.getBackBufferEvictionEnd=function(e,t,r){for(var i=this.fragments,n=0,a=0,s=Object.keys(i),o=0;o<s.length;o++){var l=i[s[o]];if(l&&l.buffered&&l.body.type===t){var u=l.body;if(u.gap)return 0;var d=u.hasStats&&u.stats.loaded||u.byteLength||u.bitrate&&8*u.bitrate*u.duration;if(u.end<=e&&d&&(n+=d,a=Math.max(a,u.end),n>=r))return a}}return a>0?a:0},t.removeFragmentsInRange=function(e,t,r,i,n){var a=this;i&&!this.hasGaps||Object.keys(this.fragments).forEach((function(s){var o=a.fragments[s];if(o){var l=o.body;l.type!==r||i&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&a.removeFragment(l)}}))},t.removeFragment=function(e){var t=$r(e);e.clearElementaryStreamInfo();var r=this.activePartLists[e.type];if(r){var i=e.sn;this.activePartLists[e.type]=Zr(r,(function(e){return e.fragment.sn!==i}))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]},t.removeAllFragments=function(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;var t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach((function(e){return e.clearElementaryStreamInfo()}))},e}();function Qr(e){var t,r,i,n;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(r=e.range.audio)&&r.partial||null!=(i=e.range.audiovideo)&&i.partial||null!=(n=e.range.subs)&&n.partial)}function $r(e){return e.type+"_"+e.level+"_"+e.sn}function Zr(e,t){return e.filter((function(e){var r=t(e);return r||e.clearElementaryStreamInfo(),r}))}var Jr=0,ei=1,ti=function(){function e(e,t,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=r}return e.prototype.decrypt=function(e,t){switch(this.aesMode){case Jr:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case ei:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error("[AESCrypto] invalid aes mode "+this.aesMode)}},e}(),ri=function(){function e(){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()}var t=e.prototype;return t.uint8ArrayToUint32Array_=function(e){for(var t=new DataView(e),r=new Uint32Array(4),i=0;i<4;i++)r[i]=t.getUint32(4*i);return r},t.initTable=function(){var e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],n=r[1],a=r[2],s=r[3],o=this.invSubMix,l=o[0],u=o[1],d=o[2],h=o[3],f=new Uint32Array(256),c=0,g=0,v=0;for(v=0;v<256;v++)f[v]=v<128?v<<1:v<<1^283;for(v=0;v<256;v++){var m=g^g<<1^g<<2^g<<3^g<<4;m=m>>>8^255&m^99,e[c]=m,t[m]=c;var p=f[c],y=f[p],E=f[y],T=257*f[m]^16843008*m;i[c]=T<<24|T>>>8,n[c]=T<<16|T>>>16,a[c]=T<<8|T>>>24,s[c]=T,T=16843009*E^65537*y^257*p^16843008*c,l[m]=T<<24|T>>>8,u[m]=T<<16|T>>>16,d[m]=T<<8|T>>>24,h[m]=T,c?(c=p^f[f[f[E^p]]],g^=f[f[g]]):c=g=1}},t.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i<t.length&&r;)r=t[i]===this.key[i],i++;if(!r){this.key=t;var n=this.keySize=t.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);var a,s,o,l,u=this.ksRows=4*(n+6+1),d=this.keySchedule=new Uint32Array(u),h=this.invKeySchedule=new Uint32Array(u),f=this.sBox,c=this.rcon,g=this.invSubMix,v=g[0],m=g[1],p=g[2],y=g[3];for(a=0;a<u;a++)a<n?o=d[a]=t[a]:(l=o,a%n==0?(l=f[(l=l<<8|l>>>24)>>>24]<<24|f[l>>>16&255]<<16|f[l>>>8&255]<<8|f[255&l],l^=c[a/n|0]<<24):n>6&&a%n==4&&(l=f[l>>>24]<<24|f[l>>>16&255]<<16|f[l>>>8&255]<<8|f[255&l]),d[a]=o=(d[a-n]^l)>>>0);for(s=0;s<u;s++)a=u-s,l=3&s?d[a]:d[a-4],h[s]=s<4||a<=4?l:v[f[l>>>24]]^m[f[l>>>16&255]]^p[f[l>>>8&255]]^y[f[255&l]],h[s]=h[s]>>>0}},t.networkToHostOrderSwap=function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24},t.decrypt=function(e,t,r){for(var i,n,a,s,o,l,u,d,h,f,c,g,v,m,p=this.keySize+6,y=this.invKeySchedule,E=this.invSBox,T=this.invSubMix,S=T[0],A=T[1],I=T[2],L=T[3],R=this.uint8ArrayToUint32Array_(r),b=R[0],k=R[1],D=R[2],P=R[3],_=new Int32Array(e),C=new Int32Array(_.length),w=this.networkToHostOrderSwap;t<_.length;){for(h=w(_[t]),f=w(_[t+1]),c=w(_[t+2]),g=w(_[t+3]),o=h^y[0],l=g^y[1],u=c^y[2],d=f^y[3],v=4,m=1;m<p;m++)i=S[o>>>24]^A[l>>16&255]^I[u>>8&255]^L[255&d]^y[v],n=S[l>>>24]^A[u>>16&255]^I[d>>8&255]^L[255&o]^y[v+1],a=S[u>>>24]^A[d>>16&255]^I[o>>8&255]^L[255&l]^y[v+2],s=S[d>>>24]^A[o>>16&255]^I[l>>8&255]^L[255&u]^y[v+3],o=i,l=n,u=a,d=s,v+=4;i=E[o>>>24]<<24^E[l>>16&255]<<16^E[u>>8&255]<<8^E[255&d]^y[v],n=E[l>>>24]<<24^E[u>>16&255]<<16^E[d>>8&255]<<8^E[255&o]^y[v+1],a=E[u>>>24]<<24^E[d>>16&255]<<16^E[o>>8&255]<<8^E[255&l]^y[v+2],s=E[d>>>24]<<24^E[o>>16&255]<<16^E[l>>8&255]<<8^E[255&u]^y[v+3],C[t]=w(i^b),C[t+1]=w(s^k),C[t+2]=w(a^D),C[t+3]=w(n^P),b=h,k=f,D=c,P=g,t+=4}return C.buffer},e}(),ii=function(){function e(e,t,r){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=r}return e.prototype.expandKey=function(){var e=function(e){switch(e){case Jr:return"AES-CBC";case ei:return"AES-CTR";default:throw new Error("[FastAESKey] invalid aes mode "+e)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])},e}(),ni=function(){function e(e,t){if(this.logEnabled=!0,this.decryptRange=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,!0!==t)try{var r=self.crypto;r&&(this.subtle=r.subtle||r.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle}var t=e.prototype;return t.destroy=function(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null},t.isSync=function(){return this.useSoftware},t.flush=function(){var e=this.currentResult,t=this.remainderData;if(!e||t)return this.reset(),null;var r=new Uint8Array(e);this.reset();var i,n,a,s=this.decryptRange;return s?0===s.start&&s.end>=r.length?r:r.slice(s.start,s.end):(n=(i=r).byteLength,(a=n&&new DataView(i.buffer).getUint8(n-1))?i.slice(0,n-a):i)},t.reset=function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)},t.decrypt=function(e,t,r,i,n){var a=this;return this.decryptRange=n,this.useSoftware||n?new Promise((function(n,s){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);a.softwareDecrypt(o,t,r,i);var l=a.flush();l?n(l.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,r,i)},t.softwareDecrypt=function(e,t,r,i){var n=this.currentIV,a=this.currentResult,s=this.remainderData;if(i!==Jr||16!==t.byteLength)return Le.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),s&&(e=Et(s,e),this.remainderData=null);var o=this.getValidChunk(e);if(!o.length)return null;n&&(r=n);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new ri),l.expandKey(t);var u=a;return this.currentResult=l.decrypt(o.buffer,0,r),this.currentIV=o.slice(-16).buffer,u||null},t.webCryptoDecrypt=function(e,t,r,i){var n=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,i));this.key=t,this.fastAesKey=new ii(this.subtle,t,i)}return this.fastAesKey.expandKey().then((function(t){return n.subtle?(n.logOnce("WebCrypto AES decrypt"),new ti(n.subtle,new Uint8Array(r),i).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))})).catch((function(a){return Le.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, "+a.name+": "+a.message),n.onWebCryptoError(e,t,r,i)}))},t.onWebCryptoError=function(e,t,r,i){var n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,i);var a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")},t.getValidChunk=function(e){var t=e,r=e.length-e.length%16;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t},t.logOnce=function(e){this.logEnabled&&(Le.log("[decrypter]: "+e),this.logEnabled=!1)},e}(),ai=Math.pow(2,17),si=function(){function e(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}var t=e.prototype;return t.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},t.abort=function(){this.loader&&this.loader.abort()},t.load=function(e,t,r,i){var n=this,a=e.url;if(!a)return Promise.reject(new di({type:B.NETWORK_ERROR,details:U.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(a?"part list":"url")),networkDetails:null}));this.abort();var s=this.config,o=s.fLoader,l=s.loader;return new Promise((function(u,d){if(n.loader&&n.loader.destroy(),e.gap){if(e.tagList.some((function(e){return"GAP"===e[0]})))return void d(ui(e));e.gap=!1}var h=n.loader=o?new o(s):new l(s),f=oi(e,null,t);e.loader=h;var g=he(s.fragLoadPolicy.default),v={loadPolicy:g,timeout:g.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:ai};h.stats.retry=e.stats.retry,e.stats=h.stats;var m={onSuccess:function(t,r,i,a){n.resetLoader(e,h);var s=t.data;i.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(s.slice(0,16)),s=s.slice(16)),u({frag:e,part:null,payload:s,networkDetails:a})},onError:function(t,r,i,s){n.resetLoader(e,h),d(new di({type:B.NETWORK_ERROR,details:U.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:c({url:a,data:void 0},t),error:new Error("HTTP Error "+t.code+" "+t.text),networkDetails:i,stats:s}))},onAbort:function(t,r,i){n.resetLoader(e,h),d(new di({type:B.NETWORK_ERROR,details:U.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:i,stats:t}))},onTimeout:function(t,r,i){n.resetLoader(e,h),d(new di({type:B.NETWORK_ERROR,details:U.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error("Timeout after "+v.timeout+"ms"),networkDetails:i,stats:t}))}};if(r){var p=n.gateProgress(r,i);m.onProgress=function(t,r,i,n){return p({frag:e,part:null,payload:i,networkDetails:n})}}h.load(f,v,m)}))},t.gateProgress=function(e,t){var r=e;if(t){var i=[],n=!1;t.then((function(){n=!0,i.forEach((function(t){return e(t)})),i.length=0})).catch((function(){})),r=function(t){n?e(t):i.push(t)}}return r},t.loadPart=function(e,t,r){var i=this;this.abort();var n=this.config,a=n.fLoader,s=n.loader;return new Promise((function(o,l){if(i.loader&&i.loader.destroy(),e.gap||t.gap)l(ui(e,t));else{var u=i.loader=a?new a(n):new s(n),d=oi(e,t);e.loader=u;var h=he(n.fragLoadPolicy.default),f={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:ai};t.stats=u.stats,u.load(d,f,{onSuccess:function(n,a,s,l){i.resetLoader(e,u),i.updateStatsFromPart(e,t);var d={frag:e,part:t,payload:n.data,networkDetails:l};r(d),o(d)},onError:function(r,n,a,s){i.resetLoader(e,u),l(new di({type:B.NETWORK_ERROR,details:U.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:c({url:d.url,data:void 0},r),error:new Error("HTTP Error "+r.code+" "+r.text),networkDetails:a,stats:s}))},onAbort:function(r,n,a){e.stats.aborted=t.stats.aborted,i.resetLoader(e,u),l(new di({type:B.NETWORK_ERROR,details:U.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:a,stats:r}))},onTimeout:function(r,n,a){i.resetLoader(e,u),l(new di({type:B.NETWORK_ERROR,details:U.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:a,stats:r}))}})}}))},t.updateStatsFromPart=function(e,t){var r=e.stats,i=t.stats,n=i.total;if(r.loaded+=i.loaded,n){var a=Math.round(e.duration/t.duration),s=Math.min(Math.round(r.loaded/n),a),o=(a-s)*Math.round(r.loaded/s);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,u=i.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end},t.resetLoader=function(e,t){e.loader=null,e.url=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()},e}();function oi(e,t,r){void 0===t&&(t=null);var i={type:W,frag:e,part:t,responseType:"arraybuffer",url:(t||e).url,headers:{},rangeStart:0,rangeEnd:0},n=li(e,t,r);return n.resetIV&&(i.resetIV=!0),n.byteRange&&(i.rangeStart=n.byteRange.start,i.rangeEnd=n.byteRange.end),i}function li(e,t,r){void 0===t&&(t=null);var i,n,a={},s=t||e,o=s.byteRangeStartOffset,l=s.byteRangeEndOffset;if(x(o)&&x(l))if("initSegment"!==e.sn&&!r||"AES-128"!==(n=null==(i=e.decryptdata)?void 0:i.method)&&"AES-256"!==n)a.byteRange={start:o,end:l};else{var u=16*Math.floor(o/16),d=16*Math.ceil(l/16);a.decryptRange={start:o-u,end:l-u},u>=16&&(a.resetIV=!0,u-=16),a.byteRange={start:u,end:d}}return a}function ui(e,t){var r=new Error("GAP "+(e.gap?"tag":"attribute")+" found"),i={type:B.MEDIA_ERROR,details:U.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new di(i)}var di=function(e){function t(t){var r;return(r=e.call(this,t.error.message)||this).data=void 0,r.data=t,r}return d(t,e),t}(E(Error)),hi=function(e){function t(t,r){var i;return(i=e.call(this,t,r)||this)._boundTick=void 0,i._tickTimer=null,i._tickInterval=null,i._tickCallCount=0,i._boundTick=i.tick.bind(i),i}d(t,e);var r=t.prototype;return r.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},r.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},r.onHandlerDestroyed=function(){},r.hasInterval=function(){return!!this._tickInterval},r.hasNextTick=function(){return!!this._tickTimer},r.setInterval=function(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)},r.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},r.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},r.tick=function(){this._tickCallCount++,1===this._tickCallCount?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(this.log("possible exception thrown in task-loop ("+this.constructor.name+".doTick)"),this._tickCallCount=0)},r.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},r.doTick=function(){},t}(pe),fi=function(e,t,r,i,n,a,s,o,l){void 0===i&&(i=0),void 0===n&&(n=-1),void 0===a&&(a=!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.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=r,this.size=i,this.part=n,this.partial=a,this.duration=s||0,this.decryptRange=l,this.iframe=o||!1},ci={length:0,start:function(){return 0},end:function(){return 0}},gi=function(){function e(){}return e.isBuffered=function(t,r){if(t)for(var i=e.getBuffered(t),n=i.length;n--;)if(r>=i.start(n)&&r<=i.end(n))return!0;return!1},e.bufferedRanges=function(t){if(t){var r=e.getBuffered(t);return e.timeRangesToArray(r)}return[]},e.timeRangesToArray=function(e){for(var t=[],r=0;r<e.length;r++)t.push({start:e.start(r),end:e.end(r)});return t},e.bufferInfo=function(t,r,i){if(t){var n=e.bufferedRanges(t);if(n.length)return e.bufferedInfo(n,r,i)}return{len:0,start:r,end:r,bufferedIndex:-1}},e.bufferedInfo=function(e,t,r){t=Math.max(0,t),e.length>1&&e.sort((function(e,t){return e.start-t.start||t.end-e.end}));var i=-1,n=[];if(r)for(var a=0;a<e.length;a++){t>=e[a].start&&t<=e[a].end&&(i=a);var s=n.length;if(s){var o=n[s-1].end;e[a].start-o<r?e[a].end>o&&(n[s-1].end=e[a].end):n.push(e[a])}else n.push(e[a])}else n=e;for(var l,u=0,d=t,h=t,f=0;f<n.length;f++){var c=n[f].start,g=n[f].end;if(-1===i&&t>=c&&t<=g&&(i=f),t+r>=c&&t<g)d=c,u=(h=g)-t;else if(t+r<c){l=c;break}}return{len:u,start:d||0,end:h||0,nextStart:l,buffered:e,bufferedIndex:i}},e.getBuffered=function(e){try{return e.buffered||ci}catch(e){return Le.log("failed to get media.buffered",e),ci}},e}(),vi=/\{\$([a-zA-Z0-9-_]+)\}/g;function mi(e){return vi.lastIndex=0,vi.test(e)}function pi(e,t){if(null!==e.variableList||e.hasVariableRefs){var r=e.variableList;return t.replace(vi,(function(t){var i=t.substring(2,t.length-1),n=null==r?void 0:r[i];return void 0===n?(e.playlistParsingError||(e.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'+i+'"')),t):n}))}return t}function yi(e,t,r){var i,n,a=e.variableList;if(a||(e.variableList=a={}),"QUERYPARAM"in t){i=t.QUERYPARAM;try{var s=new self.URL(r).searchParams;if(!s.has(i))throw new Error('"'+i+'" does not match any query parameter in URI: "'+r+'"');n=s.get(i)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: "+t.message))}}else i=t.NAME,n=t.VALUE;i in a?e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'+i+'"')):a[i]=n||""}function Ei(e,t,r){var i=t.IMPORT;if(r&&i in r){var n=e.variableList;n||(e.variableList=n={}),n[i]=r[i]}else e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'+i+'"'))}var Ti=/^(\d+)x(\d+)$/,Si=/(.+?)=(".*?"|.*?)(?:,|$)/g,Ai=function(){function e(t,r){"string"==typeof t&&(t=e.parseAttrList(t,r)),l(this,t)}var t=e.prototype;return t.decimalInteger=function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.hexadecimalInteger=function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),i=0;i<t.length/2;i++)r[i]=parseInt(t.slice(2*i,2*i+2),16);return r}return null},t.hexadecimalIntegerAsNumber=function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.decimalFloatingPoint=function(e){return parseFloat(this[e])},t.optionalFloat=function(e,t){var r=this[e];return r?parseFloat(r):t},t.enumeratedString=function(e){return this[e]},t.enumeratedStringList=function(e,t){var r=this[e];return(r?r.split(/[ ,]+/):[]).reduce((function(e,t){return e[t.toLowerCase()]=!0,e}),t)},t.bool=function(e){return"YES"===this[e]},t.decimalResolution=function(e){var t=Ti.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e,t){var r,i={};for(Si.lastIndex=0;null!==(r=Si.exec(e));){var n=r[1].trim(),a=r[2],s=0===a.indexOf('"')&&a.lastIndexOf('"')===a.length-1,o=!1;if(s)a=a.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(s||o))a=pi(t,a);else if(!o&&!s)switch(n){case"CLOSED-CAPTIONS":if("NONE"===a)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":Le.warn(e+": attribute "+n+" is missing quotes")}i[n]=a}return i},a(e,[{key:"clientAttrs",get:function(){return Object.keys(this).filter((function(e){return"X-"===e.substring(0,2)}))}}])}();function Ii(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var Li=function(){return a((function(e,t,r){var i;if(void 0===r&&(r=0),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=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(i=null==t?void 0:t.tagOrder)?i:r,t){var n=t.attr;for(var a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){Le.warn('DATERANGE tag attribute: "'+a+'" does not match for tags with ID: "'+e.ID+'"'),this._badValueForSameId=a;break}e=l(new Ai({}),n,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 e){var s=(null==t?void 0:t.endDate)||new Date(e["END-DATE"]);x(s.getTime())&&(this._endDate=s)}}),[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"cue",get:function(){var e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}},{key:"startTime",get:function(){var e=this.tagAnchor;return null===e||null===e.programDateTime?(Le.warn('Expected tagAnchor Fragment with PDT set for DateRange "'+this.id+'": '+e),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){var e=this._endDate||this._dateAtEnd;if(e)return e;var t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}},{key:"duration",get:function(){if("DURATION"in this.attr){var e=this.attr.decimalFloatingPoint("DURATION");if(x(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{key:"plannedDuration",get:function(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}},{key:"endOnNext",get:function(){return this.attr.bool("END-ON-NEXT")}},{key:"isInterstitial",get:function(){return"com.apple.hls.interstitial"===this.class}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&x(this.startDate.getTime())&&(null===this.duration||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)}},{key:"invalidReason",get:function(){return this.id?this._badValueForSameId?"Date range "+this._badValueForSameId+" mismatch":x(this.startDate.getTime())?!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr?this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Interstitial Date range missing X-ASSET-(LIST|URI)":"Date range invalid start date":"Missing ID"}}])}(),Ri=function(){function e(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.iframesOnly=!1,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}var t=e.prototype;return t.reloaded=function(e){if(!e)return this.advanced=!0,void(this.updated=!0);var t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1},t.hasKey=function(e){return this.encryptedFragments.some((function(t){var r=t.decryptdata;return r||(t.setKeyFormat(e.keyFormat),r=t.decryptdata),!!r&&e.matches(r)}))},a(e,[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&x(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}},{key:"fragmentStart",get:function(){return this.fragments.length?this.fragments[0].start:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"maxPartIndex",get:function(){var e=this.partList;if(e){var t=this.lastPartIndex;if(-1!==t){for(var r=e.length;r--;)if(e[r].index>t)return e[r].index;return t}}return 0}},{key:"lastPartSn",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}},{key:"expired",get:function(){if(this.live&&this.age&&this.misses<3){var e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}])}();function bi(e,t){return e.length===t.length&&!e.some((function(e,r){return e!==t[r]}))}function ki(e,t){return!e&&!t||!(!e||!t)&&bi(e,t)}function Di(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function Pi(e){switch(e){case"AES-128":case"AES-256":return Jr;case"AES-256-CTR":return ei;default:throw new Error("invalid full segment method "+e)}}function _i(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(function(e){return e.charCodeAt(0)}))}function Ci(e){var t=function(e,t,r){var i=e[t];e[t]=e[r],e[r]=i};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function wi(e){var t,r,i=e.split(":"),n=null;if("data"===i[0]&&2===i.length){var a=i[1].split(";"),s=a[a.length-1].split(",");if(2===s.length){var o="base64"===s[0],l=s[1];o?(a.splice(-1,1),n=je(l)):(t=_i(l).subarray(0,16),(r=new Uint8Array(16)).set(t,16-t.length),n=r)}}return n}var Oi="undefined"!=typeof self?self:void 0,Mi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},xi="org.w3.clearkey",Fi="com.apple.streamingkeydelivery",Ni="com.microsoft.playready",Bi="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Ui(e){switch(e){case Fi:return Mi.FAIRPLAY;case Ni:return Mi.PLAYREADY;case Bi:return Mi.WIDEVINE;case xi:return Mi.CLEARKEY}}var Gi="edef8ba979d64acea3c827dcd51d21ed";function Ki(e){switch(e){case Mi.FAIRPLAY:return Fi;case Mi.PLAYREADY:return Ni;case Mi.WIDEVINE:return Bi;case Mi.CLEARKEY:return xi}}function Vi(e){var t=e.drmSystems,r=e.widevineLicenseUrl,i=t?[Mi.FAIRPLAY,Mi.WIDEVINE,Mi.PLAYREADY,Mi.CLEARKEY].filter((function(e){return!!t[e]})):[];return!i[Mi.WIDEVINE]&&r&&i.push(Mi.WIDEVINE),i}var Hi,Yi=null!=Oi&&null!=(Hi=Oi.navigator)&&Hi.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function ji(e){var t=We(new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2)),r=t.substring(t.indexOf("<"),t.length),i=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(i){var n=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute("VALUE");if(n){var a=je(n).subarray(0,16);return Ci(a),a}}return null}var Wi={},qi=function(){function e(e,t,r,i,n,a){void 0===i&&(i=[1]),void 0===n&&(n=null),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.scheme=void 0,this.method=e,this.uri=t,this.keyFormat=r,this.keyFormatVersions=i,this.iv=n,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!Di(e),null!=a&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Ye(a)))}e.clearKeyUriToKeyIdMap=function(){Wi={}},e.setKeyIdForUri=function(e,t){Wi[e]=t},e.addKeyIdForUri=function(e){var t=Object.keys(Wi).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,t),Wi[e]=r,r};var t=e.prototype;return t.matches=function(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&bi(e.keyFormatVersions,this.keyFormatVersions)&&ki(e.iv,this.iv)&&ki(e.keyId,this.keyId)},t.isSupported=function(){if(this.method){if(Di(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Fi:case Bi:case Ni:case xi:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1},t.getDecryptData=function(t,r){var i;if(!this.encrypted||!this.uri)return null;if(Di(this.method)){var n=this.iv;return n||("number"!=typeof t&&(Le.warn('missing IV for initialization segment with method="'+this.method+'" - compliance issue'),t=0),n=function(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}(t)),new e(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){var a=Wi[this.uri];if(a&&!bi(this.keyId,a)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}var s,o=wi(this.uri);if(o)switch(this.keyFormat){case Bi:if(this.pssh=o,!this.keyId){var l=Rt(o.buffer).filter((function(e){return e.systemId===Gi}));if(l.length){var u,d=l[0];this.keyId=null!=(u=d.kids)&&u.length?d.kids[0]:null}}this.keyId||(this.keyId=Xi(r));break;case Ni:var h=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Lt(h,0,o),this.keyId=ji(o);break;default:var f=o.subarray(0,16);if(16!==f.length){var c=new Uint8Array(16);c.set(f,16-f.length),f=c}this.keyId=f}return 16!==(null==(i=this.keyId)?void 0:i.byteLength)&&(s=function(e){var t=null==e?void 0:e[Bi];return t?t.keyId:null}(r),s||(s=Xi(r))||(s=Wi[this.uri]),s&&(this.keyId=s,e.setKeyIdForUri(this.uri,s))),this},e}();function Xi(e){var t=null==e?void 0:e[Ni];if(t){var r=wi(t.uri);if(r)return ji(r)}return null}var zi=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,Qi=/#EXT-X-MEDIA:(.*)/g,$i=/^#EXT(?:INF|-X-TARGETDURATION):/m,Zi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Ji=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|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),en=function(){function e(){}return e.findGroup=function(e,t){for(var r=0;r<e.length;r++){var i=e[r];if(i.id===t)return i}},e.resolve=function(e,t){return M.buildAbsoluteURL(t,e,{alwaysNormalize:!0})},e.isMediaPlaylist=function(e){return $i.test(e)},e.parseMasterPlaylist=function(t,r){var i,n={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:mi(t)},a=[];if(zi.lastIndex=0,!t.startsWith("#EXTM3U"))return n.playlistParsingError=new Error("no EXTM3U delimiter"),n;for(;null!=(i=zi.exec(t));)if(i[1]){var s=tn(new Ai(i[1],n),i[2],r,n,a);s&&n.levels.push(s)}else if(i[3]){var o=i[3],l=i[4];switch(o){case"I-FRAME-STREAM-INF":var u=new Ai(l,n),d=tn(u,u.URI,r,n,a,!0);d&&n.iframeVariants.push(d);break;case"SESSION-DATA":var h=new Ai(l,n),f=h["DATA-ID"];f&&(null===n.sessionData&&(n.sessionData={}),n.sessionData[f]=h);break;case"SESSION-KEY":var c=an(l,r,n);c.encrypted&&c.isSupported()?(null===n.sessionKeys&&(n.sessionKeys=[]),n.sessionKeys.push(c)):Le.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'+l+'"');break;case"DEFINE":yi(n,new Ai(l,n),r);break;case"CONTENT-STEERING":var g=new Ai(l,n);n.contentSteering={uri:e.resolve(g["SERVER-URI"],r),pathwayId:g["PATHWAY-ID"]||"."};break;case"START":n.startTimeOffset=sn(l)}}var v=a.length>0&&a.length<n.levels.length;return n.levels=v?a:n.levels,0===n.levels.length&&(n.playlistParsingError=new Error("no levels found in manifest")),n},e.parseMasterPlaylistMedia=function(t,r,i){var n,a={},s=i.levels,o={AUDIO:s.map((function(e){return{id:e.attrs.AUDIO,audioCodec:e.audioCodec}})),SUBTITLES:s.map((function(e){return{id:e.attrs.SUBTITLES,textCodec:e.textCodec}})),"CLOSED-CAPTIONS":[]},l=0;for(Qi.lastIndex=0;null!==(n=Qi.exec(t));){var u=new Ai(n[1],i),d=u.TYPE;if(d){var h=o[d],f=a[d]||[];a[d]=f;var c=u.LANGUAGE,g=u["ASSOC-LANGUAGE"],v=u.CHANNELS,m=u.CHARACTERISTICS,p=u["INSTREAM-ID"],y={attrs:u,bitrate:0,id:l++,groupId:u["GROUP-ID"]||"",name:u.NAME||c||"",type:d,default:u.bool("DEFAULT"),autoselect:u.bool("AUTOSELECT"),forced:u.bool("FORCED"),lang:c,url:u.URI?e.resolve(u.URI,r):""};if(g&&(y.assocLang=g),v&&(y.channels=v),m&&(y.characteristics=m),p&&(y.instreamId=p),null!=h&&h.length){var E=e.findGroup(h,y.groupId)||h[0];ln(y,E,"audioCodec"),ln(y,E,"textCodec")}f.push(y)}}return a},e.parseLevelPlaylist=function(e,t,r,i,n,a){var s,o,u,d,h,f={url:t},c=new Ri(t),g=c.fragments,v=[],m=null,p=0,y=0,E=0,T=0,S=0,A=null,I=new ie(i,f),L=-1,R=!1,b=null;if(Zi.lastIndex=0,c.m3u8=e,c.hasVariableRefs=mi(e),"#EXTM3U"!==(null==(s=Zi.exec(e))?void 0:s[0]))return c.playlistParsingError=new Error("Missing format identifier #EXTM3U"),c;for(;null!==(o=Zi.exec(e));){R&&(R=!1,(I=new ie(i,f)).playlistOffset=E,I.setStart(E),I.sn=p,I.cc=T,S&&(I.bitrate=S),I.level=r,m&&(I.initSegment=m,m.rawProgramDateTime&&(I.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),b&&(I.setByteRange(b),b=null)));var k=o[1];if(k){I.duration=parseFloat(k);var D=(" "+o[2]).slice(1);I.title=D||null,I.tagList.push(D?["INF",k,D]:["INF",k])}else if(o[3]){if(x(I.duration)){var P;I.playlistOffset=E,I.setStart(E),d&&hn(I,d,c),I.sn=p,I.level=r,I.cc=T;var _=(" "+o[3]).slice(1);I.relurl=pi(c,_),un(I,A,v),A=I,E+=I.duration,p++,y=0;var C=I.byteRange;if(2===C.length&&(I.bitrate=8*(C[1]-C[0])/I.duration|0),c.iframesOnly&&C[0]&&(null==(P=m)?void 0:P.cc)!==T){var w=new ie(i,f);w.relurl=I.relurl,w.setByteRange(Math.min(C[0],1316)+"@0"),w.level=r,w.sn="initSegment",d&&(w.levelkeys=d,d.identity&&(w._decryptdata=d.identity.getDecryptData(0))),m=w,I.initSegment=m}g.push(I),R=!0}}else{if(!(o=o[0].match(Ji))){Le.warn("No matches on slow regex match for level playlist!");continue}for(u=1;u<o.length&&void 0===o[u];u++);var O=(" "+o[u]).slice(1),M=(" "+o[u+1]).slice(1),F=o[u+2]?(" "+o[u+2]).slice(1):null;switch(O){case"BYTERANGE":A?I.setByteRange(M,A):I.setByteRange(M);break;case"PROGRAM-DATE-TIME":I.rawProgramDateTime=M,I.tagList.push(["PROGRAM-DATE-TIME",M]),-1===L&&(L=g.length);break;case"PLAYLIST-TYPE":c.type&&fn(c,O,o),c.type=M.toUpperCase();break;case"MEDIA-SEQUENCE":0!==c.startSN?fn(c,O,o):null!==A&&cn(c,O,o),c.startSN=parseInt(M),p=c.startSN+c.skippedSegments;break;case"SKIP":c.skippedSegments&&fn(c,O,o);var N=new Ai(M,c),B=N.decimalInteger("SKIPPED-SEGMENTS");if(x(B)){c.skippedSegments+=B;for(var U=B;U--;)g.push(null);p+=B}var G=N.enumeratedString("RECENTLY-REMOVED-DATERANGES");G&&(c.recentlyRemovedDateranges=(c.recentlyRemovedDateranges||[]).concat(G.split("\t")));break;case"TARGETDURATION":0!==c.targetduration&&fn(c,O,o),c.targetduration=Math.max(parseInt(M),1);break;case"VERSION":null!==c.version&&fn(c,O,o),c.version=parseInt(M);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":c.iframesOnly=!0;break;case"ENDLIST":c.live||fn(c,O,o),c.live=!1;break;case"#":(M||F)&&I.tagList.push(F?[M,F]:[M]);break;case"DISCONTINUITY":T++,I.tagList.push(["DIS"]);break;case"GAP":I.gap=!0,I.tagList.push([O]);break;case"BITRATE":I.tagList.push([O,M]),S=1e3*parseInt(M),x(S)?I.bitrate=S:S=0;break;case"DATERANGE":var K=new Ai(M,c),V=new Li(K,c.dateRanges[K.ID],c.dateRangeTagCount);c.dateRangeTagCount++,V.isValid||c.skippedSegments?c.dateRanges[V.id]=V:Le.log("Ignoring invalid DATERANGE tag: "+V.invalidReason+": "+M),I.tagList.push(["EXT-X-DATERANGE",M]);break;case"DEFINE":var H=new Ai(M,c);"IMPORT"in H?Ei(c,H,a):yi(c,H,t);break;case"DISCONTINUITY-SEQUENCE":0!==c.startCC&&fn(c,O,o),c.startCC=T=parseInt(M),g.forEach((function(e){return e&&(e.cc=T)}));break;case"KEY":var Y=an(M,t,c);if(Y.isSupported()){if("NONE"===Y.method){d=void 0;break}d||(d={});var j=d[Y.keyFormat];null!=j&&j.matches(Y)||(j&&(d=l({},d)),d[Y.keyFormat]=Y)}else Le.warn('[Keys] Ignoring unsupported EXT-X-KEY tag: "'+M+'"');break;case"START":c.startTimeOffset=sn(M);break;case"MAP":var W=new Ai(M,c);if(I.duration){var q=new ie(i,f);dn(q,W,r,d),m=q,I.initSegment=m,m.rawProgramDateTime&&!I.rawProgramDateTime&&(I.rawProgramDateTime=m.rawProgramDateTime)}else{var X=I.byteRangeEndOffset;if(X){var z=I.byteRangeStartOffset;b=X-z+"@"+z}else b=null;dn(I,W,r,d),m=I,R=!0}m.cc=T;break;case"SERVER-CONTROL":h&&fn(c,O,o),h=new Ai(M),c.canBlockReload=h.bool("CAN-BLOCK-RELOAD"),c.canSkipUntil=h.optionalFloat("CAN-SKIP-UNTIL",0),c.canSkipDateRanges=c.canSkipUntil>0&&h.bool("CAN-SKIP-DATERANGES"),c.partHoldBack=h.optionalFloat("PART-HOLD-BACK",0),c.holdBack=h.optionalFloat("HOLD-BACK",0);break;case"PART-INF":c.partTarget&&fn(c,O,o);var Q=new Ai(M);c.partTarget=Q.decimalFloatingPoint("PART-TARGET");break;case"PART":var $=c.partList;$||($=c.partList=[]);var Z=y>0?$[$.length-1]:void 0,J=y++,ee=new Ai(M,c),te=new ne(ee,I,f,J,Z);$.push(te),I.duration+=te.duration;break;case"PRELOAD-HINT":var re=new Ai(M,c);c.preloadHint=re;break;case"RENDITION-REPORT":var ae=new Ai(M,c);c.renditionReports=c.renditionReports||[],c.renditionReports.push(ae);break;default:Le.warn("line parsed but not handled: "+o)}}}A&&!A.relurl?(g.pop(),E-=A.duration,c.partList&&(c.fragmentHint=A)):c.partList&&(un(I,A,v),I.cc=T,c.fragmentHint=I,d&&hn(I,d,c)),c.targetduration||(c.playlistParsingError=new Error("Missing Target Duration"));var se=g.length,oe=g[0],le=g[se-1];if((E+=c.skippedSegments*c.targetduration)>0&&se&&le){c.averagetargetduration=E/se;var ue=le.sn;c.endSN="initSegment"!==ue?ue:0,c.live||(le.endList=!0),L>0&&(function(e,t,r){if(r||(r=e[t]),r)for(var i=t;i--;){var n=e[i];if(!n)return;n.programDateTime=r.programDateTime-1e3*n.duration,r=n}}(g,L,L>se-1?I:null),oe&&v.unshift(oe))}return c.fragmentHint&&(E+=c.fragmentHint.duration),c.totalduration=E,v.length&&c.dateRangeTagCount&&oe&&rn(v,c),c.endCC=T,c},e}();function tn(e,t,r,i,n,a){var s;if(void 0===t)return null;var o=pi(i,t),l={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:en.resolve(o,r)},u=e.decimalResolution("RESOLUTION");u&&(l.width=u.width,l.height=u.height),on(e.CODECS,l);var d=e["SUPPLEMENTAL-CODECS"];return d&&(l.supplemental={},on(d,l.supplemental)),null!=(s=l.unknownCodecs)&&s.length||n.push(l),a&&(l.iframes=!0),l}function rn(e,t){var r=e.length;if(!r){if(!t.hasProgramDateTime)return;var i=t.fragments[t.fragments.length-1];e.push(i),r++}for(var n=e[r-1],a=t.live?1/0:t.totalduration,s=Object.keys(t.dateRanges),o=s.length;o--;){var l=t.dateRanges[s[o]],u=l.startDate.getTime();l.tagAnchor=n.ref;for(var d=r;d--;){var h;if((null==(h=e[d])?void 0:h.sn)<t.startSN)break;var f=nn(t,u,e,d,a);if(f){l.tagAnchor=f.ref;break}}}}function nn(e,t,r,i,n){var a=r[i];if(a){var s,o=a.programDateTime;if((t>=o||0===i)&&t<=o+1e3*(((null==(s=r[i+1])?void 0:s.start)||n)-a.start)){var l=a.sn-e.startSN,u=e.fragments;if(l>=0&&l<u.length){if(u.length>r.length)for(var d=r[i+1]||u[u.length-1],h=Math.min(d.sn-e.startSN,u.length-1);h>l;h--){var f=u[h].programDateTime;if(t>=f&&t<f+1e3*u[h].duration)return u[h]}return u[l]}}}return null}function an(e,t,r){var i,n,a=new Ai(e,r),s=null!=(i=a.METHOD)?i:"",o=a.URI,l=a.hexadecimalInteger("IV"),u=a.KEYFORMATVERSIONS,d=null!=(n=a.KEYFORMAT)?n:"identity";o&&a.IV&&!l&&Le.error("Invalid IV: "+a.IV);var h=o?en.resolve(o,t):"",f=(u||"1").split("/").map(Number).filter(Number.isFinite);return new qi(s,h,d,f,l,a.KEYID)}function sn(e){var t=new Ai(e).decimalFloatingPoint("TIME-OFFSET");return x(t)?t:null}function on(e,t){var r=(e||"").split(/[ ,]+/).filter((function(e){return e}));["video","audio","text","image"].forEach((function(e){var i=r.filter((function(t){return Ft(t,e)}));i.length&&(t[e+"Codec"]=i.map((function(e){return e.split("/")[0]})).join(","),r=r.filter((function(e){return-1===i.indexOf(e)})))})),t.unknownCodecs=r}function ln(e,t,r){var i=t[r];i&&(e[r]=i)}function un(e,t,r){e.rawProgramDateTime?r.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function dn(e,t,r,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function hn(e,t,r){e.levelkeys=t;var i=r.encryptedFragments;i.length&&i[i.length-1].levelkeys===t||!Object.keys(t).some((function(e){return t[e].isCommonEncryption}))||i.push(e)}function fn(e,t,r){e.playlistParsingError=new Error("#EXT-X-"+t+" must not appear more than once ("+r[0]+")")}function cn(e,t,r){e.playlistParsingError=new Error("#EXT-X-"+t+" must appear before the first Media Segment ("+r[0]+")")}function gn(e,t){var r=t.startPTS;if(x(r)){var i,n=0;t.sn>e.sn?(n=r-e.start,i=e):(n=e.start-r,i=t),i.duration!==n&&i.setDuration(n)}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 vn(e,t,r,i,n,a,s,o){i-r<=0&&(o.warn("Fragment should have a positive duration",t),i=r+t.duration,a=n+t.duration);var l=r,u=i,d=t.startPTS,h=t.endPTS;if(x(d)){var f=Math.abs(d-r);e&&f>e.totalduration?o.warn("media timestamps and playlist times differ by "+f+"s for level "+t.level+" "+e.url):x(t.deltaPTS)?t.deltaPTS=Math.max(f,t.deltaPTS):t.deltaPTS=f,l=Math.max(r,d),r=Math.min(r,d),n=void 0!==t.startDTS?Math.min(n,t.startDTS):n,u=Math.min(i,h),i=Math.max(i,h),a=void 0!==t.endDTS?Math.max(a,t.endDTS):a}var c=r-t.start;0!==t.start&&t.setStart(r),t.setDuration(i-t.start),t.startPTS=r,t.maxStartPTS=l,t.startDTS=n,t.endPTS=i,t.minEndPTS=u,t.endDTS=a;var g,v=t.sn;if(!e||v<e.startSN||v>e.endSN)return 0;var m=v-e.startSN,p=e.fragments;for(p[m]=t,g=m;g>0;g--)gn(p[g],p[g-1]);for(g=m;g<p.length-1;g++)gn(p[g],p[g+1]);return e.fragmentHint&&gn(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,c}function mn(e,t,r){if(e!==t){for(var i,n=null,a=e.fragments,s=a.length-1;s>=0;s--){var o=a[s].initSegment;if(o){n=o;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,r){for(var i,n=t.skippedSegments,a=Math.max(e.startSN,t.startSN)-t.startSN,s=(e.fragmentHint?1:0)+(n?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,o=t.startSN-e.startSN,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,u=null!=(i=e.fragmentHint)&&i.duration?e.fragments.concat(e.fragmentHint):e.fragments,d=a;d<=s;d++){var h=u[o+d],f=l[d];if(n&&!f&&h&&(f=t.fragments[d]=h),h&&f){r(h,f,d,l);var c=h.relurl,g=f.relurl;if(c&&Ln(c,g))return void(t.playlistParsingError=pn("media sequence mismatch "+f.sn+":",e,t,0,f));if(h.cc!==f.cc)return void(t.playlistParsingError=pn("discontinuity sequence mismatch ("+h.cc+"!="+f.cc+")",e,t,0,f))}}}(e,t,(function(e,r,a,s){if((!t.startCC||t.skippedSegments)&&r.cc!==e.cc){for(var o=e.cc-r.cc,l=a;l<s.length;l++)s[l].cc+=o;t.endCC=s[s.length-1].cc}x(e.startPTS)&&x(e.endPTS)&&(r.setStart(r.startPTS=e.startPTS),r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.setDuration(e.endPTS-e.startPTS),r.duration&&(i=r),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(r.elementaryStreams=e.elementaryStreams),r.loader=e.loader,e.hasStats&&(r.stats=e.stats),e.initSegment&&(r.initSegment=e.initSegment,n=e.initSegment)}));var u=t.fragments,d=t.fragmentHint?u.concat(t.fragmentHint):u;if(n&&d.forEach((function(e){var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=n)?void 0:t.relurl)||(e.initSegment=n)})),t.skippedSegments){if(t.deltaUpdateFailed=u.some((function(e){return!e})),t.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var h=t.skippedSegments;h--;)u.shift();t.startSN=u[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,r){var i=t.dateRanges,n=t.recentlyRemovedDateranges,a=l({},e);n&&n.forEach((function(e){delete a[e]}));var s=Object.keys(a).length;return s?(Object.keys(i).forEach((function(e){var t=a[e],n=new Li(i[e].attr,t);n.isValid?(a[e]=n,t||(n.tagOrder+=s)):r.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'+cr(i[e].attr)+'"')})),a):i}(e.dateRanges,t,r));var f=e.fragments.filter((function(e){return e.rawProgramDateTime}));if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(var c=1;c<d.length;c++)null===d[c].programDateTime&&un(d[c],d[c-1],f);rn(f,t)}t.endCC=u[u.length-1].cc}if(!t.startCC){var g,v=Tn(e,t.startSN-1);t.startCC=null!=(g=null==v?void 0:v.cc)?g:u[0].cc}(function(e,t,r){if(e&&t)for(var i=0,n=0,a=e.length;n<a;n++){var s=e[n],o=t[n+i];s&&o&&s.index===o.index&&s.fragment.sn===o.fragment.sn?r(s,o):i--}})(e.partList,t.partList,(function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats,t.gap=e.gap||t.gap})),i?(t.iframesOnly&&(i.type,$.MAIN),vn(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,0,r)):yn(e,t),u.length&&(t.totalduration=t.edge-u[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;var m=t.advancedDateTime;if(t.advanced&&m){var p=t.edge;t.driftStart||(t.driftStartTime=m,t.driftStart=p),t.driftEndTime=m,t.driftEnd=p}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}}function pn(e,t,r,i,n){return new Error(e+" "+n.url+"\nPlaylist starting @"+t.startSN+"\n"+t.m3u8+"\n\nPlaylist starting @"+r.startSN+"\n"+r.m3u8)}function yn(e,t,r,i){void 0===r&&(r=!0);var n=t.startSN+t.skippedSegments-e.startSN,a=e.fragments,s=n>=0,o=0;if(s&&n<a.length)o=a[n].start,null==i||i.log("Aligning playlists based on SN "+t.startSN+" (diff: "+o+")");else if(s&&t.startSN===e.endSN+1)o=e.fragmentEnd,null==i||i.log("Aligning playlists based on first/last SN "+t.startSN+" (diff: "+o+")");else if(s&&r)o=e.fragmentStart+n*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return o;o=e.fragmentStart,null==i||i.log("Aligning playlists based on first SN "+t.startSN+" (diff: "+o+")")}return function(e,t){if(t){for(var r=e.fragments,i=e.skippedSegments;i<r.length;i++)r[i].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}(t,o),o}function En(e,t){void 0===t&&(t=1/0);var r=1e3*e.targetduration;if(e.updated){var i=e.fragments;if(i.length&&4*r>t){var n=1e3*i[i.length-1].duration;n<r&&(r=n)}}else r/=2;return Math.round(r)}function Tn(e,t,r){var i;if(!e)return null;var n=e.fragments[t-e.startSN];return n||((null==(i=n=e.fragmentHint)?void 0:i.sn)===t?n:r&&t<e.startSN&&r.sn===t?r:null)}function Sn(e,t,r){return e?An(e.partList,t,r):null}function An(e,t,r){if(e)for(var i=e.length;i--;){var n=e[i];if(n.index===r&&n.fragment.sn===t)return n}return null}function In(e){e.forEach((function(e,t){var r;null==(r=e.details)||r.fragments.forEach((function(e){e.level=t,e.initSegment&&(e.initSegment.level=t)}))}))}function Ln(e,t){return!(e===t||!t)&&Rn(e)!==Rn(t)}function Rn(e){return e.replace(/\?[^?]*$/,"")}function bn(e,t){for(var r=0,i=e.length;r<i;r++){var n;if((null==(n=e[r])?void 0:n.cc)===t)return e[r]}return null}function kn(e,t){var r=e.start+t;e.setStart(r)}function Dn(e,t){for(var r=t.fragments,i=0,n=r.length;i<n;i++)kn(r[i],e);t.fragmentHint&&kn(t.fragmentHint,e),t.alignedSliding=!0}function Pn(e,t,r){e&&(function(e,t,r){if(function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e)){var i=Math.min(t.endCC,e.endCC),n=bn(t.fragments,i),a=bn(e.fragments,i);if(n&&a){var s=n.start-a.start;r.log("Aligning playlists using dicontinuity sequence "+i+" (diff: "+s+")"),Dn(s,e)}}}(t,e,r),t.alignedSliding||function(e,t,r){if(e.hasProgramDateTime&&t.hasProgramDateTime){var i,n,a=e.fragments,s=t.fragments;if(a.length&&s.length){var o=Math.min(t.endCC,e.endCC);t.startCC<o&&e.startCC<o&&(i=bn(s,o),n=bn(a,o)),i&&n||(n=bn(a,(i=s[Math.floor(s.length/2)]||s.filter((function(e){return!!e}))[0]).cc)||a[Math.floor(a.length/2)]);var l=i.programDateTime,u=n.programDateTime;if(l&&u){var d=(u-l)/1e3;if(Math.abs(d)>Math.max(60,e.totalduration))r.log("Cannot align playlists using PDT without overlap ("+Math.abs(d)+" > "+e.totalduration+")");else{var h=d-(n.start-i.start);r.log("Aligning playlists using PDT (diff: "+h+")"),Dn(h,e)}}}}}(t,e,r),t.alignedSliding||t.skippedSegments||yn(e,t,!1,r))}function _n(e,t,r){Cn(e,t,r),e.addEventListener(t,r)}function Cn(e,t,r){e.removeEventListener(t,r)}function wn(e){for(var t="",r=e.length,i=0;i<r;i++)t+="["+e.start(i).toFixed(3)+"-"+e.end(i).toFixed(3)+"]";return t}var On={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"},Mn=function(e){function t(t,r,i,n,a){var s;return(s=e.call(this,n,t.logger)||this).hls=void 0,s.fragPrevious=null,s.fragCurrent=null,s.fragPlaying=null,s.fragmentTracker=void 0,s.transmuxer=null,s._state=On.STOPPED,s.playlistType=void 0,s.media=null,s.mediaBuffer=null,s.config=void 0,s.bitrateTest=!1,s.lastCurrentTime=0,s.nextLoadPosition=0,s.startPosition=-1,s.startTimeOffset=null,s.retryDate=0,s.levels=null,s.fragmentLoader=void 0,s.initFragmentLoader=void 0,s.keyLoader=void 0,s.levelLastLoaded=null,s.startFragRequested=!1,s.decrypter=void 0,s.initPTS=[],s.buffering=!0,s.loadingParts=!1,s.loopSn=void 0,s.onMediaSeeking=function(){var e=s,t=e.config,r=e.fragCurrent,i=e.media,n=e.mediaBuffer,a=e.state,o=i?i.currentTime:0,l=gi.bufferInfo(n||i,o,t.maxBufferHole),u=l.len;if(s.log("Media seeking to "+o+", state: "+a+", "+(u?"in":"out of")+" buffer"),s.state===On.ENDED)s.resetLoadingState();else if(r){var d=t.maxFragLookUpTolerance,h=r.start-d,f=r.start+r.duration+d;if(!u||f<l.start||h>l.end){var c=o<h,g=o>f;(c||g)&&(!r.loader||!g&&s.isFragmentNearlyDownloaded(r)?s.fragPrevious=null:(s.log("Cancelling fragment load for seek (sn: "+r.sn+") - "+(c?"backward":"forward")+" seek"),r.abortRequests(),s.resetLoadingState()))}}if(i&&(s.fragmentTracker.removeFragmentsInRange(o,1/0,s.playlistType,!0),o>s.lastCurrentTime&&(s.lastCurrentTime=o),!s.loadingParts)){var v=Math.max(l.end,o),m=s.shouldLoadParts(s.getLevelDetails(),v);m&&(s.log("LL-Part loading ON after seeking to "+o+" with buffer @"+v),s.loadingParts=m)}var p=!gi.isBuffered(i,o);s.hls.hasEnoughToStart&&!p||(s.log("Setting "+(p?"startPosition":"nextLoadPosition")+" to "+o+" for seek without enough to start"),s.nextLoadPosition=o,p&&(s.startPosition=o)),u<1&&s.state===On.IDLE&&s.tickImmediate()},s.onMediaEnded=function(){s.log("setting startPosition to 0 because media ended"),s.startPosition=s.lastCurrentTime=0},s.playlistType=a,s.hls=t,s.fragmentLoader=new si(t.config),s.initFragmentLoader=new si(t.config),s.keyLoader=i,s.fragmentTracker=r,s.config=t.config,s.decrypter=new ni(t.config),s}d(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e.on(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(G.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(G.ERROR,this.onError,this)},r.doTick=function(){this.onTickEnd()},r.onTickEnd=function(){},r.startLoad=function(e){},r.stopLoad=function(){if(this.state!==On.STOPPED){this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);var e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=On.STOPPED}},r.pauseBuffering=function(){this.buffering=!1},r.resumeBuffering=function(){this.buffering=!0},r._streamEnded=function(e,t){if(t.live||!this.media)return!1;var r=e.end||0,i=this.config.timelineOffset||0;if(r<=i)return!1;var n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=gi.bufferedInfo(n,e.start,0));var a=e.nextStart;if(a&&a>i&&a<t.edge)return!1;if(this.media.currentTime<e.start)return!1;var s=t.partList;if(null!=s&&s.length){var o=s[s.length-1];return gi.isBuffered(this.media,o.start+o.duration/2)}var l=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(l.type)},r.getLevelDetails=function(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details},r.onMediaAttached=function(e,t){var r=this.media=this.mediaBuffer=t.media;_n(r,"seeking",this.onMediaSeeking),_n(r,"ended",this.onMediaEnded);var i=this.config;this.levels&&i.autoStartLoad&&this.state===On.STOPPED&&this.startLoad(i.startPosition)},r.onMediaDetaching=function(e,t){this.fragPlaying=null;var r=!!t.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Cn(i,"seeking",this.onMediaSeeking),Cn(i,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,r)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}},r.onManifestLoading=function(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1},r.onError=function(e,t){},r.onManifestLoaded=function(e,t){this.startTimeOffset=t.startTimeOffset},r.onHandlerDestroying=function(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),e.prototype.onHandlerDestroying.call(this),this.hls=this.onMediaSeeking=this.onMediaEnded=null},r.onHandlerDestroyed=function(){this.state=On.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,e.prototype.onHandlerDestroyed.call(this)},r.loadFragment=function(e,t,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)},r._loadFragForPlayback=function(e,t,r){var i=this;this._doFragLoad(e,t,r,(function(e){var t=e.frag;if(i.fragContextChanged(t))return i.warn(t.type+" sn: "+t.sn+(e.part?" part: "+e.part.index:"")+" of "+i.fragInfo(t,!1,e.part)+" was dropped during download."),void i.fragmentTracker.removeFragment(t);var r=++t.stats.chunkCount;i.log("load progress "+t.type+" sn: "+t.sn+(e.part?" part: "+e.part.index:"")+" of "+i.fragInfo(t,!1,e.part)+" chunk: "+r),i._handleFragmentLoadProgress(e)})).then((function(e){if(e){var t=i.state,r=e.frag;i.fragContextChanged(r)?(t===On.FRAG_LOADING||!i.fragCurrent&&t===On.PARSING)&&(i.fragmentTracker.removeFragment(r),i.state=On.IDLE):("payload"in e&&(i.log("Loaded "+r.type+" sn: "+r.sn+" of "+i.playlistLabel()+" "+r.level+" (bytes "+r.stats.loaded+")"),i.hls.trigger(G.FRAG_LOADED,e)),i._handleFragmentLoadComplete(e))}})).catch((function(t){i.state!==On.STOPPED&&i.state!==On.ERROR&&(i.log("Frag error "+e.type+" sn:"+e.sn+" cc:"+e.cc+": "+((null==t?void 0:t.message)||t)),i.resetFragmentLoading(e))}))},r.clearTrackerIfNeeded=function(e){var t,r=this.fragmentTracker;if(r.getState(e)===Wr){var i=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,i),a=Math.max(e.duration,n?n.len:this.config.maxBufferLength),s=this.backtrackFragment;(1==(s?e.sn-s.sn:0)||this.reduceMaxBufferLength(a,e.duration))&&r.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===qr&&r.removeFragment(e))},r.checkLiveUpdate=function(e){if(e.updated&&!e.live){var t=this.fragmentTracker,r=e.fragments[e.fragments.length-1];if(r.endList&&!t.isEndListAppended(this.playlistType)){var i=t.getPartialFragment(r.end);i&&(t.removeFragment(i),t.fragBuffered(r,!0))}t.detectPartialFragments({frag:r,part:null,stats:r.stats,id:r.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)},r.waitForLive=function(e){var t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)},r.flushMainBuffer=function(e,t,r){if(void 0===r&&(r=null),e-t){var i={startOffset:e,endOffset:t,type:r};this.hls.trigger(G.BUFFER_FLUSHING,i)}},r._loadInitSegment=function(e){var t=this,r=this.hls;return this.initFragmentLoader.abort(),r.trigger(G.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then((function(e){var r,i=e.frag;if(!t.levels||!re(i,null==(r=t.fragCurrent)?void 0:r.initSegment))throw new di({type:B.NETWORK_ERROR,details:U.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:i,networkDetails:null});return e})).then((function(e){var i=e.frag,n=e.payload,a=i.decryptdata;if(n&&n.byteLength>0&&null!=a&&a.key&&a.iv&&Di(a.method)){var s=self.performance.now(),o=li(i,null,t.iframesOnly).decryptRange;return t.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,Pi(a.method),o).catch((function(e){throw r.trigger(G.ERROR,{type:B.MEDIA_ERROR,details:U.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),t.fragmentLoader.abort(),e})).then((function(n){var a=self.performance.now();return r.trigger(G.FRAG_DECRYPTED,{frag:i,part:null,payload:n,stats:{tstart:s,tdecrypt:a}}),e.payload=n,t.completeInitSegmentLoad(e)}))}return t.completeInitSegmentLoad(e)}))},r.completeInitSegmentLoad=function(e){var t=e.frag.stats;e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now()},r.loadInitSegmentIfNeeded=function(e){var t,r=this,i=e.initSegment;if(!this.bitrateTest&&ee(e)&&i&&!i.data)return(!i.encrypted||null!=(t=i.decryptdata)&&t.key?this._loadInitSegment(i):this.keyLoader.load(i).then((function(){return r._loadInitSegment(i)}))).catch((function(t){if(r.state===On.STOPPED||r.state===On.ERROR)throw t;throw"data"in t&&(t.data.frag=e,r.fragmentLoader.abort(),r.handleFragLoadError(t)),r.resetFragmentLoading(e),t}))},r.unhandledEncryptionError=function(e,t){var r,i,n=e.tracks;if(n&&!t.encrypted&&(null!=(r=n.audio)&&r.encrypted||null!=(i=n.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){var a=this.media,s=new Error("Encrypted track with no key in "+this.fragInfo(t)+" (media "+(a?"attached mediaKeys: "+a.mediaKeys:"detached")+")");return this.warn(s.message),!(!a||a.mediaKeys)&&(this.hls.trigger(G.ERROR,{type:B.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_KEYS,fatal:!1,error:s,frag:t}),this.resetTransmuxer(),!0)}return!1},r.fragContextChanged=function(e){var t=this.fragCurrent;return!e||!re(e,t)},r.fragBufferedComplete=function(e,t){var r=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:"+(r?wn(gi.getBuffered(r)):"(detached)")+")"),ee(e)){var i;if(e.type!==$.SUBTITLE){var n=e.elementaryStreams;if(!Object.keys(n).some((function(e){return!!n[e]})))return void(this.state=On.IDLE)}var a=null==(i=this.levels)?void 0:i[e.level];null!=a&&a.fragmentError&&(t||this.fragmentTracker.getState(e)!==qr)&&(this.log("Resetting level fragment error count of "+a.fragmentError+" on frag buffered"),a.fragmentError=0,e.stats.retry=0)}this.state=On.IDLE},r._handleFragmentLoadComplete=function(e){var t=this.transmuxer;if(t){var r=e.frag,i=e.part,n=e.partsLoaded,a=!n||0===n.length||n.some((function(e){return!e})),s=li(r,i).decryptRange,o=new fi(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!a,r.duration,this.iframesOnly,s);this.log("load complete "+r.type+" sn: "+r.sn+(i?" part: "+i.index:"")+" of "+this.fragInfo(r,!1,i)),t.flush(o)}},r._handleFragmentLoadProgress=function(e){},r.loadKeyFor=function(e,t,r){var i,n=this,a=null;return!e.encrypted||null!=(i=e.decryptdata)&&i.key?e.encrypted||(a=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested))&&this.log("[eme] blocking frag sn: "+e.sn+" load until media-keys acquired"):(this.log("Loading key for "+e.sn+" of ["+t.startSN+"-"+t.endSN+"], "+this.playlistLabel()+" "+e.level),this.state=On.KEY_LOADING,a=this.keyLoader.load(e,r).then((function(e){if(!n.fragContextChanged(e.frag))return n.hls.trigger(G.KEY_LOADED,e),n.state===On.KEY_LOADING&&(n.state=On.IDLE),e})),this.hls.trigger(G.KEY_LOADING,{frag:e})),a},r._doFragLoad=function(e,t,r,i){var n=this;void 0===r&&(r=null),this.fragCurrent=e;var a=t.details;if(!this.levels||!a)throw new Error("frag load aborted, missing level"+(a?"":" detail")+"s");var s,o=this.fragPrevious;if(!te(e,o)){var l=this.shouldLoadParts(t.details,e.end);l!==this.loadingParts&&(this.log("LL-Part loading "+(l?"ON":"OFF")+" loading sn "+(null==o?void 0:o.sn)+"->"+e.sn),this.loadingParts=l)}if(r=Math.max(e.start,r||0),this.loadingParts){var u=a.partList;if(u&&i){r>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);var d=this.getNextPart(u,e,r);if(d>-1){var h=u[d];if(!te(e=this.fragCurrent=h.fragment,o)&&!this.shouldLoadParts(t.details,e.end))return this.log("LL-Part loading OFF @"+this.playhead+" next part: "+this.fragInfo(e,!1,h)),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(h,t.details))return Promise.resolve(null);var f,c=this.loadKeyFor(e,a);if(this.fragContextChanged(e))return Promise.resolve(null);this.log("Loading "+e.type+" sn: "+e.sn+" part: "+h.index+" ("+d+"/"+(u.length-1)+") of "+this.fragInfo(e,!1,h)+" cc: "+e.cc+" ["+a.startSN+"-"+a.endSN+"], target: "+r+(h.byteRange.length?" range:"+h.byteRange.join("-"):"")),this.nextLoadPosition=h.start+h.duration,this.state=On.FRAG_LOADING;var g=this.loadInitSegmentIfNeeded(e);if(c||g){var v=!!c;f=Promise.all([c,g]).then((function(r){var a=r[0];return!v||a&&!n.fragContextChanged(a.frag)?n.doFragPartsLoad(e,h,t,i):null})).catch((function(e){return n.handleFragLoadError(e)}))}else f=this.doFragPartsLoad(e,h,t,i).catch((function(e){return n.handleFragLoadError(e)}));return this.hls.trigger(G.FRAG_LOADING,{frag:e,part:h,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}if(!e.url||this.loadedEndOfParts(u,r))return Promise.resolve(null)}}if(this.loadingParts)this.log("LL-Part loading OFF after next part miss @"+r+" Check buffer at sn: "+e.sn+" loaded parts: "+(null==(s=a.partList)?void 0:s.filter((function(e){return e.loaded})).map((function(e){return"["+e.start+"-"+e.end+"]"})))),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);var m,p=this.loadInitSegmentIfNeeded(e),y=this.loadKeyFor(e,a,p);if(this.fragContextChanged(e))return this.log("Context changed in KEY_LOADING sn: "+e.sn+" "+e.relurl+" > "+(null==(m=this.fragCurrent)?void 0:m.relurl)),null==p||p.catch((function(){return null})),null==y||y.catch((function(){return null})),Promise.resolve(null);this.log("Loading "+e.type+" sn: "+e.sn+" of "+this.fragInfo(e,!1)+" cc: "+e.cc+" ["+a.startSN+"-"+a.endSN+"], target: "+r+(e.byteRange.length?" range:"+e.byteRange.join("-"):"")),x(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=On.FRAG_LOADING;var E,T=this.config.progressive&&e.type!==$.SUBTITLE;return E=T&&y?y.then((function(t){return!t||n.fragContextChanged(t.frag)?null:n.fragmentLoader.load(e,n.iframesOnly,i,p)})).catch((function(e){return n.handleFragLoadError(e)})):Promise.all([this.fragmentLoader.load(e,this.iframesOnly,T?i:void 0,T?p:void 0),y,p]).then((function(e){var t=e[0];return!T&&i&&i(t),t})).catch((function(e){return n.handleFragLoadError(e)})),this.hls.trigger(G.FRAG_LOADING,{frag:e,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([E,p]).then((function(e){return e[0]}))},r.doFragPartsLoad=function(e,t,r,i){var n=this;return new Promise((function(a,s){var o,l=[],u=null==(o=r.details)?void 0:o.partList,d=function(t){n.fragmentLoader.loadPart(e,t,i).then((function(i){l[t.index]=i;var s=i.part;n.hls.trigger(G.FRAG_LOADED,i);var o=Sn(r.details,e.sn,t.index+1)||An(u,e.sn,t.index+1);if(!o)return a({frag:e,part:s,partsLoaded:l});d(o)})).catch(s)};d(t)}))},r.handleFragLoadError=function(e){if("data"in e){var t=e.data;t.frag&&t.details===U.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===B.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(G.ERROR,t)}else this.hls.trigger(G.ERROR,{type:B.OTHER_ERROR,details:U.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null},r._handleTransmuxerFlush=function(e){var t=this.getCurrentContext(e);if(t&&this.state===On.PARSING){var r=t.frag,i=t.part,n=t.level,a=self.performance.now();r.stats.parsing.end=a,i&&(i.stats.parsing.end=a);var s=this.getLevelDetails(),o=s&&r.sn>s.endSN||this.shouldLoadParts(s,r.end);o!==this.loadingParts&&(this.log("LL-Part loading "+(o?"ON":"OFF")+" after parsing segment ending @"+r.end),this.loadingParts=o),this.updateLevelTiming(r,i,n,e)}else this.fragCurrent||this.state===On.STOPPED||this.state===On.ERROR||(this.state=On.IDLE)},r.shouldLoadParts=function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var r,i=e.partList[0];if(t>=i.end+((null==(r=e.fragmentHint)?void 0:r.duration)||0)&&this.playhead>i.start-i.fragment.duration)return!0}}return!1},r.getCurrentContext=function(e){var t=this.levels,r=this.fragCurrent,i=e.level,n=e.sn,a=e.part;if(null==t||!t[i])return this.warn("Levels object was unset while buffering fragment "+n+" of "+this.playlistLabel()+" "+i+". The current chunk will not be buffered."),null;var s=t[i],o=s.details,l=a>-1?Sn(o,n,a):null,u=l?l.fragment:Tn(o,n,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:l,level:s}):null},r.bufferFragmentData=function(e,t,r,i,n){if(this.state===On.PARSING){ee(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);var a=e.data1,s=e.data2,o=a;if(s&&(o=Et(a,s)),o.length){var l=this.initPTS[t.cc],u=l?-l.baseTime/l.timescale:void 0,d={type:e.type,frag:t,part:r,chunkMeta:i,offset:u,parent:t.type,data:o};if(this.hls.trigger(G.BUFFER_APPENDING,d),e.dropped&&e.independent&&!r){if(n)return;this.flushBufferGap(t)}}}},r.flushBufferGap=function(e){var t=this.media;if(t)if(gi.isBuffered(t,t.currentTime)){var r=t.currentTime,i=gi.bufferInfo(t,r,0),n=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),s=Math.max(Math.min(e.start-a,i.end-a),r+a);e.start-s>a&&this.flushMainBuffer(s,e.start)}else this.flushMainBuffer(0,e.start)},r.getFwdBufferInfo=function(e,t){var r,i=this.playhead,n=this.lastCurrentTime>i||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,n)},r.getFwdBufferInfoAtPos=function(e,t,r,i){var n=gi.bufferInfo(e,t,i);if(0===n.len&&void 0!==n.nextStart){var a=this.fragmentTracker.getBufferedFrag(t,r);if(a&&(n.nextStart<=a.end||a.gap)){var s=Math.max(Math.min(n.nextStart,a.end)-t,i);return gi.bufferInfo(e,t,s)}}return n},r.getMaxBufferLength=function(e){var t,r=this.config;return t=e?Math.max(8*r.maxBufferSize/e,r.maxBufferLength):r.maxBufferLength,Math.min(t,r.maxMaxBufferLength)},r.exceedsMaxBuffer=function(e,t,r){var i=e.nextStart;if(i&&r.start>i){var n=e.buffered;if(n){for(var a=e.len,s=e.bufferedIndex,o=n.length-1;o>s;o--)n[o].start<r.start&&(a+=n[o].end-n[o].start);return a>=t}}return!1},r.reduceMaxBufferLength=function(e,t){var r=this.config,i=Math.max(Math.min(e-t,r.maxBufferLength),t/2),n=Math.max(e-3*t,r.maxMaxBufferLength/2,i);return n>=i&&(r.maxMaxBufferLength=n,this.warn("Reduce max buffer length to "+n+"s"),!0)},r.getAppendedFrag=function(e){var t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return t&&"fragment"in t?t.fragment:t},r.getNextFragment=function(e,t){var r=t.fragments,i=r.length;if(!i)return null;var n=this.config,a=t.fragmentStart,s=n.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=n.initialLiveManifestSize;if(i<l)return this.warn("Not enough fragments to start playback (have: "+i+", need: "+l+")"),null;if(this.startFragRequested||!s||this.loadingParts||(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<a){var u;o=this.getInitialLiveFragment(t);var d,h,f=this.config.startPosition,c=this.hls.startPosition,g=this.hls.liveSyncPosition,v=(null==(u=o)?void 0:u.start)||0;if(-1!==c&&c>=a?(d=c,h=c===f?"config":"next load start"):g?(d=g,h="live edge"):(d=e,h="buffer pos"),d<v&&(d=v,h="live frag start"),d<a&&(d=a,h="playlist start"),this.startPosition!=d||this.nextLoadPosition!=d){var m=t.live&&!this.filterReplacedPrimary(o,t)?-1:d;this.log("Setting startPosition to "+m+" next load "+d+" "+(-1===c?"":"(from "+f+") ")+"based on "+h+". live edge: "+g+" live frag start: "+v+" playlist start: "+a+" buffer pos: "+e),this.startPosition=m,this.nextLoadPosition=d}}}else e<=a&&(o=r[0]);if(!o){var p=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,p,t)}var y=this.filterReplacedPrimary(o,t);return!y&&o&&(y=_r(t,o.sn))&&(this.nextLoadPosition=y.start),y},r.isLoopLoading=function(e,t){if(this.nextLoadPosition<=t)return!1;var r=this.fragmentTracker.getState(e);if(r===Xr)return!0;if(r===qr){if(e.gap)return!0;if(e.stats.retry>1)return!0}return!1},r.getNextFragmentLoopLoading=function(e,t,r,i,n){var a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t))&&!a.gap&&r.nextStart){var s=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i,0);if(null!==s&&r.len+s.len>=n){var o=a.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'+i+'" playlist starting at sn: '+o),this.loopSn=o),null}}return this.loopSn=void 0,a},r.filterReplacedPrimary=function(e,t){if(!e)return e;if(Fn(this.config)&&("type"in e?e:e.fragment).type!==$.SUBTITLE){var r=this.hls.interstitialsManager,i=null==r?void 0:r.bufferingItem;if(i){var n=i.event;if(n){if(!n.appendInPlace&&(Math.abs(e.start-i.start)>1||0===i.start))return null}else{if(e.end<=i.start&&!1===(null==t?void 0:t.live))return null;if(e.start>=i.end&&i.nextEvent&&(i.nextEvent.appendInPlace&&!i.nextEvent.hasPlayed||e.start-i.end>1))return null}}if(xn(e,null==r?void 0:r.playerQueue,this.playhead))return null}return e},r.getNextPart=function(e,t,r){for(var i=-1,n=!1,a=!0,s=0,o=e.length;s<o;s++){var l=e[s];if(a=a&&!l.independent,i>-1&&r<l.start)break;var u=l.loaded||l.gap;u?i=-1:(n||(l.independent||a)&&l.fragment===t)&&(i=s),n=u&&!l.gap}var d=e[i];return d&&d.fragment!==t&&this.log("Need buffer at "+r+" but next unloaded part starts at "+d.start+" (sn: "+t.sn+" -> "+d.fragment.sn+")"),i},r.loadedEndOfParts=function(e,t){for(var r,i=e.length;i--;){if(!(r=e[i]).loaded)return!1;if(t>r.start)return!0}return!1},r.getInitialLiveFragment=function(e){var t=e.fragments,r=this.fragPrevious,i=null;if(r){if(e.hasProgramDateTime&&(i=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!x(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(var i=0;i<e.length;++i){var n=e[i];if(Dr(t,r,n))return n}return null}(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log("Live playlist, switching playlist, load frag with same PDT: "+r.programDateTime)),!i){var n=r.sn+1;if(n>=e.startSN&&n<=e.endSN){var a=t[n-e.startSN];r.cc===a.cc&&(i=a,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=Pr(e,r.cc,r.end))&&this.log("Live playlist, switching playlist, load frag with same CC: "+i.sn)}}else{var s=this.hls.liveSyncPosition;null!==s&&(i=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i},r.getFragmentAtPosition=function(e,t,r){var i,n,a=this.config,s=this.fragPrevious,o=r.fragments,l=r.endSN,u=r.fragmentHint,d=a.maxFragLookUpTolerance,h=r.partList,f=!!(this.loadingParts&&null!=h&&h.length&&u);if(f&&!this.bitrateTest&&h[h.length-1].fragment.sn===u.sn&&(o=o.concat(u),l=u.sn),s&&this.fragmentTracker.getState(s)===jr&&(s=null),i=e<t?br(s,o,e,e<this.lastCurrentTime||e>t-d||null!=(n=this.media)&&n.paused||!this.startFragRequested?0:d):o[o.length-1]){var c=i.sn-r.startSN,g=this.fragmentTracker.getState(i);if((g===Xr||g===qr&&i.gap)&&(s=i),te(i,s)&&(!f||h[0].fragment.sn>i.sn||!r.live)){var v=o[c+1];i=i.sn<l&&this.fragmentTracker.getState(v)!==Xr?v:null}}return i},r.alignPlaylists=function(e,t,r){var i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;var n=e.fragmentStart,a=!t,s=e.alignedSliding&&x(n);if(a||!s&&!n){Pn(r,e,this);var o=e.fragmentStart;return this.log("Live playlist sliding: "+o+" start-sn: "+(t?t.startSN:"na")+"->"+e.startSN+" fragments: "+i),o}return n},r.waitForCdnTuneIn=function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)},r.setStartPosition=function(e,t){var r=this.startPosition;r<t&&(r=-1);var i=this.timelineOffset;if(-1===r){var n=null!==this.startTimeOffset,a=n?this.startTimeOffset:e.startTimeOffset;if(null!==a&&x(a))r=t+a,a<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log("Setting startPosition to "+r+" for start time offset "+a+" found in "+(n?"multivariant":"media")+" playlist"),this.startPosition=r;else if(e.live){var s=this.hls.liveSyncPosition;r=s||t,this.log("Setting startPosition to -1 to start at "+(s?"live edge":"playlist start")+" "+r),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=r=0;this.lastCurrentTime=r+i}this.nextLoadPosition=r+i},r.getLoadPosition=function(){var e,t=this.media,r=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t&&!this.iframesOnly?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r},r.handleFragLoadAborted=function(e,t){this.transmuxer&&e.type===this.playlistType&&ee(e)&&e.stats.aborted&&(this.log("Fragment "+e.sn+(t?" part "+t.index:"")+" of "+this.playlistLabel()+" "+e.level+" was aborted"),this.resetFragmentLoading(e))},r.resetFragmentLoading=function(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===On.FRAG_LOADING_WAITING_RETRY)||(this.state=On.IDLE)},r.onFragmentOrKeyLoadError=function(e,t){if(t.chunkMeta&&!t.frag){var r=this.getCurrentContext(t.chunkMeta);r&&(t.frag=r.frag)}var i=t.frag,n=t.part;if(i&&this.levels&&i.type===e)if(this.fragContextChanged(i)){var a;this.warn("Frag load error must match current frag to retry "+i.relurl+" > "+(null==(a=this.fragCurrent)?void 0:a.relurl))}else{var s=t.details===U.FRAG_GAP;s&&this.fragmentTracker.addAsGap(i);var o=t.errorAction;if(o){var l=o.action,u=o.flags,d=o.retryCount,h=void 0===d?0:d,f=o.retryConfig,c=!!f,g=c&&l===Mr,v=c&&!o.resolved&&u&Fr,m=this.hls.latestLevelDetails,p=null==m?void 0:m.live;if(!g&&v&&ee(i)&&p&&i.sn<m.endSN&&!le(t))this.resetFragmentErrors(e),n?n.gap=!0:this.treatAsGap(i),o.resolved=!0;else if((g||v)&&h<f.maxNumRetry){var y,E=ce(null==(y=t.response)?void 0:y.code),T=de(f,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+T,this.state=On.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,E)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn("Fragment "+i.sn+" of "+e+" "+i.level+" errored with "+t.details+", retrying loading "+(h+1)+"/"+f.maxNumRetry+" in "+T+"ms")}else if(f){if(this.resetFragmentErrors(e),!(h<f.maxNumRetry))return void this.warn(t.details+" reached or exceeded max retry ("+h+")");s||l===Or||(o.resolved=!0)}else this.state=l===wr?On.WAITING_LEVEL:On.ERROR;this.tickImmediate()}else this.state=On.ERROR}},r.checkRetryDate=function(){var e=self.performance.now(),t=this.retryDate,r=t===1/0;(!t||e>=t||r&&!ce(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=On.IDLE)},r.reduceLengthAndFlushBuffer=function(e){if(this.state===On.PARSING||this.state===On.PARSED){var t=e.frag,r=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,r),n=i&&i.len>.5;n&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);var a=!n;return a?this.warn("Buffer full error while media.currentTime ("+this.playhead+") is not buffered, flush "+r+" buffer"):i.nextStart&&t&&i.nextStart>t.start&&this.flushMainBuffer(i.nextStart,Number.POSITIVE_INFINITY,r===$.AUDIO?r:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1},r.resetFragmentErrors=function(e){e===$.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==On.STOPPED&&(this.state=On.IDLE)},r.afterBufferFlushed=function(e,t){if(e){var r=gi.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,this.playlistType),this.state===On.ENDED&&this.resetLoadingState()}},r.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==On.STOPPED&&(this.state=On.IDLE)},r.resetStartWhenNotLoaded=function(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;var e=this.getLevelDetails();null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}},r.resetWhenMissingContext=function(e){this.log("Loading context changed while buffering sn "+e.sn+" of "+this.playlistLabel()+" "+(-1===e.level?"<removed>":e.level)+". This chunk will not be buffered."),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()},r.removeUnbufferedFrags=function(e){void 0===e&&(e=0),this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)},r.updateLevelTiming=function(e,t,r,i){var n=this,a=r.details;if(a){if(this.log("update level timing "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+this.fragInfo(e,!1,t)),!Object.keys(e.elementaryStreams).reduce((function(t,s){var o=e.elementaryStreams[s];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return n.warn("Could not parse fragment "+e.sn+" "+s+" duration reliably ("+l+")"),t||!1;var u=i.partial?0:vn(a,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,n.iframesOnly,n);return n.hls.trigger(G.LEVEL_PTS_UPDATED,{details:a,level:r,drift:u,type:s,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t}),!1)){var s,o,l,u,d=null===(null==(s=this.transmuxer)?void 0:s.error),h=null!=(null==(o=this.transmuxer)?void 0:o.error),f=(null!=(l=null==(u=this.levels)?void 0:u.length)?l:0)>1;if((0===r.fragmentError||d&&(r.fragmentError<2||e.endList)||h&&f)&&this.treatAsGap(e,r),d){var c=new Error("Found no media in "+this.playlistLabel()+" "+e.level+" "+(t?"part: "+t.index+" of ":"")+"sn: "+e.sn+" at playlist time: "+e.start+". Resetting transmuxer to fallback to playlist timing");if(this.warn(c.message),this.hls.trigger(G.ERROR,{type:B.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,fatal:!1,error:c,frag:e,reason:"Found no media in msn "+e.sn+" of "+this.playlistLabel()+' "'+r.url+'"'}),!this.hls)return;this.resetTransmuxer()}}this.state=On.PARSED,this.log("Parsed "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+this.fragInfo(e,!1,t)),this.hls.trigger(G.FRAG_PARSED,{frag:e,part:t,chunkMeta:i})}else this.warn("level.details undefined")},r.playlistLabel=function(){return this.playlistType+" playlist"},r.fragInfo=function(e,t,r){var i,n;return void 0===t&&(t=!0),this.playlistLabel()+" "+e.level+" ("+(r?"part":"frag")+":["+(null!=(i=t&&!r?e.startPTS:(r||e).start)?i:NaN)+"-"+(null!=(n=t&&!r?e.endPTS:(r||e).end)?n:NaN)+"]"+(r&&"main"===e.type?"INDEPENDENT="+(r.independent?"YES":"NO"):"")+")"},r.treatAsGap=function(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)},r.resetTransmuxer=function(){var e;null==(e=this.transmuxer)||e.reset()},r.isFragmentNearlyDownloaded=function(e){var t,r=null==(t=e.loader)?void 0:t.stats;if(!r)return!1;var i=r.loading.first>0,n=(r.total-r.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return i&&n<=.15},r.recoverWorkerError=function(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())},r.calculateOptimalSwitchPoint=function(e,t){var r=0,i=this.hls,n=this.media,a=this.config,s=this.levels,o=this.playlistType,l=this.getLevelDetails();if(n&&!n.paused&&s){var u,d=o===$.AUDIO?er(e.audioCodec,128e3):e.maxBitrate,h=1+i.ttfbEstimate/1e3,f=i.bandwidthEstimate*a.abrBandWidthUpFactor;r=h+d*(l&&(this.loadingParts?l.partTarget:l.averagetargetduration)||(null==(u=this.fragCurrent)?void 0:u.duration)||6)/f,e.details||(r+=h)}var c=this.playhead;return{fetchdelay:r,okToFlushForwardBuffer:!(null!=l&&l.live)||t.end-c>1.5*r}},r.scheduleTrackSwitch=function(e,t,r){var i=this.media,n=this.playlistType;if(i&&e){var a=r?this.getBufferedFrag(this.playhead+t):null;if(a){var s=this.followingBufferedFrag(a);if(s){var o;this.abortCurrentFrag();var l=s.maxStartPTS?s.maxStartPTS:s.start,u=s.duration,d=Math.max(a.end,l+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));if(((null==(o=this.getLevelDetails())?void 0:o.fragmentStart)||0)>d)return;var h=n===$.MAIN?null:"audio";this.flushMainBuffer(d,Number.POSITIVE_INFINITY,h),this.cleanupBackBuffer()}}}},r.cleanupBackBuffer=function(){var e=this.media,t=this.playlistType;if(e){var r=this.getAppendedFrag(this.playhead);if(r&&r.start>1){var i=t===$.AUDIO;this.flushMainBuffer(0,r.start-(i?0:1),i?"audio":null)}}},r.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)},r.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.end+.5):null},r.abortCurrentFrag=function(){var e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case On.KEY_LOADING:case On.FRAG_LOADING:case On.FRAG_LOADING_WAITING_RETRY:case On.PARSING:case On.PARSED:this.state=On.IDLE}this.nextLoadPosition=this.playhead},r.checkFragPlaying=function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var r=e.currentTime;if(gi.isBuffered(e,r)?t=this.getAppendedFrag(r):gi.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t&&(this.backtrackFragment=void 0,!te(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1},r.getBufferOutput=function(){return null},r.nextLevelSwitch=function(){var e=this.levels,t=this.media,r=this.hls,i=this.config,n=this.playlistType;if(null!=t&&t.readyState&&e&&r&&i){var a=this.getBufferOutput(),s=this.getFwdBufferInfo(a,n);if(!s)return;var o=e[n===$.AUDIO?r.nextAudioTrack:r.nextLoadLevel],l=this.calculateOptimalSwitchPoint(o,s),u=l.fetchdelay,d=l.okToFlushForwardBuffer;this.scheduleTrackSwitch(s,u,d)}this.tickImmediate()},a(t,[{key:"startPositionValue",get:function(){var e=this.nextLoadPosition,t=this.startPosition;if(-1===t&&e){var r=this.getLevelDetails();return null!=r&&r.live?(this.hls.liveSyncPosition||r.fragmentStart)+this.timelineOffset:e}return t}},{key:"bufferingEnabled",get:function(){return this.buffering}},{key:"backtrackFragment",get:function(){},set:function(e){}},{key:"couldBacktrack",get:function(){return!1},set:function(e){}},{key:"inFlightFrag",get:function(){return{frag:this.fragCurrent,state:this.state}}},{key:"timelineOffset",get:function(){var e,t=this.config.timelineOffset;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}},{key:"primaryPrefetch",get:function(){var e;return!(!Fn(this.config)||!(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event))}},{key:"playhead",get:function(){var e;if(null!=(e=this.hls)&&e.hasEnoughToStart){var t,r=null==(t=this.media)?void 0:t.currentTime;return x(r)?r:this.lastCurrentTime}return this.getLoadPosition()}},{key:"iframesOnly",get:function(){var e;if(this.playlistType!==$.MAIN)return!1;var t=this.getLevelDetails();return t?t.iframesOnly:null==(e=this.levelLastLoaded)?void 0:e.iframes}},{key:"state",get:function(){return this._state},set:function(e){var t=this._state;t!==e&&(this._state=e,this.log(t+"->"+e))}}])}(hi);function xn(e,t,r){if(t)for(var i=t.length;i--;){var n=t[i].interstitial,a=n.startTime,s=Math.min(a+n.duration,n.resumeTime);if(n.appendInPlace){if(e.start>=a&&e.end<=s)return!0;if(r>e.start&&e.end>a&&e.start<s)return!0}}return!1}function Fn(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}var Nn=function(){function e(){this.chunks=[],this.dataLength=0}var t=e.prototype;return t.push=function(e){this.chunks.push(e),this.dataLength+=e.length},t.flush=function(){var e,t=this.chunks,r=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var r=new Uint8Array(t),i=0,n=0;n<e.length;n++){var a=e[n];r.set(a,i),i+=a.length}return r}(t,r),this.reset(),e):new Uint8Array(0)},t.reset=function(){this.chunks.length=0,this.dataLength=0},e}();function Bn(e,t){return 255===e[t]&&240==(246&e[t+1])}function Un(e,t){return 1&e[t+1]?7:9}function Gn(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function Kn(e,t){return t+1<e.length&&Bn(e,t)}function Vn(e,t){if(Kn(e,t)){var r=Un(e,t);if(t+r>=e.length)return!1;var i=Gn(e,t);if(i<=r)return!1;var n=t+i;return n===e.length||Kn(e,n)}return!1}function Hn(e,t,r,i,n){if(!e.samplerate){var a=function(e,t,r,i){var n=t[r+2],a=n>>2&15;if(!(a>12)){var s,o=1+(n>>6&3),l=t[r+3]>>6&3|(1&n)<<2,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],d=a;5!==o&&29!==o||(d-=3);var h=(14&d)>>1,f=(1&d)<<7|l<<3,c=0;if(1===o&&a>=6){var g=a-3;s=[(c=5)<<3|h,f|(14&g)>>1,(1&g)<<7|8,0]}else s=[o<<3|h,f];var v="mp4a.40."+(c||o);return Le.log("manifest codec:"+i+", parsed codec:"+v+", channels:"+l+", rate:"+u+" (ADTS object type:"+o+" sampling index:"+a+" esds config:["+s.join(",")+"])"),{config:s,samplerate:u,channelCount:l,codec:v,parsedCodec:v,manifestCodec:i}}var m=new Error("invalid ADTS sampling index:"+a);e.emit(G.ERROR,G.ERROR,{type:B.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,fatal:!0,error:m,reason:m.message})}(t,r,i,n);if(!a)return;l(e,a)}}function Yn(e){return 9216e4/e}function jn(e,t,r,i,n){var a,s=i+n*Yn(e.samplerate),o=function(e,t){var r=Un(e,t);if(t+r<=e.length){var i=Gn(e,t)-r;if(i>0)return{headerLength:r,frameLength:i}}}(t,r);if(o){var l=o.frameLength,u=o.headerLength,d=u+l,h=Math.max(0,r+d-t.length);h?(a=new Uint8Array(d-u)).set(t.subarray(r+u,t.length),0):a=t.subarray(r+u,r+d);var f={unit:a,pts:s};return h||e.samples.push(f),{sample:f,length:d,missing:h}}var c=t.length-r;return(a=new Uint8Array(c)).set(t.subarray(r,t.length),0),{sample:{unit:a,pts:s},length:c,missing:-1}}var Wn=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}({});function qn(e,t){return void 0===e&&(e=""),void 0===t&&(t=9e4),{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}var Xn=function(){function e(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}var t=e.prototype;return t.resetInitSegment=function(e,t,r,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},t.resetTimeStamp=function(e){this.initPTS=e,this.resetContiguity()},t.resetContiguity=function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0},t.canParse=function(e,t){return!1},t.appendFrame=function(e,t,r){},t.demux=function(e,t){this.cachedData&&(e=Et(this.cachedData,e),this.cachedData=null);var r,i=Ce(e,0),n=i?i.length:0,a=this._audioTrack,s=this._id3Track,o=i?Ve(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&x(o))&&(this.basePTS=zn(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Wn.audioId3,duration:Number.POSITIVE_INFINITY});n<l;){if(this.canParse(e,n)){var u=this.appendFrame(a,e,n);u?(this.frameIndex++,this.lastPTS=u.sample.pts,r=n+=u.length):n=l}else Pe(e,n)?(i=Ce(e,n),s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Wn.audioId3,duration:Number.POSITIVE_INFINITY}),r=n+=i.length):n++;if(n===l&&r!==l){var d=e.slice(r);this.cachedData?this.cachedData=Et(this.cachedData,d):this.cachedData=d}}return{audioTrack:a,videoTrack:qn(),id3Track:s,textTrack:qn()}},t.demuxSampleAes=function(e,t,r){return Promise.reject(new Error("["+this+"] This demuxer does not support Sample-AES decryption"))},t.flush=function(e){var t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:qn(),id3Track:this._id3Track,textTrack:qn()}},t.destroy=function(){this.cachedData=null,this._audioTrack=this._id3Track=void 0},e}(),zn=function(e,t,r){return x(e)?90*e:9e4*t+(r?9e4*r.baseTime/r.timescale:0)},Qn=[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],$n=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Zn=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Jn=[0,1,1,4];function ea(e,t,r,i,n){if(!(r+24>t.length)){var a=ta(t,r);if(a&&r+a.frameLength<=t.length){var s=i+n*(9e4*a.samplesPerFrame/a.sampleRate),o={unit:t.subarray(r,r+a.frameLength),pts:s,dts:s};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(o),{sample:o,length:a.frameLength,missing:0}}}}function ta(e,t){var r=e[t+1]>>3&3,i=e[t+1]>>1&3,n=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==r&&0!==n&&15!==n&&3!==a){var s=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Qn[14*(3===r?3-i:3===i?3:4)+n-1],u=$n[3*(3===r?0:2===r?1:2)+a],d=3===o?1:2,h=Zn[r][i],f=Jn[i],c=8*h*f,g=Math.floor(h*l/u+s)*f,v=Ot();return!!v&&v<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:u,channelCount:d,frameLength:g,samplesPerFrame:c}}}function ra(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])}function ia(e,t){return t+1<e.length&&ra(e,t)}function na(e,t){if(t+1<e.length&&ra(e,t)){var r=ta(e,t),i=4;null!=r&&r.frameLength&&(i=r.frameLength);var n=t+i;return n===e.length||ia(e,n)}return!1}var aa=function(){function e(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new ni(t,!0)}var t=e.prototype;return t.decryptBuffer=function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Jr,{start:0,end:e.byteLength})},t.decryptAacSample=function(e,t,r){var i=this,n=e[t].unit;if(!(n.length<=16)){var a=n.subarray(16,n.length-n.length%16),s=a.buffer.slice(a.byteOffset,a.byteOffset+a.length);this.decryptBuffer(s).then((function(a){var s=new Uint8Array(a);n.set(s,16),i.decrypter.isSync()||i.decryptAacSamples(e,t+1,r)})).catch(r)}},t.decryptAacSamples=function(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32||(this.decryptAacSample(e,t,r),this.decrypter.isSync())))return}},t.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,n=32;n<e.length-16;n+=160,i+=16)r.set(e.subarray(n,n+16),i);return r},t.getAvcDecryptedUnit=function(e,t){for(var r=new Uint8Array(t),i=0,n=32;n<e.length-16;n+=160,i+=16)e.set(r.subarray(i,i+16),n);return e},t.decryptAvcSample=function(e,t,r,i,n){var a=this,s=It(n.data),o=this.getAvcEncryptedData(s);this.decryptBuffer(o.buffer).then((function(o){n.data=a.getAvcDecryptedUnit(s,o),a.decrypter.isSync()||a.decryptAvcSamples(e,t,r+1,i)})).catch(i)},t.decryptAvcSamples=function(e,t,r,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length)return void i();for(var n=e[t].units;!(r>=n.length);r++){var a=n[r];if(!(a.data.length<=48||1!==a.type&&5!==a.type||(this.decryptAvcSample(e,t,r,i,a),this.decrypter.isSync())))return}}},e}(),sa=function(e){function t(t,r){var i;return(i=e.call(this)||this).observer=void 0,i.config=void 0,i.sampleAes=null,i.observer=t,i.config=r,i}d(t,e);var r=t.prototype;return r.resetInitSegment=function(t,r,i,n){e.prototype.resetInitSegment.call(this,t,r,i,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}},t.probe=function(e,t){if(!e)return!1;var r=Ce(e,0),i=(null==r?void 0:r.length)||0;if(na(e,i))return!1;for(var n=e.length;i<n;i++)if(Vn(e,i))return t.log("ADTS sync word found !"),!0;return!1},r.canParse=function(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&Bn(e,t)&&Gn(e,t)<=e.length-t}(e,t)},r.appendFrame=function(e,t,r){Hn(e,this.observer,t,r,e.manifestCodec);var i=jn(e,t,r,this.basePTS,this.frameIndex);if(0===(null==i?void 0:i.missing))return i},r.demuxSampleAes=function(e,t,r){var i=this.demux(e,r),n=this.sampleAes=new aa(this.observer,this.config,t);return new Promise((function(e){n.decryptAacSamples(i.audioTrack.samples,0,(function(){e(i)}))}))},t}(Xn),oa=function(e,t){var r=0,i=5;t+=i;for(var n=new Uint32Array(1),a=new Uint32Array(1),s=new Uint8Array(1);i>0;){s[0]=e[t];var o=Math.min(i,8),l=8-o;a[0]=4278190080>>>24+l<<l,n[0]=(s[0]&a[0])>>l,r=r?r<<o|n[0]:n[0],t+=1,i-=o}return r},la=function(e){function t(t){var r;return(r=e.call(this)||this).observer=void 0,r.observer=t,r}d(t,e);var r=t.prototype;return r.resetInitSegment=function(t,r,i,n){e.prototype.resetInitSegment.call(this,t,r,i,n),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}},r.canParse=function(e,t){return t+64<e.length},r.appendFrame=function(e,t,r){var i=ua(e,t,r,this.basePTS,this.frameIndex);if(-1!==i)return{sample:e.samples[e.samples.length-1],length:i,missing:0}},t.probe=function(e){if(!e)return!1;var t=Ce(e,0);if(!t)return!1;var r=t.length;if(11===e[r]&&119===e[r+1]&&void 0!==Ve(t)){if(oa(e,r)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1},t}(Xn);function ua(e,t,r,i,n){if(r+8>t.length)return-1;if(11!==t[r]||119!==t[r+1])return-1;var a=t[r+4]>>6;if(a>=3)return-1;var s=[48e3,44100,32e3][a],o=63&t[r+4],l=2*[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][3*o+a];if(r+l>t.length)return-1;var u=t[r+6]>>5,d=0;2===u?d+=2:(1&u&&1!==u&&(d+=2),4&u&&(d+=2));var h=(t[r+6]<<8|t[r+7])>>12-d&1,f=[2,1,2,3,3,4,4,5][u]+h,c=t[r+5]>>3,g=7&t[r+5],v=new Uint8Array([a<<6|c<<1|g>>2,(3&g)<<6|u<<3|h<<2|o>>4,o<<4&224]),m=i+n*(1536/s*9e4),p=t.subarray(r,r+l);return e.config=v,e.channelCount=f,e.samplerate=s,e.samples.push({unit:p,pts:m}),l}var da=function(e){function t(){return e.apply(this,arguments)||this}d(t,e);var r=t.prototype;return r.resetInitSegment=function(t,r,i,n){e.prototype.resetInitSegment.call(this,t,r,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}},t.probe=function(e){if(!e)return!1;var t=Ce(e,0),r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==Ve(t)&&oa(e,r)<=16)return!1;for(var i=e.length;r<i;r++)if(na(e,r))return Le.log("MPEG Audio sync word found !"),!0;return!1},r.canParse=function(e,t){return function(e,t){return ra(e,t)&&4<=e.length-t}(e,t)},r.appendFrame=function(e,t,r){if(null!==this.basePTS)return ea(e,t,r,this.basePTS,this.frameIndex)},t}(Xn),ha=/\/emsg[-/]ID3/i,fa=function(){function e(e,t,r,i){void 0===i&&(i=Le),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.initData=void 0,this.logger=void 0,this.config=t,this.logger=i}var t=e.prototype;return t.resetTimeStamp=function(){},t.resetInitSegment=function(e,t,r,i){var n=this.videoTrack=qn("video",1),a=this.audioTrack=qn("audio",1),s=this.txtTrack=qn("text",1);if(this.id3Track=qn("id3",1),this.initData=void 0,this.timeOffset=0,null!=e&&e.byteLength){var o=this.initData=ut(e);if(o.video){var l=o.video,u=l.id,d=l.timescale,h=l.codec,f=l.supplemental;n.id=u,n.timescale=s.timescale=d,n.codec=h,n.supplemental=f}if(o.audio){var c=o.audio,g=c.id,v=c.timescale,m=c.codec;a.id=g,a.timescale=v,a.codec=m}s.id=Qe.text,n.sampleDuration=0,n.duration=a.duration=i}},t.resetContiguity=function(){this.remainderData=null},e.probe=function(e){return function(e,t){for(var r=e.byteLength,i=0;i<r;){var n=Ze(e,i);if(n>8&&Ze(e,i+4)===ze[t])return!0;i=n>1?i+n:r}return!1}(e,"moof")},t.demux=function(e,t,r){this.timeOffset=t;var i=e,n=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Et(this.remainderData,e));var s=function(e){var t={valid:null,remainder:null},r=st(e,["moof"]);if(r.length<2)return t.remainder=e,t;var i=r[r.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}(i);this.remainderData=s.remainder,n.samples=s.valid||new Uint8Array}else n.samples=i;var o=this.extractID3Track(n,t),l=this.parseFragment(n,a,t,r);return{videoTrack:n,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}},t.flush=function(e,t){var r=this.timeOffset,i=this.videoTrack,n=this.txtTrack;i.samples=this.remainderData||new Uint8Array,this.remainderData=null;var a=this.extractID3Track(i,this.timeOffset),s=this.parseFragment(i,n,r,t);return{videoTrack:i,audioTrack:qn(),id3Track:a,textTrack:qn(),initData:this.initData,sampleData:s}},t.parseFragment=function(e,t,r,i){var n=this.initData;if(n&&i){var a=function(e,t,r,i,n){void 0===n&&(n=!1);var a=[];return{samples:a,sampleData:{includeSampleDetails:n,tracks:yt(t.samples,r,i,n,{isHEVCFlavor:Tt(t.codec),samples:a,timeOffset:e,timescale:t.timescale,trackId:t.id})}}}(r,e,n,this.logger,i.iframe),s=a.samples,o=a.sampleData;return t.samples=s,o}t.samples=function(e,t){var r=[],i=t.samples,n=t.timescale,a=t.id,s=!1;return st(i,["moof"]).map((function(o){var l=o.byteOffset-8;st(o,["traf"]).map((function(o){var u=st(o,["tfdt"]).map((function(e){var t=e[0],r=Ze(e,4);return 1===t&&(r*=Math.pow(2,32),r+=Ze(e,8)),r/n}))[0];return void 0!==u&&(e=u),st(o,["tfhd"]).map((function(u){var d=Ze(u,4),h=16777215&Ze(u,0),f=0!=(1&h),c=0,g=0!=(2&h),v=0!=(8&h),m=0,p=0!=(16&h),y=0,E=0!=(32&h),T=!f&&0!=(131072&h),S=8;d===a&&(f?(c=Ze(u,S),S+=4,c*=Math.pow(2,32),c+=Ze(u,S),S+=4):T&&(c=l),g&&(S+=4),v&&(m=Ze(u,S),S+=4),p&&(y=Ze(u,S),S+=4),E&&(S+=4),"video"===t.type&&(s=Tt(t.codec)),st(o,["trun"]).map((function(a){var o=a[0],l=16777215&Ze(a,0),u=0!=(1&l),d=0,h=0!=(4&l),f=0!=(256&l),g=0,v=0!=(512&l),p=0,E=0!=(1024&l),T=0!=(2048&l),S=0,A=Ze(a,4),I=8;u&&(d=Ze(a,I),I+=4),h&&(I+=4);for(var L=c+d,R=0;R<A;R++){if(f?(g=Ze(a,I),I+=4):g=m,v?(p=Ze(a,I),I+=4):p=y,E&&(I+=4),T&&(S=0===o?Ze(a,I):tt(a,I),I+=4),t.type===Z.VIDEO)for(var b=0;b<p;){var k=Ze(i,L);St(s,i[L+=4])&&At(i.subarray(L,L+k),s?2:1,e+S/n,r),L+=k,b+=k+4}e+=g/n}})))}))}))})),r}(r,e)},t.extractID3Track=function(e,t){var r=this,i=this.id3Track;if(e.samples.length){var n=st(e.samples,["emsg"]);n&&n.forEach((function(e){var n=function(e){var t,r=e[0],i="",n="",a=0,s=0,o=0,l=0,u=4;if(0===r){var d=et(e,u),h=null!==d?et(e,u+d.length):null;null!==d&&null!==h?(i=d,n=h,a=Ze(e,u+=d.length+h.length),s=Ze(e,u+=4),o=Ze(e,u+=4),l=Ze(e,u+=4),u+=4):(Le.warn("Unterminated "+(null===d?"scheme_id_uri":"value")+" in parsing emsg box: version 0 box ends inside a string, dropping all of its fields"),u=e.length)}else if(1===r){a=Ze(e,u);var f=Ze(e,u+=4),c=Ze(e,u+=4);u+=4,t=Math.pow(2,32)*f+c,F(t)||(t=Number.MAX_SAFE_INTEGER,Le.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Ze(e,u),l=Ze(e,u+=4);var g=et(e,u+=4),v=null!==g?et(e,u+g.length):null;null!==g&&(i=g,u+=g.length),null!==v?(n=v,u+=v.length):(Le.warn("Unterminated "+(null===g?"scheme_id_uri":"value")+" in parsing emsg box: version 1 box ends inside a string, dropping its "+(null===g?"strings and payload":"value and payload")),u=e.length)}return{schemeIdUri:i,value:n,timeScale:a,presentationTime:t,presentationTimeDelta:s,eventDuration:o,id:l,payload:e.subarray(u,e.byteLength)}}(e);if(ha.test(n.schemeIdUri)){var a=ca(n,t),s=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);var o=n.payload;i.samples.push({data:o,len:o.byteLength,dts:a,pts:a,type:Wn.emsg,duration:s})}else if(r.config.enableEmsgKLVMetadata){var l=r.config.emsgKLVSchemaUri||Wn.misbklv;if(n.schemeIdUri.startsWith(l)){var u=ca(n,t);i.samples.push({data:n.payload,len:n.payload.byteLength,dts:u,pts:u,type:Wn.misbklv,duration:Number.POSITIVE_INFINITY})}}}))}return i},t.demuxSampleAes=function(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},t.destroy=function(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0},e}();function ca(e,t){return x(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var ga=function(){function e(){this.VideoSample=null}var t=e.prototype;return t.createVideoSample=function(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}},t.getLastNalUnit=function(e){var t,r,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){var n=i.units;r=n[n.length-1]}return r},t.pushAccessUnit=function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var r=t.samples,i=r.length;if(!i)return void t.dropped++;var n=r[i-1];e.pts=n.pts,e.dts=n.dts}t.samples.push(e)}},t.parseNALu=function(e,t,r){var i=t.byteLength;if(0===i)return[];var n=e.naluState||0,a=-1===n?0:n,s=[],o=0,l=0,u=-1,d=0;for(-1===n&&(u=0,d=this.getNALuType(t,0),l=1);l<i;){var h=t.indexOf(1,l);if(-1===h)break;l=h+1;for(var f=h;f>0&&0===t[f-1];)f--;if(!(h-f+(0===f?a:0)<2)){if(u>=0)s.push({data:t.subarray(u,f),type:d});else{var c=this.getLastNalUnit(e.samples);c&&(f>0?c.data=Et(c.data,t.subarray(0,f)):a>0&&(c.data=c.data.subarray(0,c.data.byteLength-a)),c.state=0)}if(!(l<i)){o=-1,u=-1;break}u=l,d=this.getNALuType(t,l)}}if(-1!==o){for(var g=i;g>0&&0===t[g-1];)g--;o=i-g+(0===g?a:0)}if(u>=0)s.push({data:t.subarray(u),type:d,state:o});else if(0===s.length&&-1!==o){var v=this.getLastNalUnit(e.samples);v&&(v.data=Et(v.data,t),v.state=o)}return e.naluState=o,s},e}(),va=function(){function e(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}var t=e.prototype;return t.loadWord=function(){var e=this.data,t=this.bytesAvailable,r=e.byteLength-t,i=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");i.set(e.subarray(r,r+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n},t.skipBits=function(e){var t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)},t.readBits=function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;if(e>32&&Le.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(t=e-t)>0&&this.bitsAvailable?r<<t|this.readBits(t):r},t.skipLZ=function(){var e;for(e=0;e<this.bitsAvailable;++e)if(0!=(this.word&2147483648>>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()},t.skipUEG=function(){this.skipBits(1+this.skipLZ())},t.skipEG=function(){this.skipBits(1+this.skipLZ())},t.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},t.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},t.readBoolean=function(){return 1===this.readBits(1)},t.readUByte=function(){return this.readBits(8)},e}(),ma=function(e){function t(){return e.apply(this,arguments)||this}d(t,e);var r=t.prototype;return r.parsePES=function(e,t,r,i,n){var a,s=this,o=n.iframe,l=this.parseNALu(e,r.data,i),u=this.VideoSample,d=!1;r.data=null,u&&l.length&&!e.audFound&&(this.pushAccessUnit(u,e),u=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),l.forEach((function(i){var n,l;switch(i.type){case 1:if(o)break;var h=!1;a=!0;var f,c=i.data;if(d&&c.length>4){var g=s.readSliceType(c);2!==g&&4!==g&&7!==g&&9!==g||(h=!0)}h&&null!=(f=u)&&f.frame&&!u.key&&(s.pushAccessUnit(u,e),u=s.VideoSample=null),u||(u=s.VideoSample=s.createVideoSample(!0,r.pts,r.dts)),u.frame=!0,u.key=h;break;case 5:a=!0,null!=(n=u)&&n.frame&&!u.key&&(s.pushAccessUnit(u,e),u=s.VideoSample=null),u||(u=s.VideoSample=s.createVideoSample(!0,r.pts,r.dts)),u.key=!0,u.frame=!0;break;case 6:if(o)break;a=!0,At(i.data,1,r.pts,t.samples);break;case 7:var v,m;a=!0,d=!0;var p=i.data,y=s.readSPS(p);if(!e.sps||e.width!==y.width||e.height!==y.height||(null==(v=e.pixelRatio)?void 0:v[0])!==y.pixelRatio[0]||(null==(m=e.pixelRatio)?void 0:m[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[p];for(var E=p.subarray(1,4),T="avc1.",S=0;S<3;S++){var A=E[S].toString(16);A.length<2&&(A="0"+A),T+=A}e.codec=T}break;case 8:a=!0,e.pps=[i.data];break;case 9:a=!0,e.audFound=!0,null!=(l=u)&&l.frame&&(s.pushAccessUnit(u,e),u=null),u||(u=s.VideoSample=s.createVideoSample(!1,r.pts,r.dts));break;case 12:a=!0;break;default:a=!1}u&&a&&u.units.push(i)})),i&&u&&(this.pushAccessUnit(u,e),this.VideoSample=null)},r.getNALuType=function(e,t){return 31&e[t]},r.readSliceType=function(e){var t=new va(e);return t.readUByte(),t.readUEG(),t.readUEG()},r.skipScalingList=function(e,t){for(var r=8,i=8,n=0;n<e;n++)0!==i&&(i=(r+t.readEG()+256)%256),r=0===i?r:i},r.readSPS=function(e){var t,r,i,n=new va(e),a=0,s=0,o=0,l=0,u=n.readUByte.bind(n),d=n.readBits.bind(n),h=n.readUEG.bind(n),f=n.readBoolean.bind(n),c=n.skipBits.bind(n),g=n.skipEG.bind(n),v=n.skipUEG.bind(n),m=this.skipScalingList.bind(this);u();var p=u();if(d(5),c(3),u(),v(),100===p||110===p||122===p||244===p||44===p||83===p||86===p||118===p||128===p){var y=h();if(3===y&&c(1),v(),v(),c(1),f())for(r=3!==y?8:12,i=0;i<r;i++)f()&&m(i<6?16:64,n)}v();var E=h();if(0===E)h();else if(1===E)for(c(1),g(),g(),t=h(),i=0;i<t;i++)g();v(),c(1);var T=h(),S=h(),A=d(1);0===A&&c(1),c(1),f()&&(a=h(),s=h(),o=h(),l=h());var I=[1,1];if(f()&&f())switch(u()){case 1:I=[1,1];break;case 2:I=[12,11];break;case 3:I=[10,11];break;case 4:I=[16,11];break;case 5:I=[40,33];break;case 6:I=[24,11];break;case 7:I=[20,11];break;case 8:I=[32,11];break;case 9:I=[80,33];break;case 10:I=[18,11];break;case 11:I=[15,11];break;case 12:I=[64,33];break;case 13:I=[160,99];break;case 14:I=[4,3];break;case 15:I=[3,2];break;case 16:I=[2,1];break;case 255:I=[u()<<8|u(),u()<<8|u()]}return{width:Math.ceil(16*(T+1)-2*a-2*s),height:(2-A)*(S+1)*16-(A?2:4)*(o+l),pixelRatio:I}},t}(ga),pa=function(e){function t(){for(var t,r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];return(t=e.call.apply(e,[this].concat(i))||this).initVPS=null,t}d(t,e);var r=t.prototype;return r.parsePES=function(e,t,r,i){var n,a=this,s=this.parseNALu(e,r.data,i),o=this.VideoSample,u=!1;r.data=null;var d=function(e){return o=a.VideoSample=a.createVideoSample(e,r.pts,r.dts)};s.forEach((function(i,s){var h,f;if(a.startsNewAccessUnit(o,e,i,s)){a.pushAccessUnit(o,e);var c=i.type>=16&&i.type<=23;o=d(c),u=!1}switch(i.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=d(!1)),o.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:var g;n=!0,u&&null!=(g=o)&&g.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null),o||(o=d(!0)),o.key=!0,o.frame=!0;break;case 19:case 20:n=!0,null!=(h=o)&&h.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null),o||(o=d(!0)),o.key=!0,o.frame=!0;break;case 39:n=!0,At(i.data,2,r.pts,t.samples);break;case 32:n=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=l(e.params,a.readVPS(i.data)),a.initVPS=i.data),e.vps=[i.data];break;case 33:if(n=!0,u=!0,void 0===e.vps||e.vps[0]===a.initVPS||void 0===e.sps||a.matchSPS(e.sps[0],i.data)||(a.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){var v=a.readSPS(i.data);for(var m in e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.codec=v.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={}),v.params)e.params[m]=v.params[m]}a.pushParameterSet(e.sps,i.data,e.vps),o||(o=d(!1));break;case 34:if(n=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];var p=a.readPPS(i.data);for(var y in p)e.params[y]=p[y]}a.pushParameterSet(e.pps,i.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(f=o)&&f.frame&&(a.pushAccessUnit(o,e),o=null),o||(o=d(!1));break;default:n=!1}o&&n&&o.units.push(i)})),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)},r.pushParameterSet=function(e,t,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(t)},r.startsNewAccessUnit=function(e,t,r,i){if(!e)return!1;if(!t.audFound&&0===i)return!0;if(!e.frame)return!1;var n=r.type,a=r.data;return!!(n>=32&&n<=35||39===n||n>=41&&n<=44||n>=48&&n<=55)||n<=31&&a.length>2&&0!=(128&a[2])},r.getNALuType=function(e,t){return(126&e[t])>>>1},r.ebsp2rbsp=function(e){for(var t=new Uint8Array(e.byteLength),r=0,i=0;i<e.byteLength;i++)i>=2&&3===e[i]&&0===e[i-1]&&0===e[i-2]||(t[r]=e[i],r++);return new Uint8Array(t.buffer,0,r)},r.pushAccessUnit=function(t,r){e.prototype.pushAccessUnit.call(this,t,r),this.initVPS&&(this.initVPS=null)},r.readVPS=function(e){var t=new va(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}},r.readSPS=function(e){var t=new va(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);var r=t.readBits(3);t.readBoolean();for(var i=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),s=t.readUByte(),o=t.readUByte(),l=t.readUByte(),u=t.readUByte(),d=t.readUByte(),h=t.readUByte(),f=t.readUByte(),c=t.readUByte(),g=t.readUByte(),v=t.readUByte(),m=t.readUByte(),p=[],y=[],E=0;E<r;E++)p.push(t.readBoolean()),y.push(t.readBoolean());if(r>0)for(var T=r;T<8;T++)t.readBits(2);for(var S=0;S<r;S++)p[S]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[S]&&t.readUByte();t.readUEG();var A=t.readUEG();3==A&&t.skipBits(1);var I=t.readUEG(),L=t.readUEG(),R=t.readBoolean(),b=0,k=0,D=0,P=0;R&&(b+=t.readUEG(),k+=t.readUEG(),D+=t.readUEG(),P+=t.readUEG());for(var _=t.readUEG(),C=t.readUEG(),w=t.readUEG(),O=t.readBoolean()?0:r;O<=r;O++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(var M=0;M<4;M++)for(var x=0;x<(3===M?2:6);x++)if(t.readBoolean()){var F=Math.min(64,1<<4+(M<<1));M>1&&t.readEG();for(var N=0;N<F;N++)t.readEG()}else t.readUEG();t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());for(var B=t.readUEG(),U=0,G=0;G<B;G++){var K=!1;if(0!==G&&(K=t.readBoolean()),K){G===B&&t.readUEG(),t.readBoolean(),t.readUEG();for(var V=0,H=0;H<=U;H++){var Y=t.readBoolean(),j=!1;Y||(j=t.readBoolean()),(Y||j)&&V++}U=V}else{var W=t.readUEG(),q=t.readUEG();U=W+q;for(var X=0;X<W;X++)t.readUEG(),t.readBoolean();for(var z=0;z<q;z++)t.readUEG(),t.readBoolean()}}if(t.readBoolean())for(var Q=t.readUEG(),$=0;$<Q;$++){for(var Z=0;Z<w+4;Z++)t.readBits(1);t.readBits(1)}var J=0,ee=1,te=1,re=!0,ie=1,ne=0;if(t.readBoolean(),t.readBoolean(),t.readBoolean()){if(t.readBoolean()){var ae=t.readUByte();ae>0&&ae<16?(ee=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][ae-1],te=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][ae-1]):255===ae&&(ee=t.readBits(16),te=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(),t.readBoolean()&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ie=t.readBits(32),ne=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){var se=t.readBoolean(),oe=t.readBoolean(),le=!1;(se||oe)&&((le=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),le&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(var ue=0;ue<=r;ue++){var de=!1;(re=t.readBoolean())||t.readBoolean()?t.readEG():de=t.readBoolean();var he=de?1:t.readUEG()+1;if(se)for(var fe=0;fe<he;fe++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(oe)for(var ce=0;ce<he;ce++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),J=t.readUEG())}var ge=I,ve=L;if(R){var me=1,pe=1;1===A?me=pe=2:2==A&&(me=2),ge=I-me*k-me*b,ve=L-pe*P-pe*D}for(var ye=i?["A","B","C"][i]:"",Ee=s<<24|o<<16|l<<8|u,Te=0,Se=0;Se<32;Se++)Te=(Te|(Ee>>Se&1)<<31-Se)>>>0;var Ae=Te.toString(16);return 1===a&&"2"===Ae&&(Ae="6"),{codecString:"hvc1."+ye+a+"."+Ae+"."+(n?"H":"L")+m+".B0",params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[s,o,l,u],general_constraint_indicator_flags:[d,h,f,c,g,v],general_level_idc:m,bit_depth:_+8,bit_depth_luma_minus8:_,bit_depth_chroma_minus8:C,min_spatial_segmentation_idc:J,chroma_format_idc:A,frame_rate:{fixed:re,fps:ne/ie}},width:ge,height:ve,pixelRatio:[ee,te]}},r.readPPS=function(e){var t=new va(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);var r=t.readBoolean(),i=t.readBoolean(),n=1;return i&&r?n=0:i?n=3:r&&(n=2),{parallelismType:n}},r.matchSPS=function(e,t){return We(e).substring(3)===We(t).substring(3)},t}(ga),ya=188,Ea=function(){function e(e,t,r,i){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._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=t,this.typeSupported=r,this.logger=i,this.videoParser=null}e.probe=function(t,r){var i=e.syncOffset(t);return i>0&&r.warn("MPEG2-TS detected but first sync word found @ offset "+i),-1!==i},e.syncOffset=function(e){for(var t=e.length,r=Math.min(940,t-ya)+1,i=0;i<r;){for(var n=!1,a=-1,s=0,o=i;o<t;o+=ya){if(71!==e[o]||t-o!==ya&&71!==e[o+ya]){if(s)return-1;break}if(s++,-1===a&&0!==(a=o)&&(r=Math.min(a+18612,e.length-ya)+1),n||(n=0===Ta(e,o)),n&&s>1&&(0===a&&s>2||o+ya>r))return a}i++}return-1},e.createTrack=function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Qe[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}};var t=e.prototype;return t.resetInitSegment=function(t,r,i,n,a,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=n,this.videoIntegrityChecker="skip"===this.config.handleMpegTsVideoIntegrityErrors?new ka(this.logger):null,this._audioTrack=e.createTrack("audio",n),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=i,t&&this.demux(t,0,s,"SAMPLE-AES"===(null==a?void 0:a.method))},t.resetTimeStamp=function(){},t.resetContiguity=function(){var e=this._audioTrack,t=this._videoTrack,r=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null},t.demux=function(t,r,i,n,a){var s;void 0===n&&(n=!1),void 0===a&&(a=!1),n||(this.sampleAes=null);var o=this._videoTrack,l=this.videoIntegrityChecker,u=this._audioTrack,d=this._id3Track,h=this._txtTrack,f=i.iframe,c=o.pid,g=o.pesData,v=u.pid,m=d.pid,p=this._klvPid,y=u.pesData,E=d.pesData,T=null,S=null,A=this.pmtParsed,I=this._pmtId,L=t.length;if(this.remainderData&&(L=(t=Et(this.remainderData,t)).length,this.remainderData=null),L<ya&&!a)return this.remainderData=t,{audioTrack:u,videoTrack:o,id3Track:d,textTrack:h};var R=Math.max(0,e.syncOffset(t));(L-=(L-R)%ya)<t.byteLength&&!a&&(this.remainderData=new Uint8Array(t.buffer,L,t.buffer.byteLength-L));for(var b=0,k=R;k<L;k+=ya)if(71===t[k]){var D=!!(64&t[k+1]),P=Ta(t,k),_=void 0;if((48&t[k+3])>>4>1){if((_=k+5+t[k+4])===k+ya)continue}else _=k+4;switch(P){case c:D&&(!g||null!=l&&l.isCorrupted||!(s=Ra(g,this.logger))||(this.readyVideoParser(o.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(o,h,s,!1,i)),g={data:[],size:0},null==l||l.reset(c)),null==l||l.handlePacket(t.subarray(k)),g&&(g.data.push(t.subarray(_,k+ya)),g.size+=k+ya-_);break;case v:if(f)break;if(D){if(y&&(s=Ra(y,this.logger)))switch(u.segmentCodec){case"aac":this.parseAACPES(u,s,i);break;case"mp3":this.parseMPEGPES(u,s);break;case"ac3":this.parseAC3PES(u,s)}y={data:[],size:0}}y&&(y.data.push(t.subarray(_,k+ya)),y.size+=k+ya-_);break;case m:if(f)break;D&&(E&&(s=Ra(E,this.logger))&&this.parseID3PES(d,s),E={data:[],size:0}),E&&(E.data.push(t.subarray(_,k+ya)),E.size+=k+ya-_);break;case p:if(f)break;D&&(T&&(s=Ra(T,this.logger))&&this.parseKlvPES(d,s),T={data:[],size:0}),T&&(T.data.push(t.subarray(_,k+ya)),T.size+=k+ya-_);break;case 0:D&&(_+=t[_]+1),I=this._pmtId=Sa(t,_);break;case I:D&&(_+=t[_]+1);var C=Aa(t,_,this.typeSupported,n,this.observer,this.logger,this.config,i);(c=C.videoPid)>0&&(o.pid=c,o.segmentCodec=C.segmentVideoCodec),(v=C.audioPid)>0&&(u.pid=v,u.segmentCodec=C.segmentAudioCodec),(m=C.id3Pid)>0&&(d.pid=m),(p=C.klvPid)>0&&(this._klvPid=p),null===S||A||(this.logger.warn("MPEG-TS PMT found at "+k+" after unknown PID '"+S+"'. Backtracking to sync byte @"+R+" to parse all TS packets."),S=null,k=R-188),A=this.pmtParsed=!0;break;case 17:case 8191:break;default:S=P}}else b++;b>0&&Ia(this.observer,new Error("Found "+b+" TS packet/s that do not start with 0x47"),i,void 0,this.logger),o.pesData=g,u.pesData=y,d.pesData=E;var w={audioTrack:u,videoTrack:o,id3Track:d,textTrack:h};return a&&this.extractRemainingSamples(w,i),w},t.flush=function(e,t){var r,i=this.remainderData;return this.remainderData=null,r=i?this.demux(i,0,t,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(r,t),this.sampleAes?this.decrypt(r,this.sampleAes):r},t.extractRemainingSamples=function(e,t){var r,i=e.audioTrack,n=e.videoTrack,a=e.id3Track,s=e.textTrack,o=n.pesData,l=i.pesData,u=a.pesData,d=this.videoIntegrityChecker;if(!o||null!=d&&d.isCorrupted||!(r=Ra(o,this.logger))?n.pesData=o:(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(n,s,r,!0,t),n.pesData=null)),l&&(r=Ra(l,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,r,t);break;case"mp3":this.parseMPEGPES(i,r);break;case"ac3":this.parseAC3PES(i,r)}i.pesData=null}else null!=l&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=l;u&&(r=Ra(u,this.logger))?(this.parseID3PES(a,r),a.pesData=null):a.pesData=u},t.demuxSampleAes=function(e,t,r,i){var n=this.demux(e,r,i,!0,!this.config.progressive),a=this.sampleAes=new aa(this.observer,this.config,t);return this.decrypt(n,a)},t.readyVideoParser=function(e){null===this.videoParser&&("avc"===e?this.videoParser=new ma:"hevc"===e&&(this.videoParser=new pa))},t.decrypt=function(e,t){return new Promise((function(r){var i=e.audioTrack,n=e.videoTrack;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,(function(){n.samples?t.decryptAvcSamples(n.samples,0,0,(function(){r(e)})):r(e)})):n.samples&&t.decryptAvcSamples(n.samples,0,0,(function(){r(e)}))}))},t.destroy=function(){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,this.videoIntegrityChecker=null},t.parseAACPES=function(e,t,r){var i,n,a,s=0,o=this.aacOverFlow,l=t.data;if(o){this.aacOverFlow=null;var u=o.missing,d=o.sample.unit.byteLength;if(-1===u)l=Et(o.sample.unit,l);else{var h=d-u;o.sample.unit.set(l.subarray(0,u),h),e.samples.push(o.sample),s=o.missing}}for(i=s,n=l.length;i<n-1&&!Kn(l,i);i++);if(i!==s){var f,c=i<n-1;if(f=c?"AAC PES did not start with ADTS header,offset:"+i:"No ADTS header found in AAC PES",Ia(this.observer,new Error(f),r,c,this.logger),!c)return}if(Hn(e,this.observer,l,i,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!o)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var g=Yn(e.samplerate);a=o.sample.pts+g}for(var v,m=0;i<n;){if(i+=(v=jn(e,l,i,a,m)).length,v.missing){this.aacOverFlow=v;break}for(m++;i<n-1&&!Kn(l,i);i++);}},t.parseMPEGPES=function(e,t){var r=t.data,i=r.length,n=0,a=0,s=t.pts;if(void 0!==s)for(;a<i;)if(ia(r,a)){var o=ea(e,r,a,s,n);if(!o)break;a+=o.length,n++}else a++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")},t.parseAC3PES=function(e,t){var r=t.data,i=t.pts;if(void 0!==i)for(var n,a=r.length,s=0,o=0;o<a&&(n=ua(e,r,o,i,s++))>0;)o+=n;else this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS")},t.parseID3PES=function(e,t){if(void 0!==t.pts){var r=l({},t,{type:this._videoTrack?Wn.emsg:Wn.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")},t.parseKlvPES=function(e,t){var r,i=null!=(r=t.pts)?r:t.dts;if(void 0!==i){var n=t.data;if(n.length<16)this.logger.warn("[tsdemuxer]: KLV PES payload too short");else for(var a=0;a<n.length;){var s;if(a+16>n.length)break;var o=a;if((a+=16)>=n.length)break;var l=n[a];a+=1;var u=0;if(128&l){var d=127&l;if(0===d||d>4||a+d>n.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(var h=0;h<d;h++)u=u<<8|n[a+h];a+=d}else u=l;if(a+u>n.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}var f=a+u,c=n.subarray(o,f),g={data:c,len:c.byteLength,pts:i,dts:null!=(s=t.dts)?s:i,type:Wn.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(g),a=f}}else this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS")},e}();function Ta(e,t){return((31&e[t+1])<<8)+e[t+2]}function Sa(e,t){return(31&e[t+10])<<8|e[t+11]}function Aa(e,t,r,i,n,a,s,o){var l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},u=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<u;){var d=Ta(e,t),h=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!i){La("ADTS AAC",a);break}case 15:-1===l.audioPid&&(l.audioPid=d);break;case 21:-1===l.id3Pid&&(l.id3Pid=d);break;case 219:if(!i){La("H.264",a);break}case 27:-1===l.videoPid&&(l.videoPid=d);break;case 3:case 4:r.mpeg||r.mp3?-1===l.audioPid&&(l.audioPid=d,l.segmentAudioCodec="mp3"):a.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){La("AC-3",a);break}case 129:r.ac3?-1===l.audioPid&&(l.audioPid=d,l.segmentAudioCodec="ac3"):a.log("AC-3 audio found, not supported in this browser");break;case 6:if(h>0)for(var f=t+5,c=h;c>2;){switch(e[f]){case 106:-1===l.audioPid&&(!0!==r.ac3?a.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=d,l.segmentAudioCodec="ac3"));break;case 5:-1===l.klvPid&&s.enableEmsgKLVMetadata&&(l.klvPid=d,a.log("KLV metadata PID found: "+d))}var g=e[f+1]+2;f+=g,c-=g}break;case 194:case 135:return Ia(n,new Error("Unsupported EC-3 in M2TS found"),o,void 0,a),l;case 36:-1===l.videoPid&&(l.videoPid=d,l.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"))}t+=h+5}return l}function Ia(e,t,r,i,n){n.warn("parsing error: "+t.message),e.emit(G.ERROR,G.ERROR,{type:B.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,chunkMeta:r,error:t,reason:t.message})}function La(e,t){t.log(e+" with AES-128-CBC encryption found in unencrypted stream")}function Ra(e,t){var r,i,n,a,s,o=0,l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Et(l[0],l[1]),l.splice(1,1);if(1===((r=l[0])[0]<<16)+(r[1]<<8)+r[2]){if((i=(r[4]<<8)+r[5])&&i>e.size-6)return null;var u=r[7];192&u&&(a=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,64&u?a-(s=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2)>54e5&&(t.warn(Math.round((a-s)/9e4)+"s delta between PTS and DTS, align them"),a=s):s=a);var d=(n=r[8])+9;if(e.size<=d)return null;e.size-=d;for(var h=new Uint8Array(e.size),f=0,c=l.length;f<c;f++){var g=(r=l[f]).byteLength;if(d){if(d>g){d-=g;continue}r=r.subarray(d),g-=d,d=0}h.set(r,o),o+=g}return i&&(i-=n+3),{data:h,pts:a,dts:s,len:i}}return null}var ba,ka=function(){function e(e){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=e}var t=e.prototype;return t.reset=function(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"},t.handlePacket=function(e){if(!(e.byteLength<4)){var t=Ta(e,0);if(t===this.pid){var r=(48&e[3])>>4;if(0!==r){var i=15&e[3],n=this.lastContinuityCounter;this.lastContinuityCounter=i;var a=0!=(1&r);if(!(0!=(2&r)&&0!=e[4]&&0!=(128&e[5])||n<0)){var s=a?n+1&15:n;return i!==s?(this.logger.warn("MPEG-TS Continuity Counter check failed for PID='"+t+"', CC="+i+", Expected-CC="+s+" Last-CC="+n),void(this.integrityState="cc-failed")):0!=(128&e[1])?(this.logger.warn("MPEG-TS Packet had TEI flag set for PID='"+t+"'"),void(this.integrityState="tei-bit")):void 0}}}else this.logger.debug("Packet PID mismatch, expected "+this.pid+" got "+t)}},a(e,[{key:"isCorrupted",get:function(){return"ok"!==this.integrityState}}])}(),Da=function(){function e(){}return e.getSilentFrame=function(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)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(6===t)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])}else{if(1===t)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(2===t)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(3===t)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])}},e}(),Pa={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])},_a=new Uint8Array([0,0,0,0,0,0,0,0]),Ca=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),wa=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Oa=new Uint8Array([0,0,0,0,0,0,0,0]),Ma=new Uint8Array([0,0,0,0,0,0,0,1]),xa=new Uint8Array([105,115,111,109]),Fa=new Uint8Array([97,118,99,49]),Na=new Uint8Array([0,0,0,1]),Ba=function(){function e(){}return e.box=function(e){for(var t=8,r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];for(var a=i.length,s=a;a--;)t+=i[a].byteLength;var o=new Uint8Array(t);for(rt(o,0,t),rt(o,4,e),a=0,t=8;a<s;a++)o.set(i[a],t),t+=i[a].byteLength;return o},e.hdlr=function(t){return e.box(ze.hdlr,Pa[t])},e.mdat=function(t){return e.box(ze.mdat,t)},e.mdhd=function(t,r){r*=t;var i=Math.floor(r/(Xe+1)),n=Math.floor(r%(Xe+1));return e.box(ze.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,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))},e.mdia=function(t){return e.box(ze.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))},e.mfhd=function(t){return e.box(ze.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))},e.minf=function(t){return"audio"===t.type?e.box(ze.minf,e.box(ze.smhd,Oa),e.DINF,e.stbl(t)):e.box(ze.minf,e.box(ze.vmhd,wa),e.DINF,e.stbl(t))},e.moof=function(t,r,i){return e.box(ze.moof,e.mfhd(t),e.traf(i,r))},e.moov=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[ze.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(e.mvex(t)))},e.mvex=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[ze.mvex].concat(i))},e.mvhd=function(t,r){r*=t;var i=Math.floor(r/(Xe+1)),n=Math.floor(r%(Xe+1)),a=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,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,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 e.box(ze.mvhd,a)},e.sdtp=function(t){var r,i,n=t.samples||[],a=new Uint8Array(4+n.length);for(r=0;r<n.length;r++)i=n[r].flags,a[r+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return e.box(ze.sdtp,a)},e.stbl=function(t){return e.box(ze.stbl,e.stsd(t),e.box(ze.stts,_a),e.box(ze.stsc,_a),e.box(ze.stsz,Ca),e.box(ze.stco,_a))},e.avc1=function(t){var r,i,n,a=[],s=[];for(r=0;r<t.sps.length;r++)n=(i=t.sps[r]).byteLength,a.push(n>>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));for(r=0;r<t.pps.length;r++)n=(i=t.pps[r]).byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(i));var o=e.box(ze.avcC,new Uint8Array([1,a[3],a[4],a[5],255,224|t.sps.length].concat(a).concat([t.pps.length]).concat(s))),l=t.width,u=t.height,d=t.pixelRatio[0],h=t.pixelRatio[1];return e.box(ze.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,255&l,u>>8&255,255&u,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,e.box(ze.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(ze.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))},e.esds=function(e){var t=e.config,r=t.length;return new Uint8Array([0,0,0,0,3,23+r,0,1,0,4,15+r,64,21,0,0,0,0,0,0,0,0,0,0,0,5,r].concat(t,[6,1,2]))},e.audioStsd=function(e){var t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])},e.mp4a=function(t){return e.box(ze.mp4a,e.audioStsd(t),e.box(ze.esds,e.esds(t)))},e.mp3=function(t){return e.box(ze[".mp3"],e.audioStsd(t))},e.ac3=function(t){return e.box(ze["ac-3"],e.audioStsd(t),e.box(ze.dac3,t.config))},e.stsd=function(t){var r=t.segmentCodec;if("audio"===t.type){if("aac"===r)return e.box(ze.stsd,Ma,e.mp4a(t));if("ac3"===r&&t.config)return e.box(ze.stsd,Ma,e.ac3(t));if("mp3"===r&&"mp3"===t.codec)return e.box(ze.stsd,Ma,e.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===r)return e.box(ze.stsd,Ma,e.avc1(t));if("hevc"===r&&t.vps)return e.box(ze.stsd,Ma,e.hvc1(t))}throw new Error("unsupported "+t.type+" segment codec ("+r+"/"+t.codec+")")},e.tkhd=function(t){var r=t.id,i=(t.duration||0)*(t.timescale||0),n=t.width||0,a=t.height||0,s=Math.floor(i/(Xe+1)),o=Math.floor(i%(Xe+1));return e.box(ze.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o,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,n>>8&255,255&n,0,0,a>>8&255,255&a,0,0]))},e.traf=function(t,r){var i=e.sdtp(t),n=t.id,a=Math.floor(r/(Xe+1)),s=Math.floor(r%(Xe+1));return e.box(ze.traf,e.box(ze.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.box(ze.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,s>>24,s>>16&255,s>>8&255,255&s])),e.trun(t,i.length+16+20+8+16+8+8),i)},e.trak=function(t){return t.duration=t.duration||4294967295,e.box(ze.trak,e.tkhd(t),e.mdia(t))},e.trex=function(t){var r=t.id;return e.box(ze.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},e.trun=function(t,r){var i,n,a,s,o,l,u=t.samples||[],d=u.length,h=12+16*d,f=new Uint8Array(h);for(r+=8+h,f.set(["video"===t.type?1:0,0,15,1,d>>>24&255,d>>>16&255,d>>>8&255,255&d,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i<d;i++)a=(n=u[i]).duration,s=n.size,o=n.flags,l=n.cts,f.set([a>>>24&255,a>>>16&255,a>>>8&255,255&a,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return e.box(ze.trun,f)},e.initSegment=function(t){var r=e.moov(t);return Et(e.FTYP,r)},e.hvc1=function(t){for(var r=t.params,i=[t.vps,t.sps,t.pps],n=new Uint8Array([1,r.general_profile_space<<6|(r.general_tier_flag?32:0)|r.general_profile_idc,r.general_profile_compatibility_flags[0],r.general_profile_compatibility_flags[1],r.general_profile_compatibility_flags[2],r.general_profile_compatibility_flags[3],r.general_constraint_indicator_flags[0],r.general_constraint_indicator_flags[1],r.general_constraint_indicator_flags[2],r.general_constraint_indicator_flags[3],r.general_constraint_indicator_flags[4],r.general_constraint_indicator_flags[5],r.general_level_idc,240|r.min_spatial_segmentation_idc>>8,255&r.min_spatial_segmentation_idc,252|r.parallelismType,252|r.chroma_format_idc,248|r.bit_depth_luma_minus8,248|r.bit_depth_chroma_minus8,0,parseInt(r.frame_rate.fps),3|r.temporal_id_nested<<2|r.num_temporal_layers<<3|(r.frame_rate.fixed?64:0),i.length]),a=n.length,s=0;s<i.length;s+=1){a+=3;for(var o=0;o<i[s].length;o+=1)a+=2+i[s][o].length}var l=new Uint8Array(a);l.set(n,0),a=n.length;for(var u=i.length-1,d=0;d<i.length;d+=1){l.set(new Uint8Array([32+d|(d===u?128:0),0,i[d].length]),a),a+=3;for(var h=0;h<i[d].length;h+=1)l.set(new Uint8Array([i[d][h].length>>8,255&i[d][h].length]),a),a+=2,l.set(i[d][h],a),a+=i[d][h].length}var f=e.box(ze.hvcC,l),c=t.width,g=t.height,v=t.pixelRatio[0],m=t.pixelRatio[1];return e.box(ze.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,c>>8&255,255&c,g>>8&255,255&g,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]),f,e.box(ze.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(ze.pasp,new Uint8Array([v>>24,v>>16&255,v>>8&255,255&v,m>>24,m>>16&255,m>>8&255,255&m])))},e}();ba=Ba,Ba.FTYP=ba.box(ze.ftyp,xa,Na,xa,Fa),Ba.DINF=ba.box(ze.dinf,ba.box(ze.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));var Ua=9e4;function Ga(e,t,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var n=e*t*r;return i?Math.round(n):n}function Ka(e,t){return Ga(e,1e3,1/Ua,t)}function Va(e){var t=e.baseTime,r=e.timescale;return t/r+" ("+t+"/"+r+") trackId: "+e.trackId}var Ha=8589934592;function Ya(e,t,r,i){return{duration:t,size:r,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1,paddingValue:0}}}var ja=function(e){function t(t,r,i,n){var a;return(a=e.call(this,"mp4-remuxer",n)||this).observer=void 0,a.config=void 0,a.typeSupported=void 0,a.ISGenerated=!1,a._initPTS=null,a._initDTS=null,a.nextVideoTs=null,a.nextAudioTs=null,a.videoSampleDuration=null,a.isAudioContiguous=!1,a.isVideoContiguous=!1,a.videoTrackConfig=void 0,a.observer=t,a.config=r,a.typeSupported=i,a.ISGenerated=!1,a}d(t,e);var r=t.prototype;return r.destroy=function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null},r.resetTimeStamp=function(e){var t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log("Reset initPTS: "+(t?Va(t):t)+" > "+(e?Va(e):e)),this._initPTS=this._initDTS=e},r.resetNextTimestamp=function(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},r.resetInitSegment=function(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0},r.getVideoStartPts=function(e){var t=!1,r=e[0].pts,i=e.reduce((function(e,i){var n=i.pts,a=n-e;return a<-4294967296&&(t=!0,a=(n=Wa(n,r))-e),a>0?e:n}),r);return t&&this.debug("PTS rollover detected"),i},r.remux=function(e,t,r,i,n,a,s,o,l){var u,d,h,f,c,g,v=n,m=n,p=!l.iframe&&e.pid>-1,y=t.pid>-1,E=t.samples.length,T=e.samples.length>0,S=s&&E>0||E>1;if((!p||T)&&(!y||S)||this.ISGenerated||s){if(this.ISGenerated){var A,I,L,R,b=this.videoTrackConfig;(b&&(t.width!==b.width||t.height!==b.height||(null==(A=t.pixelRatio)?void 0:A[0])!==(null==(I=b.pixelRatio)?void 0:I[0])||(null==(L=t.pixelRatio)?void 0:L[1])!==(null==(R=b.pixelRatio)?void 0:R[1]))||!b&&S||null===this.nextAudioTs&&T)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,n,a));var k,D=this.isVideoContiguous,P=-1;if(S&&(P=function(e){for(var t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!D&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,P>0){this.warn("Dropped "+P+" out of "+E+" video samples due to a missing keyframe");var _=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(P),t.dropped+=P,k=m+=(t.samples[0].pts-_)/t.inputTimeScale}else-1===P&&(this.warn("No keyframe found out of "+E+" video samples"),g=!1);if(this.ISGenerated){if(T&&S&&n){var C=this.getVideoStartPts(t.samples),w=(Wa(e.samples[0].pts,C)-C)/t.inputTimeScale;v+=Math.max(0,w),m+=Math.max(0,-w)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(e,t,n,a)),d=this.remuxAudio(e,v,this.isAudioContiguous,a,y||S||o===$.AUDIO?m:void 0,l),S){var O=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(e,t,n,a)),u=this.remuxVideo(t,m,D,O,l)}}else S&&(u=this.remuxVideo(t,m,D,0,l));u&&(u.firstKeyFrame=P,u.independent=-1!==P,u.firstKeyFramePTS=k)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(c=qa(r,n,this._initPTS,this._initDTS)),i.samples.length&&(f=Xa(i,n,this._initPTS))),{audio:d,video:u,initSegment:h,independent:g,text:f,id3:c}},r.computeInitPts=function(e,t,r,i){var n=Math.round(r*t),a=Wa(e,n);if(a<n)for(this.log("Adjusting PTS for rollover in timeline near "+(n-a)/t+" "+i);a<n;)a+=Ha;return a-n},r.generateIS=function(e,t,r,i){var n,a,s,o=e.samples,l=t.samples,u=this.typeSupported,d={},h=this._initPTS,f=!h||i,c="audio/mp4",g=-1;if(f&&(n=a=1/0),e.config&&o.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":u.mpeg?(c="audio/mpeg",e.codec=""):u.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}if(d.audio={id:"audio",container:c,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&u.mpeg?new Uint8Array(0):Ba.initSegment([e]),metadata:{channelCount:e.channelCount}},f){g=e.id,s=e.inputTimeScale;var v=this.computeInitPts(o[0].pts,s,r,"audio");(!h||s!==h.timescale||0===r&&v<h.baseTime)&&(n=a=v)}}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Ba.initSegment([t]),metadata:{width:t.width,height:t.height}},f){g=t.id,s=t.inputTimeScale;var m=this.getVideoStartPts(l),p=Wa(l[0].dts,m),y=this.computeInitPts(p,s,r,"video"),E=this.computeInitPts(m,s,r,"video");(!h||s!==h.timescale||x(n)||0===r&&E<h.baseTime)&&(a=Math.min(a,y),n=Math.min(n,y))}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(d).length)return this.ISGenerated=!0,f&&x(n)?(h&&this.warn("Timestamps at playlist time: "+(i?"":"~")+r+" "+n/s+" != initPTS: "+h.baseTime/h.timescale+" ("+h.baseTime+"/"+h.timescale+") trackId: "+h.trackId),this.log("Found initPTS at playlist time: "+r+" offset: "+n/s+" ("+n+"/"+s+") trackId: "+g),this._initPTS={baseTime:n,timescale:s,trackId:g},this._initDTS={baseTime:a,timescale:s,trackId:g}):n=s=void 0,{tracks:d,initPTS:n,timescale:s,trackId:g}},r.remuxVideo=function(e,t,r,i,n){var a,s,o=e.inputTimeScale,u=e.samples,d=[],h=u.length,f=this._initPTS,c=f.baseTime*o/f.timescale,g=this.nextVideoTs,v=8,m=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,E=!1;if(!r||null===g){var T=c+t*o,S=u[0].pts-Wa(u[0].dts,u[0].pts);Ot()&&null!==g&&Math.abs(T-S-(g+c))<15e3?r=!0:g=T-S-c}for(var A=g+c,I=0;I<h;I++){var L=u[I];L.pts=Wa(L.pts,A),L.dts=Wa(L.dts,A),L.dts<u[I>0?I-1:I].dts&&(E=!0)}E&&u.sort((function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i})),a=u[0].dts;var R=(s=u[u.length-1].dts)-a,b=R?Math.round(R/(h-1)):m||e.inputTimeScale/30;if(r){var k=a-A,D=k>b,P=k<-1;if((D||P)&&(D?this.warn((e.segmentCodec||"").toUpperCase()+": "+Ka(k,!0)+" ms ("+k+"dts) hole between fragments detected at "+t.toFixed(3)):this.warn((e.segmentCodec||"").toUpperCase()+": "+Ka(-k,!0)+" ms ("+k+"dts) overlapping between fragments detected at "+t.toFixed(3)),!P||A>=u[0].pts||Ot())){a=A;var _=u[0].pts-k;if(D)u[0].dts=a,u[0].pts=_;else for(var C=!0,w=0;w<u.length&&!(u[w].dts>_&&C);w++){var O=u[w].pts;if(u[w].dts-=k,u[w].pts-=k,w<u.length-1){var M=u[w+1].pts;C=M<=u[w].pts==M<=O}}this.log("Video: Initial PTS/DTS adjusted: "+Ka(_,!0)+"/"+Ka(a,!0)+", delta: "+Ka(k,!0)+" ms")}}for(var x=0,F=0,N=a=Math.max(0,a),K=0;K<h;K++){for(var V=u[K],H=V.units,Y=H.length,j=0,W=0;W<Y;W++)j+=H[W].data.length;F+=j,x+=Y,V.length=j,V.dts<N?(V.dts=N,N+=b/4|0||1):N=V.dts,p=Math.min(V.pts,p),y=Math.max(V.pts,y)}s=u[h-1].dts;var q,X=F+4*x+8;try{q=new Uint8Array(X)}catch(e){return void this.observer.emit(G.ERROR,G.ERROR,{type:B.MUX_ERROR,details:U.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:n,error:e,bytes:X,reason:"fail allocating video mdat "+X})}rt(q,0,X),rt(q,4,ze.mdat);for(var z=!1,Q=Number.POSITIVE_INFINITY,$=Number.POSITIVE_INFINITY,Z=Number.NEGATIVE_INFINITY,J=Number.NEGATIVE_INFINITY,ee=0;ee<h;ee++){for(var te=u[ee],re=te.units,ie=0,ne=0,ae=re.length;ne<ae;ne++){var se=re[ne],oe=se.data,le=se.data.byteLength;rt(q,v,le),v+=4,q.set(oe,v),v+=le,ie+=4+le}var ue=void 0;if(ee<h-1)m=u[ee+1].dts-te.dts,ue=u[ee+1].pts-te.pts;else{var de=this.config,he=ee>0?te.dts-u[ee-1].dts:b;if(ue=ee>0?te.pts-u[ee-1].pts:b,de.stretchShortVideoTrack&&null!==this.nextAudioTs){var fe=Math.floor(de.maxBufferHole*o),ce=(i?p+i*o:this.nextAudioTs+c)-te.pts;ce>fe?((m=ce-he)<0?m=he:z=!0,this.log("It is approximately "+ce/90+" ms to the next segment; using duration "+m/90+" ms for the last video frame.")):m=he}else m=he}var ge=Math.round(te.pts-te.dts);if(Q=Math.min(Q,m),Z=Math.max(Z,m),$=Math.min($,ue),J=Math.max(J,ue),!r&&0===ee&&ge>m){var ve=Math.round(ge/b)*b;ve-ge==1&&(this.log("pad first CTS "+ge+" -> "+ve+" of sn: "+n.sn),ge=ve)}d.push(Ya(te.key,m,ie,ge))}if(d.length){var me=Ot();if(me){if(me<70){var pe=d[0].flags;pe.dependsOn=2,pe.isNonSync=0}}else if(function(){if(void 0===Pt){var e=_t.match(/Safari\/(\d+)/i);Pt=e?parseInt(e[1]):0}return Pt}()&&J-$<Z-Q&&b/Z<.025&&0===d[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var ye=a,Ee=0,Te=d.length;Ee<Te;Ee++){var Se=ye+d[Ee].duration,Ae=ye+d[Ee].cts;if(Ee<Te-1){var Ie=Se+d[Ee+1].cts;d[Ee].duration=Ie-Ae}else d[Ee].duration=Ee?d[Ee-1].duration:b;d[Ee].cts=0,ye=Se}}}var Le=s+(m=z||!m?b:m);this.nextVideoTs=g=Le-c,this.videoSampleDuration=m,this.isVideoContiguous=!0,n.iframe&&(1===d.length?(d[0].duration=m=n.duration*o,this.nextVideoTs=g=a+m-c):this.warn("Not adjusting IFrame duration (sample count "+d.length+")"));var Re={data1:Ba.moof(n.sn,a,l(e,{samples:d})),data2:q,startPTS:(p-c)/o,endPTS:(y+m-c)/o,startDTS:(a-c)/o,endDTS:g/o,type:"video",hasAudio:!1,hasVideo:!0,nb:d.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Re},r.getSamplesPerFrame=function(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}},r.remuxAudio=function(e,t,r,i,n,a){var s=e.inputTimeScale,o=s/(e.samplerate?e.samplerate:s),u=this.getSamplesPerFrame(e),d=u*o,h=this._initPTS,f="mp3"===e.segmentCodec&&this.typeSupported.mpeg,c=[],g=void 0!==n,v=e.samples,m=f?0:8,p=this.nextAudioTs||-1,y=h.baseTime*s/h.timescale,E=y+t*s;if(this.isAudioContiguous=r=r||v.length&&p>0&&(i&&Math.abs(E-(p+y))<9e3||Math.abs(Wa(v[0].pts,E)-(p+y))<20*d),v.forEach((function(e){e.pts=Wa(e.pts,E)})),!r||p<0){var T=v.length;if(v=v.filter((function(e){return e.pts>=0})),T!==v.length&&this.warn("Removed "+(v.length-T)+" of "+T+" samples (initPTS "+y+" / "+s+")"),!v.length)return;p=0===n?0:i&&!g?Math.max(0,E-y):v[0].pts-y}if("aac"===e.segmentCodec)for(var S=this.config.maxAudioFramesDrift,A=0,I=p+y;A<v.length;A++){var L=v[A],R=L.pts,b=R-I,k=Math.abs(1e3*b/s);if(b<=-S*d&&g)0===A&&(this.warn("Audio frame @ "+(R/s).toFixed(3)+"s overlaps marker by "+Math.round(1e3*b/s)+" ms."),this.nextAudioTs=p=R-y,I=R);else if(b>=S*d&&k<1e4&&g){var D=Math.round(b/d);for(I=R-D*d;I<0&&D&&d;)D--,I+=d;0===A&&(this.nextAudioTs=p=I-y),this.warn("Injecting "+D+" audio frames @ "+((I-y)/s).toFixed(3)+"s due to "+Math.round(1e3*b/s)+" ms gap.");for(var P=0;P<D;P++){var _=Da.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);_||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),_=L.unit.subarray()),v.splice(A,0,{unit:_,pts:I}),I+=d,A++}}L.pts=I,I+=d}for(var C,w=null,O=null,M=0,x=v.length;x--;)M+=v[x].unit.byteLength;for(var F=0,N=v.length;F<N;F++){var K=v[F],V=K.unit,H=K.pts;if(null!==O)c[F-1].duration=Math.round((H-O)/o);else{if(r&&"aac"===e.segmentCodec&&(H=p+y),w=H,!(M>0))return;M+=m;try{C=new Uint8Array(M)}catch(e){return void this.observer.emit(G.ERROR,G.ERROR,{type:B.MUX_ERROR,details:U.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:e,bytes:M,reason:"fail allocating audio mdat "+M})}f||(rt(C,0,M),rt(C,4,ze.mdat))}C&&C.set(V,m);var Y=V.byteLength;m+=Y,c.push(Ya(!0,u,Y,0)),O=H}var j=c.length;if(j){var W=c[c.length-1];p=O-y,this.nextAudioTs=p+o*W.duration;var q=f?new Uint8Array(0):Ba.moof(e.sequenceNumber++,w/o,l({},e,{samples:c}));e.samples=[];var X=(w-y)/s,z=this.nextAudioTs/s,Q={data1:q,data2:C,startPTS:X,endPTS:z,startDTS:X,endDTS:z,type:"audio",hasAudio:!0,hasVideo:!1,nb:j};return this.isAudioContiguous=!0,Q}},t}(pe);function Wa(e,t){var r;if(null===t)return e;for(r=t<e?-Ha:Ha;Math.abs(e-t)>4294967296;)e+=r;return e}function qa(e,t,r,i){var n=e.samples.length;if(n){for(var a=e.inputTimeScale,s=0;s<n;s++){var o=e.samples[s];o.pts=Wa(o.pts-r.baseTime*a/r.timescale,t*a)/a,o.dts=Wa(o.dts-i.baseTime*a/i.timescale,t*a)/a}var l=e.samples;return e.samples=[],{samples:l}}}function Xa(e,t,r){var i=e.samples.length;if(i){for(var n=e.inputTimeScale,a=0;a<i;a++){var s=e.samples[a];s.pts=Wa(s.pts-r.baseTime*n/r.timescale,t*n)/n}e.samples.sort((function(e,t){return e.pts-t.pts}));var o=e.samples;return e.samples=[],{samples:o}}}var za,Qa=function(e){function t(t,r,i,n){var a;return(a=e.call(this,"passthrough-remuxer",n)||this).observer=void 0,a.emitInitSegment=!1,a.audioCodec=void 0,a.videoCodec=void 0,a.initData=void 0,a.initPTS=null,a.initTracks=void 0,a.lastEndTime=null,a.isVideoContiguous=!1,a.videoOnlyRemux=!1,a.decryptdata=null,a.pendingInitSegment=void 0,a.observer=t,a}d(t,e);var r=t.prototype;return r.destroy=function(){this.observer&&this.observer.removeAllListeners(),this.observer=null},r.resetTimeStamp=function(e){this.lastEndTime=null;var t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)},r.resetNextTimestamp=function(){this.isVideoContiguous=!1,this.lastEndTime=null},r.resetInitSegment=function(e,t,r,i){this.audioCodec=t,this.videoCodec=r,this.decryptdata=i,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0},r.generateInitSegment=function(e,t,r){this.videoOnlyRemux=!1;var i=this.audioCodec,n=this.videoCodec;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var a=this.initData=r||ut(e),s=a.audio,o=a.video;if(t)!function(e,t){if(e&&t){var r=t.keyId;16===(null==r?void 0:r.byteLength)&&t.isCommonEncryption&&vt(e,(function(e,t){var i=e.subarray(8,24);i.some((function(e){return 0!==e}))||(Le.log("[eme] Patching keyId in 'enc"+(t?"a":"v")+">sinf>>tenc' box: "+He(i)+" -> "+He(r)),e.set(r,8))}))}}(e,t);else{var l=s||o;null!=l&&l.encrypted&&this.warn('Init segment with encrypted track with has no key ("'+l.codec+'")!')}s&&(i=Za(s,Z.AUDIO,this)),o&&(n=Za(o,Z.VIDEO,this));var u={};s&&o?u.audiovideo={container:"video/mp4",codec:i+","+n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:s?u.audio={container:"audio/mp4",codec:i,encrypted:s.encrypted,initSegment:e,id:"audio"}:o?u.video={container:"video/mp4",codec:n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=u},r.remux=function(e,t,r,i,n,a,s,o,l,u,d){var h,f,c=this.initPTS,g=this.lastEndTime,v={audio:void 0,video:void 0,text:void 0,id3:r,initSegment:void 0};x(g)||(g=this.lastEndTime=n||0);var m=t.samples;if(!m.length)return v;var p=this.pendingInitSegment;p&&(this.pendingInitSegment=void 0,this.generateInitSegment(p,this.decryptdata,u));var y={initPTS:void 0,timescale:void 0,trackId:void 0},E=this.initData;if(null!=(h=E)&&h.length||(this.generateInitSegment(m),E=this.initData),null==(f=E)||!f.length)return this.warn("Failed to generate initSegment."),v;if(l.iframe&&E.audio&&E.video){var T,S,A=null==(T=this.initTracks)||null==(T=T.audiovideo)?void 0:T.initSegment,I=A?function(e){var t=st(e,["moov"]);if(1!==t.length||st(e,["moof"]).length)return null;for(var r=e.byteOffset,i=[],n=[],a=!1,s=st(t[0],["trak"]),o=0;o<s.length;o++){var l=s[o],u=st(l,["mdia","hdlr"])[0];if("vide"!==(u?We(u.subarray(8,12)):"")){var d=st(l,["tkhd"])[0];if(!d)return null;var h=d[0];n.push(Ze(d,0===h?12:20)),i.push(nt(l,r))}else a=!0}if(!a||!i.length)return null;var f=st(t[0],["mvex"])[0],c=0;if(f)for(var g=st(f,["trex"]),v=0;v<g.length;v++){var m=g[v];-1!==n.indexOf(Ze(m,4))&&(i.push(nt(m,r)),c+=m.byteLength+8)}var p=at(e,i),y=p.result,E=p.dropped,T=p.droppedBefore;if(rt(y,t[0].byteOffset-r-8,t[0].byteLength+8-E),f&&c){var S=f.byteOffset-r-8;rt(y,S-T(S),f.byteLength+8-c)}return y}(A):null;I&&(this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(I,this.decryptdata),null!=(S=this.initData)&&S.length&&(E=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0))}this.emitInitSegment&&(y.tracks=this.initTracks,v.initSegment=y,this.emitInitSegment=!1);var L=l.iframe,R=!d||L&&!d.includeSampleDetails?function(e,t,r,i,n){return void 0===n&&(n=!0),yt(e,t,i,n)}(m,E,0,this,L):d.tracks,b=E.audio?R[E.audio.id]:null,k=E.video?R[E.video.id]:null,D=!!E.audio,P=!!E.video,_="";D&&(_+="audio"),P&&(_+="video");var C,w=$a(k,1/0),O=$a(b,1/0),M=$a(k,0,!0),F=$a(b,0,!0),N=0;k&&b&&E.audio&&(O>M||w>F)&&this.warn("audio and video track sample timestamps do not overlap. v: "+w+"-"+M+" a: "+O+"-"+F+"}",k,b);var B=!!b&&(!k||!c&&O<w||!!c&&c.trackId===E.audio.id),U=B?b:k;if(!U)return this.log("No media samples found in "+o+" "+l.level+" "+(-1===l.part?"":"part: "+l.part+" of")+" sn: "+l.sn+" at playlist time: "+n),v;var G,K=m;if(k&&k.sampleCount>=1&&E.video&&l.iframe){var V,H=k.trun,Y=k.start,j=1===H.length,W=H.length?j?H[0].samples:(V=H[0].samples).concat.apply(V,H.slice(1).map((function(e){return e.samples}))):[];if(W.length){for(var q=H[0],X=q,z=H.length;z--;)if(H[z].samples.length){X=H[z];break}var Q=X.lastSampleDurationOffset,$=q.defaultSampleDurationOffset,Z=Math.abs(l.duration-(M-w))>.05,J=W.length<k.sampleCount;if(Z||J||this.videoOnlyRemux||!j){var ee=J?X.sampleOffset+X.samples.reduce((function(e,t){return e+t.size}),0):void 0,te=Z?l.duration:M-w,re=function(e,t,r,i){if(void 0!==r){for(var n=e[e.length-1],a=t,s=0;s<e.length-1;s++)a-=e[s].duration;return a<=0&&(a=n.duration),n.duration=a,{durationOffset:r,value:a}}if(void 0!==i){for(var o=Math.round(t/e.length),l=0;l<e.length;l++)e[l].duration=o;return{durationOffset:i,value:o}}}(W,te*E.video.timescale,Q,$),ie=function(e,t,r,i,n){if(r<1)return null;var a=st(e,["moof"]);if(1!==a.length)return null;for(var s=a[0],o=e.byteOffset,l=[],u=[],d=st(s,["traf"]),h=!0,f=0;f<d.length;f++){var c=d[f],g=st(c,["tfhd"])[0];if(!g)return null;Ze(g,4)===t?(l.push(c),131072&Ze(g,0)||(h=!1)):u.push(nt(c,o))}if(!l.length)return null;if(u.length&&!h)return null;if(void 0!==i){for(var v=r,m=0;m<l.length;m++){for(var p=l[m],y=0,E=st(p,["trun"]),T=0;T<E.length;T++){var S=E[T],A=Math.min(v,Ze(S,4));if(A){rt(e,S.byteOffset-o+4,A);var I=16777215&Ze(S,0);it(e,S,8+(1&I?4:0)+(4&I?4:0)+A*((256&I?4:0)+(512&I?4:0)+(1024&I?4:0)+(2048&I?4:0)))}else rt(e,S.byteOffset-o-4,ze.free);v-=A,y+=A}var L=st(p,["senc"])[0];L&&rt(e,L.byteOffset-o+4,y);var R=st(p,["saiz"])[0];if(R){var b=4;1&(R[1]<<16|R[2]<<8|R[3])&&(b+=8);var k=R[b];b+=1,rt(e,R.byteOffset-o+b,y),it(e,R,b+4+(0===k?y:0))}}var D=st(e,["mdat"]);if(1===D.length){var P=D[0].byteOffset-o-8;rt(e,P,i-P)}}var _=e,C=0,w=function(){return 0};if(u.length){var O=at(e,u);_=O.result,C=O.dropped,w=O.droppedBefore,rt(_,s.byteOffset-o-8,s.byteLength+8-C);for(var M=0;M<l.length;M++){for(var x=l[M],F=w(x.byteOffset-o),N=st(x,["trun"]),B=0;B<N.length;B++){var U=N[B];1&Ze(U,0)&&rt(_,U.byteOffset-o-F+8,Ze(U,8)-C)}if(F)for(var G=st(x,["saio"]),K=0;K<G.length;K++){var V=G[K],H=0===V[0]?4:8,Y=1&Ze(V,0)?12:4,j=Ze(V,Y);for(Y+=4;j--;Y+=H){var W=Y+H-4;rt(_,V.byteOffset-o-F+W,Ze(V,W)-F)}}}}if(n){var q=n.durationOffset,X=n.value;rt(_,q-w(q),X)}return void 0!==i?_.subarray(0,i-C):_}(m,E.video.id,W.length,ee,re);ie?(K=ie,G=function(e,t){for(var r=e,i=e,n=0;n<t.length;n++){var a=t[n],s=a.cts,o=a.duration;i=Math.max(i,r+(s||0)+o),r+=o}return i}(Y,W)):this.warn("IFrame remux skipped (sn "+l.sn+"); using native sample duration"),N=ie&&re?te:M-w}else N=M-w}else this.warn("Could not remux IFrame track fragment (no samples in range, trun count "+H.length+")"),N=M-w}else N=B?F-O:M-w;if(this.videoOnlyRemux&&K===m)return this.warn("Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: "+l.sn+")"),v;var ne=U.timescale,ae=U.start-n*ne,se=B?E.audio.id:E.video.id;if(C=U.start/ne,(a||!c)&&(function(e,t,r,i){if(null===e)return!0;var n=Math.max(i,1),a=t-e.baseTime/e.timescale;return Math.abs(a-r)>=n}(c,C,n,N)||ne!==c.timescale)){var oe=!1,le=B?"audio":"video";if(c){var ue=0!==n?C/n:1+C/1;oe=C>=0&&Math.abs(1-ue)<.001,this.log(le+" timestamps in track "+se+" at playlist time: "+(a?"":"~")+n+" maps to "+C+" with initPTS: "+c.baseTime/c.timescale+" ("+(ae/ne-c.baseTime/c.timescale)+"s diff) ("+_+") drift estimate: "+ue+" "+(oe?"(ignoring drift)":"remapping timestamps (initPTS)"))}oe||(this.log("Found initPTS in "+le+" track "+se+" at playlist time: "+n+" offset: "+(C-n)+" ("+ae+"/"+ne+")"),c=null,y.initPTS=ae,y.timescale=ne,y.trackId=se)}c?(y.initPTS=c.baseTime,y.timescale=c.timescale,y.trackId=c.trackId):(y.timescale&&void 0!==y.trackId&&void 0!==y.initPTS||(this.warn("Could not set initPTS"),y.initPTS=C,y.timescale=1,y.trackId=-1),this.initPTS=c={baseTime:y.initPTS,timescale:y.timescale,trackId:y.trackId});var de=C-c.baseTime/c.timescale,he=de+N,fe=P&&void 0!==(null==U?void 0:U.ptsMin)?U.ptsMin/U.timescale-c.baseTime/c.timescale:de,ce=void 0!==G&&k?G/k.timescale-c.baseTime/c.timescale:P&&null!=U&&U.ptsMax?U.ptsMax/U.timescale-c.baseTime/c.timescale:he;N>0?this.lastEndTime=he:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var ge={data1:K,data2:void 0,startPTS:fe,startDTS:de,endPTS:ce,endDTS:he,type:_,hasAudio:D,hasVideo:P,nb:1,dropped:0,encrypted:!!E.audio&&E.audio.encrypted||!!E.video&&E.video.encrypted};v.audio=D&&!P?ge:void 0,v.video=P?ge:void 0;var ve=this.isVideoContiguous,me=null==k?void 0:k.sampleCount;if(me){var pe=k.keyFrameIndex,ye=-1!==pe;ge.nb=me,ge.dropped=0===pe||ve?0:ye?pe:me,ge.independent=ye,ge.firstKeyFrame=pe,ye&&k.keyFrameStart&&(ge.firstKeyFramePTS=(k.keyFrameStart-c.baseTime)/c.timescale),ve||(v.independent=ye),this.isVideoContiguous||(this.isVideoContiguous=ye),ge.dropped&&this.warn("fmp4 does not start with IDR: firstIDR "+pe+"/"+me+" dropped: "+ge.dropped+" start: "+(ge.firstKeyFramePTS||"NA"))}return v.initSegment=y,v.id3=qa(r,n,c,c),i.samples.length&&(v.text=Xa(i,n,c)),v},t}(pe);function $a(e,t,r){return void 0===r&&(r=!1),void 0!==(null==e?void 0:e.start)?(e.start+(r?e.duration:0))/e.timescale:t}function Za(e,t,r){var i=e.codec;return i&&i.length>4?i:t===Z.AUDIO?"ec-3"===i||"ac-3"===i||"alac"===i?i:"fLaC"===i||"Opus"===i?Yt(i,!1):(r.warn('Unhandled audio codec "'+i+'" in mp4 MAP'),i||"mp4a"):"mjpg"===i?i:(r.warn('Unhandled video codec "'+i+'" in mp4 MAP'),i||"avc1")}try{za=self.performance.now.bind(self.performance)}catch(e){za=Date.now}var Ja=[{demux:fa,remux:Qa},{demux:Ea,remux:ja},{demux:sa,remux:ja},{demux:da,remux:ja}];Ja.splice(2,0,{demux:la,remux:ja});var es=function(){function e(e,t,r,i,n,a){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=r,this.id=n,this.logger=a}var t=e.prototype;return t.configure=function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()},t.push=function(e,t,r,i){var n=this;if(!this.observer)return ts(r);var a=r.transmuxing;a.executeStart=za();var s=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;i&&(this.currentTransmuxState=i);var u=i||o,d=u.contiguous,h=u.discontinuity,f=u.trackSwitch,c=u.accurateTimeOffset,g=u.timeOffset,v=u.initSegmentChange,m=l.audioCodec,p=l.videoCodec,y=l.defaultInitPts,E=l.duration,T=l.initSegmentData,S=function(e,t){var r=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(r=t),r}(s,t);if(S&&Di(S.method)){var A=this.getDecrypter(),I=Pi(S.method);return this.asyncResult=!0,this.decryptionPromise=A.decrypt(s,S.key.buffer,S.iv.buffer,I,r.decryptRange).then((function(e){var t=n.push(e,null,r);return n.decryptionPromise=null,t})),this.decryptionPromise}var L=this.needsProbing(h,f);if(L){var R=r.iframe&&T&&Ea.probe(T,this.logger)?T:s,b=this.configureTransmuxer(R);if(b)return this.logger.warn("[transmuxer] "+b.message),this.observer.emit(G.ERROR,G.ERROR,{type:B.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,fatal:!1,error:b,reason:b.message}),a.executeEnd=za(),ts(r)}(h||f||v||L)&&this.resetInitSegment(T,m,p,E,t,r),(h||v||L)&&this.resetInitialTimestamp(y),d||this.resetContiguity();var k=this.transmux(s,S,g,c,r);this.asyncResult=rs(k);var D=this.currentTransmuxState;return D.contiguous=!0,D.discontinuity=!1,D.trackSwitch=!1,a.executeEnd=za(),k},t.flush=function(e){var t=this,r=e.transmuxing;r.executeStart=za();var i=this.decrypter,n=this.currentTransmuxState,a=this.decryptionPromise;if(a)return this.asyncResult=!0,a.then((function(){return t.flush(e)}));var s=[],o=n.timeOffset;if(i){var l=i.flush();l&&s.push(this.push(l.buffer,null,e))}var u=this.demuxer,d=this.remuxer;if(!u||!d){r.executeEnd=za();var h=[ts(e)];return this.asyncResult?Promise.resolve(h):h}var f=u.flush(o,e);return rs(f)?(this.asyncResult=!0,f.then((function(r){return t.flushRemux(s,r,e),s}))):(this.flushRemux(s,f,e),this.asyncResult?Promise.resolve(s):s)},t.flushRemux=function(e,t,r){if(this.remuxer){var i=t.audioTrack,n=t.videoTrack,a=t.id3Track,s=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;this.logger.log("[transmuxer.ts]: Flushed "+this.id+" sn: "+r.sn+(r.part>-1?" part: "+r.part:"")+" of "+this.id+" playlist "+r.level);var d=this.remuxer.remux(i,n,a,s,u,l,!0,this.id,r,t.initData,t.sampleData);e.push({remuxResult:d,chunkMeta:r}),r.transmuxing.executeEnd=za()}},t.resetInitialTimestamp=function(e){var t=this.demuxer,r=this.remuxer;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))},t.resetContiguity=function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())},t.resetInitSegment=function(e,t,r,i,n,a){var s=this.demuxer,o=this.remuxer;s&&o&&(s.resetInitSegment(e,t,r,i,n,a),o.resetInitSegment(e,t,r,n))},t.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0},t.transmux=function(e,t,r,i,n){return"SAMPLE-AES"===(null==t?void 0:t.method)?this.transmuxSampleAes(e,t,r,i,n):this.transmuxUnencrypted(e,r,i,n)},t.transmuxUnencrypted=function(e,t,r,i){var n=this.demuxer,a=this.remuxer;if(!n||!a)return ts(i);var s=n.demux(e,t,i,!1,!this.config.progressive),o=s.audioTrack,l=s.videoTrack,u=s.id3Track,d=s.textTrack;return{remuxResult:a.remux(o,l,u,d,t,r,!1,this.id,i,s.initData,s.sampleData),chunkMeta:i}},t.transmuxSampleAes=function(e,t,r,i,n){var a=this;return this.demuxer?this.demuxer.demuxSampleAes(e,t,r,n).then((function(e){return{remuxResult:a.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,i,!1,a.id,n,e.initData,e.sampleData),chunkMeta:n}})):Promise.reject(new Error("no demuxer"))},t.configureTransmuxer=function(e){var t=this.config,r=this.observer,i=this.typeSupported;if(r){var n;try{for(var a=0,s=Ja.length;a<s;a++){var o;if(null!=(o=Ja[a].demux)&&o.probe(e,this.logger)){n=Ja[a];break}}}catch(e){return e}if(!n)return new Error("Failed to find demuxer by probing fragment data");var l=this.demuxer,u=this.remuxer,d=n.demux,h=n.remux;l&&l instanceof d||(this.logger.log("Using "+d.name),this.demuxer=new d(r,t,i,this.logger),this.probe=d.probe),u&&u instanceof h||(this.logger.log("Using "+h.name),this.remuxer=new h(r,t,i,this.logger))}},t.needsProbing=function(e,t){return!this.demuxer||!this.remuxer||e||t},t.getDecrypter=function(){var e=this.decrypter;return e||(e=this.decrypter=new ni(this.config)),e},e}(),ts=function(e){return{remuxResult:{},chunkMeta:e}};function rs(e){return"then"in e&&e.then instanceof Function}var is=function(e,t,r,i,n){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=r,this.duration=i,this.defaultInitPts=n||null},ns=function(e,t,r,i,n,a){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=r,this.trackSwitch=i,this.timeOffset=n,this.initSegmentChange=a},as=[];function ss(e,t,r){if(!((i=t.remuxResult).audio||i.video||i.text||i.id3||i.initSegment))return!1;var i,n=[],a=t.remuxResult,s=a.audio,o=a.video;return s&&os(n,s),o&&os(n,o),e.postMessage({event:"transmuxComplete",data:t,instanceNo:r},n),!0}function os(e,t){t.data1&&e.push(t.data1.buffer),t.data2&&e.push(t.data2.buffer)}function ls(e,t,r,i){t.reduce((function(t,r){return ss(e,r,i)||t}),!1)||e.postMessage({event:"transmuxComplete",data:t[0],instanceNo:i}),e.postMessage({event:"flush",data:r,instanceNo:i})}function us(e,t,r){self.postMessage({event:e,data:t,instanceNo:r})}void 0!==t&&t&&self.addEventListener("message",(function(e){var t=e.data,r=t.instanceNo;if(void 0!==r){var i=as[r];if("reset"===t.cmd&&(delete as[t.resetNo],i&&i.destroy(),t.cmd="init"),"init"===t.cmd){var n=JSON.parse(t.config),a=new w;a.on(G.FRAG_DECRYPTED,(function(e,t){return us(e,t,r)})),a.on(G.ERROR,(function(e,t){return us(e,t,r)}));var s=Ie(n.debug,t.id);return function(e,t){var r=function(r){e[r]=function(){var e=Array.prototype.join.call(arguments," ");us("workerLog",{logType:r,message:e},t)}};for(var i in e)r(i)}(s,r),as[r]=new es(a,t.typeSupported,n,"",t.id,s),void us("init",null,r)}if(i)switch(t.cmd){case"configure":i.configure(t.config);break;case"demux":var o=i.push(t.data,t.decryptdata,t.chunkMeta,t.state);rs(o)?o.then((function(e){ss(self,e,r)})).catch((function(e){us(G.ERROR,{instanceNo:r,type:B.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,chunkMeta:t.chunkMeta,fatal:!1,error:e,err:e,reason:"transmuxer-worker push error"},r)})):ss(self,o,r);break;case"flush":var l=t.chunkMeta,u=i.flush(l);rs(u)?u.then((function(e){ls(self,e,l,r)})).catch((function(e){us(G.ERROR,{type:B.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,chunkMeta:t.chunkMeta,fatal:!1,error:e,err:e,reason:"transmuxer-worker flush error"},r)})):ls(self,u,l,r)}}}));var ds="1.7.2",hs={},fs=0,cs=function(){function t(t,r,i,n){var a=this;this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=fs++,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=function(e){var t=e.data,r=a.hls;if(r&&null!=t&&t.event&&t.instanceNo===a.instanceNo)switch(t.event){case"init":var i,n=null==(i=a.workerContext)?void 0:i.objectURL;n&&self.URL.revokeObjectURL(n);break;case"transmuxComplete":a.handleTransmuxComplete(t.data);break;case"flush":a.onFlush(t.data);break;case"workerLog":r.logger[t.data.logType]&&r.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=a.frag,t.data.part=a.part,t.data.id=a.id,r.trigger(t.event,t.data)}},this.onWorkerError=function(e){if(a.hls){var t=new Error(e.message+" ("+e.filename+":"+e.lineno+")");a.hls.config.enableWorker=!1,a.hls.logger.warn('Error in "'+a.id+'" Web Worker, fallback to inline'),a.hls.trigger(G.ERROR,{type:B.OTHER_ERROR,details:U.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})}};var s=t.config;this.hls=t,this.id=r,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;var o=function(e,t){(t=t||{}).frag=a.frag||void 0,e===G.ERROR&&(t.parent=a.id,t.part=a.part,a.error=t.error),a.hls.trigger(e,t)};this.observer=new w,this.observer.on(G.FRAG_DECRYPTED,o),this.observer.on(G.ERROR,o);var l=Xt(s.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){var u=this.hls.logger;s.workerPath;try{s.workerPath?(u.log("loading Web Worker "+s.workerPath+' for "'+r+'"'),this.workerContext=function(e){var t=hs[e];if(t)return t.clientCount++,t;var r=new self.URL(e,self.location.href).href,i={worker:new self.Worker(r),scriptURL:r,clientCount:1};return hs[e]=i,i}(s.workerPath)):(u.log('injecting Web Worker for "'+r+'"'),this.workerContext=function(){var t=hs[ds];if(t)return t.clientCount++,t;var r=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;("+e.toString()+")(true);"],{type:"text/javascript"}),i=self.URL.createObjectURL(r),n={worker:new self.Worker(i),objectURL:i,clientCount:1};return hs[ds]=n,n}());var d=this.workerContext.worker;d.addEventListener("message",this.onWorkerMessage),d.addEventListener("error",this.onWorkerError),d.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:l,id:r,config:cr(s)})}catch(e){u.warn('Error setting up "'+r+'" Web Worker, fallback to inline',e),this.terminateWorker(),this.error=null,this.transmuxer=new es(this.observer,l,s,"",r,t.logger)}}else this.transmuxer=new es(this.observer,l,s,"",r,t.logger)}var r=t.prototype;return r.reset=function(){if(this.frag=null,this.part=null,this.workerContext){var e=this.instanceNo;this.instanceNo=fs++;var t=this.hls.config,r=Xt(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:cr(t)})}},r.terminateWorker=function(){if(this.workerContext){var e=this.workerContext.worker;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){var t=hs[e||ds];if(t&&1==t.clientCount--){var r=t.worker,i=t.objectURL;delete hs[e||ds],i&&self.URL.revokeObjectURL(i),r.terminate()}}(this.hls.config.workerPath)}},r.destroy=function(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null},r.push=function(e,t,r,i,n,a,s,o,l,u){var d,h,f=this;l.transmuxing.start=self.performance.now();var c=this.instanceNo,g=this.transmuxer,v=a?a.start:n.start,m=n.decryptdata,p=this.frag,y=!p||n.cc!==p.cc,E=!p||l.level!==p.level,T=p?l.sn-p.sn:-1,S=this.part?l.part-this.part.index:-1,A=0===T&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),I=!E&&(1===T||0===T&&(1===S||A&&S<=0)),L=self.performance.now();(E||T||0===n.stats.parsing.start)&&(n.stats.parsing.start=L),!a||!S&&I||(a.stats.parsing.start=L);var R=!(p&&(null==(d=n.initSegment)?void 0:d.url)===(null==(h=p.initSegment)?void 0:h.url)),b=new ns(y,I,o,E,v,R);if(!I||y||R){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for "+n.type+" sn: "+l.sn+(l.part>-1?" part: "+l.part:"")+" "+this.id+" playlist: "+l.level+" id: "+l.id+"\n discontinuity: "+y+"\n trackSwitch: "+E+"\n contiguous: "+I+"\n accurateTimeOffset: "+o+"\n timeOffset: "+v+"\n initSegmentChange: "+R);var k=new is(r,i,t,s,u);this.configureTransmuxer(k)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:c,cmd:"demux",data:e,decryptdata:m,chunkMeta:l,state:b},e instanceof ArrayBuffer?[e]:[]);else if(g){var D=g.push(e,m,l,b);rs(D)?D.then((function(e){f.handleTransmuxComplete(e)})).catch((function(e){f.transmuxerError(e,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(D)}},r.flush=function(e){var t=this;e.transmuxing.start=self.performance.now();var r=this.instanceNo,i=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:r,cmd:"flush",chunkMeta:e});else if(i){var n=i.flush(e);rs(n)?n.then((function(r){t.handleFlushResult(r,e)})).catch((function(r){t.transmuxerError(r,e,"transmuxer-interface flush error")})):this.handleFlushResult(n,e)}},r.transmuxerError=function(e,t,r){this.hls&&(this.error=e,this.hls.trigger(G.ERROR,{type:B.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:r}))},r.handleFlushResult=function(e,t){var r=this;e.forEach((function(e){r.handleTransmuxComplete(e)})),this.onFlush(t)},r.configureTransmuxer=function(e){var t=this.instanceNo,r=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):r&&r.configure(e)},r.handleTransmuxComplete=function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)},t}(),gs=function(e){function t(t,r,i){var n;return(n=e.call(this,t,r,i,"audio-stream-controller",$.AUDIO)||this).mainAnchor=null,n.mainFragLoading=null,n.audioOnly=!1,n.bufferedTrack=null,n.switchingTrack=null,n.trackId=-1,n.nextTrackId=-1,n.waitingData=null,n.mainDetails=null,n.flushing=!1,n.bufferFlushed=!1,n.cachedTrackLoadedData=null,n.registerListeners(),n}d(t,e);var r=t.prototype;return r.onHandlerDestroying=function(){this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this),this.resetItem()},r.resetItem=function(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null},r.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(G.LEVEL_LOADED,this.onLevelLoaded,this),t.on(G.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(G.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(G.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(G.BUFFER_RESET,this.onBufferReset,this),t.on(G.BUFFER_CREATED,this.onBufferCreated,this),t.on(G.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(G.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(G.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(G.FRAG_LOADING,this.onFragLoading,this),t.on(G.FRAG_BUFFERED,this.onFragBuffered,this)},r.unregisterListeners=function(){var t=this.hls;t&&(e.prototype.unregisterListeners.call(this),t.off(G.LEVEL_LOADED,this.onLevelLoaded,this),t.off(G.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(G.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(G.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(G.BUFFER_RESET,this.onBufferReset,this),t.off(G.BUFFER_CREATED,this.onBufferCreated,this),t.off(G.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(G.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(G.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(G.FRAG_LOADING,this.onFragLoading,this),t.off(G.FRAG_BUFFERED,this.onFragBuffered,this))},r.onInitPtsFound=function(e,t){var r=t.frag,i=t.id,n=t.initPTS,a=t.timescale,s=t.trackId,o=t.timestampOffsets;if(i===$.MAIN){var l=r.cc,u=this.fragCurrent;if(this.initPTS=o,this.log("InitPTS for cc: "+l+" found from main: "+n/a+" ("+n+"/"+a+") trackId: "+s),this.mainAnchor=r,this.state===On.WAITING_INIT_PTS){var d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==l)&&this.syncWithAnchor(r,null==d?void 0:d.frag)}else!this.hls.hasEnoughToStart&&u&&u.cc!==l?(u.abortRequests(),this.syncWithAnchor(r,u)):this.state===On.IDLE&&this.tick()}},r.getLoadPosition=function(){var t;return!this.startFragRequested&&this.nextLoadPosition>=0&&!1!==(null==(t=this.switchingTrack)?void 0:t.flushImmediate)?this.nextLoadPosition:e.prototype.getLoadPosition.call(this)},r.syncWithAnchor=function(e,t){var r,i=(null==(r=this.mainFragLoading)?void 0:r.frag)||null;if(!t||(null==i?void 0:i.cc)!==t.cc){var n=(i||e).cc,a=Pr(this.getLevelDetails(),n,this.getLoadPosition());a&&(this.log("Syncing with main frag at "+a.start+" cc "+a.cc),this.startFragRequested=!1,this.nextLoadPosition=a.start,this.resetLoadingState(),this.state===On.IDLE&&this.doTickIdle())}},r.startLoad=function(e,t){if(!this.levels)return this.startPosition=e,void(this.state=On.STOPPED);var r=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),r>0&&-1===e&&!t&&this.initPTS.length&&(this.log("Override startPosition with lastCurrentTime @"+r.toFixed(3)),e=r),this.state=On.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this.startFragRequested=!1),this.tick()},r.doTick=function(){switch(this.state){case On.IDLE:this.doTickIdle();break;case On.WAITING_TRACK:var t=this.levels,r=this.trackId,i=null==t?void 0:t[r],n=null==i?void 0:i.details;if(n&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(n))break;this.state=On.WAITING_INIT_PTS}break;case On.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case On.WAITING_INIT_PTS:var a=this.waitingData;if(a){var s=a.frag,o=a.part,l=a.cache,u=a.complete,d=this.mainAnchor;if(void 0!==this.initPTS[s.cc]){this.waitingData=null,this.state=On.FRAG_LOADING;var h={frag:s,part:o,payload:l.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(h),u&&e.prototype._handleFragmentLoadComplete.call(this,h)}else d&&d.cc!==a.frag.cc&&this.syncWithAnchor(d,a.frag)}else this.state=On.IDLE}this.onTickEnd()},r.resetLoadingState=function(){var t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),e.prototype.resetLoadingState.call(this)},r.onTickEnd=function(){var e=this.media;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime,this.checkFragmentChanged())},r.doTickIdle=function(){var e,t=this.hls,r=this.levels,i=this.media,n=this.trackId,a=t.config;if(this.buffering&&(i||this.primaryPrefetch||!this.startFragRequested&&a.startFragPrefetch)&&null!=r&&r[n]){var s=r[n],o=s.details;if(!o||this.waitForLive(s)||this.waitForCdnTuneIn(o))return this.state=On.WAITING_TRACK,void(this.startFragRequested=!1);var l=this.getBufferOutput();this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Z.AUDIO));var u=this.getFwdBufferInfo();if(null!==u){if(!this.switchingTrack&&this._streamEnded(u,o))return t.trigger(G.BUFFER_EOS,{type:"audio"}),void(this.state=On.ENDED);var d=u.len,h=t.maxBufferLength,f=o.fragments,c=f[0].start,g=this.getLoadPosition(),v=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?g:u.end;if(this.switchingTrack&&i){var m=g;o.PTSKnown&&m<c&&m>=this.timelineOffset&&(u.end>c||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track "+m+" -> "+c+" + 0.05"),i.currentTime=c+.05)}if(!(d>=h&&!this.switchingTrack&&v<f[f.length-1].start)){var p=this.getNextFragment(v,o);if(p&&this.isLoopLoading(p,v)&&(p=this.getNextFragmentLoopLoading(p,o,u,$.MAIN,h)),p){if(!this.exceedsMaxBuffer(u,h,p)){var y=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&ee(p)&&!p.endList&&(!o.live||!this.loadingParts&&v<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===Xr&&(this.mainFragLoading=y=null),y&&ee(y))){if(p.start>y.end){var E=this.fragmentTracker.getFragAtPos(v,$.MAIN);E&&E.end>y.end&&(y=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(p.start>y.end)return}this.loadFragment(p,s,v)}}else this.bufferFlushed=!0}}}},r.onMediaDetaching=function(t,r){this.bufferFlushed=this.flushing=!1,e.prototype.onMediaDetaching.call(this,t,r)},r.onAudioTracksUpdated=function(e,t){var r=t.audioTracks;this.resetTransmuxer(),this.levels=r.map((function(e){return new dr(e)}))},r.onAudioTrackSwitching=function(e,t){var r=!!t.url;this.trackId=t.id;var i=this.fragCurrent;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),r?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==On.STOPPED&&(this.setInterval(100),this.state=On.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())},r.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1},r.onLevelLoaded=function(e,t){this.mainDetails=t.details;var r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(G.AUDIO_TRACK_LOADED,r))},r.onAudioTrackLoaded=function(e,t){var r,i=this.levels,n=t.details,a=t.id,s=t.groupId,o=t.track;if(i){var l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==On.STOPPED&&(this.state=On.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log("Audio track "+a+' "'+o.name+'" of "'+s+'" loaded ['+n.startSN+","+n.endSN+"]"+(n.lastPartSn?"[part-"+n.lastPartSn+"-"+n.lastPartIndex+"]":"")+",duration:"+n.totalduration);var u=i[a],d=0;if(n.live||null!=(r=u.details)&&r.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;var h;u.details&&(d=this.alignPlaylists(n,u.details,null==(h=this.levelLastLoaded)?void 0:h.details)),n.alignedSliding||(Pn(l,n,this),d=n.fragmentStart)}u.details=n,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(l,d),this.hls.trigger(G.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state!==On.WAITING_TRACK||this.waitForCdnTuneIn(n)||(this.state=On.IDLE),this.tick()}else this.warn("Audio tracks reset while loading track "+a+' "'+o.name+'" of "'+s+'"')},r._handleFragmentLoadProgress=function(e){var t,r=e.frag,i=e.part,n=e.payload,a=this.config,s=this.trackId,o=this.levels;if(o){var l=o[s];if(l){var u=l.details;if(!u)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(r.start);var d=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2",h=this.transmuxer;h||(h=this.transmuxer=new cs(this.hls,$.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var f=this.initPTS[r.cc],c=null==(t=r.initSegment)?void 0:t.data;if(void 0!==f){var g=i?i.index:-1,v=-1!==g,m=new fi(r.level,r.sn,r.stats.chunkCount,n.byteLength,g,v,r.duration);h.push(n,c,d,"",r,i,u.totalduration,!1,m,f)}else this.log("Unknown video PTS for cc "+r.cc+", waiting for video PTS before demuxing audio frag "+r.sn+" of ["+u.startSN+" ,"+u.endSN+"],track "+s),(this.waitingData=this.waitingData||{frag:r,part:i,cache:new Nn,complete:!1}).cache.push(new Uint8Array(n)),this.state!==On.STOPPED&&(this.state=On.WAITING_INIT_PTS)}else this.warn("Audio track is undefined on fragment load progress")}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},r._handleFragmentLoadComplete=function(t){this.waitingData?this.waitingData.complete=!0:e.prototype._handleFragmentLoadComplete.call(this,t)},r.onBufferReset=function(){this.mediaBuffer=null},r.onBufferCreated=function(e,t){this.bufferFlushed=this.flushing=!1;var r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)},r.onFragLoading=function(e,t){!this.audioOnly&&t.frag.type===$.MAIN&&ee(t.frag)&&(this.mainFragLoading=t,this.state===On.IDLE&&this.tick())},r.onFragBuffered=function(e,t){var r=t.frag,i=t.part;if(r.type===$.AUDIO)if(this.fragContextChanged(r))this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state+", audioSwitch: "+(this.switchingTrack?this.switchingTrack.name:"false"));else{if(ee(r)){var n=this.switchingTrack;n&&(this.bufferedTrack=n)}this.fragBufferedComplete(r,i),this.media&&this.tick()}else this.audioOnly||r.type!==$.MAIN||r.elementaryStreams.video||r.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)},r.getFwdBufferInfo=function(){var t=this.getBufferOutput();return e.prototype.getFwdBufferInfo.call(this,t,$.AUDIO)},r.getBufferOutput=function(){return this.mediaBuffer?this.mediaBuffer:this.media},r.checkFragmentChanged=function(){var e=this.fragPlaying;if(!this.checkFragPlaying())return!1;var t=this.fragPlaying,r=null==e?void 0:e.level;return t&&t.level===r||(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0},r.onError=function(t,r){var i;if(r.fatal)this.state=On.ERROR;else switch(r.details){case U.FRAG_GAP:case U.FRAG_PARSING_ERROR:case U.FRAG_DECRYPT_ERROR:case U.FRAG_LOAD_ERROR:case U.FRAG_LOAD_TIMEOUT:case U.KEY_LOAD_ERROR:case U.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError($.AUDIO,r);break;case U.AUDIO_TRACK_LOAD_ERROR:case U.AUDIO_TRACK_LOAD_TIMEOUT:case U.LEVEL_PARSING_ERROR:r.levelRetry||this.state!==On.WAITING_TRACK||(null==(i=r.context)?void 0:i.type)!==Y||(this.state=On.IDLE);break;case U.BUFFER_APPEND_NO_PROGRESS:if("audio"!==r.parent)return;r.frag&&(r.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn("Marking fragment "+r.frag.sn+" of track "+r.frag.level+" as a gap after "+r.appendsWithoutProgress+" appends without buffered range growth, to prevent loop loading"),this.fragmentTracker.addAsGap(r.frag));break;case U.BUFFER_ADD_CODEC_ERROR:case U.BUFFER_APPEND_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case U.BUFFER_FULL_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"));break;case U.INTERNAL_EXCEPTION:this.recoverWorkerError(r)}},r.onBufferFlushing=function(e,t){t.type!==Z.VIDEO&&(this.flushing=!0)},r.onBufferFlushed=function(e,t){var r=t.type;if(r!==Z.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===On.ENDED&&(this.state=On.IDLE);var i=this.getBufferOutput();i&&(this.afterBufferFlushed(i,r),this.tick())}},r._handleTransmuxComplete=function(t){var r,i="audio",n=this.hls,a=t.remuxResult,s=t.chunkMeta,o=this.getCurrentContext(s);if(o){var u=o.frag,d=o.part,h=o.level,f=h.details,c=a.audio,g=a.text,v=a.id3,m=a.initSegment;if(this.fragContextChanged(u)||!f)return this.fragmentTracker.removeFragment(u),void(null!=m&&m.tracks&&this.resetTransmuxer());if(this.state=On.PARSING,c&&this.switchingTrack&&!this.switchingTrack.flushImmediate){var p=this.config.nextAudioTrackBufferFlushForwardOffset,y=Math.max(this.getLoadPosition()+p,u.start);e.prototype.flushMainBuffer.call(this,y,Number.POSITIVE_INFINITY,$.AUDIO)}if(null!=m&&m.tracks){var E=u.initSegment||u;if(this.unhandledEncryptionError(m,u))return;this._bufferInitSegment(h,m.tracks,E,s),n.trigger(G.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:i,tracks:m.tracks})}if(c){var T=c.startPTS,S=c.endPTS,A=c.startDTS,I=c.endDTS;d&&(d.elementaryStreams[Z.AUDIO]={startPTS:T,endPTS:S,startDTS:A,endDTS:I}),u.setElementaryStreamInfo(Z.AUDIO,T,S,A,I),this.bufferFragmentData(c,u,d,s)}if(null!=v&&null!=(r=v.samples)&&r.length){var L=l({id:i,frag:u,details:f},v);n.trigger(G.FRAG_PARSING_METADATA,L)}if(g){var R=l({id:i,frag:u,details:f},g);n.trigger(G.FRAG_PARSING_USERDATA,R)}}else this.resetWhenMissingContext(s)},r._bufferInitSegment=function(e,t,r,i){if(this.state===On.PARSING&&(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,t.audio)){var n=t.audio;n.id=$.AUDIO;var a=e.audioCodec;this.log("Init audio buffer, container:"+n.container+", codecs[level/parsed]=["+a+"/"+n.codec+"]"),1===(null==a?void 0:a.split(",").length)&&(n.levelCodec=a),this.hls.trigger(G.BUFFER_CODECS,t);var s=n.initSegment;if(null!=s&&s.byteLength){var o={type:"audio",frag:r,part:null,chunkMeta:i,parent:r.type,data:s};this.hls.trigger(G.BUFFER_APPENDING,o)}this.tickImmediate()}},r.loadFragment=function(t,r,i){var n,a=this.fragmentTracker.getState(t);if(this.switchingTrack||a===jr||a===qr)if(null!=(n=r.details)&&n.live&&!this.initPTS[t.cc]){this.log("Waiting for video PTS in continuity counter "+t.cc+" of live stream before loading audio fragment "+t.sn+" of level "+this.trackId),this.state=On.WAITING_INIT_PTS;var s=this.mainDetails;s&&s.fragmentStart!==r.details.fragmentStart&&Pn(s,r.details,this)}else e.prototype.loadFragment.call(this,t,r,i);else this.clearTrackerIfNeeded(t)},r.flushAudioIfNeeded=function(t){if(this.media&&this.bufferedTrack&&t.flushImmediate){var r=this.bufferedTrack;yr({name:r.name,lang:r.lang,assocLang:r.assocLang,characteristics:r.characteristics,audioCodec:r.audioCodec,channels:r.channels},t,Er)||(Sr(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}},r.completeAudioSwitch=function(e){var t=this.hls;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(G.AUDIO_TRACK_SWITCHED,c({},e))},a(t,[{key:"nextAudioTrack",get:function(){return this.nextTrackId}}])}(Mn),vs=function(e){function t(t,r){var i;return(i=e.call(this,r,t.logger)||this).hls=void 0,i.canLoad=!1,i.timer=-1,i.hls=t,i}d(t,e);var r=t.prototype;return r.destroy=function(){this.clearTimer(),this.hls=null},r.clearTimer=function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)},r.startLoad=function(){this.canLoad=!0,this.loadPlaylist()},r.stopLoad=function(){this.canLoad=!1,this.clearTimer()},r.switchParams=function(e,t,r){var i=null==t?void 0:t.renditionReports;if(i){for(var n=-1,a=0;a<i.length;a++){var s=i[a],o=void 0;try{o=new self.URL(s.URI,t.url).href}catch(e){this.warn("Could not construct new URL for Rendition Report: "+e),o=s.URI||""}if(o===e){n=a;break}o===e.substring(0,o.length)&&(n=a)}if(-1!==n){var l=i[n],u=parseInt(l["LAST-MSN"])||t.lastPartSn,d=parseInt(l["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){var h=Math.min(t.age-t.partTarget,t.targetduration);d>=0&&h>t.partTarget&&(d+=1)}var f=r&&lr(r);return new ur(u,d>=0?d:void 0,f)}}},r.loadPlaylist=function(e){this.clearTimer()},r.loadingPlaylist=function(e,t){this.clearTimer()},r.shouldLoadPlaylist=function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)},r.getUrlWithDirectives=function(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: "+e)}return e},r.playlistLoaded=function(e,t,r){var i=t.details,n=t.stats,a=i.fragments,s=self.performance.now(),o=n.loading.first?Math.max(0,Math.floor(s-n.loading.first)):0;i.advancedDateTime=Date.now()-o;var l=this.hls.config.timelineOffset;if(l!==i.appliedTimelineOffset){var u=Math.max(l||0,0);i.appliedTimelineOffset=u,a.forEach((function(e){null==e||e.setStart(e.playlistOffset+u)}))}if(i.live||null!=r&&r.live){var d,h="levelInfo"in t?t.levelInfo:t.track;i.reloaded(r);var f=null==(d=a[a.length-1])?void 0:d.type;if(i.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){var c=new Error(f+" playlist "+h.id+" hit max allowed unchanged reloads.");this.warn(c);var g=t.networkDetails,v=t.context;return void this.hls.trigger(G.ERROR,{type:B.NETWORK_ERROR,details:U.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:i.url,error:c,reason:c.message,level:t.level,parent:f,context:v,networkDetails:g,stats:n})}if(r){mn(r,i,this);var m=i.playlistParsingError;if(m){this.warn(m);var p=this.hls;if(!p.config.ignorePlaylistParsingErrors){var y=t.networkDetails;return void p.trigger(G.ERROR,{type:B.NETWORK_ERROR,details:U.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:m,reason:m.message,level:t.level,parent:f,networkDetails:y,stats:n})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=n.loading.start);var E=this.hls.mainForwardBufferInfo,T=E?E.end-E.len:0,S=En(i,1e3*(i.edge-T));i.requestScheduled+S<s?i.requestScheduled=s:i.requestScheduled<=s&&(i.requestScheduled+=S);var A,I=t.deliveryDirectives;if(this.log("live playlist "+e+" "+(i.advanced?"REFRESHED "+i.lastPartSn+" - "+i.lastPartIndex:i.updated?"UPDATED":"MISSED (received "+i.lastPartSn+" - "+i.lastPartIndex+(I?" | requested "+I.msn+" - "+I.part:"")+")")),!this.canLoad||!i.live)return;var L=void 0,R=void 0;if(i.canBlockReload&&i.advanced){var b=this.hls.config.lowLatencyMode,k=i.lastPartSn,D=i.endSN,P=i.lastPartIndex,_=k===D;-1!==P?_?(L=D+1,R=b?0:P):(L=k,R=b?P+1:i.maxPartIndex):L=D+1;var C=i.age,w=C+i.ageHeader,O=Math.min(w-i.partTarget,1.5*i.targetduration);if(O>0){if(w>3*i.targetduration)this.log("Playlist last advanced "+C.toFixed(2)+"s ago. Omitting segment and part directives."),L=void 0,R=void 0;else if(null!=r&&r.tuneInGoal&&w-i.partTarget>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+O+" with playlist age: "+i.age),O=0;else{var M=Math.floor(O/i.targetduration);L+=M,void 0!==R&&(R+=Math.round(O%i.targetduration/i.partTarget)),this.log("CDN Tune-in age: "+i.ageHeader+"s last advanced "+C.toFixed(2)+"s goal: "+O+" skip sn "+M+" to part "+R)}i.tuneInGoal=O}if(A=this.getDeliveryDirectives(i,t.deliveryDirectives,L,R),b||!_)return i.requestScheduled=s,void this.loadingPlaylist(h,A)}else(i.canBlockReload||i.canSkipUntil)&&(A=this.getDeliveryDirectives(i,t.deliveryDirectives,L,R));A&&void 0!==L&&i.canBlockReload&&(i.requestScheduled=n.loading.first+Math.max(S-2*o,S/2)),this.scheduleLoading(h,A,i)}else this.clearTimer()},r.scheduleLoading=function(e,t,r){var i=this,n=r||e.details;if(n){var a=self.performance.now(),s=n.requestScheduled;if(a>=s)this.loadingPlaylist(e,t);else{var o=s-a;this.log("reload live playlist "+(e.name||e.bitrate+"bps")+" in "+Math.round(o)+" ms"),this.clearTimer(),this.timer=self.setTimeout((function(){return i.loadingPlaylist(e,t)}),o)}}else this.loadingPlaylist(e,t)},r.getDeliveryDirectives=function(e,t,r,i){var n=lr(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,i=t.part,n=ar),new ur(r,i,n)},r.checkRetry=function(e){var t=this,r=e.details,i=se(e),n=e.errorAction,a=n||{},s=a.action,o=a.retryCount,l=void 0===o?0:o,u=a.retryConfig,d=!!n&&!!u&&(s===Mr||!n.resolved&&s===wr);if(d){var h;if(l>=u.maxNumRetry)return!1;if(i&&null!=(h=e.context)&&h.deliveryDirectives)this.warn("Retrying playlist loading "+(l+1)+"/"+u.maxNumRetry+' after "'+r+'" without delivery-directives'),this.loadPlaylist();else{var f,c=ce(null==(f=e.response)?void 0:f.code);if(this.clearTimer(),c)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout((function(){return t.checkOfflineStatus()}),1e3);else{var g=de(u,l);this.warn("Retrying playlist loading "+(l+1)+"/"+u.maxNumRetry+' after "'+r+'" in '+g+"ms"),this.timer=self.setTimeout((function(){return t.loadPlaylist()}),g)}}e.levelRetry=!0,n.resolved=!0}return d},r.checkOfflineStatus=function(){var e=this;this.clearTimer(),ce(0)?this.timer=self.setTimeout((function(){return e.checkOfflineStatus()}),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())},t}(pe);function ms(e,t){if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++)if(!ps(e[r].attrs,t[r].attrs))return!1;return!0}function ps(e,t,r){var i=e["STABLE-RENDITION-ID"];return i&&!r?i===t["STABLE-RENDITION-ID"]:!(r||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((function(r){return e[r]!==t[r]}))}var ys=function(e){function t(t){var r;return(r=e.call(this,t,"audio-track-controller")||this).tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.registerListeners(),r}d(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_PARSED,this.onManifestParsed,this),e.on(G.LEVEL_LOADING,this.onLevelLoading,this),e.on(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(G.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(G.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_PARSED,this.onManifestParsed,this),e.off(G.LEVEL_LOADING,this.onLevelLoading,this),e.off(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(G.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(G.ERROR,this.onError,this)},r.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,e.prototype.destroy.call(this)},r.onManifestLoading=function(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0},r.onManifestParsed=function(e,t){this.tracks=t.audioTracks||[]},r.onAudioTrackLoaded=function(e,t){var r=t.id,i=t.groupId,n=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===i){var s=a.details;a.details=t.details,this.log("Audio track "+r+' "'+a.name+'" lang:'+a.lang+" group:"+i+" loaded ["+n.startSN+"-"+n.endSN+"]"),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Audio track with id:"+r+" and group:"+i+" not found in active group "+(null==a?void 0:a.groupId))},r.onLevelLoading=function(e,t){this.switchLevel(t.level)},r.onLevelSwitching=function(e,t){this.switchLevel(t.level)},r.switchLevel=function(e){var t=this.hls.levels[e];if(t){var r=t.audioGroups||null,i=this.groupIds,n=this.currentTrack;if(!r||(null==i?void 0:i.length)!==(null==r?void 0:r.length)||null!=r&&r.some((function(e){return-1===(null==i?void 0:i.indexOf(e))}))){this.groupIds=r,this.trackId=-1,this.currentTrack=null;var a=this.tracks.filter((function(e){return Ar(e.groupId,r)}));if(a.length)this.selectDefaultTrack&&!a.some((function(e){return e.default}))&&(this.selectDefaultTrack=!1),a.forEach((function(e,t){e.id=t}));else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;var s=this.hls.config.audioPreference;if(!n&&s){var o=pr(s,a,Er);if(o>-1)n=a[o];else{var l=pr(s,this.tracks);n=this.tracks[l]}}var u=this.findTrackId(n);-1===u&&n&&(u=this.findTrackId(null));var d={audioTracks:a};this.log("Updating audio tracks, "+a.length+" track(s) found in group(s): "+(null==r?void 0:r.join(","))),this.hls.trigger(G.AUDIO_TRACKS_UPDATED,d);var h=this.trackId;if(-1!==u&&-1===h)this.setAudioTrack(u);else if(a.length&&-1===h){var f,c=new Error("No audio track selected for current audio group-ID(s): "+(null==(f=this.groupIds)?void 0:f.join(","))+" track count: "+a.length);this.warn(c.message),this.hls.trigger(G.ERROR,{type:B.MEDIA_ERROR,details:U.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:c})}}}},r.onError=function(e,t){!t.fatal&&t.context&&t.context.type===Y&&t.context.id===this.trackId&&Ar(t.context.groupId,this.groupIds)&&this.checkRetry(t)},r.setAudioOption=function(e){var t=this.hls;if(t.config.audioPreference=e,e){var r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){var i=this.currentTrack;if(i&&yr(e,i,Er))return i;var n=pr(e,this.tracksInGroup,Er);if(n>-1){var a=this.tracksInGroup[n];return this.setAudioTrack(n,"flushImmediate"in e&&e.flushImmediate),a}if(i){var s=t.loadLevel;-1===s&&(s=t.firstAutoLevel);var o=function(e,t,r,i,n){var a=t[i],s=t.reduce((function(e,t,r){var i=t.uri;return(e[i]||(e[i]=[])).push(r),e}),{})[a.uri];s.length>1&&(i=Math.max.apply(Math,s));var o=a.videoRange,l=a.frameRate,u=a.codecSet.substring(0,4),d=Tr(t,i,(function(t){if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==u)return!1;var i=t.audioGroups,a=r.filter((function(e){return Ar(e.groupId,i)}));return pr(e,a,n)>-1}));return d>-1?d:Tr(t,i,(function(t){var i=t.audioGroups,a=r.filter((function(e){return Ar(e.groupId,i)}));return pr(e,a,n)>-1}))}(e,t.levels,r,s,Er);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=pr(e,r);if(l>-1)return r[l]}}}return null},r.setAudioTrack=function(e,t){void 0===t&&(t=!0);var r=this.tracksInGroup;if(e<0||e>=r.length)this.warn("Invalid audio track id: "+e);else{this.selectDefaultTrack=!1;var i=this.currentTrack,n=r[e],a=n.details&&!n.details.live;if(!(e===this.trackId&&n===i&&a||(this.log("Switching to audio-track "+e+' "'+n.name+'" lang:'+n.lang+" group:"+n.groupId+" channels:"+n.channels),this.trackId=e,this.currentTrack=n,this.hls.trigger(G.AUDIO_TRACK_SWITCHING,c(c({},n),{},{flushImmediate:t})),a))){var s=this.switchParams(n.url,null==i?void 0:i.details,n.details);this.loadPlaylist(s)}}},r.findTrackId=function(e){for(var t=this.tracksInGroup,r=0;r<t.length;r++){var i=t[r];if((!this.selectDefaultTrack||i.default)&&(!e||yr(e,i,Er)))return r}if(e){for(var n=e.name,a=e.lang,s=e.assocLang,o=e.characteristics,l=e.audioCodec,u=e.channels,d=0;d<t.length;d++)if(yr({name:n,lang:a,assocLang:s,characteristics:o,audioCodec:l,channels:u},t[d],Er))return d;for(var h=0;h<t.length;h++){var f=t[h];if(ps(e.attrs,f.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return h}for(var c=0;c<t.length;c++){var g=t[c];if(ps(e.attrs,g.attrs,["LANGUAGE"]))return c}}return-1},r.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this);var r=this.currentTrack;this.shouldLoadPlaylist(r)&&Sr(r.url,this.hls)&&this.scheduleLoading(r,t)},r.loadingPlaylist=function(t,r){e.prototype.loadingPlaylist.call(this,t,r);var i=t.id,n=t.groupId,a=this.getUrlWithDirectives(t.url,r),s=t.details,o=null==s?void 0:s.age;this.log("Loading audio-track "+i+' "'+t.name+'" lang:'+t.lang+" group:"+n+(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"")+(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):"")+" "+a),this.hls.trigger(G.AUDIO_TRACK_LOADING,{url:a,id:i,groupId:n,deliveryDirectives:r||null,track:t})},a(t,[{key:"allAudioTracks",get:function(){return this.tracks}},{key:"audioTracks",get:function(){return this.tracksInGroup}},{key:"audioTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}},{key:"nextAudioTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}}])}(vs),Es=function(){function e(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}var t=e.prototype;return t.destroy=function(){this.tracks=this.queues=null},t.append=function(e,t,r){if(null!==this.queues&&null!==this.tracks){var i=this.queues[t];i.push(e),1!==i.length||r||this.executeNext(t)}},t.appendBlocker=function(e){var t=this;return new Promise((function(r){var i={label:"async-blocker",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.append(i,e)}))},t.prependBlocker=function(e){var t=this;return new Promise((function(r){if(t.queues){var i={label:"async-blocker-prepend",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.queues[e].unshift(i)}}))},t.removeBlockers=function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((function(e){var t,r=null==(t=e[0])?void 0:t.label;"async-blocker"===r||"async-blocker-prepend"===r?(e[0].execute(),e.splice(0,1)):"block-audio"===r&&e.splice(0,1)}))},t.insertNext=function(e,t){var r;null!==this.queues&&(r=this.queues[t]).splice.apply(r,[1,0].concat(e))},t.unblockAudio=function(){var e;null!==this.queues&&"block-audio"===(null==(e=this.current("audio"))?void 0:e.label)&&this.shiftAndExecuteNext("audio")},t.audioBlocking=function(){return null!==this.queues&&this.queues.audio.some((function(e){return"block-audio"===e.label}))},t.executeNext=function(e){if(null!==this.queues&&null!==this.tracks){var t=this.queues[e];if(t.length){var r=t[0];try{r.execute()}catch(t){var i;if(r.onError(t),null===this.queues||null===this.tracks)return;var n=null==(i=this.tracks[e])?void 0:i.buffer;null!=n&&n.updating||this.shiftAndExecuteNext(e)}}}},t.shiftAndExecuteNext=function(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))},t.current=function(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null},t.toString=function(){var e=this.queues,t=this.tracks;return null===e||null===t?"<destroyed>":"\n"+this.list("video")+"\n"+this.list("audio")+"\n"+this.list("audiovideo")+"}"},t.list=function(e){var t,r;return null!=(t=this.queues)&&t[e]||null!=(r=this.tracks)&&r[e]?e+": ("+this.listSbInfo(e)+") "+this.listOps(e):""},t.listSbInfo=function(e){var t,r=null==(t=this.tracks)?void 0:t[e],i=null==r?void 0:r.buffer;return i?"SourceBuffer"+(i.updating?" updating":"")+(r.ended?" ended":"")+(r.ending?" ending":""):"none"},t.listOps=function(e){var t;return(null==(t=this.queues)?void 0:t[e].map((function(e){return e.label})).join(", "))||""},e}(),Ts=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Ss="HlsJsTrackRemovedError",As=function(e){function t(t){var r;return(r=e.call(this,t)||this).name=Ss,r}return d(t,e),t}(E(Error)),Is=function(e){function t(t,r){var i,n;return(i=e.call(this,"buffer-controller",t.logger)||this).hls=void 0,i.fragmentTracker=void 0,i.fragmentAppendProgress=Object.create(null),i.appendsWithoutProgress=Object.create(null),i.details=null,i._objectUrl=null,i.operationQueue=null,i.bufferCodecEventsTotal=0,i.media=null,i.mediaSource=null,i.lastMpegAudioChunk=null,i.lastVideoAppendEnd=0,i.appendSource=void 0,i.transferData=void 0,i.overrides=void 0,i.appendErrors={audio:0,video:0,audiovideo:0},i.appendError=void 0,i._quotaEvictionPending={},i.tracks={},i.sourceBuffers=[[null,null],[null,null]],i._onEndStreaming=function(e){var t;i.hls&&"open"===(null==(t=i.mediaSource)?void 0:t.readyState)&&i.media&&!i.media.seeking&&i.hls.pauseBuffering()},i._onStartStreaming=function(e){i.hls&&i.hls.resumeBuffering()},i._onMediaSourceOpen=function(e){var t=i,r=t.media,n=t.mediaSource;e&&i.log("Media source opened"),r&&n&&(Cn(n,"sourceopen",i._onMediaSourceOpen),Cn(r,"emptied",i._onMediaEmptied),i.updateDuration(),i.hls.trigger(G.MEDIA_ATTACHED,{media:r,mediaSource:n}),null!==i.mediaSource&&i.checkPendingTracks())},i._onMediaSourceClose=function(){if(i.log("Media source closed"),i.media){var e=i.media.error,t=i,r=t.appendError,n=t.appendErrors,a=!1;!r&&e&&(a=Math.max(++n.audio,++n.video,++n.audiovideo)>=i.hls.config.appendErrorMaxRetry);var s=new Error("MediaSource closed while media attached"+bs(a,e));i.warn(s),i.hls.trigger(G.ERROR,l({fatal:a},r,{type:B.MEDIA_ERROR,details:U.MEDIA_SOURCE_REQUIRES_RESET,error:s}))}},i._onMediaSourceEnded=function(){i.log("Media source ended")},i._onMediaEmptied=function(){var e=i,t=e.mediaSrc,r=e._objectUrl;t!==r&&i.error("Media element src was set while attaching MediaSource ("+r+" > "+t+")")},i._onMediaError=function(){var e,t,r=i.media;r&&i.log("Media error (code: "+(null==(e=r.error)?void 0:e.code)+"): "+(null==(t=r.error)?void 0:t.message))},i.hls=t,i.fragmentTracker=r,i.appendSource=(n=Re(t.config.preferManagedMediaSource),"undefined"!=typeof self&&n===self.ManagedMediaSource),i.initTracks(),i.registerListeners(),i}d(t,e);var r=t.prototype;return r.hasSourceTypes=function(){return Object.keys(this.tracks).length>0},r.destroy=function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=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,this._onMediaEmptied=this._onMediaError=null},r.registerListeners=function(){var e=this.hls;e.on(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_PARSED,this.onManifestParsed,this),e.on(G.BUFFER_RESET,this.onBufferReset,this),e.on(G.BUFFER_APPENDING,this.onBufferAppending,this),e.on(G.BUFFER_CODECS,this.onBufferCodecs,this),e.on(G.BUFFER_EOS,this.onBufferEos,this),e.on(G.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(G.FRAG_PARSED,this.onFragParsed,this),e.on(G.FRAG_CHANGED,this.onFragChanged,this),e.on(G.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_PARSED,this.onManifestParsed,this),e.off(G.BUFFER_RESET,this.onBufferReset,this),e.off(G.BUFFER_APPENDING,this.onBufferAppending,this),e.off(G.BUFFER_CODECS,this.onBufferCodecs,this),e.off(G.BUFFER_EOS,this.onBufferEos,this),e.off(G.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(G.FRAG_PARSED,this.onFragParsed,this),e.off(G.FRAG_CHANGED,this.onFragChanged,this),e.off(G.ERROR,this.onError,this)},r.transferMedia=function(){var e=this,t=this.media,r=this.mediaSource;if(!t)return null;var i={};if(this.operationQueue){var n=this.isUpdating();n||this.operationQueue.removeBlockers();var a=this.isQueued();(n||a)&&this.warn("Transfering MediaSource with"+(a?" operations in queue":"")+(n?" updating SourceBuffer(s)":"")+" "+this.operationQueue),this.operationQueue.destroy()}var s=this.transferData;return s&&!this.sourceBufferCount&&s.mediaSource===r?l(i,s.tracks):this.sourceBuffers.forEach((function(t){var r=t[0];r&&(i[r]=l({},e.tracks[r]),e.removeBuffer(r)),t[0]=t[1]=null})),{media:t,mediaSource:r,tracks:i}},r.initTracks=function(){this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0},r.onManifestLoading=function(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()},r.onManifestParsed=function(e,t){var r,i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(i+" bufferCodec event(s) expected."),null!=(r=this.transferData)&&r.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()},r.onMediaAttaching=function(e,t){var r=this.media=t.media;this.transferData=this.overrides=void 0;var i=Re(this.appendSource);if(i){var n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var a=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(a),n)this._objectUrl=r.src,this.attachTransferred();else{var s=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{r.removeAttribute("src");var o=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||o&&a instanceof o,Ls(r),function(e,t){var r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}(r,s),r.load()}catch(e){r.src=s}else r.src=s}_n(r,"emptied",this._onMediaEmptied),_n(r,"error",this._onMediaError),this.appendSource&&_n(r,"seeking",this._onStartStreaming)}},r.assignMediaSource=function(e){var t,r;this.log(((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created")+" media source: "+(null==(r=e.constructor)?void 0:r.name)),_n(e,"sourceopen",this._onMediaSourceOpen),_n(e,"sourceended",this._onMediaSourceEnded),_n(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(_n(e,"startstreaming",this._onStartStreaming),_n(e,"endstreaming",this._onEndStreaming))},r.attachTransferred=function(){var e=this,t=this.media,r=this.transferData;if(r&&t){var i=this.tracks,n=r.tracks,a=n?Object.keys(n):null,s=a?a.length:0,o=function(){Promise.resolve().then((function(){e.media&&e.mediaSourceOpenOrEnded&&e._onMediaSourceOpen()}))};if(n&&a&&s){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log("attachTransferred: (bufferCodecEventsTotal "+this.bufferCodecEventsTotal+")\nrequired tracks: "+cr(i,(function(e,t){return"initSegment"===e?void 0:t}))+";\ntransfer tracks: "+cr(n,(function(e,t){return"initSegment"===e?void 0:t}))+"}"),!be(n,i)){r.mediaSource=null,r.tracks=void 0;var l=t.currentTime,u=this.details,d=Math.max(l,(null==u?void 0:u.fragments[0].start)||0);return d-l>1?void this.log("attachTransferred: waiting for playback to reach new tracks start time "+l+" -> "+d):(this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'+Object.keys(n)+'"->"'+Object.keys(i)+'") start time: '+d+" currentTime: "+l),this.onMediaDetaching(G.MEDIA_DETACHING,{}),this.onMediaAttaching(G.MEDIA_ATTACHING,r),void(t.currentTime=d))}this.transferData=void 0,a.forEach((function(t){var r=t,i=n[r];if(i){var a=i.buffer;if(a){var s=e.fragmentTracker,o=i.id;if(s.hasFragments(o)||s.hasParts(o)){var l=gi.getBuffered(a);s.detectEvictedFragments(r,l,o,null,null,!0)}var u=Rs(r),d=[r,a];e.sourceBuffers[u]=d,a.updating&&e.operationQueue&&e.operationQueue.prependBlocker(r),e.trackSourceBuffer(r,i)}}})),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}},r.onMediaDetaching=function(e,t){var r=this,i=!!t.transferMedia;this.transferData=this.overrides=void 0;var n=this.media,a=this.mediaSource,s=this._objectUrl;if(a){if(this.log("media source "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach((function(e){var t=e[0];t&&r.removeBuffer(t)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){var o="open"===a.readyState;try{for(var l=a.sourceBuffers,u=l.length;u--;)o&&l[u].abort(),a.removeSourceBuffer(l[u]);o&&a.endOfStream()}catch(e){this.warn("onMediaDetaching: "+e.message+" while calling endOfStream")}}this.sourceBufferCount&&this.onBufferReset()}Cn(a,"sourceopen",this._onMediaSourceOpen),Cn(a,"sourceended",this._onMediaSourceEnded),Cn(a,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Cn(a,"startstreaming",this._onStartStreaming),Cn(a,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(Cn(n,"emptied",this._onMediaEmptied),Cn(n,"error",this._onMediaError),Cn(n,"seeking",this._onStartStreaming),i||(s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(n.removeAttribute("src"),this.appendSource&&Ls(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)},r.onBufferReset=function(){var e=this;this.sourceBuffers.forEach((function(t){var r=t[0];r&&e.resetBuffer(r)})),this.initTracks()},r.resetBuffer=function(e){var t,r=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),r)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(t){this.warn("onBufferReset "+e,t)}delete this.tracks[e]},r.removeBuffer=function(e){this.removeBufferListeners(e),this.sourceBuffers[Rs(e)]=[null,null];var t=this.tracks[e];t&&(this.clearBufferAppendTimeoutId(t),t.buffer=void 0)},r.resetQueue=function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Es(this.tracks)},r.onBufferCodecs=function(e,t){var r,i=this,n=this.tracks,a=Object.keys(t);this.log('BUFFER_CODECS: "'+a+'" (current SB count '+this.sourceBufferCount+")");var s="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),o=!s&&this.sourceBufferCount&&this.media&&a.some((function(e){return!n[e]}));s||o?this.warn('Unsupported transition between "'+Object.keys(n)+'" and "'+a+'" SourceBuffers'):(a.forEach((function(e){var r,a,s=t[e],o=s.id,l=s.codec,u=s.levelCodec,d=s.container,h=s.metadata,f=s.supplemental,c=n[e],g=null==(r=i.transferData)||null==(r=r.tracks)?void 0:r[e],v=null!=g&&g.buffer?g:c,m=(null==v?void 0:v.pendingCodec)||(null==v?void 0:v.codec),p=null==v?void 0:v.levelCodec;c||(c=n[e]={buffer:void 0,listeners:[],codec:l,supplemental:f,container:d,levelCodec:u,metadata:h,id:o});var y=jt(m,p),E=null==y?void 0:y.replace(Ts,"$1"),T=jt(l,u),S=null==(a=T)?void 0:a.replace(Ts,"$1");T&&y&&E!==S&&("audio"===e.slice(0,5)&&(T=Yt(T,i.appendSource)),i.log("switching codec "+m+" to "+T),T!==(c.pendingCodec||c.codec)&&(c.pendingCodec=T),c.container=d,i.appendChangeType(e,d,T))})),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(r=t.audio)?void 0:r.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))},r.appendChangeType=function(e,t,r){var i=this,n=t+";codecs="+r,a={label:"change-type="+n,execute:function(){var a=i.tracks[e];if(a){var s=a.buffer;null!=s&&s.changeType&&(i.log("changing "+e+" sourceBuffer type to "+n),s.changeType(n),a.codec=r,a.container=t)}i.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){i.warn("Failed to change "+e+" SourceBuffer type",t)}};this.append(a,e,this.isPending(this.tracks[e]))},r.blockAudio=function(e){var t,r=this,i=e.start,n=i+.05*e.duration;if(!0!==(null==(t=this.fragmentTracker.getAppendedFrag(i,$.MAIN))?void 0:t.gap)){var a={label:"block-audio",execute:function(){var e,t;(r.lastVideoAppendEnd>n||gi.isBuffered(null==(e=r.tracks.video)?void 0:e.buffer,n)||!0===(null==(t=r.fragmentTracker.getAppendedFrag(n,$.MAIN))?void 0:t.gap))&&r.unblockAudio()},onStart:function(){},onComplete:function(){},onError:function(e){r.warn("Error executing block-audio operation",e)}};this.append(a,"audio",!0)}},r.unblockAudio=function(){this.operationQueue&&this.operationQueue.unblockAudio()},r.onBufferAppending=function(e,t){var r=this,i=this.tracks,n=t.data,a=t.type,s=t.parent,o=t.frag,l=t.part,u=t.chunkMeta,d=t.offset,h=u.buffering[a],f=ee(o)&&!l&&!o.gap&&!u.partial&&!u.iframe,c=null,g=!1,v=o.sn,m=o.cc,p=self.performance.now();h.start=p;var y=o.stats.buffering,E=l?l.stats.buffering:null;0===y.start&&(y.start=p),0===(null==E?void 0:E.start)&&(E.start=p);var T=i.audio,S=!1;"audio"===a&&"audio/mpeg"===(null==T?void 0:T.container)&&(S=!this.lastMpegAudioChunk||1===u.id||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);var A=i.video,I=null==A?void 0:A.buffer;if(I&&"initSegment"!==v&&void 0!==d){var L=null==T?void 0:T.buffer,R=l||o;if("audio"===a&&"main"!==s&&!A.ending&&!A.ended&&L&&gi.getBuffered(L).length){var b=R.start+.05*R.duration,k=gi.getBuffered(I),D=this.currentOp("video");k.length||D?!gi.isBuffered(I,b)&&this.lastVideoAppendEnd<b&&this.blockAudio(R):this.blockAudio(R)}else if("video"===a){var P=R.end,_=this.lastVideoAppendEnd-P;this.lastVideoAppendEnd=P,_<0||_>R.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}var C=(l||o).start,w={label:"append-"+a,execute:function(){var e;h.executeStart=self.performance.now();var t=null==(e=r.tracks[a])?void 0:e.buffer;t&&(f&&(c=gi.timeRangesToArray(gi.getBuffered(t)),g=Ps(Ds(c,o),o)),S?r.updateTimestampOffset(t,C,.1,a,v,m):void 0!==d&&x(d)&&r.updateTimestampOffset(t,d,1e-6,a,v,m)),r.appendExecutor(n,a)},onStart:function(){},onComplete:function(){r.clearBufferAppendTimeoutId(r.tracks[a]);var e=self.performance.now();h.executeEnd=h.end=e,0===y.first&&(y.first=e),0===(null==E?void 0:E.first)&&(E.first=e);var t={};if(r.sourceBuffers.forEach((function(e){var r=e[0],i=e[1];r&&(t[r]=gi.getBuffered(i))})),f){var i=r.getFragmentAppendProgress(o),n=t[a];if(n&&c){var d=Ds(gi.timeRangesToArray(n),o);i.progressed||(i.progressed=d-Ds(c,o)>.001);var v=g&&Ps(d,o);i.fullyBuffered[a]=(void 0===i.fullyBuffered[a]||i.fullyBuffered[a])&&v}}r.hls.trigger(G.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:u,parent:s,timeRanges:t})},onError:function(e){var t;r.clearBufferAppendTimeoutId(r.tracks[a]);var i=e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e;if(i&&!r._quotaEvictionPending[a]){var d=r.getBackBufferEvictionTarget(a,n.byteLength,o.type);if(d>0){r._quotaEvictionPending[a]=!0,r.log('QuotaExceededError on "'+a+'" append sn: '+v+" - evicting back buffer to "+d.toFixed(3)+"s and retrying");var h=r.getFlushOp(a,0,d),c=r.getClearEvictionPendingOp(a);return void r.insertNext([h,w,c],a)}r.warn('QuotaExceededError on "'+a+'" sn: '+v+" - no back buffer available to evict")}f&&(r.getFragmentAppendProgress(o).errored=!0);var g={type:B.MEDIA_ERROR,parent:s,details:U.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:u,error:e,err:e,fatal:!1},m=null==(t=r.media)?void 0:t.error;if(e.name!==Ss||0!==r.sourceBufferCount||r.media&&0!==r.pendingTrackCount){var p;i&&(g.details=U.BUFFER_FULL_ERROR);var y=++r.appendErrors[a],E=r.hls.config.appendErrorMaxRetry;r.warn("Failed "+y+"/"+(E+1)+' times to append segment in "'+a+'" sourceBuffer with error: '+e.message),y>=E&&(g.fatal=!i);var T=null==(p=r.mediaSource)?void 0:p.readyState;("ended"===T||"closed"===T||m)&&(r.warn('MediaSource readyState "'+T+'" during SourceBuffer'+bs(g.fatal,m)),g.details=U.MEDIA_SOURCE_REQUIRES_RESET)}else g.errorAction=Yr(!0);r.appendError=g,r.hls.trigger(G.ERROR,g),i&&r.hls&&r.trimBuffers(o.start,1)}};this.log('queuing "'+a+'" append sn: '+v+(l?" p: "+l.index:"")+" of "+s+" playlist "+o.level+" cc: "+m+" offset: "+d+" bytes: "+n.byteLength),this.append(w,a,this.isPending(this.tracks[a]))},r.getClearEvictionPendingOp=function(e){var t=this;return{label:"clear",execute:function(){t._quotaEvictionPending[e]=!1,t.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(){}}},r.getFlushOp=function(e,t,r){var i=this;return this.log('queuing "'+e+'" remove '+t+"-"+r),{label:"remove",execute:function(){i.removeExecutor(e,t,r)},onStart:function(){},onComplete:function(){var n,a=null==(n=i.tracks[e])?void 0:n.buffer;i.log("Remove request "+t+"-"+r+" from "+e+" Source Buffer complete > buffer: "+(a?wn(gi.getBuffered(a)):"(detached)")),i.hls.trigger(G.BUFFER_FLUSHED,{type:e,start:t,end:r})},onError:function(n){i.warn("Failed to remove "+t+"-"+r+' from "'+e+'" SourceBuffer',n),i.hls.trigger(G.BUFFER_FLUSHED,{type:e,start:0,end:0,error:n})}}},r.onBufferFlushing=function(e,t){var r=this,i=t.type,n=t.startOffset,a=t.endOffset;i&&"audio"!==i||this.unblockAudio(),i?this.append(this.getFlushOp(i,n,a),i):this.sourceBuffers.forEach((function(e){var t=e[0];t&&r.append(r.getFlushOp(t,n,a),t)}))},r.onFragParsed=function(e,t){var r=this,i=t.frag,n=t.part,a=t.chunkMeta,s=[],o=n?n.elementaryStreams:i.elementaryStreams;o[Z.AUDIOVIDEO]?s.push("audiovideo"):(o[Z.AUDIO]&&s.push("audio"),o[Z.VIDEO]&&s.push("video")),0===s.length&&this.log("Fragments must have at least one ElementaryStreamType set. "+i.type+" "+i.level+" "+(n?"part: "+n.index+" of ":"")+"sn: "+i.sn),this.blockBuffers((function(){var e=self.performance.now();i.stats.buffering.end=e,n&&(n.stats.buffering.end=e);var t=n?n.stats:i.stats;r.checkAppendProgress(i,n,a,s),r.hls&&(r.hls.trigger(G.FRAG_BUFFERED,{frag:i,part:n,stats:t,id:i.type,chunkMeta:a}),!n&&i.gap&&t.retry&&r.log("Nothing buffered for "+i.type+" level: "+i.level+" sn: "+i.sn+" retries "+t.retry))}),s).catch((function(e){r.warn("Fragment buffered callback "+e.message),r.stepOperationQueue(r.sourceBufferTypes)}))},r.onFragChanged=function(e,t){var r,i,n=this,a=null==(r=this.hls)?void 0:r.config;if(a){var s=a.backBufferLength,o=a.frontBufferFlushThreshold;this.trimBuffers(o,s,t.frag,t.previousFrag);var l=t.frag.elementaryStreams,u=this.appendErrors,d=null==(i=this.appendError)?void 0:i.sourceBufferName;Object.keys(l).forEach((function(e){l[e]&&(u[e]=0,e===d&&(n.appendError=void 0),"audio"===e||"video"===e?(u.audiovideo=0,"audiovideo"===d&&(n.appendError=void 0)):(u.audio=0,u.video=0,"audiovideo"!==d&&(n.appendError=void 0)))}))}},r.onBufferEos=function(e,t){var r,i=this;this.sourceBuffers.forEach((function(e){var r=e[0];if(r){var n=i.tracks[r];t.type&&t.type!==r||(n.ending=!0,n.ended||(n.ended=!0,i.log(r+" buffer reached EOS")))}}));var n=!1!==(null==(r=this.overrides)?void 0:r.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((function(e){var t,r=e[0];return r&&!(null!=(t=i.tracks[r])&&t.ended)}))?(this.unblockAudio(),n?(this.log("Queueing EOS"),this.blockUntilOpen((function(){i.tracksEnded();var e=i.mediaSource;"open"===(null==e?void 0:e.readyState)?(i.log("Calling mediaSource.endOfStream()"),e.endOfStream(),i.hls.trigger(G.BUFFERED_TO_END,void 0)):e&&i.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: "+e.readyState)}))):(this.tracksEnded(),this.hls.trigger(G.BUFFERED_TO_END,void 0))):"video"===t.type&&this.unblockAudio()},r.tracksEnded=function(){var e=this;this.sourceBuffers.forEach((function(t){var r=t[0];if(null!==r){var i=e.tracks[r];i&&(i.ending=!1)}}))},r.onLevelUpdated=function(e,t){var r=t.details;r.fragments.length&&(this.details=r,this.updateDuration())},r.updateDuration=function(){var e=this;this.blockUntilOpen((function(){var t=e.getDurationAndRange();t&&e.updateMediaSource(t)}))},r.onError=function(e,t){if(t.details===U.BUFFER_APPEND_ERROR&&t.frag){var r,i=null==(r=t.errorAction)?void 0:r.nextAutoLevel;x(i)&&i!==t.frag.level&&this.resetAppendErrors()}},r.getBackBufferEvictionTarget=function(e,t,r){var i=this.media;return i?this.fragmentTracker.getBackBufferEvictionEnd(i.currentTime,r,t):0},r.getFragmentAppendProgress=function(e){var t,r=ks(e),i=this.fragmentAppendProgress[r];return(null==(t=i)?void 0:t.stats)!==e.stats&&(i={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[r]=i),i},r.checkAppendProgress=function(e,t,r,i){if(!(t||!ee(e)||e.gap||r.iframe||r.partial)){var n=ks(e),a=this.fragmentAppendProgress[n];delete this.fragmentAppendProgress[n];var s=e.stats.buffering;if(!s.start||s.first){var o=(null==a?void 0:a.stats)===e.stats?a:void 0;if(null==o||!o.errored){var l=i.length>0&&i.every((function(e){return!0===(null==o?void 0:o.fullyBuffered[e])}));if(null!=o&&o.progressed||l)delete this.appendsWithoutProgress[n];else if(o||0!==i.length){var u=(this.appendsWithoutProgress[n]||0)+1,d=this.hls;u>=d.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[n]:this.appendsWithoutProgress[n]=u,this.warn("Fragment "+e.sn+" of "+e.type+" playlist "+e.level+" appended "+u+" time"+(u>1?"s":"")+" without buffered range growth"),d.trigger(G.ERROR,{type:B.MEDIA_ERROR,details:U.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:r,parent:e.type,appendsWithoutProgress:u,error:new Error("Fragment append did not increase buffered coverage ("+u+")")})}}}}},r.resetAppendProgress=function(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)},r.resetAppendErrors=function(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0},r.trimBuffers=function(e,t,r,i){var n=this.hls,a=this.details,s=this.media;if(s&&null!==a&&this.sourceBufferCount){var o=n.config,l=s.currentTime,u=a.levelTargetDuration;t=a.live&&null!==o.liveBackBufferLength?o.liveBackBufferLength:t;var d=-1/0;if(x(t)&&t>=0){var h=Math.max(t,u);d=Math.floor(l/u)*u-h}if(r){var f=this.getLoopBackBufferFlushEnd(r,null!=i?i:null);f>0&&(d=Math.max(d,f))}if(d>0&&this.flushBackBuffer(l,u,d),x(e)&&e>0){var c=Math.max(o.maxBufferLength,e),g=Math.max(c,u),v=Math.floor(l/u)*u+g;this.flushFrontBuffer(l,u,v)}}},r.getLoopBackBufferFlushEnd=function(e,t){var r,i=this.media;if(!1===(null==(r=this.hls)?void 0:r.config.loopBackBufferFlush)||null==i||!i.loop||!t||e.level<=t.level)return 0;var n=e.elementaryStreams,a=n.video,s=n.audiovideo;if(null!=a&&a.partial||null!=s&&s.partial)return 0;var o=this.getEarliestElementaryStreamStart(e)-.25;return o<=0?0:(this.log("Flushing lower quality back buffer for loop: level "+e.level+", range [0-"+o.toFixed(3)+"]"),o)},r.getEarliestElementaryStreamStart=function(e){var t=e.elementaryStreams,r=t.audio,i=t.video,n=t.audiovideo,a=e.start;return n?a=Math.min(a,n.startDTS):(r&&(a=Math.min(a,r.startDTS)),i&&(a=Math.min(a,i.startDTS))),a},r.flushBackBuffer=function(e,t,r){var i=this;this.sourceBuffers.forEach((function(e){var t=e[0],n=e[1];if(n){var a=gi.getBuffered(n);if(a.length>0&&r>a.start(0)){var s,o,l;i.hls.trigger(G.BACK_BUFFER_REACHED,{bufferEnd:r});var u=i.tracks[t];if(null!=(s=i.details)&&s.live)i.hls.trigger(G.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=u&&u.ended&&(null==(o=i.media)||!o.loop||!1===(null==(l=i.hls)?void 0:l.config.loopBackBufferFlush)))return void i.log("Cannot flush "+t+" back buffer while SourceBuffer is in ended state");i.hls.trigger(G.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:t})}}}))},r.flushFrontBuffer=function(e,t,r){var i=this;this.sourceBuffers.forEach((function(t){var n=t[0],a=t[1];if(a){var s=gi.getBuffered(a),o=s.length;if(o<2)return;var l=s.start(o-1),u=s.end(o-1);if(r>l||e>=l&&e<=u)return;i.hls.trigger(G.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:n})}}))},r.getDurationAndRange=function(){var e,t=this.details,r=this.mediaSource;if(!t||!this.media||"open"!==(null==r?void 0:r.readyState))return null;var i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&r.setLiveSeekableRange){var n=Math.max(0,t.fragmentStart);return{duration:1/0,start:n,end:Math.max(n,i)}}return{duration:1/0}}var a=null==(e=this.overrides)?void 0:e.duration;if(a)return x(a)?{duration:a}:null;var s=this.media.duration;return i>(x(r.duration)?r.duration:0)&&i>s||!x(s)?{duration:i}:null},r.updateMediaSource=function(e){var t=e.duration,r=e.start,i=e.end,n=this.mediaSource;n&&this.media&&"open"===n.readyState&&(n.duration!==t&&(x(t)&&this.log("Updating MediaSource duration to "+t.toFixed(3)),n.duration=t),void 0!==r&&void 0!==i&&(this.log("MediaSource duration is set to "+n.duration+". Setting seekable range to "+r+"-"+i+"."),n.setLiveSeekableRange(r,i)))},r.checkPendingTracks=function(){var e=this.bufferCodecEventsTotal,t=this.pendingTrackCount,r=this.tracks;if(this.log("checkPendingTracks (pending: "+t+" codec events expected: "+e+") "+cr(r)),this.tracksReady){var i,n=null==(i=this.transferData)?void 0:i.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}},r.bufferCreated=function(){var e=this;if(this.sourceBufferCount){var t={};this.sourceBuffers.forEach((function(r){var i=r[0],n=r[1];if(i){var a=e.tracks[i];t[i]={buffer:n,container:a.container,codec:a.codec,supplemental:a.supplemental,levelCodec:a.levelCodec,id:a.id,metadata:a.metadata}}})),this.hls.trigger(G.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: "+this.operationQueue),this.sourceBuffers.forEach((function(t){var r=t[0];e.executeNext(r)}))}else{var r=new Error("could not create source buffer for media codec(s)");this.hls.trigger(G.ERROR,{type:B.MEDIA_ERROR,details:U.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:r,reason:r.message})}},r.createSourceBuffers=function(){var e=this.tracks,t=this.sourceBuffers,r=this.mediaSource;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(var i in e){var n=i,a=e[n];if(this.isPending(a)){var s=this.getTrackCodec(a,n),o=a.container+";codecs="+s;a.codec=s,this.log("creating sourceBuffer("+o+")"+(this.currentOp(n)?" Queued":"")+" "+cr(a));try{var l=r.addSourceBuffer(o),u=Rs(n),d=[n,l];t[u]=d,a.buffer=l}catch(e){var h;return this.error("error while trying to add sourceBuffer: "+e.message),this.shiftAndExecuteNext(n),null==(h=this.operationQueue)||h.removeBlockers(),delete this.tracks[n],void this.hls.trigger(G.ERROR,{type:B.MEDIA_ERROR,details:U.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:o,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()},r.clearBufferAppendTimeoutId=function(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)},r.getTrackCodec=function(e,t){var r=e.supplemental,i=e.codec;r&&("video"===t||"audiovideo"===t)&&Nt(r,"video")&&(i=function(e,t){var r=[];if(e)for(var i=e.split(","),n=0;n<i.length;n++)Ft(i[n],"video")||r.push(i[n]);return t&&r.push(t),r.join(",")}(i,r));var n=jt(i,e.levelCodec);return n?"audio"===t.slice(0,5)?Yt(n,this.appendSource):n:""},r.trackSourceBuffer=function(e,t){var r=this,i=t.buffer;if(i){var n=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:n,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",(function(e,t){var i=t.removedRanges;null!=i&&i.length&&(r.log(e+" buffer removed "+wn(i)),r.hls.trigger(G.BUFFER_FLUSHED,{type:e,start:i.start(0),end:i.end(i.length-1)}))}))}},r.onSBUpdateStart=function(e){var t=this.currentOp(e);t&&t.onStart()},r.onSBUpdateEnd=function(e){var t,r,i=this;if("closed"!==(null==(t=this.mediaSource)?void 0:t.readyState)){var n=this.currentOp(e);if(n){if(n.onComplete(),null==(r=this.tracks[e])||null==(r=r.buffer)?void 0:r.updating)return this.log(e+' SourceBuffer updating on "updateend"'),void this.blockUntilOpen((function(){i.shiftAndExecuteNext(e)}));this.shiftAndExecuteNext(e)}}else this.resetBuffer(e)},r.onSBUpdateError=function(e,t){var r,i=null==(r=this.mediaSource)?void 0:r.readyState,n=new Error(e+" SourceBuffer error. MediaSource readyState: "+i);this.error(""+n.message,t),this.hls.trigger(G.ERROR,{type:B.MEDIA_ERROR,details:U.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});var a=this.currentOp(e);a&&a.onError(n)},r.updateTimestampOffset=function(e,t,r,i,n,a){var s=t-e.timestampOffset;Math.abs(s)>=r&&(this.log("Updating "+i+" SourceBuffer timestampOffset to "+t+" (sn: "+n+" cc: "+a+")"),e.timestampOffset=t)},r.removeExecutor=function(e,t,r){var i=this.media,n=this.mediaSource,a=this.tracks[e],s=null==a?void 0:a.buffer;if(!i||!n||!s)throw new Error("Attempting to remove from the "+e+" SourceBuffer, but it does not exist");var o,l=x(i.duration)?i.duration:1/0,u=x(n.duration)?n.duration:1/0,d=Math.max(0,t);if(d>=u)return null==(o=this.currentOp(e))||o.onComplete(),void this.shiftAndExecuteNext(e);var h=Math.min(r,l,u);if(!(h>d)||a.ending&&!a.ended)throw new Error("Cannot remove "+(h<=d?"invalid range ("+d+" >= "+h+") ":"")+"from the "+e+" SourceBuffer"+(a.ending?" while track ending":""));a.ended=!1,this.log("Removing ["+d+","+h+"] from the "+e+" SourceBuffer"),s.remove(d,h)},r.appendExecutor=function(e,t){var r=this,i=this.tracks[t],n=null==i?void 0:i.buffer;if(!n)throw new As("Attempting to append to the "+t+" SourceBuffer, but it does not exist");if(i.ending=!1,i.ended=!1,this.hls.config.appendTimeout!==1/0){var a=this.calculateAppendTimeoutTime(n);i.bufferAppendTimeoutId=self.setTimeout((function(){return r.appendTimeoutHandler(t,n,a)}),a)}n.appendBuffer(e)},r.appendTimeoutHandler=function(e,t,r){this.log("Received timeout after "+r+"ms for append on "+e+" source buffer. Aborting and triggering error.");try{t.abort()}catch(t){this.log("Failed to abort append on "+e+" source buffer after timeout.")}var i=this.currentOp(e);i&&i.onError(new Error(e+"-append-timeout"))},r.calculateAppendTimeoutTime=function(e){var t=10;this.details&&(t=this.details.levelTargetDuration);var r=2*t*1e3;if(null===this.media)return r;var i=gi.bufferInfo(e,this.media.currentTime,0);return i.len?(r=Math.max(1e3*i.len,r),Math.max(this.hls.config.appendTimeout,r)):r},r.blockUntilOpen=function(e){var t=this;if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch((function(e){t.warn("SourceBuffer blocked callback "+e),t.stepOperationQueue(t.sourceBufferTypes)}));else try{e()}catch(e){this.warn("Callback run without blocking "+this.operationQueue+" "+e)}},r.isUpdating=function(){return this.sourceBuffers.some((function(e){var t=e[0],r=e[1];return t&&r.updating}))},r.isQueued=function(){var e=this;return this.sourceBuffers.some((function(t){var r=t[0];return r&&!!e.currentOp(r)}))},r.isPending=function(e){return!!e&&!e.buffer},r.isAudioBlocked=function(){var e;return"block-audio"===(null==(e=this.currentOp("audio"))?void 0:e.label)},r.isAudioBlocking=function(){return!!this.operationQueue&&this.operationQueue.audioBlocking()},r.blockBuffers=function(e,t){var r=this;if(void 0===t&&(t=this.sourceBufferTypes),!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);var i=this.operationQueue,n=2===t.length&&this.isAudioBlocking()?[this.appendBlocker("video")]:t.map((function(e){return r.appendBlocker(e)}));return Promise.all(n).then((function(t){i===r.operationQueue&&(e(),r.stepOperationQueue(r.sourceBufferTypes))}))},r.stepOperationQueue=function(e){var t=this;e.forEach((function(e){var r,i=null==(r=t.tracks[e])?void 0:r.buffer;!i||i.updating||"audio"===e&&t.isAudioBlocked()||t.shiftAndExecuteNext(e)}))},r.append=function(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)},r.insertNext=function(e,t){this.operationQueue&&this.operationQueue.insertNext(e,t)},r.appendBlocker=function(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)},r.currentOp=function(e){return this.operationQueue?this.operationQueue.current(e):null},r.executeNext=function(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)},r.shiftAndExecuteNext=function(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)},r.addBufferListener=function(e,t,r){var i=this.tracks[e];if(i){var n=i.buffer;if(n){var a=r.bind(this,e);i.listeners.push({event:t,listener:a}),_n(n,t,a)}}},r.removeBufferListeners=function(e){var t=this.tracks[e];if(t){var r=t.buffer;r&&(t.listeners.forEach((function(e){Cn(r,e.event,e.listener)})),t.listeners.length=0)}},a(t,[{key:"mediaSourceOpenOrEnded",get:function(){var e,t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}},{key:"sourceBufferTracks",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,r){var i=e.tracks[r];return t[r]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t}),{})}},{key:"bufferedToEnd",get:function(){var e=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some((function(t){var r=t[0];if(r){var i=e.tracks[r];if(i)return!i.ended||i.ending}return!1}))}},{key:"tracksReady",get:function(){var e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}},{key:"mediaSrc",get:function(){var e,t,r=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==r?void 0:r.src}},{key:"pendingTrackCount",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,r){return t+(e.isPending(e.tracks[r])?1:0)}),0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce((function(e,t){return e+(t[0]?1:0)}),0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map((function(e){return e[0]})).filter((function(e){return!!e}))}}])}(pe);function Ls(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach((function(t){e.removeChild(t)}))}function Rs(e){return"audio"===e?1:0}function bs(e,t){return(e?"":" - triggering recovery")+(t?" with HTMLMediaElement Error: "+t.message:"")}function ks(e){return e.type+"_"+e.sn+"_"+e.level}function Ds(e,t){for(var r=t.start,i=t.end,n=0,a=0;a<e.length;a++){var s=e[a];if(s.start>=i)break;var o=Math.max(r,s.start),l=Math.min(i,s.end);l>o&&(n+=l-o)}return n}function Ps(e,t){return t.duration-e<=.05}var _s=function(){function e(e){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}var t=e.prototype;return t.setStreamController=function(e){this.streamController=e},t.destroy=function(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0},t.registerListeners=function(){var e=this.hls;e&&(e.on(G.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(G.MANIFEST_PARSED,this.onManifestParsed,this),e.on(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(G.BUFFER_CODECS,this.onBufferCodecs,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this))},t.unregisterListener=function(){var e=this.hls;e&&(e.off(G.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(G.MANIFEST_PARSED,this.onManifestParsed,this),e.off(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(G.BUFFER_CODECS,this.onBufferCodecs,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this))},t.onFpsDropLevelCapping=function(e,t){if(this.hls){var r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}},t.onMediaAttaching=function(e,t){var r=t.media;this.clientRect=null,this.hls&&(r instanceof HTMLVideoElement?(this.media=r,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())},t.onManifestParsed=function(e,t){this.restrictedLevels=[],t.video&&this.startCapping(),this.onLevelsUpdated()},t.onLevelsUpdated=function(){if(this.hls)if((this.timer||this.observer)&&(x(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(void 0===this.observer&&void 0===this.timer){var e=this.hls.levels;e.length>1&&e.some((function(e){return!!e.videoCodec}))&&this.startCapping()}},t.onBufferCodecs=function(e,t){t.video&&this.startCapping()},t.onMediaDetaching=function(){this.stopCapping(),this.media=null},t.detectPlayerSize=function(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls)return void(this.clientRect=null);var e=this.hls.levels;if(e.length>1){var t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to "+r+": "+e[r].height+"p@"+e[r].bitrate+" for media "+this.mediaWidth+"x"+this.mediaHeight),t.autoLevelCapping=r,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else 1===e.length&&this.stopCapping()}},t.getMaxLevel=function(t){var r=this;if(!this.hls)return-1;var i=this.hls.levels;if(!i.length)return-1;var n=i.filter((function(e,i){return r.isLevelAllowed(e)&&i<=t}));return this.observer||(this.clientRect=null),e.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)},t.observe=function(){var e=this,t=self.ResizeObserver;t&&(this.observer=new t((function(t){var r,i=null==(r=t[0])?void 0:r.contentRect;i&&(e.clientRect=i,e.detectPlayerSize())}))),this.observer&&this.media&&this.observer.observe(this.media)},t.startCapping=function(){var e;this.timer||this.observer||null==(e=this.hls)||!e.config.capLevelToPlayerSize||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())},t.stopCapping=function(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)},t.getDimensions=function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t},t.isLevelAllowed=function(e){return!this.restrictedLevels.some((function(t){return e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height}))},e.getMaxLevelByMediaSize=function(e,t,r){if(null==e||!e.length)return-1;for(var i,n,a=e.length-1,s=Math.max(t,r),o=0;o<e.length;o+=1){var l=e[o];if((l.width>=s||l.height>=s)&&(i=l,!(n=e[o+1])||i.width!==n.width||i.height!==n.height)){a=o;break}}return a},a(e,[{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var e=1;if(!this.hls)return e;var t=this.hls.config,r=t.ignoreDevicePixelRatio,i=t.maxDevicePixelRatio;if(!r)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,i)}}])}(),Cs=function e(t,r){Array.isArray(t)&&(t=t.map((function(t){return t instanceof e?t:new e(t)}))),this.value=t,this.params=r},ws="Dict";function Os(e,t,r,i){return new Error("failed to "+e+' "'+(n=t,(Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"==typeof n?JSON.stringify(n):String(n))+'" as ')+r,{cause:i});var n}var Ms="Bare Item",xs="Boolean",Fs="Byte Sequence",Ns="Decimal",Bs="Integer",Us="String",Gs=/[\x00-\x1f\x7f]+/,Ks=function(e){this.description=e},Vs="Token",Hs="Key";function Ys(e,t,r){return Os("serialize",e,t,r)}function js(e){if(!1===ArrayBuffer.isView(e))throw Ys(e,Fs);return":"+(t=e,btoa(String.fromCharCode.apply(String,t))+":");var t}function Ws(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw Ys(e,Bs);return e.toString()}function qs(e){var t=R(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Ys(e,Ns);var r=t.toString();return r.includes(".")?r:r+".0"}function Xs(e){var t,r=(t=e).description||t.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(r))throw Ys(r,Vs);return r}function zs(e){switch(typeof e){case"number":if(!x(e))throw Ys(e,Ms);return Number.isInteger(e)?Ws(e):qs(e);case"string":return function(e){if(Gs.test(e))throw Ys(e,Us);return'"'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}(e);case"symbol":return Xs(e);case"boolean":return function(e){if("boolean"!=typeof e)throw Ys(e,xs);return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return"@"+Ws(e.getTime()/1e3)}(e);if(e instanceof Uint8Array)return js(e);if(e instanceof Ks)return Xs(e);default:throw Ys(e,Ms)}}function Qs(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw Ys(e,Hs);return e}function $s(e){return null==e?"":Object.entries(e).map((function(e){var t=e[0],r=e[1];return!0===r?";"+Qs(t):";"+Qs(t)+"="+zs(r)})).join("")}function Zs(e){return e instanceof Cs?""+zs(e.value)+$s(e.params):zs(e)}function Js(e,t){var r;if(void 0===t&&(t={whitespace:!0}),"object"!=typeof e||null==e)throw Ys(e,ws);var i=e instanceof Map?e.entries():Object.entries(e),n=null!=(r=t)&&r.whitespace?" ":"";return Array.from(i).map((function(e){var t=e[0],r=e[1];r instanceof Cs==0&&(r=new Cs(r));var i,n=Qs(t);return!0===r.value?n+=$s(r.params):(n+="=",Array.isArray(r.value)?n+="("+(i=r).value.map(Zs).join(" ")+")"+$s(i.params):n+=Zs(r)),n})).join(","+n)}function eo(e,t){return Js(e,t)}var to,ro=["url"],io=["version","eventTargets","sid","transmissionMode"],no=["customData","headers"],ao=function(e){return e instanceof Cs?new Cs(Math.round(e.value),e.params):Math.round(e)},so=function(e){return Array.isArray(e)?e.map(ao):ao(e)},oo=function(e,t){return Array.isArray(e)?e.map((function(e){return oo(e,t)})):e instanceof Cs&&"string"==typeof e.value?new Cs(oo(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){var r;try{r=new URL(e)}catch(t){return e}var i=new URL(t);if(r.origin!==i.origin)return e;for(var n=r.pathname.split("/").slice(1),a=i.pathname.split("/").slice(1,-1),s=Math.min(n.length,a.length),o=0;o<s&&n[o]===a[o];o++)n.shift(),a.shift();for(;a.length;)a.shift(),n.unshift("..");return n.join("/")+r.search+r.hash}(e,(r=t.baseUrl,(i="string"==typeof r?new URL(r):r).origin+i.pathname.substring(0,i.pathname.lastIndexOf("/")+1)))),1===t.version?encodeURIComponent(e):e);var r,i},lo=function(e){return e instanceof Cs?new Cs(100*Math.round(e.value/100),e.params):100*Math.round(e/100)},uo=function(e){return Array.isArray(e)?e.map(lo):lo(e)},ho={br:so,d:so,bl:uo,dl:uo,mtp:uo,nor:function(e,t){var r=e;return t.version>=2&&(e instanceof Cs&&"string"==typeof e.value?r=new Cs([e]):"string"==typeof e&&(r=[e])),oo(r,t)},rtp:uo,tb:so},fo=2,co="pr",go="b",vo="rr",mo="ce",po="bc",yo="e",Eo=vo,To=mo,So=new Map([["ps","sta"],[co,"pr"],["c","cid"],[go,"bg"],["bc","br"]]),Ao="event",Io="request",Lo=["cen","e","h","ts"],Ro=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],bo=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function ko(e){return bo.test(e)}var Do=new Set(Ro);function Po(e){return Do.has(e)||ko(e)}var _o=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],Co=new Set(_o);function wo(e){return Co.has(e)}var Oo=new Set(Lo),Mo=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),xo=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Fo=new Set(xo);function No(e){return Fo.has(e)||ko(e)}var Bo=new Set(["ot","sf","st","e","sta"]);function Uo(e){return Bo.has(e)}function Go(e){return"number"==typeof e?x(e):null!=e&&""!==e&&!1!==e}var Ko=((to={})[Ao]=function(e){return Po(e)||wo(e)||Oo.has(e)},to[Io]=Po,to);function Vo(e,t){var r;return Array.isArray(e)?(t&&(r=e.find((function(e){var r;return(null==(r=e.params)?void 0:r.ot)===t}))),r||(r=e[0]),Vo(r)):e instanceof Cs?e.value:e}function Ho(e,t){void 0===t&&(t={});var r={};if(null==e||"object"!=typeof e)return r;var i=t.version||e.v||fo,n=t.reportingMode||Io,a=1===i?function(e){for(var t={},r=0,i=Object.entries(e);r<i.length;r++){var n=i[r],a=n[0],s=n[1];if(null!=s)if("nor"===a){var o,l=(Array.isArray(s)?s:[s])[0];l instanceof Cs?(t.nor=l.value,null!=(o=l.params)&&o.r&&(t.nrr=l.params.r)):t.nor=l}else Mo.has(a)?t[a]=Vo(s,e.ot):t[a]=s;else t[a]=s}return t}(e):e,o=1===i?No:Ko[n],l=Object.keys(a).filter(o);a.e&&a.e!==vo&&(l=l.filter((function(e){return!wo(e)})));var u=t.filter;"function"==typeof u&&(l=l.filter(u));var d=n===Ao;if(d){var h=a.e;l.includes("e")||null==h||l.push("e"),l.includes("ts")||l.push("ts"),l.includes("cen")||null==a.cen||h!==mo||l.push("cen");var f=h?So.get(h):void 0;f&&null!=a[f]&&!l.includes(f)&&l.push(f)}if(0===l.length)return r;i>1&&!l.includes("v")&&l.push("v");var c={version:i,reportingMode:n,baseUrl:t.baseUrl};l.sort();for(var g,v=s(l);!(g=v()).done;){var m,p,y=g.value,E=a[y],T=null!=(m=null==(p=t.formatters)?void 0:p[y])?m:ho[y];if("function"==typeof T&&(E=T(E,c)),"v"===y){if(1===i)continue;E=i}if("pr"!==y||1!==E||d&&a.e===co){d&&"ts"===y&&!x(E)&&(E=Date.now());var S=d&&!1===E&&"bg"===y&&a.e===go;(Go(E)||S)&&(Uo(y)&&"string"==typeof E&&(E=new Ks(E)),r[y]=E)}}return r}var Yo="CMCD-Object",jo="CMCD-Request",Wo="CMCD-Session",qo="CMCD-Status",Xo={REQUEST:jo},zo={ab:Yo,br:Yo,d:Yo,lab:Yo,lb:Yo,ot:Yo,tab:Yo,tb:Yo,tpb:Yo,bl:jo,cs:jo,dfa:jo,dl:jo,ltc:jo,mtp:jo,nor:jo,nrr:jo,pb:jo,sn:jo,sta:jo,su:jo,tbl:jo,cid:Wo,msd:Wo,sf:Wo,sid:Wo,st:Wo,v:Wo,bg:qo,bs:qo,bsa:qo,bsd:qo,bsda:qo,cdn:qo,ec:qo,nr:qo,pr:qo,pt:qo,rtp:qo};function Qo(e,t){var r={};if(!e)return r;for(var i,n=Object.keys(e),a=t?(i=t,Object.keys(i).reduce((function(e,t){var r;return null==(r=i[t])||r.forEach((function(r){return e[r]=t})),e}),{})):{},s=0,o=n;s<o.length;s++){var l,u=o[s],d=zo[u]||a[u]||Xo.REQUEST;(null!=(l=r[d])?l:r[d]={})[u]=e[u]}return r}var $o="CMCD";function Zo(e){return eo(e,{whitespace:!1})}function Jo(e,t){return void 0===t&&(t={}),e?Zo(Ho(e,t)):""}var el=[].concat(xo,Ro,_o,Lo).filter((function(e,t,r){return r.indexOf(e)===t})),tl="m",rl="a",il="v",nl="av",al="i",sl="tt",ol="s",ll="p",ul="k",dl="r",hl="a",fl="e",cl="f",gl="d",vl="query",ml="headers";function pl(e,t,r){var i,n=new Set(null!=(i=t.enabledKeys)?i:[]);return{version:t.version||fo,reportingMode:e,filter:function(e){return n.has(e)},baseUrl:r}}var yl=Object.is,El=function(e){return e},Tl=Array.from(So,(function(e){var t=e[0],r=e[1];return"br"===r?{event:t,field:r,equal:function(e,t){return void 0===e||void 0===t?e===t:function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++){var i=e[r],n=t[r];if(i!==n){if("number"==typeof i||"number"==typeof n)return!1;if(i.value!==n.value)return!1;var a=i.params,s=n.params,o=a&&Object.keys(a)[0],l=s&&Object.keys(s)[0];if(o!==l)return!1;if(void 0!==o&&void 0!==l&&a&&s&&a[o]!==s[l])return!1}}return!0}(e,t)},snapshot:function(e){return e.slice()}}:{event:t,field:r,equal:yl,snapshot:El}})),Sl=new Map(Tl.map((function(e){return[e.event,e]})));function Al(e){var t=e.url,r=g(e,ro);return fetch(t,r)}var Il=function(){function e(e,t){var r;void 0===t&&(t=Al),this.timeOrigin=performance.timeOrigin||(null==(r=performance.timing)?void 0:r.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=function(e){var t=e.version,r=void 0===t?fo:t,i=e.eventTargets,n=void 0===i?[]:i,a=e.sid,s=void 0===a?b():a,o=e.transmissionMode,l=void 0===o?vl:o;return c(c({},g(e,io)),{},{version:r,transmissionMode:l,sid:s,eventTargets:n.reduce((function(e,t){var r,i,n;return null!=t&&t.url&&null!=(r=t.events)&&r.length&&e.push({version:t.version||fo,enabledKeys:(null==(i=t.enabledKeys)?void 0:i.slice())||[],url:t.url,events:t.events.slice(),interval:null!=(n=t.interval)?n:30,batchSize:t.batchSize||1}),e}),[])})}(e),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=t;for(var i,n=s(this.config.eventTargets);!(i=n()).done;){var a=i.value;this.eventTargets.set(a,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}}var t=e.prototype;return t.start=function(){var e=this;this.eventTargets.forEach((function(t,r){if(e.disarmInterval(t),0!==r.interval&&r.events.includes("t")){var i=function(){e.recordTargetEvent(t,r,"t"),e.processEventTargets()};t.intervalId=setInterval(i,1e3*r.interval),i()}}))},t.stop=function(e){var t=this;void 0===e&&(e=!1),e&&this.flush(),this.eventTargets.forEach((function(e){t.disarmInterval(e)}))},t.flush=function(){this.processEventTargets(!0)},t.update=function(e){e.sid&&e.sid!==this.data.sid&&this.resetSession(),e.msd&&!isNaN(e.msd)&&(this.msd=e.msd),this.data=c(c(c({},this.data),e),{},{msd:void 0});for(var t=0,r=Tl;t<r.length;t++){var i=r[t];i.field in e&&!i.equal(this.data[i.field],this.lastEmitted[i.field])&&this.recordEvent(i.event)}},t.recordEvent=function(e,t){var r=this;void 0===t&&(t={});var i=Sl.get(e);if(i){var n,a,s=i.field,o=t[s];void 0!==o&&l(this.data,((n={})[s]=o,n));var u=this.data[s];if(void 0===u)return;if(i.equal(u,this.lastEmitted[s]))return;l(this.lastEmitted,((a={})[s]=i.snapshot(u),a))}this.eventTargets.forEach((function(i,n){r.recordTargetEvent(i,n,e,t)})),this.processEventTargets()},t.recordTargetEvent=function(e,t,r,i){var n;if(void 0===i&&(i={}),t.events.includes(r)){var a=c(c(c({},this.data),i),{},{e:r,ts:null!=(n=i.ts)?n:Date.now(),sn:e.sn++});isNaN(this.msd)||e.msdSent||(a.msd=this.msd,e.msdSent=!0),e.queue.push(a)}},t.recordResponseReceived=function(e,t){var r,i,n;void 0===t&&(t={});var a=e.request,s=null!=(r=t.url)?r:null==a?void 0:a.url;if(s){var o=new URL(s);o.searchParams.delete($o);var l={url:o.toString(),rc:e.status},u=e.resourceTiming;u&&(null!=u.startTime&&(l.ts=Math.round(this.timeOrigin+u.startTime),null!=u.responseStart&&(l.ttfb=Math.round(u.responseStart-u.startTime))),null!=u.duration&&(l.ttlb=Math.round(u.duration)));var d=null!=(i=null==(n=a.customData)?void 0:n.cmcd)?i:{};this.recordEvent(vo,c(c(c({},d),l),t))}},t.applyRequestReport=function(e){var t;return null!=(t=this.createRequestReport(e))?t:e},t.isRequestReportingEnabled=function(){var e;return!(null==(e=this.config.enabledKeys)||!e.length)},t.createRequestReport=function(e,t){var r,i=e.customData,n=void 0===i?{}:i,a=e.headers,s=void 0===a?{}:a,o=c(c({},g(e,no)),{},{headers:c({},s),customData:c(c({},n),{},{cmcd:{}})});if(null==(r=this.config.enabledKeys)||!r.length||!o.url)return o;var u=new URL(o.url),d=c(c(c({},this.data),t),{},{sn:this.requestTarget.sn++}),h=pl(Io,this.config,o.url);isNaN(this.msd)||this.requestTarget.msdSent||(d.msd=this.msd,this.requestTarget.msdSent=!0);var f=o.customData.cmcd=Ho(d,h);switch(this.config.transmissionMode){case vl:var v=Zo(f);v&&(u.searchParams.set($o,v),o.url=u.toString());break;case ml:l(o.headers,function(e,t){for(var r={},i=Qo(e,t),n=0,a=Object.entries(i);n<a.length;n++){var s=a[n],o=s[0],l=eo(s[1],{whitespace:!1});l&&(r[o]=l)}return r}(f,h.customHeaderMap))}return o},t.processEventTargets=function(e){var t=this;void 0===e&&(e=!1);var r=!1;this.eventTargets.forEach((function(i,n){var a=i.queue;if(a.length&&(!(a.length<n.batchSize)||e)){var s=e?a.length:n.batchSize,o=a.splice(0,s);t.sendEventReport(n,o).catch((function(){var e;(e=i.queue).unshift.apply(e,o)})),r||(r=a.length>0)}})),r&&this.processEventTargets()},t.sendEventReport=function(){var e,t=(e=v().m((function e(t,r){var i,n,a;return v().w((function(e){for(;;)switch(e.n){case 0:return i=pl(Ao,t),e.n=1,this.requester({url:t.url,method:"POST",headers:{"Content-Type":"application/cmcd"},body:r.map((function(e){return Jo(e,i)})).join("\n")+"\n"});case 1:if(n=e.v,410!==(a=n.status)){e.n=2;break}this.disposeEventTarget(t),e.n=3;break;case 2:if(!(429===a||a>499&&a<600)){e.n=3;break}throw new Error("Event report failed with status "+a);case 3:return e.a(2)}}),e,this)})),function(){var t=this,r=arguments;return new Promise((function(n,a){var s=e.apply(t,r);function o(e){i(s,n,a,o,l,"next",e)}function l(e){i(s,n,a,o,l,"throw",e)}o(void 0)}))});return function(e,r){return t.apply(this,arguments)}}(),t.disarmInterval=function(e){clearInterval(e.intervalId),e.intervalId=void 0},t.disposeEventTarget=function(e){var t=this.eventTargets.get(e);t&&(this.disarmInterval(t),this.eventTargets.delete(e))},t.resetSession=function(){this.eventTargets.forEach((function(e){return e.sn=0})),this.requestTarget.sn=0,this.lastEmitted={}},e}(),Ll="h",Rl="v",bl="l",kl="ll";new Set(xo),new Set(el);var Dl=["includeKeys"];function Pl(e){return Object.keys(e).every(ko)}var _l=function(){function e(e){var t=this;this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=function(){t.initialized&&(t.starved=!0,t.setPlayerState(dl)),t.buffering=!0},this.onPlay=function(){t.initialized||t.setPlayerState(ol)},this.onPlaying=function(){t.initialized||(t.initialized=!0),t.buffering=!1,t.setPlayerState(ll)},this.onPause=function(){t.media&&!t.media.ended&&t.setPlayerState(hl)},this.onSeeking=function(){t.initialized&&t.setPlayerState(ul)},this.onSeeked=function(){var e;t.initialized&&null!=(e=t.media)&&e.paused&&t.setPlayerState(hl)},this.onRateChange=function(){t.reporter&&t.media&&t.reporter.update({pr:t.media.playbackRate})},this.applyPlaylistData=function(e){try{t.apply(e,{ot:tl,su:!t.initialized})}catch(e){t.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=function(e){try{var r=e.frag,i=e.part,n=t.hls.levels[r.level],a=t.getObjectType(r,n),s={d:1e3*(i||r).duration,ot:a};if(a===il||a===rl||a===nl||null==a&&("main"===r.type||"audio"===r.type)){var o,l=n.bitrate/1e3;s.br=[l];var u=t.config.cmcd,d=null!=(o=null==u?void 0:u.rtpSafetyFactor)?o:5;if(s.rtp=100*Math.round(l*d/100),a===nl||null==a&&"main"===r.type){var h=t.getTopBandwidth()/1e3;x(h)&&(s.tb=[h]);var f=t.getLowestBandwidth()/1e3;x(f)&&(s.lb=[f])}var c=t.getBufferLength(r);if(x(c)){var g;s.bl=[c];var v=(null==(g=t.media)?void 0:g.playbackRate)||1;s.dl=100*Math.round(c/v/100)}t.playheadLevel&&(s.pb=[t.playheadLevel.bitrate/1e3]);var m=t.hls.maxAutoLevel;if(m>=0){var p=t.hls.levels[m];p&&(s.tpb=[p.bitrate/1e3])}}var y=i?t.getNextPart(i):t.getNextFrag(r);null!=y&&y.url&&y.url!==r.url&&(y.byteRange.length>0?s.nor=[(E=y.url,T={r:y.byteRange[0]+"-"+y.byteRange[1]},new Cs(E,T))]:s.nor=[y.url]),t.apply(e,s)}catch(e){t.hls.logger.warn("Could not generate segment CMCD data.",e)}var E,T},this.recordFragmentResponse=function(e,r,i){var n,a=t.config.cmcd,s=null==a||null==(n=a.eventTargets)?void 0:n.some((function(e){var t;return null==(t=e.events)?void 0:t.includes(Eo)}));if(t.reporter&&i.loading.first>0&&s)try{t.reporter.recordResponseReceived({request:{url:e},status:r.code,resourceTiming:{startTime:i.loading.start,responseStart:i.loading.first,duration:i.loading.end-i.loading.start,encodedBodySize:i.total}})}catch(e){t.hls.logger.warn("Could not record fragment response CMCD data.",e)}},this.hls=e;var r=this.config=e.config;null!=r.cmcd&&(r.pLoader=this.createPlaylistLoader(),r.fLoader=this.createFragmentLoader(),this.registerListeners())}var t=e.prototype;return t.createReporter=function(){var e,t,r=this.config.cmcd;if(null!=r){var i=r.version||1;if(this.reporter=new Il({sid:r.sessionId||this.hls.sessionId,cid:r.contentId,version:i,transmissionMode:!0===r.useHeaders?ml:vl,enabledKeys:null!=(e=r.includeKeys)?e:[].concat(i>=fo?el:xo),eventTargets:(null!=(t=r.eventTargets)?t:[]).map((function(e){var t=e.includeKeys;return c(c({},g(e,Dl)),{},{enabledKeys:null!=t?t:el})}))},r.loader),this.reporter.update({sf:Ll,sta:this.playerState}),r.reporterCallback){var n=this.reporter,a={updateCustomData:function(e){Pl(e)&&n.update(e)},recordCustomEvent:function(e,t){void 0===t&&(t={}),Pl(t)&&n.recordEvent(To,c({cen:e},t))}};r.reporterCallback(a)}this.reporter.start()}},t.registerListeners=function(){var e=this.hls;e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(G.MEDIA_DETACHED,this.onMediaDetached,this),e.on(G.MEDIA_ENDED,this.onMediaEnded,this),e.on(G.ERROR,this.onError,this),e.on(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(G.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(G.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(G.BUFFER_FLUSHED,this.onBufferInfoChange,this)},t.unregisterListeners=function(){var e=this.hls;e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(G.MEDIA_DETACHED,this.onMediaDetached,this),e.off(G.MEDIA_ENDED,this.onMediaEnded,this),e.off(G.ERROR,this.onError,this),e.off(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(G.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(G.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(G.BUFFER_FLUSHED,this.onBufferInfoChange,this)},t.destroy=function(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null},t.onMediaAttaching=function(e,t){var r=this.media=t.media;this.setPlayerState(this.media.autoplay?ol:gl),_n(r,"waiting",this.onWaiting),_n(r,"play",this.onPlay),_n(r,"playing",this.onPlaying),_n(r,"pause",this.onPause),_n(r,"seeking",this.onSeeking),_n(r,"seeked",this.onSeeked),_n(r,"ratechange",this.onRateChange)},t.onMediaDetached=function(){var e=this.media;e&&(Cn(e,"waiting",this.onWaiting),Cn(e,"play",this.onPlay),Cn(e,"playing",this.onPlaying),Cn(e,"pause",this.onPause),Cn(e,"seeking",this.onSeeking),Cn(e,"seeked",this.onSeeked),Cn(e,"ratechange",this.onRateChange),this.media=null)},t.onMediaEnded=function(e,t){this.setPlayerState(fl)},t.onManifestLoading=function(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(gl)},t.onError=function(e,t){t.fatal&&(this.setPlayerState(cl),this.reporter&&this.reporter.recordEvent(yo,{ec:[t.details]}))},t.onLevelSwitching=function(e,t){var r;if(this.reporter){var i={br:[t.bitrate/1e3]},n=null==(r=t.details)?void 0:r.fragments[0];n&&(i.ot=this.getObjectType(n,t)),this.reporter.recordEvent(po,i)}},t.onLevelSwitched=function(e,t){var r=this.hls.levels[t.level];r&&(this.playheadLevel=r)},t.setPlayerState=function(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})},t.getStreamType=function(){var e=this.hls.latestLevelDetails;if(e)return e.live?e.partList&&e.canBlockReload?kl:bl:Rl},t.apply=function(e,t){var r;if(void 0===t&&(t={}),this.reporter){this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:null==(r=this.media)?void 0:r.playbackRate,st:this.getStreamType()});var i=t.ot===al||t.ot===il||t.ot===nl;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);var n=this.reporter.createRequestReport({url:e.url,headers:e.headers},t);e.url=n.url,e.headers=n.headers}},t.getNextFrag=function(e){var t,r=null==(t=this.hls.levels[e.level])?void 0:t.details;if(r){var i=e.sn-r.startSN;return r.fragments[i+1]}},t.getNextPart=function(e){var t,r=e.index,i=e.fragment,n=null==(t=this.hls.levels[i.level])||null==(t=t.details)?void 0:t.partList;if(n)for(var a=i.sn,s=n.length-1;s>=0;s--){var o=n[s];if(o.index===r&&o.fragment.sn===a)return n[s+1]}},t.getObjectType=function(e,t){var r=e.type;if("subtitle"===r)return sl;if("initSegment"===e.sn)return al;if("audio"===r)return rl;if("main"===r){if(e.hasStreams){var i=e.elementaryStreams;if(i.audiovideo)return nl;if(i.video)return il;if(i.audio)return rl}if(t){var n=t.audioCodec,a=t.videoCodec;if(!this.hls.audioTracks.length){if(n&&a)return nl;if(n)return rl}if(a)return il}}},t.getTopBandwidth=function(){var e=0,t=this.hls,r=t.maxAutoLevel,i=r>-1?r+1:t.levels.length;return t.levels.slice(0,i).forEach((function(t){t.bitrate>e&&(e=t.bitrate)})),e>0?e:NaN},t.getLowestBandwidth=function(){var e=1/0,t=this.hls,r=t.maxAutoLevel,i=r>-1?r+1:t.levels.length;return t.levels.slice(0,i).forEach((function(t){t.bitrate<e&&(e=t.bitrate)})),x(e)?e:NaN},t.getBufferLength=function(e){if(!this.media)return NaN;var t="audio"===e.type?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return t?1e3*t.len:NaN},t.getEventBufferLength=function(){if(!this.media)return NaN;var e=this.hls.mainForwardBufferInfo,t=this.hls.audioForwardBufferInfo;if(e&&t)return 1e3*Math.min(e.len,t.len);var r=e||t;return r?1e3*r.len:NaN},t.onBufferInfoChange=function(e,t){if(this.reporter){var r=this.getEventBufferLength();x(r)&&this.reporter.update({bl:[r]})}},t.createPlaylistLoader=function(){var e=this.config.pLoader,t=this.applyPlaylistData,r=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new r(e)}var i=e.prototype;return i.destroy=function(){this.loader.destroy()},i.abort=function(){this.loader.abort()},i.load=function(e,r,i){t(e),this.loader.load(e,r,i)},a(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}])}()},t.createFragmentLoader=function(){var e=this.config.fLoader,t=this.applyFragmentData,r=this.recordFragmentResponse,i=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new i(e)}var n=e.prototype;return n.destroy=function(){this.loader.destroy()},n.abort=function(){this.loader.abort()},n.load=function(e,i,n){t(e);var a=n.onSuccess;this.loader.load(e,i,c(c({},n),{},{onSuccess:function(t,i,n,s){a(t,i,n,s),r(e.url,t,i)}}))},a(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}])}()},e}(),Cl=function(e){function t(t){var r;return(r=e.call(this,"content-steering",t.logger)||this).hls=void 0,r.loader=null,r.uri=null,r.pathwayId=".",r._pathwayPriority=null,r.timeToLoad=300,r.reloadTimer=-1,r.updated=0,r.started=!1,r.enabled=!0,r.levels=null,r.audioTracks=null,r.subtitleTracks=null,r.penalizedPathways={},r.hls=t,r.registerListeners(),r}d(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(G.MANIFEST_PARSED,this.onManifestParsed,this),e.on(G.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(G.MANIFEST_PARSED,this.onManifestParsed,this),e.off(G.ERROR,this.onError,this))},r.pathways=function(){return(this.levels||[]).reduce((function(e,t){return-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e}),[])},r.startLoad=function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}},r.stopLoad=function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()},r.clearTimeout=function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)},r.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null},r.removeLevel=function(e){var t=this.levels;t&&(this.levels=t.filter((function(t){return t!==e})))},r.onManifestLoading=function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null},r.onManifestLoaded=function(e,t){var r=t.contentSteering;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())},r.onManifestParsed=function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks},r.onError=function(e,t){var r=t.errorAction;if((null==r?void 0:r.action)===wr&&r.flags&Fr){var i=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){var s=t.context,o=s.groupId,l=s.pathwayId,u=s.type;o&&i?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&i&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),r.resolved=this.pathwayId!==a,r.resolved||t.details===U.BUFFER_APPEND_ERROR&&!t.fatal||this.warn("Could not resolve "+t.details+' ("'+t.error.message+'") with content-steering for Pathway: '+a+" levels: "+(i?i.length:i)+" priorities: "+cr(n)+" penalized: "+cr(this.penalizedPathways)))}},r.filterParsedLevels=function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var r=e[0].pathwayId;this.log("No levels found in Pathway "+this.pathwayId+'. Setting initial Pathway to "'+r+'"'),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log("Found "+t.length+"/"+e.length+' levels in Pathway "'+this.pathwayId+'"'),t},r.getLevelsForPathway=function(e){return null===this.levels?[]:this.levels.filter((function(t){return e===t.pathwayId}))},r.updatePathwayPriority=function(e){var t;this._pathwayPriority=e;var r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach((function(e){i-r[e]>3e5&&delete r[e]}));for(var n=0;n<e.length;n++){var a=e[n];if(!(a in r)){if(a===this.pathwayId)return;var s=this.hls.nextLoadLevel,o=this.hls.levels[s];if((t=this.getLevelsForPathway(a)).length>0){this.log('Setting Pathway to "'+a+'"'),this.pathwayId=a,In(t),this.hls.trigger(G.LEVELS_UPDATED,{levels:t});var l=this.hls.levels[s];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=s);break}}}},r.getPathwayForGroupId=function(e,t,r){for(var i=this.getLevelsForPathway(r).concat(this.levels||[]),n=0;n<i.length;n++)if(t===Y&&i[n].hasAudioGroup(e)||t===j&&i[n].hasSubtitleGroup(e))return i[n].pathwayId;return r},r.clonePathways=function(e){var t=this,r=this.levels;if(r){var i={},n={};e.forEach((function(e){var a=e.ID,s=e["BASE-ID"],o=e["URI-REPLACEMENT"];if(!r.some((function(e){return e.pathwayId===a}))){var l=t.getLevelsForPathway(s).map((function(e){var t=new Ai(e.attrs);t["PATHWAY-ID"]=a;var r=t.AUDIO&&t.AUDIO+"_clone_"+a,s=t.SUBTITLES&&t.SUBTITLES+"_clone_"+a;r&&(i[t.AUDIO]=r,t.AUDIO=r),s&&(n[t.SUBTITLES]=s,t.SUBTITLES=s);var l=Ol(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),u=new dr({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(var d=1;d<e.audioGroups.length;d++)u.addGroupId("audio",e.audioGroups[d]+"_clone_"+a);if(e.subtitleGroups)for(var h=1;h<e.subtitleGroups.length;h++)u.addGroupId("text",e.subtitleGroups[h]+"_clone_"+a);return u}));r.push.apply(r,l),wl(t.audioTracks,i,o,a),wl(t.subtitleTracks,n,o,a)}}))}},r.loadSteeringManifest=function(e){var t,r=this,i=this.hls.config,n=i.loader;this.loader&&this.loader.destroy(),this.loader=new n(i);try{t=new self.URL(e)}catch(t){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: "+e)}if("data:"!==t.protocol){var a=0|(this.hls.bandwidthEstimate||i.abrEwmaDefaultEstimate);rr(t,"_HLS_pathway",this.pathwayId),rr(t,"_HLS_throughput",""+a)}var s={type:X,responseType:"json",url:t.href},o=i.steeringManifestLoadPolicy.default,l=o.errorRetry||o.timeoutRetry||{},u={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},d={onSuccess:function(e,i,n,a){r.log('Loaded steering manifest: "'+t+'"');var s=e.data;if(1===(null==s?void 0:s.VERSION)){r.updated=performance.now(),r.timeToLoad=s.TTL;var o=s["RELOAD-URI"],l=s["PATHWAY-CLONES"],u=s["PATHWAY-PRIORITY"];if(o)try{r.uri=new self.URL(o,t).href}catch(e){return r.enabled=!1,void r.log("Failed to parse Steering Manifest RELOAD-URI: "+o)}r.scheduleRefresh(r.uri||n.url),l&&r.clonePathways(l);var d={steeringManifest:s,url:t.toString()};r.hls.trigger(G.STEERING_MANIFEST_LOADED,d),u&&r.updatePathwayPriority(u)}else r.log("Steering VERSION "+s.VERSION+" not supported!")},onError:function(e,t,i,n){if(r.log("Error loading steering manifest: "+e.code+" "+e.text+" ("+t.url+")"),r.stopLoad(),410===e.code)return r.enabled=!1,void r.log("Steering manifest "+t.url+" no longer available");var a=1e3*r.timeToLoad;if(429!==e.code)r.scheduleRefresh(r.uri||t.url,a);else{var s=r.loader;if("function"==typeof(null==s?void 0:s.getResponseHeader)){var o=s.getResponseHeader("Retry-After");o&&(a=1e3*parseFloat(o))}r.log("Steering manifest "+t.url+" rate limited")}},onTimeout:function(e,t,i){r.log("Timeout loading steering manifest ("+t.url+")"),r.scheduleRefresh(r.uri||t.url)}};this.log("Requesting steering manifest: "+t),this.loader.load(s,u,d)},r.scheduleRefresh=function(e,t){var r=this;void 0===t&&(t=1e3*this.timeToLoad),this.clearTimeout(),this.reloadTimer=self.setTimeout((function(){var t,i=null==(t=r.hls)?void 0:t.media;!i||i.ended?r.scheduleRefresh(e,1e3*r.timeToLoad):r.loadSteeringManifest(e)}),t)},a(t,[{key:"pathwayPriority",get:function(){return this._pathwayPriority},set:function(e){this.updatePathwayPriority(e)}}])}(pe);function wl(e,t,r,i){e&&Object.keys(t).forEach((function(n){var a=e.filter((function(e){return e.groupId===n})).map((function(e){var a=l({},e);return a.details=void 0,a.attrs=new Ai(a.attrs),a.url=a.attrs.URI=Ol(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),a.groupId=a.attrs["GROUP-ID"]=t[n],a.attrs["PATHWAY-ID"]=i,a}));e.push.apply(e,a)}))}function Ol(e,t,r,i){if(t){var n=i[r];if(n){var a=n[t];if(a)return a}}var s=i.HOST,o=i.PARAMS,l=new self.URL(e);return s&&(l.hostname=s),o&&Object.keys(o).sort().forEach((function(e){e&&rr(l,e,o[e])})),l.href}var Ml=function(){function e(){this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new w,this.error=void 0,this.ok=void 0}var t=e.prototype;return t.resolve=function(){this.ok=!0,this.emitter.emit("resolved")},t.reset=function(){this.emitter.removeAllListeners();var e=this.licenseXhr;e&&(e.readyState!==XMLHttpRequest.DONE&&e.abort(),this.licenseXhr=void 0),this.onmessage=this.onkeystatuseschange=void 0},a(e,[{key:"errored",get:function(){return this.error},set:function(e){this.error=e,this.emitter.eventNames().length&&this.emitter.emit("error",e)}},{key:"hasListeners",get:function(){return this.emitter.eventNames().length>0}},{key:"resolved",get:function(){return this.ok}},{key:"useable",get:function(){var e=this;return this.ok?Promise.resolve():this.error?Promise.reject(this.error):new Promise((function(t,r){e.emitter.on("error",r),e.emitter.on("resolved",t)}))}}])}(),xl=function(e){function t(t,r){var i;return(i=e.call(this,r)||this).data=void 0,t.error||(t.error=new Error(r)),i.data=t,t.err=t.error,i}return d(t,e),t}(E(Error)),Fl=function(e){function t(r){var i;return(i=e.call(this,"eme",r.logger)||this).hls=void 0,i.config=void 0,i.media=null,i.mediaResolved=void 0,i.keyFormatPromise=null,i.keySystemAccessPromises={},i.sessionSetupByUri={},i.mediaKeySessions=[],i.activeKeys={},i.mediaKeys=null,i.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],i.onMediaEncrypted=function(e){var t=e.initDataType,r=e.initData,n='"'+e.type+'" event: init data type: "'+t+'"';if(i.log(n),null!==r){if(!i.keyFormatPromise){var a=Object.keys(i.keySystemAccessPromises);a.length||(a=Vi(i.config));var s=a.map(Ki).filter((function(e){return!!e}));i.keyFormatPromise=i.getKeyFormatPromise(s)}i.keyFormatPromise.then((function(a){var s,o,l=Ui(a),u=i.activeLevelKeys();if(l===Mi.FAIRPLAY&&"sinf"===t)try{var d=We(new Uint8Array(r)),h=mt(je(JSON.parse(d).sinf));if(!h)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");s=new Uint8Array(h.subarray(8,24))}catch(e){return void i.warn(n+" Failed to parse sinf: "+e)}else if(l===Mi.PLAYREADY)s=ji(new Uint8Array(r));else if(l===Mi.WIDEVINE){var f=Rt(r).filter((function(e){return e.systemId===Gi}));if(f.length){var c,g=f[0];s=null!=(c=g.kids)&&c.length?g.kids[0]:null}}if(s)for(var v=He(s),m=0;m<u.length;m++){var p=u[m];if(p.keyId&&(bi(s,p.keyId)||-1!==p.uri.replace(/-/g,"").indexOf(v))){p.pssh||(p.scheme=t,p.pssh=new Uint8Array(r),p.keyId=s,qi.setKeyIdForUri(p.uri,s)),o=i.getSessionForKey(p,"encrypted-event-key-match");break}}if(!o){var y,E;if(u.length)return(y=u[0]).scheme||(y.scheme=t),(E=u[0]).pssh||(E.pssh=new Uint8Array(r)),i.getSessionForKey(u[0],"encrypted-event-no-match");if(s)throw new Error("Key ID "+He(s)+" not encountered in playlist");i.log('Ignoring "'+e.type+'" event - could not determine keyId')}return o})).catch((function(e){return i.handleError(e)}))}},i.onWaitingForKey=function(e){i.log('"'+e.type+'" event')},i.hls=r,i.config=r.config,i.registerListeners(),i}d(t,e);var r=t.prototype;return r.destroy=function(){this.onDestroying(),this.onMediaDetached();var e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null},r.registerListeners=function(){var e=this.hls;e&&(e.on(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHED,this.onMediaDetached,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(G.DESTROYING,this.onDestroying,this))},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHED,this.onMediaDetached,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(G.DESTROYING,this.onDestroying,this))},r.attemptKeySystemAccess=function(e){var t=this;if(!this.hls)return Promise.reject(new Error("destroyed"));var r=this.hls.levels,i=function(e,t,r){return!!e&&r.indexOf(e)===t},n=r.map((function(e){return e.audioCodec})).filter(i),a=r.map((function(e){return e.videoCodec})).filter(i);return n.length+a.length===0&&a.push("avc1.42e01e"),new Promise((function(r,i){var s=function(e){var o=e.shift();t.getMediaKeysPromise(o,n,a).then((function(e){return r({keySystem:o,mediaKeys:e})})).catch((function(t){e.length?s(e):i(t instanceof xl?t:new xl({type:B.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};s(e)}))},r.requestMediaKeySystemAccess=function(e,t){var r=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof r){var i="Configured requestMediaKeySystemAccess is not a function "+r;return null===Yi&&"http:"===self.location.protocol&&(i="navigator.requestMediaKeySystemAccess is not available over insecure protocol "+location.protocol),Promise.reject(new Error(i))}return r(e,t)},r.getMediaKeysPromise=function(e,t,r){var i,n=this,a=function(e,t,r,i){var n;switch(e){case Mi.FAIRPLAY:n=["cenc","sinf"];break;case Mi.WIDEVINE:case Mi.PLAYREADY:n=["cenc"];break;case Mi.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error("Unknown key-system: "+e)}return function(e,t,r,i){return[{initDataTypes:e,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:t.map((function(e){return{contentType:"audio/mp4; codecs="+e,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null}})),videoCapabilities:r.map((function(e){return{contentType:"video/mp4; codecs="+e,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}}))}]}(n,t,r,i)}(e,t,r,this.config.drmSystemOptions||{}),s=this.keySystemAccessPromises[e],o=null==(i=s)?void 0:i.keySystemAccess;if(!o){this.log('Requesting encrypted media "'+e+'" key-system access with config: '+cr(a)),o=this.requestMediaKeySystemAccess(e,a);var l=s=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch((function(t){n.log('Failed to obtain access to key-system "'+e+'": '+t)})),o.then((function(t){n.throwIfDestroyed(),n.log('Access for key-system "'+t.keySystem+'" obtained');var r=n.fetchServerCertificate(e);n.log('Create media-keys for "'+e+'"');var i=l.mediaKeys=t.createMediaKeys().then((function(t){return n.log('Media-keys created for "'+e+'"'),l.hasMediaKeys=!0,r.then((function(r){return r?n.setMediaKeysServerCertificate(t,e,r):t}))}));return i.catch((function(t){n.error('Failed to create media-keys for "'+e+'"}: '+t)})),i}))}return o.then((function(){return s.mediaKeys}))},r.getMediaKeySessionContext=function(e,t,r,i){for(var n=this.mediaKeySessions,a=' key-session "'+e+'" keyId: '+He(r.keyId||[])+" keyUri: "+r.uri+' for "'+i+'"',s=0;s<n.length;s++){var o=n[s];if(!o.initialized&&o.createdFor.levelKey.uri===r.uri)return this.log("Reusing"+a),o}this.log("Creating"+a);var l=t.createSession(),u={keySystem:e,mediaKeys:t,mediaKeysSession:l,keyRequests:{},keyStatuses:{},createdFor:{levelKey:r,reason:i},initialized:!1};return n.push(u),u},r.resetMediaKeys=function(){var e,t=null==(e=this.mediaKeySessions[0])?void 0:e.keySystem,r=this.keySystemAccessPromises[t];r&&(this.log("reset mediaKeys"),this.mediaKeys=null,r.hasMediaKeys=!1,delete r.mediaKeys,delete this.keySystemAccessPromises[t])},r.updateKeySession=function(e,t,r){var i=e.mediaKeysSession;return this.log('Updating key-session "'+i.sessionId+'" for keyId '+He(t.keyId||[])+"\n } (data length: "+r.byteLength+")"),i.update(r)},r.getSelectedKeySystemFormats=function(){var e=this;return Object.keys(this.keySystemAccessPromises).map((function(t){return{keySystem:t,hasMediaKeys:e.keySystemAccessPromises[t].hasMediaKeys}})).filter((function(e){return!!e.hasMediaKeys})).map((function(e){return Ki(e.keySystem)})).filter((function(e){return!!e}))},r.getKeySystemAccess=function(e){var t=this;return this.getKeySystemSelectionPromise(e).then((function(e){var r=e.keySystem,i=e.mediaKeys;return t.attemptSetMediaKeys(r,i)}))},r.selectKeySystem=function(e){return this.getKeySystemSelectionPromise(e).then((function(e){var t=e.keySystem,r=Ki(t);if(!r)throw new Error('Unable to find format for key-system "'+t+'"');return r}))},r.selectKeySystemFormat=function(e){var t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log("Selecting key-system from fragment (sn: "+e.sn+" "+e.type+": "+e.level+") key formats "+t.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise},r.getKeyFormatPromise=function(e){var t=Vi(this.config),r=e.map(Ui).filter((function(e){return!!e&&-1!==t.indexOf(e)}));return this.selectKeySystem(r)},r.loadClear=function(e,t,r){var i=this;if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(var n,a=function(){var n=t[s];if(e.cc<=n.cc&&(!ee(e)||!ee(n)||e.sn<n.sn)||!r&&s==o-1)return{v:i.selectKeySystemFormat(n).then((function(e){if(i.hls){n.setKeyFormat(e);var t=Ui(e);return t?i.getKeySystemAccess([t]):void 0}}))}},s=0,o=t.length;s<o;s++)if(n=a())return n.v;if(this.config.requireKeySystemAccessOnStart){var l=Vi(this.config);if(l.length)return this.getKeySystemAccess(l)}}return null},r.getKeyStatus=function(e){for(var t=this.mediaKeySessions,r=0;r<t.length;r++){var i=Nl(e,t[r]);if(i)return i}},r.loadKey=function(e){var t=e.decryptdata,r=this.getKeyStatus(t);if("internal-error"===r){var i=Bl(r,t);return i.data.frag=e,this.error(i.message+" ("+He(t.keyId||[])+")"),Promise.reject(i)}var n=e.type,a=this.activeKeys,s=a[n];s&&!t.matches(s.decryptdata)&&(a.previous||(a.previous=[]),a.previous.push(s),delete a[n]),a[n]||(a[n]=e);for(var o=this.mediaKeySessions.length;o--;){var l=this.mediaKeySessions[o];if(t.keyId&&"expired"===l.keyStatuses[He(t.keyId)])return this.renewKeySession(t,l)}return this.updateUsablePromise(t,"playlist-key",e)},r.renewKeySession=function(e,t){var r=this;return this.resetMediaKeys(),this.removeSession(t).then((function(){return r.throwIfDestroyed(),r.updateUsablePromise(e,"expired")}))},r.updateUsablePromise=function(e,t,r){var i=this,n=this.getSessionForKey(e,t);return n.catch((function(e){return i.handleError(e,r)})),n.then((function(t){return e}))},r.getSessionForKey=function(e,t){var r=this,i=this.findContextForKey(e);if(void 0!==i)return Promise.resolve(i);var n,a=e.uri,s=this.sessionSetupByUri[a];n=void 0===s?this.resolveSessionForKey(e,t):s.catch((function(){})).then((function(){return r.throwIfDestroyed(),r.resolveSessionForKey(e,t)})),this.sessionSetupByUri[a]=n;var o=function(){r.sessionSetupByUri[a]===n&&delete r.sessionSetupByUri[a]};return n.then(o,o),n},r.findContextForKey=function(e){for(var t=this.mediaKeySessions,r=t.length;r--;){var i=t[r];if(Nl(e,i))return i}},r.resolveSessionForKey=function(e,t){var r=this;return this.getKeySystemForKeyPromise(e).then((function(i){var n=i.keySystem,a=i.mediaKeys;r.throwIfDestroyed();for(var s=r.mediaKeySessions.length;s--;){var o=r.mediaKeySessions[s];if(Nl(e,o))return o;var l=r.getUsableKeyPromise(o,e,t);if(l)return l}return r.attemptSetMediaKeys(n,a).then((function(){return r.throwIfDestroyed(),r.getMediaKeySessionContext(n,a,e,t)})).then((function(i){r.throwIfDestroyed();var n=e.scheme||"cenc",a=e.pssh?e.pssh.buffer:null;return r.generateRequestWithPreferredKeySession(i,e,n,a,t)}))}))},r.getUsableKeyPromise=function(e,t,r){var i=e.keyRequests[t.uri];if(i)return this.log("Waiting for usable key ("+r+" keyId: "+function(e){if(e.keyFormat===Fi)return e.uri;if(null===e.keyId)throw new Error("keyId is null");return He(e.keyId)}(t)+' format: "'+t.keyFormat+'" URI: '+t.uri+")"),i.useable.then((function(){return e}))},r.throwIfDestroyed=function(e){if(!this.hls)throw new Error("invalid state")},r.handleError=function(e,t){if(this.hls)if(e instanceof xl){t&&(e.data.frag=t);var r=e.data.decryptdata;this.error(e.message+(r?" ("+He(r.keyId||[])+")":"")),this.hls.trigger(G.ERROR,e.data)}else this.error(e.message),this.hls.trigger(G.ERROR,{type:B.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})},r.getKeySystemForKeyPromise=function(e){var t=Ui(e.keyFormat),r=t?[t]:Vi(this.config);return this.attemptKeySystemAccess(r)},r.getKeySystemSelectionPromise=function(e){if(e.length||(e=Vi(this.config)),0===e.length)throw new xl({type:B.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options "+cr({drmSystems:this.config.drmSystems}));return this.attemptKeySystemAccess(e)},r.activeLevelKeys=function(){var e=this.activeKeys,t=(e.previous||[]).map((function(e){return e.decryptdata}));return e.audio&&t.unshift(e.audio.decryptdata),e.main&&t.unshift(e.main.decryptdata),t},r.attemptSetMediaKeys=function(e,t){var r=this;if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();var i=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'+e+'"');var n=Promise.all(i).then((function(){return r.media?r.media.setMediaKeys(t):new Promise((function(e,i){r.mediaResolved=function(){if(r.mediaResolved=void 0,!r.media)return i(new Error("Attempted to set mediaKeys without media element attached"));r.mediaKeys=t,r.media.setMediaKeys(t).then(e).catch(i)}}))}));return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then((function(){r.log('Media-keys set for "'+e+'"'),i.push(n),r.setMediaKeysQueue=r.setMediaKeysQueue.filter((function(e){return-1===i.indexOf(e)}))}))},r.filterInitData=function(e,t,r,i,n){var a,s=null==(a=this.config.drmSystems)||null==(a=a[e.keySystem])?void 0:a.generateRequest;if(s)try{var o=s.call(this.hls,r,i,l({},e,{decryptdata:t,reason:n}),n);if(!o)throw new Error("Invalid response from configured generateRequest filter");t.scheme=o.initDataType?o.initDataType:"cenc";var u=o.initData?o.initData:null;return t.pssh=u?new Uint8Array(u):null,o}catch(e){var d;if(this.warn(e.message),null!=(d=this.hls)&&d.config.debug)throw e}return{initDataType:r,initData:i}},r.generateRequestWithPreferredKeySession=function(e,t,r,i,n){var a=this,s=this.getUsableKeyPromise(e,t,n);if(s)return s;var o=this.filterInitData(e,t,r,i,n);if(o&&(i=o.initData?o.initData:null,r=o.initDataType),null===i)return n.startsWith("encrypted-event")?Promise.reject(new Error('missing initialization data for "'+n+'"')):(this.log('Skipping key-session request for "'+n+'" (no initData)'),Promise.resolve(e));var l=t.uri,u=new Ml;e.keyRequests[l]=u;var d=function(r){var i=e.mediaKeysSession;if(i){var n=r.messageType,s=r.message;u.status=n,a.log('"'+n+'" message event for session "'+i.sessionId+'" message size: '+s.byteLength),"license-request"===n||"license-renewal"===n?a.renewLicense(e,t,s).catch((function(t){u.errored=t,u.hasListeners||a.handleError(t),a.removeSession(e)})):"license-release"===n?e.keySystem===Mi.FAIRPLAY&&a.updateKeySession(e,t,_i("acknowledged")).then((function(){return a.removeSession(e)})).catch((function(e){return a.handleError(e)})):a.warn('unhandled media key message type "'+n+'"')}else{var o=new Error("invalid state");u.errored=o}};return u.onmessage=d,_n(e.mediaKeysSession,"message",d),this.generateRequest(e,t,r,i,n,!1)},r.generateRequest=function(e,t,r,i,n,a){var s=this;if(a){var o=this.filterInitData(e,t,r,i,n);o&&(i=o.initData?o.initData:i,r=o.initDataType)}var l=t.uri,u=e.keyRequests[l],d=He(t.keyId||[]),h=function(e){var r;e.startsWith("usable")?u.resolve():"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?r=Bl(e,t):"expired"===e?r=new Error("key expired (keyId: "+d+")"):"released"===e?r=new Error("key released"):"status-pending"===e||s.warn('unhandled key status change "'+e+'" (keyId: '+d+")"),r&&(u.errored=r,u.hasListeners||s.handleError(r))},f=function(r){if(e.mediaKeysSession){var i=e.keyStatuses=s.getKeyStatuses(e);if(Object.keys(i).some((function(e){return"status-pending"!==i[e]}))){for(var n=s.activeLevelKeys(),a=0;a<n.length;a++){var o=He(n[a].keyId||[]);if("expired"===i[o]){var l;s.log("Expired key "+cr(i)+' in key-session "'+(null==(l=e.mediaKeysSession)?void 0:l.sessionId)+'"'),s.renewKeySession(t,e).catch((function(e){return s.handleError(e)}));break}}var f,c=i[d];if(c)h(c);else e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(f=e.keyStatusTimeouts)[d]||(f[d]=self.setTimeout((function(){var r;if(e.mediaKeysSession){var i,n=s.getKeyStatus(t);if(n&&"status-pending"!==n)return s.log("No status for keyId "+d+' in key-session "'+(null==(i=e.mediaKeysSession)?void 0:i.sessionId)+'". Using session key-status '+n+" from other session."),h(n);s.log("key status for "+d+' in key-session "'+(null==(r=e.mediaKeysSession)?void 0:r.sessionId)+'" timed out after 1000ms'),h(c="internal-error")}}),1e3)),s.log("No status for keyId "+d+" ("+cr(i)+").")}}else{var g=new Error("invalid state");u.errored=g}};u.onkeystatuseschange=f,_n(e.mediaKeysSession,"keystatuseschange",f);var c=u.useable;return this.log('Generating key-session request for "'+n+'" keyId: '+d+" URI: "+l+" (init data type: "+r+" length: "+i.byteLength+")"),u.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(r,i).then((function(){var t;u.status="generated",s.log('Request generated for key-session "'+(null==(t=e.mediaKeysSession)?void 0:t.sessionId)+'" keyId: '+d+" URI: "+l)})).catch((function(e){throw s.log("mediaKeysSession.generateRequest failed: "+e),new xl({type:B.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t,fatal:!1},"Error generating key-session request: "+e)})).then((function(){return c})).catch((function(t){var r;s.log("mediaKeysSession.generateRequest failed: "+t);var i=null==(r=t.data)?void 0:r.details;return i!==U.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED&&i!==U.KEY_SYSTEM_STATUS_INTERNAL_ERROR||!Object.keys(e.keyStatuses).some((function(t){return"usable"===e.keyStatuses[t]}))?s.removeSession(e).then((function(){throw t})):(s.handleError(t),e)})).then((function(){return e}))},r.getKeyStatuses=function(e){var t=this,r={},i=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach((function(n,a){if("string"==typeof a&&"object"==typeof n){var s=a;a=n,n=s}var o="buffer"in a?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);if(e.keySystem===Mi.PLAYREADY&&16===o.length){var l=He(o);r[l]=n,Ci(o)}var u=He(o);t.log('key status change "'+n+'" for keyStatuses keyId: '+u+' key-session "'+i+'"'),r[u]=n})),r},r.fetchServerCertificate=function(e){var t=this.config,r=new(0,t.loader)(t),i=function(e,t){var r=t.drmSystems,i=null==r?void 0:r[e];if(i)return i.serverCertificateUrl}(e,t);return i?(this.log('Fetching server certificate for "'+e+'"'),new Promise((function(n,a){var s={type:z,responseType:"arraybuffer",url:i},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:function(e,t,r,i){n(e.data)},onError:function(t,r,n,o){a(new xl({type:B.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:c({url:s.url,data:void 0},t)},'"'+e+'" certificate request failed ('+i+"). Status: "+t.code+" ("+t.text+")"))},onTimeout:function(t,r,n){a(new xl({type:B.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:{url:s.url,data:void 0}},'"'+e+'" certificate request timed out ('+i+")"))},onAbort:function(e,t,r){a(new Error("aborted"))}};r.load(s,l,u)}))):(this.log('No Server Certificate in config.drmSystems["'+e+'"]'),Promise.resolve())},r.setMediaKeysServerCertificate=function(e,t,r){var i=this;return new Promise((function(n,a){e.setServerCertificate(r).then((function(a){i.log("setServerCertificate "+(a?"success":"not supported by CDM")+" ("+r.byteLength+') on "'+t+'"'),n(e)})).catch((function(e){a(new xl({type:B.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))},r.renewLicense=function(e,t,r){var i=this;return this.requestLicense(e,t,new Uint8Array(r)).then((function(r){return i.updateKeySession(e,t,new Uint8Array(r)).catch((function(e){throw new xl({type:B.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:e,fatal:!1},e.message)}))}))},r.unpackPlayReadyKeyMessage=function(e,t){var r=We(new Uint16Array(t.buffer));if(!r.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;var i=(new DOMParser).parseFromString(r,"application/xml"),n=i.querySelectorAll("HttpHeader");if(n.length>0)for(var a,s=0,o=n.length;s<o;s++){var l,u,d=null==(l=(a=n[s]).querySelector("name"))?void 0:l.textContent,h=null==(u=a.querySelector("value"))?void 0:u.textContent;d&&h&&e.setRequestHeader(d,h)}var f=i.querySelector("Challenge"),c=null==f?void 0:f.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return _i(atob(c))},r.setupLicenseXHR=function(e,t,r,i,n){var a=this,s=this.config.licenseXhrSetup;return s?Promise.resolve().then((function(){return a.throwIfDestroyed(),s.call(a.hls,e,t,c(c({},r),{},{decryptdata:i}),n)})).catch((function(o){if(!r.mediaKeysSession)throw o;return e.open("POST",t,!0),s.call(a.hls,e,t,c(c({},r),{},{decryptdata:i}),n)})).then((function(r){return e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:r||n}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))},r.requestLicense=function(e,t,r){var i=this;return new Promise((function(n,a){var s,o,l,u,d,h=(s=e.keySystem,o=i.config,l=o.drmSystems,u=o.widevineLicenseUrl,(d=null==l?void 0:l[s])?d.licenseUrl:s===Mi.WIDEVINE&&u?u:void 0);if(!h)return a(new Error('no license server URL configured for key-system "'+e.keySystem+'"'));var f=e.keyRequests[t.uri];if(!f)return a(new Error("License emitter removed"));i.log("Sending license request to URL: "+h);var g=i.config.keyLoadPolicy.default,v=new XMLHttpRequest;v.responseType="arraybuffer",v.onreadystatechange=function(){if(!i.hls||!e.mediaKeysSession)return a(new Error("invalid state"));if(4===v.readyState)if(200===v.status){f.requestErrors=[];var s=v.response;i.log("License received "+(s instanceof ArrayBuffer?s.byteLength:s));var o=i.config.licenseResponseCallback;if(o)try{s=o.call(i.hls,v,h,c(c({},e),{},{decryptdata:t}))}catch(e){i.error(e)}n(s)}else{var l=g.errorRetry,u=l?l.maxNumRetry:0;if(f.requestErrors.push({status:v.status,message:v.statusText}),f.requestErrors.length>u||v.status>=400&&v.status<500)a(new xl({type:B.KEY_SYSTEM_ERROR,details:U.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:v,response:{url:h,data:void 0,code:v.status,text:v.statusText}},"License Request XHR failed ("+h+"). Status: "+v.status+" ("+v.statusText+")"));else{var d=u-f.requestErrors.length;i.warn("Retrying license request, "+d+" attempts left"),i.requestLicense(e,t,r).then(n,a)}}},f.licenseXhr&&f.licenseXhr.readyState!==XMLHttpRequest.DONE&&f.licenseXhr.abort(),f.licenseXhr=v,i.setupLicenseXHR(v,h,e,t,r).then((function(t){var r=t.xhr,n=t.licenseChallenge;e.keySystem==Mi.PLAYREADY&&(n=i.unpackPlayReadyKeyMessage(r,n)),r.send(n)})).catch(a)}))},r.onDestroying=function(){this.unregisterListeners(),this._clear()},r.onMediaAttached=function(e,t){if(this.config.emeEnabled){var r=t.media;this.media=r,_n(r,"encrypted",this.onMediaEncrypted),_n(r,"waitingforkey",this.onWaitingForKey);var i=this.mediaResolved;i?i():this.mediaKeys=r.mediaKeys}},r.onMediaDetached=function(){var e=this.media;e&&(Cn(e,"encrypted",this.onMediaEncrypted),Cn(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)},r._clear=function(){var e,r=this;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};var i=this.mediaResolved;if(i&&i(),this.mediaKeys||this.mediaKeySessions.length){var n=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,qi.clearKeyUriToKeyIdMap();var s=a.length;t.CDMCleanupPromise=Promise.all(a.map((function(e){return r.removeSession(e)})).concat((null==n||null==(e=n.setMediaKeys(null))?void 0:e.catch((function(e){r.log("Could not clear media keys: "+e),r.hls&&r.hls.trigger(G.ERROR,{type:B.OTHER_ERROR,details:U.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error("Could not clear media keys: "+e)})})))||Promise.resolve())).catch((function(e){r.log("Could not close sessions and clear media keys: "+e),r.hls&&r.hls.trigger(G.ERROR,{type:B.OTHER_ERROR,details:U.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: "+e)})})).then((function(){s&&r.log("finished closing key sessions and clearing media keys")}))}},r.onManifestLoading=function(){this._clear(),this.keyFormatPromise=null},r.onManifestLoaded=function(e,t){var r=t.sessionKeys;if(r&&this.config.emeEnabled&&!this.keyFormatPromise){var i=r.reduce((function(e,t){return-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e}),[]);this.log("Selecting key-system from session-keys "+i.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(i),this.keyFormatPromise.catch((function(){}))}},r.removeSession=function(e){var t=this,r=e.mediaKeysSession;if(r){this.log('Remove licenses and keys and close session "'+r.sessionId+'"'),Object.keys(e.keyRequests).forEach((function(t){var i=e.keyRequests[t];i.onmessage&&r.removeEventListener("message",i.onmessage),i.onkeystatuseschange&&r.removeEventListener("keystatuseschange",i.onkeystatuseschange),i.reset(),e.keyRequests[t]=void 0})),e.mediaKeysSession=void 0;var i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);var n=e.keyStatusTimeouts;n&&Object.keys(n).forEach((function(e){return self.clearTimeout(n[e])}));var a=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some((function(e){return"persistent-license"===e}))))}(this.config.drmSystemOptions)?new Promise((function(e,t){self.setTimeout((function(){return t(new Error("MediaKeySession.remove() timeout"))}),8e3),r.remove().then(e).catch(t)})):Promise.resolve();return a.catch((function(e){t.log("Could not remove session: "+e),t.hls&&t.hls.trigger(G.ERROR,{type:B.OTHER_ERROR,details:U.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: "+e)})})).then((function(){return r.close()})).then((function(){return r.closed})).catch((function(e){t.log("Could not close session: "+e),t.hls&&t.hls.trigger(G.ERROR,{type:B.OTHER_ERROR,details:U.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: "+e)})}))}return Promise.resolve()},t}(pe);function Nl(e,t){var r=e.keyId,i=t.mediaKeysSession;if(r&&i){var n=t.mediaKeysSession.keyStatuses;if(n.size)return n.has(r)?n.get(r):t.keyStatuses[He(r)]}}function Bl(e,t){var r="output-restricted"===e,i=r?U.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:U.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new xl({type:B.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:t},r?"HDCP level output restricted":'key status changed to "'+e+'"')}Fl.CDMCleanupPromise=void 0;var Ul=function(){function e(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()}var t=e.prototype;return t.setStreamController=function(e){this.streamController=e},t.registerListeners=function(){this.hls.on(G.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(G.MEDIA_DETACHING,this.onMediaDetaching,this)},t.unregisterListeners=function(){this.hls.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(G.MEDIA_DETACHING,this.onMediaDetaching,this)},t.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},t.onMediaAttaching=function(e,t){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},t.onMediaDetaching=function(){this.media=null},t.checkFPS=function(e,t,r){var i=performance.now();if(t){if(this.lastTime){var n=i-this.lastTime,a=r-this.lastDroppedFrames,s=t-this.lastDecodedFrames,o=1e3*a/n,l=this.hls;if(l.trigger(G.FPS_DROP,{currentDropped:a,currentDecoded:s,totalDroppedFrames:r}),o>0&&a>l.config.fpsDroppedMonitoringThreshold*s){var u=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=u)&&(u-=1,l.trigger(G.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}},t.checkFPSInterval=function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)},e}(),Gl=function(e){function t(t,r){var i;return(i=e.call(this,"gap-controller",t.logger)||this).hls=void 0,i.fragmentTracker=void 0,i.media=null,i.mediaSource=void 0,i.nudgeRetry=0,i.skipRetry=0,i.stallReported=!1,i.stalled=null,i.moved=!1,i.seeking=!1,i.buffered={},i.lastCurrentTime=void 0,i.ended=0,i.waiting=0,i.onMediaPlaying=function(){i.ended=0,i.waiting=0},i.onMediaWaiting=function(){var e;null!=(e=i.media)&&e.seeking||(i.waiting=self.performance.now(),i.tick())},i.onMediaEnded=function(){var e;i.hls&&(i.ended=(null==(e=i.media)?void 0:e.currentTime)||1,i.hls.trigger(G.MEDIA_ENDED,{stalled:!1}))},i.hls=t,i.fragmentTracker=r,i.lastCurrentTime=i.getCurrentTime(),i.registerListeners(),i}d(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e&&(e.on(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.BUFFER_APPENDED,this.onBufferAppended,this))},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.BUFFER_APPENDED,this.onBufferAppended,this))},r.destroy=function(){e.prototype.destroy.call(this),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0},r.onMediaAttached=function(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;var r=this.media=t.media;_n(r,"playing",this.onMediaPlaying),_n(r,"waiting",this.onMediaWaiting),_n(r,"ended",this.onMediaEnded)},r.onMediaDetaching=function(e,t){this.clearInterval();var r=this.media;r&&(Cn(r,"playing",this.onMediaPlaying),Cn(r,"waiting",this.onMediaWaiting),Cn(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0},r.onBufferAppended=function(e,t){this.buffered=t.timeRanges},r.getCurrentTime=function(){var e,t=(null==(e=this.hls)?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,t):t},r.tick=function(){var e;if(null!=(e=this.media)&&e.readyState&&this.hasBuffered){var t=this.getCurrentTime();this.media.currentTime<t||(this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t)}},r.poll=function(e,t){var r,i,n=null==(r=this.hls)?void 0:r.config;if(n){var a=this.media;if(a){var s=a.seeking,o=this.seeking&&!s,l=!this.seeking&&s,u=a.paused&&!s||a.ended||0===a.playbackRate;if(this.seeking=s,e!==t)return t&&(this.ended=0),this.moved=!0,s||(this.skipRetry=this.nudgeRetry=0,n.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)o&&this.stallResolved(e);else{if(u)return this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(G.MEDIA_ENDED,{stalled:!1})));if(gi.getBuffered(a).length){var d=gi.bufferInfo(a,e,0),h=this.fragmentTracker;h&&this.hls&&Yl(d,e,h,this.hls);var f=d.nextStart||0;if(s&&h&&this.hls){var c=Kl(this.hls.inFlightFragments,e),g=d.len>2,v=!f||c||f-e>2&&!h.getPartialFragment(e);if(g||v)return;this.moved=!1}var m=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&h){if(!(d.len>0||f))return;var p=Math.max(f,d.start||0)-e,y=null!=m&&m.live?2*m.targetduration:2,E=Hl(e,h);if(p>0&&(p<=y||E))return void(a.paused||this._trySkipBufferHole(E))}var T=n.detectStallWithCurrentTimeMs,S=self.performance.now(),A=this.waiting,I=this.stalled;if(null===I){if(!(A>0&&S-A<T))return void(this.stalled=S);I=this.stalled=A}var L=S-I;if(!s&&(L>=T||A&&this.moved)&&this.hls){var R;if("ended"===(null==(R=this.mediaSource)?void 0:R.readyState)&&(null==m||!m.live)&&Math.abs(e-((null==m?void 0:m.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(G.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(d),!this.media||!this.hls)return;if(a.currentTime!==e){var b=e;return e=a.currentTime,this.moved=!0,void this.log("currentTime changed "+b+" > "+e)}}var k=gi.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(k,L,e)}else this.skipRetry=this.nudgeRetry=0}}}},r.stallResolved=function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var r=self.performance.now()-t;this.log("playback not stuck anymore @"+e+", after "+Math.round(r)+"ms"),this.stallReported=!1,this.waiting=0,this.hls.trigger(G.STALL_RESOLVED,{})}},r.nudgeOnVideoHole=function(e,t){var r,i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(r=this.buffered.audio)&&r.length&&i&&i.length>1&&e>i.end(0)){var n=gi.bufferedInfo(gi.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){var a=gi.timeRangesToArray(i),s=gi.bufferedInfo(a,t,0).bufferedIndex;if(s>-1&&s<a.length-1){var o=gi.bufferedInfo(a,e,0).bufferedIndex,l=a[s].end,u=a[s+1].start;if((-1===o||o>s)&&u-l<1&&e-l<2){var d=new Error("nudging playhead to flush pipeline after video hole. currentTime: "+e+" hole: "+l+" -> "+u+" buffered index: "+o);this.warn(d.message),this.media.currentTime+=1e-6;var h=Hl(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);var f=gi.bufferInfo(this.media,e,0);this.hls.trigger(G.ERROR,{type:B.MEDIA_ERROR,details:U.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:h,buffer:f.len,bufferInfo:f})}}}}},r._tryFixBufferStall=function(e,t,r){var i,n,a=this.fragmentTracker,s=this.media,o=null==(i=this.hls)?void 0:i.config;if(s&&a&&o){var l=null==(n=this.hls)?void 0:n.latestLevelDetails,u=Hl(r,a);if((u||null!=l&&l.live&&r<l.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;var d=e.buffered,h=this.adjacentTraversal(e,r);(d&&d.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-r<o.maxBufferHole||h))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}},r.adjacentTraversal=function(e,t){var r=this.fragmentTracker,i=e.nextStart;if(r&&i){var n=r.getFragAtPos(t,$.MAIN),a=r.getFragAtPos(i,$.MAIN);if(n&&a)return a.sn-n.sn<2}return!1},r._reportStall=function(e){var t=this.hls,r=this.media,i=this.stallReported,n=this.stalled;if(!i&&null!==n&&r&&t){this.stallReported=!0;var a=new Error("Playback stalling at @"+r.currentTime+" due to low buffer ("+cr(e)+")");this.warn(a.message),t.trigger(G.ERROR,{type:B.MEDIA_ERROR,details:U.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}},r._trySkipBufferHole=function(e){var t=this.fragmentTracker,r=this.media,i=this.hls,n=null==i?void 0:i.config;if(!r||!t||!n)return 0;var a=r.currentTime,s=gi.bufferInfo(r,a,0);Yl(s,a,t,i);var o=a<s.start?s.start:s.nextStart;if(o){var l=s.len<=n.maxBufferHole,u=s.len>0&&s.len<1&&r.readyState<3,d=o-a;if(d>0&&(l||u)){if(d>n.maxBufferHole){var h=!1;if(0===a){var f=t.getAppendedFrag(0,$.MAIN);f&&o<f.end&&(h=!0)}if(!h&&e){var c;if(null==(c=i.loadLevelObj)||!c.details)return 0;if(Kl(i.inFlightFragments,o))return 0;for(var g=!1,v=e.end;v<o;){var m=Hl(v,t),p=m?m.duration:0;if(!(p>0)){g=!0;break}v+=p}if(g)return 0}}var y=n.nudgeMaxRetry,E=n.skipBufferHolePadding,T=++this.skipRetry>y,S=Math.max(o,a)+E;if(T||(this.warn("skipping hole, adjusting currentTime from "+a+" to "+S),this.moved=!0,r.currentTime=S),null==e||!e.gap||T){var A=new Error(T?"Playhead still not moving after seeking over buffer hole from "+a+" to "+S+" after "+n.nudgeMaxRetry+" attempts.":"fragment loaded with buffer holes, seeking from "+a+" to "+S),I={type:B.MEDIA_ERROR,details:U.BUFFER_SEEK_OVER_HOLE,fatal:T,error:A,reason:A.message,buffer:s.len,bufferInfo:s};e&&("fragment"in e?I.part=e:I.frag=e),i.trigger(G.ERROR,I)}return S}}return 0},r._tryNudgeBuffer=function(e){var t=this.hls,r=this.media,i=this.nudgeRetry,n=null==t?void 0:t.config;if(!r||!n)return 0;var a=r.currentTime;if(this.nudgeRetry++,i<n.nudgeMaxRetry){var s=a+(i+1)*n.nudgeOffset,o=new Error("Nudging 'currentTime' from "+a+" to "+s);this.warn(o.message),r.currentTime=s,t.trigger(G.ERROR,{type:B.MEDIA_ERROR,details:U.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{var l=new Error("Playhead still not moving while enough data buffered @"+a+" after "+n.nudgeMaxRetry+" nudges");this.error(l.message),t.trigger(G.ERROR,{type:B.MEDIA_ERROR,details:U.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}},a(t,[{key:"hasBuffered",get:function(){return Object.keys(this.buffered).length>0}}])}(hi);function Kl(e,t){var r=Vl(e.main);if(r&&r.start<=t)return r;var i=Vl(e.audio);return i&&i.start<=t?i:null}function Vl(e){if(!e)return null;switch(e.state){case On.IDLE:case On.STOPPED:case On.ENDED:case On.ERROR:return null}return e.frag}function Hl(e,t){return t.getAppendedFrag(e,$.MAIN)||t.getPartialFragment(e)}function Yl(e,t,r,i){var n=i.latestLevelDetails,a=Hl(t,r);if(Fn(i.config)&&!e.nextStart&&n&&a&&i.interstitialsManager){var s="type"in a?a:a.fragment,o=_r(n,s.sn);(null==o?void 0:o.level)===s.level&&xn(o,i.interstitialsManager.playerQueue,t)&&(e.nextStart=o.start)}}function jl(e,t,r,i,n){void 0===i&&(i=""),void 0===n&&(n="disabled");var a=e.ownerDocument.createElement("track");return a.kind=t,a.label=r,i&&(a.srclang=i),a.src="data:,WEBVTT",a.track.mode=n,e.appendChild(a),a}function Wl(e){return e.forced&&(Ct.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(_t))?"forced":e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function ql(e,t){var r=e.mode;if("disabled"===r&&(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(r){Le.debug("[texttrack-utils]: "+r);try{var i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){Le.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: "+e)}}"disabled"===r&&(e.mode=r)}function Xl(e,t,r,i){var n=e.mode;if("disabled"===n&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var a=function(e,t,r){var i=[],n=function(e,t){if(t<=e[0].startTime)return 0;var r=e.length-1;if(t>e[r].endTime)return-1;for(var i,n=0,a=r;n<=a;)if(t<e[i=Math.floor((a+n)/2)].startTime)a=i-1;else{if(!(t>e[i].startTime&&n<r))return i;n=i+1}return e[n].startTime-t<t-e[a].startTime?n:a}(e,t);if(n>-1)for(var a=n,s=e.length;a<s;a++){var o=e[a];if(o.startTime>=t&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(e.cues,t,r),s=0;s<a.length;s++)i&&!i(a[s])||e.removeCue(a[s]);"disabled"===n&&(e.mode=n)}function zl(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Ql(e,t,r,i,n){var a=new e(t,r,"");try{a.value=i,n&&(a.type=n)}catch(s){a=new e(t,r,cr(n?c({type:n},i):i))}return a}var $l=function(){var e=zl();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}(),Zl=function(){function e(e){var t=this;this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=function(){t.hls&&t.hls.trigger(G.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}var t=e.prototype;return t.destroy=function(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null},t._registerListeners=function(){var e=this.hls;e&&(e.on(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(G.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(G.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))},t._unregisterListeners=function(){var e=this.hls;e&&(e.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(G.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(G.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))},t.onMediaAttaching=function(e,t){this.media=t.media},t.onMediaAttached=function(){var e,t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)},t.onMediaDetaching=function(e,t){this.media=null,t.transferMedia||(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})},t.onManifestLoading=function(){this.dateRangeCuesAppended={}},t.createTrack=function(e){return jl(e,"metadata","id3","","hidden")},t.onFragParsingMetadata=function(e,t){if(this.media&&this.hls){var r=this.hls.config,i=r.enableEmsgMetadataCues,n=r.enableID3MetadataCues;if(i||n){var a=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var s=zl();if(s)for(var o=0;o<a.length;o++){var l=a[o].type;if((l!==Wn.emsg||i)&&n){var u=Ue(a[o].data),d=a[o].pts,h=d+a[o].duration;h>$l&&(h=$l),h-d<=0&&(h=d+.25);for(var f=0;f<u.length;f++){var c=u[f];if(!Ge(c)){this.updateId3CueEnds(d,l);var g=Ql(s,d,h,c,l);g&&this.id3Track.track.addCue(g)}}}}}}},t.updateId3CueEnds=function(e,t){var r,i=null==(r=this.id3Track)?void 0:r.track.cues;if(i)for(var n=i.length;n--;){var a=i[n];a.type===t&&a.startTime<e&&a.endTime===$l&&(a.endTime=e)}},t.onBufferFlushing=function(e,t){var r=t.startOffset,i=t.endOffset,n=t.type,a=this.id3Track,s=this.hls;if(s){var o,l=s.config,u=l.enableEmsgMetadataCues,d=l.enableID3MetadataCues;a&&(u||d)&&(o="audio"===n?function(e){return e.type===Wn.audioId3&&d}:"video"===n?function(e){return e.type===Wn.emsg&&u}:function(e){return e.type===Wn.audioId3&&d||e.type===Wn.emsg&&u},Xl(a.track,r,i,o))}},t.onLevelUpdated=function(e,t){var r=t.details;this.updateDateRangeCues(r,!0)},t.onLevelPtsUpdated=function(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)},t.updateDateRangeCues=function(e,t){var r=this;if(this.hls&&this.media){var i=this.hls.config,n=i.assetPlayerId,a=i.timelineOffset,s=i.enableDateRangeMetadataCues,o=i.interstitialsController;if(s){var l=zl();if(n&&a&&!o){var u=e.fragmentStart,d=e.fragmentEnd,h=this.assetCue;h?(h.startTime=u,h.endTime=d):l&&(h=this.assetCue=Ql(l,u,d,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"))&&(h.id=n,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(h),h.addEventListener("enter",this.onEventCueEnter))}if(e.hasProgramDateTime){var f,c=this.id3Track,g=e.dateRanges,v=Object.keys(g),m=this.dateRangeCuesAppended;if(c&&t)if(null!=(f=c.track.cues)&&f.length)for(var p=Object.keys(m).filter((function(e){return-1===v.indexOf(e)})),y=function(){var e,t=p[E],i=null==(e=m[t])?void 0:e.cues;delete m[t],i&&Object.keys(i).forEach((function(e){var t=i[e];if(t){t.removeEventListener("enter",r.onEventCueEnter);try{c.track.removeCue(t)}catch(e){}}}))},E=p.length;E--;)y();else m=this.dateRangeCuesAppended={};var T=e.fragments[e.fragments.length-1];if(0!==v.length&&x(null==T?void 0:T.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var S=function(){var e=v[A],t=g[e],i=t.startTime,n=m[e],a=(null==n?void 0:n.cues)||{},s=(null==n?void 0:n.durationKnown)||!1,u=$l,d=t.duration;if(t.endDate&&null!==d)u=i+d,s=!0;else if(t.endOnNext&&!s){var h=v.reduce((function(e,r){if(r!==t.id){var i=g[r];if(i.class===t.class&&i.startDate>t.startDate&&(!e||t.startDate<e.startDate))return i}return e}),null);h&&(u=h.startTime,s=!0)}for(var f,c=Object.keys(t.attr),p=0;p<c.length;p++){var y=c[p];if("ID"!==(f=y)&&"CLASS"!==f&&"CUE"!==f&&"START-DATE"!==f&&"DURATION"!==f&&"END-DATE"!==f&&"END-ON-NEXT"!==f){var E=a[y];if(E)!s||null!=n&&n.durationKnown?Math.abs(E.startTime-i)>.01&&(E.startTime=i,E.endTime=u):E.endTime=u;else if(l){var T=t.attr[y];Ii(y)&&(T=Ye(T));var S=Ql(l,i,u,{key:y,data:T},Wn.dateRange);S&&(S.id=e,r.id3Track.track.addCue(S),a[y]=S,o&&("X-ASSET-LIST"!==y&&"X-ASSET-URL"!==y||S.addEventListener("enter",r.onEventCueEnter)))}}}m[e]={cues:a,dateRange:t,durationKnown:s}},A=0;A<v.length;A++)S()}}}}},e}();function Jl(){return self.SourceBuffer||self.WebKitSourceBuffer}function eu(){if(!Re())return!1;var e=Jl();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}var tu,ru,iu=0,nu=1,au=2,su=function(e){function t(t,r,i){var n;return(n=e.call(this,t,r,i,"stream-controller",$.MAIN)||this).audioCodecSwap=!1,n.level=-1,n._forceStartLoad=!1,n._hasEnoughToStart=!1,n.altAudio=iu,n.audioOnly=!1,n._couldBacktrack=!1,n._backtrackFragment=void 0,n.audioCodecSwitch=!1,n.videoBuffer=null,n.onMediaPlaying=function(){n.tick()},n.onMediaSeeked=function(){var e=n.media,t=e?e.currentTime:null;if(null!==t&&x(t)&&(n.log("Media seeked to "+t),n.getBufferedFrag(t))){var r=n.getFwdBufferInfoAtPos(e,t,$.MAIN,0);r&&0!==r.len?n.tick():n.log("Main buffer empty at "+t+' on "seeked" event: '+(r?r.len:r))}},n.registerListeners(),n}d(t,e);var r=t.prototype;return r.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(G.MANIFEST_PARSED,this.onManifestParsed,this),t.on(G.LEVEL_LOADING,this.onLevelLoading,this),t.on(G.LEVEL_LOADED,this.onLevelLoaded,this),t.on(G.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(G.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(G.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(G.BUFFER_CREATED,this.onBufferCreated,this),t.on(G.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(G.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(G.FRAG_BUFFERED,this.onFragBuffered,this)},r.unregisterListeners=function(){e.prototype.unregisterListeners.call(this);var t=this.hls;t.off(G.MANIFEST_PARSED,this.onManifestParsed,this),t.off(G.LEVEL_LOADED,this.onLevelLoaded,this),t.off(G.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(G.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(G.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(G.BUFFER_CREATED,this.onBufferCreated,this),t.off(G.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(G.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(G.FRAG_BUFFERED,this.onFragBuffered,this)},r.onHandlerDestroying=function(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this)},r.startLoad=function(e,t){if(this.levels){var r=this.lastCurrentTime,i=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var n=i.startLevel;-1===n&&(i.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=i.firstAutoLevel),i.nextLoadLevel=n,this.level=i.loadLevel,this._hasEnoughToStart=!!t}r>0&&-1===e&&!t&&this.initPTS.length&&(this.log("Override startPosition with lastCurrentTime @"+r),e=r),this.state=On.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=On.STOPPED},r.stopLoad=function(){this._forceStartLoad=!1,e.prototype.stopLoad.call(this)},r.doTick=function(){switch(this.state){case On.WAITING_LEVEL:var e=this.levels,t=this.level,r=null==e?void 0:e[t],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(i))break;this.state=On.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=On.IDLE;break}break;case On.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===On.IDLE&&this.doTickIdle(),this.onTickEnd()},r.onTickEnd=function(){var t;e.prototype.onTickEnd.call(this),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()},r.doTickIdle=function(){var e=this.hls,t=this.levelLastLoaded,r=this.levels,i=this.media;if(null!==t&&(i||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var n=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=r&&r[n]){var a=r[n],s=this.getMainFwdBufferInfo();if(null!==s){var o=this.getLevelDetails();if(o&&this._streamEnded(s,o)){var l={type:this.targetBufferType()};return this.hls.trigger(G.BUFFER_EOS,l),void(this.state=On.ENDED)}if(this.buffering){e.loadLevel!==n&&-1===e.manualLevel&&this.log("Adapting to level "+n+" from level "+this.level),this.level=e.nextLoadLevel=n;var u=a.details;if(!u||this.state===On.WAITING_LEVEL||this.waitForLive(a))return this.level=n,this.state=On.WAITING_LEVEL,void(this.startFragRequested=!1);var d=s.len,h=this.getMaxBufferLength(a.maxBitrate);if(!(d>=h)){this.backtrackFragment&&this.backtrackFragment.start>s.end&&(this.backtrackFragment=void 0);var f=this.backtrackFragment?this.backtrackFragment.start:s.end,c=this.getNextFragment(f,u);if(this.couldBacktrack&&!this.fragPrevious&&c&&ee(c)&&this.fragmentTracker.getState(c)!==Xr){var g,v=(null!=(g=this.backtrackFragment)?g:c).sn-u.startSN,m=u.fragments[v-1];m&&c.cc===m.cc&&(c=m,this.fragmentTracker.removeFragment(m))}else this.backtrackFragment&&s.len&&(this.backtrackFragment=void 0);if(c&&this.isLoopLoading(c,f)){if(!c.gap){var p=this.audioOnly&&!this.altAudio?Z.AUDIO:Z.VIDEO,y=(p===Z.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,p)}c=this.getNextFragmentLoopLoading(c,u,s,$.MAIN,h)}c&&(this.exceedsMaxBuffer(s,h,c)||this.loadFragment(c,a,f))}}}}}},r.loadFragment=function(t,r,i){var n=this.fragmentTracker.getState(t);n===jr||n===qr?this.bitrateTest?(this.log("Fragment "+t.sn+" of level "+t.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(t,r)):e.prototype.loadFragment.call(this,t,r,i):this.clearTrackerIfNeeded(t)},r.immediateLevelSwitch=function(){var t;this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==iu&&((null==(t=this.getLevelDetails())?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio")},r.getBufferOutput=function(){return this.mediaBuffer&&this.altAudio===au?this.mediaBuffer:this.media},r.checkFragmentChanged=function(){var e=this.fragPlaying;if(!this.checkFragPlaying())return!1;var t=this.fragPlaying;if(t){var r=t.level;this.hls.trigger(G.FRAG_CHANGED,{frag:t,previousFrag:e}),(null==e?void 0:e.level)!==r&&this.hls.trigger(G.LEVEL_SWITCHED,{level:r})}return!0},r.abortCurrentFrag=function(){this.backtrackFragment=void 0,e.prototype.abortCurrentFrag.call(this)},r.flushMainBuffer=function(t,r){e.prototype.flushMainBuffer.call(this,t,r,this.targetBufferType())},r.targetBufferType=function(){return this.altAudio!==au||this.audioOnly?null:"video"},r.onMediaAttached=function(t,r){e.prototype.onMediaAttached.call(this,t,r);var i=r.media;_n(i,"playing",this.onMediaPlaying),_n(i,"seeked",this.onMediaSeeked)},r.onMediaDetaching=function(t,r){var i=this.media;i&&(Cn(i,"playing",this.onMediaPlaying),Cn(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,e.prototype.onMediaDetaching.call(this,t,r),r.transferMedia||(this._hasEnoughToStart=!1)},r.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.log("Trigger BUFFER_RESET"),this.hls.trigger(G.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=iu,this.audioOnly=!1},r.onManifestParsed=function(e,t){for(var r,i,n=!1,a=!1,s=0;s<t.levels.length;s++){var o=t.levels[s].audioCodec;o&&(n=n||-1!==o.indexOf("mp4a.40.2"),a=a||-1!==o.indexOf("mp4a.40.5"))}this.audioCodecSwitch=n&&a&&!("function"==typeof(null==(i=Jl())||null==(r=i.prototype)?void 0:r.changeType)),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},r.onLevelLoading=function(e,t){if(this.levels&&this.state===On.IDLE){var r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=On.WAITING_LEVEL)}},r.onLevelLoaded=function(e,t){var r,i=this,n=this.levels,a=this.startFragRequested,s=t.level,o=t.details,l=o.totalduration;if(n){this.log("Level "+s+" loaded ["+o.startSN+","+o.endSN+"]"+(o.lastPartSn?"[part-"+o.lastPartSn+"-"+o.lastPartIndex+"]":"")+", cc ["+o.startCC+", "+o.endCC+"] duration:"+l);var u=t.levelInfo,d=this.fragCurrent;!d||this.state!==On.FRAG_LOADING&&this.state!==On.FRAG_LOADING_WAITING_RETRY||d.level!==t.level&&d.loader&&this.abortCurrentFrag();var h=0;if(o.live||null!=(r=u.details)&&r.live){var f;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;h=this.alignPlaylists(o,u.details,null==(f=this.levelLastLoaded)?void 0:f.details)}if(u.details=o,this.levelLastLoaded=u,a||this.setStartPosition(o,h),this.hls.trigger(G.LEVEL_UPDATED,{details:o,level:s}),this.state===On.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=On.IDLE}a&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((function(e,t){if(t>=o.startCC)return!0;delete i.initPTS[t]})),this.tick()}else this.warn("Levels were reset while loading level "+s)},r.synchronizeToLiveEdge=function(e){var t=this.config,r=this.media;if(r){var i=this.hls.liveSyncPosition,n=this.playhead,a=e.fragmentStart,s=e.edge,o=n>=a-t.maxFragLookUpTolerance&&n<=s;if(null!==i&&r.duration>i&&(n<i||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&r.readyState<4||n<s-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),r.readyState))if(this.warn("Playback: "+n+" is located too far from the end of live sliding playlist: "+s+", reset currentTime to : "+i),"buffered"===this.config.liveSyncMode){var u,d=gi.bufferInfo(r,i,0);if(null==(u=d.buffered)||!u.length)return void(r.currentTime=i);if(d.start<=n)return void(r.currentTime=i);var h=gi.bufferedInfo(d.buffered,n,0).nextStart;h&&(r.currentTime=h)}else r.currentTime=i}}},r._handleFragmentLoadProgress=function(e){var t,r=e.frag,i=e.part,n=e.payload,a=this.levels;if(a){var s=a[r.level];if(s){var o=s.details;if(!o)return this.warn("Dropping fragment "+r.sn+" of level "+r.level+" after level details were reset"),void this.fragmentTracker.removeFragment(r);var l=s.videoCodec,u=o.PTSKnown||!o.live,d=null==(t=r.initSegment)?void 0:t.data,h=this._getAudioCodec(s),f=this.transmuxer=this.transmuxer||new cs(this.hls,$.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),c=i?i.index:-1,g=-1!==c,v=li(r,i,this.iframesOnly),m=v.decryptRange,p=v.byteRange,y=new fi(r.level,r.sn,r.stats.chunkCount,p?p.end-p.start:n.byteLength,c,g,r.duration,this.iframesOnly,m),E=this.initPTS[r.cc];f.push(n,d,h,l,r,i,o.totalduration,u,y,E)}else this.warn("Level "+r.level+" not found on progress")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},r.onAudioTrackSwitching=function(e,t){var r=this,i=this.hls,n=this.altAudio!==iu;if(Sr(t.url,i))this.altAudio=nu;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n)return this.altAudio=iu,this.fragmentTracker.removeAllFragments(),i.once(G.BUFFER_FLUSHED,(function(){r.hls&&r.hls.trigger(G.AUDIO_TRACK_SWITCHED,t)})),void i.trigger(G.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(G.AUDIO_TRACK_SWITCHED,t)}},r.onAudioTrackSwitched=function(e,t){var r=Sr(t.url,this.hls);if(r){var i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r?au:iu,this.tick()},r.onBufferCreated=function(e,t){var r,i,n=t.tracks,a=!1;for(var s in n){var o=n[s];if("main"===o.id){if(i=s,r=o,"video"===s){var l=n[s];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&r?(this.log("Alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},r.onFragBuffered=function(e,t){var r=t.frag,i=t.part,n=r.type===$.MAIN;if(n){if(this.fragContextChanged(r))return this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===On.PARSED&&(this.state=On.IDLE));var a=!1;if(ee(r)&&(a=!!r.gap&&!r.tagList.some((function(e){return"GAP"===e[0]}))),this.fragBufferedComplete(r,i),a){var s;r.stats.retry++;var o=null==(s=this.levels)?void 0:s[r.level];o&&o.fragmentError++}}var l=this.media;l&&(!this._hasEnoughToStart&&gi.getBuffered(l).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())},r.onError=function(e,t){var r;if(t.fatal)this.state=On.ERROR;else switch(t.details){case U.FRAG_GAP:case U.FRAG_PARSING_ERROR:case U.FRAG_DECRYPT_ERROR:case U.FRAG_LOAD_ERROR:case U.FRAG_LOAD_TIMEOUT:case U.KEY_LOAD_ERROR:case U.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError($.MAIN,t);break;case U.LEVEL_LOAD_ERROR:case U.LEVEL_LOAD_TIMEOUT:case U.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==On.WAITING_LEVEL||(null==(r=t.context)?void 0:r.type)!==H||(this.state=On.IDLE);break;case U.BUFFER_APPEND_NO_PROGRESS:if("main"!==t.parent)return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn("Marking fragment "+t.frag.sn+" of level "+t.frag.level+" as a gap after "+t.appendsWithoutProgress+" appends without buffered range growth, to prevent loop loading"),this.fragmentTracker.addAsGap(t.frag));break;case U.BUFFER_ADD_CODEC_ERROR:case U.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case U.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case U.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}},r.onFragLoadEmergencyAborted=function(){this.state=On.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()},r.onBufferFlushed=function(e,t){var r=t.type;if(r!==Z.AUDIO||!this.altAudio){var i=(r===Z.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,r),this.tick())}},r.onLevelsUpdated=function(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels},r.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},r.seekToStartPos=function(){var e=this.media;if(e){var t=e.currentTime,r=this.startPosition;if(r>=0&&t<r){if(e.seeking)return void this.log("could not seek to "+r+", already seeking at "+t);var i=this.timelineOffset;i&&r&&(r+=i);var n=this.getLevelDetails(),a=gi.getBuffered(e),s=a.length?a.start(0):0,o=s-r,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==n?void 0:n.partTarget)||0)))&&(this.log("adjusting start position by "+o+" to match buffer start"),r+=o,this.startPosition=r),t<r&&(this.log("seek to target start position "+r+" from current time "+t+" buffer start "+s),e.currentTime=r)}}},r._getAudioCodec=function(e){var t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t},r._loadBitrateTestFrag=function(e,t){var r=this;e.bitrateTest=!0,this._doFragLoad(e,t).then((function(e){var i=r.hls,n=null==e?void 0:e.frag;if(n&&!r.fragContextChanged(n)){t.fragmentError=0,r.state=On.IDLE,r.startFragRequested=!1,r.bitrateTest=!1;var a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),i.trigger(G.FRAG_LOADED,e),n.bitrateTest=!1}})).catch((function(t){r.state!==On.STOPPED&&r.state!==On.ERROR&&(r.warn(t),r.resetFragmentLoading(e))}))},r._handleTransmuxComplete=function(e){var t=this.playlistType,r=this.hls,i=e.remuxResult,n=e.chunkMeta,a=this.getCurrentContext(n);if(a){var s=a.frag,o=a.part,l=a.level,u=i.video,d=i.text,h=i.id3,f=i.initSegment,c=l.details,g=this.altAudio?void 0:i.audio;if(this.fragContextChanged(s))this.fragmentTracker.removeFragment(s);else{if(this.state=On.PARSING,f){var v=f.tracks;if(v){var m=s.initSegment||s;if(this.unhandledEncryptionError(f,s))return;this._bufferInitSegment(l,v,m,n),r.trigger(G.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:t,tracks:v})}var p=f.initPTS,y=f.timescale,E=this.initPTS[s.cc];if(x(p)&&(!E||E.baseTime!==p||E.timescale!==y)){var T=f.trackId;this.initPTS[s.cc]={baseTime:p,timescale:y,trackId:T};var S=this.initPTS.slice(0);r.trigger(G.INIT_PTS_FOUND,{timestampOffsets:S,frag:s,id:t,initPTS:p,timescale:y,trackId:T})}}if(u&&c){g&&"audiovideo"===u.type&&this.logMuxedErr(s);var A=c.fragments[s.sn-1-c.startSN],I=s.sn===c.startSN,L=!A||s.cc>A.cc;if(!1!==i.independent){var R=u.startPTS,b=u.endPTS,k=u.startDTS,D=u.endDTS;if(o)o.elementaryStreams[u.type]={startPTS:R,endPTS:b,startDTS:k,endDTS:D};else if(u.firstKeyFrame&&u.independent&&1===n.id&&!L&&(this.couldBacktrack=!0),u.dropped&&u.independent){var P=this.getMainFwdBufferInfo(),_=(P?P.end:this.getLoadPosition())+this.config.maxBufferHole,C=u.firstKeyFramePTS?u.firstKeyFramePTS:R;if(!I&&_<C-this.config.maxBufferHole&&!L)return void this.backtrack(s);L&&(s.gap=!0),s.setElementaryStreamInfo(u.type,s.start,b,s.start,D,!0)}else I&&R-(c.appliedTimelineOffset||0)>2&&(s.gap=!0);s.setElementaryStreamInfo(u.type,R,b,k,D),this.backtrackFragment&&(this.backtrackFragment=s),this.bufferFragmentData(u,s,o,n,I||L)}else{if(!I&&!L)return void this.backtrack(s);s.gap=!0}}if(g){var w=g.startPTS,O=g.endPTS,M=g.startDTS,F=g.endDTS;o&&(o.elementaryStreams[Z.AUDIO]={startPTS:w,endPTS:O,startDTS:M,endDTS:F}),s.setElementaryStreamInfo(Z.AUDIO,w,O,M,F),this.bufferFragmentData(g,s,o,n)}if(c&&null!=h&&h.samples.length){var N={id:t,frag:s,details:c,samples:h.samples};r.trigger(G.FRAG_PARSING_METADATA,N)}if(c&&d){var B={id:t,frag:s,details:c,samples:d.samples};r.trigger(G.FRAG_PARSING_USERDATA,B)}}}else this.resetWhenMissingContext(n)},r.logMuxedErr=function(e){this.warn((ee(e)?"Media":"Init")+" segment with muxed audiovideo where only video expected: "+e.url)},r._bufferInitSegment=function(e,t,r,i){var n=this;if(this.state===On.PARSING){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));var a=t.audio,s=t.video,o=t.audiovideo;if(a){var l=e.audioCodec,u=jt(a.codec,l);if("mp4a"===u&&(u="mp4a.40.5"),this.audioCodecSwitch){u&&(u=-1!==u.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var d=a.metadata;d&&"channelCount"in d&&1!==(d.channelCount||1)&&!function(){if(void 0===Dt){var e=_t.match(/Firefox\/(\d+)/i);Dt=e?parseInt(e[1]):0}return Dt}()&&(u="mp4a.40.5")}u&&-1!==u.indexOf("mp4a.40.5")&&/Android/.test(_t)&&"audio/mpeg"!==a.container&&(u="mp4a.40.2",this.log("Android: force audio codec to "+u)),l&&l!==u&&this.log('Swapping manifest audio codec "'+l+'" for "'+u+'"'),a.levelCodec=u,a.id=$.MAIN,this.log("Init audio buffer, container:"+a.container+", codecs[selected/level/parsed]=["+(u||"")+"/"+(l||"")+"/"+a.codec+"]"),delete t.audiovideo}if(s){s.levelCodec=e.videoCodec,s.id=$.MAIN;var h=s.codec;if(4===(null==h?void 0:h.length))switch(h){case"hvc1":case"hev1":s.codec="hvc1.1.6.L120.90";break;case"av01":s.codec="av01.0.04M.08";break;case"avc1":s.codec="avc1.42e01e"}this.log("Init video buffer, container:"+s.container+", codecs[level/parsed]=["+(e.videoCodec||"")+"/"+h+"]"+(s.codec!==h?" parsed-corrected="+s.codec:"")+(s.supplemental?" supplemental="+s.supplemental:"")),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(r),this.log("Init audiovideo buffer, container:"+o.container+", codecs[level/parsed]=["+e.codecs+"/"+o.codec+"]"),delete t.video,delete t.audio);var f=Object.keys(t);if(f.length){if(this.hls.trigger(G.BUFFER_CODECS,t),!this.hls)return;f.forEach((function(e){var a=t[e].initSegment;null!=a&&a.byteLength&&n.hls.trigger(G.BUFFER_APPENDING,{type:e,data:a,frag:r,part:null,chunkMeta:i,parent:r.type})}))}this.tickImmediate()}},r.getMainFwdBufferInfo=function(){var e=this.getBufferOutput();return this.getFwdBufferInfo(e,$.MAIN)},r.backtrack=function(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=On.IDLE},a(t,[{key:"backtrackFragment",get:function(){return this._backtrackFragment},set:function(e){this._backtrackFragment=e}},{key:"couldBacktrack",get:function(){return this._couldBacktrack},set:function(e){this._couldBacktrack=e}},{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"maxBufferLength",get:function(){var e=this.levels,t=this.level,r=null==e?void 0:e[t];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"currentFrag",get:function(){var e;if(this.fragPlaying)return this.fragPlaying;var t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return x(t)?this.getAppendedFrag(t):null}},{key:"currentProgramDateTime",get:function(){var e,t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(x(t)){var r=this.getLevelDetails(),i=this.currentFrag||(r?br(null,r.fragments,t):null);if(i){var n=i.programDateTime;if(null!==n){var a=n+1e3*(t-i.start);return new Date(a)}}}return null}},{key:"currentLevel",get:function(){var e=this.currentFrag;return e?e.level:-1}},{key:"nextBufferedFrag",get:function(){var e=this.currentFrag;return e?this.followingBufferedFrag(e):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])}(Mn),ou=function(e){function t(){for(var t,r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];return(t=e.call.apply(e,[this].concat(i))||this).currentOp=void 0,t.nextOp=void 0,t.cached=[],t.cachedSize=0,t.cacheFragmentData=!0,t.initDetails=void 0,t.onBufferedToEnd=function(){var e=t.media;null!=e&&e.seeking&&(e.currentTime=e.currentTime)},t.onMediaSeeking=function(){},t}d(t,e);var r=t.prototype;return r.setInitPts=function(e){this.initPTS=e.slice()},r.loadMediaAt=function(e,t){if(this.hls){var r=t.seekOnAppend,i=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=i,this.startPosition=e,this.state){case On.STOPPED:case On.ENDED:case On.ERROR:this.state=On.IDLE}this.state===On.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[i,t]):this.nextOp=[i,t],this.hls.off(G.BUFFERED_TO_END,this.onBufferedToEnd);var n=this.media;r&&n&&this.seekTo(i)&&(this.currentOp=[i,t],this.nextOp=void 0,this.flushPipeline(i,!0))}},r.seekTo=function(e){var t=this.media;if(t){var r,i=null==(r=this.getLevelDetails())?void 0:r.edge,n=void 0!==i?i:t.duration;if(e>=n&&(e=n-.01),gi.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1},r.getBufferedAt=function(e){return this.fragmentTracker.getBufferedFrag(e,$.MAIN)},r.cacheSet=function(e,t){if(this.hls){e.data=t;var r=this.cached;r.push(e),this.cachedSize+=t.buffer.byteLength;for(var i=this.hls.config.iframeCacheLimit;this.cachedSize>i&&r.length>1;){var n=r.shift();if(!n.data){this.cached=r.filter((function(e){return!!e.data})),this.cachedSize=r.reduce((function(e,t){var r=t.data;return r?r.buffer.byteLength:0}),0);break}this.cachedSize-=n.data.byteLength,n.data=void 0}}},r.onHandlerDestroying=function(){this.cached.length=0,this.cachedSize=0,e.prototype.onHandlerDestroying.call(this)},r._handleFragmentLoadProgress=function(t){var r=t.frag,i=t.part,n=t.payload;this.cacheFragmentData&&!i&&null!=n&&n.byteLength&&!r.data&&ee(r)&&this.cacheSet(r,new Uint8Array(n.slice(0))),e.prototype._handleFragmentLoadProgress.call(this,t)},r.loadFragment=function(t,r,i){var n=this.fragmentTracker.getState(t);n!==jr&&n!==qr||!this.canReplayCached(t)?e.prototype.loadFragment.call(this,t,r,i):this.replayCachedFragment(t)},r.canReplayCached=function(e){var t;if(!this.cacheFragmentData||null==(t=e.data)||!t.byteLength)return!1;var r=e.decryptdata;return"identity"!==(null==r?void 0:r.keyFormat)||!!r.key},r.replayCachedFragment=function(e){var t=e.data.slice().buffer;this.log("Buffering cached "+e.type+" sn: "+e.sn+" of level "+e.level+" ("+t.byteLength+" bytes)"),this.fragCurrent=e,this.startFragRequested=!0;var r=e.stats=new K;r.loading.start=r.loading.first=r.loading.end=self.performance.now(),r.loaded=r.total=t.byteLength,r.chunkCount=1,this.state=On.FRAG_LOADING;var i={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(i),this.hls.trigger(G.FRAG_LOADED,i),this._handleFragmentLoadComplete(i)},r.fragBufferedComplete=function(t,r){e.prototype.fragBufferedComplete.call(this,t,r);var i=this.currentOp,n=this.nextOp;this.currentOp=this.nextOp=void 0,this.state=On.STOPPED,null!=i&&i[1].seekOnAppend&&(this.flushPipeline(i[0],!n),this.seekTo(i[0])||this.log("Could not seek to "+i[0]+" after fragment buffered (superseded or flushed) buffer: "+(this.media?wn(gi.getBuffered(this.media)):"none"))),n&&this.loadMediaAt.apply(this,n)},r.flushPipeline=function(e,t){if(t){var r=this.media;if(r){var i=gi.bufferInfo(r,e,0),n=i.len?i.nextStart:0;n&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,$.MAIN),this.flushMainBuffer(n,1/0))}this.hls.once(G.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(G.BUFFER_EOS,{type:"video"})},r.startLoad=function(){if(!this.startFragRequested){var e=this.hls;e.nextLoadLevel=-1===e.startLevel?0:e.firstAutoLevel}},r.seekToStartPos=function(){},r.setStartPosition=function(){},r.alignPlaylists=function(t,r,i){var n=this.initDetails;return this.initDetails=null,e.prototype.alignPlaylists.call(this,t,r,i||n||void 0)},r.getMainFwdBufferInfo=function(){var e=this.playhead,t=this.getBufferedAt(e);if(t){var r=t.duration;return{len:r,start:e,end:e+r,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}},r._streamEnded=function(){var e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,$.MAIN);return!(null==t||!t.endList)},a(t,[{key:"playhead",get:function(){return this.nextLoadPosition}}])}(su),lu=function(e){function t(){for(var t,r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];return(t=e.call.apply(e,[this].concat(i))||this)._img=void 0,t.queued=void 0,t.cacheFragmentData=!1,t}d(t,e);var r=t.prototype;return r.loadMediaAt=function(e){if(this.hls){var t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case On.STOPPED:case On.ENDED:case On.ERROR:this.state=On.IDLE}if(this.state===On.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===On.IDLE){var r=this.getBufferedAt(e);r&&(this.fragCurrent=r,this.updateImage(r,null))}}else{var i=this.fragCurrent;(!i||e>=i.start&&e<i.end)&&(this.queued=[t])}}},r.updateImage=function(e,t,r){var i=this,n=e.data;n||this.fragmentTracker.removeFragment(e);var a=this._img;if(a&&n){var s=self.performance.now();(t?t.stats:e.stats).buffering.start=e.stats.buffering.start=s,a.onload=function(){if(i.hls){var n=i.hls.levels[e.level];null!=n&&n.fragmentError&&(n.fragmentError=0,e.stats.retry=0);var a=self.performance.now(),s=t?t.stats:e.stats;s.buffering.end=e.stats.buffering.end=a,i.hls.trigger(G.FRAG_BUFFERED,{frag:e,part:t,stats:s,id:e.type,chunkMeta:r})}},a.onerror=function(){i.handleError("Image decode error",e,t,r)};var o=a.src;o&&self.URL.revokeObjectURL(o);var l=new Blob([n],{type:"image/jpeg"});a.src=self.URL.createObjectURL(l)}else this.state=On.STOPPED,this.processQueued()},r.processQueued=function(){var e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)},r.handleError=function(e,t,r,i){if(this.hls){var n=new Error(e);this.hls.trigger(G.ERROR,{type:B.MEDIA_ERROR,details:U.FRAG_PARSING_ERROR,chunkMeta:i,frag:t,part:r,fatal:!1,error:n,err:n})}},r._bufferInitSegment=function(){},r.bufferFragmentData=function(t,r,i,n){e.prototype.bufferFragmentData.call(this,t,r,i,n,!0);var a=st(new Uint8Array(t.data1),["mdat"]);if(0!==a.length){var s=r;this.cacheSet(s,a[0]),this.updateImage(s,i,n)}else this.handleError("Could not find I-Frame mdat",r,i,n)},r.fragBufferedComplete=function(t,r){this.fragmentTracker.fragBuffered(t,!0),e.prototype.fragBufferedComplete.call(this,t,r),this.processQueued()},r.checkFragPlaying=function(){var e,t=null==(e=this.fragPrevious)?void 0:e.start;if(void 0!==t){var r=this.getAppendedFrag(t);if(r&&!te(r,this.fragPlaying))return this.fragPlaying=r,!0}return!1},r.getMainFwdBufferInfo=function(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}},a(t,[{key:"image",get:function(){return this._img},set:function(e){var t,r=null==(t=this._img)?void 0:t.src;r&&self.URL.revokeObjectURL(r),this._img=e}}])}(ou),uu="Image I-Frame player does not accept HTMLMediaElements",du={seekOnAppend:!0},hu=function(e){function t(t,r){var i;return(i=e.call(this,"iframes",t.logger)||this).hls=void 0,i.stats=void 0,i.variableList=null,i.initPTS=[],i.iframeInstances=void 0,i.instanceCounter=0,tu||(tu=function(e){function t(t,r,i,n){var a;return t.streamController||(t.streamController=ou),(a=e.call(this,t)||this)._url=r,a.streamController.setInitPts(i),a.streamController.initDetails=n,a}d(t,e);var r=t.prototype;return r.loadSource=function(){},r.loadMediaAt=function(e,t){if(void 0===t&&(t=du),!(e<0)){var r=c(c({},du),t);this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e,r)}},t}(r)),ru||(ru=function(e){return function(e){function t(t,r,i,n){return t.cmcdController=void 0,t.emeController=void 0,t.streamController||(t.streamController=lu),t.capLevelController=void 0,t.bufferController=void 0,e.call(this,t,r,i,n)||this}d(t,e);var r=t.prototype;return r.attachImage=function(e){this.streamController.image=e},r.detachImage=function(){this.streamController.image=void 0},r.loadSource=function(){},r.attachMedia=function(){throw new Error(uu)},r.detachMedia=function(){},r.recoverMediaError=function(){},r.transferMedia=function(){return null},r.loadMediaAt=function(e){if(e<0)return null;this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e)},t}(e)}(tu)),i.hls=t,i.iframeInstances=[],i.registerListeners(),i}d(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e&&(e.on(G.MANIFEST_LOADING,this.clearAsset,this),e.on(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(G.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(G.FRAG_BUFFERED,this.onFragBuffered,this),e.on(G.DESTROYING,this.onDestroying,this))},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(G.MANIFEST_LOADING,this.clearAsset,this),e.off(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(G.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(G.FRAG_BUFFERED,this.onFragBuffered,this),e.off(G.DESTROYING,this.onDestroying,this))},r.clearAsset=function(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach((function(e){return e.destroy()})),this.iframeInstances.length=0},r.onDestroying=function(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0},r.onManifestLoaded=function(e,t){this.stats=t.stats,this.variableList=t.variableList},r.onLevelsUpdated=function(e,t){var r,i=t.levels,n=null==(r=this.hls)?void 0:r.pathwayPriority;i.length&&n&&this.iframeInstances.forEach((function(e){e.pathwayPriority=n}))},r.onInitPtsFound=function(e,t){var r=t.id,i=t.timestampOffsets;r===$.MAIN&&(this.initPTS=i)},r.onFragBuffered=function(e,t){var r,i=this,n=this.hls;n&&n.hasEnoughToStart&&((null==(r=n.mainForwardBufferInfo)?void 0:r.len)||0)>10&&this.iframeInstances.forEach((function(e){var t;e.loadingEnabled||e.startLoad((null==(t=i.hls)||null==(t=t.media)?void 0:t.currentTime)||0)}))},r.createIFramePlayer=function(e){var t;return this.createInstance(tu,null==(t=this.hls)?void 0:t.iframeVariants,e)},r.createImageIFramePlayer=function(e){var t,r=null==(t=this.hls)?void 0:t.iframeVariants.filter((function(e){return e.imageCodec}));return this.createInstance(ru,r,e,"image-")},r.createInstance=function(e,t,r,i){var n=this.hls;if(!n)return null;var a=n.url,s=n.userConfig,o=n.latestLevelDetails,l=n.loadLevelObj,u=n.loadLevel,d=n.bandwidthEstimate,h=n.sessionId,f=this.stats,g=this.variableList;if(null==t||!t.length||!f||!a)return null;var v=(i||"")+"iframe-player-"+this.instanceCounter++,m=n.levels,p=l||m[u],y=Ir(p,s.videoPreference),E=(null==p?void 0:p.pathwayId)||".",T=new e(c(c({},s),{},{loggerId:v,primarySessionId:h,videoPreference:y,abrEwmaDefaultEstimate:d,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},r),a,this.initPTS,o);return this.iframeInstances=this.iframeInstances.filter((function(e){return!e.url})),this.iframeInstances.push(T),T.trigger(G.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:E},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:f,networkDetails:null,url:a,variableList:g}),T},t}(pe);function fu(e){for(var t=5381,r=e.length;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()}var cu=.025,gu=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function vu(e,t,r){return e.identifier+"-"+(r+1)+"-"+fu(t)}var mu=function(){function e(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)}var t=e.prototype;return t.setDateRange=function(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)},t.reset=function(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)},t.isAssetPastPlayoutLimit=function(e){var t;if(e>0&&e>=this.assetList.length)return!0;var r=this.playoutLimit;return!(e<=0||isNaN(r))&&(0===r||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>r)},t.findAssetIndex=function(e){return this.assetList.indexOf(e)},t.toString=function(){return'["'+(e=this).identifier+'" '+(e.cue.pre?"<pre>":e.cue.post?"<post>":"")+e.timelineStart.toFixed(2)+"-"+e.resumeTime.toFixed(2)+"]";var e},a(e,[{key:"identifier",get:function(){return this.dateRange.id}},{key:"startDate",get:function(){return this.dateRange.startDate}},{key:"startTime",get:function(){var e=this.dateRange.startTime;if(this.snapOptions.out){var t=this.dateRange.tagAnchor;if(t)return yu(t,e)?pu(e,t):e}return e}},{key:"startOffset",get:function(){return this.cue.pre?0:this.startTime}},{key:"startIsAligned",get:function(){if(0===this.startTime||this.snapOptions.out)return!0;var e=this.dateRange.tagAnchor;if(e){var t=this.dateRange.startTime;return t-pu(t,e)<.1}return!1}},{key:"resumptionOffset",get:function(){var e=this.resumeOffset,t=x(e)?e:this.duration;return this.cumulativeDuration+t}},{key:"resumeTime",get:function(){var e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){var t=this.resumeAnchor;if(t)return yu(t,e)?pu(e,t):e}return e}},{key:"appendInPlace",get:function(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<cu))},set:function(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}},{key:"timelineStart",get:function(){return null!==this._timelineStart?this._timelineStart:this.startTime},set:function(e){this._timelineStart=e}},{key:"duration",get:function(){var e,t=this.playoutLimit;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e},set:function(e){this._duration=e}},{key:"cue",get:function(){return this.dateRange.cue}},{key:"timelineOccupancy",get:function(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?gu.Range:gu.Point}},{key:"supplementsPrimary",get:function(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}},{key:"contentMayVary",get:function(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}},{key:"assetUrl",get:function(){return this.dateRange.attr["X-ASSET-URI"]}},{key:"assetListUrl",get:function(){return this.dateRange.attr["X-ASSET-LIST"]}},{key:"baseUrl",get:function(){return this.base.url}},{key:"assetListLoaded",get:function(){return this.assetList.length>0||null!==this.assetListResponse}}])}();function pu(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<cu)?t.start:t.start+t.duration}function yu(e,t){return t>e.start-cu&&t<e.start+e.duration+cu}function Eu(e,t,r){var i=new self.URL(e,r);return"data:"!==i.protocol&&rr(i,"_HLS_primary_id",t),i}function Tu(e,t){for(;null!=(r=e.assetList[++t])&&r.error;)var r;return t}function Su(e){var t=e.timelineStart,r=e.duration||0;return'["'+e.identifier+'" '+t.toFixed(2)+"-"+(t+r).toFixed(2)+"]"}var Au=function(){function e(e,t,r,i){var n=this;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=function(){n.reachedPlayout(n.currentTime)&&n.hls&&n.hls.trigger(G.PLAYOUT_LIMIT_REACHED,{})};var a=this.hls=new e(t);this.interstitial=r,this.assetItem=i;var s=function(){n.hasDetails=!0};a.once(G.LEVEL_LOADED,s),a.once(G.AUDIO_TRACK_LOADED,s),a.once(G.SUBTITLE_TRACK_LOADED,s),a.on(G.MEDIA_ATTACHING,(function(e,t){var r=t.media;n.removeMediaListeners(),n.mediaAttached=r,n.interstitial.playoutLimit&&(r.addEventListener("timeupdate",n.checkPlayout),n.appendInPlace&&a.on(G.BUFFER_APPENDED,(function(){var e=n.bufferedEnd;n.reachedPlayout(e)&&(n._bufferedEosTime=e,a.trigger(G.BUFFERED_TO_END,void 0))})))}))}var t=e.prototype;return t.loadSource=function(){var e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{var t=this.assetItem.uri;try{t=Eu(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}},t.bufferedInPlaceToEnd=function(e,t){var r;if(!this.appendInPlace)return!1;if(null!=(r=this.hls)&&r.bufferedToEnd)return!0;if(!e)return!1;var i=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset+(t||0),a=gi.bufferInfo(e,n,.02);return this.getAssetTime(a.end)>=i-.02},t.reachedPlayout=function(e){var t=this.interstitial.playoutLimit;return this.startOffset+e>=t},t.getAssetTime=function(e){var t=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,e-t),r)},t.removeMediaListeners=function(){var e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))},t.bufferSnapShot=function(){var e;this.mediaAttached&&null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)},t.destroy=function(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null},t.attachMedia=function(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)},t.detachMedia=function(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()},t.resumeBuffering=function(){var e;null==(e=this.hls)||e.resumeBuffering()},t.pauseBuffering=function(){var e;null==(e=this.hls)||e.pauseBuffering()},t.transferMedia=function(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null},t.resetDetails=function(){var e=this.hls;if(e&&this.hasDetails){e.stopLoad();var t=function(e){return delete e.details};e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}},t.on=function(e,t,r){var i;null==(i=this.hls)||i.on(e,t)},t.once=function(e,t,r){var i;null==(i=this.hls)||i.once(e,t)},t.off=function(e,t,r){var i;null==(i=this.hls)||i.off(e,t)},t.toString=function(){var e;return"HlsAssetPlayer: "+Su(this.assetItem)+" "+(null==(e=this.hls)?void 0:e.sessionId)+" "+(this.appendInPlace?"append-in-place":"")},a(e,[{key:"appendInPlace",get:function(){return this.interstitial.appendInPlace}},{key:"destroyed",get:function(){var e;return!(null!=(e=this.hls)&&e.userConfig)}},{key:"assetId",get:function(){return this.assetItem.identifier}},{key:"interstitialId",get:function(){return this.assetItem.parentIdentifier}},{key:"media",get:function(){var e;return(null==(e=this.hls)?void 0:e.media)||null}},{key:"bufferedEnd",get:function(){var e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;var t=gi.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}},{key:"currentTime",get:function(){var e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}},{key:"duration",get:function(){var e=this.assetItem.duration;if(!e)return 0;var t=this.interstitial.playoutLimit;if(t){var r=t-this.startOffset;if(r>0&&r<e)return r}return e}},{key:"remaining",get:function(){var e=this.duration;return e?Math.max(0,e-this.currentTime):0}},{key:"startOffset",get:function(){return this.assetItem.startOffset}},{key:"timelineOffset",get:function(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0},set:function(e){var t=this.timelineOffset;if(e!==t){var r=e-t;if(Math.abs(r)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}}])}(),Iu=.033,Lu=function(e){function t(t,r){var i;return(i=e.call(this,"interstitials-sched",r)||this).onScheduleUpdate=void 0,i.eventMap={},i.events=null,i.items=null,i.durations={primary:0,playout:0,integrated:0},i.onScheduleUpdate=t,i}d(t,e);var r=t.prototype;return r.destroy=function(){this.reset(),this.onScheduleUpdate=null},r.reset=function(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((function(e){return e.reset()})),this.events=this.items=null},r.resetErrorsInRange=function(e,t){return this.events?this.events.reduce((function(r,i){return e<=i.startOffset&&t>i.startOffset?(delete i.error,r+1):r}),0):0},r.getEvent=function(e){return e&&this.eventMap[e]||null},r.hasEvent=function(e){return e in this.eventMap},r.findItemIndex=function(e,t){if(e.event)return this.findEventIndex(e.event.identifier);var r=-1;e.nextEvent?r=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(r=this.findEventIndex(e.previousEvent.identifier)+1);var i=this.items;if(i)for(i[r]||(void 0===t&&(t=e.start),r=this.findItemIndexAtTime(t));r>=0&&null!=(n=i[r])&&n.event;){var n;r--}return r},r.findItemIndexAtTime=function(e,t){var r=this.items;if(r)for(var i=0;i<r.length;i++){var n=r[i];t&&"primary"!==t&&(n=n[t]);var a=n.start,s=r[i].event,o=null!=s&&s.cue.pre?s.duration:n.end;if(e===a||e>a&&e<o)return i}return-1},r.findJumpRestrictedIndex=function(e,t){var r=this.items;if(r)for(var i=e;i<=t&&r[i];i++){var n=r[i].event;if(null!=n&&n.restrictions.jump&&!n.appendInPlace)return i}return-1},r.findEventIndex=function(e){var t=this.items;if(t)for(var r=t.length;r--;){var i;if((null==(i=t[r].event)?void 0:i.identifier)===e)return r}return-1},r.findAssetIndex=function(e,t){var r=e.assetList,i=r.length;if(i>1)for(var n=0;n<i;n++){var a=r[n];if(!a.error){var s=a.timelineStart;if(t===s||t>s&&(t<s+(a.duration||0)||n===i-1))return n}}return 0},r.parseInterstitialDateRanges=function(e,t,r){var i=this;void 0===r&&(r=0);var n=e.main.details,a=n.dateRanges,s=this.events,o=this.parseDateRanges(a,{url:n.url},t),l=Object.keys(a),u=s?s.filter((function(e){return-1===l.indexOf(e.identifier)})):[];o.length&&o.sort((function(e,t){var r=e.cue.pre,i=e.cue.post,n=t.cue.pre,a=t.cue.post;if(r&&!n)return-1;if(n&&!r)return 1;if(i&&!a)return 1;if(a&&!i)return-1;if(!(r||n||i||a)){var s=e.startTime,o=t.startTime;if(s!==o)return s-o}return e.dateRange.tagOrder-t.dateRange.tagOrder})),this.events=o,u.forEach((function(e){i.removeEvent(e)})),this.updateSchedule(e,u,r)},r.updateSchedule=function(e,t,r,i){void 0===t&&(t=[]),void 0===r&&(r=0),void 0===i&&(i=!1);var n=this.events||[];if(n.length||t.length||this.length<2){var a=this.items,s=this.parseSchedule(n,e,r);(i||t.length||(null==a?void 0:a.length)!==s.length||s.some((function(e,t){return Math.abs(e.playout.start-a[t].playout.start)>.005||Math.abs(e.playout.end-a[t].playout.end)>.005})))&&(this.items=s,this.onScheduleUpdate(t,a))}},r.parseDateRanges=function(e,t,r){for(var i=[],n=Object.keys(e),a=0;a<n.length;a++){var s=n[a],o=e[s];if(o.isInterstitial){var l=this.eventMap[s];l?l.setDateRange(o):(l=new mu(o,t),this.eventMap[s]=l,!1===r&&(l.appendInPlace=r)),i.push(l)}}return i},r.parseSchedule=function(e,t,r){void 0===r&&(r=0);var i=[],n=t.main.details,a=n.live?1/0:n.edge,s=0;if((e=e.filter((function(e){return!(e.error||e.cue.once&&e.hasPlayed)}))).length){this.resolveOffsets(e,t);var o=0,l=0;if(e.forEach((function(t,u){var d=t.cue.pre,h=t.cue.post,f=e[u-1]||null,c=t.appendInPlace,g=h?a:t.startOffset,v=t.duration,m=t.timelineOccupancy===gu.Range?v:0,p=d&&n.live?r+(t.resumeOffset||0):0,y=p||t.resumptionOffset,E=(null==f?void 0:f.startTime)===g,T=g+t.cumulativeDuration,S=c?T+v:g+y;if(d||!h&&g<=0){var A=l;l+=m,t.timelineStart=T;var I=s;s+=v,i.push({event:t,start:T,end:S,playout:{start:I,end:s},integrated:{start:A,end:l}})}else{if(!(g<=a))return;if(!E){var L=g-o;if(L>Iu){var R=o,b=l;l+=L;var k=s;s+=L;var D={previousEvent:e[u-1]||null,nextEvent:t,start:R,end:R+L,playout:{start:k,end:s},integrated:{start:b,end:l}};i.push(D)}else L>0&&f&&(f.cumulativeDuration+=L,i[i.length-1].end=g)}h&&(S=T),t.timelineStart=T;var P=l;l+=m;var _=s;s+=v,i.push({event:t,start:T,end:S,playout:{start:_,end:s},integrated:{start:P,end:l}})}var C=p||t.resumeTime;o=h||C>a?a:!d&&S&&t.appendInPlaceStarted&&C-S>Iu?S:C})),o<a){var u,d=o,h=l,f=a-o;l+=f;var c=s;s+=f,i.push({previousEvent:(null==(u=i[i.length-1])?void 0:u.event)||null,nextEvent:null,start:o,end:d+f,playout:{start:c,end:s},integrated:{start:h,end:l}})}this.setDurations(a,s,l)}else i.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a);return i},r.setDurations=function(e,t,r){this.durations={primary:e,playout:t,integrated:r}},r.resolveOffsets=function(e,t){var r=this,i=t.main.details,n=i.live?1/0:i.edge,a=0,s=-1;e.forEach((function(o,l){var u=o.cue.pre,d=o.cue.post,h=u?0:d?n:o.startTime;r.updateAssetDurations(o),s===h?o.cumulativeDuration=a:(a=0,s=h),!d&&o.snapOptions.in&&(o.resumeAnchor=br(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(r.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<Iu&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&r.warn("Could not change append strategy for abutting event "+o));var f=x(o.resumeOffset)?o.resumeOffset:o.duration;a+=f}))},r.primaryCanResumeInPlaceAt=function(e,t){var r=this,i=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(i-n)>cu?(this.log('"'+e.identifier+'" resumption '+i+" not aligned with estimated timeline end "+n),!1):!Object.keys(t).some((function(n){var a=t[n].details,s=a.edge;if(i>=s)return r.log('"'+e.identifier+'" resumption '+i+" past "+n+" playlist end "+s),!1;var o=br(null,a.fragments,i);if(!o)return r.log('"'+e.identifier+'" resumption '+i+" does not align with any fragments in "+n+" playlist ("+a.fragStart+"-"+a.fragmentEnd+")"),!0;var l="audio"===n?.175:0;return!(Math.abs(o.start-i)<cu+l||Math.abs(o.end-i)<cu+l||(r.log('"'+e.identifier+'" resumption '+i+" not aligned with "+n+" fragment bounds ("+o.start+"-"+o.end+" sn: "+o.sn+" cc: "+o.cc+")"),0))}))},r.updateAssetDurations=function(e){if(e.assetListLoaded){for(var t=e.timelineStart,r=0,i=!1,n=!1,a=0;a<e.assetList.length;a++){var s=e.assetList[a],o=t+r;s.startOffset=r,s.timelineStart=o,i||(i=null===s.duration),n||(n=!!s.error),r+=s.error?0:s.duration||0}e.duration=i&&!n?Math.max(r,e.duration):r}},r.removeEvent=function(e){e.reset(),delete this.eventMap[e.identifier]},a(t,[{key:"duration",get:function(){var e=this.items;return e?e[e.length-1].end:0}},{key:"length",get:function(){return this.items?this.items.length:0}},{key:"assetIdAtEnd",get:function(){var e,t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){var r=t.assetList,i=r[r.length-1];if(i)return i.identifier}return null}}])}(pe);function Ru(e){return"["+(e.event?'"'+e.event.identifier+'"':"primary")+": "+e.start.toFixed(2)+"-"+e.end.toFixed(2)+"]"}var bu=function(){function e(e){this.hls=void 0,this.hls=e}var t=e.prototype;return t.destroy=function(){this.hls=null},t.loadAssetList=function(e,t){var r,i=this,n=e.assetListUrl;try{r=Eu(n,this.hls.sessionId,e.baseUrl)}catch(t){var a=this.assignAssetListError(e,U.ASSET_LIST_LOAD_ERROR,t,n);return void this.hls.trigger(G.ERROR,a)}t&&"data:"!==r.protocol&&rr(r,"_HLS_start_offset",""+t);var s=this.hls.config,o=new(0,s.loader)(s),l={type:Q,responseType:"json",url:r.href},u=s.interstitialAssetListLoadPolicy.default,d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:function(t,r,n,a){var s=t.data,o=null==s?void 0:s.ASSETS;if(Array.isArray(o))e.assetListResponse=s,i.hls.trigger(G.ASSET_LIST_LOADED,{event:e,assetListResponse:s,networkDetails:a});else{var l=i.assignAssetListError(e,U.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),n.url,r,a);i.hls.trigger(G.ERROR,l)}},onError:function(t,r,n,a){var s=i.assignAssetListError(e,U.ASSET_LIST_LOAD_ERROR,new Error("Error loading X-ASSET-LIST: HTTP status "+t.code+" "+t.text+" ("+r.url+")"),r.url,a,n);i.hls.trigger(G.ERROR,s)},onTimeout:function(t,r,n){var a=i.assignAssetListError(e,U.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST ("+r.url+")"),r.url,t,n);i.hls.trigger(G.ERROR,a)}};return o.load(l,d,h),this.hls.trigger(G.ASSET_LIST_LOADING,{event:e}),o},t.assignAssetListError=function(e,t,r,i,n,a){return e.error=r,{type:B.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:r,networkDetails:a,stats:n}},e}();function ku(e){var t;null==e||null==(t=e.play())||t.catch((function(){}))}function Du(e,t){return"["+e+"] Advancing timeline position to "+t}var Pu=function(e){function t(t,r){var i;return(i=e.call(this,"interstitials",t.logger)||this).HlsPlayerClass=void 0,i.hls=void 0,i.assetListLoader=void 0,i.mediaSelection=null,i.altSelection=null,i.media=null,i.detachedData=null,i.requiredTracks=null,i.manager=null,i.playerQueue=[],i.bufferedPos=-1,i.timelinePos=-1,i.schedule=void 0,i.playingItem=null,i.bufferingItem=null,i.waitingItem=null,i.endedItem=null,i.playingAsset=null,i.endedAsset=null,i.bufferingAsset=null,i.bufferPastEdge=!1,i.shouldPlay=!1,i.onPlay=function(){i.shouldPlay=!0},i.onPause=function(){i.shouldPlay=!1},i.onSeeking=function(){var e=i.currentTime;if(void 0!==e&&!i.playbackDisabled&&i.schedule){var t=e-i.timelinePos;if(!(Math.abs(t)<1/7056e5)){var r=t<=-.01;-1!==i.timelinePos||i.effectivePlayingItem||i.checkStart(),i.timelinePos=e,i.bufferedPos=e;var n=i.playingItem;if(n)if(r&&i.schedule.resetErrorsInRange(e,e-t)&&i.updateSchedule(!0),i.checkBuffer(),r&&e<n.start||e>=n.end){var a,s=i.findItemIndex(n),o=i.schedule.findItemIndexAtTime(e);if(-1===o&&(o=s+(r?-1:1),i.log("seeked "+(r?"back ":"")+"to position not covered by schedule "+e+" (resolving from "+s+" to "+o+")")),!i.isInterstitial(n)&&null!=(a=i.media)&&a.paused&&(i.shouldPlay=!1),!r&&o>s){var l=i.schedule.findJumpRestrictedIndex(s+1,o);if(l>s)return void i.setSchedulePosition(l)}i.setSchedulePosition(o)}else{var u=i.playingAsset;if(u){var d,h=u.timelineStart,f=u.duration||0;(r&&e<h||e>=h+f)&&(null!=(d=n.event)&&d.appendInPlace&&(i.clearAssetPlayers(n.event,n),i.flushFrontBuffer(e)),i.setScheduleToAssetAtTime(e,u))}else if(i.playingLastItem&&i.isInterstitial(n)){var c=n.event.assetList[0];c&&(i.endedItem=i.playingItem,i.playingItem=null,i.setScheduleToAssetAtTime(e,c))}}else i.checkBuffer()}}},i.onTimeupdate=function(){var e=i.currentTime;if(void 0!==e&&!i.playbackDisabled&&(-1!==i.timelinePos||i.effectivePlayingItem||i.checkStart(),e>i.timelinePos)){i.timelinePos=e,e>i.bufferedPos&&i.checkBuffer();var t=i.playingItem;if(t&&!i.playingLastItem){if(e>=t.end){i.timelinePos=t.end;var r=i.findItemIndex(t);i.setSchedulePosition(r+1)}var n=i.playingAsset;n&&e>=n.timelineStart+(n.duration||0)&&i.setScheduleToAssetAtTime(e,n)}}},i.onScheduleUpdate=function(e,t){var r=i.schedule;if(r){var n=i.playingItem,a=r.events||[],s=r.items||[],o=r.durations,l=e.map((function(e){return e.identifier})),u=!(!a.length&&!l.length);(u||t)&&i.log("INTERSTITIALS_UPDATED ("+a.length+"): "+a+"\nSchedule: "+s.map((function(e){return Ru(e)}))+" pos: "+i.timelinePos),l.length&&i.log("Removed events "+l);var d=null,h=null;n&&(d=i.updateItem(n,i.timelinePos),i.itemsMatch(n,d)?i.playingItem=d:i.waitingItem=null),i.waitingItem=i.updateItem(i.waitingItem);var f=i.bufferingItem;if(f&&(h=i.updateItem(f,i.bufferedPos),i.itemsMatch(f,h)?i.bufferingItem=h:f.event&&(i.bufferingItem=i.playingItem,i.clearInterstitial(f.event,null))),e.forEach((function(e){e.assetList.forEach((function(e){i.clearAssetPlayer(e.identifier,null)}))})),i.playerQueue.forEach((function(e){if(e.interstitial.appendInPlace){var t=e.assetItem.timelineStart,r=e.timelineOffset-t;if(r)try{e.timelineOffset=t}catch(n){Math.abs(r)>cu&&i.warn(n+' ("'+e.assetId+'" '+e.timelineOffset+"->"+t+")")}}})),u||t){if(i.hls.trigger(G.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:s.slice(0),durations:o,removedIds:l}),i.isInterstitial(n)&&l.indexOf(n.event.identifier)>-1)return i.warn('Interstitial "'+n.event.identifier+'" removed while playing'),void i.primaryFallback(n.event);n&&i.trimInPlace(d,n),f&&h!==d&&i.trimInPlace(h,f),i.checkBuffer()}}},i.hls=t,i.HlsPlayerClass=r,i.assetListLoader=new bu(t),i.schedule=new Lu(i.onScheduleUpdate,t.logger),i.registerListeners(),i}d(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e&&(e.on(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(G.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(G.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(G.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(G.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(G.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(G.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(G.BUFFER_APPENDED,this.onBufferAppended,this),e.on(G.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(G.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(G.MEDIA_ENDED,this.onMediaEnded,this),e.on(G.ERROR,this.onError,this),e.on(G.DESTROYING,this.onDestroying,this))},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(G.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(G.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(G.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(G.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(G.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(G.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(G.BUFFER_CODECS,this.onBufferCodecs,this),e.off(G.BUFFER_APPENDED,this.onBufferAppended,this),e.off(G.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(G.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(G.MEDIA_ENDED,this.onMediaEnded,this),e.off(G.ERROR,this.onError,this),e.off(G.DESTROYING,this.onDestroying,this))},r.startLoad=function(){this.resumeBuffering()},r.stopLoad=function(){this.pauseBuffering()},r.resumeBuffering=function(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()},r.pauseBuffering=function(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()},r.destroy=function(){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=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null},r.onDestroying=function(){var e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)},r.removeMediaListeners=function(e){Cn(e,"play",this.onPlay),Cn(e,"pause",this.onPause),Cn(e,"seeking",this.onSeeking),Cn(e,"timeupdate",this.onTimeupdate)},r.onMediaAttaching=function(e,t){var r=this.media=t.media;_n(r,"seeking",this.onSeeking),_n(r,"timeupdate",this.onTimeupdate),_n(r,"play",this.onPlay),_n(r,"pause",this.onPause)},r.onMediaAttached=function(e,t){var r=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===r)this.checkStart();else if(!i){this.clearScheduleState();var n=this.findItemIndex(r);this.setSchedulePosition(n)}},r.clearScheduleState=function(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null},r.onMediaDetaching=function(e,t){var r=!!t.transferMedia,i=this.media;if(this.media=null,!r&&(i&&this.removeMediaListeners(i),this.detachedData)){var n=this.getBufferingPlayer();n&&(this.log("Removing schedule state for detachedData and "+n),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}},r.isInterstitial=function(e){return!(null==e||!e.event)},r.retreiveMediaSource=function(e,t){var r=this.getAssetPlayer(e);r&&this.transferMediaFromPlayer(r,t)},r.transferMediaFromPlayer=function(e,t){var r=e.interstitial.appendInPlace,i=e.media;if(r&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i)return void(this.detachedData={media:i});var n=e.transferMedia();this.log("transfer MediaSource from "+e+" "+cr(n)),this.detachedData=n}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))},r.transferMediaTo=function(e,t){var r,i,n=this;if(e.media!==t){var a,s=null,o=this.hls,l=e!==o,u=l&&e.interstitial.appendInPlace,d=null==(r=this.detachedData)?void 0:r.mediaSource;if(o.media)u&&(s=o.transferMedia(),this.detachedData=s),a="Primary";else{var h=this.getBufferingPlayer();h?(s=h.transferMedia(),this.detachedData=s,a=""+h):a=d?"detached MediaSource":"detached media"}if(!s)if(d)s=this.detachedData,this.log("using detachedData: MediaSource "+cr(s));else if(!this.detachedData||o.media===t){var f=this.playerQueue;f.length>1&&f.forEach((function(e){if(l&&e.interstitial.appendInPlace!==u){var t=e.interstitial;n.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&n.warn("Could not change append strategy for queued assets "+t)}})),this.hls.detachMedia(),this.detachedData={media:t}}var g=s&&"mediaSource"in s&&"closed"!==(null==(i=s.mediaSource)?void 0:i.readyState);if(this.log((g?"transfering MediaSource":"attaching media")+" to "+(l?e:"Primary")+" from "+a+" (media.currentTime: "+t.currentTime+")"),g||l){var v=g&&s?c({},s):{media:t},m=this.schedule;if(m&&l){var p=e.assetId===m.assetIdAtEnd;v.overrides={duration:m.duration,endOfStream:p||!1===e.appendInPlace}}if(!g&&u){var y=e,E=y.assetItem.timelineStart;if(E){var T=y.hls,S=Math.max(this.timelinePos-E,Number.EPSILON);T.startPosition!==S&&(this.log("Set "+y+" startPosition: "+S),T.config.startPosition=S,T.loadingEnabled&&T.startLoad(S))}}e.attachMedia(v)}else e.attachMedia(t)}},r.onInterstitialCueEnter=function(){this.onTimeupdate()},r.checkStart=function(){var e=this.schedule,t=null==e?void 0:e.events,r=this.hls;if(t&&!this.playbackDisabled&&this.media&&r){-1===this.bufferedPos&&(this.bufferedPos=0);var i=this.timelinePos,n=this.effectivePlayingItem;if(-1===i){if(!r.loadingEnabled)return void this.log("waiting for startLoad( <startPosition> )");var a=r.startPosition;if(this.timelinePos=a,0===t.length)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Du("checkStart (preroll)",a));var s=e.findEventIndex(t[0].identifier);this.setSchedulePosition(s)}else if(a>=0||!this.primaryLive){this.log(Du("checkStart",a));var o=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}else 0===r.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(n&&!this.playingItem){this.log(Du("checkStart (playing item)",n.start));var u=e.findItemIndex(n);this.setSchedulePosition(u)}}},r.advanceAssetBuffering=function(e,t){var r=e.event,i=r.findAssetIndex(t),n=Tu(r,i);if(r.isAssetPastPlayoutLimit(n)){if(this.schedule){var a,s=this.getNextItemIndex(e,!0),o=null==(a=this.schedule.items)?void 0:a[s];o&&this.bufferedToItem(o)}}else this.bufferedToEvent(e,n)},r.livePrerollResumption=function(e,t){if(e.cue.pre&&this.primaryLive&&!x(e.resumeOffset)&&this.hls){var r=this.getLiveStartPos();if(t){var i=this.getBufferingPlayer();return r+(null!=i&&i.interstitial.cue.pre?i.remaining:0)}return r}},r.getNextItemIndex=function(e,t){if(this.schedule){var r=this.livePrerollResumption(e.event,t);if(void 0!==r)return this.log("find next item index @"+r),this.schedule.findItemIndexAtTime(r)}return this.findItemIndex(e)+1},r.advanceAfterAssetEnded=function(e,t,r){var i=Tu(e,r);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){var n=this.schedule.items;if(n){var a=n[t],s=a.event?this.getNextItemIndex(a):t+1;if(s>=n.length)return void this.setSchedulePosition(-1);var o=e.resumeTime;this.timelinePos<o&&(this.log(Du("advanceAfterAssetEnded",o)),this.timelinePos=o,e.appendInPlace&&!n[s].event&&this.hls.startLoad(o+.01),this.checkBuffer(this.bufferedPos<o)),this.setSchedulePosition(s)}}}else{if(e.appendInPlace){var l=e.assetList[i];l&&this.advanceInPlace(l.timelineStart)}this.setSchedulePosition(t,i)}},r.setScheduleToAssetAtTime=function(e,t){var r=this.schedule;if(r){var i=t.parentIdentifier,n=r.getEvent(i);if(n){var a=r.findEventIndex(i),s=r.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,s-1)}}},r.setSchedulePosition=function(e,t){var r,i=null==(r=this.schedule)?void 0:r.items;if(i&&!this.playbackDisabled){var n=e>=0?i[e]:null;this.log("setSchedulePosition "+e+", "+t+" ("+(n?Ru(n):n)+") pos: "+this.timelinePos);var a=this.waitingItem||this.playingItem,s=this.playingLastItem;if(this.isInterstitial(a)){var o=a.event,l=this.playingAsset,u=null==l?void 0:l.identifier,d=u?this.getAssetPlayer(u):null;if(d&&u&&(!this.eventItemsMatch(a,n)||void 0!==t&&u!==o.assetList[t].identifier)){var h,f=o.findAssetIndex(l);if(this.log("INTERSTITIAL_ASSET_ENDED "+(f+1)+"/"+o.assetList.length+" "+Su(l)),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(G.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:f,event:o,schedule:i.slice(0),scheduleIndex:e,player:d}),a!==this.playingItem)return void(this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(o,this.findItemIndex(this.playingItem),f));this.retreiveMediaSource(u,n),!d.media||null!=(h=this.detachedData)&&h.mediaSource||d.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=this.waitingItem=null,this.log("INTERSTITIAL_ENDED "+o+" "+Ru(a)),o.hasPlayed=!0,this.hls.trigger(G.INTERSTITIAL_ENDED,{event:o,schedule:i.slice(0),scheduleIndex:e}),o.cue.once&&this.hls)){var c;this.updateSchedule();var g=null==(c=this.schedule)?void 0:c.items;if(n&&g){var v=this.findItemIndex(n),m=this.livePrerollResumption(o);if(void 0!==m){var p=m,y=this.getNextItemIndex(a);if(!this.isInterstitial(i[y])){var E,T=null==(E=this.primaryDetails)?void 0:E.fragments;if(o.snapOptions.in&&T){var S=br(null,T,m);S&&(p=Math.min(Math.max(i[y].start,pu(p,S)),i[y].end))}}if(this.log(Du("live join (preroll)",p)),this.timelinePos=p,y!==v&&(y||0===y))return void this.advanceSchedule(y,g,void 0,a,s)}this.advanceSchedule(v,g,t,a,s)}return}}this.advanceSchedule(e,i,t,a,s)}},r.advanceSchedule=function(e,t,r,i,n){var a=this,s=this.schedule;if(s){var o=t[e]||null,l=this.primaryMedia,u=this.playerQueue;if(u.length&&u.forEach((function(t){var r=t.interstitial,i=s.findEventIndex(r.identifier);(i<e||i>e+1)&&a.clearInterstitial(r,o)})),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);var d=o.event;if(void 0===r){var h=Tu(d,(r=d.cue.pre?0:s.findAssetIndex(d,this.timelinePos))-1);if(d.isAssetPastPlayoutLimit(h)||d.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(d,e,r);r=h}var f=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);var c=this.preloadAssets(d,r);if(this.eventItemsMatch(o,f||i)||(this.waitingItem=o,this.log("INTERSTITIAL_STARTED "+Ru(o)+" "+(d.appendInPlace?"append in place":"")),d.hasPlayed=!1,this.hls.trigger(G.INTERSTITIAL_STARTED,{event:d,schedule:t.slice(0),scheduleIndex:e})),!d.assetListLoaded)return void this.log("Waiting for ASSET-LIST to complete loading "+d);if(d.assetListLoader&&(d.assetListLoader.destroy(),d.assetListLoader=void 0),!l)return void this.log("Waiting for attachMedia to start Interstitial "+d);this.waitingItem=this.endedItem=null,this.playingItem=o;var g=d.assetList[r];if(!g)return void this.advanceAfterAssetEnded(d,e,r||0);if(c||(c=this.getAssetPlayer(g.identifier)),null===c||c.destroyed){var v=d.assetList.length;this.warn("asset "+(r+1)+"/"+v+" player destroyed "+d),(c=this.createAssetPlayer(d,g,r)).loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&d.appendInPlace&&this.isAssetBuffered(g))return;this.startAssetPlayer(c,r,t,e,l),this.shouldPlay&&ku(c.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&ku(this.hls.media)):n&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(s.durations.primary,null))}},r.resumePrimary=function(e,t,r){var i,n;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log("resuming "+Ru(e));var a=this.timelinePos;if(null!=(i=this.detachedData)&&i.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(a):((a<e.start||a>=e.end||a<this.seekableStart)&&(a=this.getPrimaryResumption(e,t),this.log(Du("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)),r){var s=null==(n=this.schedule)?void 0:n.items;s&&(this.log("INTERSTITIALS_PRIMARY_RESUMED "+Ru(e)),this.hls.trigger(G.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}},r.getPrimaryResumption=function(e,t,r){var i=e.start;if(this.primaryLive){if(0===t)return this.hls.startPosition;var n=this.endedItem||this.playingItem,a=null!=n&&n.event?this.livePrerollResumption(n.event,r):void 0;if(void 0!==a)return a;var s=this.primaryDetails;if(s){var o=s.fragmentStart,l=s.edge;if(i<o||i>l&&!r){var u=this.hls.liveSyncPosition;return this.log("primary resumption out of bounds ("+i+" ["+o+"-"+l+"]) snapping to liveSync "+u),u||o}}}return this.log("primary resumption itemStart: "+i),i},r.getLiveStartPos=function(){var e,t=this.hls.startPosition,r=this.hls.liveSyncPosition||0,i=3*((null==(e=this.primaryDetails)?void 0:e.targetduration)||10);return-1===t||r&&r-t<i?r||0:t},r.isAssetBuffered=function(e){var t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:gi.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)},r.attachPrimary=function(e,t,r){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;var i=this.primaryMedia;if(i){var n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,i),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(Du("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}},r.startLoadingPrimaryAt=function(e,t){var r=this.hls,i=r.loadingEnabled,n=r.bufferingEnabled,a=r.startPosition,s=r.hasEnoughToStart;if(this.log("Start loading primary @"+e+" bufferedPos: "+this.bufferedPos+" startPosition: "+a+" skip seek: "+t+" has enough "+s+" loadingEnabled: "+i+" bufferingEnabled: "+n),!t&&s||!i||Math.abs(a-e)>.1){var o=this.primaryDetails;if(null!=o&&o.live&&e+.5>=o.edge){var l=this.bufferingItem;return this.log("Resume primary loading when live passes "+e+" buffering item: "+(l?Ru(l):null)),r.pauseBuffering(),void(this.bufferPastEdge=!0)}r.startLoad(e,t)}else n||r.resumeBuffering()},r.onManifestLoading=function(){var e;this.stopLoad(),null==(e=this.schedule)||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(G.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(G.BUFFER_CODECS,this.onBufferCodecs,this)},r.onLevelUpdated=function(e,t){if(-1!==t.level&&this.schedule){var r=this.hls.levels[t.level];if(r.details){var i=c(c({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=i;var n=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace,-1===n?0:n),this.schedule.items)if(this.effectivePlayingItem){if(this.bufferPastEdge){var a=this.primaryDetails,s=this.bufferedPos;if(null!=a&&a.live&&s+.5<a.edge){this.bufferPastEdge=!1;var o=this.bufferingItem;if(this.log("Live edge "+a.edge+" passed buffer: "+s+" buffering item: "+(o?Ru(o):null)),(null==o?void 0:o.end)===1/0){var l=this.playingItem,u=this.isInterstitial(l)&&l.event.appendInPlace;this.hls.startLoad(Math.max(s,o.start),u)}else{var d=this.getBufferingPlayer();d&&d.bufferedInPlaceToEnd(this.primaryMedia,d.currentTime)&&d.hls&&d.hls.trigger(G.BUFFERED_TO_END,void 0)}}}}else this.checkStart()}}},r.onAudioTrackUpdated=function(e,t){var r=this.hls.audioTracks[t.id],i=this.mediaSelection;if(i){var n=c(c({},i),{},{audio:r});this.mediaSelection=n}else this.altSelection=c(c({},this.altSelection),{},{audio:r})},r.onSubtitleTrackUpdated=function(e,t){var r=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(i){var n=c(c({},i),{},{subtitles:r});this.mediaSelection=n}else this.altSelection=c(c({},this.altSelection),{},{subtitles:r})},r.onAudioTrackSwitching=function(e,t){var r=mr(t);this.playerQueue.forEach((function(e){var i=e.hls;return i&&(i.setAudioOption(t)||i.setAudioOption(r))}))},r.onSubtitleTrackSwitch=function(e,t){var r=mr(t);this.playerQueue.forEach((function(e){var i=e.hls;return i&&(i.setSubtitleOption(t)||-1!==t.id&&i.setSubtitleOption(r))}))},r.onBufferCodecs=function(e,t){var r=t.tracks;r&&(this.requiredTracks=r)},r.onBufferAppended=function(e,t){this.checkBuffer()},r.onBufferFlushed=function(e,t){var r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){var i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}},r.onBufferedToEnd=function(e){if(this.schedule){var t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(var r=0;r<t.length;r++){var i=t[r];if(i.cue.post){var n=this.getEventItem(i.identifier);n&&this.eventItemsMatch(n,this.bufferingItem)&&this.bufferedToItem(n,0);break}}this.bufferedPos=Number.MAX_VALUE}}},r.onMediaEnded=function(e){var t=this.playingItem;if(!this.playingLastItem&&t){var r=this.findItemIndex(t);this.setSchedulePosition(r+1)}else this.shouldPlay=!1},r.updateItem=function(e,t){var r,i=null==(r=this.schedule)?void 0:r.items;return e&&i&&i[this.findItemIndex(e,t)]||null},r.trimInPlace=function(e,t){var r=this;if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((function(t,i){e.event.isAssetPastPlayoutLimit(i)&&r.clearAssetPlayer(t.identifier,null)}));var i=e.end+.25,n=gi.bufferInfo(this.primaryMedia,i,0);(n.end>i||(n.nextStart||0)>i)&&(this.log("trim buffered interstitial "+Ru(e)+" (was "+Ru(t)+")"),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}},r.itemsMatch=function(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))},r.eventItemsMatch=function(e,t){var r;return!!t&&(e===t||e.event.identifier===(null==(r=t.event)?void 0:r.identifier))},r.findEventIndex=function(e){return this.schedule?this.schedule.findEventIndex(e):-1},r.getEventItem=function(e){if(this.schedule){var t,r=null==(t=this.schedule.items)?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(r)&&r.event.identifier===e)return r}},r.findItemIndex=function(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1},r.updateSchedule=function(e){var t,r;void 0===e&&(e=!1);var i=this.mediaSelection;if(i){var n=(null==(t=this.hls)?void 0:t.liveSyncPosition)||0;null==(r=this.schedule)||r.updateSchedule(i,[],n,e)}},r.checkBuffer=function(e){var t,r=null==(t=this.schedule)?void 0:t.items;if(r){var i=gi.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,r,e)}},r.updateBufferedPos=function(e,t,r){var i=this.schedule,n=this.bufferingItem;if(!(this.bufferedPos>e)&&i)if(1===t.length&&this.itemsMatch(t[0],n))this.bufferedPos=e;else{var a=this.playingItem,s=this.findItemIndex(a),o=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,u=this.findItemIndex(n),d=Math.min(u+1,t.length-1),h=t[d];if((-1===o&&n&&e>=n.end||null!=(l=h.event)&&l.appendInPlace&&e+.01>=h.start)&&(o=d),this.isInterstitial(n)){var f=n.event;if(d-s>1&&!1===f.appendInPlace)return;if(0===f.assetList.length&&f.assetListLoader)return}if(this.bufferedPos=e,o>u&&o>s)this.bufferedToItem(h);else{var c=this.primaryDetails;this.primaryLive&&c&&e>c.edge-c.targetduration&&h.start<c.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.event,0)}}else r&&a&&!this.itemsMatch(a,n)&&(o===s?this.bufferedToItem(a):o===s+1&&this.bufferedToItem(t[o]))}},r.assetsBuffered=function(e,t){var r=this;return 0!==e.event.assetList.length&&!e.event.assetList.some((function(e){var i=r.getAssetPlayer(e.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(t))}))},r.setBufferingItem=function(e){var t=this,r=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,r)&&i){var n=i.items,a=i.events;if(!n||!a)return r;var s=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));var l=o?o.remaining:r?r.end-this.timelinePos:0;if(this.log("INTERSTITIALS_BUFFERED_TO_BOUNDARY "+Ru(e)+(r?" ("+l.toFixed(2)+" remaining)":"")),!this.playbackDisabled)if(s){var u=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((function(e,r){var i=t.getAssetPlayer(e.identifier);i&&(r===u&&i.loadSource(),i.resumeBuffering())}))}else this.hls.resumeBuffering(),this.playerQueue.forEach((function(e){return e.pauseBuffering()}));this.hls.trigger(G.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:a.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return r},r.bufferedToItem=function(e,t){void 0===t&&(t=0);var r=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==r){this.bufferingAsset=null;var i=this.getPrimaryResumption(e,this.findItemIndex(e),!0),n=this.bufferedPos=Math.max(i,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),a=this.detachedData;if(a)a.mediaSource?this.attachPrimary(n,e,!0):this.startLoadingPrimaryAt(n);else{var s=this.playingItem,o=this.isInterstitial(s)&&s.event.appendInPlace;this.startLoadingPrimaryAt(n,o)}}},r.bufferedToEvent=function(e,t){var r=e.event,i=0===r.assetList.length&&!r.assetListLoader,n=r.cue.once;if(i||!n){var a=this.preloadAssets(r,t);if(null!=a&&a.interstitial.appendInPlace){var s=this.primaryMedia;s&&this.bufferAssetPlayer(a,s)}}},r.preloadAssets=function(e,t){var r=e.assetUrl,i=e.assetList.length,n=0===i&&!e.assetListLoader,a=e.cue.once;if(n){var s,o,l=e.timelineStart,u=this.playingItem,d=this.getBufferingPlayer();e.appendInPlace&&(this.isInterstitial(u)||(null==u||null==(s=u.nextEvent)?void 0:s.identifier)!==e.identifier||this.flushFrontBuffer(l+.25));var h=0;if(d&&!d.interstitial.cue.pre||!this.primaryLive||(h=this.getLiveStartPos(),d&&(h+=d.remaining)),h&&!e.cue.pre&&!e.cue.post){var f=h-l;f>0&&(o=Math.round(1e3*f)/1e3)}if(this.log("Load interstitial asset "+(t+1)+"/"+(r?1:i)+" "+e+(h?" live-start: "+h+" start-offset: "+o+" (timeline-start: "+l+")":"")),r)return this.createAsset(e,0,0,l,e.duration,r);var c=this.assetListLoader.loadAssetList(e,o);c&&(e.assetListLoader=c)}else if(!a&&i){for(var g=t;g<i;g++){var v=e.assetList[g],m=this.getAssetPlayerQueueIndex(v.identifier);-1!==m&&!this.playerQueue[m].destroyed||v.error||this.createAssetPlayer(e,v,g)}var p=e.assetList[t];if(p){var y=this.getAssetPlayer(p.identifier);return y&&y.loadSource(),y}}return null},r.flushFrontBuffer=function(e){var t=this,r=this.requiredTracks;if(r){var i=this.primaryDetails;i&&e>=i.edge||(this.log("Removing front buffer starting at "+e),Object.keys(r).forEach((function(r){t.hls.trigger(G.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})})))}},r.getAssetPlayerQueueIndex=function(e){for(var t=this.playerQueue,r=0;r<t.length;r++)if(e===t[r].assetId)return r;return-1},r.getAssetPlayer=function(e){var t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null},r.getBufferingPlayer=function(){var e=this.playerQueue,t=this.primaryMedia;if(t)for(var r=0;r<e.length;r++)if(e[r].media===t)return e[r];return null},r.createAsset=function(e,t,r,i,n,a){var s={parentIdentifier:e.identifier,identifier:vu(e,a,t),duration:n,startOffset:r,timelineStart:i,uri:a};return this.createAssetPlayer(e,s,t)},r.createAssetPlayer=function(e,t,r){var i=this,n=this.hls,a=n.userConfig,s=Ir(n.loadLevelObj||n.levels[n.currentLevel],a.videoPreference),o=n.audioTracks[n.audioTrack],u=n.subtitleTracks[n.subtitleTrack],d=0;if(this.primaryLive||e.appendInPlace){var h=this.timelinePos-t.timelineStart;if(h>=0){var f=t.duration;f&&h<f&&(d=h)}}var g=t.identifier,v=c(c({},a),{},{maxMaxBufferLength:Math.min(15,n.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:g,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:s,audioPreference:o||a.audioPreference,subtitlePreference:u||a.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(v.timelineOffset=t.timelineStart));var m=v.cmcd;null!=m&&m.sessionId&&m.contentId&&(v.cmcd=l({},m,{contentId:fu(t.uri)})),this.getAssetPlayer(g)&&this.warn("Duplicate date range identifier "+e+" and asset "+g);var p=new Au(this.HlsPlayerClass,v,e,t);this.playerQueue.push(p),e.assetList[r]=t;var y=!0,E=function(n){if(n.live){var a=new Error("Interstitials MUST be VOD assets "+e),s={fatal:!0,type:B.OTHER_ERROR,details:U.INTERSTITIAL_ASSET_ITEM_ERROR,error:a},o=i.findEventIndex(e.identifier);i.handleAssetItemError(s,e,o,r,a.message)}else{var l=n.edge-n.fragmentStart,u=t.duration;(y||null===u||l>u)&&(y=!1,i.log('Interstitial asset "'+g+'" duration change '+u+" > "+l),t.duration=l,i.updateSchedule())}};p.on(G.LEVEL_UPDATED,(function(e,t){var r=t.details;return E(r)})),p.on(G.LEVEL_PTS_UPDATED,(function(e,t){var r=t.details;return E(r)})),p.on(G.EVENT_CUE_ENTER,(function(){return i.onInterstitialCueEnter()}));var T=function(e,t){var r=i.getAssetPlayer(g);if(r&&t.tracks){r.off(G.BUFFER_CODECS,T),r.tracks=t.tracks;var n=i.primaryMedia;i.bufferingAsset===r.assetItem&&n&&!r.media&&i.bufferAssetPlayer(r,n)}};p.on(G.BUFFER_CODECS,T),p.on(G.BUFFERED_TO_END,(function(){var t=i.getAssetPlayer(g);if(i.log("buffered to end of asset "+t),t&&i.schedule){var r=i.getEventItem(e.identifier);r&&i.advanceAssetBuffering(r,t.assetItem)}}));var S=function(t){return function(){if(i.getAssetPlayer(g)&&i.schedule){i.shouldPlay=!0;var r=i.findEventIndex(e.identifier);i.advanceAfterAssetEnded(e,r,t)}}};return p.once(G.MEDIA_ENDED,S(r)),p.once(G.PLAYOUT_LIMIT_REACHED,S(1/0)),p.on(G.ERROR,(function(t,n){if(i.schedule){var a=i.getAssetPlayer(g);if(n.details===U.BUFFER_STALLED_ERROR)return null!=a&&a.appendInPlace?void i.handleInPlaceStall(e):(i.onTimeupdate(),void i.checkBuffer(!0));n.details!==U.BUFFER_SEEK_OVER_HOLE&&i.handleAssetItemError(n,e,i.findEventIndex(e.identifier),r,"Asset player error "+n.error+" "+e)}})),p.on(G.DESTROYING,(function(){if(i.getAssetPlayer(g)&&i.schedule){var t=new Error("Asset player destroyed unexpectedly "+g),n={fatal:!0,type:B.OTHER_ERROR,details:U.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};i.handleAssetItemError(n,e,i.findEventIndex(e.identifier),r,t.message)}})),this.log("INTERSTITIAL_ASSET_PLAYER_CREATED "+Su(t)),this.hls.trigger(G.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:p}),p},r.clearInterstitial=function(e,t){this.clearAssetPlayers(e,t),e.reset()},r.clearAssetPlayers=function(e,t){var r=this;e.assetList.forEach((function(e){r.clearAssetPlayer(e.identifier,t)}))},r.resetAssetPlayer=function(e){var t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log('reset asset player "'+e+'" after error');var r=this.playerQueue[t];this.transferMediaFromPlayer(r,null),r.resetDetails()}},r.clearAssetPlayer=function(e,t){var r=this.getAssetPlayerQueueIndex(e);if(-1!==r){var i=this.playerQueue[r];this.log("clear "+i+" toSegment: "+(t?Ru(t):t)),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(r,1),i.destroy()}},r.emptyPlayerQueue=function(){for(var e;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]},r.startAssetPlayer=function(e,t,r,i,n){var a=e.interstitial,s=e.assetItem,o=e.assetId,l=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=s,(null==u?void 0:u.identifier)!==o&&(u&&(this.clearAssetPlayer(u.identifier,r[i]),delete u.error),this.log("INTERSTITIAL_ASSET_STARTED "+(t+1)+"/"+l+" "+Su(s)),this.hls.trigger(G.INTERSTITIAL_ASSET_STARTED,{asset:s,assetListIndex:t,event:a,schedule:r.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,n)},r.bufferAssetPlayer=function(e,t){var r;if(this.schedule){var i=e.interstitial,n=e.assetItem,a=this.getEventItem(i.identifier);if(a)if(e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=n,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime))this.advanceAssetBuffering(a,n);else{var s=this.getBufferingPlayer();if(s!==e){var o=i.appendInPlace;if(!o||!1!==(null==s?void 0:s.interstitial.appendInPlace)){var l=(null==s?void 0:s.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(o&&n!==this.playingAsset){if(!e.tracks)return void this.log("Waiting for track info before buffering "+e);if(l&&!be(l,e.tracks)){var u=new Error("Asset "+Su(n)+" SourceBuffer tracks ('"+Object.keys(e.tracks)+"') are not compatible with primary content tracks ('"+Object.keys(l)+"')"),d={fatal:!0,type:B.OTHER_ERROR,details:U.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},h=i.findAssetIndex(n);return void this.handleAssetItemError(d,i,this.findEventIndex(i.identifier),h,u.message)}}this.transferMediaTo(e,t)}}}}},r.handleInPlaceStall=function(e){var t=this.schedule,r=this.primaryMedia;if(t&&r){var i=r.currentTime,n=t.findAssetIndex(e,i),a=e.assetList[n];if(a){var s=this.getAssetPlayer(a.identifier);if(s){var o=s.currentTime||i-a.timelineStart,l=s.duration-o;if(this.warn("Stalled at "+o+" of "+(o+l)+" in "+s+" "+e+" (media.currentTime: "+i+")"),o&&(l/r.playbackRate<.5||s.bufferedInPlaceToEnd(r,s.currentTime))&&s.hls){var u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,n)}}}}},r.advanceInPlace=function(e){var t=this.primaryMedia;if(t&&t.currentTime<e){var r="advance currentTime to "+e+", duration: "+t.duration;t.duration>e?(this.log(r),t.currentTime=e):this.log("Cannot "+r)}},r.handleAssetItemError=function(e,t,r,i,n){if(e.details!==U.BUFFER_STALLED_ERROR){var a=t.assetList[i]||null;if(this.warn("INTERSTITIAL_ASSET_ERROR "+(a?Su(a):a)+" "+e.error),this.schedule){var s=(null==a?void 0:a.identifier)||"",o=this.getAssetPlayerQueueIndex(s),u=this.playerQueue[o]||null,d=this.schedule.items,h=l({},e,{fatal:!1,errorAction:Yr(!0),asset:a,assetListIndex:i,event:t,schedule:d,scheduleIndex:r,player:u});if(this.hls.trigger(G.INTERSTITIAL_ASSET_ERROR,h),e.fatal){var f=this.playingAsset,c=this.bufferingAsset,g=new Error(n);if(a&&(this.clearAssetPlayer(s,null),a.error=g),t.assetList.some((function(e){return!e.error})))for(var v=i;v<t.assetList.length;v++)this.resetAssetPlayer(t.assetList[v].identifier);else t.error=g;this.updateSchedule(!0),t.error?this.primaryFallback(t):(null==f?void 0:f.identifier)===s?this.advanceAfterAssetEnded(t,r,i):(null==c?void 0:c.identifier)===s&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,c)}}}},r.primaryFallback=function(e){var t=e.timelineStart,r=this.effectivePlayingItem,i=this.playingItem,n=this.seekableStart,a=this.hls.startPosition,s=this.timelinePos;if(this.isInterstitial(r)){this.log('Fallback to primary from event "'+e.identifier+'" start: '+t+" pos: "+s+" playing: "+Ru(r)+" startPosition: "+a+" seekableStart: "+n+" error: "+e.error),-1===s&&(s=a),s=Math.max(s,n);var o=this.updateItem(r,s);this.itemsMatch(r,o)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(-1===s)return void this.checkStart();if(this.schedule&&this.isInterstitial(i)){var l=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(l)}},r.onAssetListLoaded=function(e,t){var r,i,n=this,a=t.event,s=a.identifier,o=t.assetListResponse.ASSETS;if(null!=(r=this.schedule)&&r.hasEvent(s)){var l=a.timelineStart,u=a.duration,d=0;o.forEach((function(e,t){var r=parseFloat(e.DURATION);n.createAsset(a,t,d,l+d,r,e.URI),d+=r})),a.duration=d,this.log("Loaded asset-list with duration: "+d+" (was: "+u+") "+a);var h=this.waitingItem,f=(null==h?void 0:h.event.identifier)===s;this.updateSchedule();var c=null==(i=this.bufferingItem)?void 0:i.event;if(f){var g=this.findEventIndex(s),v=this.getEventItem(s);if(v){if(!this.playingItem&&this.timelinePos>v.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g)return a.error=new Error("Interstitial "+(o.length?"no longer within playback range":"asset-list is empty")+" "+this.timelinePos+" "+a),this.log(a.error.message),this.updateSchedule(!0),void this.primaryFallback(a);this.setBufferingItem(v)}this.setSchedulePosition(g)}else if((null==c?void 0:c.identifier)===s){var m=a.assetList[0];if(m){var p=this.getAssetPlayer(m.identifier);if(c.appendInPlace){var y=this.primaryMedia;p&&y&&this.bufferAssetPlayer(p,y)}else p&&p.loadSource()}}}},r.onError=function(e,t){if(this.schedule)switch(t.details){case U.ASSET_LIST_PARSING_ERROR:case U.ASSET_LIST_LOAD_ERROR:case U.ASSET_LIST_LOAD_TIMEOUT:var r=t.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break;case U.BUFFER_STALLED_ERROR:var i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace)return void this.handleInPlaceStall(i.event);var n=this.primaryMedia;this.log("Primary player stall @"+this.timelinePos+" currentTime: "+(null==n?void 0:n.currentTime)+" bufferedPos: "+this.bufferedPos),this.onTimeupdate(),this.checkBuffer(!0)}},a(t,[{key:"interstitialsManager",get:function(){if(!this.hls)return null;if(this.manager)return this.manager;var e=this,t=function(){return e.bufferingItem||e.waitingItem},r=function(t){return t?e.getAssetPlayer(t.identifier):t},i=function(t,i,a,s,o){if(t){var l=t[i].start,u=t.event;if(u){if("playout"===i||u.timelineOccupancy!==gu.Point){var d=r(a);(null==d?void 0:d.interstitial)===u&&(l+=d.assetItem.startOffset+d[o])}}else l+=("bufferedPos"===s?n():e[s])-t.start;return l}return 0},n=function(){var t=e.bufferedPos;return t===Number.MAX_VALUE?a("primary"):Math.max(t,0)},a=function(t){var r,i;return null!=(r=e.primaryDetails)&&r.live?e.primaryDetails.edge:(null==(i=e.schedule)?void 0:i.durations[t])||0},s=function(t,n){var a,s,o=e.effectivePlayingItem;if((null==o||null==(a=o.event)||!a.restrictions.skip)&&e.schedule){e.log("seek to "+t+' "'+n+'"');var l=e.effectivePlayingItem,u=e.schedule.findItemIndexAtTime(t,n),d=null==(s=e.schedule.items)?void 0:s[u],h=e.getBufferingPlayer(),f=null==h?void 0:h.interstitial,c=null==f?void 0:f.appendInPlace,g=l&&e.itemsMatch(l,d);if(l&&(c||g)){var v=r(e.playingAsset),m=(null==v?void 0:v.media)||e.primaryMedia;if(m){var p="primary"===n?m.currentTime:i(l,n,e.playingAsset,"timelinePos","currentTime"),y=t-p,E=(c?p:m.currentTime)+y;if(E>=0&&(!v||c||E<=v.duration))return void(m.currentTime=E)}}if(d){var T=t;if("primary"!==n){var S=t-d[n].start;T=d.start+S}var A=!e.isInterstitial(d);if(e.isInterstitial(l)&&!l.event.appendInPlace||!A&&!d.event.appendInPlace){if(l){var I=e.findItemIndex(l);if(u>I){var L=e.schedule.findJumpRestrictedIndex(I+1,u);if(L>I)return void e.setSchedulePosition(L)}var R=0;if(A)e.timelinePos=T,e.checkBuffer();else for(var b=d.event.assetList,k=t-(d[n]||d).start,D=b.length;D--;){var P=b[D];if(P.duration&&k>=P.startOffset&&k<P.startOffset+P.duration){R=D;break}}e.setSchedulePosition(u,R)}}else{var _=e.media||(c?null==h?void 0:h.media:null);_&&(_.currentTime=T)}}}},o=function(){var r=e.effectivePlayingItem;if(e.isInterstitial(r))return r;var i=t();return e.isInterstitial(i)?i:null},l={get bufferedEnd(){var r,n=t(),a=e.bufferingItem;return a&&a===n&&(i(a,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-a.playout.start||(null==(r=e.bufferingAsset)?void 0:r.startOffset))||0},get currentTime(){var t=o(),r=e.effectivePlayingItem;return r&&r===t?i(r,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-r.playout.start:0},set currentTime(t){var r=o(),i=e.effectivePlayingItem;i&&i===r&&s(t+i.playout.start,"playout")},get duration(){var e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t,r=null==(t=o())?void 0:t.event.assetList;return r?r.map((function(t){return e.getAssetPlayer(t.identifier)})):[]},get playingIndex(){var t,r=null==(t=o())?void 0:t.event;return r&&e.effectivePlayingAsset?r.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var t;return(null==(t=e.schedule)||null==(t=t.events)?void 0:t.slice(0))||[]},get schedule(){var t;return(null==(t=e.schedule)||null==(t=t.items)?void 0:t.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){var r=t();return e.findItemIndex(r)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){var t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return n()},get currentTime(){var t=e.timelinePos;return t>0?t:0},set currentTime(e){s(e,"primary")},get duration(){return a("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){s(e,"integrated")},get duration(){return a("integrated")},get seekableStart(){return function(t,r){var i;if(0!==t&&"primary"!==r&&null!=(i=e.schedule)&&i.length){var n,a=e.schedule.findItemIndexAtTime(t),s=null==(n=e.schedule.items)?void 0:n[a];if(s)return t+(s[r].start-s.start)}return t}(e.seekableStart,"integrated")}},skip:function(){var t=e.effectivePlayingItem,r=null==t?void 0:t.event;if(r&&!r.restrictions.skip){var i=e.findItemIndex(t);if(r.appendInPlace){var n=t.playout.start+t.event.duration;s(n+.001,"playout")}else e.advanceAfterAssetEnded(r,i,1/0)}}}}},{key:"effectivePlayingItem",get:function(){return this.waitingItem||this.playingItem||this.endedItem}},{key:"effectivePlayingAsset",get:function(){return this.playingAsset||this.endedAsset}},{key:"playingLastItem",get:function(){var e,t=this.playingItem,r=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&r)&&this.findItemIndex(t)===r.length-1}},{key:"playbackStarted",get:function(){return null!==this.effectivePlayingItem}},{key:"currentTime",get:function(){var e,t;if(null!==this.mediaSelection){var r=this.waitingItem||this.playingItem;if(!this.isInterstitial(r)||r.event.appendInPlace){var i=this.media;!i&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(i=this.primaryMedia);var n=null==(t=i)?void 0:t.currentTime;if(void 0!==n&&x(n))return n}}}},{key:"primaryMedia",get:function(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}},{key:"playbackDisabled",get:function(){return!1===this.hls.config.enableInterstitialPlayback}},{key:"primaryDetails",get:function(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}},{key:"primaryLive",get:function(){var e;return!(null==(e=this.primaryDetails)||!e.live)}},{key:"seekableStart",get:function(){var e;return this.primaryLive&&(null==(e=this.primaryDetails)?void 0:e.fragmentStart)||0}}])}(pe),_u=function(){function e(e){var t=this;this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=function(){var e,r=t.media,i=t.levelDetails;if(r&&i&&t.hls){t.currentTime=r.currentTime;var n=t.hls.config,a=t.computeLatency();if(null!==a){t._latency=a;var s=n.lowLatencyMode,o=n.maxLiveSyncPlaybackRate;if(s&&1!==o&&i.live){var l=t.targetLatency;if(null!==l){var u=a-l,d=u<Math.min(t.maxLatency,l+i.targetduration),h=Fn(n)&&!(null==(e=t.hls.interstitialsManager)||null==(e=e.playingItem)||!e.event);if(d&&u>.05&&t.forwardBufferLength>1&&!h){var f=Math.min(2,Math.max(1,o)),c=Math.round(2/(1+Math.exp(-.75*u-t.edgeStalled))*20)/20,g=Math.min(f,Math.max(1,c));t.changeMediaPlaybackRate(r,g)}else 1!==r.playbackRate&&0!==r.playbackRate&&t.changeMediaPlaybackRate(r,1)}}}}},this.hls=e,this.registerListeners()}var t=e.prototype;return t.destroy=function(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null},t.registerListeners=function(){var e=this.hls;e&&(e.on(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(G.ERROR,this.onError,this),e.on(G.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))},t.unregisterListeners=function(){var e=this.hls;e&&(e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(G.ERROR,this.onError,this),e.off(G.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))},t.onMediaAttached=function(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)},t.onMediaDetaching=function(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)},t.onManifestLoading=function(){this._latency=null,this.stallCount=0},t.onLevelUpdated=function(e,t){var r=t.details;r.advanced&&this.onTimeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)},t.onAssetStarted=function(e,t){var r,i=this.hls,n=this.media||t.event.appendInPlace&&(null==i||null==(r=i.interstitialsManager)?void 0:r.playerQueue.reduce((function(e,t){return e||t.media}),null));i&&n&&n.playbackRate>1&&n.playbackRate<=i.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(n,1)},t.onError=function(e,t){var r;t.details===U.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(r=this.levelDetails)&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))},t.changeMediaPlaybackRate=function(e,t){var r,i;e.playbackRate!==t&&(null==(r=this.hls)||r.logger.debug("[latency-controller]: latency="+this.latency.toFixed(3)+", targetLatency="+(null==(i=this.targetLatency)?void 0:i.toFixed(3))+", forwardBufferLength="+this.forwardBufferLength.toFixed(3)+": adjusting playback rate from "+e.playbackRate+" to "+t),e.playbackRate=t)},t.estimateLiveEdge=function(){var e=this.levelDetails;return null===e?null:e.edge+e.age},t.computeLatency=function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime},a(e,[{key:"levelDetails",get:function(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}},{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e,t=null==(e=this.hls)?void 0:e.config;if(!t)return 0;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;var r=this.levelDetails;return r?t.liveMaxLatencyDurationCount*r.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e||!this.hls)return null;var t=this.hls.config,r=e.holdBack,i=e.partHoldBack,n=e.targetduration,a=t.liveSyncDuration,s=t.liveSyncDurationCount,o=t.lowLatencyMode,l=this.hls.userConfig,u=o&&i||r;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==a?a:s*n);var d=n;return u+Math.min(this.stallCount*t.liveSyncOnStallIncrease,d)},set:function(e){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0)}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t||!this.hls)return null;var r=this.levelDetails;if(null===r)return null;var i=r.edge,n=e-t-this.edgeStalled,a=i-r.totalduration,s=i-(this.hls.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,n),s)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e||!this.hls)return 0;var t=3*(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}}])}(),Cu=function(e){function t(t,r,i){var n;return(n=e.call(this,t,r,i,"subtitle-stream-controller",$.SUBTITLE)||this).currentTrackId=-1,n.tracksBuffered=[],n.mainDetails=null,n.registerListeners(),n}d(t,e);var r=t.prototype;return r.onHandlerDestroying=function(){this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this),this.mainDetails=null},r.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(G.LEVEL_LOADED,this.onLevelLoaded,this),t.on(G.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(G.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(G.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(G.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(G.BUFFER_FLUSHING,this.onBufferFlushing,this)},r.unregisterListeners=function(){e.prototype.unregisterListeners.call(this);var t=this.hls;t.off(G.LEVEL_LOADED,this.onLevelLoaded,this),t.off(G.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(G.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(G.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(G.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(G.BUFFER_FLUSHING,this.onBufferFlushing,this)},r.startLoad=function(e,t){this.stopLoad(),this.state=On.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()},r.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.mainDetails=null},r.onMediaDetaching=function(t,r){this.tracksBuffered=[],e.prototype.onMediaDetaching.call(this,t,r)},r.onLevelLoaded=function(e,t){this.mainDetails=t.details},r.onSubtitleFragProcessed=function(e,t){var r=t.frag,i=t.part;if(t.success){var n=this.tracksBuffered[this.currentTrackId];if(n){for(var a,s=(i||r).start,o=0;o<n.length;o++)if(s>=n[o].start&&s<=n[o].end){a=n[o];break}var l=s+(i||r).duration;if(a?a.end=l:(a={start:s,end:l},n.push(a)),!i||l>=r.end){var u=this.fragmentTracker.fragBuffered(r);i&&u&&(u.range.subs={time:[{startPTS:r.start,endPTS:l}],partial:!0}),ee(r)&&!this.fragContextChanged(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,i),this.media&&this.tickImmediate()}}}},r.onBufferFlushing=function(e,t){var r=t.startOffset,i=t.endOffset;if(0===r&&i!==Number.POSITIVE_INFINITY){var n=i-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach((function(e){if(e)for(var t=0;t<e.length;)if(e[t].end<=n)e.shift();else{if(!(e[t].start<n))break;e[t].start=n,t++}})),this.fragmentTracker.removeFragmentsInRange(r,n,$.SUBTITLE)}},r.onError=function(e,t){var r=t.frag;(null==r?void 0:r.type)===$.SUBTITLE&&(t.details===U.FRAG_GAP&&this.fragmentTracker.addAsGap(r),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==On.STOPPED&&(this.state=On.IDLE))},r.onSubtitleTracksUpdated=function(e,t){var r=this,i=t.subtitleTracks;this.levels&&ms(this.levels,i)?this.levels=i.map((function(e){return new dr(e)})):(this.tracksBuffered=[],this.levels=i.map((function(e){var t=new dr(e);return r.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,$.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)},r.onSubtitleTrackSwitch=function(e,t){var r;if(this.currentTrackId=t.id,null!=(r=this.levels)&&r.length&&-1!==this.currentTrackId){var i=this.levels[this.currentTrackId];null!=i&&i.details?(this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==On.STOPPED&&this.setInterval(500)):this.mediaBuffer=null}else this.clearInterval()},r.onSubtitleTrackLoaded=function(e,t){var r,i=this.currentTrackId,n=this.levels,a=t.details,s=t.id;if(n){var o=n[s];if(!(s>=n.length)&&o){this.log("Subtitle track "+s+" loaded ["+a.startSN+","+a.endSN+"]"+(a.lastPartSn?"[part-"+a.lastPartSn+"-"+a.lastPartIndex+"]":"")+",duration:"+a.totalduration),this.mediaBuffer=this.mediaBufferTimeRanges;var l=this.mainDetails,u=0;if(a.live||null!=(r=o.details)&&r.live){if(a.deltaUpdateFailed)return;if(!l)return void(this.startFragRequested=!1);var d;o.details&&(u=this.alignPlaylists(a,o.details,null==(d=this.levelLastLoaded)?void 0:d.details)),a.alignedSliding||(Pn(l,a,this),u=a.fragmentStart)}o.details=a,this.levelLastLoaded=o,l&&!this.startFragRequested&&this.setStartPosition(l,u),s===i&&(this.hls.trigger(G.SUBTITLE_TRACK_UPDATED,{details:a,id:s,groupId:t.groupId}),this.tickImmediate())}}else this.warn("Subtitle tracks were reset while loading level "+s)},r._handleFragmentLoadProgress=function(e){var t=e.frag,r=e.part,i=e.payload;r&&null!=i&&i.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(i,t,r)},r._handleFragmentLoadComplete=function(e){var t=e.frag,r=e.payload;!this.fragContextChanged(t)&&null!=r&&r.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(r,t,null)},r.shouldDecrypt=function(e){var t=e.decryptdata;return!!(null!=t&&t.key&&t.iv&&Di(t.method))},r.decryptPayload=function(e,t,r){var i=this,n=t.decryptdata,a=performance.now();this.decrypter.decrypt(new Uint8Array(e),n.key.buffer,n.iv.buffer,Pi(n.method)).then((function(e){i.fragContextChanged(t)||i.hls.trigger(G.FRAG_DECRYPTED,{frag:t,part:r,payload:e,stats:{tstart:a,tdecrypt:performance.now()}})})).catch((function(e){i.hls.trigger(G.ERROR,{type:B.MEDIA_ERROR,details:U.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t,part:r}),r||(i.warn(e.name+": "+e.message),i.state=On.IDLE)}))},r.doTick=function(){if(this.state===On.IDLE&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;var t=this.currentTrackId,r=this.levels[t],i=null==r?void 0:r.details;if(!i||this.waitForLive(r)||this.waitForCdnTuneIn(i))return void(this.startFragRequested=!1);var n=this.config,a=this.playhead,s=gi.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],a,n.maxBufferHole),o=s.end,l=s.len;if(l>Math.max(this.hls.maxBufferLength+i.levelTargetDuration,(null==(e=this.hls.mainForwardBufferInfo)?void 0:e.len)||0)||l&&!this.buffering)return;var u=this.getNextFragment(o,i);if(!u)return;if(ee(u)){var d,h=u.sn-i.startSN,f=i.fragments[h-1];u.cc!==(null==f?void 0:f.cc)||null!=(d=i.partList)&&d.length||this.fragmentTracker.getState(f)!==jr||(u=f)}this.loadFragment(u,r,o)}},r.loadFragment=function(t,r,i){var n=this.fragmentTracker.getState(t);n!==jr&&n!==qr||e.prototype.loadFragment.call(this,t,r,i)},a(t,[{key:"mediaBufferTimeRanges",get:function(){return new wu(this.tracksBuffered[this.currentTrackId]||[])}}])}(Mn),wu=function(e){this.buffered=void 0;var t=function(t,r,i){if((r>>>=0)>i-1)throw new DOMException("Failed to execute '"+t+"' on 'TimeRanges': The index provided ("+r+") is greater than the maximum bound ("+i+")");return e[r][t]};this.buffered={get length(){return e.length},end:function(r){return t("end",r,e.length)},start:function(r){return t("start",r,e.length)}}},Ou=function(){if(null!=Oi&&Oi.VTTCue)return self.VTTCue;var e=["","lr","rl"],t=["start","middle","end","left","right"];function r(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;var r=t.toLowerCase();return!!~e.indexOf(r)&&r}function i(e){return r(t,e)}function n(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];for(var n=1;n<arguments.length;n++){var a=arguments[n];for(var s in a)e[s]=a[s]}return e}function a(t,a,s){var o=this,l={enumerable:!0};o.hasBeenReset=!1;var u="",d=!1,h=t,f=a,c=s,g=null,v="",m=!0,p="auto",y="start",E=50,T="middle",S=50,A="middle";Object.defineProperty(o,"id",n({},l,{get:function(){return u},set:function(e){u=""+e}})),Object.defineProperty(o,"pauseOnExit",n({},l,{get:function(){return d},set:function(e){d=!!e}})),Object.defineProperty(o,"startTime",n({},l,{get:function(){return h},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");h=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",n({},l,{get:function(){return f},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");f=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",n({},l,{get:function(){return c},set:function(e){c=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",n({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",n({},l,{get:function(){return v},set:function(t){var i=function(t){return r(e,t)}(t);if(!1===i)throw new SyntaxError("An invalid or illegal string was specified.");v=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",n({},l,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",n({},l,{get:function(){return p},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");p=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",n({},l,{get:function(){return y},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",n({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},l,{get:function(){return T},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return A},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");A=t,this.hasBeenReset=!0}})),o.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),Mu=function(){function e(){}return e.prototype.decode=function(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))},e}();function xu(e){function t(e,t,r,i){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(i||0)}var r=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}var Fu=function(){function e(){this.values=Object.create(null)}var t=e.prototype;return t.set=function(e,t){this.get(e)||""===t||(this.values[e]=t)},t.get=function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t},t.has=function(e){return e in this.values},t.alt=function(e,t,r){for(var i=0;i<r.length;++i)if(t===r[i]){this.set(e,t);break}},t.integer=function(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))},t.percent=function(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){var r=parseFloat(t);if(r>=0&&r<=100)return this.set(e,r),!0}return!1},e}();function Nu(e,t,r,i){var n=i?e.split(i):[e];for(var a in n)if("string"==typeof n[a]){var s=n[a].split(r);2===s.length&&t(s[0],s[1])}}var Bu=new Ou(0,0,""),Uu="middle"===Bu.align?"middle":"center";function Gu(e,t,r){var i=e;function n(){var t=xu(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function a(){e=e.replace(/^\s+/,"")}if(a(),t.startTime=n(),a(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.slice(3),a(),t.endTime=n(),a(),function(e,t){var i=new Fu;Nu(e,(function(e,t){var n;switch(e){case"region":for(var a=r.length-1;a>=0;a--)if(r[a].id===t){i.set(e,r[a].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":n=t.split(","),i.integer(e,n[0]),i.percent(e,n[0])&&i.set("snapToLines",!1),i.alt(e,n[0],["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",Uu,"end"]);break;case"position":n=t.split(","),i.percent(e,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",Uu,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",Uu,"end","left","right"])}}),/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");var n=i.get("line","auto");"auto"===n&&-1===Bu.line&&(n=-1),t.line=n,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",Uu);var a=i.get("position","auto");"auto"===a&&50===Bu.position&&(a="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=a}(e,t)}function Ku(e){return e.replace(/<br(?: \/)?>/gi,"\n")}var Vu=function(){function e(){this.state="INITIAL",this.buffer="",this.decoder=new Mu,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var t=e.prototype;return t.parse=function(e){var t=this;function r(){var e=t.buffer,r=0;for(e=Ku(e);r<e.length&&"\r"!==e[r]&&"\n"!==e[r];)++r;var i=e.slice(0,r);return"\r"===e[r]&&++r,"\n"===e[r]&&++r,t.buffer=e.slice(r),i}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{var i="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;var n=(i=r()).match(/^()?WEBVTT([ \t].*)?$/);if(null==n||!n[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}for(var a=!1;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:i=r(),t.state){case"HEADER":/:/.test(i)?Nu(i,(function(e,t){}),/:/):i||(t.state="ID");continue;case"NOTE":i||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(i)){t.state="NOTE";break}if(!i)continue;if(t.cue=new Ou(0,0,""),t.state="CUE",-1===i.indexOf("--\x3e")){t.cue.id=i;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Gu(i,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":var s=-1!==i.indexOf("--\x3e");if(!i||s&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=i;continue;case"BADCUE":i||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this},t.flush=function(){var e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this},e}(),Hu=/\r\n|\n\r|\n|\r/g,Yu="Missing initPTS for VTT ";function ju(e,t,r){return fu(e.toString())+fu(t.toString())+fu(r)}function Wu(e,t,r,i,n,a,s){var o,l,u,d=new Vu,h=Oe(new Uint8Array(e)).trim().replace(Hu,"\n").split("\n"),f=[],c=t?(o=t.baseTime,void 0===(l=t.timescale)&&(l=1),Ga(o,Ua,1/l)):0,g="00:00.000",v=0,m=0,p=!1,y=!0;d.oncue=function(e){var a=r[i],s=r.ccOffset,o=(v-c)/9e4;if(p){if(null!=a&&a.new&&(s=r.ccOffset=a.start),o){if(!t)return void(u=new Error(Yu+"MPEGTS"));s=o-r.presentationOffset}}else{if(!t)return void(u=new Error(Yu+"without X-TIMESTAMP-MAP"));s=-t.baseTime/t.timescale}var l=e.endTime-e.startTime,d=Wa(9e4*(e.startTime+s-m),9e4*n)/9e4;e.startTime=Math.max(d,0),e.endTime=Math.max(d+l,0);var h=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(h)),e.id?i&&(e.id="hlsjscc"+i+"_"+e.id):e.id=ju(e.startTime,e.endTime,h),e.endTime>0&&f.push(e)},d.onparsingerror=function(e){u=e},d.onflush=function(){u?s(u):a(f)},h.forEach((function(e){if(y){if(e.startsWith("X-TIMESTAMP-MAP=")){y=!1,p=!0,e.slice(16).split(",").forEach((function(e){e.startsWith("LOCAL:")?g=e.slice(6):e.startsWith("MPEGTS:")&&(v=parseInt(e.slice(7)))}));try{m=function(e){var t=parseInt(e.slice(-3)),r=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(x(t)&&x(r)&&x(i)&&x(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+e);return t+=1e3*r,(t+=6e4*i)+36e5*n}(g)/1e3}catch(e){u=e}return}""===e&&(y=!1)}d.parse(e+"\n")})),d.flush()}var qu="stpp.ttml.im1t",Xu=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,zu=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Qu={left:"start",center:"center",right:"end",start:"start",end:"end"};function $u(e,t,r,i){var n=st(new Uint8Array(e),["mdat"]);if(0!==n.length){var a,s,o,u,d=n.map((function(e){return Oe(e)})),h=(a=t.baseTime,s=1,void 0===(o=t.timescale)&&(o=1),void 0===u&&(u=!1),Ga(a,s,1/o,u));try{d.forEach((function(e){return r(function(e,t){var r=(new DOMParser).parseFromString(e,"text/xml"),i=r.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");var n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:1},a=Object.keys(n).reduce((function(e,t){return e[t]=i.getAttribute("ttp:"+t)||n[t],e}),{});!i.getAttribute("ttp:tickRate")&&i.getAttribute("ttp:frameRate")&&(a.tickRate=Number(a.frameRate)*Number(a.subFrameRate));var s="preserve"!==i.getAttribute("xml:space"),o=Ju(Zu(i,"styling","style")),u=Ju(Zu(i,"layout","region")),d=Zu(i,"body","[begin]");return[].map.call(d,(function(e){var r=ed(e,s);if(!r||!e.hasAttribute("begin"))return null;var i=id(e.getAttribute("begin"),a),n=id(e.getAttribute("dur"),a),d=id(e.getAttribute("end"),a);if(null===i)throw rd(e);if(null===d){if(null===n)throw rd(e);d=i+n}var h=new Ou(i-t,d-t,r);h.id=ju(h.startTime,h.endTime,h.text);var f=function(e,t,r){var i="http://www.w3.org/ns/ttml#styling",n=null,a=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],s=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return s&&r.hasOwnProperty(s)&&(n=r[s]),a.reduce((function(r,a){var s=td(t,i,a)||td(e,i,a)||td(n,i,a);return s&&(r[a]=s),r}),{})}(u[e.getAttribute("region")],o[e.getAttribute("style")],o),c=f.textAlign;if(c){var g=Qu[c];g&&(h.lineAlign=g),h.align=c}return l(h,f),h})).filter((function(e){return null!==e}))}(e,h))}))}catch(e){i(e)}}else i(new Error("Could not parse IMSC1 mdat"))}function Zu(e,t,r){var i=e.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(r)):[]}function Ju(e){return e.reduce((function(e,t){var r=t.getAttribute("xml:id");return r&&(e[r]=t),e}),{})}function ed(e,t){return[].slice.call(e.childNodes).reduce((function(e,r,i){var n;return"br"===r.nodeName&&i?e+"\n":null!=(n=r.childNodes)&&n.length?ed(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent}),"")}function td(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function rd(e){return new Error("Could not parse ttml timestamp "+e)}function id(e,t){if(!e)return null;var r=xu(e);return null===r&&(Xu.test(e)?r=function(e,t){var r=Xu.exec(e),i=(0|r[4])+(0|r[5])/t.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+i/t.frameRate}(e,t):zu.test(e)&&(r=function(e,t){var r=zu.exec(e),i=Number(r[1]);switch(r[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return i/1e3;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}(e,t))),r}var nd=function(e){function t(t){var r;return(r=e.call(this,t,"subtitle-track-controller")||this).media=null,r.tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.queuedDefaultTrack=-1,r.useTextTrackPolling=!1,r.subtitlePollingInterval=-1,r._subtitleDisplay=!0,r.asyncPollTrackChange=function(){return r.pollTrackChange(0)},r.onTextTracksChanged=function(){if(r.useTextTrackPolling||self.clearInterval(r.subtitlePollingInterval),r.media&&r.hls.config.renderTextTracksNatively){var e,t=-1,i=!1;if(r.currentTrack){var n,a=null==(n=r.currentTrack.trackNode)?void 0:n.track.mode;"showing"===a?(t=r.trackId,i=!0):"hidden"===a&&(t=r.trackId)}if(!i)for(var s=0;s<r.tracksInGroup.length;s++){var o,l=null==(o=r.tracksInGroup[s].trackNode)?void 0:o.track.mode;if("showing"===l){t=s;break}t<0&&"hidden"===l&&(t=s)}t>-1&&(r._subtitleDisplay="showing"===(null==(e=r.tracksInGroup[t].trackNode)?void 0:e.track.mode)),r.setSubtitleTrack(t,!0)}},r.registerListeners(),r}d(t,e);var r=t.prototype;return r.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,e.prototype.destroy.call(this)},r.registerListeners=function(){var e=this.hls;e.on(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_PARSED,this.onManifestParsed,this),e.on(G.LEVEL_LOADING,this.onLevelLoading,this),e.on(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(G.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(G.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_PARSED,this.onManifestParsed,this),e.off(G.LEVEL_LOADING,this.onLevelLoading,this),e.off(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(G.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(G.ERROR,this.onError,this)},r.createTracksInGroup=function(){var e,t=this;if(this.media&&this.hls.config.renderTextTracksNatively){this.tracksInGroup.forEach((function(e){e.trackNode||(e.trackNode=jl(t.media,Wl(e),e.name,e.lang))}));var r=null==(e=this.currentTrack)||null==(e=e.trackNode)?void 0:e.track;"disabled"===(null==r?void 0:r.mode)&&(r.mode=this._subtitleDisplay?"showing":"hidden")}},r.onMediaAttached=function(e,t){var r=t.media;this.media=r;var i=this.trackId;this.queuedDefaultTrack>-1&&(i=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(i),this.createTracksInGroup(),this.useTextTrackPolling=!(r.textTracks&&"onchange"in r.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):r.textTracks.addEventListener("change",this.asyncPollTrackChange)},r.pollTrackChange=function(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)},r.onMediaDetaching=function(e,t){var r=this.media;if(r){var i=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,i||this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach((function(e){var t=e.trackNode;t&&(t.track.mode="hidden",t.remove(),e.trackNode=void 0)}))}},r.onManifestLoading=function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0},r.onManifestParsed=function(e,t){this.tracks=t.subtitleTracks},r.onSubtitleTrackLoaded=function(e,t){var r=t.id,i=t.groupId,n=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===i){var s=a.details;a.details=t.details,this.log("Subtitle track "+r+' "'+a.name+'" lang:'+a.lang+" group:"+i+" loaded ["+n.startSN+"-"+n.endSN+"]"),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Subtitle track with id:"+r+" and group:"+i+" not found in active group "+(null==a?void 0:a.groupId))},r.onLevelLoading=function(e,t){this.switchLevel(t.level)},r.onLevelSwitching=function(e,t){this.switchLevel(t.level)},r.switchLevel=function(e){var t=this,r=this.hls.levels[e];if(r){var i=r.subtitleGroups||null,n=this.groupIds,a=this.currentTrack;if(!i||(null==n?void 0:n.length)!==(null==i?void 0:i.length)||null!=i&&i.some((function(e){return-1===(null==n?void 0:n.indexOf(e))}))){this.groupIds=i;var s=[];if(this.tracks.forEach((function(e){(e.textCodec===qu?t.hls.config.enableIMSC1:t.hls.config.enableWebVTT)&&(!i||i.indexOf(e.groupId)>-1?(e.id=s.length,s.push(e)):e.trackNode&&(e.trackNode.remove(),e.trackNode=void 0))})),s.length===this.tracksInGroup.length){for(var o=!1,l=0;l<s.length;l++)if(s[l]!==this.tracksInGroup[l]){o=!0;break}if(!o)return}s.length&&this.selectDefaultTrack&&!s.some((function(e){return e.default}))&&(this.selectDefaultTrack=!1),this.tracksInGroup=s,this.trackId=-1,this.currentTrack=null;var u=this.hls.config.subtitlePreference;if(!a&&u){this.selectDefaultTrack=!1;var d=pr(u,s);if(d>-1)a=s[d];else{var h=pr(u,this.tracks);a=this.tracks[h]}}var f=this.findTrackId(a);-1===f&&a&&(f=this.findTrackId(null));var c={subtitleTracks:s};this.log("Updating subtitle tracks, "+s.length+' track(s) found in "'+(null==i?void 0:i.join(","))+'" group-id'),this.hls.trigger(G.SUBTITLE_TRACKS_UPDATED,c),this.setSubtitleTrack(f),this.createTracksInGroup()}}},r.findTrackId=function(e){for(var t=this.tracksInGroup,r=this.selectDefaultTrack,i=0;i<t.length;i++){var n=t[i];if((!r||n.default)&&(r||e)&&(!e||yr(n,e)))return i}if(e){for(var a=0;a<t.length;a++){var s=t[a];if(ps(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return a}for(var o=0;o<t.length;o++){var l=t[o];if(ps(e.attrs,l.attrs,["LANGUAGE"]))return o}}return-1},r.onError=function(e,t){!t.fatal&&t.context&&t.context.type===j&&t.context.id===this.trackId&&Ar(t.context.groupId,this.groupIds)&&this.checkRetry(t)},r.setSubtitleOption=function(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1,!0),null;var t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){var r=this.currentTrack;if(r&&yr(e,r))return r;var i=pr(e,this.tracksInGroup);if(i>-1){var n=this.tracksInGroup[i];return this.setSubtitleTrack(i,!0),n}if(r)return null;var a=pr(e,t);if(a>-1)return t[a]}}return null},r.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)},r.loadingPlaylist=function(t,r){e.prototype.loadingPlaylist.call(this,t,r);var i=t.id,n=t.groupId,a=this.getUrlWithDirectives(t.url,r),s=t.details,o=null==s?void 0:s.age;this.log("Loading subtitle "+i+' "'+t.name+'" lang:'+t.lang+" group:"+n+(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"")+(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):"")+" "+a),this.hls.trigger(G.SUBTITLE_TRACK_LOADING,{url:a,id:i,groupId:n,deliveryDirectives:r||null,track:t})},r.toggleTrackModes=function(){var e=this;if(this.media&&this.hls.config.renderTextTracksNatively){var t=this.currentTrack;this.tracksInGroup.forEach((function(r){if(r.trackNode){var i=r===t?e._subtitleDisplay?"showing":"hidden":"disabled",n=r.trackNode.track;n.mode!==i&&(n.mode=i)}}))}},r.setSubtitleTrack=function(e,t){void 0===t&&(t=!1);var r=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=r.length||!x(e))this.warn("Invalid subtitle track id: "+e);else{var i=this.currentTrack,n=r[e]||null;if(this.trackId=e,this.currentTrack=n,t&&this.toggleTrackModes(),n){var a=!!n.details&&!n.details.live;if(n!==i||!a){this.log("Switching to subtitle-track "+e+(n?' "'+n.name+'" lang:'+n.lang+" group:"+n.groupId:""));var s=n.id,o=n.groupId,l=void 0===o?"":o,u=n.name,d=n.type,h=n.url;this.hls.trigger(G.SUBTITLE_TRACK_SWITCH,{id:s,groupId:l,name:u,type:d,url:h});var f=this.switchParams(n.url,null==i?void 0:i.details,n.details);this.loadPlaylist(f)}}else i&&this.hls.trigger(G.SUBTITLE_TRACK_SWITCH,{id:e})}},a(t,[{key:"subtitleDisplay",get:function(){return this._subtitleDisplay},set:function(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}},{key:"allSubtitleTracks",get:function(){return this.tracks}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}}])}(vs),ad={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},sd=function(e){return String.fromCharCode(ad[e]||e)},od=15,ld=42,ud={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},dd={17:2,18:4,21:6,22:8,23:10,19:13,20:15},hd={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},fd={25:2,26:4,29:6,30:8,31:10,27:13,28:15},cd=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],gd=function(){function e(){this.time=null,this.verboseLevel=0}return e.prototype.log=function(e,t){if(this.verboseLevel>=e){var r="function"==typeof t?t():t;Le.log(this.time+" ["+e+"] "+r)}},e}(),vd=function(e){for(var t=[],r=0;r<e.length;r++)t.push(e[r].toString(16));return t},md=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1}),pd=function(){function e(){this.styles=md}var t=e.prototype;return t.reset=function(){this.styles=md},t.setStyles=function(e){var t=this.styles,r=Object.prototype.hasOwnProperty;this.styles={foreground:r.call(e,"foreground")?e.foreground:t.foreground,underline:r.call(e,"underline")?e.underline:t.underline,italics:r.call(e,"italics")?e.italics:t.italics,background:r.call(e,"background")?e.background:t.background,flash:r.call(e,"flash")?e.flash:t.flash}},t.toString=function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash},a(e,[{key:"foreground",get:function(){return this.styles.foreground},set:function(e){var t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}},{key:"underline",get:function(){return this.styles.underline},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}},{key:"italics",get:function(){return this.styles.italics},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}},{key:"background",get:function(){return this.styles.background},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}},{key:"flash",get:function(){return this.styles.flash},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}}])}(),yd=function(){function e(){this.uchar=" ",this.penState=new pd}var t=e.prototype;return t.reset=function(){this.uchar=" ",this.penState.reset()},t.setChar=function(e,t){this.uchar=e,this.penState.styles=t.styles},t.setPenState=function(e){this.penState.styles=e.styles},t.copy=function(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles},e}(),Ed=function(){function e(e){this.chars=[],this.pos=0,this.currPenState=new pd,this.cueStartTime=null,this.logger=void 0;for(var t=0;t<ld;t++)this.chars.push(new yd);this.logger=e}var t=e.prototype;return t.equals=function(e){for(var t=this.chars,r=e.chars,i=0;i<ld;i++){var n=t[i],a=r[i];if(n.uchar!==a.uchar)return!1;var s=n.penState.styles,o=a.penState.styles;if(s!==o&&(s.foreground!==o.foreground||s.underline!==o.underline||s.italics!==o.italics||s.background!==o.background||s.flash!==o.flash))return!1}return!0},t.copy=function(e){for(var t=0;t<ld;t++)this.chars[t].copy(e.chars[t])},t.isEmpty=function(){for(var e=this.chars,t=0;t<ld;t++){var r=e[t];if(" "!==r.uchar)return!1;var i=r.penState.styles;if(i!==md&&("white"!==i.foreground||i.underline||i.italics||"black"!==i.background||i.flash))return!1}return!0},t.setCursor=function(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>=ld&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=41)},t.moveCursor=function(e){var t=Math.min(this.pos+e,ld);if(e>1)for(var r=this.pos+1;r<t;r++)this.chars[r].setPenState(this.currPenState);this.setCursor(t)},t.backSpace=function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)},t.insertChar=function(e){var t=this;e>=144&&this.backSpace();var r=sd(e);this.pos>=ld?this.logger.log(0,(function(){return"Cannot insert "+e.toString(16)+" ("+r+") at position "+t.pos+". Skipping it!"})):(this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1))},t.clearFromPos=function(e){var t;for(t=e;t<ld;t++)this.chars[t].reset()},t.clear=function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},t.clearToEndOfRow=function(){this.clearFromPos(this.pos)},t.getTextString=function(){for(var e=[],t=!0,r=0;r<ld;r++){var i=this.chars[r].uchar;" "!==i&&(t=!1),e.push(i)}return t?"":e.join("")},t.setPenStyles=function(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)},e}(),Td=function(){function e(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(var t=0;t<od;t++)this.rows.push(new Ed(e));this.logger=e}var t=e.prototype;return t.reset=function(){for(var e=0;e<od;e++)this.rows[e].clear();this.currRow=14},t.equals=function(e){for(var t=!0,r=0;r<od;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t},t.copy=function(e){for(var t=0;t<od;t++)for(var r=this.rows[t].chars,i=e.rows[t].chars,n=0;n<ld;n++){var a=r[n],s=i[n];a.uchar=s.uchar,a.penState.styles=s.penState.styles}},t.isEmpty=function(){for(var e=!0,t=0;t<od;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e},t.backSpace=function(){this.rows[this.currRow].backSpace()},t.clearToEndOfRow=function(){this.rows[this.currRow].clearToEndOfRow()},t.insertChar=function(e){this.rows[this.currRow].insertChar(e)},t.setPen=function(e){this.rows[this.currRow].setPenStyles(e)},t.moveCursor=function(e){this.rows[this.currRow].moveCursor(e)},t.setCursor=function(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)},t.setPAC=function(e){this.logger.log(2,(function(){return"pacData = "+cr(e)}));var t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(var r=0;r<od;r++)this.rows[r].clear();var i=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){var a=n.rows[i].cueStartTime,s=this.logger.time;if(null!==a&&null!==s&&a<s)for(var o=0;o<this.nrRollUpRows;o++)this.rows[t-this.nrRollUpRows+o+1].copy(n.rows[i+o])}}this.currRow=t;var l=this.rows[this.currRow];if(null!==e.indent){var u=e.indent,d=Math.max(u-1,0);l.setCursor(e.indent),e.color=l.chars[d].penState.foreground}var h={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(h)},t.setBkgData=function(e){this.logger.log(2,(function(){return"bkgData = "+cr(e)})),this.backSpace(),this.setPen(e),this.insertChar(32)},t.setRollUpRows=function(e){this.nrRollUpRows=e},t.rollUp=function(){var e=this;if(null!==this.nrRollUpRows){this.logger.log(1,(function(){return e.getDisplayText()}));var t=this.currRow+1-this.nrRollUpRows,r=this.rows.splice(t,1)[0];r.clear(),this.rows.splice(this.currRow,0,r),this.logger.log(2,"Rolling up")}else this.logger.log(3,"roll_up but nrRollUpRows not set yet")},t.getDisplayText=function(e){e=e||!1;for(var t=[],r="",i=-1,n=0;n<od;n++){var a=this.rows[n].getTextString();a&&(i=n+1,e?t.push("Row "+i+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r},t.getTextAndFormat=function(){return this.rows},e}(),Sd=function(){function e(e,t,r){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 Td(r),this.nonDisplayedMemory=new Td(r),this.lastOutputScreen=new Td(r),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}var t=e.prototype;return t.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},t.getHandler=function(){return this.outputFilter},t.setHandler=function(e){this.outputFilter=e},t.setPAC=function(e){this.writeScreen.setPAC(e)},t.setBkgData=function(e){this.writeScreen.setBkgData(e)},t.setMode=function(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(function(){return"MODE="+e})),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)},t.insertChars=function(e){for(var t=this,r=0;r<e.length;r++)this.writeScreen.insertChar(e[r]);var i=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(function(){return i+": "+t.writeScreen.getDisplayText(!0)})),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(function(){return"DISPLAYED: "+t.displayedMemory.getDisplayText(!0)})),this.outputDataUpdate())},t.ccRCL=function(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")},t.ccBS=function(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())},t.ccAOF=function(){},t.ccAON=function(){},t.ccDER=function(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()},t.ccRU=function(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)},t.ccFON=function(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})},t.ccRDC=function(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")},t.ccTR=function(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")},t.ccRTD=function(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")},t.ccEDM=function(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)},t.ccCR=function(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)},t.ccENM=function(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()},t.ccEOC=function(){var e=this;if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(function(){return"DISP: "+e.displayedMemory.getDisplayText()}))}this.outputDataUpdate(!0)},t.ccTO=function(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)},t.ccMIDROW=function(e){var t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{var r=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}this.logger.log(2,"MIDROW: "+cr(t)),this.writeScreen.setPen(t)},t.outputDataUpdate=function(e){void 0===e&&(e=!1);var t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?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.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))},t.cueSplitAtTime=function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))},e}(),Ad=function(){function e(e,t,r){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new gd,this.field=e,this.outputFilters=[null,t,r]}var t=e.prototype;return t.getHandler=function(e){return this.outputFilters[e]},t.setHandler=function(e,t){var r;this.outputFilters[e]=t,null==(r=this.channels[e])||r.setHandler(t)},t.getChannel=function(e){var t=this.channels[e];return t||(t=this.channels[e]=new Sd(this.field+e-1,this.outputFilters[e],this.logger)),t},t.addData=function(e,t){var r=this;this.logger.time=e;for(var i=function(e){var i=127&t[e],n=127&t[e+1],a=!1,s=null;if(0===i&&0===n)return 0;r.logger.log(3,(function(){return"["+vd([t[e],t[e+1]])+"] -> ("+vd([i,n])+")"}));var o=r.cmdHistory;if(i>=16&&i<=31){if(function(e,t,r){return r.a===e&&r.b===t}(i,n,o))return Id(null,null,o),r.logger.log(3,(function(){return"Repeated command ("+vd([i,n])+") is dropped"})),0;Id(i,n,r.cmdHistory),(a=r.parseCmd(i,n))||(a=r.parseMidrow(i,n)),a||(a=r.parsePAC(i,n)),a||(a=r.parseBackgroundAttributes(i,n))}else Id(null,null,o);if(!a&&(s=r.parseChars(i,n))){var l=r.currentChannel;l&&l>0?r.getChannel(l).insertChars(s):r.logger.log(2,"No channel found yet. TEXT-MODE?")}a||s||r.logger.log(2,(function(){return"Couldn't parse cleaned data "+vd([i,n])+" orig: "+vd([t[e],t[e+1]])}))},n=0;n<t.length;n+=2)i(n)},t.parseCmd=function(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;var r=20===e||21===e||23===e?1:2,i=this.getChannel(r);return 20===e||21===e||28===e||29===e?32===t?i.ccRCL():33===t?i.ccBS():34===t?i.ccAOF():35===t?i.ccAON():36===t?i.ccDER():37===t?i.ccRU(2):38===t?i.ccRU(3):39===t?i.ccRU(4):40===t?i.ccFON():41===t?i.ccRDC():42===t?i.ccTR():43===t?i.ccRTD():44===t?i.ccEDM():45===t?i.ccCR():46===t?i.ccENM():47===t&&i.ccEOC():i.ccTO(t-32),this.currentChannel=r,!0},t.parseMidrow=function(e,t){var r=0;if((17===e||25===e)&&t>=32&&t<=47){if((r=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var i=this.channels[r];return!!i&&(i.ccMIDROW(t),this.logger.log(3,(function(){return"MIDROW ("+vd([e,t])+")"})),!0)}return!1},t.parsePAC=function(e,t){var r;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(16===e||24===e)&&t>=64&&t<=95))return!1;var i=e<=23?1:2;return r=t>=64&&t<=95?1===i?ud[e]:hd[e]:1===i?dd[e]:fd[e],this.getChannel(i).setPAC(this.interpretPAC(r,t)),this.currentChannel=i,!0},t.interpretPAC=function(e,t){var r,i={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,i.underline=1==(1&r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i},t.parseChars=function(e,t){var r,i,n=null,a=null;return e>=25?(r=2,a=e-8):(r=1,a=e),a>=17&&a<=19?(i=17===a?t+80:18===a?t+112:t+144,this.logger.log(2,(function(){return"Special char '"+sd(i)+"' in channel "+r})),n=[i]):e>=32&&e<=127&&(n=0===t?[e]:[e,t]),n&&this.logger.log(3,(function(){return"Char codes = "+vd(n).join(",")})),n},t.parseBackgroundAttributes=function(e,t){var r;if(!((16===e||24===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=45&&t<=47))return!1;var i={};16===e||24===e?(r=Math.floor((t-32)/2),i.background=cd[r],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));var n=e<=23?1:2;return this.getChannel(n).setBkgData(i),!0},t.reset=function(){for(var e=0;e<Object.keys(this.channels).length;e++){var t=this.channels[e];t&&t.reset()}Id(null,null,this.cmdHistory)},t.cueSplitAtTime=function(e){for(var t=0;t<this.channels.length;t++){var r=this.channels[t];r&&r.cueSplitAtTime(e)}},e}();function Id(e,t,r){r.a=e,r.b=t}var Ld=function(){function e(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}var t=e.prototype;return t.dispatchCue=function(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)},t.newCue=function(e,t,r){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)},t.reset=function(){this.cueRanges=[],this.startTime=null},e}(),Rd=function(){function e(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.cueCache={},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(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(G.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(G.FRAG_LOADING,this.onFragLoading,this),e.on(G.FRAG_LOADED,this.onFragLoaded,this),e.on(G.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(G.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(G.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(G.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(G.BUFFER_APPENDED,this.onBufferAppended,this),e.on(G.BUFFER_FLUSHING,this.onBufferFlushing,this)}var t=e.prototype;return t.destroy=function(){var e=this.hls;e.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(G.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(G.FRAG_LOADING,this.onFragLoading,this),e.off(G.FRAG_LOADED,this.onFragLoaded,this),e.off(G.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(G.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(G.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(G.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(G.BUFFER_APPENDED,this.onBufferAppended,this),e.off(G.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0},t.initCea608Parsers=function(){var e=new Ld(this,"textTrack1"),t=new Ld(this,"textTrack2"),r=new Ld(this,"textTrack3"),i=new Ld(this,"textTrack4");this.cea608Parser1=new Ad(1,e,t),this.cea608Parser2=new Ad(3,r,i)},t.addCues=function(e,t,r,i,n){for(var a,s,o,l,u=!1,d=n.length;d--;){var h=n[d],f=(a=h[0],s=h[1],o=t,l=r,Math.min(s,l)-Math.max(a,o));if(f>=0&&(h[0]=Math.min(h[0],t),h[1]=Math.max(h[1],r),u=!0,f/(r-t)>.5))return}if(u||n.push([t,r]),this.config.renderTextTracksNatively){var c=this.cueCache[e];if(c){var g=this.Cues.newCue(null,t,r,i);g.length&&c.push.apply(c,g)}else{var v=this.captionsTracks[e].track;this.Cues.newCue(v,t,r,i)}}else{var m,p=this.Cues.newCue(null,t,r,i),y=null==(m=this.captionsProperties[e])?void 0:m.media;this.hls.trigger(G.CUES_PARSED,{type:"captions",cues:p,track:e,closedCaptions:y})}},t.onInitPtsFound=function(e,t){var r=this,i=t.id,n=t.timestampOffsets,a=this.unparsedVttFrags;i===$.MAIN&&(this.initPTS=n),a.length&&(this.unparsedVttFrags=[],a.forEach((function(e){r.initPTS[e.frag.cc]?r.onFragLoaded(G.FRAG_LOADED,e):r.hls.trigger(G.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})})))},t.createCaptionsTrack=function(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)},t.createNativeTrack=function(e){if(!this.captionsTracks[e]){var t=this.captionsProperties,r=this.captionsTracks,i=this.cueCache,n=this.media,a=t[e],s=a.label,o=a.languageCode;n&&(i[e]=[],r[e]=jl(n,"captions",s,o,"hidden"))}},t.createNonNativeTrack=function(e){if(!this.nonNativeCaptionsTracks[e]){var t=this.captionsProperties[e];if(t){var r={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(G.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}}},t.onMediaAttaching=function(e,t){this.media=t.media},t.onMediaDetaching=function(e,t){var r=!!t.transferMedia;if(this.media=null,!r){if(this.config.renderTextTracksNatively){var i=this.captionsTracks,n=this.cueCache;for(var a in i)i[a].remove(),delete n[a]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}},t.onManifestLoading=function(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())},t.onSubtitleTracksUpdated=function(e,t){var r=t.subtitleTracks||[];if(r.length&&!this.config.renderTextTracksNatively&&!ms(this.tracks,r)){var i=r.map((function(e){return{label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}}));this.hls.trigger(G.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:i})}this.tracks=r},t.onManifestLoaded=function(e,t){var r=this;this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((function(e){var t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(t){var i="textTrack"+t[1],n=r.captionsProperties[i];n&&(n.label=e.name,e.lang&&(n.languageCode=e.lang),n.media=e)}}))},t.closedCaptionsForLevel=function(e){var t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]},t.onFragLoading=function(e,t){if(this.enabled&&t.frag.type===$.MAIN){var r,i,n=this.cea608Parser1,a=this.cea608Parser2,s=this.lastSn,o=t.frag,l=o.cc,u=o.sn,d=null!=(r=null==(i=t.part)?void 0:i.index)?r:-1;n&&a&&(u!==s+1||u===s&&d!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=u,this.lastPartIndex=d}},t.onFragLoaded=function(e,t){var r,i=t.frag,n=t.payload;if(i.level<this.tracks.length&&i.type===$.SUBTITLE)if(n.byteLength||null!=(r=i.initSegment)&&null!=(r=r.data)&&r.byteLength){var a=i.decryptdata,s="stats"in t;if(null==a||!a.encrypted||s){var o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),(null==o?void 0:o.textCodec)===qu?this._parseIMSC1(t):this._parseVTTs(t)}}else{var u="part"in t?t.part:null;this.hls.trigger(G.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:u,error:new Error("Empty subtitle payload")})}},t._parseIMSC1=function(e){var t=this,r=e.frag,i=e.payload,n="part"in e?e.part:null,a=this.hls;$u(i,this.initPTS[r.cc],(function(e){t._appendCues(e,r.level),a.trigger(G.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r,part:n})}),(function(e){a.logger.log("Cannot parse IMSC1 (sn: "+r.sn+" @"+r.start+"): "+e),a.trigger(G.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,part:n,error:e})}))},t._parseVTTs=function(e){var t,r=this,i=e.frag,n=e.payload,a="part"in e?e.part:null,s=this.initPTS,o=this.unparsedVttFrags,l=s.length-1;if(s[i.cc]||-1!==l){var u=this.hls,d=null==(t=i.initSegment)?void 0:t.data;Wu(d?Et(d,new Uint8Array(n)).buffer:n,this.initPTS[i.cc],this.vttCCs,i.cc,(a&&!d?a:i).start,(function(e){r._appendCues(e,i.level),u.trigger(G.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i,part:a})}),(function(t){var n=t.message.startsWith("Missing initPTS");u.logger.log((n?"Deferred parsing of":"Cannot parse")+" VTT cue (sn: "+i.sn+" @"+i.start+"): "+t),n?o.push(e):(r.config.enableIMSC1&&r._fallbackToIMSC1(e),u.trigger(G.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:a,error:t}))}))}else o.push(e)},t._fallbackToIMSC1=function(e){var t=this,r=e.frag,i=e.payload,n=this.tracks[r.level];n.textCodec||$u(i,this.initPTS[r.cc],(function(){n.textCodec=qu,t._parseIMSC1(e)}),(function(){n.textCodec="wvtt"}))},t._appendCues=function(e,t){var r=this.hls;if(this.config.renderTextTracksNatively){var i,n=null==(i=this.tracks[t].trackNode)?void 0:i.track;if(!n||"disabled"===n.mode)return;e.forEach((function(e){return ql(n,e)}))}else{var a=this.tracks[t];if(!a)return;var s=a.default?"default":"subtitles"+t;r.trigger(G.CUES_PARSED,{type:"subtitles",cues:e,track:s,subtitleTrack:a})}},t.onFragDecrypted=function(e,t){t.frag.type===$.SUBTITLE&&this.onFragLoaded(G.FRAG_LOADED,t)},t.onSubtitleTracksCleared=function(){this.tracks=[],this.captionsTracks={}},t.onFragParsingUserdata=function(e,t){if(this.enabled&&this.config.enableCEA708Captions){var r=t.frag,i=t.samples;if(r.type!==$.MAIN||"NONE"!==this.closedCaptionsForLevel(r))for(var n=0;n<i.length;n++){var a=i[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();var s=this.extractCea608Data(a);this.cea608Parser1.addData(i[n].pts,s[0]),this.cea608Parser2.addData(i[n].pts,s[1])}}}},t.onBufferAppended=function(e,t){if(this.config.renderTextTracksNatively){var r,i=t.type,n=t.timeRanges;if("video"===i&&null!=(r=n[i])&&r.length){var a=this.captionsTracks,s=this.cueCache;Object.keys(s).forEach((function(e){var t,r=null==(t=a[e])?void 0:t.track;if(r)for(var i=s[e],n=0;n<i.length;n++)ql(r,i[n]);delete s[e]}))}}},t.onBufferFlushing=function(e,t){var r=t.startOffset,i=t.endOffset,n=t.endOffsetSubtitles,a=t.type,s=this.media;if(s&&!(s.currentTime<i)){if(!a||"video"===a){var o=this.captionsTracks,l=this.cueCache;Object.keys(o).forEach((function(e){return Xl(o[e].track,r,i)})),Object.keys(l).forEach((function(e){for(var t=l[e],n=t.length;n--;){var a=t[n];a.startTime>=r&&a.endTime<=i&&t.splice(n,1)}}))}this.config.renderTextTracksNatively&&0===r&&void 0!==n&&this.tracks.forEach((function(e){var t,i=null==(t=e.trackNode)?void 0:t.track;i&&Xl(i,r,n)}))}},t.extractCea608Data=function(e){for(var t=[[],[]],r=31&e[0],i=2,n=0;n<r;n++){var a=e[i++],s=127&e[i++],o=127&e[i++];if((0!==s||0!==o)&&0!=(4&a)){var l=3&a;0!==l&&1!==l||(t[l].push(s),t[l].push(o))}}return t},e}(),bd=/\s/,kd={newCue:function(e,t,r,i){for(var n,a,s,o,l,u=[],d=self.VTTCue||self.TextTrackCue,h=0;h<i.rows.length;h++)if(s=!0,o=0,l="",!(n=i.rows[h]).isEmpty()){for(var f,c=0;c<n.chars.length;c++)bd.test(n.chars[c].uchar)&&s?o++:(l+=n.chars[c].uchar,s=!1);n.cueStartTime=t,t===r&&(r+=1e-4),o>=16?o--:o++;var g=Ku(l.trim()),v=ju(t,r,g);null!=e&&null!=(f=e.cues)&&f.getCueById(v)||((a=new d(t,r,g)).id=v,a.line=h+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*o/32)),u.push(a))}return e&&u.length&&(u.sort((function(e,t){return"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line})),u.forEach((function(t){return ql(e,t)}))),u}},Dd=function(){function e(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new K}var t=e.prototype;return t.destroy=function(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null},t.load=function(e,t,r){var i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.loadInternal()},t.abort=function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())},t.loadtimeout=function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(fe(e,this.stats.retry,!0))this.retry(e);else{var t;Le.warn("timeout while loading "+(null==(t=this.context)?void 0:t.url));var r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}},t.retry=function(e){var t=this,r=this.context,i=this.stats;this.retryDelay=de(e,i.retry),i.retry++,Le.warn((status?"HTTP Status "+status:"Timeout")+" while loading "+(null==r?void 0:r.url)+", retrying "+i.retry+"/"+e.maxNumRetry+" in "+this.retryDelay+"ms"),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout((function(){return t.loadInternal()}),this.retryDelay)},e}(),Pd=/(\d+)-(\d+)\/(\d+)/,_d=function(e){function t(t){var r;return(r=e.call(this)||this).fetchSetup=void 0,r.request=null,r.response=null,r.controller=null,r.fetchSetup=t.fetchSetup||Cd,r}d(t,e);var r=t.prototype;return r.destroy=function(){this.request=null,e.prototype.destroy.call(this),this.response=null,this.controller=null,this.fetchSetup=null},r.abortInternal=function(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())},r.getNetworkDetails=function(){return this.response},r.resetInternalLoader=function(){this.response=null},r.loadInternal=function(){var e=this,t=this.config,r=this.context,i=this.stats;if(t&&r){i.loading.first=0,i.loaded=0,i.aborted=!1,this.controller=new self.AbortController;var n=function(e,t){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(l({},e.headers))};return e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),r}(r,this.controller.signal),a="arraybuffer"===r.responseType,s=a?"byteLength":"length",o=t.loadPolicy,u=o.maxTimeToFirstByteMs,d=o.maxLoadTimeMs;this.request=this.fetchSetup(r,n),self.clearTimeout(this.requestTimeout),t.timeout=u&&x(u)?u:d,this.requestTimeout=self.setTimeout((function(){e.loadtimeout()}),t.timeout),(rs(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((function(n){var s;e.response=n;var o=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(e.requestTimeout),t.timeout=d,e.requestTimeout=self.setTimeout((function(){e.loadtimeout()}),d-(o-i.loading.start)),!n.ok){var l=n.status,u=n.statusText;throw new wd(u||"fetch, bad network response",l,n)}i.loading.first=o,i.total=function(e){var t=e.get("Content-Range");if(t){var r=function(e){var t=Pd.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(x(r))return r}var i=e.get("Content-Length");if(i)return parseInt(i)}(n.headers)||i.total;var h=null==(s=e.callbacks)?void 0:s.onProgress;return h&&x(t.highWaterMark)?e.loadProgressively(n,i,r,t.highWaterMark,h):a?n.arrayBuffer():"json"===r.responseType?n.json():n.text()})).then((function(n){var a,o,l=e.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(e.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);var u=n[s];u&&(i.loaded=i.total=u);var d={url:l.url,data:n,code:l.status},h=null==(a=e.callbacks)?void 0:a.onProgress;h&&!x(t.highWaterMark)&&h(i,r,n,l),null==(o=e.callbacks)||o.onSuccess(d,i,r,l)})).catch((function(n){if(self.clearTimeout(e.requestTimeout),!i.aborted){var a,s=n&&n.code||0,o=n?n.message:null,l=t.loadPolicy.errorRetry;fe(l,i.retry,!1,{url:r.url,data:void 0,code:s})?e.retry(l):(Le.error(s+" while loading "+r.url),null==(a=e.callbacks)||a.onError({code:s,text:o},r,n?n.details:null,i))}}))}},r.getCacheAge=function(){var e=null;if(this.response){var t=this.response.headers.get("age");e=t?parseFloat(t):null}return e},r.getResponseHeader=function(e){return this.response?this.response.headers.get(e):null},r.loadProgressively=function(e,t,r,i,n){void 0===i&&(i=0);var a=new Nn,s=e.body.getReader(),o=function(){return s.read().then((function(s){if(s.done)return a.dataLength&&n(t,r,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=s.value,u=l.length;return t.loaded+=u,u<i||a.dataLength?(a.push(l),a.dataLength>=i&&n(t,r,a.flush().buffer,e)):n(t,r,l.buffer,e),o()})).catch((function(){return Promise.reject()}))};return o()},t}(Dd);function Cd(e,t){return new self.Request(e.url,t)}var wd=function(e){function t(t,r,i){var n;return(n=e.call(this,t)||this).code=void 0,n.details=void 0,n.code=r,n.details=i,n}return d(t,e),t}(E(Error)),Od=/^age:\s*[\d.]+\s*$/im,Md=function(e){function t(t){var r;return(r=e.call(this)||this).xhrSetup=void 0,r.loader=null,r.xhrSetup=t.xhrSetup||null,r}d(t,e);var r=t.prototype;return r.destroy=function(){e.prototype.destroy.call(this),this.loader=null,this.xhrSetup=null},r.abortInternal=function(){var e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))},r.getNetworkDetails=function(){return this.loader},r.resetInternalLoader=function(){this.loader=null},r.loadInternal=function(){var e=this,t=this.config,r=this.context;if(t&&r){var i=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;var a=this.xhrSetup;a?Promise.resolve().then((function(){if(e.loader===i&&!e.stats.aborted)return a.call(e,i,r.url,r)})).catch((function(t){if(e.loader===i&&!e.stats.aborted)return i.open("GET",r.url,!0),a.call(e,i,r.url,r)})).then((function(){e.loader!==i||e.stats.aborted||e.openAndSendXhr(i,r,t)})).catch((function(t){var a;null==(a=e.callbacks)||a.onError({code:i.status,text:t.message},r,i,n)})):this.openAndSendXhr(i,r,t)}},r.openAndSendXhr=function(e,t,r){e.readyState||e.open("GET",t.url,!0);var i=t.headers,n=r.loadPolicy,a=n.maxTimeToFirstByteMs,s=n.maxLoadTimeMs;if(i)for(var o in i)e.setRequestHeader(o,i[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),r.timeout=a&&x(a)?a:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()},r.readystatechange=function(){var e=this.context,t=this.loader,r=this.stats;if(e&&t){var i=t.readyState,n=this.config;if(!r.aborted&&i>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;var a=t.status,s="text"===t.responseType?t.responseText:null;if(a>=200&&a<300){var o=null!=s?s:t.response;if(null!=o){var l,u;r.loading.end=Math.max(self.performance.now(),r.loading.first);var d="arraybuffer"===t.responseType?o.byteLength:o.length;r.loaded=r.total=d,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first);var h=null==(l=this.callbacks)?void 0:l.onProgress;h&&h(r,e,o,t);var f={url:t.responseURL,data:o,code:a};return e.rangeEnd&&d!==e.rangeEnd-e.rangeStart&&Le.warn("Payload length "+d+" does not match requested Range: bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),void(null==(u=this.callbacks)||u.onSuccess(f,r,e,t))}}var c,g=n.loadPolicy.errorRetry;fe(g,r.retry,!1,{url:e.url,data:void 0,code:a})?this.retry(g):(Le.error(a+" while loading "+e.url),null==(c=this.callbacks)||c.onError({code:a,text:t.statusText},e,t,r))}}},r.loadprogress=function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)},r.getCacheAge=function(){var e=null;if(this.loader&&Od.test(this.loader.getAllResponseHeaders())){var t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e},r.getResponseHeader=function(e){return this.loader&&new RegExp("^"+e+":\\s*[\\d.]+\\s*$","im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null},t}(Dd),xd=c(c({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh: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,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:Md,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Yi,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,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,streamController:su,abrController:Lr,bufferController:Is,capLevelController:_s,errorController:Kr,fpsController:Ul,id3TrackController:Zl,gapController:Gl,latencyController:_u},{cueHandler:kd,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:Cu,subtitleTrackController:nd,timelineController:Rd,audioStreamController:gs,audioTrackController:ys,emeController:Fl,cmcdController:_l,contentSteeringController:Cl,iframeController:hu,interstitialsController:Pu});function Fd(e,t,r){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(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(void 0!==t.liveMaxUnchangedPlaylistRefresh){var i=t.liveMaxUnchangedPlaylistRefresh,n=(a=i,s=2,o=1/0,Math.max(s,Math.min(a,o)));n!==i&&r.warn('hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from '+i+" to "+n+"."),t.liveMaxUnchangedPlaylistRefresh=n}var a,s,o,l=Nd(e),u=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((function(e){var i=("level"===e?"playlist":e)+"LoadPolicy",n=void 0===t[i],a=[];u.forEach((function(r){var s=e+"Loading"+r,o=t[s];if(void 0!==o&&n){a.push(s);var u=l[i].default;switch(t[i]={default:u},r){case"TimeOut":u.maxLoadTimeMs=o,u.maxTimeToFirstByteMs=o;break;case"MaxRetry":u.errorRetry.maxNumRetry=o,u.timeoutRetry.maxNumRetry=o;break;case"RetryDelay":u.errorRetry.retryDelayMs=o,u.timeoutRetry.retryDelayMs=o;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=o,u.timeoutRetry.maxRetryDelayMs=o}}})),a.length&&r.warn('hls.js config: "'+a.join('", "')+'" setting(s) are deprecated, use "'+i+'": '+cr(t[i]))})),c(c({},l),t)}function Nd(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(Nd):Object.keys(e).reduce((function(t,r){return t[r]=Nd(e[r]),t}),{}):e}function Bd(e,t){var r=e.loader;r!==_d&&r!==Md?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}()&&(e.loader=_d,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Ud=function(e){function t(t,r){var i;return(i=e.call(this,t,"level-controller")||this)._levels=[],i._firstLevel=-1,i._maxAutoLevel=-1,i._startLevel=void 0,i.currentLevel=null,i.currentLevelIndex=-1,i.manualLevelIndex=-1,i.steering=void 0,i.lastABRSwitchTime=-1,i._iframeVariants=[],i.onParsedComplete=void 0,i.steering=r,i._registerListeners(),i}d(t,e);var r=t.prototype;return r._registerListeners=function(){var e=this.hls;e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(G.LEVEL_LOADED,this.onLevelLoaded,this),e.on(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(G.FRAG_BUFFERED,this.onFragBuffered,this),e.on(G.ERROR,this.onError,this)},r._unregisterListeners=function(){var e=this.hls;e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(G.LEVEL_LOADED,this.onLevelLoaded,this),e.off(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(G.FRAG_BUFFERED,this.onFragBuffered,this),e.off(G.ERROR,this.onError,this)},r.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),e.prototype.destroy.call(this)},r.stopLoad=function(){this._levels.forEach((function(e){e.loadError=0,e.fragmentError=0})),e.prototype.stopLoad.call(this)},r.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]},r.onManifestLoading=function(e,t){this.resetLevels()},r.onManifestLoaded=function(e,t){var r=this,i=this.hls.config.preferManagedMediaSource,n=[],a={},s={},o=!1,l=!1,u=!1,d=!1;t.levels.forEach((function(e){var t=e.attrs,h=Vd(e,i),f=e.audioCodec,c=e.videoCodec,g=e.imageCodec,v=e.width,m=e.height;if(h){o||(o=!(!v||!m)),l||(l=!!c),u||(u=!!f),d||(d=!!g);var p=t.CODECS,y=t["FRAME-RATE"],E=t["HDCP-LEVEL"],T=t["PATHWAY-ID"],S=t.RESOLUTION,A=t["VIDEO-RANGE"],I=(T||".")+"-"+e.bitrate+"-"+S+"-"+y+"-"+p+"-"+A+"-"+E;if(a[I])if(a[I].uri===e.url||e.attrs["PATHWAY-ID"])e.iframes||(a[I].addGroupId("audio",t.AUDIO),a[I].addGroupId("text",t.SUBTITLES));else{var L=s[I]+=1;e.attrs["PATHWAY-ID"]=new Array(L+1).join(".");var R=r.createLevel(e);a[I]=R,n.push(R)}else{var b=r.createLevel(e);a[I]=b,s[I]=1,n.push(b)}}else r.log('Some or all CODECS not supported "'+t.CODECS+'"')})),this.filterAndSortMediaOptions(n,t,o,l,u,d)},r.createLevel=function(e){var t=new dr(e),r=e.supplemental;if(null!=r&&r.videoCodec&&!Kd(r.videoCodec,this.hls.config.preferManagedMediaSource)){var i=new Error('SUPPLEMENTAL-CODECS not supported "'+r.videoCodec+'"');this.log(i.message),t.supportedResult=Zt(i,[])}return t},r.filterAndSortMediaOptions=function(e,t,r,i,n,a){var s,o=this,l=[],u=[],d=e,h=(null==(s=t.stats)?void 0:s.parsing)||{},f=this.hls.config.preferManagedMediaSource;if((r||i)&&n&&(d=d.filter((function(e){var t,r=e.videoCodec,i=e.videoRange,n=e.width,a=e.height;return(!!r||!(!n||!a))&&!!(t=i)&&nr.indexOf(t)>-1}))),i&&a&&(d=d.filter((function(e){return!e.imageCodec}))),0===d.length)return Promise.resolve().then((function(){if(o.hls){var e="no level with compatible codecs found in manifest",r=e;t.levels.length&&(r="one or more CODECS in variant not supported: "+cr(t.levels.map((function(e){return e.attrs.CODECS})).filter((function(e,t,r){return r.indexOf(e)===t}))),o.warn(r),e+=" ("+r+")");var i=new Error(e);o.hls.trigger(G.ERROR,{type:B.MEDIA_ERROR,details:U.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:i,reason:r})}})),void(h.end=performance.now());t.audioTracks&&Hd(l=t.audioTracks.filter((function(e){return!e.audioCodec||Gd(e.audioCodec,f)}))),t.subtitles&&Hd(u=t.subtitles);var c=d.slice(0);d.sort((function(e,t){if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return nr.indexOf(e.videoRange)-nr.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var i=Gt(e.videoCodec),n=Gt(t.videoCodec);if(i!==n)return n-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var a=Kt(e.codecSet),s=Kt(t.codecSet);if(a!==s)return s-a}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));var g=c[0];if(this.steering&&(d=this.steering.filterParsedLevels(d)).length!==c.length)for(var v=0;v<c.length;v++)if(c[v].pathwayId===d[0].pathwayId){g=c[v];break}this._levels=d;for(var m=0;m<d.length;m++)if(d[m]===g){var p;this._firstLevel=m;var y=g.bitrate,E=this.hls.bandwidthEstimate;if(this.log("manifest loaded, "+d.length+" level(s) found, first bitrate: "+y),void 0===(null==(p=this.hls.userConfig)?void 0:p.abrEwmaDefaultEstimate)){var T=Math.min(y,this.hls.config.abrEwmaDefaultEstimateMax);T>E&&E===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=T)}break}var S=t.iframeVariants.filter((function(e){return Vd(e,f)}));this._iframeVariants=S;var A=n&&!i,I=this.hls.config,L=!(!I.audioStreamController||!I.audioTrackController),R={levels:d,audioTracks:l,subtitleTracks:u,iframeVariants:S,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:i,altAudio:L&&!A&&l.some((function(e){return!!e.url}))};h.end=performance.now(),this.hls.trigger(G.MANIFEST_PARSED,R)},r.onError=function(e,t){!t.fatal&&t.context&&t.context.type===H&&t.context.level===this.level&&this.checkRetry(t)},r.onFragBuffered=function(e,t){var r=t.frag;if(r.type===$.MAIN){var i=r.elementaryStreams;if(!Object.keys(i).some((function(e){return!!i[e]})))return;var n=this._levels[r.level];null!=n&&n.loadError&&(this.log("Resetting level error count of "+n.loadError+" on frag buffered"),n.loadError=0)}},r.onLevelLoaded=function(e,t){var r,i,n=t.level,a=t.details,s=t.levelInfo;if(!s)return this.warn("Invalid level index "+n),void(null!=(i=t.deliveryDirectives)&&i.skip&&(a.deltaUpdateFailed=!0));if(s===this.currentLevel||t.withoutMultiVariant){0===s.fragmentError&&(s.loadError=0);var o=s.details;o===t.details&&o.advanced&&(o=void 0),this.playlistLoaded(n,t,o)}else null!=(r=t.deliveryDirectives)&&r.skip&&(a.deltaUpdateFailed=!0)},r.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)},r.loadingPlaylist=function(t,r){e.prototype.loadingPlaylist.call(this,t,r);var i=this.getUrlWithDirectives(t.uri,r),n=this.currentLevelIndex,a=t.attrs["PATHWAY-ID"],s=t.details,o=null==s?void 0:s.age;this.log("Loading level index "+n+(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"")+(a?" Pathway "+a:"")+(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):"")+" "+i),this.hls.trigger(G.LEVEL_LOADING,{url:i,level:n,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:r||null})},r.removeLevel=function(e){var t,r=this;if(1!==this._levels.length){var i=this._levels.filter((function(t,i){return i!==e||(r.steering&&r.steering.removeLevel(t),t===r.currentLevel&&(r.currentLevel=null,r.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((function(e){return e.level=-1}))),!1)}));In(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);var n=i.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(G.LEVELS_UPDATED,{levels:i})}},r.onLevelsUpdated=function(e,t){var r=t.levels;this._levels=r},r.checkMaxAutoUpdated=function(){var e=this.hls,t=e.autoLevelCapping,r=e.maxAutoLevel,i=e.maxHdcpLevel;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(G.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))},a(t,[{key:"iframeVariants",get:function(){return 0===this._iframeVariants.length?null:this._iframeVariants}},{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"loadLevelObj",get:function(){return this.currentLevel}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;if(0!==t.length){if(e<0||e>=t.length){var r=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(G.ERROR,{type:B.OTHER_ERROR,details:U.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:r,reason:r.message}),i)return;e=Math.min(e,t.length-1)}var n=this.currentLevelIndex,a=this.currentLevel,s=a?a.attrs["PATHWAY-ID"]:void 0,o=t[e],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,n!==e||!a||s!==l){this.log("Switching to level "+e+" ("+(o.height?o.height+"p ":"")+(o.videoRange?o.videoRange+" ":"")+(o.codecSet?o.codecSet+" ":"")+"@"+o.bitrate+")"+(l?" with Pathway "+l:"")+" from level "+n+(s?" with Pathway "+s:""));var u={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(G.LEVEL_SWITCHING,u);var d=o.details;if(!d||d.live){var h=this.switchParams(o.uri,null==a?void 0:a.details,d);this.loadPlaylist(h)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"pathways",get:function(){return this.steering?this.steering.pathways():[]}},{key:"pathwayPriority",get:function(){return this.steering?this.steering.pathwayPriority:null},set:function(e){if(this.steering){var t=this.steering.pathways(),r=e.filter((function(e){return-1!==t.indexOf(e)}));if(e.length<1)return void this.warn("pathwayPriority "+e+" should contain at least one pathway from list: "+t);this.steering.pathwayPriority=r}}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){var t=this.currentLevelIndex;if(-1===this.manualLevelIndex&&e!==t&&-1!==e){var r=this.hls.config.abrSwitchInterval;if(r>0){var i=performance.now(),n=i-this.lastABRSwitchTime,a=1e3*r;if(this.lastABRSwitchTime>-1&&n<a)return void this.warn("Preventing ABR level switch: "+t+" -> "+e+" ("+Math.round(n)+"ms < "+a+"ms / "+r+"s)");this.lastABRSwitchTime=i,this.log("Allowing ABR level switch: "+t+" -> "+e+" ("+Math.round(n)+"ms >= "+a+"ms / "+r+"s)")}}this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}}])}(vs);function Gd(e,t){return Nt(e,"audio",t)}function Kd(e,t){return Nt(e,"video",t)}function Vd(e,t){var r=e.audioCodec,i=e.videoCodec;r&&(e.audioCodec=r=Yt(r,t)||void 0),i&&(i=e.videoCodec=function(e){for(var t=e.split(","),r=0;r<t.length;r++){var i=t[r].split(".");i.length>2&&"avc1"===i[0]&&(t[r]="avc1."+parseInt(i[1]).toString(16)+("000"+parseInt(i[2]).toString(16)).slice(-4))}return t.join(",")}(i));var n=e.unknownCodecs;return!((null==n?void 0:n.length)||r&&!Gd(r,t)||i&&!Kd(i,t))}function Hd(e){var t={};e.forEach((function(e){var r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++}))}var Yd=function(e){function t(t,r){var i;return(i=e.call(this,"key-loader",r)||this).config=void 0,i.keyLoaderInfo={},i.emeController=null,i.config=t,i}d(t,e);var r=t.prototype;return r.abort=function(e){for(var t in this.keyLoaderInfo){var r=this.keyLoaderInfo[t].loader;if(r){var i;if(e&&e!==(null==(i=r.context)?void 0:i.frag.type))return;r.abort()}}},r.destroy=function(){for(var e in this.keyLoaderInfo){var t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}},r.loadClear=function(e,t,r){return this.emeController?this.emeController.loadClear(e,t,r):null},r.load=function(e,t){var r=this;return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then((function(i){return r.loadInternal(e,t,i)})):this.loadInternal(e,t)},r.loadInternal=function(e,t,r){var i=this;r&&e.setKeyFormat(r);var n=e.decryptdata;if(!n){var a=new Error(r?"Expected frag.decryptdata to be defined after setting format "+r:"Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: "+(this.emeController&&this.config.emeEnabled)+")");return Promise.reject(jd(e,U.KEY_LOAD_ERROR,a))}var s=e;switch(n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===n.keyFormat?this.loadKeyHTTP(s):t?t.then((function(){return i.loadKeyEME(s)})):this.loadKeyEME(s);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(s);default:return Promise.reject(jd(e,U.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'+n.method+'"')))}},r.loadKeyEME=function(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&null!=(t=e.initSegment)&&t.data){var r=function(e){var t=[];return vt(e,(function(e){return t.push(e.subarray(8,24))})),t}(e.initSegment.data);if(r.length){var i=r[0],n=e.decryptdata.uri;if(i.some((function(e){return 0!==e})))this.log("Using keyId found in init segment "+He(i)+" keyUri: "+n),qi.setKeyIdForUri(n,i);else{var a=qi.addKeyIdForUri(n);this.log("Patching empty keyId with "+He(a)+" keyUri: "+n),i=a}e.decryptdata.keyId=i}}return this.emeController.loadKey(e).then((function(){return{frag:e,keyInfo:{decryptdata:e.decryptdata}}}))}return Promise.reject(jd(e,U.KEY_LOAD_ERROR,new Error("emeEnabled with controller: "+(this.emeController&&this.config.emeEnabled)+")")))},r.loadKeyHTTP=function(e){var t=this,r=e.decryptdata,i=r.uri;if(!i)return Promise.reject(jd(e,U.KEY_LOAD_ERROR,new Error('Invalid key URI: "'+i+'"')));var n=this.keyLoaderInfo[i];if(n){if(n.decryptdata.key)return r.key=n.decryptdata.key,n.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:n});if(n.keyLoadPromise)return n.keyLoadPromise.then((function(t){return r.key=n.decryptdata.key,c(c({},t),{},{frag:e})}))}this.log("Loading"+(r.keyId?" keyId: "+He(r.keyId):"")+" URI: "+r.uri+" from "+e.type+" "+e.level);var a=this.config,s=new(0,a.loader)(a);e.keyLoader=s;var o=this.keyLoaderInfo[i]={decryptdata:r,keyLoadPromise:null,loader:s};return o.keyLoadPromise=new Promise((function(r,n){var l={type:q,keyInfo:o,frag:e,responseType:"arraybuffer",url:i},u=a.keyLoadPolicy.default,d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:function(e,i,a,s){var o=a.frag,l=a.keyInfo,u=a.url;if(!o.decryptdata||l!==t.keyLoaderInfo[u])return n(jd(o,U.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));l.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=l.loader=l.keyLoadPromise=null,r({frag:o,keyInfo:l})},onError:function(r,a,s,o){t.resetLoader(a),n(jd(e,U.KEY_LOAD_ERROR,new Error("HTTP Error "+r.code+" loading key "+r.text),s,c({url:i,data:void 0},r)))},onTimeout:function(r,i,a){t.resetLoader(i),n(jd(e,U.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),a))},onAbort:function(r,i,a){t.resetLoader(i),n(jd(e,U.INTERNAL_ABORTED,new Error("key loading aborted"),a))}};s.load(l,d,h)}))},r.resetLoader=function(e){var t=e.frag,r=e.keyInfo,i=e.url,n=r.loader;t.keyLoader===n&&(t.keyLoader=r.loader=r.keyLoadPromise=null),delete this.keyLoaderInfo[i],n&&n.destroy()},t}(pe);function jd(e,t,r,i,n){return void 0===t&&(t=U.KEY_LOAD_ERROR),new di({type:B.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:r,networkDetails:i||null})}function Wd(e){switch(e.type){case Y:return $.AUDIO;case j:return $.SUBTITLE;default:return $.MAIN}}function qd(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}var Xd=function(){function e(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}var t=e.prototype;return t.startLoad=function(e){},t.stopLoad=function(){this.destroyInternalLoaders()},t.registerListeners=function(){var e=this.hls;e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.LEVEL_LOADING,this.onLevelLoading,this),e.on(G.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(G.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(G.LEVELS_UPDATED,this.onLevelsUpdated,this)},t.unregisterListeners=function(){var e=this.hls;e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.LEVEL_LOADING,this.onLevelLoading,this),e.off(G.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(G.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(G.LEVELS_UPDATED,this.onLevelsUpdated,this)},t.createInternalLoader=function(e){var t=this.hls.config,r=t.pLoader,i=t.loader,n=new(r||i)(t);return this.loaders[e.type]=n,n},t.getInternalLoader=function(e){return this.loaders[e.type]},t.resetInternalLoader=function(e){this.loaders[e]&&delete this.loaders[e]},t.destroyInternalLoaders=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}},t.destroy=function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()},t.onManifestLoading=function(e,t){var r=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:V,url:r,deliveryDirectives:null,levelOrTrack:null})},t.onLevelLoading=function(e,t){var r=t.id,i=t.level,n=t.pathwayId,a=t.url,s=t.deliveryDirectives,o=t.levelInfo;this.load({id:r,level:i,pathwayId:n,responseType:"text",type:H,url:a,deliveryDirectives:s,levelOrTrack:o})},t.onAudioTrackLoading=function(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:Y,url:n,deliveryDirectives:a,levelOrTrack:s})},t.onSubtitleTrackLoading=function(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:j,url:n,deliveryDirectives:a,levelOrTrack:s})},t.onLevelsUpdated=function(e,t){var r=this.loaders[H];if(r){var i=r.context;i&&!t.levels.some((function(e){return e===i.levelOrTrack}))&&(r.abort(),delete this.loaders[H])}},t.load=function(e){var t,r,i,n=this,a=this.hls.config,s=this.getInternalLoader(e);if(s){var o=this.hls.logger,u=s.context;if((null==u?void 0:u.levelOrTrack)===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives))return void(u.url===e.url?o.log("[playlist-loader]: ignore "+e.url+" ongoing request"):o.log("[playlist-loader]: ignore "+e.url+" in favor of "+u.url));o.log("[playlist-loader]: aborting previous loader for type: "+e.type),s.abort()}if(r=e.type===V?a.manifestLoadPolicy.default:l({},a.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),x(null==(t=e.deliveryDirectives)?void 0:t.part)&&(e.type===H&&null!==e.level?i=this.hls.levels[e.level].details:e.type===Y&&null!==e.id?i=this.hls.audioTracks[e.id].details:e.type===j&&null!==e.id&&(i=this.hls.subtitleTracks[e.id].details),i)){var d=i.partTarget,h=i.targetduration;if(d&&h){var f=1e3*Math.max(3*d,.8*h);r=l({},r,{maxTimeToFirstByteMs:Math.min(f,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(f,r.maxTimeToFirstByteMs)})}}var c=r.errorRetry||r.timeoutRetry||{},g={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:c.maxNumRetry||0,retryDelay:c.retryDelayMs||0,maxRetryDelay:c.maxRetryDelayMs||0},v={onSuccess:function(e,t,r,i){var a=n.getInternalLoader(r);n.resetInternalLoader(r.type);var s=e.data;t.parsing.start=performance.now(),en.isMediaPlaylist(s)||r.type!==V?n.handleTrackOrLevelPlaylist(e,t,r,i||null,a):n.handleMasterPlaylist(e,t,r,i)},onError:function(e,t,r,i){n.handleNetworkError(t,r,!1,e,i)},onTimeout:function(e,t,r){n.handleNetworkError(t,r,!0,void 0,e)}};s.load(e,g,v)},t.checkAutostartLoad=function(){if(this.hls){var e=this.hls,t=e.config,r=t.autoStartLoad,i=t.startPosition,n=e.forceStartLoad;(r||n)&&(this.hls.logger.log((r?"auto":"force")+" startLoad with configured startPosition "+i),this.hls.startLoad(i))}},t.handleMasterPlaylist=function(e,t,r,i){var n=this,a=this.hls,s=e.data,o=qd(e,r),l=en.parseMasterPlaylist(s,o);if(l.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,r,l.playlistParsingError,i,t);var u=l.contentSteering,d=l.levels,h=l.iframeVariants,f=l.sessionData,c=l.sessionKeys,g=l.startTimeOffset,v=l.variableList;this.variableList=v,d.forEach((function(e){var t=e.unknownCodecs;if(t)for(var r=n.hls.config.preferManagedMediaSource,i=e.audioCodec,a=e.videoCodec,s=t.length;s--;){var o=t[s];Nt(o,"audio",r)?(e.audioCodec=i=i?i+","+o:o,xt.audio[i.substring(0,4)]=2,t.splice(s,1)):Nt(o,"video",r)&&(e.videoCodec=a=a?a+","+o:o,xt.video[a.substring(0,4)]=2,t.splice(s,1))}}));var m=en.parseMasterPlaylistMedia(s,o,l),p=m.AUDIO,y=void 0===p?[]:p,E=m.SUBTITLES,T=m["CLOSED-CAPTIONS"];y.length&&(y.some((function(e){return!e.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"),y.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Ai({}),bitrate:0,url:""}))),a.trigger(G.MANIFEST_LOADED,{levels:d,audioTracks:y,subtitles:E,iframeVariants:h,captions:T,contentSteering:u,url:o,stats:t,networkDetails:i,sessionData:f,sessionKeys:c,startTimeOffset:g,variableList:v})},t.handleTrackOrLevelPlaylist=function(e,t,r,i,n){var a=this.hls,s=r.id,o=r.level,l=r.type,u=qd(e,r),d=x(o)?o:x(s)?s:0,h=Wd(r),f=en.parseLevelPlaylist(e.data,u,d,h,0,this.variableList);if(l===V){var c={attrs:new Ai({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=t.loading.start+En(f,0),a.trigger(G.MANIFEST_LOADED,{levels:[c],audioTracks:[],iframeVariants:[],url:u,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=f,this.handlePlaylistLoaded(f,e,t,r,i,n)},t.handleManifestParsingError=function(e,t,r,i,n){this.hls.trigger(G.ERROR,{type:B.NETWORK_ERROR,details:U.MANIFEST_PARSING_ERROR,fatal:t.type===V,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:i,stats:n})},t.handleNetworkError=function(e,t,r,i,n){void 0===r&&(r=!1);var a="A network "+(r?"timeout":"error"+(i?" (status "+i.code+")":""))+" occurred while loading "+e.type;e.type===H?a+=": "+e.level+" id: "+e.id:e.type!==Y&&e.type!==j||(a+=" id: "+e.id+' group-id: "'+e.groupId+'"');var s=new Error(a);this.hls.logger.warn("[playlist-loader]: "+a);var o=U.UNKNOWN,l=!1,u=this.getInternalLoader(e);switch(e.type){case V:o=r?U.MANIFEST_LOAD_TIMEOUT:U.MANIFEST_LOAD_ERROR,l=!0;break;case H:o=r?U.LEVEL_LOAD_TIMEOUT:U.LEVEL_LOAD_ERROR,l=!1;break;case Y:o=r?U.AUDIO_TRACK_LOAD_TIMEOUT:U.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case j:o=r?U.SUBTITLE_TRACK_LOAD_TIMEOUT:U.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(e.type);var d={type:B.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:u,context:e,error:s,networkDetails:t,stats:n};if(i){var h=e.url;t&&"url"in t&&(h=t.url),d.response=c({url:h,data:void 0},i)}this.hls.trigger(G.ERROR,d)},t.handlePlaylistLoaded=function(e,t,r,i,n,a){var s=this.hls,o=i.type,l=i.level,u=i.levelOrTrack,d=i.id,h=i.groupId,f=i.deliveryDirectives,c=qd(t,i),g=Wd(i),v="number"==typeof i.level&&g===$.MAIN?l:void 0;u&&"iframes"in u&&u.iframes&&!e.iframesOnly&&(e.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);var m=e.playlistParsingError;if(m){if(this.hls.logger.warn(m+" "+e.url),!s.config.ignorePlaylistParsingErrors)return void s.trigger(G.ERROR,{type:B.NETWORK_ERROR,details:U.LEVEL_PARSING_ERROR,fatal:!1,url:c,error:m,reason:m.message,response:t,context:i,level:v,parent:g,networkDetails:n,stats:r});e.playlistParsingError=null}if(e.fragments.length)switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),a.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case V:case H:if(v)if(u){if(u!==s.levels[v]){var p=s.levels.indexOf(u);p>-1&&(v=p)}}else v=0;s.trigger(G.LEVEL_LOADED,{details:e,levelInfo:u||s.levels[0],level:v||0,id:d||0,stats:r,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:o===V,context:i});break;case Y:s.trigger(G.AUDIO_TRACK_LOADED,{details:e,track:u,id:d||0,groupId:h||"",stats:r,networkDetails:n,deliveryDirectives:f,context:i});break;case j:s.trigger(G.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:d||0,groupId:h||"",stats:r,networkDetails:n,deliveryDirectives:f,context:i})}else{var y=e.playlistParsingError=new Error("No Segments found in Playlist");s.trigger(G.ERROR,{type:B.NETWORK_ERROR,details:U.LEVEL_EMPTY_ERROR,fatal:!1,url:c,error:y,reason:y.message,response:t,context:i,level:v,parent:g,networkDetails:n,stats:r})}},e}(),zd=function(){function e(t){void 0===t&&(t={}),this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new w,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;var r=this.logger=Ie(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),i=this.config=Fd(e.DefaultConfig,t,r);this.userConfig=t,i.progressive&&Bd(i,r);var n=i.streamController,a=i.abrController,s=i.bufferController,o=i.capLevelController,l=i.errorController,u=i.fpsController,d=i.id3TrackController,h=i.iframeController,f=i.gapController,c=new l(this),g=this.abrController=new a(this),v=new zr(this),m=i.interstitialsController,p=m?this.interstitialsController=new m(this,e):null,y=s?this.bufferController=new s(this,v):null,E=o?this.capLevelController=new o(this):null,T=u?new u(this):null,S=i.cmcdController,A=S?this.cmcdController=new S(this):null,I=new Xd(this),L=i.contentSteeringController,R=L?new L(this):null,b=this.levelController=new Ud(this,R),k=d?new d(this):void 0,D=new Yd(this.config,this.logger),P=this.streamController=new n(this,v,D),_=this.gapController=f?new f(this,v):void 0;E&&E.setStreamController(P);var C=[I,b,P];p&&C.splice(1,0,p),R&&C.splice(1,0,R),this.networkControllers=C;var O=[g];y&&O.push(y),_&&O.push(_),E&&O.push(E),T&&(T.setStreamController(P),O.push(T)),k&&O.push(k),O.push(v),this.audioTrackController=this.createController(i.audioTrackController,C);var M=i.audioStreamController;M&&C.push(this.audioStreamController=new M(this,v,D)),this.subtitleTrackController=this.createController(i.subtitleTrackController,C);var x=i.subtitleStreamController;x&&C.push(this.subtititleStreamController=new x(this,v,D)),this.createController(i.timelineController,O),D.emeController=this.emeController=this.createController(i.emeController,O),A&&O.push(A),this.latencyController=this.createController(i.latencyController,O),this.coreComponents=O,this.iframeController=h?new h(this,e):void 0,C.push(c);var F=c.onErrorOut;"function"==typeof F&&this.on(G.ERROR,F,c),this.on(G.MANIFEST_LOADED,I.onManifestLoaded,I)}e.isMSESupported=function(){return eu()},e.isSupported=function(){return function(){if(!eu())return!1;var e=Re();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((function(t){return e.isTypeSupported(Ut(t,"video"))}))||["mp4a.40.2","fLaC"].some((function(t){return e.isTypeSupported(Ut(t,"audio"))})))}()},e.getMediaSource=function(){return Re()};var t=e.prototype;return t.createController=function(e,t){if(e){var r=new e(this);return t&&t.push(r),r}return null},t.on=function(e,t,r){void 0===r&&(r=this),this._emitter.on(e,t,r)},t.once=function(e,t,r){void 0===r&&(r=this),this._emitter.once(e,t,r)},t.removeAllListeners=function(e){this._emitter.removeAllListeners(e)},t.off=function(e,t,r,i){void 0===r&&(r=this),this._emitter.off(e,t,r,i)},t.listeners=function(e){return this._emitter.listeners(e)},t.emit=function(e,t,r){return this._emitter.emit(e,t,r)},t.trigger=function(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;var r=e===G.ERROR;this.trigger(G.ERROR,{type:B.OTHER_ERROR,details:U.INTERNAL_EXCEPTION,fatal:r,event:e,error:t}),this.triggeringException=!1}}return!1},t.listenerCount=function(e){return this._emitter.listenerCount(e)},t.destroy=function(){this.logger.log("destroy"),this.trigger(G.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((function(e){return e.destroy()})),this.networkControllers.length=0,this.coreComponents.forEach((function(e){return e.destroy()})),this.coreComponents.length=0,this.iframeController=void 0;var e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null},t.attachMedia=function(e){if(!e||"media"in e&&!e.media){var t=new Error("attachMedia failed: invalid argument ("+e+")");this.trigger(G.ERROR,{type:B.OTHER_ERROR,details:U.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}else{this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());var r="media"in e,i=r?e.media:e,n=r?e:{media:i};this._media=i,this.trigger(G.MEDIA_ATTACHING,n)}},t.detachMedia=function(){this.logger.log("detachMedia");var e={};this.trigger(G.MEDIA_DETACHING,e),this._media=null,this.trigger(G.MEDIA_DETACHED,e)},t.transferMedia=function(){var e;this._media=null;var t=(null==(e=this.bufferController)?void 0:e.transferMedia())||null,r={transferMedia:t};return this.trigger(G.MEDIA_DETACHING,r),this.trigger(G.MEDIA_DETACHED,r),t},t.loadSource=function(e){var t;this.stopLoad();var r=this.media,i=this._url,n=this._url=M.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:"+n),r&&i&&(i!==n||null!=(t=this.bufferController)&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(G.MANIFEST_LOADING,{url:e})},t.startLoad=function(e,t){void 0===e&&(e=-1),this.logger.log("startLoad("+e+(t?", <skip seek to start>":"")+")"),this.started=!0,this.resumeBuffering();for(var r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),this.started&&this.networkControllers);r++);},t.stopLoad=function(){this.logger.log("stopLoad"),this.started=!1;for(var e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);},t.resumeBuffering=function(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach((function(e){e.resumeBuffering&&e.resumeBuffering()})))},t.pauseBuffering=function(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((function(e){e.pauseBuffering&&e.pauseBuffering()})))},t.swapAudioCodec=function(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()},t.recoverMediaError=function(){this.logger.log("recoverMediaError");var e=this._media,t=this.started,r=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(r?this.startLoad(r):this.config.autoStartLoad||this.startLoad()))},t.removeLevel=function(e){this.levelController.removeLevel(e)},t.setAudioOption=function(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null},t.setSubtitleOption=function(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null},t.createIFramePlayer=function(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null},t.createImageIFramePlayer=function(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null},t.getMediaDecodingInfo=function(e,t){return void 0===t&&(t=this.allAudioTracks),Jt(e,vr(t),navigator.mediaCapabilities)},a(e,[{key:"url",get:function(){return this._url}},{key:"hasEnoughToStart",get:function(){return this.streamController.hasEnoughToStart}},{key:"startPosition",get:function(){return this.streamController.startPositionValue}},{key:"loadingEnabled",get:function(){return this.started&&this.streamController.state!==On.STOPPED}},{key:"bufferingEnabled",get:function(){return this.streamController.bufferingEnabled}},{key:"inFlightFragments",get:function(){var e,t=((e={})[$.MAIN]=this.streamController.inFlightFrag,e);return this.audioStreamController&&(t[$.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[$.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}},{key:"sessionId",get:function(){var e=this._sessionId;return e||(e=this._sessionId=b()),e}},{key:"levels",get:function(){var e=this.levelController.levels;return e||[]}},{key:"latestLevelDetails",get:function(){return this.streamController.getLevelDetails()||null}},{key:"loadLevelObj",get:function(){return this.levelController.loadLevelObj}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){this.logger.log("set currentLevel:"+e),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){this.logger.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){this.logger.log("set loadLevel:"+e),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){this.logger.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){var e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e},set:function(e){this.logger.log("set startLevel:"+e),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(e){var t=this.capLevelController,r=!!e;t&&r!==this.config.capLevelToPlayerSize&&(r?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=r)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){this._autoLevelCapping!==e&&(this.logger.log("set autoLevelCapping:"+e),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimate():NaN},set:function(e){this.abrController.resetEstimator(e)}},{key:"abrEwmaDefaultEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.defaultEstimate:NaN}},{key:"ttfbEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(e){(function(e){return ir.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var r=e.length,i=0;i<r;i++)if(e[i].maxBitrate>=t)return i;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,r=this.autoLevelCapping,i=this.maxHdcpLevel;if(e=-1===r&&null!=t&&t.length?t.length-1:r,i)for(var n=e;n--;){var a=t[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return e}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(e){this.abrController.nextAutoLevel=e}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"audioForwardBufferInfo",get:function(){var e;return(null==(e=this.audioStreamController)?void 0:e.getFwdBufferInfo())||null}},{key:"maxBufferLength",get:function(){return this.streamController.maxBufferLength}},{key:"allAudioTracks",get:function(){var e=this.audioTrackController;return e?e.allAudioTracks:[]}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"nextAudioTrack",get:function(){var e,t;return null!=(e=null==(t=this.audioStreamController)?void 0:t.nextAudioTrack)?e:-1},set:function(e){var t=this.audioTrackController;t&&(t.nextAudioTrack=e)}},{key:"allSubtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(e){this.config.lowLatencyMode=e}},{key:"liveSyncPosition",get:function(){var e,t;return null!=(e=null==(t=this.latencyController)?void 0:t.liveSyncPosition)?e:null}},{key:"latency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.latency)||0}},{key:"maxLatency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.maxLatency)||0}},{key:"targetLatency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.targetLatency)||null},set:function(e){this.latencyController&&(this.latencyController.targetLatency=e)}},{key:"drift",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.drift)||null}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}},{key:"pathways",get:function(){return this.levelController.pathways}},{key:"pathwayPriority",get:function(){return this.levelController.pathwayPriority},set:function(e){this.levelController.pathwayPriority=e}},{key:"bufferedToEnd",get:function(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}},{key:"interstitialsManager",get:function(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}},{key:"iframeVariants",get:function(){var e=this.levelController.iframeVariants;return e||[]}}],[{key:"version",get:function(){return ds}},{key:"Events",get:function(){return G}},{key:"MetadataSchema",get:function(){return Wn}},{key:"ErrorTypes",get:function(){return B}},{key:"ErrorDetails",get:function(){return U}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:xd},set:function(t){e.defaultConfig=t}}])}();return zd.defaultConfig=void 0,zd},"object"==typeof exports&&"undefined"!=typeof module?module.exports=i():"function"==typeof define&&define.amd?define(i):(r="undefined"!=typeof globalThis?globalThis:r||self).Hls=i()}(!1);
+//# sourceMappingURL=hls.min.js.map
diff --git a/i18n.js b/i18n.js
index 4e9b67b..1b4bf5f 100644
--- a/i18n.js
+++ b/i18n.js
@@ -1,6 +1,12 @@
import { normalizeUiPreferences, resolveLocale } from "./preferences.js";
const EN = Object.freeze({
+ "视频逆推分析规则": "Video analysis rules",
+ "未保存": "Unsaved",
+ "任务模型": "Task models",
+ "连接其他服务": "Connect another service",
+ "下载分享包": "Download share package",
+ "故障诊断": "Diagnostics",
"读取校验 · {done} / {total}": "Reading and verifying · {done} / {total}",
"检查图片 · {done}/{total}": "Checking images · {done}/{total}",
"保存资源 · {done} / {total}": "Saving files · {done} / {total}",
@@ -1048,6 +1054,9 @@ const EN = Object.freeze({
"扫描不会自动保存。请确认正文、图片或视频,未勾选的内容不会进入案例库。": "Scanning never saves automatically. Confirm the text, images, or videos you want; unchecked content will not enter the library.",
"网页": "Webpage",
"待保存内容没有更新": "The capture draft was not updated",
+ "{message};部分媒体未完整保存,请在案例库检查": "{message}; some media is incomplete. Check the saved case in the library",
+ "暂未取得可在案例库播放的视频": "A playable video is not available in the library yet",
+ "引用帖 · {count} 个素材": "Quoted post · {count} media items",
"引用帖 · {count} 张图": "Quoted post · {count} images",
"已撤销上次调整": "Last change undone",
"加入这组": "Add this group",
@@ -1095,7 +1104,6 @@ const EN = Object.freeze({
"你没有授予当前网站访问权限。请再次点击“网页采集”,或在 Chrome 扩展详情的“网站访问权限”中允许此网站;待保存内容没有改变。": "Access to this site was not granted. Click Capture page again, or allow this site under the extension's Site access settings. Unsaved content was not changed.",
"媒体域名权限未获授权;仍会保存正文和可用引用,并逐项显示下载失败原因。": "Media-domain access was not granted. Text and usable references will still be saved, with download failures shown per item.",
"网页内容保存失败": "Web content could not be saved",
- "{message};{count} 项存在媒体下载问题": "{message}; {count} items have media download issues",
"跨网页截图权限没有生效,请返回侧边栏重新授权;当前草稿没有改变。": "Cross-page screenshot access is not active. Return to the side panel and grant access again. Your draft has not changed.",
"本地案例": "Local cases",
"最近保存": "Latest save",
@@ -1322,6 +1330,7 @@ const EN = Object.freeze({
"案例已存在": "Case already saved",
"查看来源": "View source",
"视频封面": "Video cover",
+ "视频暂不可播放,请从原页面重新采集": "Video unavailable. Capture it again from the original page.",
"视频暂不可播放": "Video unavailable",
"视频加载失败": "Video could not be loaded",
"图片加载失败": "Image could not be loaded",
diff --git a/library-model.js b/library-model.js
index e9da08a..d645d6d 100644
--- a/library-model.js
+++ b/library-model.js
@@ -107,6 +107,7 @@ export function entrySourceMetadataRows(entry = {}, sourceLabel = "来源") {
addField(labels[name], sourceFacts[name]);
}
if (sourceFacts.description) addField(english ? "Description" : "作品说明", sourceFacts.description);
+ for (const warning of Array.isArray(sourceFacts.captureWarnings) ? sourceFacts.captureWarnings : []) addField(english ? "Capture issue" : "采集问题", warning);
for (const [name, amount] of Object.entries(sourceFacts.engagement || {})) {
if (Number.isFinite(Number(amount)) && Number(amount) >= 0) addField(labels[name] || name, String(amount));
}
diff --git a/library-package.js b/library-package.js
index fa9f199..ac6d130 100644
--- a/library-package.js
+++ b/library-package.js
@@ -776,6 +776,10 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =
assetId: visualIdMap[note.assetId] ?? note.assetId,
...(note.frameAssetId ? { frameAssetId: visualIdMap[note.frameAssetId] ?? note.frameAssetId } : {})
}));
+ entry.mediaPrompts = (entry.mediaPrompts ?? []).map((prompt) => ({
+ ...prompt,
+ assetId: visualIdMap[prompt.assetId] ?? prompt.assetId
+ }));
entry.videoAnalyses = (entry.videoAnalyses ?? []).map((analysis) => ({
...analysis,
...(analysis.assetId ? { assetId: visualIdMap[analysis.assetId] ?? analysis.assetId } : {})
diff --git a/library.css b/library.css
index c392c19..5a02413 100644
--- a/library.css
+++ b/library.css
@@ -1187,19 +1187,12 @@ details:not([open]) > .selection-menu-panel { display: none; }
.detail-video-wrap .media-open-link { display: none; }
.detail-video-wrap.has-playback-error .media-open-link { display: inline-flex; }
.referenced-video { min-height: 280px; display: grid; place-content: center; gap: 14px; text-align: center; }
-.platform-link-card { position: relative; display: grid; width: 100%; aspect-ratio: 16 / 9; min-height: 220px; overflow: hidden; align-content: end; color: #fff; background: #111419; text-decoration: none; }
-.platform-link-card img { position: absolute; width: 100%; height: 100%; object-fit: cover; inset: 0; }
-.platform-link-card::after { position: absolute; content: ""; background: rgba(5, 7, 9, .68); inset: 0; }
-.platform-link-label { position: relative; z-index: 1; display: grid; gap: 5px; padding: 18px; }
-.platform-link-label small { color: var(--accent); font-size: 10px; font-weight: 850; letter-spacing: .12em; }
-.platform-link-label strong { font-size: 16px; }
-.platform-link-label > span { font-size: 12px; }
-.platform-link-label > span:not(.platform-link-actions) { opacity: .86; }
-.platform-link-actions, .media-playback-actions { position: relative; z-index: 1; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
-.platform-link-actions { margin-top: 8px; }
-.platform-link-actions a, .platform-link-actions button, .media-playback-actions a { min-height: 36px; font-size: 12px; }
-.platform-link-actions a, .platform-link-actions button { background: var(--ui-surface); color: var(--ui-text); border-color: var(--ui-border-strong); }
-.platform-link-actions a:hover, .platform-link-actions button:hover { background: var(--ui-hover); }
+.unavailable-video-stage { display: grid; place-items: center; overflow: hidden; aspect-ratio: 16 / 9; }
+.unavailable-video-stage img { width: 100%; height: 100%; min-height: 0; object-fit: contain; }
+.unavailable-video-stage > .ui-icon { width: 40px; height: 40px; color: #aeb5bb; }
+.platform-playback-fallback { align-items: stretch; }
+.media-playback-actions { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 8px; }
+.media-playback-actions a, .media-playback-actions button { min-height: 36px; font-size: 12px; }
.media-playback-status { width: 100%; margin: 0; color: var(--muted); font-size: 11px; text-align: left; }
.media-playback-status.error { color: var(--danger); }
.referenced-video-embed { gap: 8px; align-items: stretch; }
@@ -1341,8 +1334,7 @@ details:not([open]) > .selection-menu-panel { display: none; }
.detail-discovery { padding-top: 18px; }
.detail-discovery-heading { margin-bottom: 12px; padding-inline: 4px; }
.detail-discovery-heading h2 { font-size: 15px; }
-.case-document-cover, .case-video-link-cover, .case-text-cover, .platform-link-card { background: var(--raised); }
-.platform-link-card::after { background: rgba(9, 11, 10, .68); }
+.case-document-cover, .case-video-link-cover, .case-text-cover { background: var(--raised); }
.video-poster-badge, .pdf-cover-label { backdrop-filter: none; }
@media (max-width: 900px) {
@@ -1422,8 +1414,7 @@ details:not([open]) > .selection-menu-panel { display: none; }
.detail-visual-gallery.is-video-detail .detail-visual-actions { width: 100%; }
.detail-visual-gallery.is-video-detail .detail-visual-actions .button-secondary,
.detail-visual-gallery.is-video-detail .detail-visual-actions .button-danger-secondary,
- .platform-link-actions a,
- .platform-link-actions button,
+ .media-playback-actions button,
.media-playback-actions a { min-height: 44px; }
}
@@ -1442,11 +1433,6 @@ details:not([open]) > .selection-menu-panel { display: none; }
.article-document-reader [contenteditable="plaintext-only"]:focus { outline: 2px solid var(--accent); }
.media-thumb-play { position: absolute; right: 4px; bottom: 4px; padding: 1px 4px; border-radius: 4px; color: white; background: rgba(0,0,0,.72); font-size: 11px; }
.detail-visual-actions .media-remove-action { margin-left: 8px; color: var(--danger); }
-.platform-playback-fallback:not(.has-poster) { aspect-ratio: auto; min-height: 0; padding: 40px 20px 24px; justify-items: center; align-content: center; color: var(--ink); background: var(--panel); }
-.platform-playback-fallback:not(.has-poster)::after { display: none; }
-.platform-playback-fallback:not(.has-poster) > .ui-icon { width: 40px; height: 40px; color: var(--muted); }
-.platform-playback-fallback:not(.has-poster) .platform-link-label { justify-items: center; text-align: center; }
-.platform-playback-fallback:not(.has-poster) .platform-link-actions { justify-content: center; }
.media-playback-error { padding: 16px; margin: 0; color: var(--ink); background: var(--raised); }
.detail-video-wrap.has-playback-error .detail-video { display: none; }
@@ -1478,3 +1464,83 @@ details:not([open]) > .selection-menu-panel { display: none; }
.project-tree-tools { position: sticky; top: -15px; z-index: 10; display: grid; gap: 8px; padding-block: 8px; background: var(--sidebar); }
.project-row.project-search-result { grid-template-columns: minmax(0, 1fr) auto; }
+
+/* Reviewed settings surfaces; the general settings and case viewer keep their layout. */
+.settings-dialog:has(.settings-panel:not([hidden]):is(#settings-ai-panel, #settings-rules-panel, #settings-tasks-panel)) {
+ display: flex; flex-direction: column; height: fit-content; min-height: 0;
+ inset: 0; margin: auto; max-height: calc(100dvh - 40px);
+}
+.settings-dialog:has(.settings-panel:not([hidden]):is(#settings-ai-panel, #settings-rules-panel, #settings-tasks-panel)) > .data-safety-header { flex: none; }
+.settings-dialog:has(.settings-panel:not([hidden]):is(#settings-ai-panel, #settings-rules-panel, #settings-tasks-panel)) .settings-shell { display: flex; flex-direction: column; min-height: 0; }
+.settings-dialog:has(.settings-panel:not([hidden]):is(#settings-ai-panel, #settings-rules-panel, #settings-tasks-panel)) .settings-tabs { flex: none; }
+#settings-ai-panel, #settings-rules-panel, #settings-tasks-panel { min-height: 0; overflow: auto; }
+:is(#settings-ai-panel, #settings-rules-panel, #settings-tasks-panel) button { white-space: nowrap; }
+#settings-ai-panel .ai-routing-card, #settings-ai-panel .ai-routing-regions > section { border: 0; padding: 0; background: transparent; }
+#settings-ai-panel .ai-routing-heading { display: none; }
+#settings-ai-panel .ai-assignment-row { grid-template-columns: minmax(120px, .7fr) minmax(0, 1fr); gap: 20px; align-items: center; padding: 10px 0; }
+#settings-ai-panel .ai-model-choice { display: flex; width: 100%; min-width: 0; align-items: center; justify-content: space-between; gap: 8px; }
+#settings-ai-panel .ai-model-choice span { flex: 1; min-width: 0; text-align: center; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
+#settings-ai-panel .ai-model-choice .ui-icon { flex: none; }
+#settings-ai-panel .ai-provider-row { grid-template-columns: minmax(120px, .7fr) minmax(0, 1fr) auto; gap: 16px; min-height: 64px; padding: 14px 0; align-items: center; }
+#settings-ai-panel .ai-provider-row > strong { grid-column: 1; grid-row: 1; }
+#settings-ai-panel .ai-provider-row > span { grid-column: 2; grid-row: 1; text-align: center; line-height: 1.5; overflow-wrap: anywhere; color: var(--muted); }
+#settings-ai-panel .ai-provider-actions { grid-column: 3; grid-row: 1; display: flex; align-items: center; justify-content: center; gap: 8px; min-width: 80px; }
+#settings-ai-panel .ai-provider-actions button { flex: none; }
+#settings-ai-panel .ai-more-providers { margin-top: 12px; }
+#settings-ai-panel .ai-more-providers > summary { cursor: pointer; padding: 10px 0; color: var(--muted); font-size: 12px; }
+#settings-rules-panel .analysis-kind-tabs { display: flex; gap: 6px; flex-wrap: wrap; }
+#settings-rules-panel .analysis-kind-tabs button { flex: none; }
+#settings-rules-panel .analysis-settings-form { gap: 12px; }
+#settings-rules-panel .rule-toolbar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
+#settings-rules-panel .rule-toolbar h3 { margin: 0 4px 0 0; font-size: 14px; }
+#settings-rules-panel .rule-toolbar .icon-button { width: 32px; min-height: 32px; flex: 0 0 32px; }
+#settings-rules-panel .rule-save-state { display: inline-flex; align-items: center; min-height: 26px; line-height: 1; color: var(--muted); font-size: 12px; }
+#settings-rules-panel .analysis-settings-form textarea { width: 100%; min-height: 280px; resize: vertical; line-height: 1.75; }
+#settings-rules-panel .analysis-settings-form label { min-width: 0; }
+#settings-rules-panel .analysis-protocol { padding: 0; border: 0; background: transparent; }
+#settings-rules-panel .analysis-protocol summary { color: var(--muted); font-size: 12px; padding: 8px 0; }
+#settings-rules-panel #composer-task-key { min-width: 0; }
+#settings-tasks-panel .batch-card { padding: 0 0 16px; border: 0; border-bottom: 1px solid var(--line); background: transparent; border-radius: 0; }
+#settings-tasks-panel .batch-card-heading, #settings-tasks-panel .task-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
+#settings-tasks-panel :is(.batch-card-heading, .task-heading) h3 { margin: 0; font-size: 14px; }
+#settings-tasks-panel :is(.batch-card-heading, .task-heading) .batch-actions { display: flex; align-items: center; justify-content: flex-end; gap: 8px; margin: 0; flex-wrap: wrap; }
+#settings-tasks-panel #batch-status-badge { display: inline-flex; align-items: center; justify-content: center; align-self: center; height: 26px; min-height: 26px; line-height: 1; padding: 0 10px; margin: 0; box-sizing: border-box; white-space: nowrap; }
+#settings-tasks-panel .batch-summary { padding: 10px 0; border: 0; background: transparent; }
+#settings-tasks-panel :is(.batch-summary, .reanalyze-preview):empty { display: none; }
+#settings-tasks-panel .task-diagnostics, #settings-tasks-panel .advanced-reanalysis { padding: 0; border: 0; margin-top: 12px; background: transparent; }
+#settings-tasks-panel .task-diagnostics > summary { color: var(--muted); font-size: 12px; cursor: pointer; }
+#settings-tasks-panel .task-diagnostics > label { margin-top: 12px; }
+.share-dialog-public-panel { display: grid; gap: 12px; margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--line); }
+.share-dialog-public-panel > button { justify-self: start; }
+.share-dialog-options button { white-space: nowrap; }
+#import-dialog .import-summary, .library-package-import-dialog .import-summary { display: flex; flex-wrap: wrap; gap: 8px 16px; padding: 10px 0; border: 0; background: transparent; }
+:is(#import-dialog, .library-package-import-dialog) .import-summary > span { display: flex; align-items: center; gap: 5px; border: 0; padding: 0; font-size: 12px; white-space: nowrap; }
+:is(#import-dialog, .library-package-import-dialog) .import-summary > span > span { display: inline; border: 0; padding: 0; font-size: 12px; }
+#import-dialog .import-options { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; }
+#import-dialog .import-project-field { display: flex; align-items: center; gap: 10px; flex: 1; min-width: 220px; }
+#import-dialog .import-project-field > span { white-space: nowrap; }
+#import-dialog .import-project-field > input { min-width: 0; flex: 1; }
+#import-dialog .import-label-field { display: flex; align-items: start; gap: 10px; }
+#import-dialog .import-label-field > span { padding-top: 8px; white-space: nowrap; }
+#import-dialog .import-label-editor { flex: 1; min-width: 0; }
+#import-dialog .tag-editor-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; }
+#import-dialog .tag-editor-row button { justify-self: auto; white-space: nowrap; }
+@media (max-width: 700px) {
+ .settings-dialog:has(.settings-panel:not([hidden]):is(#settings-ai-panel, #settings-rules-panel, #settings-tasks-panel)) { width: calc(100vw - 16px); max-height: calc(100dvh - 24px); border-radius: var(--ui-container-radius); }
+ .settings-dialog:has(.settings-panel:not([hidden]):is(#settings-ai-panel, #settings-rules-panel, #settings-tasks-panel)) .settings-tabs { display: flex; flex-wrap: wrap; gap: 4px; }
+ .settings-dialog:has(.settings-panel:not([hidden]):is(#settings-ai-panel, #settings-rules-panel, #settings-tasks-panel)) .settings-tabs button { width: auto; flex: none; white-space: nowrap; }
+ #settings-ai-panel .ai-assignment-row { grid-template-columns: 88px minmax(0, 1fr); gap: 12px; }
+ #settings-ai-panel .ai-provider-row { grid-template-columns: minmax(0, 1fr) auto; gap: 4px 12px; }
+ #settings-ai-panel .ai-provider-row > span { grid-column: 1; grid-row: 2; text-align: left; }
+ #settings-ai-panel .ai-provider-actions { grid-column: 2; grid-row: 1 / span 2; }
+ #settings-ai-panel .ai-provider-region-heading { flex-wrap: wrap; }
+ html[lang="en"] #settings-ai-panel .ai-assignment-row { grid-template-columns: minmax(0, 1fr); gap: 6px; }
+ #settings-tasks-panel :is(.batch-card-heading, .task-heading) .batch-actions { margin-left: auto; }
+ #import-dialog .import-project-field { min-width: 0; flex-basis: 100%; }
+ #import-dialog .import-label-field { flex-wrap: wrap; gap: 6px; }
+ #import-dialog .import-label-editor { flex-basis: 100%; }
+}
+@media (max-width: 430px) {
+ html[lang="en"] .share-dialog-options { grid-template-columns: minmax(0, 1fr); }
+}
+#settings-ai-panel .ai-model-choice { font-weight: 400; }
diff --git a/library.html b/library.html
index 079a8c4..7cc81f4 100644
--- a/library.html
+++ b/library.html
@@ -166,10 +166,10 @@
<div class="data-safety-body share-dialog-body">
<p id="share-dialog-meta" class="share-dialog-meta"></p>
<div id="share-dialog-options" class="share-dialog-options">
- <button id="share-dialog-export" class="button-secondary" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-download"></use></svg><span data-i18n="导出分享包">导出分享包</span></button>
- <button id="share-dialog-submit" type="button" disabled><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-upload"></use></svg><span data-i18n="投稿到精选">投稿到精选</span></button>
+ <button id="share-dialog-export" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-download"></use></svg><span data-i18n="下载分享包">下载分享包</span></button>
+ <button id="share-dialog-public" class="button-secondary" type="button" aria-expanded="false" aria-controls="share-dialog-public-panel"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-upload"></use></svg><span data-i18n="公开投稿">公开投稿</span></button>
</div>
- <label class="share-dialog-disclosure"><input id="share-dialog-disclosure" type="checkbox" /><span data-i18n="我确认素材将公开上传到 GitHub 审核队列">我确认素材将公开上传到 GitHub 审核队列</span></label>
+ <section id="share-dialog-public-panel" class="share-dialog-public-panel" hidden><label class="share-dialog-disclosure"><input id="share-dialog-disclosure" type="checkbox" /><span data-i18n="我确认素材将公开上传到 GitHub 审核队列">我确认素材将公开上传到 GitHub 审核队列</span></label><button id="share-dialog-submit" type="button" disabled><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-upload"></use></svg><span data-i18n="投稿到精选">投稿到精选</span></button></section>
<section id="share-dialog-result" class="share-dialog-result" hidden>
<strong id="share-dialog-result-text"></strong>
<div><button id="share-dialog-show-files" class="button-secondary" type="button" data-i18n="显示投稿文件">显示投稿文件</button><button id="share-dialog-open-form" type="button" data-i18n="打开投稿表单">打开投稿表单</button></div>
@@ -340,17 +340,9 @@
</footer>
</section>
<section id="settings-tasks-panel" class="settings-panel settings-tasks-panel" data-settings-panel="tasks" hidden>
- <label class="ai-consent"><input id="show-analysis-diagnostics" type="checkbox" /><span data-i18n="显示故障诊断(仅排查问题时开启)">显示故障诊断(仅排查问题时开启)</span></label>
+
<div class="batch-card batch-primary">
- <div class="batch-card-heading"><div><h3 data-i18n="批量文字分析">批量文字分析</h3><p data-i18n="使用“文字工作”中已分配的供应商和模型;只处理未分析或原文已变化的文字案例。">使用“文字工作”中已分配的供应商和模型;只处理未分析或原文已变化的文字案例。</p></div><span id="batch-status-badge" data-i18n="尚未开始">尚未开始</span></div>
- <div id="analysis-batch-summary" class="batch-summary" data-i18n="先生成预览,不会直接产生 API 请求。">先生成预览,不会直接产生 API 请求。</div>
- <details id="analysis-diagnostics" class="analysis-diagnostics" hidden>
- <summary><span data-i18n="分析诊断">分析诊断</span><span id="analysis-runtime-version"></span></summary>
- <div class="analysis-diagnostics-heading"><p data-i18n="仅记录运行版本、阶段、标签数量、耗时和错误类别;不记录案例原文、API Key 或模型完整输出。">仅记录运行版本、阶段、标签数量、耗时和错误类别;不记录案例原文、API Key 或模型完整输出。</p><button id="copy-analysis-diagnostics" class="button-secondary" type="button" data-i18n="复制诊断日志">复制诊断日志</button></div>
- <ol id="analysis-diagnostic-events"></ol>
- </details>
- <div id="analysis-progress" class="maintenance-progress" hidden><progress id="analysis-progress-bar" max="1" value="0"></progress></div>
- <div class="batch-actions">
+ <div class="batch-card-heading"><div><h3 data-i18n="批量文字分析">批量文字分析</h3></div><div class="batch-actions"><span id="batch-status-badge" data-i18n="尚未开始">尚未开始</span>
<button id="preview-analysis-batch" type="button" data-i18n="生成预览">生成预览</button>
<button id="start-analysis-batch" type="button" disabled data-i18n="确认并开始">确认并开始</button>
<button id="pause-analysis-batch" class="button-secondary" type="button" hidden data-i18n="暂停">暂停</button>
@@ -359,33 +351,38 @@
<button id="apply-staged-analysis-rebuild" type="button" hidden data-i18n="应用已成功结果">应用已成功结果</button>
<button id="cancel-analysis-batch" class="quiet-danger" type="button" hidden data-i18n="取消">取消</button>
<button id="undo-analysis-batch" class="button-secondary" type="button" hidden data-i18n="撤回本次分析">撤回本次分析</button>
- </div>
- <details class="advanced-reanalysis"><summary data-i18n="重建标签系统">重建标签系统</summary><p data-i18n="付费重跑全部文字案例;结果先暂存,全部成功后一次切换,并可完整撤回。">付费重跑全部文字案例;结果先暂存,全部成功后一次切换,并可完整撤回。</p><div class="batch-actions"><button id="preview-analysis-reanalyze" class="button-secondary" type="button" data-i18n="预览重建费用">预览重建费用</button><button id="start-analysis-reanalyze" type="button" disabled hidden data-i18n="确认付费并重建">确认付费并重建</button></div></details>
+ </div></div>
+ <div id="analysis-batch-summary" class="batch-summary" data-i18n="先生成预览,不会直接产生 API 请求。">先生成预览,不会直接产生 API 请求。</div>
+
+ <div id="analysis-progress" class="maintenance-progress" hidden><progress id="analysis-progress-bar" max="1" value="0"></progress></div>
+
+ <details class="task-diagnostics"><summary data-i18n="故障诊断">故障诊断</summary><label class="ai-consent"><input id="show-analysis-diagnostics" type="checkbox" /><span data-i18n="显示故障诊断(仅排查问题时开启)">显示故障诊断(仅排查问题时开启)</span></label><details id="analysis-diagnostics" class="analysis-diagnostics" hidden>
+ <summary><span data-i18n="分析诊断">分析诊断</span><span id="analysis-runtime-version"></span></summary>
+ <div class="analysis-diagnostics-heading"><p data-i18n="仅记录运行版本、阶段、标签数量、耗时和错误类别;不记录案例原文、API Key 或模型完整输出。">仅记录运行版本、阶段、标签数量、耗时和错误类别;不记录案例原文、API Key 或模型完整输出。</p><button id="copy-analysis-diagnostics" class="button-secondary" type="button" data-i18n="复制诊断日志">复制诊断日志</button></div>
+ <ol id="analysis-diagnostic-events"></ol>
+ </details></details><details class="advanced-reanalysis"><summary data-i18n="重建标签系统">重建标签系统</summary><p data-i18n="付费重跑全部文字案例;结果先暂存,全部成功后一次切换,并可完整撤回。">付费重跑全部文字案例;结果先暂存,全部成功后一次切换,并可完整撤回。</p><div class="batch-actions"><button id="preview-analysis-reanalyze" class="button-secondary" type="button" data-i18n="预览重建费用">预览重建费用</button><button id="start-analysis-reanalyze" type="button" disabled hidden data-i18n="确认付费并重建">确认付费并重建</button></div></details>
</div>
- <div class="batch-card local-index-card">
- <h3 data-i18n="资料索引自动补全">资料索引自动补全</h3>
- <p data-i18n="每次导入后会在本机自动补齐内容类型和图片色卡,不调用 AI。这里可查看状态或重试失败项。">每次导入后会在本机自动补齐内容类型和图片色卡,不调用 AI。这里可查看状态或重试失败项。</p>
- <div class="batch-actions">
+ <div class="batch-card local-index-card"><div class="task-heading"><h3 data-i18n="资料索引自动补全">资料索引自动补全</h3><div class="batch-actions">
<button id="preview-reanalyze" type="button" data-i18n="检查缺失项">检查缺失项</button>
<button id="apply-reanalyze" type="button" hidden data-i18n="开始补全">开始补全</button>
<button id="pause-library-maintenance" class="button-secondary" type="button" hidden data-i18n="暂停">暂停</button>
<button id="resume-library-maintenance" type="button" hidden data-i18n="继续">继续</button>
<button id="retry-library-maintenance" class="button-secondary" type="button" hidden data-i18n="重试失败项">重试失败项</button>
<button id="cancel-library-maintenance" class="quiet-danger" type="button" hidden data-i18n="取消">取消</button>
- </div>
+ </div></div>
<div id="reanalyze-preview" class="reanalyze-preview" role="status" aria-live="polite"></div>
</div>
<div id="legacy-candidates" class="batch-card"></div>
</section>
<section id="settings-ai-panel" class="settings-panel settings-ai-panel" data-settings-panel="ai" hidden>
<section class="ai-routing-card">
- <div class="ai-routing-heading"><h3 data-i18n="AI 配置">AI 配置</h3><p id="ai-routing-summary" data-i18n="AI 服务只连接一次;任务路由显示每类功能实际调用哪个服务与模型。">AI 服务只连接一次;任务路由显示每类功能实际调用哪个服务与模型。</p></div>
+ <div class="ai-routing-heading"><p id="ai-routing-summary" hidden></p></div>
<nav class="ai-routing-tabs" role="tablist" aria-label="AI 配置视图" data-i18n-aria-label="AI 配置视图">
- <button type="button" data-ai-routing-tab="tasks" aria-selected="true" data-i18n="任务路由">任务路由</button>
+ <button type="button" data-ai-routing-tab="tasks" aria-selected="true" data-i18n="任务模型">任务模型</button>
<button type="button" data-ai-routing-tab="providers" aria-selected="false" data-i18n="服务连接">服务连接</button>
</nav>
<div class="ai-routing-regions">
- <section class="ai-task-region" data-ai-routing-panel="tasks"><h4 data-i18n="各任务实际路由">各任务实际路由</h4><div id="ai-assignment-list" class="ai-assignment-list"></div></section>
+ <section class="ai-task-region" data-ai-routing-panel="tasks"><div id="ai-assignment-list" class="ai-assignment-list"></div></section>
<section data-ai-routing-panel="providers" hidden><div class="ai-provider-region-heading"><h4 data-i18n="服务连接">服务连接</h4><button id="open-ai-routing" type="button" data-i18n="连接 AI 服务">连接 AI 服务</button></div><div id="ai-provider-list" class="ai-provider-list"></div></section>
</div>
</section>
@@ -398,28 +395,28 @@
<button type="button" data-analysis-kind="composer" aria-selected="false" data-i18n="创作方法">创作方法</button>
</div>
<form id="ai-settings-form" class="analysis-settings-form" data-analysis-kind-panel="text">
- <div class="section-heading"><div><h3 data-i18n="文字分析规则">文字分析规则</h3><p data-i18n="这里只显示当前界面语言的规则;切换界面语言后可编辑另一语言。修改不会自动调用 API。">这里只显示当前界面语言的规则;切换界面语言后可编辑另一语言。修改不会自动调用 API。</p></div></div>
+ <div class="rule-toolbar"><h3 id="ai-settings-form-heading-1" data-i18n="文字分析规则">文字分析规则</h3><button class="icon-button" title="恢复默认" aria-label="恢复默认" data-i18n-title="恢复默认" data-i18n-aria-label="恢复默认" id="restore-analysis-default" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-refresh-cw"></use></svg></button><button class="icon-button" title="保存分析规则" aria-label="保存分析规则" data-i18n-title="保存分析规则" data-i18n-aria-label="保存分析规则" type="submit"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-save"></use></svg></button><span id="ai-settings-status" class="rule-save-state" role="status"></span></div>
<section data-analysis-locale-panel="zh-CN">
- <label><span data-i18n="中文分析规则">中文分析规则</span><textarea id="analysis-instructions-zh" rows="10"></textarea></label>
+ <label><textarea aria-labelledby="ai-settings-form-heading-1" id="analysis-instructions-zh" rows="10"></textarea></label>
</section>
<section data-analysis-locale-panel="en" hidden>
- <label><span>English analysis rules</span><textarea id="analysis-instructions-en" rows="10"></textarea></label>
+ <label><textarea aria-labelledby="ai-settings-form-heading-1" id="analysis-instructions-en" rows="10"></textarea></label>
</section>
- <div class="analysis-rule-actions"><button id="restore-analysis-default" class="button-secondary" type="button" data-i18n="恢复默认">恢复默认</button></div>
+
<details class="analysis-protocol"><summary data-i18n="固定输入与输出协议">固定输入与输出协议</summary><p id="analysis-protocol"></p></details>
- <div class="analysis-settings-actions"><button type="submit" data-i18n="保存分析规则">保存分析规则</button></div>
- <p id="ai-settings-status"></p>
+
+
</form>
<form id="composer-settings-form" class="analysis-settings-form" data-analysis-kind-panel="composer" hidden>
- <div class="section-heading"><div><h3 data-i18n="轻量 Agent">轻量 Agent</h3><p data-i18n="系统指令和任务方法分开管理;所有输出语言共用同一份任务方法。">系统指令和任务方法分开管理;所有输出语言共用同一份任务方法。</p></div><span id="composer-method-version" class="status-badge"></span></div>
- <label><span data-i18n="Agent 系统指令">Agent 系统指令</span><textarea id="composer-agent-instruction" rows="10"></textarea></label>
- <div class="analysis-settings-actions"><button id="save-composer-agent" class="button-secondary" type="button" data-i18n="保存系统指令">保存系统指令</button><button id="restore-composer-agent" class="button-secondary" type="button" data-i18n="恢复默认系统指令">恢复默认系统指令</button></div>
+
+ <div class="rule-toolbar"><h3 id="composer-settings-form-heading-1" data-i18n="Agent 系统指令">Agent 系统指令</h3><button class="icon-button" title="恢复默认系统指令" aria-label="恢复默认系统指令" data-i18n-title="恢复默认系统指令" data-i18n-aria-label="恢复默认系统指令" id="restore-composer-agent" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-refresh-cw"></use></svg></button><button class="icon-button" title="保存系统指令" aria-label="保存系统指令" data-i18n-title="保存系统指令" data-i18n-aria-label="保存系统指令" id="save-composer-agent" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-save"></use></svg></button><span id="composer-agent-save-state" class="rule-save-state" role="status"></span><span id="composer-method-version" class="status-badge"></span></div><label><textarea aria-labelledby="composer-settings-form-heading-1" id="composer-agent-instruction" rows="10"></textarea></label>
+
<label><span data-i18n="任务方法">任务方法</span><select id="composer-task-key"><option value="compose.image" data-i18n="图片提示词">图片提示词</option><option value="compose.video" data-i18n="视频提示词">视频提示词</option><option value="analyze_materials" data-i18n="本地资料分析">本地资料分析</option><option value="chat" data-i18n="普通对话">普通对话</option></select></label>
- <label><span data-i18n="当前任务方法">当前任务方法</span><textarea id="composer-task-method" rows="10"></textarea></label>
+ <div class="rule-toolbar"><h3 id="composer-settings-form-heading-2" data-i18n="当前任务方法">当前任务方法</h3><button class="icon-button" title="恢复当前任务默认方法" aria-label="恢复当前任务默认方法" data-i18n-title="恢复当前任务默认方法" data-i18n-aria-label="恢复当前任务默认方法" id="restore-composer-task" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-refresh-cw"></use></svg></button><button class="icon-button" title="保存任务方法" aria-label="保存任务方法" data-i18n-title="保存任务方法" data-i18n-aria-label="保存任务方法" type="submit"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-save"></use></svg></button><span id="composer-task-save-state" class="rule-save-state" role="status"></span></div><label><textarea aria-labelledby="composer-settings-form-heading-2" id="composer-task-method" rows="10"></textarea></label>
<p id="composer-method-migration" class="privacy-note"></p>
<details class="composer-method-default"><summary data-i18n="查看当前任务默认方法">查看当前任务默认方法</summary><pre id="composer-method-default-text"></pre></details>
<details class="analysis-protocol"><summary data-i18n="轻量执行协议">轻量执行协议</summary><p data-i18n="第一阶段只判断任务、必要问题和本地检索;第二阶段按自然语言执行说明流式生成。规划缺少可选字段时会透明提示,并按原始要求继续。">第一阶段只判断任务、必要问题和本地检索;第二阶段按自然语言执行说明流式生成。规划缺少可选字段时会透明提示,并按原始要求继续。</p></details>
- <div class="analysis-settings-actions"><button type="submit" data-i18n="保存任务方法">保存任务方法</button><button id="restore-composer-task" class="button-secondary" type="button" data-i18n="恢复当前任务默认方法">恢复当前任务默认方法</button></div>
+
<p id="composer-settings-status"></p>
<details class="creative-experiment-settings">
<summary data-i18n="创作实验(高级)">创作实验(高级)</summary>
@@ -438,30 +435,30 @@
</details>
</form>
<form id="vision-settings-form" class="analysis-settings-form" data-analysis-kind-panel="vision" hidden>
- <div class="section-heading"><div><h3 data-i18n="图片视觉分析规则">图片视觉分析规则</h3></div></div>
+ <div class="rule-toolbar"><h3 id="vision-settings-form-heading-1" data-i18n="图片视觉分析规则">图片视觉分析规则</h3><button class="icon-button" title="恢复默认" aria-label="恢复默认" data-i18n-title="恢复默认" data-i18n-aria-label="恢复默认" id="restore-vision-default" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-refresh-cw"></use></svg></button><button class="icon-button" title="保存分析规则" aria-label="保存分析规则" data-i18n-title="保存分析规则" data-i18n-aria-label="保存分析规则" type="submit"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-save"></use></svg></button><span id="vision-settings-status" class="rule-save-state" role="status"></span></div>
<section data-analysis-locale-panel="zh-CN">
- <label><span data-i18n="中文图片分析规则">中文图片分析规则</span><textarea id="vision-instructions-zh" rows="10"></textarea></label>
+ <label><textarea aria-labelledby="vision-settings-form-heading-1" id="vision-instructions-zh" rows="10"></textarea></label>
</section>
<section data-analysis-locale-panel="en" hidden>
- <label><span>English vision rules</span><textarea id="vision-instructions-en" rows="10"></textarea></label>
+ <label><textarea aria-labelledby="vision-settings-form-heading-1" id="vision-instructions-en" rows="10"></textarea></label>
</section>
- <div class="analysis-rule-actions"><button id="restore-vision-default" class="button-secondary" type="button" data-i18n="恢复默认">恢复默认</button></div>
+
<details class="analysis-protocol"><summary data-i18n="固定输入与输出协议">固定输入与输出协议</summary><p id="vision-protocol"></p></details>
- <div class="analysis-settings-actions"><button type="submit" data-i18n="保存分析规则">保存分析规则</button></div>
- <p id="vision-settings-status"></p>
+
+
</form>
<form id="video-settings-form" class="analysis-settings-form" data-analysis-kind-panel="video" hidden>
- <div class="section-heading"><div><h3 data-i18n="视频逆推规则">视频逆推规则</h3><p data-i18n="这里只管理视频提示词逆推的方法;固定输出结构与证据校验不会被覆盖。">这里只管理视频提示词逆推的方法;固定输出结构与证据校验不会被覆盖。</p></div></div>
+ <div class="rule-toolbar"><h3 id="video-settings-form-heading-1" data-i18n="视频逆推分析规则">视频逆推分析规则</h3><button class="icon-button" title="恢复默认" aria-label="恢复默认" data-i18n-title="恢复默认" data-i18n-aria-label="恢复默认" id="restore-video-default" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-refresh-cw"></use></svg></button><button class="icon-button" title="保存分析规则" aria-label="保存分析规则" data-i18n-title="保存分析规则" data-i18n-aria-label="保存分析规则" type="submit"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-save"></use></svg></button><span id="video-settings-status" class="rule-save-state" role="status"></span></div>
<section data-analysis-locale-panel="zh-CN">
- <label><span data-i18n="中文视频逆推规则">中文视频逆推规则</span><textarea id="video-instructions-zh" rows="8"></textarea></label>
+ <label><textarea aria-labelledby="video-settings-form-heading-1" id="video-instructions-zh" rows="8"></textarea></label>
</section>
<section data-analysis-locale-panel="en" hidden>
- <label><span>English video reconstruction rules</span><textarea id="video-instructions-en" rows="8"></textarea></label>
+ <label><textarea aria-labelledby="video-settings-form-heading-1" id="video-instructions-en" rows="8"></textarea></label>
</section>
- <div class="analysis-rule-actions"><button id="restore-video-default" class="button-secondary" type="button" data-i18n="恢复默认">恢复默认</button></div>
+
<details class="analysis-protocol"><summary data-i18n="固定输入与输出协议">固定输入与输出协议</summary><p id="video-protocol"></p></details>
- <div class="analysis-settings-actions"><button type="submit" data-i18n="保存分析规则">保存分析规则</button></div>
- <p id="video-settings-status"></p>
+
+
</form>
</section>
</div>
diff --git a/library.js b/library.js
index d922a0b..95430c5 100644
--- a/library.js
+++ b/library.js
@@ -153,7 +153,8 @@ import {
officialMediaEmbedUrl,
resolveMediaReference
} from "./media-reference-resolver.js";
-import { ensureYouTubePlaybackPermission, youtubePlaybackError } from "./media-playback.js";
+import { attachRemoteVideo } from "./remote-video-player.js";
+import { localVideoController, ensureYouTubePlaybackPermission, youtubePlaybackError, tiktokMediaController, EMBED_PLAYER_RESPONSE_TIMEOUT_MS } from "./media-playback.js";
import { createPdfPreview, createPdfViewer, extractPdfSearchText } from "./document-viewer.js";
import { markdownPlainText, renderMarkdownDocument } from "./markdown-renderer.js";
import {
@@ -216,7 +217,7 @@ bindTransientMenus(document, ".package-menu, .project-menu, .detail-project-menu
const libraryWindowId = (await chrome.windows.getCurrent()).id;
const elements = Object.fromEntries([
- "about-version", "add-folder", "add-media", "add-video-reference", "ai-settings-form", "ai-settings-status", "ai-routing-summary", "ai-provider-list", "ai-assignment-list", "open-ai-routing", "analysis-instructions-en", "analysis-instructions-zh", "analysis-protocol", "apply-reanalyze", "case-list", "project-folder-list", "cancel-library-maintenance",
+ "about-version", "add-folder", "add-media", "add-video-reference", "settings-rules-panel", "ai-settings-form", "ai-settings-status", "ai-routing-summary", "ai-provider-list", "ai-assignment-list", "open-ai-routing", "analysis-instructions-en", "analysis-instructions-zh", "analysis-protocol", "apply-reanalyze", "case-list", "project-folder-list", "cancel-library-maintenance",
"content-filters", "content-type-count", "content-type-name", "content-type-replacement", "content-type-replacement-field", "content-type-role", "content-type-role-help",
"content-type-list", "content-type-editor", "content-type-editor-title", "content-type-delete-transfer", "content-type-delete-message",
"add-content-type", "cancel-content-type-edit", "cancel-delete-content-type", "confirm-delete-content-type", "save-content-type",
@@ -232,7 +233,7 @@ const elements = Object.fromEntries([
"new-node-name", "new-node-parent", "pending-count", "pending-filter",
"add-quick-note", "organize-detail-tags", "organize-detail-status", "pause-analysis-batch", "pause-library-maintenance", "preview-analysis-batch", "preview-analysis-reanalyze", "preview-reanalyze", "reanalyze-preview", "result-count", "resume-analysis-batch", "resume-library-maintenance", "retry-analysis-failures", "retry-library-maintenance", "start-analysis-reanalyze",
"project-selection-actions", "project-selection-cancel", "project-selection-clear", "project-selection-count", "project-selection-save", "project-selection-select-all", "project-selection-select-filtered", "project-selection-title", "project-order-status", "restore-analysis-default", "search-input", "share-bar", "share-cancel", "share-count", "share-export", "start-analysis-batch", "start-compose", "toggle-filters", "undo-analysis-batch", "undo-facet", "vocabulary-facet", "workspace-library", "workspace-unassigned",
- "share-dialog", "share-dialog-close", "share-dialog-title", "share-dialog-meta", "share-dialog-options", "share-dialog-export", "share-dialog-submit", "share-dialog-disclosure", "share-dialog-result", "share-dialog-result-text", "share-dialog-show-files", "share-dialog-open-form",
+ "share-dialog", "share-dialog-public", "share-dialog-public-panel", "share-dialog-close", "share-dialog-title", "share-dialog-meta", "share-dialog-options", "share-dialog-export", "share-dialog-submit", "share-dialog-disclosure", "share-dialog-result", "share-dialog-result-text", "share-dialog-show-files", "share-dialog-open-form",
"add-menu", "export-path-setting", "media-file", "media-folder", "library-name-setting", "save-library-settings", "select-cases", "selection-select-filtered", "selection-clear", "selection-label-input", "selection-add-labels", "selection-add-project", "selection-move-project", "selection-remove-project", "selection-new-project", "selection-combine", "selection-analyze", "selection-video-analyze", "selection-project-impact", "selection-project-target", "selection-trash", "open-settings", "settings-dialog", "settings-close", "settings-update-badge", "open-about", "local-extension-package", "library-settings-feedback", "update-status", "check-extension-update", "apply-extension-update", "update-feedback",
"project-section", "project-root-drop", "collapse-projects", "project-search", "project-move-feedback", "project-move-undo", "selection-simple-actions", "selection-selected-actions", "show-analysis-diagnostics", "ui-locale", "ui-theme", "ui-motion", "vocabulary-tree",
"vision-instructions-en", "vision-instructions-zh", "vision-protocol", "vision-settings-form", "vision-settings-status", "restore-vision-default",
@@ -300,6 +301,10 @@ let importJobsState = { items: [] };
let aiSettings = { configured: false, consent: false, analysisModel: "deepseek-v4-flash" };
let visionSettings = normalizeVisionSettings();
let aiServiceProfiles = { gemini: { configured: false, model: "" }, xai: { configured: false, textModel: "", imageModel: "", videoModel: "" } };
+const ruleEditorDrafts = new Map();
+const ruleEditorBaselines = new Map();
+const settingsPanelScroll = new Map();
+
let aiProviderRegistry = { version: 1, providers: {} };
let aiTaskAssignments = {};
let aiPreferences = { videoInstructionsByLocale: DEFAULT_VIDEO_ANALYSIS_INSTRUCTIONS_BY_LOCALE };
@@ -543,7 +548,7 @@ function renderAnalysisBatch() {
: t(preview.mode === "rebuild" ? "没有可重建的文字案例。" : "没有需要分析的案例:现有文字均已分析且原文未变化。");
} else if (!job) {
elements.batchStatusBadge.textContent = t("尚未开始");
- elements.analysisBatchSummary.textContent = t("先生成预览,不会直接产生 API 请求。");
+ elements.analysisBatchSummary.textContent = "";
} else {
const statusNames = { running: "分析中", paused: "已暂停", completed: unfinishedRebuild ? "重建待完成" : partialRebuildApplied ? "成功结果已应用" : "已完成", partial: "有失败项", failed: "分析失败", canceled: "上次已取消" };
elements.batchStatusBadge.textContent = t(statusNames[job.status] || job.status);
@@ -657,6 +662,7 @@ function bindEvents() {
if (dataSafetyOperationActive) event.preventDefault();
});
settingsTabs.forEach((button) => button.addEventListener("click", () => {
+ settingsPanelScroll.set(activeSettingsTab, document.querySelector(`[data-settings-panel="${activeSettingsTab}"]`)?.scrollTop || 0);
activeSettingsTab = button.dataset.settingsTab || "general";
renderSettingsPanels({ resetActiveScroll: true });
}));
@@ -763,6 +769,12 @@ function bindEvents() {
elements.shareDialog.addEventListener("click", (event) => {
if (event.target === elements.shareDialog) closeShareDialog();
});
+ elements.shareDialogPublic.addEventListener("click", () => {
+ const expanded = elements.shareDialogPublicPanel.hidden;
+ elements.shareDialogPublicPanel.hidden = !expanded;
+ elements.shareDialogPublic.setAttribute("aria-expanded", String(expanded));
+ if (expanded) elements.shareDialogDisclosure.focus();
+ });
elements.shareDialogDisclosure.addEventListener("change", () => {
elements.shareDialogSubmit.disabled = !elements.shareDialogDisclosure.checked;
});
@@ -812,6 +824,14 @@ function bindEvents() {
activeManagerTab = button.dataset.managerTab;
renderManager();
}));
+ elements.settingsRulesPanel.addEventListener("input", (event) => {
+ const editor = event.target;
+ const key = editor.dataset.ruleDraftKey;
+ if (!key) return;
+ if (editor.value === ruleEditorBaselines.get(key)) ruleEditorDrafts.delete(key);
+ else ruleEditorDrafts.set(key, editor.value);
+ renderRuleDraftStatus();
+ });
analysisKindTabs.forEach((button) => button.addEventListener("click", () => {
preserveSettingsAnchor(button.closest(".analysis-kind-tabs"), () => {
activeAnalysisKind = button.dataset.analysisKind;
@@ -890,6 +910,7 @@ function bindEvents() {
elements.restoreAnalysisDefault.addEventListener("click", () => {
const target = activeAnalysisLocale === "en" ? elements.analysisInstructionsEn : elements.analysisInstructionsZh;
target.value = DEFAULT_ANALYSIS_INSTRUCTIONS_BY_LOCALE[activeAnalysisLocale];
+ target.dispatchEvent(new Event("input", { bubbles: true }));
target.focus();
showFeedback(t("已恢复编辑框默认内容,点击保存后生效"));
});
@@ -897,6 +918,7 @@ function bindEvents() {
elements.restoreVisionDefault.addEventListener("click", () => {
const target = activeAnalysisLocale === "en" ? elements.visionInstructionsEn : elements.visionInstructionsZh;
target.value = DEFAULT_VISION_INSTRUCTIONS_BY_LOCALE[activeAnalysisLocale];
+ target.dispatchEvent(new Event("input", { bubbles: true }));
target.focus();
showFeedback(t("已恢复编辑框默认内容,点击保存后生效"));
});
@@ -904,6 +926,7 @@ function bindEvents() {
elements.restoreVideoDefault.addEventListener("click", () => {
const target = activeAnalysisLocale === "en" ? elements.videoInstructionsEn : elements.videoInstructionsZh;
target.value = DEFAULT_VIDEO_ANALYSIS_INSTRUCTIONS_BY_LOCALE[activeAnalysisLocale];
+ target.dispatchEvent(new Event("input", { bubbles: true }));
target.focus();
showFeedback(t("已恢复编辑框默认内容,点击保存后生效"));
});
@@ -2648,6 +2671,8 @@ function openShareDialog({ entryIds = [], collectionId = "", title = "", count =
submissionDownloadIds = [];
elements.shareDialogTitle.textContent = title || t("分享案例");
elements.shareDialogMeta.textContent = t("{count} 个案例", { count: selectedCount });
+ elements.shareDialogPublicPanel.hidden = true;
+ elements.shareDialogPublic.setAttribute("aria-expanded", "false");
elements.shareDialogDisclosure.checked = false;
elements.shareDialogSubmit.disabled = true;
elements.shareDialogExport.disabled = true;
@@ -2792,6 +2817,7 @@ async function submitFromShareDialog() {
: t("投稿包已生成");
elements.shareDialogResult.hidden = false;
elements.shareDialogOptions.hidden = true;
+ elements.shareDialogPublicPanel.hidden = true;
} catch (error) {
showFeedback(error.message || t("无法生成精选投稿包"), true);
elements.shareDialogSubmit.disabled = false;
@@ -3149,7 +3175,11 @@ function openSettingsDialog(tab = "general", analysisKind = activeAnalysisKind)
function renderSettingsPanels({ resetActiveScroll = false } = {}) {
settingsTabs.forEach((button) => button.setAttribute("aria-selected", String(button.dataset.settingsTab === activeSettingsTab)));
settingsPanels.forEach((panel) => { panel.hidden = panel.dataset.settingsPanel !== activeSettingsTab; });
- if (resetActiveScroll) resetActiveSettingsPanelScroll();
+ if (resetActiveScroll) {
+ resetActiveSettingsPanelScroll();
+ const panel = document.querySelector(`[data-settings-panel="${activeSettingsTab}"]`);
+ if (panel) panel.scrollTop = settingsPanelScroll.get(activeSettingsTab) || 0;
+ }
if (activeSettingsTab === "ai") renderAiRoutingSummary();
if (activeSettingsTab === "rules") renderAnalysisSettings();
if (activeSettingsTab === "tasks") renderBatchManager();
@@ -6327,6 +6357,28 @@ async function createReferencedMediaViewer(asset, entry) {
const url = asset.reference?.url || asset.sourceUrl;
const provider = asset.reference?.provider || "generic";
const providerLabel = mediaReferenceProviderLabel(provider);
+ if (asset.reference?.playbackUrl || asset.reference?.streamUrl) {
+ const wrap = el("div", "detail-video-wrap referenced-video-stream");
+ const video = document.createElement("video");
+ video.className = "detail-video";
+ video.controls = true;
+ video.playsInline = true;
+ video.preload = "metadata";
+ const poster = posterAssetForVideo(entry, asset);
+ const blob = poster ? await getMediaBlob(poster.id) : null;
+ if (blob) video.poster = rememberDetailBlobUrl(blob);
+ const status = textEl("p", "media-playback-status", "播放器正在加载…");
+ const source = textEl("a", "button-secondary media-reference-fallback", "打开来源");
+ source.href = url;
+ source.target = "_blank";
+ source.rel = "noopener noreferrer";
+ wrap.append(video, status, source);
+ wrap.mediaController = await attachRemoteVideo(video, asset.reference, (message, failed) => {
+ status.textContent = t(message);
+ status.classList.toggle("error", failed);
+ });
+ return wrap;
+ }
const embedUrl = officialMediaEmbedUrl(url, provider);
if (provider === "youtube" && embedUrl && !await ensureYouTubePlaybackPermission(chrome, { request: false })) {
return createPlaybackFallback(entry, asset, {
@@ -6359,7 +6411,12 @@ async function createReferencedMediaViewer(asset, entry) {
? vimeoMediaController(frame)
: provider === "youtube"
? youtubeMediaController(frame, status, asset.id)
- : basicEmbedController(frame, status, providerLabel);
+ : provider === "tiktok"
+ ? tiktokMediaController(frame, (message, failed) => {
+ status.textContent = t(message);
+ status.classList.toggle("error", failed);
+ })
+ : basicEmbedController(frame, status, providerLabel);
const source = textEl("a", "button-secondary media-reference-fallback", "打开来源");
source.href = provider === "youtube" ? youtubeWatchUrl(url) : url;
source.target = "_blank";
@@ -6370,29 +6427,26 @@ async function createReferencedMediaViewer(asset, entry) {
wrap.mediaController = controller;
return wrap;
}
- return createPlaybackFallback(entry, asset, { providerLabel, reason: "此来源没有可验证的官方内嵌播放器" });
+ return createPlaybackFallback(entry, asset, { providerLabel, reason: "暂未取得可在案例库播放的视频" });
}
async function createPlaybackFallback(entry, asset, { providerLabel, reason, actionLabel = "", onAction = null }) {
const url = asset.reference?.url || asset.sourceUrl;
- const card = el("div", "platform-link-card platform-playback-fallback");
+ const card = el("div", "detail-video-wrap platform-playback-fallback");
+ const stage = el("div", "detail-video unavailable-video-stage");
+ stage.setAttribute("role", "img");
+ stage.setAttribute("aria-label", t("视频暂不可播放"));
const poster = posterAssetForVideo(entry, asset);
const posterBlob = poster ? await getMediaBlob(poster.id) : null;
if (posterBlob) {
const image = document.createElement("img");
image.src = rememberDetailBlobUrl(posterBlob);
image.alt = `${entry.title || providerLabel} 封面`;
- card.append(image);
+ stage.append(image);
}
- card.classList.toggle("has-poster", Boolean(posterBlob));
- if (!posterBlob) card.append(createUiIcon("video"));
- const label = el("span", "platform-link-label");
- label.append(
- textEl("small", "", providerLabel.toLocaleUpperCase("en-US")),
- rawTextEl("strong", "", entry.title || asset.sourceTitle || `${providerLabel} 视频`),
- rawTextEl("span", "", t(reason))
- );
- const actions = el("span", "platform-link-actions");
+ if (!posterBlob) stage.append(createUiIcon("video"));
+ const status = rawTextEl("p", "media-playback-status", t(reason));
+ const actions = el("div", "media-playback-actions");
if (actionLabel && onAction) {
const action = textEl("button", "", actionLabel);
action.addEventListener("click", () => onAction(action));
@@ -6406,8 +6460,7 @@ async function createPlaybackFallback(entry, asset, { providerLabel, reason, act
open.rel = "noopener noreferrer";
actions.append(open);
}
- label.append(actions);
- card.append(label);
+ card.append(stage, status, actions);
return card;
}
@@ -6417,7 +6470,7 @@ function youtubeMediaController(frame, status, playerId) {
const origin = "https://www.youtube-nocookie.com";
const timeoutId = setTimeout(() => {
if (!ready) status.textContent = t("播放器响应超时,可重试或打开来源");
- }, 8000);
+ }, EMBED_PLAYER_RESPONSE_TIMEOUT_MS);
const onMessage = (event) => {
if (event.origin !== origin || event.source !== frame.contentWindow) return;
const payload = typeof event.data === "string" ? safeJson(event.data) : event.data;
@@ -6456,7 +6509,7 @@ function youtubeMediaController(frame, status, playerId) {
function basicEmbedController(frame, status, providerLabel) {
let timeoutId = setTimeout(() => {
status.textContent = t("{provider} 播放器响应超时,可打开来源", { provider: providerLabel });
- }, 8000);
+ }, EMBED_PLAYER_RESPONSE_TIMEOUT_MS);
const loaded = () => {
clearTimeout(timeoutId);
timeoutId = null;
@@ -6594,16 +6647,6 @@ async function saveVideoKeyframe(button, video, entry, asset, text) {
}
}
-function localVideoController(video) {
- return {
- video,
- getCurrentTimeMs: async () => Math.max(0, Math.round(video.currentTime * 1000)),
- seekToMs: async (value) => {
- video.currentTime = Math.max(0, Number(value) || 0) / 1000;
- await video.play().catch(() => undefined);
- }
- };
-}
function vimeoMediaController(frame) {
const pending = new Map();
@@ -8930,19 +8973,41 @@ function renderBatchManager() {
);
}
+function renderRuleEditor(editor, savedValue, key = editor.id) {
+ editor.dataset.ruleDraftKey = key;
+ ruleEditorBaselines.set(key, savedValue);
+ editor.value = ruleEditorDrafts.has(key) ? ruleEditorDrafts.get(key) : savedValue;
+}
+
+function forgetSavedRuleDraft(key, submittedValue) {
+ if (ruleEditorDrafts.get(key) === submittedValue) ruleEditorDrafts.delete(key);
+}
+
+function renderRuleDraftStatus() {
+ const groups = [
+ [elements.aiSettingsStatus, ["analysis-instructions-zh", "analysis-instructions-en"]],
+ [elements.visionSettingsStatus, ["vision-instructions-zh", "vision-instructions-en"]],
+ [elements.videoSettingsStatus, ["video-instructions-zh", "video-instructions-en"]],
+ [document.getElementById("composer-agent-save-state"), ["composer-agent-instruction"]],
+ [document.getElementById("composer-task-save-state"), [`composer-task-method:${elements.composerTaskKey.value}`]]
+ ];
+ for (const [status, keys] of groups) {
+ const dirty = keys.some((key) => ruleEditorDrafts.has(key));
+ status.textContent = t(dirty ? "未保存" : "已保存");
+ status.dataset.dirty = String(dirty);
+ }
+}
+
function renderAnalysisSettings() {
analysisKindTabs.forEach((button) => button.setAttribute("aria-selected", String(button.dataset.analysisKind === activeAnalysisKind)));
analysisKindPanels.forEach((panel) => { panel.hidden = panel.dataset.analysisKindPanel !== activeAnalysisKind; });
elements.showAnalysisDiagnostics.checked = uiPreferences.analysisDiagnostics;
- elements.analysisInstructionsZh.value = aiSettings.analysisInstructionsByLocale?.["zh-CN"] || DEFAULT_ANALYSIS_INSTRUCTIONS_BY_LOCALE["zh-CN"];
- elements.analysisInstructionsEn.value = aiSettings.analysisInstructionsByLocale?.en || DEFAULT_ANALYSIS_INSTRUCTIONS_BY_LOCALE.en;
- elements.aiSettingsStatus.textContent = t("规则保存在本机,只在对应任务运行时使用。");
- elements.visionInstructionsZh.value = visionSettings.instructionsByLocale?.["zh-CN"] || DEFAULT_VISION_INSTRUCTIONS_BY_LOCALE["zh-CN"];
- elements.visionInstructionsEn.value = visionSettings.instructionsByLocale?.en || DEFAULT_VISION_INSTRUCTIONS_BY_LOCALE.en;
- elements.visionSettingsStatus.textContent = t("规则保存在本机,只在对应任务运行时使用。");
- elements.videoInstructionsZh.value = aiPreferences.videoInstructionsByLocale?.["zh-CN"] || DEFAULT_VIDEO_ANALYSIS_INSTRUCTIONS_BY_LOCALE["zh-CN"];
- elements.videoInstructionsEn.value = aiPreferences.videoInstructionsByLocale?.en || DEFAULT_VIDEO_ANALYSIS_INSTRUCTIONS_BY_LOCALE.en;
- elements.videoSettingsStatus.textContent = t("规则保存在本机,只在对应任务运行时使用。");
+ renderRuleEditor(elements.analysisInstructionsZh, aiSettings.analysisInstructionsByLocale?.["zh-CN"] || DEFAULT_ANALYSIS_INSTRUCTIONS_BY_LOCALE["zh-CN"]);
+ renderRuleEditor(elements.analysisInstructionsEn, aiSettings.analysisInstructionsByLocale?.en || DEFAULT_ANALYSIS_INSTRUCTIONS_BY_LOCALE.en);
+ renderRuleEditor(elements.visionInstructionsZh, visionSettings.instructionsByLocale?.["zh-CN"] || DEFAULT_VISION_INSTRUCTIONS_BY_LOCALE["zh-CN"]);
+ renderRuleEditor(elements.visionInstructionsEn, visionSettings.instructionsByLocale?.en || DEFAULT_VISION_INSTRUCTIONS_BY_LOCALE.en);
+ renderRuleEditor(elements.videoInstructionsZh, aiPreferences.videoInstructionsByLocale?.["zh-CN"] || DEFAULT_VIDEO_ANALYSIS_INSTRUCTIONS_BY_LOCALE["zh-CN"]);
+ renderRuleEditor(elements.videoInstructionsEn, aiPreferences.videoInstructionsByLocale?.en || DEFAULT_VIDEO_ANALYSIS_INSTRUCTIONS_BY_LOCALE.en);
elements.videoProtocol.textContent = t("一次有效结果返回提示词、AI 标签和不确定项;必要时自动补救,每轮最多 {requests} 次请求,其中格式纠正最多 {corrections} 次。超时、停止或状态未知不自动重发。", {
requests: ANALYSIS_RETRY_POLICY.maxProviderCallsPerItem,
corrections: ANALYSIS_RETRY_POLICY.outputCorrectionRequests
@@ -8950,6 +9015,7 @@ function renderAnalysisSettings() {
renderComposerMethodSettings();
renderAnalysisLocale();
renderAiRoutingSummary();
+ renderRuleDraftStatus();
}
function renderAiRoutingSummary() {
@@ -8959,29 +9025,49 @@ function renderAiRoutingSummary() {
elements.aiRoutingSummary.textContent = connected.length
? t("已连接 {count} 个服务;文字、图片、视频与生成任务各自明确分配,不会静默切换。", { count: connected.length })
: t("尚未连接 AI 服务;本地资料整理仍可使用。");
+ const moreProviders = document.createElement("details");
+ moreProviders.className = "ai-more-providers";
+ moreProviders.open = elements.aiProviderList?.querySelector(".ai-more-providers")?.open || false;
+ moreProviders.append(textEl("summary", "", "连接其他服务"));
const categoryLabels = { official: "官方服务", aggregator: "聚合平台", custom: "自定义兼容服务" };
const providerGroups = Object.entries(categoryLabels).flatMap(([category, label]) => {
const members = profiles.filter((profile) => profile.category === category);
if (!members.length) return [];
const group = el("section", "ai-provider-group");
group.dataset.providerCategory = category;
- group.append(rawTextEl("h5", "", t(label)), ...members.map((profile) => {
+ group.setAttribute("aria-label", t(label));
+ group.append(...members.map((profile) => {
const row = el("div", "ai-provider-row");
row.dataset.providerId = profile.id;
const status = `${providerConnectionLabel(profile)} · ${providerCatalogLabel(profile)}`;
- const configure = textEl("button", "button-secondary", profile.credentialConfigured ? "编辑配置" : "配置");
+ const configure = document.createElement("button");
+ configure.className = "icon-button";
+ configure.title = `${t(profile.credentialConfigured ? "编辑配置" : "配置")} · ${providerDisplayLabel(profile)}`;
+ configure.setAttribute("aria-label", configure.title);
+ configure.append(createUiIcon(profile.credentialConfigured ? "pencil" : "plus"));
configure.type = "button";
configure.addEventListener("click", () => openAiProviderDialog(profile.id));
- const refresh = textEl("button", "button-secondary", "刷新模型");
+ const refresh = document.createElement("button");
+ refresh.className = "icon-button";
+ refresh.title = `${t("刷新模型")} · ${providerDisplayLabel(profile)}`;
+ refresh.setAttribute("aria-label", refresh.title);
+ refresh.append(createUiIcon("refresh-cw"));
+ refresh.hidden = !profile.credentialConfigured;
refresh.type = "button";
refresh.disabled = !profile.credentialConfigured;
refresh.addEventListener("click", () => refreshAiProviderModels(profile.id, refresh));
- row.append(rawTextEl("strong", "", providerDisplayLabel(profile)), textEl("span", "", status), configure, refresh);
+ const actions = el("div", "ai-provider-actions");
+ actions.append(configure, refresh);
+ row.append(rawTextEl("strong", "", providerDisplayLabel(profile)), rawTextEl("span", "", status), actions);
return row;
}));
- return [group];
+ for (const row of [...group.children]) {
+ const profile = aiProviderRegistry.providers[row.dataset.providerId];
+ if (!profile.credentialConfigured && !profile.discovery?.error) moreProviders.append(row);
+ }
+ return group.childElementCount ? [group] : [];
});
- elements.aiProviderList?.replaceChildren(...providerGroups);
+ elements.aiProviderList?.replaceChildren(...providerGroups, ...(moreProviders.childElementCount > 1 ? [moreProviders] : []));
elements.aiAssignmentList?.replaceChildren(...AI_ASSIGNMENT_TASKS.map((task) => {
const assignment = aiTaskAssignments[task.id] ?? {};
const profile = aiProviderRegistry.providers?.[assignment.providerId];
@@ -9000,12 +9086,14 @@ function renderAiRoutingSummary() {
: modelUnavailable
? `${providerDisplayLabel(profile)} · ${assignment.model} · ${t("已分配但模型不可用")}`
: `${providerDisplayLabel(profile)} · ${assignment.model}`;
- const change = textEl("button", "button-secondary", assignment.providerId ? "更换" : "配置");
+ const change = el("button", "button-secondary ai-model-choice");
+ change.title = `${t(task.label)} · ${routeState}`;
+ change.setAttribute("aria-label", `${t(task.label)} · ${t(assignment.providerId ? "更换" : "配置")} · ${routeState}`);
+ change.append(rawTextEl("span", "", routeState), createUiIcon("chevron-down"));
change.type = "button";
change.addEventListener("click", () => openAiTaskAssignmentDialog(task.id));
row.append(
rawTextEl("strong", "", t(task.label)),
- rawTextEl("span", "", routeState),
change
);
return row;
@@ -9686,8 +9774,8 @@ function renderComposerMethodSettings() {
const taskKey = elements.composerTaskKey.value;
const normalized = normalizeComposerSettings(composerSettings);
elements.composerMethodVersion.textContent = `v${normalized.methodVersion}`;
- elements.composerAgentInstruction.value = normalized.agentInstruction.text;
- elements.composerTaskMethod.value = normalized.taskMethods[taskKey].text;
+ renderRuleEditor(elements.composerAgentInstruction, normalized.agentInstruction.text);
+ renderRuleEditor(elements.composerTaskMethod, normalized.taskMethods[taskKey].text, `composer-task-method:${taskKey}`);
elements.creativeExperimentEnabled.checked = Boolean(creativeExperimentSettings.enabled);
elements.creativeExperimentAutoAnalyze.checked = Boolean(creativeExperimentSettings.autoAnalyze);
elements.creativeExperimentAutoAnalyze.disabled = !creativeExperimentSettings.enabled;
@@ -9697,6 +9785,7 @@ function renderComposerMethodSettings() {
: t("已开启;可在结果卡手动发起视觉对照。")
: t("默认关闭。普通结果关联不会调用任何模型。");
renderComposerMethodStatus();
+ renderRuleDraftStatus();
}
function renderComposerMethodStatus() {
@@ -9704,17 +9793,15 @@ function renderComposerMethodStatus() {
const taskKey = elements.composerTaskKey.value;
const normalized = normalizeComposerSettings(composerSettings);
elements.composerMethodDefaultText.textContent = DEFAULT_TASK_METHODS[taskKey];
- const selected = normalized.taskMethods[taskKey];
elements.composerMethodMigration.textContent = normalized.migrationCandidates[taskKey]?.length > 1
? t("这个任务仍有两个历史语言版本;当前会按输出语言继续使用,保存上方单一方法后完成合并。")
: "";
- elements.composerSettingsStatus.textContent = [
- normalized.agentInstruction.customized ? t("系统指令已自定义") : t("系统指令使用当前默认版本"),
- selected.customized ? t("当前任务方法已自定义") : t("当前任务方法使用当前默认版本")
- ].join(" · ");
+ elements.composerSettingsStatus.textContent = "";
}
async function saveComposerMethodSettings(event) {
+ const submittedEditorValue = elements.composerTaskMethod.value;
+ const submittedEditorKey = elements.composerTaskMethod.dataset.ruleDraftKey;
event.preventDefault();
const button = event.submitter ?? elements.composerSettingsForm.querySelector('button[type="submit"]');
button.disabled = true;
@@ -9722,6 +9809,7 @@ async function saveComposerMethodSettings(event) {
const taskKey = elements.composerTaskKey.value;
const response = await chrome.runtime.sendMessage({ type: "UPDATE_COMPOSER_SETTINGS", action: "save_task", taskKey, text: elements.composerTaskMethod.value });
if (!response?.ok) throw new Error(response?.message || "无法保存创作方法");
+ forgetSavedRuleDraft(submittedEditorKey, submittedEditorValue);
composerSettings = normalizeComposerSettings(response.composerSettings);
renderComposerMethodSettings();
showFeedback(response.message);
@@ -9733,27 +9821,36 @@ async function saveComposerMethodSettings(event) {
}
async function saveComposerAgentInstruction() {
+ const submittedEditorValue = elements.composerAgentInstruction.value;
+ const submittedEditorKey = elements.composerAgentInstruction.dataset.ruleDraftKey;
const response = await chrome.runtime.sendMessage({ type: "UPDATE_COMPOSER_SETTINGS", action: "save_agent", text: elements.composerAgentInstruction.value });
if (!response?.ok) return showFeedback(response?.message || "无法保存 Agent 系统指令", true);
+ forgetSavedRuleDraft(submittedEditorKey, submittedEditorValue);
composerSettings = normalizeComposerSettings(response.composerSettings);
renderComposerMethodSettings();
showFeedback(response.message);
}
async function restoreComposerAgentInstruction() {
+ const submittedEditorValue = elements.composerAgentInstruction.value;
+ const submittedEditorKey = elements.composerAgentInstruction.dataset.ruleDraftKey;
if (composerSettings.agentInstruction.customized && !await confirmAppAction({ title: "恢复默认系统指令?", description: "当前自定义内容会被替换。", confirmLabel: "恢复默认" })) return;
const response = await chrome.runtime.sendMessage({ type: "UPDATE_COMPOSER_SETTINGS", action: "reset_agent" });
if (!response?.ok) return showFeedback(response?.message || "无法恢复默认系统指令", true);
+ forgetSavedRuleDraft(submittedEditorKey, submittedEditorValue);
composerSettings = normalizeComposerSettings(response.composerSettings);
renderComposerMethodSettings();
showFeedback(response.message);
}
async function restoreComposerTaskDefault() {
+ const submittedEditorValue = elements.composerTaskMethod.value;
+ const submittedEditorKey = elements.composerTaskMethod.dataset.ruleDraftKey;
const taskKey = elements.composerTaskKey.value;
if (composerSettings.taskMethods[taskKey].customized && !await confirmAppAction({ title: "恢复默认任务方法?", description: "当前自定义内容会被替换。", confirmLabel: "恢复默认" })) return;
const response = await chrome.runtime.sendMessage({ type: "UPDATE_COMPOSER_SETTINGS", action: "reset_task", taskKey });
if (!response?.ok) return showFeedback(response?.message || "无法恢复默认方法", true);
+ forgetSavedRuleDraft(submittedEditorKey, submittedEditorValue);
composerSettings = normalizeComposerSettings(response.composerSettings);
renderComposerMethodSettings();
showFeedback(response.message);
@@ -9785,6 +9882,9 @@ async function saveAiRulePreferences(event) {
event.preventDefault();
const button = event.submitter ?? event.currentTarget.querySelector("button[type='submit']");
button.disabled = true;
+ const submitted = [...document.querySelectorAll("#settings-rules-panel textarea[data-rule-draft-key]")]
+ .filter((editor) => !editor.id.startsWith("composer-"))
+ .map((editor) => [editor.dataset.ruleDraftKey, editor.value]);
try {
const response = await chrome.runtime.sendMessage({
type: "UPDATE_AI_PROVIDER_CONFIGURATION",
@@ -9805,6 +9905,7 @@ async function saveAiRulePreferences(event) {
}
});
if (!response?.ok) throw new Error(response?.message || t("分析规则保存失败"));
+ for (const [key, value] of submitted) forgetSavedRuleDraft(key, value);
applyAiConfigurationResponse(response);
const message = t("分析规则已保存");
elements.aiSettingsStatus.textContent = message;
diff --git a/libtv-capture.js b/libtv-capture.js
index 1da653f..a1c9113 100644
--- a/libtv-capture.js
+++ b/libtv-capture.js
@@ -83,7 +83,7 @@ export function normalizeLibTvPublicPayload(value) {
return [{ id: `libtv:${item.id}`, adapter: 'libtv', pageType: kind === 'video' ? 'video' : 'artwork',
canonicalUrl: canonicalUrl.href, title: String(item.title || item.id), contentText: text,
excerpt: String(item.description || ''), completeness: value.limited ? 'partial' : 'complete',
- media: [{ id: `libtv:${item.id}:media`, kind, url, posterUrl: String(item.posterUrl || ''), placement: 'inline',
+ media: [{ id: `libtv:${item.id}:media`, kind, url, originalPrompt: text, posterUrl: String(item.posterUrl || ''), placement: 'inline',
sourceKind: 'site-original', sourceTitle: String(item.title || ''), sourceAuthor: String(item.author || ''),
originalWorkUrl: canonicalUrl.href, captureMethod: 'source' }],
extraction: { scope: 'document', method: 'structured' },
diff --git a/manifest.json b/manifest.json
index 74c0b4b..4e2838d 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "__MSG_extensionName__",
- "version": "1.20.5",
+ "version": "1.20.6",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq2m8W9ACXJTkJqPAd36sPrtzonmHhOYU34uS7c+D7DXX6ggWNMwB4xZapGFJ4ScBQJv71PeG9KfsEnhcXFZ9RoX/X3wY+57evL19hf6woNX1xxhKOe1rtx5QmzWCEYIr99TzW50k/N9U6tS9Ri+2DHKYA85ssXTC8B2yRQ5zUXhsAWZe/HDU18UFuvUKXYt3ZdIUi31c2vIlgFFBfsyKbIUMny9LlxL/smb4vJzU/+A3LwJDjjvOtS/lmQ2vHoQGjHJItO18bYI6h67fIEvmWk+HJKtO08Ca+5RLS8TYhI+K7l7S0RyDVNujyVWtvhAULot1H0BvteYL87fKu3SNywIDAQAB",
"homepage_url": "https://github.com/wchao6891/PromptDirector",
"default_locale": "zh_CN",
@@ -52,7 +52,7 @@
"default_path": "collector.html"
},
"content_security_policy": {
- "extension_pages": "script-src 'self'; object-src 'self'; img-src 'self' data: blob: https:; media-src 'self' blob: https://github.com https://objects.githubusercontent.com https://release-assets.githubusercontent.com; frame-src blob: https://player.vimeo.com https://www.youtube-nocookie.com https://player.bilibili.com https://www.douyin.com https://open.douyin.com https://platform.twitter.com;"
+ "extension_pages": "script-src 'self'; object-src 'self'; img-src 'self' data: blob: https:; media-src 'self' blob: https:; frame-src blob: https://player.vimeo.com https://www.youtube-nocookie.com https://player.bilibili.com https://www.douyin.com https://open.douyin.com https://www.tiktok.com;"
},
"commands": {
"save-selection": {
diff --git a/media-playback.js b/media-playback.js
index 80f27fe..595c759 100644
--- a/media-playback.js
+++ b/media-playback.js
@@ -4,6 +4,7 @@ export const YOUTUBE_PLAYBACK_HOSTS = Object.freeze([
]);
const YOUTUBE_PLAYBACK_RULE_ID = 61001;
+export const EMBED_PLAYER_RESPONSE_TIMEOUT_MS = 8000;
export function buildYouTubePlaybackRule({ extensionId, homepageUrl }) {
const clientIdentity = publicHttpUrl(homepageUrl);
@@ -58,6 +59,46 @@ export function youtubePlaybackError(codeValue) {
return { status: "failed", blockReason: "播放器未能加载此视频" };
}
+// TikTok's official player reports readiness, playback time and errors via postMessage.
+export function tiktokMediaController(frame, onStatus, eventTarget = globalThis.window) {
+ const origin = "https://www.tiktok.com";
+ let currentTimeMs = null;
+ const timeoutId = setTimeout(() => onStatus("播放器响应超时,可重试或打开来源", true), EMBED_PLAYER_RESPONSE_TIMEOUT_MS);
+ const onLoadError = () => {
+ clearTimeout(timeoutId);
+ onStatus("播放器未能加载此视频", true);
+ };
+ const onMessage = (event) => {
+ if (event.origin !== origin || event.source !== frame.contentWindow || event.data?.["x-tiktok-player"] !== true) return;
+ const { type, value } = event.data;
+ if (type === "onPlayerReady") {
+ clearTimeout(timeoutId);
+ onStatus("播放器已加载", false);
+ }
+ if (type === "onStateChange" && value === 1) onStatus("正在播放", false);
+ if (type === "onCurrentTime" && Number.isFinite(value?.currentTime)) currentTimeMs = Math.max(0, Math.round(value.currentTime * 1000));
+ if (type === "onPlayerError" || type === "onError") {
+ clearTimeout(timeoutId);
+ const reason = value?.errorCode === 1001 ? "视频不存在、已删除或设为私密" : "播放器未能加载此视频";
+ onStatus(reason, true);
+ }
+ };
+ eventTarget.addEventListener("message", onMessage);
+ frame.addEventListener("error", onLoadError);
+ return {
+ getCurrentTimeMs: async () => {
+ if (!Number.isFinite(currentTimeMs)) throw new Error("播放器尚未报告当前时间");
+ return currentTimeMs;
+ },
+ seekToMs: async (value) => frame.contentWindow?.postMessage({ type: "seekTo", value: Math.max(0, Number(value) || 0) / 1000, "x-tiktok-player": true }, origin),
+ destroy: () => {
+ clearTimeout(timeoutId);
+ frame.removeEventListener("error", onLoadError);
+ eventTarget.removeEventListener("message", onMessage);
+ }
+ };
+}
+
function publicHttpUrl(value) {
try {
const url = new URL(String(value ?? ""));
@@ -68,3 +109,14 @@ function publicHttpUrl(value) {
return "";
}
}
+
+export function localVideoController(video) {
+ return {
+ video,
+ getCurrentTimeMs: async () => Math.max(0, Math.round(video.currentTime * 1000)),
+ seekToMs: async (value) => {
+ video.currentTime = Math.max(0, Number(value) || 0) / 1000;
+ await video.play().catch(() => undefined);
+ }
+ };
+}
diff --git a/media-reference-resolver.js b/media-reference-resolver.js
index c6892d5..95213c5 100644
--- a/media-reference-resolver.js
+++ b/media-reference-resolver.js
@@ -4,6 +4,7 @@ const PROVIDERS = Object.freeze({
youtube: { label: "YouTube", origins: ["https://www.youtube.com/*", "https://youtu.be/*", "https://i.ytimg.com/*"] },
vimeo: { label: "Vimeo", origins: ["https://vimeo.com/*", "https://i.vimeocdn.com/*"] },
bilibili: { label: "Bilibili", origins: ["https://www.bilibili.com/*", "https://b23.tv/*", "https://bili2233.cn/*"] },
+ tiktok: { label: "TikTok", origins: ["https://www.tiktok.com/*", "https://vm.tiktok.com/*", "https://vt.tiktok.com/*"] },
douyin: { label: "抖音", origins: ["https://www.douyin.com/*", "https://v.douyin.com/*", "https://iesdouyin.com/*"] },
x: { label: "X", origins: ["https://x.com/*", "https://twitter.com/*", "https://mobile.twitter.com/*", "https://t.co/*", "https://publish.twitter.com/*"] },
generic: { label: "视频来源", origins: [] }
@@ -18,6 +19,7 @@ export function detectMediaReferenceProvider(value) {
if (host === "youtu.be" || host === "youtube.com" || host.endsWith(".youtube.com")) return "youtube";
if (host === "vimeo.com" || host.endsWith(".vimeo.com")) return "vimeo";
if (host === "b23.tv" || host === "bili2233.cn" || host === "bilibili.com" || host.endsWith(".bilibili.com")) return "bilibili";
+ if (host === "tiktok.com" || host.endsWith(".tiktok.com")) return "tiktok";
if (host === "v.douyin.com" || host === "douyin.com" || host.endsWith(".douyin.com") || host === "iesdouyin.com" || host.endsWith(".iesdouyin.com")) return "douyin";
if (["x.com", "twitter.com", "mobile.twitter.com", "t.co"].includes(host) || host.endsWith(".x.com") || host.endsWith(".twitter.com")) return "x";
return "generic";
@@ -61,7 +63,7 @@ export async function resolveMediaReference(value, context = {}) {
author: "",
posterUrl: "",
durationMs: 0,
- playbackMode: ["youtube", "vimeo", "bilibili", "douyin", "x"].includes(provider) ? "embed" : "source",
+ playbackMode: officialMediaEmbedUrl(canonicalUrl, provider) ? "embed" : "source",
playback: mediaPlaybackCapability(canonicalUrl, provider)
});
if (provider === "generic" || typeof context.fetch !== "function") {
@@ -113,14 +115,14 @@ export function officialMediaEmbedUrl(value, providerValue = "") {
params.set("poster", "1");
return `https://player.bilibili.com/player.html?${params}`;
}
+ if (provider === "tiktok") {
+ const id = url.pathname.match(/\/(?:video|photo|player\/v1)\/(\d+)(?:\/|$)/u)?.[1] || "";
+ return id ? `https://www.tiktok.com/player/v1/${id}` : "";
+ }
if (provider === "douyin") {
const id = url.pathname.match(/\/video\/(\d+)/u)?.[1] || "";
return id ? `https://open.douyin.com/player/video?vid=${encodeURIComponent(id)}&autoplay=0` : "";
}
- if (provider === "x") {
- const id = url.pathname.match(/\/status\/(\d+)/u)?.[1] || "";
- return id ? `https://platform.twitter.com/embed/Tweet.html?id=${encodeURIComponent(id)}&dnt=true` : "";
- }
return "";
}
diff --git a/media.js b/media.js
index 3e0296f..5bc4597 100644
--- a/media.js
+++ b/media.js
@@ -14,7 +14,7 @@ const MEDIA_KINDS = new Set(SUPPORTED_ASSET_KINDS);
const STORAGE_MODES = new Set(["managed", "reference"]);
const MEDIA_USAGES = new Set(["content", "poster"]);
const PLAYBACK_MODES = new Set(["local", "embed", "source"]);
-const OFFICIAL_EMBED_PROVIDERS = new Set(["youtube", "vimeo", "bilibili", "douyin", "x"]);
+const OFFICIAL_EMBED_PROVIDERS = new Set(["youtube", "vimeo", "bilibili", "douyin", "tiktok"]);
const PLAYBACK_CAPABILITIES = new Set(["native", "external", "unknown"]);
const LOCAL_ASSET_LINK_STATUSES = new Set(["relink-required", "linked", "missing", "needs-permission", "changed"]);
const GENERIC_ATTACHMENT_MIME_TYPES = new Set(["application/octet-stream", "application/x-unknown"]);
@@ -83,9 +83,10 @@ export function normalizeMediaAsset(value = {}) {
: {}),
...(/^[a-f0-9]{64}$/iu.test(clean(value.contentHash)) ? { contentHash: clean(value.contentHash).toLocaleLowerCase("en-US") } : {}),
...(["source", "css-background", "pixel-fallback"].includes(value.captureMethod) ? { captureMethod: value.captureMethod } : {}),
- playbackCapability: PLAYBACK_CAPABILITIES.has(value.playbackCapability)
- ? value.playbackCapability
- : storageMode === "reference" ? "external" : "unknown",
+ playbackCapability: storageMode === "reference" && reference.playbackMode !== "embed" && value.playbackCapability === "embedded"
+ ? "external"
+ : PLAYBACK_CAPABILITIES.has(value.playbackCapability) ? value.playbackCapability
+ : storageMode === "reference" ? "external" : "unknown",
...(assetPath ? { assetPath } : {}),
...(relativePath ? { relativePath } : {}),
...(clean(value.posterAssetId) ? { posterAssetId: clean(value.posterAssetId) } : {}),
@@ -325,10 +326,10 @@ export function setEntryMediaPrompt(entryValue, assetIdValue, textValue, source
assetId,
text,
textRevision: 1,
- source: source === "ai-suggestion" ? "ai-suggestion" : "manual",
+ source: normalizeMediaPromptSource(source),
updatedAt: new Date().toISOString()
});
- entry.mediaPrompts.sort((a, b) => Number(a.source === "ai-suggestion") - Number(b.source === "ai-suggestion"));
+ entry.mediaPrompts.sort(compareMediaPromptSources);
return entry;
}
@@ -406,12 +407,21 @@ function normalizeTimeNotes(values, assetIds) {
}).toSorted((left, right) => left.startMs - right.startMs || left.createdAt.localeCompare(right.createdAt));
}
+function normalizeMediaPromptSource(value) {
+ return ["webpage", "ai-suggestion"].includes(value) ? value : "manual";
+}
+
+function compareMediaPromptSources(a, b) {
+ const sources = ["manual", "webpage", "ai-suggestion"];
+ return sources.indexOf(a.source) - sources.indexOf(b.source);
+}
+
function normalizeMediaPrompts(values, assetIds) {
const seen = new Set();
return (Array.isArray(values) ? values : []).flatMap((value) => {
const assetId = clean(value?.assetId);
const text = cleanMultiline(value?.text);
- const source = value?.source === "ai-suggestion" ? "ai-suggestion" : "manual";
+ const source = normalizeMediaPromptSource(value?.source);
const identity = JSON.stringify([assetId, source]);
if (!assetIds.has(assetId) || !text || seen.has(identity)) return [];
seen.add(identity);
@@ -422,7 +432,7 @@ function normalizeMediaPrompts(values, assetIds) {
source,
updatedAt: validIso(value.updatedAt) || new Date().toISOString()
}];
- }).sort((a, b) => Number(a.source === "ai-suggestion") - Number(b.source === "ai-suggestion"));
+ }).sort(compareMediaPromptSources);
}
function normalizeVersionedAnalyses(values, kind) {
@@ -578,7 +588,9 @@ function normalizeReference(value, fallbackUrl) {
? value.metadataStatus
: "partial";
const author = clean(value?.author);
- return { url, provider, playbackMode, metadataStatus, ...(author ? { author } : {}) };
+ return { url, provider, playbackMode, metadataStatus, ...(author ? { author } : {}),
+ ...(safeHttpUrl(value?.playbackUrl) ? { playbackUrl: safeHttpUrl(value.playbackUrl) } : {}),
+ ...(safeHttpUrl(value?.streamUrl) ? { streamUrl: safeHttpUrl(value.streamUrl) } : {}) };
}
function normalizeLocalAssetReference(value, kind) {
diff --git a/package-lock.json b/package-lock.json
index faefd11..c759d9a 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,17 +1,18 @@
{
"name": "prompt-case-collector",
- "version": "1.20.5",
+ "version": "1.20.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "prompt-case-collector",
- "version": "1.20.5",
+ "version": "1.20.6",
"license": "Apache-2.0",
"dependencies": {
"@jonahschulte/rtf-toolkit": "0.5.0",
"@mozilla/readability": "0.6.0",
"@noble/hashes": "2.4.0",
+ "hls.js": "1.7.2",
"pdfjs-dist": "6.2.108",
"turndown": "7.2.4"
},
@@ -707,6 +708,12 @@
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
+ "node_modules/hls.js": {
+ "version": "1.7.2",
+ "resolved": "https://registry.npmjs.org/hls.js/-/hls.js-1.7.2.tgz",
+ "integrity": "sha512-CW/pPvSOFIRsosbwxrYaE9ERmpTo5fbTqL7wCvuCFlqW1Bmb1K5fXsY7yiH95rmlr4rVuA7UXHbM/cIXQ6AXwg==",
+ "license": "Apache-2.0"
+ },
"node_modules/htmlparser2": {
"version": "10.1.0",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz",
diff --git a/package.json b/package.json
index 574aa87..1539ad7 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "prompt-case-collector",
- "version": "1.20.5",
+ "version": "1.20.6",
"private": false,
"license": "Apache-2.0",
"repository": "https://github.com/wchao6891/PromptDirector",
@@ -22,23 +22,26 @@
"check:pdfjs": "node tools/pdfjs-runtime.mjs --check",
"check:store": "node tools/build-store-assets.mjs --check && node tools/check-store-readiness.mjs",
"check:compat": "node tools/check-data-compatibility.mjs",
- "package": "npm run build:brand && npm run build:hash && npm run build:documents && npm run build:icons && node tools/package-extension.mjs",
- "package:release": "npm run build:brand && npm run build:hash && npm run build:documents && npm run build:icons && node tools/package-extension.mjs --release",
+ "package": "npm run build:brand && npm run build:capture-runtime && npm run build:hash && npm run build:documents && npm run build:icons && node tools/package-extension.mjs",
+ "package:release": "npm run build:brand && npm run build:capture-runtime && npm run build:hash && npm run build:documents && npm run build:icons && node tools/package-extension.mjs --release",
"test:e2e": "python3 test/run_e2e.py",
"test:local-extension": "npm run package && node tools/local-extension-lab.mjs",
"test:live:zhipu": "node tools/zhipu-live-smoke.mjs",
"test:upgrade": "node tools/run-release-upgrade-e2e.mjs",
"test:smart-picker": "python3 test/smart_visual_picker_e2e.py",
- "verify:source": "npm run check:public && npm run check && npm run check:hash && npm run check:brand && npm run check:documents && npm run check:pdfjs && npm run check:store && npm run check:compat && npm test",
+ "verify:source": "npm run check:public && npm run check && npm run check:capture-runtime && npm run check:hash && npm run check:brand && npm run check:documents && npm run check:pdfjs && npm run check:store && npm run check:compat && npm test",
"verify:release": "npm run verify:source && npm run test:local-extension && npm run package:release && npm run test:upgrade",
"verify": "npm run verify:release",
"build:hash": "node tools/hash-runtime.mjs",
- "check:hash": "node tools/hash-runtime.mjs --check"
+ "check:hash": "node tools/hash-runtime.mjs --check",
+ "build:capture-runtime": "node tools/capture-runtime.mjs",
+ "check:capture-runtime": "node tools/capture-runtime.mjs --check"
},
"dependencies": {
"@jonahschulte/rtf-toolkit": "0.5.0",
"@mozilla/readability": "0.6.0",
"@noble/hashes": "2.4.0",
+ "hls.js": "1.7.2",
"pdfjs-dist": "6.2.108",
"turndown": "7.2.4"
},
diff --git a/page-capture-adapter-registry.js b/page-capture-adapter-registry.js
index cd5b1d5..f74ae5f 100644
--- a/page-capture-adapter-registry.js
+++ b/page-capture-adapter-registry.js
@@ -24,6 +24,11 @@ export const PAGE_CAPTURE_ADAPTERS = Object.freeze([
}, ["higgsfield.ai", "higgs.ai", "d2ol7oe51mr4n9.cloudfront.net", "du4zrvwy3vtek.cloudfront.net", "d8j0ntlcm91z4.cloudfront.net"]),
adapter("krea", "Krea", ["krea.ai"], "verified-declarative", ["a[href^='/feed/']", "[data-testid*=generation]", "[class*=gallery] > *"], {}, ["krea.ai"]),
adapter("tapnow", "TapNow", ["tapnow.ai"], "generic", ["[data-testid*=work]", "[class*=gallery] > *"]),
+ adapter("lovart", "Lovart", ["lovart.ai"], "generic", GENERIC_CARD_SELECTORS),
+ adapter("midjourney", "Midjourney", ["midjourney.com"], "generic", GENERIC_CARD_SELECTORS),
+ adapter("civitai", "Civitai", ["civitai.com"], "generic", GENERIC_CARD_SELECTORS),
+ adapter("runway", "Runway", ["runwayml.com"], "generic", GENERIC_CARD_SELECTORS),
+ adapter("kling", "可灵", ["klingai.com", "klingai.kuaishou.com"], "generic", GENERIC_CARD_SELECTORS),
adapter("pinterest", "Pinterest", ["pinterest.com", "pin.it"], "verified-deep", ["[data-test-id=pin]", "[data-grid-item]"], {}, ["i.pinimg.com"]),
adapter("behance", "Behance", ["behance.net"], "verified-declarative", ["[data-project-id]", "main article"], {}, ["mir-s3-cdn-cf.behance.net"]),
@@ -47,6 +52,9 @@ export const PAGE_CAPTURE_ADAPTERS = Object.freeze([
}),
adapter("imgur", "Imgur", ["imgur.com"], "generic", ["main article", "[class*=Gallery-Content]"]),
adapter("weibo", "微博", ["weibo.com", "weibo.cn"], "generic", ["article", "[class*=Feed_wrap]"]),
+ adapter("xiaohongshu", "小红书", ["xiaohongshu.com", "xhslink.com"], "generic", GENERIC_CARD_SELECTORS),
+ adapter("tiktok", "TikTok", ["tiktok.com"], "generic", GENERIC_CARD_SELECTORS),
+ adapter("douyin", "抖音", ["douyin.com", "iesdouyin.com"], "generic", GENERIC_CARD_SELECTORS),
adapter("jike", "即刻", ["okjike.com"], "generic", ["main article", "[data-testid*=post]"]),
adapter("qzone", "QQ 空间相册", ["qzone.qq.com", "photo.qq.com"], "generic", ["main article", "[class*=photo]"]),
adapter("douban", "豆瓣相册", ["douban.com"], "generic", ["main article", ".photo_wrap", ".photolst li"]),
@@ -130,8 +138,8 @@ function platformAdapter(id, label, signalPatterns) {
}
function defaultPageType(id) {
- if (["youtube", "bilibili"].includes(id)) return "video";
- if (["x", "reddit", "instagram", "weibo", "jike"].includes(id)) return "post";
+ if (["youtube", "bilibili", "tiktok", "douyin"].includes(id)) return "video";
+ if (["x", "reddit", "instagram", "weibo", "jike", "xiaohongshu"].includes(id)) return "post";
if (["wechat", "medium", "architectural-digest", "house-beautiful", "officesnapshots", "archdaily", "archdaily-cn", "dezeen", "interior-design"].includes(id)) return "article";
return "artwork";
}
diff --git a/page-capture-frames.js b/page-capture-frames.js
new file mode 100644
index 0000000..b503691
--- /dev/null
+++ b/page-capture-frames.js
@@ -0,0 +1,93 @@
+// Observed public ArtStation project video player; keep the rule scoped to that player.
+export const PAGE_CAPTURE_VIDEO_FRAME_RULES = Object.freeze([
+ Object.freeze({ host: "www.artstation.com", pathPrefix: "/api/v2/animation/video_clips/", pathSuffix: "/embed.html" })
+]);
+
+function readableFrameUrl(value) {
+ try {
+ const url = new URL(value);
+ return url.protocol === "https:" && PAGE_CAPTURE_VIDEO_FRAME_RULES.some(rule =>
+ url.hostname === rule.host && url.pathname.startsWith(rule.pathPrefix) && url.pathname.endsWith(rule.pathSuffix));
+ } catch {
+ return false;
+ }
+}
+
+// Injected into accessible frames. Read only a player explicitly found in the capture candidates.
+export function readPageCaptureVideoFrame(expectedUrls) {
+ const frameUrl = globalThis.location.href;
+ if (!expectedUrls.includes(frameUrl)) return null;
+ const players = [...document.querySelectorAll("video")];
+ if (players.length !== 1) return null;
+ const player = players[0];
+ const httpUrl = value => {
+ try {
+ const url = new URL(value);
+ return ["http:", "https:"].includes(url.protocol) && !url.username && !url.password ? url.href : "";
+ } catch { return ""; }
+ };
+ const url = httpUrl(player.currentSrc || player.src);
+ if (!url) return null;
+ return {
+ frameUrl, url, posterUrl: httpUrl(player.poster),
+ width: player.videoWidth || 0, height: player.videoHeight || 0
+ };
+}
+
+export async function resolvePageCaptureVideoFrames(snapshot, tabId, scripting) {
+ const frameUrls = [...new Set((snapshot.candidates || []).flatMap(candidate =>
+ (candidate.media || []).filter(media => media.kind === "video" && readableFrameUrl(media.url)).map(media => media.url)))];
+ if (!frameUrls.length) return snapshot;
+ let results = [];
+ try {
+ results = await scripting.executeScript({
+ target: { tabId, allFrames: true },
+ func: readPageCaptureVideoFrame,
+ args: [frameUrls]
+ });
+ } catch {
+ // An inaccessible or navigated player remains in the preview as incomplete content.
+ }
+ const byUrl = new Map();
+ for (const { result } of results) {
+ if (!result || !frameUrls.includes(result.frameUrl)) continue;
+ try {
+ const url = new URL(result.url);
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) continue;
+ byUrl.set(result.frameUrl, { ...result, url: url.href });
+ } catch { /* A player without a usable URL remains pending. */ }
+ }
+ return {
+ ...snapshot,
+ candidates: (snapshot.candidates || []).map(candidate => {
+ let pending = 0;
+ const replacements = new Map();
+ const media = (candidate.media || []).map(item => {
+ if (item.kind !== "video" || !frameUrls.includes(item.url)) return item;
+ const source = byUrl.get(item.url);
+ if (!source) { pending += 1; return item; }
+ replacements.set(item.id, source);
+ return {
+ ...item, url: source.url, sourceKind: "video-element", variants: [],
+ posterUrl: source.posterUrl || item.posterUrl || "",
+ width: source.width || item.width || 0, height: source.height || item.height || 0
+ };
+ });
+ return {
+ ...candidate, media,
+ ...(candidate.articleDocument ? { articleDocument: {
+ ...candidate.articleDocument,
+ blocks: candidate.articleDocument.blocks.map(block => {
+ const source = replacements.get(block.assetId);
+ return source ? { ...block, sourceUrl: source.url, posterUrl: source.posterUrl || block.posterUrl || "" } : block;
+ })
+ } } : {}),
+ ...(pending ? {
+ completeness: "partial",
+ sourceFacts: { ...candidate.sourceFacts, status: "partial" },
+ extraction: { ...candidate.extraction, pendingMediaCount: (candidate.extraction?.pendingMediaCount || 0) + pending }
+ } : {})
+ };
+ })
+ };
+}
diff --git a/page-capture-repair.js b/page-capture-repair.js
index 7effd73..5905a3b 100644
--- a/page-capture-repair.js
+++ b/page-capture-repair.js
@@ -1,5 +1,16 @@
import { remapArticleDocumentAssets } from "./article-document.js";
+export function capturedMediaPrompts(candidate, assetIds, existing = []) {
+ const prompts = existing.map(item => ({ ...item }));
+ for (const media of candidate.media || []) {
+ const assetId = assetIds.get(media.id);
+ const text = String(media.originalPrompt || "").trim();
+ if (!assetId || !text || prompts.some(item => item.assetId === assetId && item.source !== "ai-suggestion")) continue;
+ prompts.push({ assetId, text, source: "webpage", textRevision: 1 });
+ }
+ return prompts;
+}
+
function sourceUrls(media) {
return new Set([media.url, media.sourceUrl, media.reference?.url, ...(media.variants || []).map(item => item.url)].filter(Boolean));
}
@@ -35,7 +46,8 @@ export async function planPageCaptureRepair(entry, candidate, hasBlob) {
}
} else pending.push(media);
}
- return { pending, matched, assetIds, obsoleteReferences };
+ const promptsChanged = capturedMediaPrompts(candidate, assetIds, entry.mediaPrompts).length > (entry.mediaPrompts || []).length;
+ return { pending, matched, assetIds, obsoleteReferences, promptsChanged };
}
export function mergePageCaptureRepair(entry, candidate, plan, capturedAssets, assetIds) {
@@ -68,6 +80,7 @@ export function mergePageCaptureRepair(entry, candidate, plan, capturedAssets, a
return {
...entry,
mediaAssets: assets,
+ mediaPrompts: capturedMediaPrompts(candidate, assetIds, entry.mediaPrompts),
primaryMediaId: primary?.storageMode === "managed" ? primary.id : preferred?.id || primary?.id || entry.primaryMediaId,
articleDocument,
sourceFacts: { ...entry.sourceFacts, ...candidate.sourceFacts }
diff --git a/page-capture-site-adapters.js b/page-capture-site-adapters.js
index 8be855e..a95b6d4 100644
--- a/page-capture-site-adapters.js
+++ b/page-capture-site-adapters.js
@@ -151,6 +151,18 @@ export function collectPageCaptureSitePayload(options = {}) {
const maxNodes = Number.isSafeInteger(Number(options.maxCandidates)) && Number(options.maxCandidates) > 0 ? Number(options.maxCandidates) : 0;
const maxTextCharacters = Number.isSafeInteger(Number(options.maxTextCharacters)) && Number(options.maxTextCharacters) > 0 ? Number(options.maxTextCharacters) : 0;
const host = clean(globalThis.location?.hostname).toLocaleLowerCase("en-US");
+ if ((host === "artstation.com" || host.endsWith(".artstation.com"))
+ && /^\/projects\/[^/]+\/?$/u.test(globalThis.location?.pathname || "")) {
+ const description = globalThis.document?.querySelector?.(".project-description");
+ if (description && globalThis.document?.querySelector?.(".project-assets-image,.asset-responsive.video-clip")) {
+ return {
+ adapter: "artstation", canonicalUrl: globalThis.location.href,
+ title: clean(globalThis.document.querySelector("h1")?.textContent),
+ description: String(description.innerText || description.textContent || "").slice(0, maxTextCharacters),
+ author: clean(globalThis.document.querySelector("header a")?.textContent)
+ };
+ }
+ }
if ((host === "liblib.art" || host.endsWith(".liblib.art") || host === "liblib.ai" || host.endsWith(".liblib.ai"))
&& clean(globalThis.location?.pathname).startsWith("/imageinfo/")) {
try {
@@ -229,11 +241,28 @@ export function collectPageCaptureSitePayload(options = {}) {
const uuidPattern = /[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/iu;
const detailId = path.match(uuidPattern)?.[0]?.toLocaleLowerCase("en-US") || "";
if (detailId) {
+ const preview = globalThis.document?.querySelector?.("article figure img");
+ const styleReferences = [...(globalThis.document?.querySelectorAll?.('article button[aria-label^="Copy style reference image"]') || [])]
+ .slice(0, Math.max(0, maxMedia - 1)).flatMap(button => {
+ const style = globalThis.getComputedStyle?.(button)?.backgroundImage || button.style?.backgroundImage || "";
+ const observed = String(style).match(/url\(["']?([^"')]+)["']?\)/u)?.[1];
+ if (!observed) return [];
+ try {
+ const previewUrl = new URL(observed, globalThis.location.href);
+ const original = previewUrl.hostname === host && previewUrl.pathname === "/api/img"
+ ? previewUrl.searchParams.get("i") : previewUrl.href;
+ const url = new URL(original);
+ if (url.protocol !== "https:" || url.hostname !== "app-uploads.krea.ai") return [];
+ return [{ url: url.href, previewUrl: previewUrl.href, label: clean(button.getAttribute("aria-label")).replace(/^Copy /u, "") }];
+ } catch { return []; }
+ });
return {
adapter: "krea",
pageKind: "detail",
canonicalUrl: clean(globalThis.location?.href),
prompt: String(globalThis.document?.querySelector?.("article h1")?.textContent || "").slice(0, maxTextCharacters).trim(),
+ imagePreviewUrl: clean(preview?.currentSrc || preview?.src),
+ styleReferences,
jsonLd,
status: jsonLd.length ? "complete" : "partial"
};
@@ -617,6 +646,24 @@ export function collectPageCaptureSitePayload(options = {}) {
}
export function normalizePageCaptureSitePayload(value, canonicalUrlValue = "") {
+ if (value?.adapter === "artstation") {
+ const canonicalUrl = safeHttpUrl(canonicalUrlValue || value.canonicalUrl);
+ if (!canonicalUrl) return null;
+ const url = new URL(canonicalUrl);
+ if (!(url.hostname === "artstation.com" || url.hostname.endsWith(".artstation.com"))
+ || !/^\/projects\/[^/]+\/?$/u.test(url.pathname)) return null;
+ const contentText = cleanMultiline(value.description);
+ const title = clean(value.title);
+ if (!title || !contentText) return null;
+ return {
+ adapter: "artstation", pageKind: "detail", pageType: "artwork", canonicalUrl,
+ title, contentText, media: [],
+ sourceFacts: {
+ provider: "artstation", pageType: "artwork", itemId: url.pathname.split("/")[2],
+ author: clean(value.author), description: contentText, extractionMethod: "structured"
+ }
+ };
+ }
if (value?.adapter === "liblibai") return normalizeStructuredFeedMedia(normalizeLiblibPayload(value, canonicalUrlValue));
if (value?.adapter === "krea") return normalizeStructuredFeedMedia(normalizeKreaPayload(value, canonicalUrlValue));
if (value?.adapter === "higgsfield") return normalizeStructuredFeedMedia(normalizeHiggsfieldPayload(value, canonicalUrlValue));
@@ -726,6 +773,8 @@ function normalizeKreaPayload(value, canonicalUrlValue) {
title: jsonLd.name,
prompt: value?.prompt,
imageUrl: jsonLd.contentUrl || jsonLd.url || jsonLd.thumbnailUrl,
+ imagePreviewUrl: value?.imagePreviewUrl,
+ styleReferences: value?.styleReferences,
publishedAt: jsonLd.datePublished,
width: jsonLd.width,
height: jsonLd.height
@@ -743,15 +792,29 @@ function normalizeKreaItem(value) {
const width = positiveInteger(value?.width);
const height = positiveInteger(value?.height);
const prompt = cleanMultiline(value?.prompt);
+ const previewUrl = safeTrustedMediaUrl("krea", value?.imagePreviewUrl);
const media = url ? [{
- id: `krea:${itemId}:1`, kind: "image", url, width, height,
+ id: `krea:${itemId}:1`, kind: "image", url, width, height, originalPrompt: prompt,
sourceKind: "site-original", captureMethod: "source",
- variants: [{ url, sourceKind: "site-original", width, height }]
+ variants: [{ url, sourceKind: "site-original", width, height },
+ ...(previewUrl && previewUrl !== url ? [{ url: previewUrl, sourceKind: "current" }] : [])]
}] : [];
+ for (const [index, reference] of (Array.isArray(value?.styleReferences) ? value.styleReferences : []).entries()) {
+ const referenceUrl = safeTrustedMediaUrl("krea", reference.url);
+ if (!referenceUrl || media.some(item => item.url === referenceUrl)) continue;
+ const referencePreviewUrl = safeTrustedMediaUrl("krea", reference.previewUrl);
+ media.push({
+ id: `krea:${itemId}:reference:${index + 1}`, kind: "image", url: referenceUrl,
+ alt: clean(reference.label), sourceKind: "site-original", captureMethod: "source",
+ variants: [{ url: referenceUrl, sourceKind: "site-original" },
+ ...(referencePreviewUrl && referencePreviewUrl !== referenceUrl ? [{ url: referencePreviewUrl, sourceKind: "current" }] : [])]
+ });
+ }
const complete = Boolean(prompt && media.length);
return {
id: `krea:${itemId}`,
adapter: "krea",
+ pageKind: "detail",
pageType: "artwork",
canonicalUrl,
title: clean(value?.title) || (prompt ? prompt.slice(0, 160) : `Krea ${itemId.slice(0, 8)}`),
@@ -760,6 +823,7 @@ function normalizeKreaItem(value) {
completeness: complete ? "complete" : "partial",
extraction: { scope: "document", method: "structured", textBlockCount: prompt ? 1 : 0 },
sourceFacts: {
+ originalPromptAvailable: Boolean(prompt),
provider: "krea", pageType: "artwork", itemId,
publishedAt: validIso(value?.publishedAt),
dimensions: width && height ? `${width}×${height}` : "",
@@ -1022,6 +1086,7 @@ function normalizeLiblibPayload(value, canonicalUrlValue) {
return [{
id: `liblibai:${itemId}:${clean(image?.uuid || image?.id) || index + 1}`,
kind: "image",
+ originalPrompt: cleanMultiline(image?.generateInfo?.prompt),
url,
width,
height,
@@ -1030,7 +1095,7 @@ function normalizeLiblibPayload(value, canonicalUrlValue) {
variants
}];
});
- const promptText = cleanMultiline(images.map((image) => image?.generateInfo?.prompt).find(clean));
+ const promptText = [...new Set(media.map(image => image.originalPrompt).filter(Boolean))].join("\n\n");
const model = [...new Set(images.flatMap((image) => Array.isArray(image?.models) ? image.models : []).map((entry) => (
[clean(entry?.modelName), clean(entry?.versionName)].filter(Boolean).join(" ")
)).filter(Boolean))].join(" · ");
@@ -1051,7 +1116,7 @@ function normalizeLiblibPayload(value, canonicalUrlValue) {
completeness: complete ? "complete" : "partial",
extraction: { scope: "document", method: "structured", textBlockCount: promptText ? 1 : 0 },
sourceFacts: {
- provider: "liblibai", pageType: "artwork", itemId, author, handle,
+ provider: "liblibai", pageType: "artwork", itemId, author, handle, originalPromptAvailable: Boolean(promptText),
publishedAt: validIso(data.createTime), model,
dimensions: media[0]?.width && media[0]?.height ? `${media[0].width}×${media[0].height}` : "",
engagement, extractionMethod: "structured",
@@ -1137,6 +1202,7 @@ function normalizeJimengItem(item, modelNamesValue = {}) {
return [{
id: `jimeng:${workId}:${index + 1}`,
kind: "image",
+ originalPrompt: prompt,
url,
width,
height,
@@ -1162,6 +1228,7 @@ function normalizeJimengItem(item, modelNamesValue = {}) {
completeness: complete ? "complete" : "partial",
extraction: { scope: "document", method: "structured", textBlockCount: prompt ? 1 : 0 },
sourceFacts: {
+ originalPromptAvailable: Boolean(prompt),
provider: "jimeng",
pageType: "artwork",
itemId: workId,
diff --git a/page-capture.js b/page-capture.js
index 6fb1b66..82144c7 100644
--- a/page-capture.js
+++ b/page-capture.js
@@ -14,7 +14,7 @@ export function detectPageCaptureAdapter(value, adapters = PAGE_CAPTURE_ADAPTERS
export function pageCaptureDefaultMediaIds(candidateValue = {}) {
return (normalizePageCaptureCandidate(candidateValue)?.media || [])
- .filter((item) => !item.quotedPostUrl && (item.placement === "inline" || item.isCover))
+ .filter((item) => !item.isQuoted && !item.quotedPostUrl && (item.placement === "inline" || item.isCover))
.map((item) => item.id);
}
@@ -26,6 +26,7 @@ export function resolvePageCapturePageType({
metadataType = ""
} = {}) {
if (adapterPageType === "post") return "post";
+ if (structuredTypes.some((type) => ["Article", "NewsArticle", "BlogPosting"].includes(type))) return "article";
if (structuredTypes.includes("VideoObject") || ["youtube", "bilibili"].includes(adapterPageType)) return "video";
if (structuredTypes.some((type) => ["Article", "NewsArticle", "BlogPosting"].includes(type)) || articleTextLength > 500) return "article";
if (cardCount > 1) return metadataType === "website" ? "gallery" : "feed";
@@ -271,6 +272,13 @@ export function applyPageCaptureSelections(batchValue = {}) {
selectedTextBlockIds,
selectedMediaIds
});
+ const sourceFacts = { ...candidate.sourceFacts };
+ if (!selection.includeText) sourceFacts.originalPromptAvailable = false;
+ else if (!selectedAllText && sourceFacts.originalPromptAvailable === true) {
+ const knownPrompts = candidate.media.map(item => item.originalPrompt).filter(Boolean);
+ if (knownPrompts.length) sourceFacts.originalPromptAvailable = knownPrompts.some(prompt => selectedText.includes(prompt));
+ else delete sourceFacts.originalPromptAvailable;
+ }
return [{
...candidate,
contentHtml: selection.includeText
@@ -280,7 +288,12 @@ export function applyPageCaptureSelections(batchValue = {}) {
excerpt: selection.includeText
? selectedAllText ? candidate.excerpt : selectedTextBlocks[0]?.text || ""
: "",
- media: candidate.media.filter((item) => selectedMediaIds.has(item.id)),
+ media: candidate.media.filter((item) => selectedMediaIds.has(item.id)).map(item => {
+ const { originalPrompt, ...media } = item;
+ return originalPrompt && selection.includeText && (selectedAllText || selectedText.includes(originalPrompt))
+ ? { ...media, originalPrompt } : media;
+ }),
+ sourceFacts,
articleDocument
}];
});
@@ -475,7 +488,7 @@ function prepareCreativeSections(blocks, context) {
};
for (const block of sourceBlocks) {
- if (block.text === context.title || block.text === context.sourceFacts.author) continue;
+ if (block.relevance !== "explicit-creative" && (block.text === context.title || block.text === context.sourceFacts.author)) continue;
if (block.kind === "noise") {
flush();
omitted.push({ ...block, reason: "page-chrome" });
@@ -546,7 +559,7 @@ export function pageCapturePermissionOrigins(candidates = []) {
for (const candidate of candidates) {
for (const media of normalizePageCaptureCandidate(candidate)?.media || []) {
if (media.localAssetId || media.kind === "document" && !isSupportedDocumentMimeType(media.mimeType)) continue;
- for (const value of [media.posterUrl, ...pageCaptureMediaFetchCandidates(media)]) {
+ for (const value of [media.posterUrl, media.streamUrl, ...pageCaptureMediaFetchCandidates(media)]) {
try {
const url = new URL(value);
if (["http:", "https:"].includes(url.protocol)) origins.add(`${url.origin}/*`);
@@ -953,6 +966,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
function detectPageType({ adapter, metadata, structured, article, cardCount }) {
const types = structured.flatMap((item) => Array.isArray(item["@type"]) ? item["@type"] : [item["@type"]]).filter(Boolean);
if (adapter.pageType === "post") return "post";
+ if (types.some((type) => ["Article", "NewsArticle", "BlogPosting"].includes(type))) return "article";
if (types.includes("VideoObject") || ["youtube", "bilibili"].includes(adapter.id)) return "video";
if (types.some((type) => ["Article", "NewsArticle", "BlogPosting"].includes(type)) || (article?.length || 0) > 500) return "article";
if (cardCount > 1) return metadata.type === "website" ? "gallery" : "feed";
@@ -1083,7 +1097,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
}]
: null;
const textBlocks = post?.textBlocks || pageSelection?.textBlocks || structuredTextBlocks || collectTextBlocks(root, contentHtml, text);
- const siteMedia = Array.isArray(siteData?.media) ? siteData.media : [];
+ const siteMedia = [...(Array.isArray(siteData?.media) ? siteData.media : []), ...collectStructuredMedia(structured)];
const domMedia = post?.media || (pageSelection || root.isConnected === false ? [] : collectMedia(root, context.maxMedia));
const pairedDomIds = new Set();
const pairedSiteMedia = siteMedia.map((item) => {
@@ -1102,16 +1116,15 @@ export async function collectPageCaptureSnapshot(options = {}) {
});
let media = mergeCollectedMedia([
...pairedSiteMedia,
- ...collectStructuredMedia(structured),
...domMedia.filter((item) => !pairedDomIds.has(item.id))
], context.maxMedia);
const article = collectArticleDocument(root, contentHtml, textBlocks, media, context.maxMedia);
if (capturePost) {
- for (const item of media.filter(item => item.postPhotoUrl)) {
- item.quotedPostUrl = sameUrl(item.postPhotoUrl, canonicalUrl) ? "" : item.postPhotoUrl;
- item.originalWorkUrl = item.postPhotoUrl;
+ for (const item of media.filter(item => item.postMediaUrl)) {
+ item.quotedPostUrl = sameUrl(item.postMediaUrl, canonicalUrl) ? "" : item.postMediaUrl;
+ item.originalWorkUrl = item.postMediaUrl;
if (!article.blocks.some(block => block.assetId === item.id)) article.blocks.push({
- id: `article:photo:${item.id}`, kind: "image", assetId: item.id, sourceUrl: item.url,
+ id: `article:media:${item.id}`, kind: item.kind, assetId: item.id, sourceUrl: item.url,
sourceOrder: article.blocks.length
});
}
@@ -1155,6 +1168,8 @@ export async function collectPageCaptureSnapshot(options = {}) {
excerpt: cleanText(context.article?.excerpt || context.metadata.description),
media,
sourceFacts: {
+ ...(typeof siteData?.sourceFacts?.originalPromptAvailable === "boolean" ? { originalPromptAvailable: siteData.sourceFacts.originalPromptAvailable } : {}),
+ ...(siteData?.sourceFacts?.description ? { description: cleanBlockText(siteData.sourceFacts.description) } : {}),
provider: cleanText(siteData?.sourceFacts?.provider) || (context.adapter.id === "generic" ? location.hostname : context.adapter.id),
pageType,
itemId,
@@ -1625,6 +1640,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
function isVideoUrl(value) {
try {
const url = new URL(value);
+ if (url.hostname === "www.tiktok.com" && /^\/player\/v1\/\d+\/?$/u.test(url.pathname)) return true;
if (["x.com", "twitter.com"].some(host => url.hostname === host || url.hostname.endsWith(`.${host}`))) return /^\/[^/]+\/status\/\d+\/video\/\d+\/?$/u.test(url.pathname);
return /\.(?:mp4|webm|mov)(?:$|[?#])/iu.test(url.pathname) || ["youtube.com", "youtu.be", "vimeo.com", "bilibili.com", "douyin.com"].some((host) => url.hostname === host || url.hostname.endsWith(`.${host}`));
} catch {
@@ -1653,6 +1669,20 @@ export async function collectPageCaptureSnapshot(options = {}) {
function collectStructuredMedia(value) {
const images = [];
+ const types = Array.isArray(value?.["@type"]) ? value["@type"] : [value?.["@type"]];
+ const videos = (types.includes("VideoObject") ? [value]
+ : Array.isArray(value?.video) ? value.video : value?.video ? [value.video] : []).flatMap(item => {
+ const source = safeHttpUrl(item?.contentUrl);
+ const embed = safeHttpUrl(item?.embedUrl);
+ const url = source || (embed && isVideoUrl(embed) ? embed : "");
+ if (!url) return [];
+ const posterUrl = safeHttpUrl(Array.isArray(item.thumbnailUrl) ? item.thumbnailUrl[0] : item.thumbnailUrl);
+ return [{ id: `structured-video:${hashText(url)}`, kind: "video", url, posterUrl,
+ width: Number(item.width?.value || item.width) || 0,
+ height: Number(item.height?.value || item.height) || 0,
+ sourceKind: source ? "site-original" : "structured", captureMethod: "source",
+ ...(/\.m3u8(?:\?|$)/iu.test(source) ? { streamUrl: source } : {}) }];
+ });
const addImage = (candidate) => {
const item = typeof candidate === "string" ? { url: candidate } : candidate || {};
const url = safeHttpUrl(item.contentUrl || item.url || item["@id"]);
@@ -1670,9 +1700,11 @@ export async function collectPageCaptureSnapshot(options = {}) {
variants: [{ url, width, height, sourceKind: "structured" }]
});
};
+ if (types.includes("ImageObject") && value.contentUrl) addImage(value);
for (const image of Array.isArray(value?.image) ? value.image : value?.image ? [value.image] : []) addImage(image);
- if (!images.length && value?.thumbnailUrl) addImage(value.thumbnailUrl);
- return images;
+ if (!images.length && !videos.length && value?.thumbnailUrl) addImage(Array.isArray(value.thumbnailUrl) ? value.thumbnailUrl[0] : value.thumbnailUrl);
+ const posters = new Set(videos.map(item => item.posterUrl).filter(Boolean));
+ return [...images.filter(item => !posters.has(item.url)), ...videos];
}
function readBlockText(node) {
@@ -1784,7 +1816,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
kind,
url,
posterUrl,
- postPhotoUrl: xPostPhotoUrl(element),
+ postMediaUrl: xPostMediaUrl(element), isQuoted: Boolean(xQuoteContainer(element)),
alt: cleanText(element.alt),
width: imageSource?.declaredWidth || (responsiveCandidate ? 0 : Number(element.naturalWidth || element.videoWidth || element.width) || 0),
height: responsiveCandidate ? 0 : Number(element.naturalHeight || element.videoHeight || element.height) || 0,
@@ -1805,7 +1837,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
const url = safeHttpUrl(match?.[1]);
const rect = element.getBoundingClientRect();
if (!url || sameUrl(url, location.href) || rect.width < 48 || rect.height < 48) continue;
- media.push({ id: `background:${hashText(url)}`, kind: "image", url, postPhotoUrl: xPostPhotoUrl(element), posterUrl: "", alt: "", width: element.clientWidth, height: element.clientHeight, captureMethod: "css-background", sourceKind: "css-background", variants: [{ url, sourceKind: "css-background", width: element.clientWidth, height: element.clientHeight }] });
+ media.push({ id: `background:${hashText(url)}`, kind: "image", url, postMediaUrl: xPostMediaUrl(element), isQuoted: Boolean(xQuoteContainer(element)), posterUrl: "", alt: "", width: element.clientWidth, height: element.clientHeight, captureMethod: "css-background", sourceKind: "css-background", variants: [{ url, sourceKind: "css-background", width: element.clientWidth, height: element.clientHeight }] });
if (media.length >= limit) break;
}
}
@@ -1956,8 +1988,12 @@ export async function collectPageCaptureSnapshot(options = {}) {
const url = safeHttpUrl(element.src);
if (!url) return false;
try {
- const host = new URL(url).hostname.toLocaleLowerCase("en-US");
- return ["youtube.com", "youtube-nocookie.com", "youtu.be", "player.vimeo.com", "player.bilibili.com", "douyin.com", "open.douyin.com", "platform.twitter.com"].some((suffix) => host === suffix || host.endsWith(`.${suffix}`));
+ const parsed = new URL(url);
+ const host = parsed.hostname.toLocaleLowerCase("en-US");
+ if (parsed.protocol === "https:" && (options.videoFrameRules || []).some(rule =>
+ host === rule.host && parsed.pathname.startsWith(rule.pathPrefix) && parsed.pathname.endsWith(rule.pathSuffix))) return true;
+ if (host === "www.tiktok.com") return /^\/player\/v1\/\d+\/?$/u.test(new URL(element.src).pathname);
+ return ["youtube.com", "youtube-nocookie.com", "youtu.be", "player.vimeo.com", "player.bilibili.com", "douyin.com", "open.douyin.com"].some((suffix) => host === suffix || host.endsWith(`.${suffix}`));
} catch {
return false;
}
@@ -2016,6 +2052,24 @@ export async function collectPageCaptureSnapshot(options = {}) {
return candidates;
}
+ function xQuoteContainer(element) {
+ if (!["x.com", "twitter.com"].includes(location.hostname) || !element.closest('article[data-testid="tweet"]')) return null;
+ return element.closest('[data-testid="quoteTweet"], [role="link"][tabindex="0"]');
+ }
+
+ function xPostMediaUrl(element) {
+ const photoUrl = xPostPhotoUrl(element);
+ if (photoUrl) return photoUrl;
+ if (!["x.com", "twitter.com"].includes(location.hostname) || !element.matches("video")) return "";
+ const post = element.closest('article[data-testid="tweet"]');
+ if (!post) return "";
+ const quote = xQuoteContainer(element);
+ const link = quote
+ ? [...quote.querySelectorAll('a[href*="/status/"]')].find(node => node.querySelector("time"))
+ : ownPostLinks(post)[0];
+ return safeHttpUrl(link?.href);
+ }
+
function xPostPhotoUrl(element) {
if (!["x.com", "twitter.com"].includes(location.hostname) || !element.closest('article[data-testid="tweet"]')) return "";
const link = element.closest('a[href*="/photo/"]');
@@ -2026,6 +2080,14 @@ export async function collectPageCaptureSnapshot(options = {}) {
}
function isExcludedMedia(element) {
+ if (options.siteData?.adapter === "krea" && options.siteData?.pageKind === "detail") {
+ const link = element.closest?.("a[href]");
+ try {
+ const url = new URL(link?.href);
+ if ((url.hostname === "krea.ai" || url.hostname.endsWith(".krea.ai"))
+ && url.pathname.startsWith("/feed/") && url.pathname !== new URL(options.siteData.canonicalUrl).pathname) return true;
+ } catch { /* This media is not a link to another Krea work. */ }
+ }
const postPhoto = Boolean(xPostPhotoUrl(element));
if (!postPhoto && element.closest("nav,aside,header,[role=banner],[aria-label*=广告],[aria-label*=advertisement]")) return true;
const rect = element.getBoundingClientRect();
@@ -2123,15 +2185,18 @@ function uniqueMedia(values) {
placement: value?.placement === "inline" ? "inline" : "unplaced",
...(localAssetId ? { localAssetId } : {}),
...(value?.contentHash ? { contentHash: clean(value.contentHash) } : {}),
+ ...(value?.isQuoted === true ? { isQuoted: true } : {}),
...(safeUrl(value?.quotedPostUrl) ? { quotedPostUrl: safeUrl(value.quotedPostUrl) } : {}),
...(value?.isCover === true && kind === "image" ? { isCover: true } : {}),
url,
posterUrl,
+ ...(safeUrl(value.streamUrl) ? { streamUrl: safeUrl(value.streamUrl) } : {}),
...(dataUrl ? { dataUrl } : {}),
...(previewDataUrl ? { previewDataUrl } : {}),
...(normalizeFallbackRect(value?.fallbackRect) ? { fallbackRect: normalizeFallbackRect(value.fallbackRect) } : {}),
variants,
alt: clean(value.alt),
+ ...(clean(value.originalPrompt) ? { originalPrompt: normalizeText(value.originalPrompt) } : {}),
filename: clean(value.filename),
mimeType: clean(value.mimeType).toLocaleLowerCase("en-US"),
...(["document", "attachment"].includes(kind) && /^data:(?:text\/[a-z0-9.+-]+|application\/(?:pdf|rtf|zip|gzip|x-gzip|octet-stream))(?:;charset=[a-z0-9-]+)?;base64,[a-z0-9+/=]+$/i.test(value.downloadDataUrl || "")
@@ -2164,6 +2229,7 @@ function uniqueMedia(values) {
previewDataUrl: existing.previewDataUrl || item.previewDataUrl,
fallbackRect: existing.fallbackRect || item.fallbackRect,
alt: existing.alt || item.alt,
+ ...((existing.originalPrompt || item.originalPrompt) ? { originalPrompt: existing.originalPrompt || item.originalPrompt } : {}),
placement: existing.placement === "inline" || item.placement === "inline" ? "inline" : "unplaced"
};
indexById.set(id, existingIndex);
@@ -2230,7 +2296,7 @@ function normalizeMediaVariants(value = {}) {
function normalizeMediaSourceKind(value) {
const sourceKind = clean(value);
- return ["site-original", "structured", "picture-srcset", "deferred-srcset", "deferred-src", "img-srcset", "css-background", "current", "source"].includes(sourceKind)
+ return ["site-original", "video-element", "structured", "picture-srcset", "deferred-srcset", "deferred-src", "img-srcset", "css-background", "current", "source"].includes(sourceKind)
? sourceKind
: "source";
}
diff --git a/prompt-sources.js b/prompt-sources.js
index 4ad6f31..1b307d5 100644
--- a/prompt-sources.js
+++ b/prompt-sources.js
@@ -1,11 +1,17 @@
import { usesArticleReader } from "./case-presentation.js";
import { currentVideoReconstruction } from "./media.js";
import { validReconstructionPrompt } from "./image-prompt.js";
+import { CONTENT_ROLES, contentRoleForEntry } from "./taxonomy.js";
export function detailPromptSources(entry = {}, asset = {}) {
- const mediaPrompt = entry.mediaPrompts?.find(item => item.assetId === asset.id && item.source !== "ai-suggestion");
+ const mediaPrompt = entry.mediaPrompts?.find(item => item.assetId === asset.id && item.source === "manual")
+ || entry.mediaPrompts?.find(item => item.assetId === asset.id && item.source !== "ai-suggestion");
const adoptedAi = String(entry.mediaPrompts?.find(item => item.assetId === asset.id && item.source === "ai-suggestion")?.text ?? "").trim();
- const original = (mediaPrompt?.source !== "ai-suggestion" ? String(mediaPrompt?.text ?? "").trim() : "") || (usesArticleReader(entry) ? "" : String(entry.text ?? "").trim());
+ const sharedPromptAllowed = !usesArticleReader(entry)
+ && entry.sourceFacts?.originalPromptAvailable !== false
+ && !entry.mediaPrompts?.some(item => item.source === "webpage")
+ && ![CONTENT_ROLES.imageCase, CONTENT_ROLES.videoCase].includes(contentRoleForEntry(entry));
+ const original = String(mediaPrompt?.text ?? "").trim() || (sharedPromptAllowed ? String(entry.text ?? "").trim() : "");
const record = asset.kind === "video" ? currentVideoReconstruction(entry, asset.id) : null;
return {
original,
diff --git a/remote-video-player.js b/remote-video-player.js
new file mode 100644
index 0000000..40e82f9
--- /dev/null
+++ b/remote-video-player.js
@@ -0,0 +1,57 @@
+import { localVideoController } from "./media-playback.js";
+
+let runtime;
+const loadHls = () => runtime ||= import("./hls-runtime.js").then(() => globalThis.Hls);
+
+export async function attachRemoteVideo(video, reference, onStatus) {
+ const direct = reference.playbackUrl || "";
+ const stream = reference.streamUrl || (/\.m3u8(?:\?|$)/iu.test(direct) ? direct : "");
+ const controller = localVideoController(video);
+ let hls = null;
+ let disposed = false;
+ const fail = () => onStatus("视频暂不可播放,请从原页面重新采集", true);
+ let triedStream = false;
+ const startStream = async () => {
+ triedStream = true;
+ try {
+ const Hls = await loadHls();
+ if (disposed) return;
+ if (Hls.isSupported()) {
+ // Bundled runtime; workers stay disabled to avoid blob code execution.
+ hls = new Hls({ enableWorker: false });
+ hls.on(Hls.Events.ERROR, (_event, data) => {
+ if (data.fatal || [401, 403, 429].includes(data.response?.code)) {
+ hls.destroy();
+ fail();
+ }
+ });
+ hls.loadSource(stream);
+ hls.attachMedia(video);
+ } else if (video.canPlayType("application/vnd.apple.mpegurl")) video.src = stream;
+ else fail();
+ } catch { fail(); }
+ };
+ const onError = () => {
+ if (stream && !triedStream) void startStream();
+ else fail();
+ };
+ const ready = () => onStatus("可以播放", false);
+ video.addEventListener("playing", ready);
+ video.addEventListener("error", onError);
+ controller.destroy = () => {
+ disposed = true;
+ hls?.destroy();
+ video.removeEventListener("playing", ready);
+ video.removeEventListener("error", onError);
+ video.pause();
+ video.removeAttribute("src");
+ video.load();
+ };
+ try {
+ if (stream && (!direct || /\.m3u8(?:\?|$)/iu.test(direct))) {
+ await startStream();
+ } else if (direct) video.src = direct;
+ else fail();
+ } catch { fail(); }
+ return controller;
+}
diff --git a/skills-page.css b/skills-page.css
index a412b40..499d771 100644
--- a/skills-page.css
+++ b/skills-page.css
@@ -254,3 +254,39 @@ body:not([data-skill-view="list"]) .skills-main { padding-top: 20px; }
.skills-top-actions { gap: 6px; }
.skills-top-actions > button { padding-inline: 9px; }
}
+
+/* Source selection and the goal form share the workspace; detail view is unchanged. */
+.skill-builder:is([data-mode="create"], [data-mode="refine"]) { display: block; }
+.skill-builder:is([data-mode="create"], [data-mode="refine"]) > .skill-builder-content { display: grid; grid-template-columns: minmax(0, 1fr) 340px; align-items: start; gap: 16px; }
+.skill-builder:is([data-mode="create"], [data-mode="refine"]) #skill-source-step { grid-column: 1; grid-row: 1; min-width: 0; }
+.skill-builder:is([data-mode="create"], [data-mode="refine"]) #skill-target-step { grid-column: 2; grid-row: 1; position: sticky; top: 80px; min-width: 0; }
+.skill-builder:is([data-mode="create"], [data-mode="refine"]) :is(#skill-draft-step, #skill-versions-step, #skill-run-evidence-step) { grid-column: 1 / -1; }
+#skill-source-step #skill-source-sidebar { position: static; display: grid; grid-template-columns: auto minmax(0, 1fr) 36px; align-items: center; gap: 8px; margin: 12px 0; padding: 0; border: 0; background: transparent; }
+#skill-source-step #skill-source-sidebar > label { min-width: 0; }
+#skill-source-step #skill-case-search { min-width: 0; width: 100%; }
+#skill-source-step #skill-project-picker { margin: 0; }
+#skill-source-step #skill-project-picker > summary { white-space: nowrap; }
+#skill-source-step #skill-clear-selection { width: 36px; min-width: 36px; min-height: 36px; padding: 0; }
+.skill-builder:is([data-mode="create"], [data-mode="refine"]) #skill-case-grid { grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 8px; }
+.skill-builder:is([data-mode="create"], [data-mode="refine"]) #skill-case-scroll { max-height: calc(100dvh - 340px); min-height: 260px; }
+.skill-builder:is([data-mode="create"], [data-mode="refine"]) #skill-goal { min-height: 150px; line-height: 1.7; }
+.skill-builder:is([data-mode="create"], [data-mode="refine"]) .skill-section-heading { align-items: center; flex-wrap: wrap; }
+.skill-builder:is([data-mode="create"], [data-mode="refine"]) .skill-section-heading small { display: none; }
+.skill-builder:is([data-mode="create"], [data-mode="refine"]) .skill-vision-toggle { border: 0; padding: 10px 0; background: transparent; }
+.skill-builder:is([data-mode="create"], [data-mode="refine"]) .skill-advanced { border: 0; background: transparent; }
+.skill-builder:is([data-mode="create"], [data-mode="refine"]) .skill-step-actions { justify-content: flex-start; flex-wrap: wrap; }
+.skill-builder:is([data-mode="create"], [data-mode="refine"]) .skill-step-actions button { white-space: nowrap; }
+@media (max-width: 900px) {
+ .skill-builder:is([data-mode="create"], [data-mode="refine"]) > .skill-builder-content { grid-template-columns: minmax(0, 1fr) 300px; }
+}
+@media (max-width: 700px) {
+ .skill-builder:is([data-mode="create"], [data-mode="refine"]) > .skill-builder-content { display: flex; flex-direction: column; }
+ .skill-builder:is([data-mode="create"], [data-mode="refine"]) > .skill-builder-content > section { width: 100%; }
+ .skill-builder:is([data-mode="create"], [data-mode="refine"]) #skill-target-step { position: static; }
+ #skill-source-step #skill-source-sidebar { grid-template-columns: minmax(0, 1fr) 36px; }
+ #skill-source-step #skill-source-sidebar > div { grid-column: 1 / -1; }
+ .skill-builder:is([data-mode="create"], [data-mode="refine"]) #skill-case-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+ .skill-builder:is([data-mode="create"], [data-mode="refine"]) #skill-case-scroll { max-height: 330px; }
+}
+.skills-page:is([data-skill-view="create"], [data-skill-view="refine"]) .skills-topbar { display: flex; justify-content: space-between; align-items: center; gap: 12px; }
+.skills-page:is([data-skill-view="create"], [data-skill-view="refine"]) .skills-top-actions { margin: 0; flex-wrap: wrap; }
diff --git a/skills-page.js b/skills-page.js
index 2530834..7d2018d 100644
--- a/skills-page.js
+++ b/skills-page.js
@@ -64,7 +64,7 @@ bindTransientMenus(document, ".skill-detail-more, .skill-project-picker");
const CURATED_SKILL_PUBLISHER_STORAGE_KEY = "curatedSkillPublisher";
const elements = Object.fromEntries([
- "skill-search", "skill-import", "skill-create", "skill-context-back", "skill-zip-file", "skill-folder-files", "skill-library", "skill-summary", "skill-feedback", "skill-list", "skill-empty", "skill-empty-create",
+ "skill-search", "skill-import", "skill-create", "skill-context-back", "skill-zip-file", "skill-folder-files", "skill-library", "skill-summary", "skill-feedback", "skill-list", "skill-empty",
"skill-detail", "skill-detail-title", "skill-detail-call-name", "skill-detail-feedback", "skill-detail-description", "skill-detail-version", "skill-detail-source", "skill-detail-updated", "skill-detail-markdown", "skill-detail-edit", "skill-detail-more", "skill-detail-refine", "skill-export", "skill-submit-curated",
"skill-workspace", "skill-workspace-kicker", "skill-workspace-title", "skill-delete", "skill-builder", "skill-source-sidebar", "skill-source-step", "skill-target-step", "skill-selected-count", "skill-project-picker", "skill-project-label", "skill-project-filter", "skill-case-search", "skill-clear-selection", "skill-visible-select", "skill-selection-summary", "skill-case-scroll", "skill-case-grid", "skill-case-load-more",
"skill-run-evidence-step", "skill-run-evidence-count", "skill-run-evidence-list",
@@ -107,7 +107,6 @@ initializeNavigation();
function bindEvents() {
elements.skillSearch.addEventListener("input", renderSkillList);
elements.skillCreate.addEventListener("click", () => navigateTo("create"));
- elements.skillEmptyCreate.addEventListener("click", () => navigateTo("create"));
elements.skillContextBack.addEventListener("click", () => safely(navigateBack)());
elements.skillDetailEdit.addEventListener("click", () => navigateTo("editor", activeSkillId));
elements.skillDetailRefine.addEventListener("click", () => navigateTo("refine", activeSkillId));
diff --git a/skills.html b/skills.html
index 0d65eba..1011ac2 100644
--- a/skills.html
+++ b/skills.html
@@ -25,7 +25,7 @@
<div class="skills-heading"><div><h1 data-i18n="创作 Skill 中心">创作 Skill 中心</h1><p id="skill-summary"></p></div><div class="skills-heading-actions"><a class="button-secondary" href="curated-skills.html" data-i18n="精选 Skill">精选 Skill</a><button id="skill-import" class="button-secondary" type="button" data-i18n="导入">导入</button><button id="skill-create" type="button" data-i18n="新建 Skill">新建 Skill</button></div></div>
<p id="skill-feedback" class="skill-feedback" role="status"></p>
<div id="skill-list" class="skill-grid"></div>
- <div id="skill-empty" class="skill-empty" hidden><strong data-i18n="还没有创作 Skill">还没有创作 Skill</strong><p data-i18n="从你真正喜欢的案例中,按明确目标提炼一份可重复调用的方法。">从你真正喜欢的案例中,按明确目标提炼一份可重复调用的方法。</p><button id="skill-empty-create" type="button" data-i18n="创建第一份 Skill">创建第一份 Skill</button></div>
+ <div id="skill-empty" class="skill-empty" hidden><strong data-i18n="还没有创作 Skill">还没有创作 Skill</strong><p data-i18n="从你真正喜欢的案例中,按明确目标提炼一份可重复调用的方法。">从你真正喜欢的案例中,按明确目标提炼一份可重复调用的方法。</p></div>
</section>
<section id="skill-detail" class="skill-detail" hidden>
@@ -62,16 +62,17 @@
<header class="skill-workspace-header"><div><p id="skill-workspace-kicker" class="skill-workspace-mode"></p><h1 id="skill-workspace-title" data-i18n="创建创作 Skill">创建创作 Skill</h1></div><button id="skill-delete" class="button-secondary danger-button" type="button" hidden data-i18n="删除">删除</button></header>
<div id="skill-builder" class="skill-builder">
- <aside id="skill-source-sidebar" class="skill-source-sidebar">
- <div class="skill-section-heading"><div><small>01</small><strong data-i18n="选择来源案例">选择来源案例</strong></div><span id="skill-selected-count">0</span></div>
- <div><span class="skill-field-label" data-i18n="按项目筛选">按项目筛选</span><details id="skill-project-picker" class="skill-project-picker"><summary><span id="skill-project-label" data-i18n="全部项目">全部项目</span><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-chevron-down"></use></svg></summary><div id="skill-project-filter" class="skill-project-filter" role="listbox" aria-label="按项目筛选" data-i18n-aria-label="按项目筛选"></div></details></div>
- <label><span data-i18n="搜索案例">搜索案例</span><input id="skill-case-search" type="search" placeholder="搜索提示词或标题" data-i18n-placeholder="搜索提示词或标题" /></label>
- <button id="skill-clear-selection" class="button-secondary" type="button" disabled data-i18n="清空全部案例">清空全部案例</button>
- </aside>
<div class="skill-builder-content">
<section id="skill-source-step" class="skill-step">
<div class="skill-section-heading"><div><small data-i18n="来源">来源</small><strong data-i18n="案例组合">案例组合</strong></div><button id="skill-visible-select" class="button-secondary skill-visible-select" type="button" data-i18n="全选当前结果">全选当前结果</button></div>
+
+ <aside id="skill-source-sidebar" class="skill-source-sidebar skill-filter-row">
+ <span id="skill-selected-count" hidden>0</span>
+ <div><details id="skill-project-picker" class="skill-project-picker"><summary><span id="skill-project-label" data-i18n="全部项目">全部项目</span><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-chevron-down"></use></svg></summary><div id="skill-project-filter" class="skill-project-filter" role="listbox" aria-label="按项目筛选" data-i18n-aria-label="按项目筛选"></div></details></div>
+ <label><input aria-label="搜索案例" data-i18n-aria-label="搜索案例" id="skill-case-search" type="search" placeholder="搜索提示词或标题" data-i18n-placeholder="搜索提示词或标题" /></label>
+ <button class="icon-button" title="清空全部案例" aria-label="清空全部案例" data-i18n-title="清空全部案例" data-i18n-aria-label="清空全部案例" id="skill-clear-selection" type="button" disabled><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-x"></use></svg></button>
+ </aside>
<div id="skill-selection-summary" class="skill-selection-summary"></div>
<div id="skill-case-scroll" class="skill-case-scroll"><div id="skill-case-grid" class="skill-case-grid"></div><button id="skill-case-load-more" class="button-secondary skill-case-load-more" type="button" hidden data-i18n="加载更多案例">加载更多案例</button></div>
</section>
diff --git a/store/CHROME_WEB_STORE_SUBMISSION.md b/store/CHROME_WEB_STORE_SUBMISSION.md
index 0b3267a..affbd3b 100644
--- a/store/CHROME_WEB_STORE_SUBMISSION.md
+++ b/store/CHROME_WEB_STORE_SUBMISSION.md
@@ -6,7 +6,7 @@ This file is the source-of-truth worksheet for the current PromptDirector manife
- Chrome Web Store item public key: stored in the source `manifest.json` for local identity verification only; `package:release` removes `key` from the upload manifest.
- Expected extension ID: `iahakaahijddcjjldidbclicedibgpjm`.
-- Current upload artifact: `dist/PromptDirector-1.20.5.zip`. The GitHub `FIXED-ID-DEV` artifact is for local installations only.
+- Current upload artifact: `dist/PromptDirector-1.20.6.zip`. The GitHub `FIXED-ID-DEV` artifact is for local installations only.
- Generate a candidate only with `npm run package:release`; the command verifies the source public key against the expected identity, then removes `key` from the Web Store upload manifest and excludes the local program installer. Record the generated ZIP size and SHA-256 from the final release assets.
## Store listing
diff --git a/test/artstation_capture_e2e.py b/test/artstation_capture_e2e.py
new file mode 100644
index 0000000..44aeebd
--- /dev/null
+++ b/test/artstation_capture_e2e.py
@@ -0,0 +1,87 @@
+"""Reduced DOM based on a public ArtStation project; isolated fixtures, not live-site acceptance."""
+from __future__ import annotations
+
+import json
+import tempfile
+from pathlib import Path
+
+from e2e_support import EXTENSION_DIR, extension_session
+from page_capture_e2e import fixture_png
+
+SITE = "https://fixture-artist.artstation.com"
+PLAYER = "https://www.artstation.com"
+CDN = "https://cdn.artstation.com"
+WORK = f"{SITE}/projects/fixture"
+FRAME = f"{PLAYER}/api/v2/animation/video_clips/fixture/embed.html?s=fixture"
+VIDEO = f"{CDN}/p/video_sources/fixture.mp4"
+
+
+def main():
+ with tempfile.TemporaryDirectory(prefix="artstation-extension-") as temp:
+ extension = Path(temp)
+ for file in EXTENSION_DIR.iterdir():
+ if file.name not in {"manifest.json", ".git", "node_modules", "dist"}:
+ (extension / file.name).symlink_to(file, target_is_directory=file.is_dir())
+ manifest = json.loads((EXTENSION_DIR / "manifest.json").read_text())
+ # Only this disposable fixture install gets pre-granted test origins.
+ manifest["host_permissions"] += [f"{origin}/*" for origin in (SITE, PLAYER, CDN)]
+ (extension / "manifest.json").write_text(json.dumps(manifest))
+ with extension_session("artstation-capture-", extension_dir=extension) as run:
+ video_bytes = (Path(__file__).parent / "fixtures/zhipu-local-video-smoke.mp4").read_bytes()
+ images = "".join(f'<img class="project-assets-image" alt="Artwork {i}" src="{CDN}/list-image-{i}.png" style="width:280px;height:280px">' for i in range(1, 4))
+ document = f'''<!doctype html><html><head><title>Mixed artwork fixture</title><link rel="canonical" href="{WORK}"></head>
+ <body class="project"><h1>Mixed artwork fixture</h1><div class="project-description"><p>This is a personal artwork with alternate versions and a process film.</p></div>
+ {images}<div class="asset-responsive video-clip"><iframe title="Process film" src="{FRAME}" style="width:360px;height:400px"></iframe></div></body></html>'''
+
+ def route(request):
+ url = request.request.url
+ if url == WORK:
+ request.fulfill(status=200, content_type="text/html", body=document)
+ elif url == FRAME:
+ request.fulfill(status=200, content_type="text/html", body=f'<video controls preload="auto" src="{VIDEO}"></video>')
+ elif url == VIDEO:
+ request.fulfill(status=200, content_type="video/mp4", body=video_bytes)
+ elif url.startswith(CDN):
+ request.fulfill(status=200, content_type="image/png", body=fixture_png(url))
+ else:
+ request.abort()
+
+ for origin in (SITE, PLAYER, CDN):
+ run.context.route(f"{origin}/**", route)
+ collector = run.open_page("collector.html")
+ run.seed_storage(collector, {"schemaVersion": 24, "entries": []})
+ source = run.context.new_page()
+ source.goto(WORK, wait_until="networkidle")
+ source.frame_locator("iframe").locator("video").evaluate("v => {if(v.readyState < 2) throw new Error('Fixture video not loaded');}")
+ source.bring_to_front()
+ batch = collector.evaluate('''async () => {
+ const response = await chrome.runtime.sendMessage({type:'START_PAGE_CAPTURE',mode:'loaded'});
+ if (!response.ok) throw new Error(response.message);
+ return response.batch;
+ }''')
+ candidate = next((c for c in batch["candidates"] if len(c["media"]) == 4), None)
+ assert candidate is not None, batch
+ assert [m["kind"] for m in candidate["media"]] == ["image", "image", "image", "video"], candidate
+ assert candidate["media"][-1]["url"] == VIDEO, candidate
+ assert candidate["media"][-1]["sourceKind"] == "video-element", candidate
+ assert collector.evaluate("async () => (await chrome.storage.local.get('entries')).entries") == []
+ batch["selections"] = [{"candidateId": candidate["id"], "includeText": True,
+ "selectedMediaIds": [m["id"] for m in candidate["media"]], "mediaDecision": "confirmed"}]
+ saved = collector.evaluate("async batch => chrome.runtime.sendMessage({type:'COMMIT_PAGE_CAPTURE',batch})", batch)
+ assert saved.get("ok"), saved
+ entries = collector.evaluate("async () => (await chrome.runtime.sendMessage({type:'GET_STATE'})).entries")
+ assert len(entries) == 1, entries
+ assets = [a for a in entries[0]["mediaAssets"] if a.get("usage") != "poster"]
+ assert [a["kind"] for a in assets] == ["image", "image", "image", "video"], assets
+ assert all(a["storageMode"] == "managed" for a in assets), assets
+ assert not any("prompt" in path or path in {"content:reference", "content:tutorial"} for path in entries[0]["classification"]["pathIds"]), entries[0]
+ video = assets[-1]
+ assert video["originalWorkUrl"] == WORK, video
+ collector.reload()
+ readback = collector.evaluate("async id => {const {getMediaBlob}=await import('./media-store.js'); const blob=await getMediaBlob(id); return {size:blob.size,type:blob.type};}", video["id"])
+ assert readback == {"size": len(video_bytes), "type": "video/mp4"}, readback
+ print("ArtStation fixture: 3 images + 1 cross-origin player video captured in order, local video bytes retained after reload.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/capture-additions.test.js b/test/capture-additions.test.js
index 5c04a48..142df4e 100644
--- a/test/capture-additions.test.js
+++ b/test/capture-additions.test.js
@@ -53,3 +53,16 @@ test('adding a webpage preserves headings and quotes without repeating original
assert.ok(blocks.some(b => b.kind === 'quote' && b.text === 'A quoted creative direction.'));
assert.equal(blocks.map(b => b.text || '').join(' ').match(/A quoted creative direction/g).length, 1);
});
+
+
+test("saved capture outcomes consume partial and duplicate cases but preserve unsaved candidates", async () => {
+ const { savedPageCaptureCandidateIds } = await import("../capture-additions.js");
+ const candidates = ["saved", "partial", "duplicate", "failed"].map(id => ({ id }));
+ const results = candidates.map(({ id }) => ({ candidateId: id, status: id, ...(id !== "failed" ? { entryId: `entry:${id}` } : {}) }));
+ assert.deepEqual([...savedPageCaptureCandidateIds({}, candidates, results)], ["saved", "partial", "duplicate"]);
+ assert.deepEqual([...savedPageCaptureCandidateIds({}, candidates, [])], []);
+ assert.deepEqual([...savedPageCaptureCandidateIds({captureMode:"list",saveMode:"combined"}, candidates,
+ [{candidateId:"combined-id",entryId:"saved-entry",status:"partial"}])], candidates.map(item => item.id));
+ assert.deepEqual([...savedPageCaptureCandidateIds({captureMode:"list",saveMode:"combined"}, candidates,
+ [{candidateId:"combined-id",status:"failed"}])], []);
+});
diff --git a/test/capture-content-contract.test.js b/test/capture-content-contract.test.js
new file mode 100644
index 0000000..09bf237
--- /dev/null
+++ b/test/capture-content-contract.test.js
@@ -0,0 +1,159 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import { classifyContent } from "../classifier.js";
+import { CONTENT_IDS } from "../taxonomy.js";
+import { usesArticleReader } from "../case-presentation.js";
+import { normalizePageCaptureCandidate, resolvePageCapturePageType, applyPageCaptureSelections, collectPageCaptureSnapshot } from "../page-capture.js";
+import { normalizePageCaptureSitePayload } from "../page-capture-site-adapters.js";
+import { capturedMediaPrompts, planPageCaptureRepair, mergePageCaptureRepair } from "../page-capture-repair.js";
+import { normalizeEntryMedia, setEntryMediaPrompt } from "../media.js";
+import { detailPromptSources } from "../prompt-sources.js";
+
+test("structured work descriptions are not original generation prompts", () => {
+ for (const [kind, pageType, expected] of [["image", "artwork", CONTENT_IDS.imageCase], ["video", "video", CONTENT_IDS.videoCase]]) {
+ const entry = { text: "My latest campaign for a local brand.", sourceFacts: { pageType, extractionMethod: "structured" },
+ mediaAssets: [{ id: kind, kind }] };
+ assert.deepEqual(classifyContent(entry).pathIds, [expected]);
+ entry.text = "Prompt collection: Create a portrait";
+ entry.sourceFacts.originalPromptAvailable = false;
+ assert.deepEqual(classifyContent(entry).pathIds, [expected]);
+ assert.equal(detailPromptSources(entry, entry.mediaAssets[0]).original, "");
+ }
+});
+
+test("an article with a video and example prompt opens as an intact article", () => {
+ assert.equal(resolvePageCapturePageType({ structuredTypes: ["Article", "VideoObject"] }), "article");
+ const entry = { title: "A production diary", text: "Prompt: Create a cinematic scene --ar 16:9",
+ sourceFacts: { pageType: "article", extractionMethod: "structured" },
+ mediaAssets: [{ id: "v", kind: "video" }],
+ articleDocument: { version: 1, blocks: [{ kind: "paragraph", text: "Introduction" }, { kind: "video", assetId: "v" }, { kind: "code", text: "Create a scene" }] } };
+ const before = structuredClone(entry);
+ const classified = { ...entry, classification: classifyContent(entry) };
+ assert.equal(usesArticleReader(classified), true);
+ assert.deepEqual(classified.classification.pathIds, [CONTENT_IDS.reference]);
+ assert.deepEqual(entry, before);
+});
+
+test("a social video caption or image model name alone cannot invent a generation prompt", () => {
+ for (const [kind, text, expected] of [["video", "My video made in Runway", CONTENT_IDS.videoCase], ["image", "Midjourney photography from this week", CONTENT_IDS.imageCase]]) {
+ const entry = { text, sourceFacts: { pageType: "post", extractionMethod: "page" }, mediaAssets: [{ id: "m", kind }] };
+ assert.deepEqual(classifyContent(entry).pathIds, [expected]);
+ }
+ assert.deepEqual(classifyContent({ text: "Prompt: a red landscape", mediaAssets: [{ id: "m", kind: "image" }] }).pathIds, [CONTENT_IDS.promptImage]);
+});
+
+test("injected page extraction keeps article precedence and source prompt evidence", async () => {
+ const keys = ["window", "document", "location", "chrome", "Readability"];
+ const original = Object.fromEntries(keys.map(key => [key, globalThis[key]]));
+ const url = "https://example.com/creative-work";
+ const body = { innerText: "A complete production diary", scrollHeight: 800, querySelector: () => null, querySelectorAll: () => [] };
+ const structured = [{ "@type": "Article", articleBody: body.innerText, url }, { "@type": "VideoObject", url }];
+ Object.assign(globalThis, { window: { scrollX: 0, scrollY: 0, scrollTo: () => {} },
+ document: { title: "Production diary", body, documentElement: { scrollHeight: 800 }, baseURI: url,
+ querySelector: () => null, querySelectorAll: selector => selector === 'script[type="application/ld+json"]' ? [{ textContent: JSON.stringify(structured) }] : [],
+ cloneNode: () => ({}) }, location: { hostname: "example.com", href: url }, chrome: undefined, Readability: undefined });
+ try {
+ const injected = (0, eval)(`(${collectPageCaptureSnapshot.toString()})`);
+ const article = await injected({ adapters: [], maxCandidates: 10, maxMedia: 10 });
+ assert.equal(article.candidates[0].pageType, "article");
+ const work = await injected({ adapters: [], maxCandidates: 10, maxMedia: 10, siteData: {
+ pageKind: "detail", pageType: "artwork", canonicalUrl: url, title: "Selected work", contentText: "原始提示词",
+ sourceFacts: { originalPromptAvailable: true, description: "作品说明", extractionMethod: "structured" },
+ media: [{ id: "one", kind: "image", url: "https://example.com/one.png", originalPrompt: "原始提示词" }] } });
+ assert.equal(work.candidates[0].sourceFacts.originalPromptAvailable, true);
+ assert.equal(work.candidates[0].sourceFacts.description, "作品说明");
+ assert.equal(work.candidates[0].media[0].originalPrompt, "原始提示词");
+ } finally {
+ Object.assign(globalThis, original);
+ }
+});
+
+function liblibWork() {
+ return normalizePageCaptureCandidate(normalizePageCaptureSitePayload({ adapter: "liblibai",
+ canonicalUrl: "https://www.liblib.art/imageinfo/work-fixture",
+ data: { uuid: "work-fixture", title: "Two different prompts", user: { nickname: "Fixture" },
+ images: ["A red landscape", "A blue portrait"].map((prompt, index) => ({ id: index + 1,
+ originalImageUrl: `https://liblib.cloud/${index + 1}.png`, generateInfo: { prompt } })) }
+ }));
+}
+
+test("different source prompts survive normalization, asset remapping and manual edits", () => {
+ const candidate = liblibWork();
+ assert.deepEqual(candidate.media.map(item => item.originalPrompt), ["A red landscape", "A blue portrait"]);
+ assert.equal(candidate.contentText, "A red landscape\n\nA blue portrait");
+ const ids = new Map(candidate.media.map((item, i) => [item.id, `saved-${i}`]));
+ const entry = normalizeEntryMedia({ text: candidate.contentText, sourceFacts: candidate.sourceFacts,
+ mediaAssets: [...ids.values()].map(id => ({ id, kind: "image" })), mediaPrompts: capturedMediaPrompts(candidate, ids) });
+ assert.deepEqual(entry.mediaPrompts.map(item => item.source), ["webpage", "webpage"]);
+ assert.equal(detailPromptSources(entry, entry.mediaAssets[1]).original, "A blue portrait");
+ const edited = setEntryMediaPrompt(entry, "saved-1", "My edit", "manual", { preserveOtherSource: true });
+ assert.equal(detailPromptSources(edited, edited.mediaAssets[1]).original, "My edit");
+ assert.equal(detailPromptSources(edited, { id: "unrelated", kind: "image" }).original, "");
+ assert.deepEqual(capturedMediaPrompts(candidate, ids, edited.mediaPrompts), edited.mediaPrompts);
+});
+
+test("deselecting text does not secretly save original prompts through the selected images", () => {
+ const candidate = liblibWork();
+ const [selected] = applyPageCaptureSelections({ candidates: [candidate], selections: [{ candidateId: candidate.id,
+ includeText: false, mediaDecision: "confirmed", selectedMediaIds: candidate.media.map(item => item.id) }] });
+ assert.equal(selected.contentText, "");
+ assert.ok(selected.media.every(item => !item.originalPrompt));
+ assert.equal(selected.sourceFacts.originalPromptAvailable, false);
+});
+
+test("keeping only a description cannot inherit the deselected source prompt classification", () => {
+ const work = liblibWork();
+ const candidate = normalizePageCaptureCandidate({ ...work,
+ contentText: `${work.contentText}\n\nA study from my portfolio.`,
+ textBlocks: [{ id: "prompts", text: work.contentText }, { id: "description", text: "A study from my portfolio." }]
+ });
+ const select = id => applyPageCaptureSelections({ candidates: [candidate], selections: [{ candidateId: candidate.id,
+ includeText: true, selectedTextBlockIds: [id], mediaDecision: "confirmed", selectedMediaIds: candidate.media.map(item => item.id) }] })[0];
+ const description = select("description");
+ assert.equal(description.sourceFacts.originalPromptAvailable, false);
+ assert.ok(description.media.every(item => !item.originalPrompt));
+ assert.deepEqual(classifyContent({ text: description.contentText, sourceFacts: description.sourceFacts,
+ mediaAssets: description.media }).pathIds, [CONTENT_IDS.imageCase]);
+ assert.equal(select("prompts").sourceFacts.originalPromptAvailable, true);
+});
+
+test("recapture fills missing per-image prompts without downloading saved media or overwriting edits", async () => {
+ const candidate = liblibWork();
+ const entry = { text: "Edited case body", title: "My title", customLabels: ["Keep"],
+ mediaAssets: candidate.media.map((item, index) => ({ id: `saved-${index}`, kind: item.kind, sourceUrl: item.url, storageMode: "managed" })),
+ mediaPrompts: [{ assetId: "saved-0", source: "manual", text: "My prompt" }] };
+ const plan = await planPageCaptureRepair(entry, candidate, async () => true);
+ assert.equal(plan.pending.length, 0);
+ assert.equal(plan.promptsChanged, true);
+ const repaired = mergePageCaptureRepair(entry, candidate, plan, [], plan.assetIds);
+ assert.deepEqual(repaired.mediaPrompts.map(item => item.text), ["My prompt", "A blue portrait"]);
+ assert.equal(repaired.text, entry.text);
+ assert.equal(repaired.title, entry.title);
+ assert.deepEqual(repaired.customLabels, entry.customLabels);
+ assert.equal((await planPageCaptureRepair(repaired, candidate, async () => true)).promptsChanged, false);
+});
+
+test("capture save and additions cannot enqueue paid analysis as an automatic side effect", async () => {
+ const source = await readFile(new URL("../background.js", import.meta.url), "utf8");
+ for (const name of ["commitPageCapture", "commitCaptureDraft", "commitCaptureIntoCompound", "addUploadedVisual", "addUploadedMedia"]) {
+ const start = source.indexOf(`async function ${name}(`);
+ assert.ok(start >= 0);
+ const end = source.indexOf("\nasync function ", start + 1);
+ assert.doesNotMatch(source.slice(start, end), /queueAutomaticVisionAnalysis|startOrJoinAnalysisTask|analyzeTextDetailedWithDeepSeek/);
+ }
+ assert.match(source, /async function startOrJoinAnalysisTaskAction/);
+});
+
+
+test("a short original prompt used as the work title still survives preview and selection", () => {
+ const prompt = "A cinematic silhouette.";
+ const candidate = normalizePageCaptureCandidate({ id: "prompt-title", title: prompt, canonicalUrl: "https://example.com/work",
+ pageType: "artwork", contentText: prompt, sourceFacts: { originalPromptAvailable: true },
+ textBlocks: [{ id: "prompt", kind: "paragraph", text: prompt, relevance: "explicit-creative" }],
+ media: [{ id: "image", kind: "image", url: "https://example.com/image.png", originalPrompt: prompt }] });
+ const [selected] = applyPageCaptureSelections({ candidates: [candidate], selections: [{ candidateId: candidate.id,
+ includeText: true, selectedMediaIds: ["image"], mediaDecision: "confirmed" }] });
+ assert.equal(selected.contentText, prompt);
+ assert.equal(selected.media[0].originalPrompt, prompt);
+});
diff --git a/test/capture-runtime-wiring.test.js b/test/capture-runtime-wiring.test.js
index c76709e..9eab106 100644
--- a/test/capture-runtime-wiring.test.js
+++ b/test/capture-runtime-wiring.test.js
@@ -55,7 +55,7 @@ test("captured posts retain real media facts when suggesting a case category", a
const start = source.indexOf("async function commitPageCapture");
const end = source.indexOf("async function", start + 20);
const save = source.slice(start, end);
- assert.match(save, /classifyContent\(\{ \.\.\.base, sourceFacts: candidate\.sourceFacts, mediaAssets \}/);
+ assert.match(save, /classifyContent\(\{ \.\.\.base, sourceFacts: candidate\.sourceFacts, mediaAssets, mediaPrompts \}/);
assert.doesNotMatch(save, /classificationMediaAssets/);
});
diff --git a/test/capture_partial_save_e2e.py b/test/capture_partial_save_e2e.py
new file mode 100644
index 0000000..57aad5f
--- /dev/null
+++ b/test/capture_partial_save_e2e.py
@@ -0,0 +1,60 @@
+"""Reproduce saved video references leaving the capture sidebar uncleared. Isolated fixture."""
+import re
+from playwright.sync_api import expect
+from e2e_support import extension_session
+from page_capture_e2e import fixture_png
+
+
+def main():
+ with extension_session('capture-partial-save-', viewport={'width':390,'height':844}) as run:
+ run.context.route('https://pbs.twimg.com/**', lambda route: route.fulfill(body=fixture_png(route.request.url), content_type='image/png'))
+ page=run.open_page('collector.html')
+ run.seed_storage(page, {'entries':[], 'capturePermissionOnboarding':{'version':1,'acknowledgedAt':'2026-09-07T00:00:00Z','clipboardIncluded':True}})
+ page.evaluate("""async () => {
+ const send=chrome.runtime.sendMessage.bind(chrome.runtime);
+ const {createCaptureDraft}=await import('./capture-draft.js');
+ await send({type:'UPDATE_CAPTURE_DRAFT',draft:createCaptureDraft({fragments:[{id:'clipboard-fragment',text:'用户补充的剪贴板文字,已入库后应从侧栏清除。',sourceUrl:'https://x.com/director/status/123'}]})});
+ chrome.permissions.contains=async()=>true;chrome.permissions.request=async()=>true;
+ chrome.tabs.query=async()=>[{id:999,url:'https://x.com/director/status/123'}];
+ chrome.runtime.sendMessage=async m=>{
+ if(m.type==='COMMIT_PAGE_CAPTURE' && window.forceSaveFailure)return {ok:false,message:'模拟保存失败'};
+ if(m.type==='START_PAGE_CAPTURE') return {ok:true,batch:{sourceUrl:'https://x.com/director/status/123',candidates:[{
+ id:'partial-video',title:'Video prompt fixture',canonicalUrl:'https://x.com/director/status/123',pageType:'post',
+ contentText:'Prompt: a cinematic martial arts scene.',textBlocks:[{id:'text',kind:'section',text:'Prompt: a cinematic martial arts scene.'}],
+ media:[{id:'video',kind:'video',url:'',posterUrl:'https://pbs.twimg.com/video-poster.png',placement:'inline',sourceKind:'video-element'}],
+ articleDocument:{version:1,blocks:[{id:'text',kind:'paragraph',text:'Prompt: a cinematic martial arts scene.'},{id:'video-block',kind:'video',assetId:'video'}]},
+ sourceFacts:{provider:'x',pageType:'post'}
+ }]}};
+ if(['PREVIEW_PAGE_CAPTURE_REGION','CLEAR_PAGE_CAPTURE_MARKERS'].includes(m.type)) return {ok:true};
+ const result=await send(m);
+ if(m.type==='COMMIT_PAGE_CAPTURE')window.saveResult=result;
+ return result;
+ };
+ }""")
+ page.evaluate("()=>window.dispatchEvent(new Event('focus'))")
+ page.locator('#add-page-capture').click()
+ page.locator('.page-capture-confirm').click()
+ page.locator('#page-capture-save').click()
+ page.wait_for_function('()=>Boolean(window.saveResult)')
+ result=page.evaluate('window.saveResult')
+ assert result['ok'] and result['results'][0]['status']=='partial', result
+ entries=page.evaluate("async()=> (await chrome.storage.local.get('entries')).entries")
+ assert len(entries)==1 and any(asset['kind']=='video' for asset in entries[0]['mediaAssets']),entries
+ assert entries[0]['sourceFacts']['captureWarnings'], entries
+ expect(page.locator('#page-capture')).to_be_hidden()
+ expect(page.locator('#feedback')).to_contain_text('已保存')
+ assert len(page.evaluate("async()=> (await chrome.storage.local.get('entries')).entries"))==1
+ expect(page.locator('#feedback')).not_to_have_class(re.compile(r'\berror\b'))
+ workspace=page.evaluate("async()=>chrome.runtime.sendMessage({type:'GET_CAPTURE_WORKSPACE'})")
+ assert workspace['draft']['fragments']==[],workspace
+ page.evaluate('()=>window.forceSaveFailure=true')
+ page.locator('#start-page-capture').click()
+ page.locator('.page-capture-confirm').click()
+ page.locator('#page-capture-save').click()
+ expect(page.locator('#feedback')).to_contain_text('模拟保存失败')
+ expect(page.locator('#page-capture')).to_be_visible()
+ assert len(page.evaluate("async()=> (await chrome.storage.local.get('entries')).entries"))==1
+ print({'case_saved':True,'warning_retained':True,'saved_sidebar_cleared':True,'unsaved_content_preserved':True})
+
+
+if __name__=='__main__':main()
diff --git a/test/classifier.test.js b/test/classifier.test.js
index 659d053..5e7f082 100644
--- a/test/classifier.test.js
+++ b/test/classifier.test.js
@@ -12,7 +12,7 @@ import { CONTENT_IDS, CONTENT_ROLES, createContentType, createDefaultTaxonomy, r
test("declared creative works use their medium even when prompt text resembles an article or a broad site rule", () => {
const entry = { url: "https://example.com/work", title: "Workflow", text: "First use the attached image. Then follow these steps, because identity consistency matters.",
- sourceFacts: { pageType: "video", extractionMethod: "structured" },
+ sourceFacts: { pageType: "video", extractionMethod: "structured", originalPromptAvailable: true },
mediaAssets: [{ id: "video", kind: "video", storageMode: "reference", sourceUrl: "https://cdn.example.com/movie.mp4" }] };
const rules = [{ hostname: "example.com", pathIds: [CONTENT_IDS.tutorial], enabled: true }];
assert.deepEqual(classifyContent(entry, rules).pathIds, [CONTENT_IDS.promptVideo]);
diff --git a/test/fixtures/hls-audio-video/README.md b/test/fixtures/hls-audio-video/README.md
new file mode 100644
index 0000000..6ba8fda
--- /dev/null
+++ b/test/fixtures/hls-audio-video/README.md
@@ -0,0 +1 @@
+Synthetic 3-second blue H.264 video (160×90, 10 fps) with a 440 Hz AAC audio track, fragmented MP4 HLS. Generated with FFmpeg for playback tests; contains no platform media. Presentation starts at 0.2 seconds; complete playback ends at 3.2 seconds. Tests assert decoded audio and video, seeking, teardown and unavailable-source handling.
diff --git a/test/fixtures/hls-audio-video/init.mp4 b/test/fixtures/hls-audio-video/init.mp4
new file mode 100644
index 0000000..89c5c1b
Binary files /dev/null and b/test/fixtures/hls-audio-video/init.mp4 differ
diff --git a/test/fixtures/hls-audio-video/stream.m3u8 b/test/fixtures/hls-audio-video/stream.m3u8
new file mode 100644
index 0000000..674fce6
--- /dev/null
+++ b/test/fixtures/hls-audio-video/stream.m3u8
@@ -0,0 +1,13 @@
+#EXTM3U
+#EXT-X-VERSION:7
+#EXT-X-TARGETDURATION:1
+#EXT-X-MEDIA-SEQUENCE:0
+#EXT-X-PLAYLIST-TYPE:VOD
+#EXT-X-MAP:URI="init.mp4"
+#EXTINF:1.000000,
+stream0.m4s
+#EXTINF:1.000000,
+stream1.m4s
+#EXTINF:1.000000,
+stream2.m4s
+#EXT-X-ENDLIST
diff --git a/test/fixtures/hls-audio-video/stream0.m4s b/test/fixtures/hls-audio-video/stream0.m4s
new file mode 100644
index 0000000..615d15f
Binary files /dev/null and b/test/fixtures/hls-audio-video/stream0.m4s differ
diff --git a/test/fixtures/hls-audio-video/stream1.m4s b/test/fixtures/hls-audio-video/stream1.m4s
new file mode 100644
index 0000000..9ec86b9
Binary files /dev/null and b/test/fixtures/hls-audio-video/stream1.m4s differ
diff --git a/test/fixtures/hls-audio-video/stream2.m4s b/test/fixtures/hls-audio-video/stream2.m4s
new file mode 100644
index 0000000..351ca57
Binary files /dev/null and b/test/fixtures/hls-audio-video/stream2.m4s differ
diff --git a/test/frontend_compact_surfaces_e2e.py b/test/frontend_compact_surfaces_e2e.py
new file mode 100644
index 0000000..f398798
--- /dev/null
+++ b/test/frontend_compact_surfaces_e2e.py
@@ -0,0 +1,63 @@
+from __future__ import annotations
+
+from playwright.sync_api import expect
+from e2e_support import extension_session, base_entry
+
+# Publicly shaped fixtures in a disposable install; no provider or public submission request is sent.
+with extension_session('pd-six-surfaces-', viewport={'width':1440,'height':960}) as session:
+ page=session.open_page('collector.html',wait_until='networkidle')
+ session.seed_storage(page, {'entries':[base_entry('frontend-review-case','界面验收案例','光线与构图参考','content:prompt:image',0)], 'uiPreferences':{'locale':'zh-CN','theme':'dark','motion':'reduced'}})
+ page=session.open_page('library.html',wait_until='networkidle')
+ page.locator('#open-settings').click()
+ page.locator('[data-settings-tab="rules"]').click()
+ text=page.locator('#analysis-instructions-zh');original=text.input_value()
+ text.fill('保留尚未保存的规则')
+ expect(page.locator('#ai-settings-status')).to_have_text('未保存')
+ page.locator('[data-analysis-kind="vision"]').click()
+ page.locator('#vision-instructions-zh').fill('保留图片规则')
+ page.locator('[data-analysis-kind="text"]').click()
+ expect(text).to_have_value('保留尚未保存的规则')
+ page.locator('#settings-close').click();page.locator('#open-settings').click();page.locator('[data-settings-tab="rules"]').click()
+ expect(text).to_have_value('保留尚未保存的规则')
+ page.locator('#ai-settings-form button[type=submit]').click()
+ expect(page.locator('#ai-settings-status')).to_have_text('分析规则已保存')
+ saved=page.evaluate("async()=> (await chrome.runtime.sendMessage({type:'GET_STATE'})).aiSettings.analysisInstructionsByLocale['zh-CN']")
+ assert saved=='保留尚未保存的规则',saved
+ page.locator('[data-analysis-kind="composer"]').click()
+ page.locator('#composer-agent-instruction').fill('独立的系统指令草稿')
+ page.locator('#composer-task-method').fill('图片方法草稿')
+ page.locator('#composer-task-key').select_option('compose.video');page.locator('#composer-task-method').fill('视频方法草稿')
+ page.locator('#composer-task-key').select_option('compose.image');expect(page.locator('#composer-task-method')).to_have_value('图片方法草稿')
+ page.locator('#composer-settings-form button[type=submit]').click();expect(page.locator('#composer-task-save-state')).to_have_text('已保存')
+ expect(page.locator('#composer-agent-instruction')).to_have_value('独立的系统指令草稿')
+ page.locator('#composer-task-key').select_option('compose.video');expect(page.locator('#composer-task-method')).to_have_value('视频方法草稿')
+ page.locator('[data-analysis-kind="text"]').click();page.locator('#restore-analysis-default').click();expect(text).to_have_value(original);expect(page.locator('#ai-settings-status')).to_have_text('未保存')
+ for width,height,locale,theme in [(1440,960,'zh-CN','dark'),(390,844,'en','light')]:
+ page.set_viewport_size({'width':width,'height':height})
+ page.locator('[data-settings-tab="general"]').click()
+ for selector,value in [('#ui-theme',theme),('#ui-locale',locale)]:
+ if page.locator(selector).input_value()!=value:
+ with page.expect_navigation(wait_until='networkidle'):
+ page.locator(selector).select_option(value)
+ page.locator('#open-settings').click()
+ for tab in ['ai','rules','tasks']:
+ page.locator(f'[data-settings-tab="{tab}"]').click()
+ metrics=page.locator(f'#settings-{tab}-panel').evaluate('(e)=>({width:e.clientWidth,scroll:e.scrollWidth})')
+ assert metrics['scroll']<=metrics['width']+1,(tab,metrics)
+ centers=page.evaluate("""()=>{const a=document.querySelector('#batch-status-badge').getBoundingClientRect(),b=document.querySelector('#preview-analysis-batch').getBoundingClientRect();return Math.abs(a.top+a.height/2-b.top-b.height/2)}""")
+ assert centers<=1,centers
+ page.set_viewport_size({'width':1440,'height':960});page.locator('#settings-close').click()
+ page.locator('#select-cases').click();page.locator('#selection-select-filtered').click();page.locator('#share-export').click()
+ expect(page.locator('#share-dialog .eyebrow')).to_be_visible();expect(page.locator('#share-dialog-public-panel')).to_be_hidden()
+ page.locator('#share-dialog-public').click();expect(page.locator('#share-dialog-submit')).to_be_disabled();page.locator('#share-dialog-disclosure').check();expect(page.locator('#share-dialog-submit')).to_be_enabled()
+ page.evaluate("""()=>{const send=chrome.runtime.sendMessage.bind(chrome.runtime);window.frontendCalls=[];chrome.runtime.sendMessage=async m=>{if(['EXPORT_ARCHIVE','EXPORT_CURATED_SUBMISSION'].includes(m.type)){window.frontendCalls.push(m);return {ok:false,message:'Isolated failure fixture'}}return send(m)}}""")
+ page.locator('#share-dialog-submit').click();expect(page.locator('#share-dialog-submit')).to_be_enabled();page.locator('#share-dialog-export').click();expect(page.locator('#share-dialog-export')).to_be_enabled()
+ calls=page.evaluate('window.frontendCalls');assert [c['type'] for c in calls]==['EXPORT_CURATED_SUBMISSION','EXPORT_ARCHIVE'],calls
+ assert all(c['entryIds']==['frontend-review-case'] for c in calls),calls
+ page.locator('#share-dialog-close').click()
+ page.locator('#media-file').set_input_files([{'name':'review.txt','mimeType':'text/plain','buffer':b'Frontend import fixture'}])
+ expect(page.locator('#import-confirmation')).to_be_visible();tags=page.locator('#import-label-editor input');tags.fill('manual-tag');tags.press('Enter');expect(page.locator('#import-label-editor')).to_contain_text('manual-tag')
+ page.set_viewport_size({'width':390,'height':844})
+ assert page.locator('.tag-editor-row').evaluate('(e)=>e.scrollWidth<=e.clientWidth+1')
+ assert not session.page_errors,session.page_errors
+ print({'rules_save_and_draft_retention':True,'independent_composer_drafts':True,'share_original_payloads':True,'manual_tags':True,'responsive_alignment':True})
diff --git a/test/krea_capture_e2e.py b/test/krea_capture_e2e.py
new file mode 100644
index 0000000..95e18b7
--- /dev/null
+++ b/test/krea_capture_e2e.py
@@ -0,0 +1,55 @@
+"""Reduced Krea detail DOM fixtures; verifies source selection, not live-site availability."""
+import json
+from e2e_support import extension_session
+
+URL = 'https://www.krea.ai/feed/work-554bfb91-2a06-5e91-8a21-24a162f3b81f'
+ORIGINAL = 'https://gen.krea.ai/images/554bfb91-2a06-5e91-8a21-24a162f3b81f.png'
+PREVIEW = 'https://optim-images.krea.ai/work-preview.webp'
+REFERENCE = 'https://app-uploads.krea.ai/style.webp'
+PROXY = 'https://www.krea.ai/api/img?i=https%3A%2F%2Fapp-uploads.krea.ai%2Fstyle.webp&s=128'
+PROMPT = 'A cinematic silhouette in a carefully composed moonlit landscape.'
+HTML = f'''<!doctype html><html><head><title>Krea fixture</title><link rel="canonical" href="{URL}">
+<script type="application/ld+json">{json.dumps({'@type':'ImageObject','contentUrl':ORIGINAL,'url':URL,'width':768,'height':1376})}</script></head><body>
+<article><h1>{PROMPT}</h1><figure><img src="{PREVIEW}" style="width:280px;height:500px"></figure>
+<button aria-label="Copy style reference image 1" style="width:100px;height:100px;background-image:url('{PROXY}')"></button>
+<a href="/feed/recommendation-72324387-04f9-526e-ae96-e132f34ab60c"><div style="width:200px;height:200px;background-image:url('https://optim-images.krea.ai/recommended.webp')"></div></a>
+</article></body></html>'''
+
+
+def main():
+ with extension_session('krea-capture-') as run:
+ run.context.route('https://www.krea.ai/feed/**', lambda route: route.fulfill(body=HTML, content_type='text/html'))
+ setup = run.open_page('collector.html')
+ functions = setup.evaluate("""async () => ({
+ site: (await import('./page-capture-site-adapters.js')).collectPageCaptureSitePayload.toString(),
+ scan: (await import('./page-capture.js')).collectPageCaptureSnapshot.toString(),
+ adapters: (await import('./page-capture-adapter-registry.js')).PAGE_CAPTURE_ADAPTERS,
+ limits: (await import('./resource-limits.js')).PAGE_CAPTURE_LIMITS,
+ maxTextCharacters: (await import('./resource-limits.js')).PORTABLE_LIBRARY_LIMITS.maxLibraryJsonBytes
+ })""")
+ page = run.context.new_page()
+ page.goto(URL)
+ payload = page.evaluate('options => ('+functions['site']+')(options)', {'maxMedia':functions['limits']['maxMediaPerCandidate'],'maxCandidates':functions['limits']['maxCandidates'],'maxTextCharacters':functions['maxTextCharacters']})
+ assert payload['styleReferences'][0]['url'] == REFERENCE, payload
+ site = setup.evaluate("async p => (await import('./page-capture-site-adapters.js')).normalizePageCaptureSitePayload(p,p.canonicalUrl)", payload)
+ snapshot = page.evaluate('options => ('+functions['scan']+')(options)', {'siteData':site,'adapters':functions['adapters']})
+ assert len(snapshot['candidates']) == 1, snapshot
+ candidate = snapshot['candidates'][0]
+ assert [m['url'] for m in candidate['media']] == [ORIGINAL, REFERENCE], candidate
+ assert candidate['contentText'] == PROMPT, candidate
+ assert candidate['media'][0]['originalPrompt'] == PROMPT, candidate
+ assert not candidate['media'][1].get('originalPrompt'), candidate
+ assert all('recommended' not in v['url'] for m in candidate['media'] for v in m.get('variants', [])), candidate
+ selected = setup.evaluate("""async c => {
+ const {applyPageCaptureSelections}=await import('./page-capture.js');
+ return applyPageCaptureSelections({status:'ready',candidates:[c],selections:[{
+ candidateId:c.id,includeText:true,selectedMediaIds:c.media.map(m=>m.id),mediaDecision:'confirmed'
+ }]})[0];
+ }""", candidate)
+ assert len(selected['media']) == 2, selected
+ assert selected['media'][0].get('originalPrompt') == PROMPT and not selected['media'][1].get('originalPrompt'), selected
+ print({'krea_detail_one_case':True,'original_without_preview_duplicate':True,'style_reference_without_invented_prompt':True,'recommendations_excluded':True})
+
+
+if __name__ == '__main__':
+ main()
diff --git a/test/library-model.test.js b/test/library-model.test.js
index 8244dd4..94ce72e 100644
--- a/test/library-model.test.js
+++ b/test/library-model.test.js
@@ -173,3 +173,9 @@ test("a compound logical case matches search, content filters, and pending state
assert.equal(filterEntries([compound], { contentId: CONTENT_IDS.promptVideo }, createDefaultFacetCatalog()).length, 1);
assert.equal(filterEntries([compound], { pendingOnly: true }, createDefaultFacetCatalog()).length, 1);
});
+
+
+test("saved capture warnings remain readable in source details after the sidebar clears", () => {
+ const rows = entrySourceMetadataRows({sourceFacts:{captureWarnings:["视频文件未保存"]}});
+ assert.ok(rows.some(row => row.label === "采集问题" && row.value === "视频文件未保存"));
+});
diff --git a/test/library-package.test.js b/test/library-package.test.js
index 0e5dd86..86154a7 100644
--- a/test/library-package.test.js
+++ b/test/library-package.test.js
@@ -50,6 +50,25 @@ function catalog() {
return createFacetNode(value, { id: "tag:epic", facetId: "facet:mood", parentId: "tag:dramatic", name: "史诗" });
}
+test("webpage prompt provenance survives a portable package and media identity collisions", () => {
+ const data = packageData([{ ...entry("remote"), hasScreenshot: false, screenshotPath: undefined,
+ mediaAssets: [{ id: "shared-image", kind: "image", storageMode: "managed", sourceUrl: "https://example.com/remote.png", mimeType: "image/png", assetPath: "images/remote.png" }],
+ mediaPrompts: [{ assetId: "shared-image", source: "webpage", text: "Original source prompt", textRevision: 1 }]
+ }], catalog());
+ const parsed = parseLibraryPackage(data, new Map([["images/remote.png", new Blob(["fixture image"], { type: "image/png" })]]));
+ assert.equal(parsed.entries[0].mediaPrompts[0].source, "webpage");
+ const current = { entries: [{ ...entry("local"), hasScreenshot: false, screenshotPath: undefined,
+ mediaAssets: [{ id: "shared-image", kind: "image", storageMode: "reference", sourceUrl: "https://example.com/local.png" }] }],
+ taxonomy: createDefaultTaxonomy(), facetCatalog: catalog(), settings: {}, classificationRules: [], organizerState: { collections: [] } };
+ const merged = mergeLibraryPackage(current, data);
+ const restored = merged.state.entries.find(item => item.title === "案例 remote");
+ assert.ok(restored);
+ assert.notEqual(restored.mediaAssets[0].id, "shared-image");
+ assert.equal(restored.mediaPrompts[0].assetId, restored.mediaAssets[0].id);
+ assert.equal(restored.mediaPrompts[0].source, "webpage");
+ assert.equal(restored.mediaPrompts[0].text, "Original source prompt");
+});
+
test("parseLibraryPackage validates the portable library format and referenced screenshots", () => {
const data = packageData([entry("one")], catalog());
data.entries[0].customLabels = ["喜欢", " 喜欢 ", "待复刻"];
diff --git a/test/local-index-maintenance-ui.test.js b/test/local-index-maintenance-ui.test.js
index 0661994..ca07400 100644
--- a/test/local-index-maintenance-ui.test.js
+++ b/test/local-index-maintenance-ui.test.js
@@ -8,10 +8,10 @@ const [html, source, background] = await Promise.all([
readFile(new URL("../background.js", import.meta.url), "utf8")
]);
-test("local index maintenance explains automatic local completion and has no decorative progress bar", () => {
+test("local index maintenance groups its original controls with the title and has no decorative progress bar", () => {
const card = html.slice(html.indexOf('<div class="batch-card local-index-card">'), html.indexOf('id="legacy-candidates"'));
assert.match(card, /资料索引自动补全/);
- assert.match(card, /每次导入后会在本机自动补齐内容类型和图片色卡,不调用 AI/);
+ assert.match(card, /class="task-heading"><h3[^>]*>资料索引自动补全<\/h3><div class="batch-actions">/);
assert.match(card, /id="preview-reanalyze"[^>]*>检查缺失项/);
assert.match(card, /id="apply-reanalyze"[^>]*hidden[^>]*>开始补全/);
assert.doesNotMatch(card, /<progress|maintenance-progress/);
diff --git a/test/media-playback.test.js b/test/media-playback.test.js
index c99251b..b70d544 100644
--- a/test/media-playback.test.js
+++ b/test/media-playback.test.js
@@ -1,4 +1,5 @@
import test from "node:test";
+import { tiktokMediaController } from "../media-playback.js";
import assert from "node:assert/strict";
import {
@@ -50,3 +51,29 @@ test("YouTube player errors distinguish author blocks, missing videos and client
assert.match(youtubePlaybackError(100).blockReason, /不存在|私密/);
assert.match(youtubePlaybackError(153).blockReason, /客户端身份/);
});
+test("TikTok player messages require the matching frame and report real playback state", async () => {
+ let listener;
+ let removed = false;
+ const statuses = [];
+ const sent = [];
+ const frame = { contentWindow: { postMessage: (...args) => sent.push(args) }, addEventListener: () => {}, removeEventListener: () => {} };
+ const events = { addEventListener: (_, fn) => { listener = fn; }, removeEventListener: (_, fn) => { removed = fn === listener; } };
+ const controller = tiktokMediaController(frame, (...args) => statuses.push(args), events);
+ const event = (type, value, overrides = {}) => ({ origin: "https://www.tiktok.com", source: frame.contentWindow,
+ data: { "x-tiktok-player": true, type, value }, ...overrides });
+ listener(event("onPlayerReady", undefined, { origin: "https://evil.example" }));
+ listener(event("onPlayerReady", undefined, { source: {} }));
+ assert.deepEqual(statuses, []);
+ await assert.rejects(controller.getCurrentTimeMs(), /尚未报告/);
+ listener(event("onPlayerReady"));
+ listener(event("onStateChange", 1));
+ listener(event("onCurrentTime", { currentTime: 3.25 }));
+ assert.equal(await controller.getCurrentTimeMs(), 3250);
+ assert.deepEqual(statuses, [["播放器已加载", false], ["正在播放", false]]);
+ await controller.seekToMs(2000);
+ assert.deepEqual(sent, [[{ type: "seekTo", value: 2, "x-tiktok-player": true }, "https://www.tiktok.com"]]);
+ listener(event("onPlayerError", { errorCode: 1001 }));
+ assert.deepEqual(statuses.at(-1), ["视频不存在、已删除或设为私密", true]);
+ controller.destroy();
+ assert.equal(removed, true);
+});
diff --git a/test/media-reference-resolver.test.js b/test/media-reference-resolver.test.js
index 80c8cb8..d50c9cc 100644
--- a/test/media-reference-resolver.test.js
+++ b/test/media-reference-resolver.test.js
@@ -40,7 +40,7 @@ test("Bilibili page and official player URLs normalize to one playable reference
);
assert.equal(
officialMediaEmbedUrl("https://x.com/director/status/123", "x"),
- "https://platform.twitter.com/embed/Tweet.html?id=123&dnt=true"
+ ""
);
});
@@ -53,6 +53,21 @@ test("media playback capability starts from honest provider state", async () =>
assert.match(bilibili.playback.embedUrl, /^https:\/\/player\.bilibili\.com\/player\.html\?/);
});
+test("TikTok uses the official post player and does not pretend a short link is playable", async () => {
+ for (const kind of ["video", "photo"]) {
+ const source = `https://www.tiktok.com/@creator/${kind}/6718335390845095173?is_from_webapp=1`;
+ assert.equal(detectMediaReferenceProvider(source), "tiktok");
+ assert.equal(officialMediaEmbedUrl(source), "https://www.tiktok.com/player/v1/6718335390845095173");
+ const result = await resolveMediaReference(source);
+ assert.equal(result.playbackMode, "embed");
+ assert.equal(result.playback.status, "loading");
+ }
+ const short = await resolveMediaReference("https://vm.tiktok.com/fixture/");
+ assert.equal(short.playbackMode, "source");
+ assert.equal(short.playback.embedUrl, "");
+ assert.equal(detectMediaReferenceProvider("https://tiktok.com.evil.example/@creator/video/123"), "generic");
+});
+
test("permission denial and metadata failure keep a saveable reference without invented fields", async () => {
const denied = await resolveMediaReference("https://www.bilibili.com/video/BV1abc", {
requestOrigins: async () => false,
@@ -102,3 +117,12 @@ test("Open Graph parser accepts property order variants", () => {
title: "封面标题", author: "作者", posterUrl: "", durationMs: 0
});
});
+
+
+test("X posts remain source references and never masquerade as standalone video players", async () => {
+ const url = "https://x.com/director/status/123";
+ const reference = await resolveMediaReference(url);
+ assert.equal(reference.playbackMode, "source");
+ assert.equal(reference.playback.embedUrl, "");
+ assert.notEqual(reference.playback.status, "playing");
+});
diff --git a/test/media-ui.test.js b/test/media-ui.test.js
index fbf6ec1..ff024b2 100644
--- a/test/media-ui.test.js
+++ b/test/media-ui.test.js
@@ -43,7 +43,7 @@ test("time notes seek the local player and support optional segment ends", () =>
test("social video references prefer official embeds and never download a platform video", () => {
const viewer = source.slice(source.indexOf("function createReferencedMediaViewer"), source.indexOf("function renderTimeNotes"));
- assert.match(viewer, /platform-link-card/);
+ assert.match(viewer, /unavailable-video-stage/);
assert.match(viewer, /referenced-video-embed/);
assert.match(viewer, /target = "_blank"/);
assert.doesNotMatch(viewer, /复制直链|readVideoMedia|saveMediaBlob/);
@@ -52,7 +52,7 @@ test("social video references prefer official embeds and never download a platfo
test("YouTube references request scoped playback permission and keep an honest source fallback", () => {
const viewer = source.slice(source.indexOf("function createReferencedMediaViewer"), source.indexOf("function renderTimeNotes"));
assert.match(viewer, /youtubeWatchUrl/);
- assert.match(viewer, /platform-link-card/);
+ assert.match(viewer, /unavailable-video-stage/);
assert.match(viewer, /posterAssetForVideo/);
assert.match(viewer, /ensureYouTubePlaybackPermission\(chrome, \{ request: true \}\)/);
assert.match(viewer, /youtubeMediaController/);
diff --git a/test/media.test.js b/test/media.test.js
index a55fdb9..4e5a00e 100644
--- a/test/media.test.js
+++ b/test/media.test.js
@@ -440,3 +440,14 @@ test("relinking an inert local source updates only verifiable file metadata", ()
sourceTitle: "custom.zzz", relativePath: "../custom.zzz", byteSize: 20, sourceLastModified: 1
}), /安全相对路径/u);
});
+
+
+test("saved X embed records keep their identity and source while losing unsupported embed mode", () => {
+ const url = "https://x.com/director/status/123";
+ const asset = normalizeMediaAsset({ id: "saved:x-video", kind: "video", storageMode: "reference", sourceUrl: url, playbackCapability: "embedded",
+ reference: { url, provider: "x", playbackMode: "embed" } });
+ assert.equal(asset.id, "saved:x-video");
+ assert.equal(asset.sourceUrl, url);
+ assert.equal(asset.reference.playbackMode, "source");
+ assert.equal(asset.playbackCapability, "external");
+});
diff --git a/test/media_reference_cards_e2e.py b/test/media_reference_cards_e2e.py
index 1c86011..2636648 100644
--- a/test/media_reference_cards_e2e.py
+++ b/test/media_reference_cards_e2e.py
@@ -45,13 +45,15 @@ def main() -> None:
results = []
for provider, label, url in FIXTURES:
library.locator(f'.case-card[data-entry-id="reference:{provider}"]').click()
- if provider == "youtube":
+ if provider in ["youtube", "x"]:
card = library.locator(".platform-playback-fallback")
expect(card).to_be_visible()
- expect(card).to_contain_text("授权并在案例库播放")
+ expect(card.locator(".unavailable-video-stage")).to_be_visible()
+ expect(library.locator(".referenced-video-embed iframe")).to_have_count(0)
+ expect(card).to_contain_text("授权并在案例库播放" if provider == "youtube" else "暂未取得可在案例库播放的视频")
source = card.locator("a", has_text="打开来源")
expect(source).to_have_attribute("href", url)
- results.append({"provider": provider, "state": "permission-required"})
+ results.append({"provider": provider, "state": "permission-required" if provider == "youtube" else "video-unavailable"})
else:
frame = library.locator(".referenced-video-embed iframe")
expect(frame).to_be_visible()
@@ -60,8 +62,6 @@ def main() -> None:
assert source.startswith("https://player.bilibili.com/player.html?") and "bvid=BV1abc" in source, source
elif provider == "douyin":
assert source.startswith("https://open.douyin.com/player/video?vid=123"), source
- else:
- assert source == "https://platform.twitter.com/embed/Tweet.html?id=123&dnt=true", source
expect(library.locator(".media-reference-fallback")).to_have_attribute("target", "_blank")
results.append({"provider": provider, "state": "official-embed"})
library.locator("#detail-close").click()
diff --git a/test/page-capture-frames.test.js b/test/page-capture-frames.test.js
new file mode 100644
index 0000000..69e4200
--- /dev/null
+++ b/test/page-capture-frames.test.js
@@ -0,0 +1,73 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readPageCaptureVideoFrame, resolvePageCaptureVideoFrames } from "../page-capture-frames.js";
+import { normalizePageCaptureCandidate } from "../page-capture.js";
+
+const frameUrl = "https://www.artstation.com/api/v2/animation/video_clips/fixture/embed.html?s=fixture";
+const videoUrl = "https://cdn.artstation.com/p/video_sources/fixture.mp4";
+const snapshot = () => ({ candidates: [{
+ id: "work", canonicalUrl: "https://artist.artstation.com/projects/fixture", title: "Mixed artwork",
+ completeness: "complete", sourceFacts: { status: "complete" },
+ media: [{ id: "image", kind: "image", url: "https://cdn.artstation.com/fixture.jpg" },
+ { id: "film", kind: "video", url: frameUrl }],
+ articleDocument: { version: 1, blocks: [{ id: "film-block", kind: "video", assetId: "film", sourceUrl: frameUrl }] }
+}] });
+
+test("a loaded project player becomes a downloadable video without changing media identity or order", async () => {
+ const result = await resolvePageCaptureVideoFrames(snapshot(), 42, {
+ executeScript: async request => {
+ assert.deepEqual(request.target, { tabId: 42, allFrames: true });
+ assert.deepEqual(request.args, [[frameUrl]]);
+ return [{ frameId: 0, result: null }, { frameId: 8, result: {
+ frameUrl, url: videoUrl, posterUrl: "https://cdn.artstation.com/thumb.jpg", width: 360, height: 400
+ } }];
+ }
+ });
+ const candidate = normalizePageCaptureCandidate(result.candidates[0]);
+ assert.deepEqual(candidate.media.map(item => item.id), ["image", "film"]);
+ assert.equal(candidate.media[1].url, videoUrl);
+ assert.equal(candidate.media[1].sourceKind, "video-element");
+ assert.equal(candidate.articleDocument.blocks[0].assetId, "film");
+ assert.equal(candidate.articleDocument.blocks[0].sourceUrl, videoUrl);
+ assert.equal(candidate.completeness, "complete");
+});
+
+test("inaccessible or unloaded players keep their place and report an incomplete capture", async () => {
+ for (const scripting of [{ executeScript: async () => { throw new Error("Missing host permission"); } },
+ { executeScript: async () => [{ result: null }] }]) {
+ const result = await resolvePageCaptureVideoFrames(snapshot(), 42, scripting);
+ const candidate = normalizePageCaptureCandidate(result.candidates[0]);
+ assert.equal(candidate.media.length, 2);
+ assert.equal(candidate.media[1].url, frameUrl);
+ assert.equal(candidate.completeness, "partial");
+ assert.equal(candidate.sourceFacts.status, "partial");
+ assert.equal(candidate.extraction.pendingMediaCount, 1);
+ }
+});
+
+test("ordinary pages and unrelated or spoofed frames do not trigger the player reader", async () => {
+ for (const url of ["https://www.artstation.com/account", frameUrl.replace(".com/", ".com.evil.test/"), "https://example.com/player"]) {
+ const input = snapshot();
+ input.candidates[0].media[1].url = url;
+ assert.equal(await resolvePageCaptureVideoFrames(input, 42, {
+ executeScript: () => assert.fail("unselected and unsupported frames must not be read")
+ }), input);
+ }
+});
+
+test("the serialized frame reader inspects only the selected frame and uses the active media source", () => {
+ const original = { location: globalThis.location, document: globalThis.document };
+ const reader = (0, eval)(`(${readPageCaptureVideoFrame.toString()})`);
+ try {
+ globalThis.location = { href: "https://example.com/advert" };
+ globalThis.document = { querySelectorAll: () => assert.fail("unselected frames must not be inspected") };
+ assert.equal(reader([frameUrl]), null);
+ globalThis.location = { href: frameUrl };
+ globalThis.document = { querySelectorAll: () => [{ currentSrc: videoUrl, poster: "", videoWidth: 360, videoHeight: 400 }] };
+ assert.equal(reader([frameUrl]).url, videoUrl);
+ globalThis.document = { querySelectorAll: () => [{ currentSrc: "blob:https://www.artstation.com/fixture" }] };
+ assert.equal(reader([frameUrl]), null);
+ } finally {
+ Object.assign(globalThis, original);
+ }
+});
diff --git a/test/page-capture-site-adapters.test.js b/test/page-capture-site-adapters.test.js
index 087cfe5..d2e799a 100644
--- a/test/page-capture-site-adapters.test.js
+++ b/test/page-capture-site-adapters.test.js
@@ -663,3 +663,21 @@ test("YesAnd has no dedicated collector and falls through to the generic page en
Object.assign(globalThis, original);
}
});
+
+
+test("Krea detail keeps original and preview together and does not assign the work prompt to style references", () => {
+ const url = "https://www.krea.ai/feed/work-554bfb91-2a06-5e91-8a21-24a162f3b81f";
+ const original = "https://gen.krea.ai/images/554bfb91-2a06-5e91-8a21-24a162f3b81f.png";
+ const preview = "https://optim-images.krea.ai/preview.webp";
+ const reference = "https://app-uploads.krea.ai/style.webp";
+ const result = normalizePageCaptureSitePayload({ adapter: "krea", pageKind: "detail", canonicalUrl: url,
+ prompt: "A cinematic silhouette.", imagePreviewUrl: preview,
+ jsonLd: [{ "@type": "ImageObject", contentUrl: original }],
+ styleReferences: [{ url: reference, previewUrl: "https://www.krea.ai/api/img?fixture", label: "style reference image 1" }]
+ }, url);
+ assert.equal(result.pageKind, "detail");
+ assert.deepEqual(result.media.map(media => media.url), [original, reference]);
+ assert.deepEqual(result.media[0].variants.map(variant => variant.url), [original, preview]);
+ assert.equal(result.media[0].originalPrompt, "A cinematic silhouette.");
+ assert.equal(result.media[1].originalPrompt, undefined);
+});
diff --git a/test/page-capture.test.js b/test/page-capture.test.js
index 7253ba9..93edf45 100644
--- a/test/page-capture.test.js
+++ b/test/page-capture.test.js
@@ -911,6 +911,20 @@ test("generic JSON-LD provides author, identity, publication time, engagement an
assert.deepEqual(candidate.sourceFacts.engagement, { likes: 91 });
assert.equal(candidate.media[0].url, "https://cdn.example.com/original.webp");
assert.equal(candidate.media[0].sourceKind, "structured");
+
+ Object.assign(structured, { "@type": "VideoObject", contentUrl: "https://cdn.example.com/work.m3u8", thumbnailUrl: "https://cdn.example.com/poster.jpg" });
+ delete structured.image;
+ const video = (await injected({ adapters: [], maxCandidates: 10, maxMedia: 10 })).candidates[0];
+ assert.equal(video.media.length, 1, "a video poster must not become a separate image case");
+ assert.equal(video.media[0].kind, "video");
+ assert.equal(video.media[0].streamUrl, structured.contentUrl);
+ assert.equal(video.pageType, "video");
+ const embeddedVideo = { ...structured };
+ Object.assign(structured, { "@type": "Article", video: embeddedVideo });
+ delete structured.contentUrl;
+ const article = (await injected({ adapters: [], maxCandidates: 10, maxMedia: 10 })).candidates[0];
+ assert.equal(article.pageType, "article", "an article containing a film retains article reading");
+ assert.equal(article.media[0].kind, "video");
} finally {
Object.assign(globalThis, original);
}
diff --git a/test/page_capture_e2e.py b/test/page_capture_e2e.py
index e1bdc6b..20c62be 100644
--- a/test/page_capture_e2e.py
+++ b/test/page_capture_e2e.py
@@ -204,12 +204,16 @@ def main() -> None:
expect(collector.locator("#page-capture-save-summary")).to_contain_text("6 项媒体")
expect(collector.locator("#page-capture-save")).to_be_enabled()
collector.locator("#page-capture-save").click()
- # A media failure must remain reviewable and retryable, with the real reason.
- expect(collector.locator("#page-capture-help")).to_contain_text("有效视频文件", timeout=8000)
+ # A committed case leaves the draft; its exact media failure remains in the case.
+ expect(collector.locator("#page-capture")).to_be_hidden(timeout=8000)
partial_saved = collector.evaluate("() => chrome.storage.local.get('entries').then(({entries}) => entries)")
assert len(partial_saved) == 1, partial_saved
original_entry_id = partial_saved[0]['id']
+ assert any('有效视频文件' in warning for warning in partial_saved[0]['sourceFacts']['captureWarnings']), partial_saved
video_available = True
+ fixture.bring_to_front()
+ collector.locator('#start-page-capture').click()
+ collector.locator('.page-capture-confirm').first.click()
collector.locator("#page-capture-save").click()
expect(collector.locator("#page-capture")).to_be_hidden(timeout=8000)
expect(fixture.locator("#promptdirector-page-capture-region-preview")).to_have_count(0)
diff --git a/test/run_e2e.py b/test/run_e2e.py
index 294ccfe..9def676 100644
--- a/test/run_e2e.py
+++ b/test/run_e2e.py
@@ -10,6 +10,7 @@ from pathlib import Path
TEST_DIR = Path(__file__).resolve().parent
SCRIPTS = [
+ "frontend_compact_surfaces_e2e.py",
"capture_and_cross_page_e2e.py",
"library_core_e2e.py",
"library_navigation_e2e.py",
@@ -56,8 +57,12 @@ SCRIPTS = [
"page_capture_e2e.py",
"page_capture_sidebar_e2e.py",
"capture_additions_e2e.py",
+ "capture_partial_save_e2e.py",
"x_capture_extraction_e2e.py",
+ "x_video_playback_e2e.py",
"higgsfield_capture_e2e.py",
+ "artstation_capture_e2e.py",
+ "krea_capture_e2e.py",
"libtv_capture_e2e.py",
"jimeng_capture_e2e.py",
"ai_provider_registry_e2e.py",
diff --git a/test/settings_visual_anchor_e2e.py b/test/settings_visual_anchor_e2e.py
index 5ccd796..3adde72 100644
--- a/test/settings_visual_anchor_e2e.py
+++ b/test/settings_visual_anchor_e2e.py
@@ -43,14 +43,12 @@ def settings_metrics(page) -> dict:
def assert_anchor_stable(baseline: dict, current: dict, label: str, viewport: dict) -> None:
- for surface in ("dialog", "header", "tabs"):
- # General settings now size to their content; the header and tabs stay anchored.
- for dimension in (("top",) if surface == "dialog" else ("top", "height")):
- shift = abs(current[surface][dimension] - baseline[surface][dimension])
- assert shift <= MAX_ANCHOR_SHIFT_PX, (
- f"{viewport} {label} changed {surface}.{dimension} by {shift:.2f}px: "
- f"baseline={baseline[surface]} current={current[surface]}"
- )
+ # Approved compact dialogs center according to content; general settings retain their anchor.
+ if label == "settings:general":
+ assert abs(current["dialog"]["top"] - baseline["dialog"]["top"]) <= MAX_ANCHOR_SHIFT_PX
+ else:
+ center = current["dialog"]["top"] + current["dialog"]["height"] / 2
+ assert abs(center - viewport["height"] / 2) <= MAX_ANCHOR_SHIFT_PX, (label, current)
assert current["windowScrollY"] == baseline["windowScrollY"], (label, current)
assert current["dialogScrollTop"] == 0, (label, current)
assert current["dialogScrollHeight"] <= current["dialogClientHeight"] + MAX_ANCHOR_SHIFT_PX, (label, current)
@@ -77,7 +75,7 @@ def exercise_settings(page, viewport: dict) -> None:
page.locator('[data-settings-tab="tasks"]').click()
local_index = page.locator(".local-index-card")
expect(local_index).to_contain_text("资料索引自动补全")
- expect(local_index).to_contain_text("会在本机自动补齐内容类型和图片色卡,不调用 AI")
+ expect(local_index.locator(".task-heading #preview-reanalyze")).to_be_visible()
expect(local_index.locator("progress")).to_have_count(0)
expect(local_index.locator("#apply-reanalyze")).to_be_hidden()
page.locator("#preview-reanalyze").click()
@@ -96,14 +94,14 @@ def exercise_settings(page, viewport: dict) -> None:
analysis_tabs.scroll_into_view_if_needed()
settle(page)
internal_anchor = {
- "top": analysis_tabs.evaluate("node => node.getBoundingClientRect().top"),
+ "top": analysis_tabs.evaluate("node => node.getBoundingClientRect().top - document.querySelector('#settings-dialog').getBoundingClientRect().top"),
"scrollTop": active_panel.evaluate("panel => panel.scrollTop"),
}
for tab in ("vision", "composer", "text"):
page.locator(f'[data-analysis-kind="{tab}"]').click()
settle(page)
current = {
- "top": analysis_tabs.evaluate("node => node.getBoundingClientRect().top"),
+ "top": analysis_tabs.evaluate("node => node.getBoundingClientRect().top - document.querySelector('#settings-dialog').getBoundingClientRect().top"),
"scrollTop": active_panel.evaluate("panel => panel.scrollTop"),
}
assert abs(current["top"] - internal_anchor["top"]) <= MAX_ANCHOR_SHIFT_PX, (
@@ -117,7 +115,7 @@ def exercise_settings(page, viewport: dict) -> None:
page.locator('[data-settings-tab="tasks"]').click()
page.locator('[data-settings-tab="rules"]').click()
settle(page)
- assert active_panel.evaluate("panel => panel.scrollTop") == 0
+ assert abs(active_panel.evaluate("panel => panel.scrollTop") - scrolled_to) <= MAX_ANCHOR_SHIFT_PX
expect(page.locator("#settings-close")).to_be_visible()
page.locator("#settings-close").click()
diff --git a/test/sharing_and_data_safety_e2e.py b/test/sharing_and_data_safety_e2e.py
index 1563ea0..3e45da5 100644
--- a/test/sharing_and_data_safety_e2e.py
+++ b/test/sharing_and_data_safety_e2e.py
@@ -202,6 +202,7 @@ def main() -> None:
library.locator("#share-export").click()
expect(library.locator("#share-dialog")).to_be_visible()
expect(library.locator("#share-dialog-disclosure")).not_to_be_checked()
+ library.locator("#share-dialog-public").click()
library.locator("#share-dialog-disclosure").check()
expect(library.locator("#share-dialog-submit")).to_be_enabled()
library.locator("#share-dialog-submit").click()
diff --git a/test/skill_source_density_e2e.py b/test/skill_source_density_e2e.py
index dfc1e44..acc61e8 100644
--- a/test/skill_source_density_e2e.py
+++ b/test/skill_source_density_e2e.py
@@ -96,7 +96,11 @@ def main() -> None:
desktop = layout_metrics(skills)
assert desktop["columns"] == 4, desktop
- assert desktop["minCardWidth"] >= 240, desktop
+ sources = skills.locator('#skill-source-step').bounding_box()
+ target = skills.locator('#skill-target-step').bounding_box()
+ assert target['x'] >= sources['x'] + sources['width'], (sources, target)
+ assert abs(target['y'] - sources['y']) < 1, (sources, target)
+ assert desktop["minCardWidth"] >= 220, desktop
assert desktop["pageWidth"] <= desktop["viewportWidth"], desktop
assert desktop["gridScrollWidth"] <= desktop["gridClientWidth"] + 1, desktop
assert desktop["titleClearance"] >= 4, desktop
@@ -137,7 +141,7 @@ def main() -> None:
skills.wait_for_function("""() => [...document.querySelectorAll('.skill-case-visual img')].some((image) => image.complete && image.naturalWidth > 0)""")
light = layout_metrics(skills)
assert light["columns"] == 4, light
- assert light["minCardWidth"] >= 240, light
+ assert light["minCardWidth"] >= 220, light
assert light["pageWidth"] <= light["viewportWidth"], light
assert light["headingColor"] == light["bodyColor"], light
assert light["brandColor"] == light["bodyColor"], light
@@ -146,7 +150,7 @@ def main() -> None:
skills.set_viewport_size({"width": 1200, "height": 900})
narrow = layout_metrics(skills)
assert narrow["columns"] == 3, narrow
- assert narrow["minCardWidth"] >= 240, narrow
+ assert narrow["minCardWidth"] >= 220, narrow
assert narrow["pageWidth"] <= narrow["viewportWidth"], narrow
skills.set_viewport_size({"width": 390, "height": 844})
diff --git a/test/x-video-capture.test.js b/test/x-video-capture.test.js
new file mode 100644
index 0000000..bcb8a99
--- /dev/null
+++ b/test/x-video-capture.test.js
@@ -0,0 +1,51 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import vm from 'node:vm';
+import { installXVideoObserver, applyXVideoSources, resolveXVideoSources } from '../x-video-capture.js';
+
+const variant = (name, bitrate = 1) => ({url:`https://video.twimg.com/${name}.mp4`,content_type:'video/mp4',bitrate});
+const post = (id, name) => ({rest_id:id,legacy:{extended_entities:{media:[{id_str:`media-${id}`,media_url_https:`https://pbs.twimg.com/${name}.jpg`,video_info:{variants:[variant(name),variant(`${name}-hd`,10)]}}]}}});
+function observer(payload) {
+ const original = async()=>new Response(JSON.stringify(payload));
+ const scope = vm.createContext({location:new URL('https://x.com/director/status/123'),fetch:original,URL,Blob,Response,TextDecoder,WeakSet,setTimeout,clearTimeout});
+ vm.runInContext(`(${installXVideoObserver.toString()})({timeoutMs:1000,maxBytes:100000,maxMedia:24})`,scope);
+ return {scope,original};
+}
+
+test('normal page response selects the current post at highest bitrate, never a reply or quote',async()=>{
+ const {scope,original}=observer({data:[post('456','reply'),post('123','work'),post('789','quote')]});
+ const response=await scope.fetch('/i/api/graphql/fixture');
+ assert.equal(response.status,200);
+ for(let n=0;n<30&&!scope.__PROMPTDIRECTOR_X_VIDEO__.done;n++)await new Promise(r=>setTimeout(r,5));
+ const state=scope.__PROMPTDIRECTOR_X_VIDEO__;
+ assert.equal(state.media.length,1);
+ assert.equal(state.media[0].variants[0].url,'https://video.twimg.com/work-hd.mp4');
+ assert.equal(scope.fetch,original,'the page fetch hook is restored after success');
+});
+
+test('unrelated endpoints and foreign media URLs do not become selected post video',async()=>{
+ const value=post('123','bad');value.legacy.extended_entities.media[0].video_info.variants=[{...variant('x'),url:'https://example.com/private.mp4'}];
+ const {scope,original}=observer(value);
+ await scope.fetch('/settings');await scope.fetch('/i/api/graphql/fixture');
+ await new Promise(r=>setTimeout(r,20));
+ assert.equal(scope.__PROMPTDIRECTOR_X_VIDEO__.media.length,0);
+ scope.__PROMPTDIRECTOR_X_VIDEO__.stop();assert.equal(scope.fetch,original);
+});
+
+test('resolved sources preserve text, IDs and excluded quotes even with a custom poster',()=>{
+ const snapshot={candidates:[{canonicalUrl:'https://x.com/director/status/123',contentText:'User supplement',media:[{id:'work',kind:'video',posterUrl:'https://pbs.twimg.com/custom.jpg'},{id:'quote',kind:'video',isQuoted:true}]}]};
+ const result=applyXVideoSources(snapshot,{postId:'123',media:[{variants:[{url:'https://video.twimg.com/file.mp4',mimeType:'video/mp4'}]}]});
+ assert.equal(result.candidates[0].contentText,'User supplement');
+ assert.equal(result.candidates[0].media[0].id,'work');
+ assert.equal(result.candidates[0].media[0].url,'https://video.twimg.com/file.mp4');
+ assert.deepEqual(result.candidates[0].media[1],snapshot.candidates[0].media[1]);
+ assert.equal(applyXVideoSources(snapshot,{postId:'456',media:[{}]}).candidates[0],snapshot.candidates[0]);
+});
+
+test('navigation away cleans up the temporary script without reloading another post',async()=>{
+ const actions=[];
+ const api={scripting:{unregisterContentScripts:async()=>actions.push('unregister'),registerContentScripts:async s=>{assert.equal(s[0].persistAcrossSessions,false);actions.push('register');},executeScript:async()=>[]},tabs:{reload:async()=>actions.push('reload'),get:async()=>({url:'https://x.com/director/status/456'})}};
+ const snapshot={candidates:[{canonicalUrl:'https://x.com/director/status/123',media:[{kind:'video',url:''}]}]};
+ assert.equal(await resolveXVideoSources(snapshot,{id:1,url:'https://x.com/director/status/123'},api),snapshot);
+ assert.deepEqual(actions,['unregister','register','reload','unregister']);
+});
diff --git a/test/x_capture_extraction_e2e.py b/test/x_capture_extraction_e2e.py
index 7661722..3fde8f8 100644
--- a/test/x_capture_extraction_e2e.py
+++ b/test/x_capture_extraction_e2e.py
@@ -49,6 +49,17 @@ def main():
assert noise not in c['contentText'],(noise,c['contentText'])
assert len(c['media'])==2 and all(m['kind']=='video' for m in c['media']),c['media']
assert all(not m['url'] for m in c['media']),c['media'] # no invented video route
+ assert c['media'][0]['originalWorkUrl'] == URL, c['media']
+ assert c['media'][1]['quotedPostUrl'] == 'https://x.com/other/status/456', c['media']
+ default_ids = setup.evaluate("async c=>(await import('./page-capture.js')).pageCaptureDefaultMediaIds(c)", c)
+ assert default_ids == [c['media'][0]['id']], (default_ids, c['media'])
+ # Current X quote cards can expose only a clickable container, with no public source URL.
+ page.locator('[role="link"][tabindex="0"] a[href*="/status/"]').evaluate('(link) => link.removeAttribute("href")')
+ unresolved = page.evaluate('async options => ('+scanner['fn']+')(options)', {'adapters':scanner['adapters']})['candidates'][0]
+ assert unresolved['media'][1]['isQuoted'] and not unresolved['media'][1].get('quotedPostUrl'), unresolved['media']
+ default_ids = setup.evaluate("async c=>(await import('./page-capture.js')).pageCaptureDefaultMediaIds(c)", unresolved)
+ assert default_ids == [unresolved['media'][0]['id']], (default_ids, unresolved['media'])
+
assert len(c['supplements'])==1 and c['supplements'][0]['partial'],c['supplements']
normalized=setup.evaluate("""async snapshot => {
const {normalizePageCaptureBatch, applyPageCaptureSelections} = await import(chrome.runtime.getURL('page-capture.js'));
@@ -100,9 +111,9 @@ def main():
# Group additions are independently selectable and undoable in the production sidebar.
setup.evaluate("candidate=>window.captureSnapshot={candidates:[candidate]}",grouped)
setup.locator('#start-page-capture').click();setup.locator('.page-capture-confirm').click()
- expect(setup.locator('.page-capture-media-group')).to_contain_text('引用帖 · 4 张图')
+ expect(setup.locator('.page-capture-media-group').filter(has_text="引用帖 · 4 张图")).to_have_count(1)
baseline=setup.locator('.page-capture-thumbnail').count()
- setup.get_by_role('button',name='加入这组',exact=True).click()
+ setup.locator('.page-capture-media-group').filter(has_text='引用帖 · 4 张图').get_by_role('button',name='加入这组',exact=True).click()
expect(setup.locator('.page-capture-thumbnail')).to_have_count(baseline+4)
setup.locator('#page-capture-undo-region').click()
expect(setup.locator('.page-capture-thumbnail')).to_have_count(baseline)
diff --git a/test/x_video_playback_e2e.py b/test/x_video_playback_e2e.py
new file mode 100644
index 0000000..9928a95
--- /dev/null
+++ b/test/x_video_playback_e2e.py
@@ -0,0 +1,100 @@
+"""Synthetic current-post responses. Actual extension capture, local MP4 and independent HLS playback."""
+import json, tempfile
+from pathlib import Path
+from playwright.sync_api import expect
+from e2e_support import EXTENSION_DIR, extension_session
+from page_capture_e2e import fixture_png
+
+WORK='https://x.com/director/status/123'
+CDN='https://video.twimg.com'
+MEDIA=Path(__file__).parent/'fixtures/hls-audio-video'
+
+
+def main():
+ with tempfile.TemporaryDirectory(prefix='x-video-extension-') as temp:
+ extension=Path(temp)
+ for file in EXTENSION_DIR.iterdir():
+ if file.name not in {'manifest.json','.git','node_modules','dist'}:
+ (extension/file.name).symlink_to(file,target_is_directory=file.is_dir())
+ # Chrome dynamic content scripts must be real files, as in the final archive.
+ (extension/'x-video-observer.js').unlink()
+ (extension/'x-video-observer.js').write_bytes((EXTENSION_DIR/'x-video-observer.js').read_bytes())
+ manifest=json.loads((EXTENSION_DIR/'manifest.json').read_text())
+ manifest['host_permissions']+=['https://x.com/*',CDN+'/*','https://pbs.twimg.com/*']
+ (extension/'manifest.json').write_text(json.dumps(manifest))
+ with extension_session('x-video-playback-',extension_dir=extension) as run:
+ mode={'stream':False}; loads=[]
+ video_bytes=b''.join((MEDIA/name).read_bytes() for name in ['init.mp4','stream0.m4s','stream1.m4s','stream2.m4s'])
+ document='''<html><head><link rel="canonical" href="'''+WORK+'''"></head><body><main><article data-testid="tweet">
+ <div data-testid="User-Name"><a href="/director"><span>Director</span></a></div>
+ <div data-testid="tweetText">A cinematic fight scene with a real video. Preserve this description without inventing a prompt.</div>
+ <video poster="https://pbs.twimg.com/custom.jpg" style="width:640px;height:360px"></video>
+ <a href="/director/status/123"><time datetime="2026-09-09T00:00:00Z">Today</time></a>
+ </article></main><script>fetch('/i/api/graphql/fixture').then(r=>r.json());</script></body></html>'''
+ def site(route):
+ if '/i/api/' in route.request.url:
+ variant={'url':CDN+('/stream.m3u8' if mode['stream'] else '/work.mp4'),'content_type':'application/x-mpegURL' if mode['stream'] else 'video/mp4','bitrate':100}
+ post=lambda id,variants:{'rest_id':id,'legacy':{'extended_entities':{'media':[{'id_str':'video-'+id,'media_url_https':'https://pbs.twimg.com/custom.jpg','video_info':{'variants':variants}}]}}}
+ route.fulfill(json={'data':[post('999',[{'url':CDN+'/wrong.mp4','content_type':'video/mp4','bitrate':999999}]),post('123',[variant])]})
+ else:
+ loads.append(route.request.url);route.fulfill(body=document,content_type='text/html')
+ def media(route):
+ name=route.request.url.rsplit('/',1)[-1]
+ if name=='work.mp4':route.fulfill(body=video_bytes,content_type='video/mp4')
+ elif (MEDIA/name).is_file():route.fulfill(body=(MEDIA/name).read_bytes(),content_type='application/vnd.apple.mpegurl' if name.endswith('m3u8') else 'video/mp4',headers={'Access-Control-Allow-Origin':'*'})
+ else:route.fulfill(status=403)
+ run.context.route('https://x.com/**',site)
+ run.context.route(CDN+'/**',media)
+ run.context.route('https://pbs.twimg.com/**',lambda r:r.fulfill(body=fixture_png(r.request.url),content_type='image/png'))
+ collector=run.open_page('collector.html');run.seed_storage(collector,{'entries':[]})
+ source=run.context.new_page();source.goto(WORK,wait_until='networkidle');source.bring_to_front()
+ batch=collector.evaluate("async()=>{const r=await chrome.runtime.sendMessage({type:'START_PAGE_CAPTURE',mode:'loaded'});if(!r.ok)throw Error(r.message);return r.batch;}")
+ candidate=batch['candidates'][0]
+ assert candidate['media'][0]['url']==CDN+'/work.mp4',batch
+ assert len(loads)==2,loads
+ assert collector.evaluate('async()=> (await chrome.scripting.getRegisteredContentScripts()).length')==0
+ batch['selections']=[{'candidateId':candidate['id'],'includeText':True,'selectedMediaIds':[candidate['media'][0]['id']],'mediaDecision':'confirmed'}]
+ result=collector.evaluate("async batch=>chrome.runtime.sendMessage({type:'COMMIT_PAGE_CAPTURE',batch})",batch)
+ assert result['ok'],result
+ entries=collector.evaluate("async()=> (await chrome.runtime.sendMessage({type:'GET_STATE'})).entries")
+ asset=next(a for a in entries[0]['mediaAssets'] if a['kind']=='video')
+ assert asset['storageMode']=='managed' and asset['byteSize']==len(video_bytes),asset
+ library=run.open_page('library.html');library.locator('.case-card').first.click()
+ video=library.locator('#detail-drawer video').first
+ video.evaluate('(v)=>{v.muted=true;return v.play();}')
+ library.wait_for_function("()=>{const v=document.querySelector('#detail-drawer video');return v?.ended;}")
+ assert video.evaluate('v=>v.webkitAudioDecodedByteCount>0 && v.webkitVideoDecodedByteCount>0')
+ library.locator('#detail-close').click()
+ # Exercise a second capture with HLS-only normal page data, then the real save path.
+ mode['stream']=True
+ collector.evaluate("async()=>chrome.storage.local.set({entries:[]})")
+ source.bring_to_front()
+ stream_batch=collector.evaluate("async()=>{const r=await chrome.runtime.sendMessage({type:'START_PAGE_CAPTURE',mode:'loaded'});if(!r.ok)throw Error(r.message);return r.batch;}")
+ stream_candidate=stream_batch['candidates'][0]
+ assert stream_candidate['media'][0]['streamUrl']==CDN+'/stream.m3u8',stream_batch
+ stream_batch['selections']=[{'candidateId':stream_candidate['id'],'includeText':True,'selectedMediaIds':[stream_candidate['media'][0]['id']],'mediaDecision':'confirmed'}]
+ stream_result=collector.evaluate("async batch=>chrome.runtime.sendMessage({type:'COMMIT_PAGE_CAPTURE',batch})",stream_batch)
+ assert stream_result['ok'],stream_result
+ stream_entries=collector.evaluate("async()=> (await chrome.runtime.sendMessage({type:'GET_STATE'})).entries")
+ stream_asset=next(a for a in stream_entries[0]['mediaAssets'] if a['kind']=='video')
+ assert stream_asset['storageMode']=='reference' and stream_asset['reference']['url']==WORK,stream_asset
+ library.reload();library.locator('.case-card').first.click()
+ video=library.locator('.referenced-video-stream video');expect(video).to_be_visible()
+ expect(library.locator('.referenced-video-stream iframe')).to_have_count(0)
+ video.evaluate('(v)=>{v.muted=true;return v.play();}')
+ library.wait_for_function("()=>{const v=document.querySelector('.referenced-video-stream video');return v?.currentTime>0.5;}")
+ video.evaluate('(v)=>v.currentTime=2')
+ library.wait_for_function("()=>document.querySelector('.referenced-video-stream video')?.ended")
+ evidence=video.evaluate('v=>({audio:v.webkitAudioDecodedByteCount,video:v.webkitVideoDecodedByteCount,duration:v.duration})')
+ assert evidence['audio']>0 and evidence['video']>0 and abs(evidence['duration']-3.2)<0.01,evidence
+ library.evaluate("()=>window.closedPlayer=document.querySelector('.referenced-video-stream video')")
+ library.locator('#detail-close').click()
+ assert library.evaluate("()=>window.closedPlayer.paused && !window.closedPlayer.getAttribute('src')")
+ run.context.route(CDN+'/stream.m3u8',lambda r:r.fulfill(status=403))
+ library.locator('.case-card').first.click()
+ expect(library.locator('.referenced-video-stream .media-playback-status')).to_contain_text('视频暂不可播放')
+ expect(library.locator('.referenced-video-stream iframe')).to_have_count(0)
+ library.locator('#detail-close').click()
+ print({'selected_post_only':True,'local_video_with_audio':True,'hls_audio_video_seek':evidence,'no_post_embed':True,'temporary_observer_removed':True})
+
+if __name__=='__main__':main()
diff --git a/tools/capture-runtime.mjs b/tools/capture-runtime.mjs
new file mode 100644
index 0000000..a753851
--- /dev/null
+++ b/tools/capture-runtime.mjs
@@ -0,0 +1,25 @@
+import { readFile, writeFile } from "node:fs/promises";
+import { installXVideoObserver } from "../x-video-capture.js";
+import { PAGE_CAPTURE_LIMITS, PORTABLE_LIBRARY_LIMITS } from "../resource-limits.js";
+
+const check = process.argv.includes("--check");
+const root = new URL("../", import.meta.url);
+const observer = `// Generated by build:capture-runtime from x-video-capture.js and resource-limits.js.\n(${installXVideoObserver.toString()})(${JSON.stringify({ timeoutMs: PAGE_CAPTURE_LIMITS.navigationTimeoutMs, maxBytes: PORTABLE_LIBRARY_LIMITS.maxLibraryJsonBytes, maxMedia: PAGE_CAPTURE_LIMITS.maxMediaPerCandidate })});\n`;
+const files = new Map([
+ ["x-video-observer.js", Buffer.from(observer)],
+ ["hls-runtime.js", await readFile(new URL("node_modules/hls.js/dist/hls.min.js", root))]
+]);
+for (const [name, bytes] of files) {
+ const path = new URL(name, root);
+ if (check) {
+ if (!bytes.equals(await readFile(path))) throw new Error(`Capture runtime differs: ${name}`);
+ } else await writeFile(path, bytes);
+}
+const license = await readFile(new URL("node_modules/hls.js/LICENSE", root), "utf8");
+const noticePath = new URL("THIRD_PARTY_NOTICES.md", root);
+const notices = await readFile(noticePath, "utf8");
+const marker = "\n## hls.js\n";
+const expected = `${notices.split(marker)[0]}${marker}\nBundled local video playback runtime. Exact version: package-lock.json. Source: https://github.com/video-dev/hls.js\n\n${license.trim()}\n`;
+if (check && notices !== expected) throw new Error("hls.js license differs");
+if (!check) await writeFile(noticePath, expected);
+console.log("Capture runtimes and license match locked sources");
diff --git a/x-video-capture.js b/x-video-capture.js
new file mode 100644
index 0000000..c678fad
--- /dev/null
+++ b/x-video-capture.js
@@ -0,0 +1,170 @@
+import { PAGE_CAPTURE_LIMITS } from "./resource-limits.js";
+
+// Serialized into the document-start runtime by build:capture-runtime.
+// Observe the selected post's normal responses; never issue API requests.
+export function installXVideoObserver({ timeoutMs, maxBytes, maxMedia }) {
+ const key = "__PROMPTDIRECTOR_X_VIDEO__";
+ const postId = /^\/(?:[^/]+\/status|i\/web\/status)\/(\d+)/u.exec(location.pathname)?.[1];
+ if (!postId || !/(^|\.)(x|twitter)\.com$/u.test(location.hostname) || globalThis[key]) return;
+ const state = { postId, media: [], done: false };
+ globalThis[key] = state;
+ const mediaUrl = (value) => {
+ try {
+ const url = new URL(value);
+ return url.protocol === "https:" && url.hostname === "video.twimg.com" ? url.href : "";
+ } catch { return ""; }
+ };
+ const ingest = (payload) => {
+ if (state.done) return;
+ const pending = [payload];
+ while (pending.length) {
+ const node = pending.pop();
+ if (!node || typeof node !== "object") continue;
+ const legacy = node.legacy || node;
+ if (String(node.rest_id || legacy.id_str || "") === postId && legacy.extended_entities?.media) {
+ const media = legacy.extended_entities.media.filter(item =>
+ !item.source_status_id_str || item.source_status_id_str === postId).flatMap(item => {
+ const variants = (item.video_info?.variants || []).flatMap(variant => {
+ const url = mediaUrl(variant.url);
+ return url && ["video/mp4", "application/x-mpegURL"].includes(variant.content_type)
+ ? [{ url, mimeType: variant.content_type, bitrate: Number(variant.bitrate) || 0 }] : [];
+ });
+ variants.sort((a, b) => Number(b.mimeType === "video/mp4") - Number(a.mimeType === "video/mp4") || b.bitrate - a.bitrate);
+ return variants.length ? [{ id: String(item.id_str || ""), posterUrl: String(item.media_url_https || ""), variants }] : [];
+ }).slice(0, maxMedia);
+ if (media.length) { state.media = media; state.stop(); return; }
+ }
+ // A quote is its own post; matching by ID above prevents reply/quote substitution.
+ pending.push(...Object.values(node).filter(value => value && typeof value === "object"));
+ }
+ };
+ const isResponseUrl = (value) => {
+ try {
+ const url = new URL(value, location.href);
+ return url.origin === location.origin && url.pathname.startsWith("/i/api/");
+ } catch { return false; }
+ };
+ const parse = (text) => {
+ if (!state.done && typeof text === "string" && text.length <= maxBytes) {
+ try { ingest(JSON.parse(text)); } catch { /* Unrelated or non-JSON response. */ }
+ }
+ };
+ const originalFetch = globalThis.fetch;
+ const Xhr = globalThis.XMLHttpRequest;
+ const originalOpen = Xhr?.prototype.open;
+ const originalSend = Xhr?.prototype.send;
+ const requests = new WeakSet();
+ const observedFetch = async function (...args) {
+ const response = await originalFetch.apply(this, args);
+ if (!state.done && response.ok && isResponseUrl(response.url || args[0]?.url || args[0])) {
+ const copy = response.clone();
+ (async () => {
+ const reader = copy.body.getReader();
+ const chunks = []; let bytes = 0;
+ try {
+ while (!state.done) {
+ const part = await reader.read();
+ if (part.done) break;
+ bytes += part.value.byteLength;
+ if (bytes > maxBytes) return;
+ chunks.push(part.value);
+ }
+ if (!state.done) parse(await new Blob(chunks).text());
+ } finally { await reader.cancel().catch(() => undefined); }
+ })().catch(() => undefined);
+ }
+ return response;
+ };
+ const observedOpen = function (method, url, ...rest) {
+ requests.delete(this);
+ if (isResponseUrl(url)) requests.add(this);
+ return originalOpen.call(this, method, url, ...rest);
+ };
+ const observedSend = function (...args) {
+ if (requests.has(this)) this.addEventListener("loadend", () => {
+ if (state.done || this.status < 200 || this.status >= 300) return;
+ try {
+ if (this.responseType === "json") parse(JSON.stringify(this.response));
+ else if (!this.responseType || this.responseType === "text") parse(this.responseText);
+ } catch { /* Page response type changed. */ }
+ }, { once: true });
+ return originalSend.apply(this, args);
+ };
+ let timer;
+ state.stop = () => {
+ state.done = true;
+ clearTimeout(timer);
+ if (globalThis.fetch === observedFetch) globalThis.fetch = originalFetch;
+ if (Xhr?.prototype.open === observedOpen) Xhr.prototype.open = originalOpen;
+ if (Xhr?.prototype.send === observedSend) Xhr.prototype.send = originalSend;
+ };
+ if (originalFetch) globalThis.fetch = observedFetch;
+ if (Xhr) { Xhr.prototype.open = observedOpen; Xhr.prototype.send = observedSend; }
+ timer = setTimeout(state.stop, timeoutMs);
+}
+
+export function applyXVideoSources(snapshot, result) {
+ if (!result?.media?.length) return snapshot;
+ return { ...snapshot, candidates: (snapshot.candidates || []).map(candidate => {
+ if (xPostId(candidate.canonicalUrl) !== result.postId) return candidate;
+ const videos = candidate.media.filter(item => item.kind === "video" && !item.isQuoted);
+ return { ...candidate, media: candidate.media.map(item => {
+ if (!videos.includes(item)) return item;
+ const source = result.media.find(value => value.posterUrl && value.posterUrl === item.posterUrl)
+ || (videos.length === 1 && result.media.length === 1 ? result.media[0] : null);
+ if (!source) return item;
+ const best = source.variants[0];
+ return { ...item, url: best.url, variants: [], mimeType: best.mimeType,
+ sourceKind: "site-original", originalWorkUrl: candidate.canonicalUrl,
+ ...(source.variants.find(value => value.mimeType === "application/x-mpegURL")
+ ? { streamUrl: source.variants.find(value => value.mimeType === "application/x-mpegURL").url } : {}) };
+ }) };
+ }) };
+}
+
+function xPostId(value) {
+ try {
+ const url = new URL(value);
+ return /(^|\.)(x|twitter)\.com$/u.test(url.hostname)
+ ? /^\/(?:[^/]+\/status|i\/web\/status)\/(\d+)/u.exec(url.pathname)?.[1] || "" : "";
+ } catch { return ""; }
+}
+
+export async function resolveXVideoSources(snapshot, tab, api, { cancelled = () => false } = {}) {
+ const postId = xPostId(tab.url);
+ const unresolved = (snapshot.candidates || []).some(candidate => xPostId(candidate.canonicalUrl) === postId
+ && candidate.media?.some(item => item.kind === "video" && !item.isQuoted && !/\.mp4(?:\?|$)/iu.test(item.url || "")));
+ if (!postId || !unresolved || cancelled()) return snapshot;
+ const id = `capture-x-video-${tab.id}`;
+ let registered = false;
+ try {
+ await api.scripting.unregisterContentScripts({ ids: [id] }).catch(() => undefined);
+ const url = new URL(tab.url);
+ await api.scripting.registerContentScripts([{ id, matches: [`${url.origin}${url.pathname}*`],
+ js: ["x-video-observer.js"], world: "MAIN", runAt: "document_start", persistAcrossSessions: false }]);
+ registered = true;
+ await api.tabs.reload(tab.id);
+ const deadline = Date.now() + PAGE_CAPTURE_LIMITS.navigationTimeoutMs;
+ while (Date.now() < deadline && !cancelled()) {
+ const current = await api.tabs.get(tab.id);
+ if (xPostId(current.url) !== postId) break;
+ const results = await api.scripting.executeScript({ target: { tabId: tab.id }, world: "MAIN",
+ func: () => {
+ const state = globalThis.__PROMPTDIRECTOR_X_VIDEO__;
+ return state ? { postId: state.postId, media: state.media, done: state.done } : null;
+ } }).catch(() => []);
+ const state = results[0]?.result;
+ if (state?.media?.length) return applyXVideoSources(snapshot, state);
+ if (state?.done) break;
+ await new Promise(resolve => setTimeout(resolve, 250));
+ }
+ } catch (error) {
+ console.warn("[capture-video] Selected post video source unavailable:", error?.name || "Error");
+ } finally {
+ if (registered) await api.scripting.unregisterContentScripts({ ids: [id] }).catch(() => undefined);
+ await api.scripting.executeScript({ target: { tabId: tab.id }, world: "MAIN",
+ func: () => { globalThis.__PROMPTDIRECTOR_X_VIDEO__?.stop?.(); delete globalThis.__PROMPTDIRECTOR_X_VIDEO__; }
+ }).catch(() => undefined);
+ }
+ return snapshot;
+}
diff --git a/x-video-observer.js b/x-video-observer.js
new file mode 100644
index 0000000..c292f6f
--- /dev/null
+++ b/x-video-observer.js
@@ -0,0 +1,101 @@
+// Generated by build:capture-runtime from x-video-capture.js and resource-limits.js.
+(function installXVideoObserver({ timeoutMs, maxBytes, maxMedia }) {
+ const key = "__PROMPTDIRECTOR_X_VIDEO__";
+ const postId = /^\/(?:[^/]+\/status|i\/web\/status)\/(\d+)/u.exec(location.pathname)?.[1];
+ if (!postId || !/(^|\.)(x|twitter)\.com$/u.test(location.hostname) || globalThis[key]) return;
+ const state = { postId, media: [], done: false };
+ globalThis[key] = state;
+ const mediaUrl = (value) => {
+ try {
+ const url = new URL(value);
+ return url.protocol === "https:" && url.hostname === "video.twimg.com" ? url.href : "";
+ } catch { return ""; }
+ };
+ const ingest = (payload) => {
+ if (state.done) return;
+ const pending = [payload];
+ while (pending.length) {
+ const node = pending.pop();
+ if (!node || typeof node !== "object") continue;
+ const legacy = node.legacy || node;
+ if (String(node.rest_id || legacy.id_str || "") === postId && legacy.extended_entities?.media) {
+ const media = legacy.extended_entities.media.filter(item =>
+ !item.source_status_id_str || item.source_status_id_str === postId).flatMap(item => {
+ const variants = (item.video_info?.variants || []).flatMap(variant => {
+ const url = mediaUrl(variant.url);
+ return url && ["video/mp4", "application/x-mpegURL"].includes(variant.content_type)
+ ? [{ url, mimeType: variant.content_type, bitrate: Number(variant.bitrate) || 0 }] : [];
+ });
+ variants.sort((a, b) => Number(b.mimeType === "video/mp4") - Number(a.mimeType === "video/mp4") || b.bitrate - a.bitrate);
+ return variants.length ? [{ id: String(item.id_str || ""), posterUrl: String(item.media_url_https || ""), variants }] : [];
+ }).slice(0, maxMedia);
+ if (media.length) { state.media = media; state.stop(); return; }
+ }
+ // A quote is its own post; matching by ID above prevents reply/quote substitution.
+ pending.push(...Object.values(node).filter(value => value && typeof value === "object"));
+ }
+ };
+ const isResponseUrl = (value) => {
+ try {
+ const url = new URL(value, location.href);
+ return url.origin === location.origin && url.pathname.startsWith("/i/api/");
+ } catch { return false; }
+ };
+ const parse = (text) => {
+ if (!state.done && typeof text === "string" && text.length <= maxBytes) {
+ try { ingest(JSON.parse(text)); } catch { /* Unrelated or non-JSON response. */ }
+ }
+ };
+ const originalFetch = globalThis.fetch;
+ const Xhr = globalThis.XMLHttpRequest;
+ const originalOpen = Xhr?.prototype.open;
+ const originalSend = Xhr?.prototype.send;
+ const requests = new WeakSet();
+ const observedFetch = async function (...args) {
+ const response = await originalFetch.apply(this, args);
+ if (!state.done && response.ok && isResponseUrl(response.url || args[0]?.url || args[0])) {
+ const copy = response.clone();
+ (async () => {
+ const reader = copy.body.getReader();
+ const chunks = []; let bytes = 0;
+ try {
+ while (!state.done) {
+ const part = await reader.read();
+ if (part.done) break;
+ bytes += part.value.byteLength;
+ if (bytes > maxBytes) return;
+ chunks.push(part.value);
+ }
+ if (!state.done) parse(await new Blob(chunks).text());
+ } finally { await reader.cancel().catch(() => undefined); }
+ })().catch(() => undefined);
+ }
+ return response;
+ };
+ const observedOpen = function (method, url, ...rest) {
+ requests.delete(this);
+ if (isResponseUrl(url)) requests.add(this);
+ return originalOpen.call(this, method, url, ...rest);
+ };
+ const observedSend = function (...args) {
+ if (requests.has(this)) this.addEventListener("loadend", () => {
+ if (state.done || this.status < 200 || this.status >= 300) return;
+ try {
+ if (this.responseType === "json") parse(JSON.stringify(this.response));
+ else if (!this.responseType || this.responseType === "text") parse(this.responseText);
+ } catch { /* Page response type changed. */ }
+ }, { once: true });
+ return originalSend.apply(this, args);
+ };
+ let timer;
+ state.stop = () => {
+ state.done = true;
+ clearTimeout(timer);
+ if (globalThis.fetch === observedFetch) globalThis.fetch = originalFetch;
+ if (Xhr?.prototype.open === observedOpen) Xhr.prototype.open = originalOpen;
+ if (Xhr?.prototype.send === observedSend) Xhr.prototype.send = originalSend;
+ };
+ if (originalFetch) globalThis.fetch = observedFetch;
+ if (Xhr) { Xhr.prototype.open = observedOpen; Xhr.prototype.send = observedSend; }
+ timer = setTimeout(state.stop, timeoutMs);
+})({"timeoutMs":30000,"maxBytes":16777216,"maxMedia":24});