Skip to content

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

fix(Browser Extension): 抖音下载的内容和正在播放的视频不一致 (#974)

XiaoYouChRb097a9e8fd96
diff --git a/browser_extension/GLOSSARY.md b/browser_extension/GLOSSARY.md
index b1bad871..1ce6d72d 100644
--- a/browser_extension/GLOSSARY.md
+++ b/browser_extension/GLOSSARY.md
@@ -89,6 +89,17 @@ _Avoid_: video tracker、media session
归因置信度分级。决定 URL 归属的优先级——从最高置信(缓冲追加确认)
到最低(唯一 session 兜底)。高 tier 可以从低 tier 夺取 URL 所有权。
+**MSE Lock**:
+URL 的归属已由 MSE 证据确认(典型证据:字节进入了该视频的 SourceBuffer)。
+锁定后归属不再转移。
+_Avoid_: confirmed、bound
+
+**Clicked Video Match**:
+判断一个 URL 是否装着用户点击的那个视频:same / other / unknown。
+证据是精确的——页面上的视频 id 与 URL 里的视频 id 相同,或文件时长与该 video 元素的时长相差不超过一帧;时长相差超过一秒才判为 other。
+解析时 Clicked Video Match 优先于 MSE Lock,MSE Lock 优先于捕获时间。
+_Avoid_: page video
+
**Attribution Ledger**:
跨 session 的 URL 所有权账本。仲裁多个 Video Session 争抢同一 URL 的情况
(如预加载场景中多个视频共享相同的 CDN URL)。
@@ -98,7 +109,7 @@ _Avoid_: video tracker、media session
获取 Resolution 后发送到 Resource Bridge 转发给桌面。
**Resolution Strategy**:
-按站点分发的下载解析逻辑(YouTube、X、Douyin、Instagram、generic)。
+按站点分发的下载解析逻辑(YouTube、Instagram/Facebook、generic)。
纯函数,不能回调 Attribution Engine。输出 Resolution。
**Resolution**:
diff --git a/browser_extension/app/public/_locales/en/messages.json b/browser_extension/app/public/_locales/en/messages.json
index fe7950ee..dc24d230 100644
--- a/browser_extension/app/public/_locales/en/messages.json
+++ b/browser_extension/app/public/_locales/en/messages.json
@@ -136,9 +136,6 @@
"errorBrowserNoDownloadId": {
"message": "Browser did not return a download task"
},
- "errorCannotDetermineDouyinMediaForm": {
- "message": "Cannot determine Douyin media format, please select in the resource sniffer page"
- },
"errorCannotLocateMedia": {
"message": "Cannot locate media"
},
@@ -659,12 +656,6 @@
"waiting": {
"message": "Waiting"
},
- "waitingForDouyinMuxedUrl": {
- "message": "Waiting for Douyin single MP4 URL"
- },
- "waitingForDouyinSeparateTracks": {
- "message": "Waiting for Douyin audio/video separate tracks"
- },
"waitingForInstagramSeparateTracks": {
"message": "Waiting for Instagram audio/video separate tracks"
},
diff --git a/browser_extension/app/public/_locales/en_US/messages.json b/browser_extension/app/public/_locales/en_US/messages.json
index 9b417c75..f0893b6f 100644
--- a/browser_extension/app/public/_locales/en_US/messages.json
+++ b/browser_extension/app/public/_locales/en_US/messages.json
@@ -136,9 +136,6 @@
"errorBrowserNoDownloadId": {
"message": "Browser did not return a download task"
},
- "errorCannotDetermineDouyinMediaForm": {
- "message": "Unable to determine the current Douyin media type. Please select it on the resource sniffer page."
- },
"errorCannotLocateMedia": {
"message": "Could not locate media"
},
@@ -662,12 +659,6 @@
"waiting": {
"message": "Waiting"
},
- "waitingForDouyinMuxedUrl": {
- "message": "Waiting for Douyin single MP4 URL"
- },
- "waitingForDouyinSeparateTracks": {
- "message": "Waiting for Douyin separate audio and video tracks"
- },
"waitingForInstagramSeparateTracks": {
"message": "Waiting for Instagram separate audio and video tracks"
},
diff --git a/browser_extension/app/public/_locales/es_ES/messages.json b/browser_extension/app/public/_locales/es_ES/messages.json
index 15dce29e..157a829c 100644
--- a/browser_extension/app/public/_locales/es_ES/messages.json
+++ b/browser_extension/app/public/_locales/es_ES/messages.json
@@ -136,9 +136,6 @@
"errorBrowserNoDownloadId": {
"message": "El navegador no devolvió la tarea de descarga"
},
- "errorCannotDetermineDouyinMediaForm": {
- "message": "No se puede determinar el formato del medio de Douyin, selecciónalo en la página de análisis."
- },
"errorCannotLocateMedia": {
"message": "No se pudo localizar el medio"
},
@@ -662,12 +659,6 @@
"waiting": {
"message": "Esperando"
},
- "waitingForDouyinMuxedUrl": {
- "message": "Esperando URL única MP4 de Douyin"
- },
- "waitingForDouyinSeparateTracks": {
- "message": "Esperando que las pistas de audio y vídeo de Douyin estén completas"
- },
"waitingForInstagramSeparateTracks": {
"message": "Esperando que las pistas de audio y vídeo de Instagram estén completas"
},
diff --git a/browser_extension/app/public/_locales/ja/messages.json b/browser_extension/app/public/_locales/ja/messages.json
index 0d651909..0b02b6fa 100644
--- a/browser_extension/app/public/_locales/ja/messages.json
+++ b/browser_extension/app/public/_locales/ja/messages.json
@@ -136,9 +136,6 @@
"errorBrowserNoDownloadId": {
"message": "ブラウザがダウンロードタスクを返しませんでした"
},
- "errorCannotDetermineDouyinMediaForm": {
- "message": "Douyin の現在のメディア形式を判別できません。リソーススニッファーページで選択してください"
- },
"errorCannotLocateMedia": {
"message": "メディアを見つけられませんでした"
},
@@ -662,12 +659,6 @@
"waiting": {
"message": "待機中"
},
- "waitingForDouyinMuxedUrl": {
- "message": "Douyin の単一 MP4 URL を待機中"
- },
- "waitingForDouyinSeparateTracks": {
- "message": "Douyin の音声・動画トラックが揃うのを待機中"
- },
"waitingForInstagramSeparateTracks": {
"message": "Instagram の音声・動画トラックが揃うのを待機中"
},
diff --git a/browser_extension/app/public/_locales/pt_BR/messages.json b/browser_extension/app/public/_locales/pt_BR/messages.json
index a4fd559d..f0946804 100644
--- a/browser_extension/app/public/_locales/pt_BR/messages.json
+++ b/browser_extension/app/public/_locales/pt_BR/messages.json
@@ -136,9 +136,6 @@
"errorBrowserNoDownloadId": {
"message": "O navegador não retornou uma tarefa de download"
},
- "errorCannotDetermineDouyinMediaForm": {
- "message": "Não foi possível determinar o formato de mídia atual do Douyin; selecione na página de captura de recursos"
- },
"errorCannotLocateMedia": {
"message": "Não foi possível localizar a mídia"
},
@@ -662,12 +659,6 @@
"waiting": {
"message": "Aguardando"
},
- "waitingForDouyinMuxedUrl": {
- "message": "Aguardando URL única MP4 do Douyin"
- },
- "waitingForDouyinSeparateTracks": {
- "message": "Aguardando faixas de áudio e vídeo separadas do Douyin"
- },
"waitingForInstagramSeparateTracks": {
"message": "Aguardando faixas de áudio e vídeo separadas do Instagram"
},
diff --git a/browser_extension/app/public/_locales/ru/messages.json b/browser_extension/app/public/_locales/ru/messages.json
index f70d7d8c..e04ad4dd 100644
--- a/browser_extension/app/public/_locales/ru/messages.json
+++ b/browser_extension/app/public/_locales/ru/messages.json
@@ -136,9 +136,6 @@
"errorBrowserNoDownloadId": {
"message": "Браузер не вернул идентификатор загрузки"
},
- "errorCannotDetermineDouyinMediaForm": {
- "message": "Не удалось определить текущий тип медиа Douyin, выберите на странице анализа"
- },
"errorCannotLocateMedia": {
"message": "Не удалось найти медиа"
},
@@ -662,12 +659,6 @@
"waiting": {
"message": "Ожидание"
},
- "waitingForDouyinMuxedUrl": {
- "message": "Ожидание единого MP4 URL Douyin"
- },
- "waitingForDouyinSeparateTracks": {
- "message": "Ожидание готовности раздельных аудио и видео дорожек Douyin"
- },
"waitingForInstagramSeparateTracks": {
"message": "Ожидание готовности раздельных аудио и видео дорожек Instagram"
},
diff --git a/browser_extension/app/public/_locales/zh_CN/messages.json b/browser_extension/app/public/_locales/zh_CN/messages.json
index 972c962b..3f9ab4a6 100644
--- a/browser_extension/app/public/_locales/zh_CN/messages.json
+++ b/browser_extension/app/public/_locales/zh_CN/messages.json
@@ -152,9 +152,6 @@
"errorBrowserNoDownloadId": {
"message": "浏览器未返回下载任务"
},
- "errorCannotDetermineDouyinMediaForm": {
- "message": "无法判定 Douyin 当前媒体形态,请在资源嗅探页选择"
- },
"errorCannotLocateMedia": {
"message": "未能定位媒体"
},
@@ -759,12 +756,6 @@
"waiting": {
"message": "等待中"
},
- "waitingForDouyinMuxedUrl": {
- "message": "等待 Douyin 单 MP4 URL"
- },
- "waitingForDouyinSeparateTracks": {
- "message": "等待 Douyin 音视频分轨齐全"
- },
"waitingForInstagramSeparateTracks": {
"message": "等待 Instagram 音视频分轨齐全"
},
diff --git a/browser_extension/app/public/_locales/zh_HK/messages.json b/browser_extension/app/public/_locales/zh_HK/messages.json
index 929dcf5b..6c432ba2 100644
--- a/browser_extension/app/public/_locales/zh_HK/messages.json
+++ b/browser_extension/app/public/_locales/zh_HK/messages.json
@@ -136,9 +136,6 @@
"errorBrowserNoDownloadId": {
"message": "瀏覽器未返回下載任務"
},
- "errorCannotDetermineDouyinMediaForm": {
- "message": "無法判定 Douyin 當前媒體形態,請在資源嗅探頁面選擇"
- },
"errorCannotLocateMedia": {
"message": "未能定位媒體"
},
@@ -662,12 +659,6 @@
"waiting": {
"message": "等待中"
},
- "waitingForDouyinMuxedUrl": {
- "message": "等待 Douyin 單一 MP4 網址"
- },
- "waitingForDouyinSeparateTracks": {
- "message": "等待 Douyin 音影片分軌齊全"
- },
"waitingForInstagramSeparateTracks": {
"message": "等待 Instagram 音影片分軌齊全"
},
diff --git a/browser_extension/app/public/_locales/zh_TW/messages.json b/browser_extension/app/public/_locales/zh_TW/messages.json
index b62b8600..85609d0c 100644
--- a/browser_extension/app/public/_locales/zh_TW/messages.json
+++ b/browser_extension/app/public/_locales/zh_TW/messages.json
@@ -136,9 +136,6 @@
"errorBrowserNoDownloadId": {
"message": "瀏覽器未返回下載任務"
},
- "errorCannotDetermineDouyinMediaForm": {
- "message": "無法判定 Douyin 當前媒體形態,請在資源嗅探頁選擇"
- },
"errorCannotLocateMedia": {
"message": "未能定位媒體"
},
@@ -662,12 +659,6 @@
"waiting": {
"message": "等待中"
},
- "waitingForDouyinMuxedUrl": {
- "message": "等待 Douyin 單 MP4 URL"
- },
- "waitingForDouyinSeparateTracks": {
- "message": "等待 Douyin 音視訊分軌齊全"
- },
"waitingForInstagramSeparateTracks": {
"message": "等待 Instagram 音視訊分軌齊全"
},
diff --git a/browser_extension/app/src/page-media/attribution/attribution.ts b/browser_extension/app/src/page-media/attribution/attribution.ts
index 2573df2a..0fec7c4d 100644
--- a/browser_extension/app/src/page-media/attribution/attribution.ts
+++ b/browser_extension/app/src/page-media/attribution/attribution.ts
@@ -1,6 +1,7 @@
import {isCatCatchMedia} from "../../shared/cat-catch";
import {fileExtension, filenameFromUrl, mimeFromUrl} from "../../shared/utils";
-import {fbCdnDuration, instagramAssetId, isInstagramCdnUrl, isStreamUrl, urlIdHints} from "../resolution/url-classify";
+import {fbCdnDuration, instagramAssetId, isInstagramCdnUrl, isStreamUrl, matchPageVideo, urlIdHints} from "../resolution/url-classify";
+import type {VideoMatch} from "../resolution/url-classify";
import {AttributionLedger} from "./attribution-ledger";
import {selectMediaForPage} from "../resolution/strategy";
@@ -27,6 +28,13 @@ type ResolveStateListener = (state: VideoSessionState, reason: string) => void;
// mse_buffer_appended usually follows fetch_completed within tens of ms; slow CPUs stretch.
const FETCH_BUFFER_CORRELATION_MS = 2500;
const RECENT_FETCHES_CAP = 16;
+// One AAC frame: a DASH audio track ends up to a frame short of the element's (video) duration.
+const SAME_DURATION_TOLERANCE_S = 0.025;
+// Rejecting is the risky verdict, so it waits for a gap no track of the same video shows.
+const OTHER_DURATION_GAP_S = 1;
+const DURATIONS_CAP = 512;
+
+type MatchClickedVideo = (url: string) => VideoMatch;
function toFormKind(mimeTypes: Set<string>): VideoSessionFormKind {
if (mimeTypes.size === 0) { return "unknown"; }
@@ -59,14 +67,20 @@ function trySelect(ctx: ResolveContext, findUrlsByIdHint: FindUrlsByIdHint): Res
}
}
-function toSessionSnapshot(session: VideoSession): SessionSnapshot {
+function toView(url: string, meta: AttributedUrlMeta, matchClickedVideo: MatchClickedVideo): AttributedUrlView {
+ return Object.freeze({
+ url,
+ contentType: meta.contentType,
+ capturedAt: meta.capturedAt,
+ isMaster: meta.isMaster,
+ isLockedByMse: meta.lockedByMse,
+ clickedVideo: matchClickedVideo(url),
+ });
+}
+
+function toSessionSnapshot(session: VideoSession, matchClickedVideo: MatchClickedVideo): SessionSnapshot {
const attributedUrls: SessionSnapshot["attributedUrls"] = Object.freeze(
- [...session.attributedUrls.entries()].map(([url, meta]) => Object.freeze({
- url,
- contentType: meta.contentType,
- capturedAt: meta.capturedAt,
- isMaster: meta.isMaster,
- })),
+ [...session.attributedUrls.entries()].map(([url, meta]) => toView(url, meta, matchClickedVideo)),
);
return Object.freeze({
formKind: session.formKind,
@@ -91,6 +105,8 @@ class MediaAttribution {
// The only way to definitively bind a URL to a specific <video>: lock the most recent
// unlocked fetch to whichever session consumed it via appendBuffer.
private readonly recentFetches: Array<{ url: string; capturedAt: number; idHints: ReadonlySet<string> }> = [];
+ // Read off the moov of files the player itself fetched, so no extra request.
+ private readonly durationByUrl = new Map<string, number>();
start(): void {
document.querySelectorAll<HTMLMediaElement>("video, audio").forEach((element) => {
@@ -422,6 +438,13 @@ class MediaAttribution {
this.attributeBufferAppend(signal.mediaSourceId, signal.mimeType);
return;
+ case "media_duration":
+ this.durationByUrl.set(signal.url, signal.duration);
+ if (this.durationByUrl.size > DURATIONS_CAP) {
+ this.durationByUrl.delete(this.durationByUrl.keys().next().value!);
+ }
+ return;
+
case "request_completed":
this.recordFetch(signal.url, signal.contentType);
this.attributeFetch(signal.url, signal.contentType);
@@ -592,13 +615,18 @@ class MediaAttribution {
}
const pageUrl = new URL(location.href);
- const findUrlsByIdHint: FindUrlsByIdHint = (idHint) => this.lookupByIdHint(idHint);
-
- const buildCtx = (): ResolveContext => ({
- clicked: toSessionSnapshot(session),
- pageUrl,
- hints,
- });
+ const findUrlsByIdHint: FindUrlsByIdHint = (idHint) =>
+ this.viewsOfAllSessions(this.buildClickedVideoMatcher(pageUrl, element)).filter((view) => urlIdHints(view.url).has(idHint));
+
+ const buildCtx = (): ResolveContext => {
+ const matchClickedVideo = this.buildClickedVideoMatcher(pageUrl, element);
+ return {
+ clicked: toSessionSnapshot(session, matchClickedVideo),
+ pageUrl,
+ hints,
+ clickedVideoUrls: this.viewsOfAllSessions(matchClickedVideo).filter((view) => view.clickedVideo === "same"),
+ };
+ };
const initial = trySelect(buildCtx(), findUrlsByIdHint);
if (initial.kind !== "pending") {
@@ -641,23 +669,25 @@ class MediaAttribution {
});
}
- // Douyin uses this to reach across sessions for a prefetched URL claimed by a sibling
- // before the new <video> existed.
- private lookupByIdHint(idHint: string): ReadonlyArray<AttributedUrlView> {
- const matches: AttributedUrlView[] = [];
- for (const session of this.sessionsById.values()) {
- for (const [url, meta] of session.attributedUrls) {
- if (urlIdHints(url).has(idHint)) {
- matches.push({
- url,
- contentType: meta.contentType,
- capturedAt: meta.capturedAt,
- isMaster: meta.isMaster,
- });
- }
- }
- }
- return matches;
+ // Reaches across sessions for a prefetched URL claimed by a sibling before the new <video> existed.
+ private viewsOfAllSessions(matchClickedVideo: MatchClickedVideo): AttributedUrlView[] {
+ return [...this.sessionsById.values()].flatMap((session) =>
+ [...session.attributedUrls].map(([url, meta]) => toView(url, meta, matchClickedVideo)));
+ }
+
+ // When no known file has the element's length, this site's MSE duration isn't the file's, so durations stay silent.
+ private buildClickedVideoMatcher(pageUrl: URL, element: HTMLMediaElement): MatchClickedVideo {
+ const target = element.duration;
+ const isSameLength = (duration: number) => Math.abs(duration - target) <= SAME_DURATION_TOLERANCE_S;
+ const canCompare = Number.isFinite(target) && target > 0 && [...this.durationByUrl.values()].some(isSameLength);
+ return (url) => {
+ const byPage = matchPageVideo(url, pageUrl);
+ if (byPage !== "unknown" || !canCompare) { return byPage; }
+ const duration = this.durationByUrl.get(url);
+ if (duration === undefined) { return "unknown"; }
+ if (isSameLength(duration)) { return "same"; }
+ return Math.abs(duration - target) > OTHER_DURATION_GAP_S ? "other" : "unknown";
+ };
}
// Worker-based MediaSourceHandle bypasses the MSE probe — the probe only patches
diff --git a/browser_extension/app/src/page-media/attribution/mp4-duration.ts b/browser_extension/app/src/page-media/attribution/mp4-duration.ts
new file mode 100644
index 00000000..57e4655e
--- /dev/null
+++ b/browser_extension/app/src/page-media/attribution/mp4-duration.ts
@@ -0,0 +1,53 @@
+// Past this, the moov sits at the file's end (non-faststart) and the duration stays unknown.
+export const MP4_HEAD_LIMIT = 256 * 1024;
+
+type Box = { type: string; start: number; end: number };
+
+function parseBoxes(view: DataView, from: number, to: number): Box[] {
+ const boxes: Box[] = [];
+ let offset = from;
+ while (offset + 8 <= to) {
+ let size = view.getUint32(offset);
+ const type = String.fromCharCode(
+ view.getUint8(offset + 4), view.getUint8(offset + 5), view.getUint8(offset + 6), view.getUint8(offset + 7),
+ );
+ let header = 8;
+ if (size === 1) {
+ if (offset + 16 > to) { break; }
+ size = Number(view.getBigUint64(offset + 8));
+ header = 16;
+ } else if (size === 0) {
+ size = to - offset;
+ }
+ if (size < header) { break; }
+ boxes.push({ type, start: offset + header, end: offset + size });
+ offset += size;
+ }
+ return boxes;
+}
+
+export function isMp4Head(bytes: Uint8Array): boolean {
+ return bytes.length >= 8 && bytes[4] === 0x66 && bytes[5] === 0x74 && bytes[6] === 0x79 && bytes[7] === 0x70;
+}
+
+// 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; }
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const moov = parseBoxes(view, 0, view.byteLength).find((box) => box.type === "moov");
+ if (!moov) { return undefined; }
+ const children = parseBoxes(view, moov.start, Math.min(moov.end, view.byteLength));
+ const mvhd = children.find((box) => box.type === "mvhd");
+ if (!mvhd || mvhd.start + 32 > view.byteLength) { return undefined; }
+ const isV1 = view.getUint8(mvhd.start) === 1;
+ const timescale = view.getUint32(mvhd.start + (isV1 ? 20 : 12));
+ let duration = isV1 ? Number(view.getBigUint64(mvhd.start + 24)) : view.getUint32(mvhd.start + 16);
+ if (duration === 0 || duration === 0xffffffff) {
+ const mvex = children.find((box) => box.type === "mvex");
+ const mehd = mvex && parseBoxes(view, mvex.start, Math.min(mvex.end, view.byteLength)).find((box) => box.type === "mehd");
+ if (mehd && mehd.start + 12 <= view.byteLength) {
+ duration = view.getUint8(mehd.start) === 1 ? Number(view.getBigUint64(mehd.start + 4)) : view.getUint32(mehd.start + 4);
+ }
+ }
+ return timescale > 0 && duration > 0 ? duration / timescale : undefined;
+}
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 0c082dcf..3b9e9929 100644
--- a/browser_extension/app/src/page-media/attribution/mse-probe.ts
+++ b/browser_extension/app/src/page-media/attribution/mse-probe.ts
@@ -5,6 +5,7 @@
* capturing buffers. Built as a standalone IIFE bundle (see scripts/build.mjs).
*/
import {postMediaSignal} from "./attribution-signal";
+import {isMp4Head, MP4_HEAD_LIMIT, parseMp4Duration} from "./mp4-duration";
declare global {
interface Window {
@@ -59,24 +60,49 @@ type GhostXMLHttpRequest = XMLHttpRequest & { __gdUrl?: string };
};
}
- function probeStreamContent(response: Response, url: string): void {
+ function toBytes(chunks: Uint8Array[]): Uint8Array {
+ if (chunks.length === 1) { return chunks[0]; }
+ const all = new Uint8Array(chunks.reduce((size, chunk) => size + chunk.length, 0));
+ let offset = 0;
+ for (const chunk of chunks) { all.set(chunk, offset); offset += chunk.length; }
+ return all;
+ }
+
+ // 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> {
+ const contentLength = parseInt(response.headers.get("content-length") || "", 10);
+ const contentType = response.headers.get("content-type") || "";
+ if (contentLength > 2_000_000 && !/^(video|audio)\/|octet-stream/i.test(contentType)) { return; }
+ let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
try {
- const contentLength = parseInt(response.headers.get("content-length") || "", 10);
- if (contentLength > 2_000_000) { return; }
- const reader = response.clone().body?.getReader();
- if (!reader) { return; }
- reader.read().then(({ value }) => {
- reader.cancel();
- if (!value || value[0] !== 0x23) { return; }
- const text = new TextDecoder().decode(value);
- if (!text.startsWith("#EXTM3U")) { return; }
- postMediaSignal({
- kind: "stream_detected",
- url,
- isMaster: text.includes("#EXT-X-STREAM-INF"),
- });
- }).catch(() => {});
- } catch { /* Opaque response — clone() throws. */ }
+ reader = response.clone().body?.getReader();
+ } catch { return; /* Opaque response — clone() throws. */ }
+ if (!reader) { return; }
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ 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 needs its whole moov.
+ if (!isMp4Head(chunks[0]) || parseMp4Duration(toBytes(chunks)) !== undefined) { break; }
+ }
+ reader.cancel().catch(() => {});
+ const head = toBytes(chunks);
+ const duration = parseMp4Duration(head);
+ if (duration !== undefined) {
+ postMediaSignal({ kind: "media_duration", url, duration });
+ return;
+ }
+ if (head[0] !== 0x23) { return; }
+ const text = new TextDecoder().decode(head);
+ if (!text.startsWith("#EXTM3U")) { return; }
+ postMediaSignal({
+ kind: "stream_detected",
+ url,
+ isMaster: text.includes("#EXT-X-STREAM-INF"),
+ });
}
if (typeof window.fetch === "function") {
@@ -96,7 +122,7 @@ type GhostXMLHttpRequest = XMLHttpRequest & { __gdUrl?: string };
url: resolvedUrl,
contentType: response?.headers?.get?.("content-type") ?? "",
});
- probeStreamContent(response, resolvedUrl);
+ probeContent(response, resolvedUrl).catch(() => {});
} catch {
// Opaque response.
}
@@ -134,6 +160,13 @@ type GhostXMLHttpRequest = XMLHttpRequest & { __gdUrl?: string };
});
}
} catch { /* responseText throws on non-text responseType. */ }
+ try {
+ if (xhr.responseType === "arraybuffer" && xhr.response instanceof ArrayBuffer) {
+ const head = new Uint8Array(xhr.response, 0, Math.min(xhr.response.byteLength, MP4_HEAD_LIMIT));
+ 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 originalSend.call(this, body);
};
diff --git a/browser_extension/app/src/page-media/resolution/strategies/douyin.ts b/browser_extension/app/src/page-media/resolution/strategies/douyin.ts
deleted file mode 100644
index b77eb1b5..00000000
--- a/browser_extension/app/src/page-media/resolution/strategies/douyin.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import {douyinKindOf, hostEndsWith} from "../url-classify";
-import {newestMatching, postBindAttributedUrls, selectMergePair} from "../strategy";
-import type {FindUrlsByIdHint, ResolveContext} from "../strategy";
-import type {Resolution} from "../../types";
-
-// Until the next reel's MSE binds and correlation locks the URL, the prefetched URL is
-// still provisionally owned by the previous reel's session. modal_id is what survives
-// that window.
-function matchesModalId(url: string, modalId: string): boolean {
- if (!modalId) { return true; }
- try {
- const vid = new URL(url).searchParams.get("__vid");
- return !vid || vid === modalId;
- } catch { return true; }
-}
-
-export function selectDouyin(ctx: ResolveContext, findUrlsByIdHint: FindUrlsByIdHint): Resolution {
- const modalId = ctx.pageUrl.searchParams.get("modal_id") ?? "";
- const post = postBindAttributedUrls(ctx.clicked).filter((r) =>
- hostEndsWith(r.url, "douyinvod.com") && matchesModalId(r.url, modalId),
- );
-
- if (ctx.clicked.formKind === "muxed") {
- const muxed = newestMatching(post, (url) => douyinKindOf(url) === "muxed") ?? findByModalId(ctx, findUrlsByIdHint, "muxed");
- if (muxed) {
- return { kind: "selection", selection: { kind: "single", url: muxed, formKind: "muxed" } };
- }
- return { kind: "pending", reason: chrome.i18n.getMessage("waitingForDouyinMuxedUrl") };
- }
-
- if (ctx.clicked.formKind === "dash") {
- const video = newestMatching(post, (url) => douyinKindOf(url) === "video") ?? findByModalId(ctx, findUrlsByIdHint, "video");
- const audio = newestMatching(post, (url) => douyinKindOf(url) === "audio") ?? findByModalId(ctx, findUrlsByIdHint, "audio");
- if (video && audio) {
- return { kind: "selection", selection: { kind: "merge", video, audio } };
- }
- return { kind: "pending", reason: chrome.i18n.getMessage("waitingForDouyinSeparateTracks") };
- }
-
- // formKind unknown — MSE hasn't reported yet.
- if (post.length === 0) {
- const fromModalId = findByModalId(ctx, findUrlsByIdHint, "muxed");
- if (fromModalId) {
- return { kind: "selection", selection: { kind: "single", url: fromModalId, formKind: "unknown" } };
- }
- return { kind: "pending", reason: chrome.i18n.getMessage("waitingForVideoResource") };
- }
- const muxed = newestMatching(post, (url) => douyinKindOf(url) === "muxed");
- if (muxed) {
- return { kind: "selection", selection: { kind: "single", url: muxed, formKind: "unknown" } };
- }
- const pair = selectMergePair(post, douyinKindOf);
- if (pair) {
- return { kind: "selection", selection: { kind: "merge", video: pair.video, audio: pair.audio } };
- }
- return { kind: "refused", message: chrome.i18n.getMessage("errorCannotDetermineDouyinMediaForm") };
-}
-
-// Ledger query crosses session boundaries — that's what lets us pick the prefetched
-// URL even when it's still provisionally owned by the previous reel.
-function findByModalId(ctx: ResolveContext, findUrlsByIdHint: FindUrlsByIdHint, kind: "muxed" | "video" | "audio"): string | undefined {
- const modalId = ctx.pageUrl.searchParams.get("modal_id");
- if (!modalId || modalId.length < 4) { return undefined; }
- const matches = findUrlsByIdHint(`__vid=${modalId}`);
- return newestMatching(matches, (url) => douyinKindOf(url) === kind);
-}
diff --git a/browser_extension/app/src/page-media/resolution/strategies/generic.ts b/browser_extension/app/src/page-media/resolution/strategies/generic.ts
index 71dbf631..4c5a15c8 100644
--- a/browser_extension/app/src/page-media/resolution/strategies/generic.ts
+++ b/browser_extension/app/src/page-media/resolution/strategies/generic.ts
@@ -1,24 +1,28 @@
import {classifyTrackRole, isDashSegmentUrl, isStreamUrl, stripRangeParams} from "../url-classify";
-import {newestMatching, postBindAttributedUrls, selectMergePair} from "../strategy";
+import {bestMatching, postBindAttributedUrls, selectMergePair} from "../strategy";
import type {ResolveContext} from "../strategy";
import type {Resolution} from "../../types";
+const isMuxedUrl = (url: string) => !isDashSegmentUrl(url);
+
// Fallback strategy — runs when no per-site strategy matches the hostname.
export function selectGeneric(ctx: ResolveContext): Resolution {
- const post = postBindAttributedUrls(ctx.clicked);
+ const post = postBindAttributedUrls(ctx.clicked).filter((r) => r.clickedVideo !== "other");
+ const pick = (predicate: (url: string, contentType: string) => boolean) =>
+ bestMatching(post, predicate) ?? bestMatching(ctx.clickedVideoUrls, predicate);
const master = post.find((r) => r.isMaster);
if (master) {
return { kind: "selection", selection: { kind: "stream", url: master.url } };
}
- const stream = newestMatching(post, isStreamUrl);
+ const stream = bestMatching(post, isStreamUrl);
if (stream) {
return { kind: "selection", selection: { kind: "stream", url: stream } };
}
if (ctx.clicked.formKind === "muxed") {
- const muxed = newestMatching(post, (url) => !isDashSegmentUrl(url));
+ const muxed = pick(isMuxedUrl);
if (muxed) {
return { kind: "selection", selection: { kind: "single", url: stripRangeParams(muxed), formKind: "muxed" } };
}
@@ -26,23 +30,36 @@ export function selectGeneric(ctx: ResolveContext): Resolution {
}
if (ctx.clicked.formKind === "dash") {
- const pair = selectMergePair(post, classifyTrackRole);
- if (pair) {
- return { kind: "selection", selection: { kind: "merge", video: stripRangeParams(pair.video), audio: stripRangeParams(pair.audio) } };
+ const video = pick((url, contentType) => classifyTrackRole(url, contentType) === "video");
+ const audio = pick((url, contentType) => classifyTrackRole(url, contentType) === "audio");
+ if (video && audio) {
+ return { kind: "selection", selection: { kind: "merge", video: stripRangeParams(video), audio: stripRangeParams(audio) } };
}
return { kind: "pending", reason: chrome.i18n.getMessage("waitingForSeparateTracks") };
}
+ // formKind unknown: a guess between unrelated videos is worse than asking, so only evidence or uniqueness picks.
if (post.length === 0) {
+ const muxed = pick(isMuxedUrl);
+ if (muxed) {
+ return { kind: "selection", selection: { kind: "single", url: stripRangeParams(muxed), formKind: "unknown" } };
+ }
return { kind: "pending", reason: chrome.i18n.getMessage("waitingForVideoResource") };
}
+ const evidenced = post.filter((r) => r.clickedVideo === "same");
+ // Two evidenced files are a duration collision between reels, not a choice.
+ const evidencedMuxed = evidenced.filter((r) => isMuxedUrl(r.url));
+ const muxed = evidencedMuxed.length === 1 ? evidencedMuxed[0].url : (post.length === 1 && isMuxedUrl(post[0].url) ? post[0].url : undefined);
+ if (muxed) {
+ return { kind: "selection", selection: { kind: "single", url: stripRangeParams(muxed), formKind: "unknown" } };
+ }
+ const pair = selectMergePair(evidenced, classifyTrackRole) ?? (post.length === 2 ? selectMergePair(post, classifyTrackRole) : null);
+ if (pair) {
+ return { kind: "selection", selection: { kind: "merge", video: stripRangeParams(pair.video), audio: stripRangeParams(pair.audio) } };
+ }
if (post.length === 1) {
- const only = post[0];
- if (isDashSegmentUrl(only.url)) {
- // The sibling track may still be in flight pre-MSE-ack.
- return { kind: "pending", reason: chrome.i18n.getMessage("waitingForSeparateTracks") };
- }
- return { kind: "selection", selection: { kind: "single", url: stripRangeParams(only.url), formKind: "unknown" } };
+ // The sibling track may still be in flight pre-MSE-ack.
+ return { kind: "pending", reason: chrome.i18n.getMessage("waitingForSeparateTracks") };
}
return { kind: "refused", message: chrome.i18n.getMessage("errorMultipleMediaFound") };
}
diff --git a/browser_extension/app/src/page-media/resolution/strategy.ts b/browser_extension/app/src/page-media/resolution/strategy.ts
index ce5bdaf8..029c39e4 100644
--- a/browser_extension/app/src/page-media/resolution/strategy.ts
+++ b/browser_extension/app/src/page-media/resolution/strategy.ts
@@ -1,8 +1,8 @@
-import {selectDouyin} from "./strategies/douyin";
import {selectGeneric} from "./strategies/generic";
import {selectMeta} from "./strategies/instagram";
import {selectYouTube} from "./strategies/youtube";
import {isStreamUrl} from "./url-classify";
+import type {VideoMatch} from "./url-classify";
import type {Resolution, VideoSessionFormKind} from "../types";
// One attributed URL as the strategies see it — also the element type of
@@ -12,6 +12,9 @@ export type AttributedUrlView = {
readonly contentType: string;
readonly capturedAt: number;
readonly isMaster?: boolean;
+ readonly isLockedByMse: boolean;
+ // Whether the URL holds the video the user clicked, judged by the Attribution Engine.
+ readonly clickedVideo: VideoMatch;
};
// Strategies see only this — they MUST NOT reach back into the controller.
@@ -30,20 +33,17 @@ export type ResolveContext = {
readonly clicked: SessionSnapshot;
readonly pageUrl: URL;
readonly hints: ResolveHints;
+ // Rescues a prefetched URL still provisionally owned by the previous reel's session.
+ readonly clickedVideoUrls: ReadonlyArray<AttributedUrlView>;
};
-// Cross-session ledger lookup. It is Douyin's escape hatch for the prefetch case where the
-// URL is provisionally owned by v-1 but carries v-2's __vid — so only Douyin's strategy
-// gets it, instead of leaking the capability into every strategy's context.
+// Cross-session ledger lookup by a `key=value` id hint (Instagram's xpv_asset_id).
export type FindUrlsByIdHint = (idHint: string) => ReadonlyArray<AttributedUrlView>;
// The whole dispatch: pick the strategy by hostname, Generic being the fallback. Strategies
-// are pure functions of the context; Douyin alone also takes the ledger lookup.
+// are pure functions of the context; Instagram also takes the ledger lookup.
export function selectMediaForPage(ctx: ResolveContext, findUrlsByIdHint: FindUrlsByIdHint): Resolution {
const host = ctx.pageUrl.hostname;
- if (host === "www.douyin.com" || host.endsWith(".douyin.com")) {
- return selectDouyin(ctx, findUrlsByIdHint);
- }
// Instagram and Facebook share the same CDN format (fbcdn.net, efg/vencode_tag/xpv_asset_id).
if (host === "www.instagram.com" || host.endsWith(".instagram.com")
|| host === "www.facebook.com" || host.endsWith(".facebook.com")) {
@@ -64,33 +64,33 @@ export function postBindAttributedUrls(view: SessionSnapshot): SessionSnapshot["
);
}
-export function newestBy<T>(items: ReadonlyArray<T>, key: (item: T) => number): T | undefined {
- if (items.length === 0) { return undefined; }
- let best = items[0];
- let bestKey = key(best);
- for (let i = 1; i < items.length; i += 1) {
- const k = key(items[i]);
- if (k > bestKey) { best = items[i]; bestKey = k; }
- }
- return best;
+// A prefetched sibling is fetched after the clicked video's own URL, so freshness ranks last.
+function isBetter(candidate: AttributedUrlView, best: AttributedUrlView): boolean {
+ if ((candidate.clickedVideo === "same") !== (best.clickedVideo === "same")) { return candidate.clickedVideo === "same"; }
+ if (candidate.isLockedByMse !== best.isLockedByMse) { return candidate.isLockedByMse; }
+ return candidate.capturedAt > best.capturedAt;
}
-// The freshest attributed URL whose url/contentType matches — the shared shape behind every
-// "pick the newest stream / muxed / track" line the strategies used to spell out by hand.
-export function newestMatching(
+// The most trusted attributed URL whose url/contentType matches.
+export function bestMatching(
urls: SessionSnapshot["attributedUrls"],
predicate: (url: string, contentType: string) => boolean,
): string | undefined {
- return newestBy(urls.filter((entry) => predicate(entry.url, entry.contentType)), (entry) => entry.capturedAt)?.url;
+ let best: AttributedUrlView | undefined;
+ for (const entry of urls) {
+ if (!predicate(entry.url, entry.contentType)) { continue; }
+ if (!best || isBetter(entry, best)) { best = entry; }
+ }
+ return best?.url;
}
-// The freshest video + audio track for a DASH merge, or null if either side is missing.
+// The most trusted video + audio track for a DASH merge, or null if either side is missing.
// The caller decides whether to strip range params off the returned URLs.
export function selectMergePair(
urls: SessionSnapshot["attributedUrls"],
classify: (url: string, contentType: string) => string,
): { video: string; audio: string } | null {
- const video = newestMatching(urls, (url, contentType) => classify(url, contentType) === "video");
- const audio = newestMatching(urls, (url, contentType) => classify(url, contentType) === "audio");
+ const video = bestMatching(urls, (url, contentType) => classify(url, contentType) === "video");
+ const audio = bestMatching(urls, (url, contentType) => classify(url, contentType) === "audio");
return video && audio ? { video, audio } : null;
}
diff --git a/browser_extension/app/src/page-media/resolution/url-classify.ts b/browser_extension/app/src/page-media/resolution/url-classify.ts
index ac4523c1..d2b81dd5 100644
--- a/browser_extension/app/src/page-media/resolution/url-classify.ts
+++ b/browser_extension/app/src/page-media/resolution/url-classify.ts
@@ -44,12 +44,10 @@ export function isDashSegmentUrl(url: string): boolean {
return fileExtension(filenameFromUrl(url)) === "m4s";
}
-// Douyin tags track role in the URL path; the "prime" muxed-MP4 has no marker but stays
-// on douyinvod.com with __vid in the query.
-export function douyinKindOf(url: string): "video" | "audio" | "muxed" | "" {
+// ByteDance CDNs (Douyin, TikTok) tag track role in the URL path.
+function trackRoleFromPath(url: string): "video" | "audio" | "" {
if (url.includes("/media-audio-")) { return "audio"; }
if (url.includes("/media-video-")) { return "video"; }
- if (hostEndsWith(url, "douyinvod.com") && url.includes("__vid=")) { return "muxed"; }
return "";
}
@@ -139,11 +137,42 @@ export function urlIdHints(url: string): Set<string> {
return result;
}
+function queryIdValues(parsed: URL): Set<string> {
+ const values = new Set<string>();
+ for (const key of VIDEO_ID_QUERY_KEYS) {
+ const value = parsed.searchParams.get(key);
+ if (value && value.length >= 4) { values.add(value); }
+ }
+ return values;
+}
+
+function pathIdValues(parsed: URL): Set<string> {
+ return new Set(parsed.pathname.split("/").filter(looksLikeVideoIdSegment));
+}
+
+export type VideoMatch = "same" | "other" | "unknown";
+
+// By value, not key: Douyin's page says modal_id=X where its CDN says __vid=X. CDN path segments are storage hashes, so they never prove "other".
+export function matchPageVideo(url: string, pageUrl: URL): VideoMatch {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return "unknown";
+ }
+ const pageQueryIds = queryIdValues(pageUrl);
+ const pageIds = new Set([...pageQueryIds, ...pathIdValues(pageUrl)]);
+ if (pageIds.size === 0) { return "unknown"; }
+ const queryIds = queryIdValues(parsed);
+ for (const id of [...queryIds, ...pathIdValues(parsed)]) {
+ if (pageIds.has(id)) { return "same"; }
+ }
+ return queryIds.size > 0 && pageQueryIds.size > 0 ? "other" : "unknown";
+}
+
export function classifyTrackRole(url: string, contentType: string): TrackRole {
- const douyin = douyinKindOf(url);
- if (douyin === "muxed") { return "muxed"; }
- if (douyin === "video") { return "video"; }
- if (douyin === "audio") { return "audio"; }
+ const pathRole = trackRoleFromPath(url);
+ if (pathRole) { return pathRole; }
const mime = (contentType || mimeFromUrl(url) || "").toLowerCase();
diff --git a/browser_extension/app/src/page-media/types.ts b/browser_extension/app/src/page-media/types.ts
index 88ea4f6a..7e1125bf 100644
--- a/browser_extension/app/src/page-media/types.ts
+++ b/browser_extension/app/src/page-media/types.ts
@@ -27,6 +27,7 @@ export type MseAttributionSignal =
| { kind: "mse_source_buffer_added"; mediaSourceId: string; mimeType: string }
| { kind: "mse_buffer_appended"; mediaSourceId: string; mimeType: string }
| { kind: "request_completed"; url: string; contentType: string }
+ | { kind: "media_duration"; url: string; duration: number }
| { kind: "stream_detected"; url: string; isMaster: boolean };
export type VideoSession = {