Skip to content

The only downloader you need. 下载器的集大成者。

fix(extension): 修复部分 DASH 视频匹配错音视频轨道的问题 #1070

XiaoYouChRbfd4c3fa3f77
diff --git a/browser_extension/app/src/background/resource-bridge.ts b/browser_extension/app/src/background/resource-bridge.ts
index 5354f957..610e51d4 100644
--- a/browser_extension/app/src/background/resource-bridge.ts
+++ b/browser_extension/app/src/background/resource-bridge.ts
@@ -623,14 +623,13 @@ export function createResourceBridge(options: {
if (resources.length !== 2) {
return { ok: false, message: chrome.i18n.getMessage("errorMergeRequiresTwoResources") };
}
- const ordered = sortResourcesForOnlineMerge(resources);
try {
const result = await options.sendDesktopRequest<CommandResult>({
type: "create_task",
source: "resource_merge",
- title: mergeOutputTitle(ordered),
+ title: mergeOutputTitle(resources),
payload: {
- resources: ordered.map((resource) => ({
+ resources: resources.map((resource) => ({
url: resource.url,
filename: taskNameForResource(resource),
mime: resource.mime,
@@ -642,7 +641,7 @@ export function createResourceBridge(options: {
},
});
if (result.ok) {
- ordered.forEach((resource) => cache.setSent(resource.id));
+ resources.forEach((resource) => cache.setSent(resource.id));
return { ...result, message: result.message || chrome.i18n.getMessage("mergeTaskSentToDesktop") };
}
return result;
@@ -661,7 +660,7 @@ export function createResourceBridge(options: {
return { ok: false, message: chrome.i18n.getMessage("errorResourcesNotMergeable") };
}
- return sendMergeResources(resources);
+ return sendMergeResources(sortResourcesForOnlineMerge(resources));
}
function buildPopupStateData(resolvedTabId: number | null, activeTab: chrome.tabs.Tab | null) {
diff --git a/browser_extension/app/src/page-media/attribution/attribution.ts b/browser_extension/app/src/page-media/attribution/attribution.ts
index 7319dd0f..16d9caf6 100644
--- a/browser_extension/app/src/page-media/attribution/attribution.ts
+++ b/browser_extension/app/src/page-media/attribution/attribution.ts
@@ -97,6 +97,8 @@ class MediaAttribution {
private readonly sessionsById = new Map<string, VideoSession>();
private readonly sessionByMediaSourceId = new Map<string, VideoSession>();
private readonly mediaSourceIdByObjectUrl = new Map<string, string>();
+ private readonly mimeTypesByMediaSourceId = new Map<string, Set<string>>();
+ private readonly sourceUrlsByMediaSourceId = new Map<string, Map<string, string[]>>();
private readonly selectionListenerByElement = new WeakMap<HTMLMediaElement, ResolveStateListener>();
private readonly ledger = new AttributionLedger();
private mutationObserver: MutationObserver | null = null;
@@ -225,6 +227,8 @@ class MediaAttribution {
this.sessionsById.delete(previous.id);
for (const mediaSourceId of previous.mediaSourceIds) {
this.sessionByMediaSourceId.delete(mediaSourceId);
+ this.mimeTypesByMediaSourceId.delete(mediaSourceId);
+ this.sourceUrlsByMediaSourceId.delete(mediaSourceId);
}
if (this.lastBoundSession?.id === previous.id) {
this.lastBoundSession = null;
@@ -292,6 +296,15 @@ class MediaAttribution {
}
// Pins re-fetches (rebuffering) to this session even after lastBoundSession changes.
this.ledger.lockAllFor(session.id);
+
+ const cachedMimes = this.mimeTypesByMediaSourceId.get(mediaSourceId);
+ if (cachedMimes) {
+ for (const mimeType of cachedMimes) { this.addTrackMime(session, mimeType); }
+ }
+ const cachedSources = this.sourceUrlsByMediaSourceId.get(mediaSourceId);
+ if (cachedSources) {
+ for (const [mimeType, urls] of cachedSources) { this.setTrackSourceUrls(session, mimeType, urls); }
+ }
}
// capturedAt is reset so newSession's post-bind filter sees the URL as fresh.
@@ -359,6 +372,10 @@ class MediaAttribution {
const owner = this.sessionsById.get(ledgerEntry.sessionId);
const meta = owner?.attributedUrls.get(entry.url);
if (owner && meta && this.upgradeTrackMime(meta, sourceBufferMime)) { this.emitSessionMetadata(owner); }
+ if (ledgerEntry.sessionId === session.id && (!meta?.contentType.includes("codecs") || meta.contentType === sourceBufferMime)) {
+ this.recentFetches.splice(i, 1);
+ return;
+ }
continue;
}
if (entry.idHints.size > 0 && session.idHints.size > 0) {
@@ -397,6 +414,43 @@ class MediaAttribution {
return true;
}
+ private addTrackMime(session: VideoSession, mimeType: string): void {
+ if (session.mimeTypes.has(mimeType)) { return; }
+ session.mimeTypes.add(mimeType);
+ console.log(`${LOG_PREFIX} ${session.id} mime +=`, mimeType);
+ const formKind = toFormKind(session.mimeTypes);
+ if (formKind !== session.formKind) {
+ session.formKind = formKind;
+ console.log(`${LOG_PREFIX} ${session.id} formKind = ${formKind}`);
+ this.notifyResolveListener(session, session.state, "formKind-changed");
+ }
+ }
+
+ private setTrackSourceUrls(session: VideoSession, mimeType: string, urls: string[]): void {
+ session.sourceUrlsByMime.set(mimeType, urls);
+ if (urls.length === 1) {
+ const url = urls[0];
+ const now = performance.now();
+ const claim = this.ledger.claim(url, session.id, "mse", now, true);
+ if (claim.moved || claim.ownerId === session.id) {
+ if (!session.attributedUrls.has(url)) {
+ this.handoffUrl(url, session, mimeType);
+ this.emitSessionMetadata(session);
+ } else {
+ const meta = session.attributedUrls.get(url);
+ if (meta) {
+ meta.capturedAt = now;
+ meta.lockedByMse = true;
+ if (this.upgradeTrackMime(meta, mimeType)) { this.emitSessionMetadata(session); }
+ }
+ for (const d of urlIdHints(url)) { session.idHints.add(d); }
+ }
+ }
+ }
+ console.log(`${LOG_PREFIX} ${session.id} samples come from`, mimeType, urls);
+ this.notifyResolveListener(session, session.state, "source-matched");
+ }
+
// Track mimes can land after loadedmetadata; resend so Resources learn each URL's track role.
private emitSessionMetadata(session: VideoSession): void {
const element = session.elementRef.deref();
@@ -422,17 +476,11 @@ class MediaAttribution {
}
case "mse_source_buffer_added": {
+ let mimes = this.mimeTypesByMediaSourceId.get(signal.mediaSourceId);
+ if (!mimes) { mimes = new Set(); this.mimeTypesByMediaSourceId.set(signal.mediaSourceId, mimes); }
+ mimes.add(signal.mimeType);
const session = this.sessionByMediaSourceId.get(signal.mediaSourceId);
- if (!session) { return; }
- if (session.mimeTypes.has(signal.mimeType)) { return; }
- session.mimeTypes.add(signal.mimeType);
- console.log(`${LOG_PREFIX} ${session.id} mime += ${signal.mimeType}`);
- const formKind = toFormKind(session.mimeTypes);
- if (formKind !== session.formKind) {
- session.formKind = formKind;
- console.log(`${LOG_PREFIX} ${session.id} formKind = ${formKind}`);
- this.notifyResolveListener(session, session.state, "formKind-changed");
- }
+ if (session) { this.addTrackMime(session, signal.mimeType); }
return;
}
@@ -441,11 +489,11 @@ class MediaAttribution {
return;
case "mse_buffer_matched": {
+ let sources = this.sourceUrlsByMediaSourceId.get(signal.mediaSourceId);
+ if (!sources) { sources = new Map(); this.sourceUrlsByMediaSourceId.set(signal.mediaSourceId, sources); }
+ sources.set(signal.mimeType, signal.urls);
const session = this.sessionByMediaSourceId.get(signal.mediaSourceId);
- if (!session) { return; }
- session.sourceUrlsByMime.set(signal.mimeType, signal.urls);
- console.log(`${LOG_PREFIX} ${session.id} samples come from`, signal.mimeType, signal.urls);
- this.notifyResolveListener(session, session.state, "source-matched");
+ if (session) { this.setTrackSourceUrls(session, signal.mimeType, signal.urls); }
return;
}
@@ -487,6 +535,10 @@ class MediaAttribution {
private onResourceTimingEntries = (list: PerformanceObserverEntryList): void => {
for (const entry of list.getEntries() as PerformanceResourceTiming[]) {
+ // Main-thread fetch and XHR are already observed with true HTTP status by mse-probe.ts;
+ // skipping them here keeps cross-origin 403s (whose responseStatus is 0 without CORS) out.
+ if (entry.initiatorType === "fetch" || entry.initiatorType === "xmlhttprequest") { continue; }
+ if (entry.responseStatus >= 400) { continue; }
this.attributeFetch(entry.name, "");
}
};
@@ -570,7 +622,8 @@ class MediaAttribution {
private isMediaUrl(url: string, contentType: string): boolean {
if (!/^https?:/i.test(url)) { return false; }
const extension = fileExtension(filenameFromUrl(url));
- return isCatCatchMedia(extension, contentType);
+ const mime = contentType.split(";")[0]?.trim().toLowerCase() ?? "";
+ return isCatCatchMedia(extension, mime);
}
private transition(session: VideoSession, next: VideoSessionState, reason: string): void {
diff --git a/browser_extension/app/src/page-media/attribution/mp4.ts b/browser_extension/app/src/page-media/attribution/mp4.ts
index c4ba4e29..c7199c0f 100644
--- a/browser_extension/app/src/page-media/attribution/mp4.ts
+++ b/browser_extension/app/src/page-media/attribution/mp4.ts
@@ -1,5 +1,7 @@
// Past this, the moov sits at the file's end (non-faststart) and the duration stays unknown.
export const MP4_HEAD_LIMIT = 256 * 1024;
+const MIN_TRUNCATED_MDAT_BYTES = 4096;
+const SEGMENT_BOX_TYPES = new Set(["ftyp", "styp", "sidx", "moov", "moof", "mdat", "emsg", "prft", "free", "skip", "pdin"]);
type Box = { type: string; start: number; end: number };
@@ -30,6 +32,22 @@ export function isMp4Head(bytes: Uint8Array): boolean {
return bytes.length >= 8 && bytes[4] === 0x66 && bytes[5] === 0x74 && bytes[6] === 0x79 && bytes[7] === 0x70;
}
+export function isMp4Segment(bytes: Uint8Array): boolean {
+ if (bytes.length < 8) { return false; }
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const size = view.getUint32(0);
+ if (size !== 0 && size !== 1 && size < 8) { return false; }
+ if (size === 1 && bytes.length >= 16 && Number(view.getBigUint64(8)) < 16) { return false; }
+ const type = String.fromCharCode(bytes[4], bytes[5], bytes[6], bytes[7]);
+ return SEGMENT_BOX_TYPES.has(type);
+}
+
+export function hasMdat(bytes: Uint8Array): boolean {
+ if (!isMp4Segment(bytes)) { return false; }
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ return parseBoxes(view, 0, view.byteLength).some((box) => box.type === "mdat" && box.end > box.start);
+}
+
// Seconds from mvhd, or mehd for fragmented files whose mvhd leaves the duration at 0.
export function parseMp4Duration(bytes: Uint8Array): number | undefined {
if (!isMp4Head(bytes)) { return undefined; }
@@ -61,6 +79,9 @@ export function isInitSegment(bytes: Uint8Array): boolean {
export function parseMdatTail(bytes: Uint8Array, length: number): Uint8Array | undefined {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const mdat = parseBoxes(view, 0, view.byteLength).find((box) => box.type === "mdat");
- if (!mdat || mdat.end > bytes.length || mdat.end - mdat.start < length) { return undefined; }
- return bytes.subarray(mdat.end - length, mdat.end);
+ if (!mdat) { return undefined; }
+ const end = Math.min(mdat.end, bytes.length, MP4_HEAD_LIMIT);
+ const minSpan = end < mdat.end ? Math.max(length, MIN_TRUNCATED_MDAT_BYTES) : length;
+ if (end - mdat.start < minSpan) { return undefined; }
+ return bytes.subarray(end - length, end);
}
diff --git a/browser_extension/app/src/page-media/attribution/mse-probe.ts b/browser_extension/app/src/page-media/attribution/mse-probe.ts
index d6260d38..c07c1cc2 100644
--- a/browser_extension/app/src/page-media/attribution/mse-probe.ts
+++ b/browser_extension/app/src/page-media/attribution/mse-probe.ts
@@ -5,7 +5,9 @@
* capturing buffers. Built as a standalone IIFE bundle (see scripts/build.mjs).
*/
import {postMediaSignal} from "./attribution-signal";
-import {isInitSegment, isMp4Head, MP4_HEAD_LIMIT, parseMdatTail, parseMp4Duration} from "./mp4";
+import {hasMdat, isInitSegment, isMp4Head, isMp4Segment, MP4_HEAD_LIMIT, parseMdatTail, parseMp4Duration} from "./mp4";
+import {isCatCatchMedia} from "../../shared/cat-catch";
+import {fileExtension, filenameFromUrl, mimeFromUrl} from "../../shared/utils";
declare global {
interface Window {
@@ -13,11 +15,12 @@ declare global {
}
}
-type GhostXMLHttpRequest = XMLHttpRequest & { __gdUrl?: string };
-type Head = { url: string; bytes: Uint8Array };
+type GhostXMLHttpRequest = XMLHttpRequest & { __gdUrl?: string; __gdDone?: boolean };
+type Head = { url: string; bytes: Uint8Array; hasMoov: boolean };
const MDAT_TAIL_LENGTH = 32;
const HEADS_CAP = 16;
+const PER_URL_HEADS_CAP = 2;
(function installGhostDownloaderMseAttribution() {
if (window.__gdMseAttributionInstalled) { return; }
@@ -29,13 +32,39 @@ const HEADS_CAP = 16;
// Remuxing players (TikTok) copy sample bytes verbatim, so the MP4 heads they fetched name where appended samples came from.
const recentHeads: Head[] = [];
- function addHead(url: string, bytes: Uint8Array): Head {
- const head = { url, bytes };
+ function addHead(url: string, bytes: Uint8Array, hasMoov: boolean): Head {
+ let sameUrlCount = 0;
+ let oldestSameUrlIndex = -1;
+ for (let i = 0; i < recentHeads.length; i += 1) {
+ if (recentHeads[i].url === url) {
+ sameUrlCount += 1;
+ if (oldestSameUrlIndex < 0) { oldestSameUrlIndex = i; }
+ }
+ }
+ if (sameUrlCount >= PER_URL_HEADS_CAP && oldestSameUrlIndex >= 0) {
+ recentHeads.splice(oldestSameUrlIndex, 1);
+ }
+ const head = { url, bytes, hasMoov };
recentHeads.push(head);
if (recentHeads.length > HEADS_CAP) { recentHeads.shift(); }
return head;
}
+ function isMediaRequest(url: string, contentType: string): boolean {
+ if (!/^https?:/i.test(url)) { return false; }
+ const mime = contentType.split(";")[0]?.trim().toLowerCase() || mimeFromUrl(url);
+ return isCatCatchMedia(fileExtension(filenameFromUrl(url)), mime);
+ }
+
+ function hasRangeParam(url: string): boolean {
+ try {
+ const parsed = new URL(url);
+ return parsed.searchParams.has("bytestart") || parsed.searchParams.has("byteend");
+ } catch {
+ return false;
+ }
+ }
+
// Repeated silent AAC frames are byte-identical across unrelated videos.
function isDistinctive(tail: Uint8Array): boolean {
return new Set(tail).size >= MDAT_TAIL_LENGTH / 2;
@@ -50,11 +79,6 @@ const HEADS_CAP = 16;
return false;
}
- // Every holder, not the newest: videos sharing a sound carry identical audio bytes.
- function sourceUrlsOf(tail: Uint8Array): string[] {
- return [...new Set(recentHeads.filter((head) => hasBytes(head.bytes, tail)).map((head) => head.url))];
- }
-
// Hook each MediaSource instance, never MediaSource.prototype: CCTV's player stops
// decrypting video when its prototype methods are not native.
if (typeof window.URL?.createObjectURL === "function" && typeof window.MediaSource !== "undefined") {
@@ -76,26 +100,36 @@ const HEADS_CAP = 16;
try {
const originalAppendBuffer = sourceBuffer.appendBuffer;
let sourceUrls: string[] = [];
+ let isProgressiveLocked = false;
sourceBuffer.appendBuffer = function patchedAppendBuffer(this: SourceBuffer, data: BufferSource): void {
- postMediaSignal({ kind: "mse_buffer_appended", mediaSourceId: id, mimeType });
try {
const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
if (isInitSegment(bytes)) {
// An init segment starts the next video in a reused SourceBuffer, so the old match must not outlive it.
if (sourceUrls.length > 0) { postMediaSignal({ kind: "mse_buffer_matched", mediaSourceId: id, mimeType, urls: [] }); }
sourceUrls = [];
+ isProgressiveLocked = false;
}
- const tail = parseMdatTail(bytes, MDAT_TAIL_LENGTH);
- if (tail && isDistinctive(tail) && sourceUrls.length !== 1) {
- const found = sourceUrlsOf(tail);
- // Each later segment can only narrow the holders down.
- const narrowed = sourceUrls.length === 0 ? found : sourceUrls.filter((url) => found.includes(url));
- if (narrowed.length > 0 && narrowed.length !== sourceUrls.length) {
- sourceUrls = narrowed;
- postMediaSignal({ kind: "mse_buffer_matched", mediaSourceId: id, mimeType, urls: sourceUrls });
+ const tail = !isProgressiveLocked ? parseMdatTail(bytes, MDAT_TAIL_LENGTH) : undefined;
+ if (tail && isDistinctive(tail)) {
+ const matches = recentHeads.filter((head) => hasBytes(head.bytes, tail));
+ const found = [...new Set(matches.map((head) => head.url))];
+ if (found.length > 0) {
+ const narrowed = sourceUrls.length === 0 ? found : sourceUrls.filter((url) => found.includes(url));
+ // Progressive MP4s stay strictly narrowing-only so TikTok shared-sound reels cannot flip;
+ // range-sliced DASH segments switch when CDN failover or ABR moves to another URL.
+ const next = narrowed.length > 0 ? narrowed : (matches.every((head) => !head.hasMoov) ? found : []);
+ if (next.length > 0 && (next.length !== sourceUrls.length || next.some((u, i) => u !== sourceUrls[i]))) {
+ sourceUrls = next;
+ isProgressiveLocked = next.length === 1 && matches.some((head) => head.url === next[0] && head.hasMoov);
+ postMediaSignal({ kind: "mse_buffer_matched", mediaSourceId: id, mimeType, urls: sourceUrls });
+ }
}
}
} catch { /* Detached buffer. */ }
+ if (sourceUrls.length !== 1) {
+ postMediaSignal({ kind: "mse_buffer_appended", mediaSourceId: id, mimeType });
+ }
return originalAppendBuffer.call(this, data);
};
} catch {
@@ -122,28 +156,44 @@ const HEADS_CAP = 16;
// An MP4's moov duration tells this file's video apart from a prefetched sibling's.
async function probeContent(response: Response, url: string): Promise<void> {
+ if (!/^https?:/i.test(url)) { return; }
const contentLength = parseInt(response.headers.get("content-length") || "", 10);
const contentType = response.headers.get("content-type") || "";
+ if (/^(application\/(json|ld\+json|javascript|x-javascript|wasm|x-www-form-urlencoded|grpc)|text\/(html|css|javascript|event-stream)|image\/|font\/)/i.test(contentType)) { return; }
if (contentLength > 2_000_000 && !/^(video|audio)\/|octet-stream/i.test(contentType)) { return; }
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
try {
reader = response.clone().body?.getReader();
} catch { return; /* Opaque response — clone() throws. */ }
if (!reader) { return; }
+ const isRangeSlice = response.status === 206 || hasRangeParam(url);
const chunks: Uint8Array[] = [];
let size = 0;
let mp4Head: Head | undefined;
- while (size < MP4_HEAD_LIMIT) {
- const { done, value } = await reader.read();
- if (done || !value) { break; }
- chunks.push(value);
- size += value.length;
- // One chunk settles an m3u8; an MP4 is read on for the first samples sourceUrlsOf looks for.
- if (!isMp4Head(chunks[0])) { break; }
- // Grown chunk by chunk: the player appends its first segments before the head is complete.
- if (mp4Head) { mp4Head.bytes = toBytes(chunks); } else { mp4Head = addHead(url, toBytes(chunks)); }
+ try {
+ while (size < MP4_HEAD_LIMIT) {
+ const { done, value } = await reader.read();
+ if (done || !value) { break; }
+ chunks.push(value);
+ size += value.length;
+ const current = toBytes(chunks);
+ if (current.length < 8) { continue; }
+ // One chunk settles an m3u8; MP4 heads and range segments stay open up to MP4_HEAD_LIMIT for sample matching.
+ if (!isMp4Head(current) && !(isRangeSlice && isMp4Segment(current))) { break; }
+ // Grown chunk by chunk: the player may append first segments before the head finishes arriving.
+ if (hasMdat(current)) {
+ const hasMoov = isInitSegment(current);
+ if (mp4Head) {
+ mp4Head.bytes = current;
+ mp4Head.hasMoov = hasMoov;
+ } else {
+ mp4Head = addHead(url, current, hasMoov);
+ }
+ }
+ }
+ } finally {
+ reader.cancel().catch(() => {});
}
- reader.cancel().catch(() => {});
const head = mp4Head?.bytes ?? toBytes(chunks);
const duration = parseMp4Duration(head);
if (duration !== undefined) {
@@ -171,12 +221,16 @@ const HEADS_CAP = 16;
const promise = originalFetch(input, init);
promise.then((response) => {
try {
- const resolvedUrl = response?.url || url;
- postMediaSignal({
- kind: "request_completed",
- url: resolvedUrl,
- contentType: response?.headers?.get?.("content-type") ?? "",
- });
+ if (!response || !response.ok) { return; }
+ const resolvedUrl = response.url || url;
+ const contentType = response.headers?.get?.("content-type") ?? "";
+ if (isMediaRequest(resolvedUrl, contentType)) {
+ postMediaSignal({
+ kind: "request_completed",
+ url: resolvedUrl,
+ contentType,
+ });
+ }
probeContent(response, resolvedUrl).catch(() => {});
} catch {
// Opaque response.
@@ -187,44 +241,58 @@ const HEADS_CAP = 16;
}
try {
+ const hookedXhrs = new WeakSet<XMLHttpRequest>();
const originalOpen = XMLHttpRequest.prototype.open;
- const originalSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open = function patchedOpen(this: GhostXMLHttpRequest, method: string, url: string | URL, ...rest: unknown[]): void {
this.__gdUrl = String(url);
- return (originalOpen as (...args: unknown[]) => void).apply(this, [method, url, ...rest]);
- };
- XMLHttpRequest.prototype.send = function patchedSend(this: GhostXMLHttpRequest, body?: Document | XMLHttpRequestBodyInit | null): void {
- const xhr = this;
- xhr.addEventListener("loadend", () => {
- const resolvedUrl = xhr.responseURL || xhr.__gdUrl || "";
- try {
- postMediaSignal({
- kind: "request_completed",
- url: resolvedUrl,
- contentType: xhr.getResponseHeader?.("content-type") ?? "",
- });
- } catch {
- // Opaque response.
- }
- try {
- if ((xhr.responseType === "" || xhr.responseType === "text") && xhr.responseText?.startsWith("#EXTM3U")) {
- postMediaSignal({
- kind: "stream_detected",
- url: resolvedUrl,
- isMaster: xhr.responseText.includes("#EXT-X-STREAM-INF"),
- });
- }
- } catch { /* responseText throws on non-text responseType. */ }
- try {
- if (xhr.responseType === "arraybuffer" && xhr.response instanceof ArrayBuffer && isMp4Head(new Uint8Array(xhr.response).subarray(0, 8))) {
- const head = new Uint8Array(xhr.response.slice(0, MP4_HEAD_LIMIT));
- addHead(resolvedUrl, head);
- const duration = parseMp4Duration(head);
- if (duration !== undefined) { postMediaSignal({ kind: "media_duration", url: resolvedUrl, duration }); }
+ this.__gdDone = false;
+ if (!hookedXhrs.has(this)) {
+ hookedXhrs.add(this);
+ const xhr = this;
+ // Fire on readystatechange DONE (before load / loadend) so recentHeads and request_completed
+ // land before players appendBuffer synchronously inside onload.
+ xhr.addEventListener("readystatechange", () => {
+ if (xhr.readyState !== 4 || xhr.__gdDone) { return; }
+ xhr.__gdDone = true;
+ if (xhr.status < 200 || xhr.status >= 300) { return; }
+ const resolvedUrl = xhr.responseURL || xhr.__gdUrl || "";
+ let contentType = "";
+ try {
+ contentType = xhr.getResponseHeader?.("content-type") ?? "";
+ if (isMediaRequest(resolvedUrl, contentType)) {
+ postMediaSignal({
+ kind: "request_completed",
+ url: resolvedUrl,
+ contentType,
+ });
+ }
+ } catch {
+ // Opaque response.
}
- } catch { /* Detached buffer — the player transferred it to a worker. */ }
- });
- return originalSend.call(this, body);
+ try {
+ if ((xhr.responseType === "" || xhr.responseType === "text") && xhr.responseText?.startsWith("#EXTM3U")) {
+ postMediaSignal({
+ kind: "stream_detected",
+ url: resolvedUrl,
+ isMaster: xhr.responseText.includes("#EXT-X-STREAM-INF"),
+ });
+ }
+ } catch { /* responseText throws on non-text responseType. */ }
+ try {
+ if (xhr.responseType === "arraybuffer" && xhr.response instanceof ArrayBuffer) {
+ const preview = new Uint8Array(xhr.response, 0, Math.min(xhr.response.byteLength, 16));
+ const isRangeSlice = xhr.status === 206 || hasRangeParam(resolvedUrl);
+ if (isMp4Head(preview) || (isRangeSlice && isMp4Segment(preview))) {
+ const head = new Uint8Array(xhr.response.slice(0, MP4_HEAD_LIMIT));
+ if (hasMdat(head)) { addHead(resolvedUrl, head, isInitSegment(head)); }
+ const duration = parseMp4Duration(head);
+ if (duration !== undefined) { postMediaSignal({ kind: "media_duration", url: resolvedUrl, duration }); }
+ }
+ }
+ } catch { /* Detached buffer — the player transferred it to a worker. */ }
+ });
+ }
+ return (originalOpen as (...args: unknown[]) => void).apply(this, [method, url, ...rest]);
};
} catch {
// Frozen XHR prototype on some players.