avbridge 2.2.1 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +80 -1
  2. package/NOTICE.md +2 -2
  3. package/README.md +2 -3
  4. package/THIRD_PARTY_LICENSES.md +2 -2
  5. package/dist/avi-2JPBSHGA.js +183 -0
  6. package/dist/avi-2JPBSHGA.js.map +1 -0
  7. package/dist/avi-F6WZJK5T.cjs +185 -0
  8. package/dist/avi-F6WZJK5T.cjs.map +1 -0
  9. package/dist/{avi-GCGM7OJI.js → avi-NJXAXUXK.js} +9 -3
  10. package/dist/avi-NJXAXUXK.js.map +1 -0
  11. package/dist/{avi-6SJLWIWW.cjs → avi-W6L3BTWU.cjs} +10 -4
  12. package/dist/avi-W6L3BTWU.cjs.map +1 -0
  13. package/dist/{chunk-ILKDNBSE.js → chunk-2PGRFCWB.js} +59 -10
  14. package/dist/chunk-2PGRFCWB.js.map +1 -0
  15. package/dist/chunk-5YAWWKA3.js +18 -0
  16. package/dist/chunk-5YAWWKA3.js.map +1 -0
  17. package/dist/chunk-6UUT4BEA.cjs +219 -0
  18. package/dist/chunk-6UUT4BEA.cjs.map +1 -0
  19. package/dist/{chunk-UF2N5L63.cjs → chunk-7RGG6ME7.cjs} +489 -76
  20. package/dist/chunk-7RGG6ME7.cjs.map +1 -0
  21. package/dist/{chunk-WD2ZNQA7.js → chunk-DCSOQH2N.js} +7 -4
  22. package/dist/chunk-DCSOQH2N.js.map +1 -0
  23. package/dist/chunk-F3LQJKXK.cjs +20 -0
  24. package/dist/chunk-F3LQJKXK.cjs.map +1 -0
  25. package/dist/chunk-IAYKFGFG.js +200 -0
  26. package/dist/chunk-IAYKFGFG.js.map +1 -0
  27. package/dist/chunk-NNVOHKXJ.cjs +204 -0
  28. package/dist/chunk-NNVOHKXJ.cjs.map +1 -0
  29. package/dist/{chunk-DMWARSEF.js → chunk-NV7ILLWH.js} +483 -74
  30. package/dist/chunk-NV7ILLWH.js.map +1 -0
  31. package/dist/{chunk-HZLQNKFN.cjs → chunk-QQXBPW72.js} +54 -15
  32. package/dist/chunk-QQXBPW72.js.map +1 -0
  33. package/dist/chunk-XKPSTC34.cjs +210 -0
  34. package/dist/chunk-XKPSTC34.cjs.map +1 -0
  35. package/dist/{chunk-L4NPOJ36.cjs → chunk-Z33SBWL5.cjs} +7 -4
  36. package/dist/chunk-Z33SBWL5.cjs.map +1 -0
  37. package/dist/element-browser.js +558 -85
  38. package/dist/element-browser.js.map +1 -1
  39. package/dist/element.cjs +4 -4
  40. package/dist/element.d.cts +1 -1
  41. package/dist/element.d.ts +1 -1
  42. package/dist/element.js +3 -3
  43. package/dist/index.cjs +174 -26
  44. package/dist/index.cjs.map +1 -1
  45. package/dist/index.d.cts +48 -4
  46. package/dist/index.d.ts +48 -4
  47. package/dist/index.js +93 -12
  48. package/dist/index.js.map +1 -1
  49. package/dist/libav-http-reader-AZLE7YFS.cjs +16 -0
  50. package/dist/{libav-http-reader-FPYDBMYK.cjs.map → libav-http-reader-AZLE7YFS.cjs.map} +1 -1
  51. package/dist/libav-http-reader-WXG3Z7AI.js +3 -0
  52. package/dist/{libav-http-reader-NQJVY273.js.map → libav-http-reader-WXG3Z7AI.js.map} +1 -1
  53. package/dist/{player-U2NPmFvA.d.cts → player-B6WB74RD.d.cts} +62 -3
  54. package/dist/{player-U2NPmFvA.d.ts → player-B6WB74RD.d.ts} +62 -3
  55. package/dist/player.cjs +5500 -0
  56. package/dist/player.cjs.map +1 -0
  57. package/dist/player.d.cts +649 -0
  58. package/dist/player.d.ts +649 -0
  59. package/dist/player.js +5498 -0
  60. package/dist/player.js.map +1 -0
  61. package/dist/source-73CAH6HW.cjs +28 -0
  62. package/dist/{source-CN43EI7Z.cjs.map → source-73CAH6HW.cjs.map} +1 -1
  63. package/dist/source-F656KYYV.js +3 -0
  64. package/dist/{source-FFZ7TW2B.js.map → source-F656KYYV.js.map} +1 -1
  65. package/dist/source-QJR3OHTW.js +3 -0
  66. package/dist/source-QJR3OHTW.js.map +1 -0
  67. package/dist/source-VB74JQ7Z.cjs +28 -0
  68. package/dist/source-VB74JQ7Z.cjs.map +1 -0
  69. package/dist/variant-routing-434STYAB.js +3 -0
  70. package/dist/{variant-routing-JOBWXYKD.js.map → variant-routing-434STYAB.js.map} +1 -1
  71. package/dist/variant-routing-HONNAA6R.cjs +12 -0
  72. package/dist/{variant-routing-GOHB2RZN.cjs.map → variant-routing-HONNAA6R.cjs.map} +1 -1
  73. package/package.json +9 -1
  74. package/src/classify/rules.ts +27 -5
  75. package/src/convert/remux.ts +8 -0
  76. package/src/convert/transcode.ts +41 -8
  77. package/src/element/avbridge-player.ts +845 -0
  78. package/src/element/player-icons.ts +25 -0
  79. package/src/element/player-styles.ts +472 -0
  80. package/src/errors.ts +47 -0
  81. package/src/index.ts +23 -0
  82. package/src/player-element.ts +18 -0
  83. package/src/player.ts +104 -12
  84. package/src/plugins/builtin.ts +2 -2
  85. package/src/probe/avi.ts +4 -0
  86. package/src/probe/index.ts +40 -10
  87. package/src/strategies/fallback/audio-output.ts +31 -0
  88. package/src/strategies/fallback/decoder.ts +83 -2
  89. package/src/strategies/fallback/index.ts +29 -4
  90. package/src/strategies/fallback/variant-routing.ts +7 -13
  91. package/src/strategies/fallback/video-renderer.ts +124 -32
  92. package/src/strategies/hybrid/decoder.ts +131 -20
  93. package/src/strategies/hybrid/index.ts +31 -5
  94. package/src/strategies/remux/mse.ts +12 -2
  95. package/src/subtitles/index.ts +7 -3
  96. package/src/types.ts +53 -1
  97. package/src/util/libav-http-reader.ts +5 -1
  98. package/src/util/source.ts +28 -8
  99. package/src/util/transport.ts +26 -0
  100. package/vendor/libav/avbridge/libav-6.8.8.0-avbridge.wasm.mjs +1 -1
  101. package/vendor/libav/avbridge/libav-6.8.8.0-avbridge.wasm.wasm +0 -0
  102. package/dist/avi-6SJLWIWW.cjs.map +0 -1
  103. package/dist/avi-GCGM7OJI.js.map +0 -1
  104. package/dist/chunk-DMWARSEF.js.map +0 -1
  105. package/dist/chunk-HZLQNKFN.cjs.map +0 -1
  106. package/dist/chunk-ILKDNBSE.js.map +0 -1
  107. package/dist/chunk-J5MCMN3S.js +0 -27
  108. package/dist/chunk-J5MCMN3S.js.map +0 -1
  109. package/dist/chunk-L4NPOJ36.cjs.map +0 -1
  110. package/dist/chunk-NZU7W256.cjs +0 -29
  111. package/dist/chunk-NZU7W256.cjs.map +0 -1
  112. package/dist/chunk-UF2N5L63.cjs.map +0 -1
  113. package/dist/chunk-WD2ZNQA7.js.map +0 -1
  114. package/dist/libav-http-reader-FPYDBMYK.cjs +0 -16
  115. package/dist/libav-http-reader-NQJVY273.js +0 -3
  116. package/dist/source-CN43EI7Z.cjs +0 -28
  117. package/dist/source-FFZ7TW2B.js +0 -3
  118. package/dist/variant-routing-GOHB2RZN.cjs +0 -12
  119. package/dist/variant-routing-JOBWXYKD.js +0 -3
@@ -1,9 +1,12 @@
1
1
  // src/util/libav-http-reader.ts
2
2
  var MIN_READ = 256 * 1024;
3
3
  var MAX_READ = 1 * 1024 * 1024;
4
- async function prepareLibavInput(libav, filename, source) {
4
+ async function prepareLibavInput(libav, filename, source, transport) {
5
5
  if (source.kind === "url") {
6
- const handle = await attachLibavHttpReader(libav, filename, source.url);
6
+ const handle = await attachLibavHttpReader(libav, filename, source.url, {
7
+ requestInit: transport?.requestInit,
8
+ fetchFn: transport?.fetchFn
9
+ });
7
10
  return {
8
11
  filename,
9
12
  transport: "http-range",
@@ -173,5 +176,5 @@ async function attachLibavHttpReader(libav, filename, url, options = {}) {
173
176
  }
174
177
 
175
178
  export { attachLibavHttpReader, prepareLibavInput };
176
- //# sourceMappingURL=chunk-WD2ZNQA7.js.map
177
- //# sourceMappingURL=chunk-WD2ZNQA7.js.map
179
+ //# sourceMappingURL=chunk-DCSOQH2N.js.map
180
+ //# sourceMappingURL=chunk-DCSOQH2N.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/util/libav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AAAA,QAAe;AAAA,MAC/C;AAEA,MAAA,MAAA,GAAS,IAAA;AACT,MAAA,IAAI;AAAE,QAAA,MAAM,KAAA,CAAM,oBAAoB,QAAQ,CAAA;AAAA,MAAG,CAAA,CAAA,MAAQ;AAAA,MAAe;AAAA,IAC1E;AAAA,GACF;AACF","file":"chunk-DCSOQH2N.js","sourcesContent":["/**\n * libav.js HTTP block reader.\n *\n * Wraps `libav.mkblockreaderdev` + `libav.onblockread` +\n * `libav.ff_block_reader_dev_send` so that libav can demux a remote file\n * via HTTP Range requests instead of needing the entire file in memory.\n *\n * Used by the AVI/ASF/FLV probe path and the libav-backed playback /\n * conversion strategies whenever the source is a URL.\n *\n * Design notes:\n *\n * - **Range support detection** is done by issuing a `Range: bytes=0-0`\n * probe request. We do NOT trust `Accept-Ranges` headers — some servers\n * support ranges but don't advertise them, others advertise but don't.\n * The probe request is the canonical signal: a `206 Partial Content`\n * response means we can stream; anything else fails fast with a clear\n * error. We never silently fall back to a full download.\n *\n * - **Sequential reads.** libav can issue overlapping `onblockread`\n * callbacks. The reader serializes them through a single async queue\n * so a) `ff_block_reader_dev_send` calls are well-ordered and b) we\n * never have two in-flight fetches for unrelated reads. Throughput\n * for v1 is \"good enough\"; correctness > parallelism.\n *\n * - **In-flight dedup.** If libav asks for `(pos=1000, len=4096)` twice\n * in a row before the first request resolves, the second call awaits\n * the first instead of issuing a duplicate fetch. This handles the\n * \"demuxer re-reads the same header\" pattern cheaply.\n *\n * - **Read-ahead clamp.** libav's requested length is doubled, then\n * clamped to `[256 KB, 1 MB]`. Small reads get amortized; pathological\n * large requests don't OOM us.\n *\n * - **Last-block cache.** Only the most-recent fetched block is kept.\n * Re-fetches via Range are cheap; an LRU cache is post-1.0.\n *\n * - **Safe detach.** `detach()` clears `libav.onblockread`, sets a\n * destroyed flag, and ignores any in-flight fetch resolutions so we\n * never write into a torn-down demuxer.\n */\n\nconst MIN_READ = 256 * 1024;\nconst MAX_READ = 1 * 1024 * 1024;\n\ninterface LibavLike {\n mkblockreaderdev(name: string, size: number): Promise<void>;\n unlinkreadaheadfile(name: string): Promise<void>;\n ff_block_reader_dev_send(\n name: string,\n pos: number,\n data: Uint8Array | null,\n opts?: { errorCode?: number; error?: unknown },\n ): Promise<void>;\n onblockread?: (filename: string, pos: number, length: number) => void;\n}\n\nexport interface LibavHttpReaderHandle {\n /** Total file size (bytes) reported by the server. */\n readonly size: number;\n /** Always `\"http-range\"` for now. Reserved for future transports. */\n readonly transport: \"http-range\";\n /** Stop serving reads, clear the libav callback, and ignore late fetches. */\n detach(): Promise<void>;\n}\n\nexport interface AttachLibavHttpReaderOptions {\n /** Optional `RequestInit` extras (mode, credentials, headers, etc.). */\n requestInit?: RequestInit;\n /** Override fetch (for testing). Defaults to globalThis.fetch. */\n fetchFn?: typeof fetch;\n}\n\n/**\n * Result of preparing a libav-readable file from a normalized source.\n * Either an in-memory Blob (created via `mkreadaheadfile`) or a streaming\n * HTTP reader (created via `attachLibavHttpReader`). Callers should\n * `await detach()` when done so resources are cleaned up symmetrically.\n */\nexport interface LibavInputHandle {\n /** The virtual filename libav sees — pass to `ff_init_demuxer_file`. */\n readonly filename: string;\n /** \"blob\" for in-memory, \"http-range\" for streaming URL. */\n readonly transport: \"blob\" | \"http-range\";\n /** Total file size in bytes if known, otherwise undefined. */\n readonly size: number | undefined;\n /** Tear down the virtual file (and any HTTP reader state). */\n detach(): Promise<void>;\n}\n\ninterface LibavLikeWithBlob extends LibavLike {\n mkreadaheadfile(name: string, blob: Blob): Promise<void>;\n}\n\n/**\n * Convenience for the libav-backed strategies. Given a normalized source,\n * either creates an in-memory readahead file (for Blob inputs) or attaches\n * the HTTP block reader (for URL inputs). Returns a handle the caller\n * should detach when done.\n */\nexport async function prepareLibavInput(\n libav: LibavLikeWithBlob,\n filename: string,\n source: import(\"./source.js\").NormalizedSource,\n transport?: import(\"../types.js\").TransportConfig,\n): Promise<LibavInputHandle> {\n if (source.kind === \"url\") {\n const handle = await attachLibavHttpReader(libav, filename, source.url, {\n requestInit: transport?.requestInit,\n fetchFn: transport?.fetchFn,\n });\n return {\n filename,\n transport: \"http-range\",\n size: handle.size,\n detach: () => handle.detach(),\n };\n }\n await libav.mkreadaheadfile(filename, source.blob);\n return {\n filename,\n transport: \"blob\",\n size: source.byteLength,\n detach: async () => {\n try { await libav.unlinkreadaheadfile(filename); } catch { /* ignore */ }\n },\n };\n}\n\n/**\n * Attach an HTTP block reader to a libav.js instance. After this resolves,\n * libav can `ff_init_demuxer_file(filename)` and the demuxer will pull\n * bytes via Range requests instead of needing a Blob.\n *\n * Fails fast (before any libav setup) if the server doesn't support\n * Range requests.\n */\nexport async function attachLibavHttpReader(\n libav: LibavLike,\n filename: string,\n url: string,\n options: AttachLibavHttpReaderOptions = {},\n): Promise<LibavHttpReaderHandle> {\n const fetchFn = options.fetchFn ?? fetch;\n\n // 1. Probe the server with a single-byte Range request.\n let probeRes: Response;\n try {\n probeRes = await fetchFn(url, {\n ...options.requestInit,\n headers: {\n ...(options.requestInit?.headers ?? {}),\n Range: \"bytes=0-0\",\n },\n });\n } catch (err) {\n throw new Error(\n `libav HTTP reader: failed to reach ${url}: ${(err as Error).message}`,\n );\n }\n if (probeRes.status !== 206) {\n // 200 means the server ignored Range and would have sent the whole\n // file. We refuse to silently slurp gigabytes.\n throw new Error(\n `libav HTTP reader: ${url} does not support HTTP Range requests ` +\n `(server returned ${probeRes.status} for a Range probe; need 206 Partial Content). ` +\n `Remote AVI/ASF/FLV playback requires a server that honors byte-range requests.`,\n );\n }\n\n // 2. Parse total file size from Content-Range: \"bytes 0-0/12345678\"\n const contentRange = probeRes.headers.get(\"content-range\") ?? \"\";\n const sizeMatch = contentRange.match(/\\/(\\d+)$/);\n if (!sizeMatch) {\n throw new Error(\n `libav HTTP reader: ${url} returned 206 but no parseable Content-Range header (got: \"${contentRange}\")`,\n );\n }\n const size = parseInt(sizeMatch[1], 10);\n if (!Number.isFinite(size) || size <= 0) {\n throw new Error(\n `libav HTTP reader: ${url} reported invalid file size ${size}`,\n );\n }\n\n // Drain the probe body so the connection can be reused.\n try { await probeRes.arrayBuffer(); } catch { /* ignore */ }\n\n // 3. Create the virtual file libav will read from.\n await libav.mkblockreaderdev(filename, size);\n\n // ── State ───────────────────────────────────────────────────────────────\n\n let detached = false;\n // Most-recently fetched block. Cached so re-reads of the same region\n // (e.g. demuxer re-walks the header) don't issue another HTTP request.\n let cached: { pos: number; bytes: Uint8Array } | null = null;\n // The currently in-flight fetch, if any. Used both for serialization\n // (we await this before starting another) and for in-flight dedup.\n let inflight: Promise<void> | null = null;\n\n function clampReadLength(requested: number): number {\n const doubled = requested * 2;\n if (doubled < MIN_READ) return MIN_READ;\n if (doubled > MAX_READ) return MAX_READ;\n return doubled;\n }\n\n /** True if the cached block fully covers `[pos, pos+length)`. */\n function cacheCovers(pos: number, length: number): boolean {\n if (!cached) return false;\n return pos >= cached.pos && pos + length <= cached.pos + cached.bytes.byteLength;\n }\n\n /** Slice the requested window out of the cached block. */\n function sliceFromCache(pos: number, length: number): Uint8Array {\n if (!cached) throw new Error(\"sliceFromCache called with no cache\");\n const offset = pos - cached.pos;\n return cached.bytes.subarray(offset, offset + length);\n }\n\n /** Fetch one Range and update the cache. */\n async function fetchRange(pos: number, length: number): Promise<Uint8Array> {\n const end = Math.min(pos + length - 1, size - 1);\n const res = await fetchFn(url, {\n ...options.requestInit,\n headers: {\n ...(options.requestInit?.headers ?? {}),\n Range: `bytes=${pos}-${end}`,\n },\n });\n if (res.status !== 206 && res.status !== 200) {\n throw new Error(\n `libav HTTP reader: Range request bytes=${pos}-${end} returned ${res.status}`,\n );\n }\n const buf = new Uint8Array(await res.arrayBuffer());\n cached = { pos, bytes: buf };\n return buf;\n }\n\n /**\n * Handle a single libav read request. Serializes against any in-flight\n * read by chaining off `inflight`. Honors `detached` at every async\n * boundary so a torn-down reader never writes back into libav.\n */\n async function handleRead(name: string, pos: number, length: number): Promise<void> {\n // Wait for any preceding read to finish so we don't interleave.\n if (inflight) {\n try { await inflight; } catch { /* ignore — that read's own caller handled it */ }\n }\n if (detached) return;\n\n // Cache hit — reply directly without a network round-trip.\n if (cacheCovers(pos, length)) {\n const data = sliceFromCache(pos, length);\n try { await libav.ff_block_reader_dev_send(name, pos, data); } catch { /* ignore — libav may have torn down */ }\n return;\n }\n\n // Cache miss — fetch via Range. Read-ahead amortizes small reads.\n const fetchLen = clampReadLength(length);\n const fetched = (async () => {\n try {\n const buf = await fetchRange(pos, fetchLen);\n if (detached) return;\n // Slice exactly what libav asked for and send it back.\n const reply = buf.subarray(0, Math.min(length, buf.byteLength));\n try { await libav.ff_block_reader_dev_send(name, pos, reply); } catch { /* ignore */ }\n } catch (err) {\n if (detached) return;\n // Signal EOF + error code to libav so the demuxer surfaces it.\n try {\n await libav.ff_block_reader_dev_send(name, pos, null, {\n error: err,\n });\n } catch { /* ignore */ }\n }\n })();\n inflight = fetched;\n try { await fetched; } finally { if (inflight === fetched) inflight = null; }\n }\n\n // 4. Wire the callback. The signature accepts `(name, pos, length)` and\n // we hand it to handleRead which does all the work asynchronously.\n // Note: libav.js dispatches this synchronously from a worker message,\n // so we kick off handleRead but don't await — the queue inside handleRead\n // serializes things.\n const previousCallback = libav.onblockread;\n libav.onblockread = (name: string, pos: number, length: number) => {\n if (detached || name !== filename) {\n // Forward to any previous callback (e.g. another reader on the same\n // libav instance). This is rare in practice but cheap to support.\n previousCallback?.(name, pos, length);\n return;\n }\n void handleRead(name, pos, length);\n };\n\n return {\n size,\n transport: \"http-range\",\n async detach() {\n if (detached) return;\n detached = true;\n // Restore the previous callback (if any) so we don't break unrelated\n // readers on the same libav instance.\n libav.onblockread = previousCallback;\n // Wait for the last in-flight read to settle so we don't tear down\n // the virtual file while libav is still expecting a response.\n if (inflight) {\n try { await inflight; } catch { /* ignore */ }\n }\n // Drop the cache and unlink the virtual file.\n cached = null;\n try { await libav.unlinkreadaheadfile(filename); } catch { /* ignore */ }\n },\n };\n}\n"]}
@@ -0,0 +1,20 @@
1
+ 'use strict';
2
+
3
+ // src/strategies/fallback/variant-routing.ts
4
+ var LEGACY_CONTAINERS = /* @__PURE__ */ new Set(["avi", "asf", "flv"]);
5
+ var WEBCODECS_AUDIO = /* @__PURE__ */ new Set(["aac", "mp3", "opus", "vorbis", "flac"]);
6
+ var WEBCODECS_VIDEO = /* @__PURE__ */ new Set(["h264", "h265", "vp8", "vp9", "av1"]);
7
+ function pickLibavVariant(ctx) {
8
+ if (LEGACY_CONTAINERS.has(ctx.container)) return "avbridge";
9
+ for (const v of ctx.videoTracks) {
10
+ if (!WEBCODECS_VIDEO.has(v.codec)) return "avbridge";
11
+ }
12
+ for (const a of ctx.audioTracks) {
13
+ if (!WEBCODECS_AUDIO.has(a.codec)) return "avbridge";
14
+ }
15
+ return "webcodecs";
16
+ }
17
+
18
+ exports.pickLibavVariant = pickLibavVariant;
19
+ //# sourceMappingURL=chunk-F3LQJKXK.cjs.map
20
+ //# sourceMappingURL=chunk-F3LQJKXK.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/strategies/fallback/variant-routing.ts"],"names":[],"mappings":";;;AAmBA,IAAM,oCAAoB,IAAI,GAAA,CAAI,CAAC,KAAA,EAAO,KAAA,EAAO,KAAK,CAAC,CAAA;AAIvD,IAAM,eAAA,uBAAsB,GAAA,CAAgB,CAAC,OAAO,KAAA,EAAO,MAAA,EAAQ,QAAA,EAAU,MAAM,CAAC,CAAA;AACpF,IAAM,eAAA,uBAAsB,GAAA,CAAgB,CAAC,QAAQ,MAAA,EAAQ,KAAA,EAAO,KAAA,EAAO,KAAK,CAAC,CAAA;AAE1E,SAAS,iBAAiB,GAAA,EAAiC;AAChE,EAAA,IAAI,iBAAA,CAAkB,GAAA,CAAI,GAAA,CAAI,SAAS,GAAG,OAAO,UAAA;AACjD,EAAA,KAAA,MAAW,CAAA,IAAK,IAAI,WAAA,EAAa;AAE/B,IAAA,IAAI,CAAC,eAAA,CAAgB,GAAA,CAAI,CAAA,CAAE,KAAK,GAAG,OAAO,UAAA;AAAA,EAC5C;AACA,EAAA,KAAA,MAAW,CAAA,IAAK,IAAI,WAAA,EAAa;AAC/B,IAAA,IAAI,CAAC,eAAA,CAAgB,GAAA,CAAI,CAAA,CAAE,KAAK,GAAG,OAAO,UAAA;AAAA,EAC5C;AACA,EAAA,OAAO,WAAA;AACT","file":"chunk-F3LQJKXK.cjs","sourcesContent":["import type { MediaContext, AudioCodec, VideoCodec } from \"../../types.js\";\nimport type { LibavVariant } from \"./libav-loader.js\";\n\n/**\n * Decide which libav.js variant to load for a given media context.\n *\n * - **webcodecs** (~5 MB, npm) — modern formats only, designed for the\n * WebCodecs bridge. Used when the codec is browser-supported and we just\n * need libav.js for demuxing or as a parser source.\n *\n * - **avbridge** (custom build, vendor/libav/) — has the AVI/ASF/FLV demuxers\n * and the legacy decoders (WMV3, MPEG-4 Part 2, VC-1, MS-MPEG4 v1/2/3,\n * AC-3, WMA*). Required for any of those formats; the npm variants ship\n * none of them.\n *\n * Rule: pick \"avbridge\" if either the container or any codec is one only the\n * custom build can handle. Otherwise pick \"webcodecs\".\n */\n\nconst LEGACY_CONTAINERS = new Set([\"avi\", \"asf\", \"flv\"]);\n\n/** Codecs the webcodecs variant can handle (native browser codecs only).\n * Anything not in these sets needs the custom avbridge variant. */\nconst WEBCODECS_AUDIO = new Set<AudioCodec>([\"aac\", \"mp3\", \"opus\", \"vorbis\", \"flac\"]);\nconst WEBCODECS_VIDEO = new Set<VideoCodec>([\"h264\", \"h265\", \"vp8\", \"vp9\", \"av1\"]);\n\nexport function pickLibavVariant(ctx: MediaContext): LibavVariant {\n if (LEGACY_CONTAINERS.has(ctx.container)) return \"avbridge\";\n for (const v of ctx.videoTracks) {\n // Any codec the webcodecs variant can't handle → need avbridge\n if (!WEBCODECS_VIDEO.has(v.codec)) return \"avbridge\";\n }\n for (const a of ctx.audioTracks) {\n if (!WEBCODECS_AUDIO.has(a.codec)) return \"avbridge\";\n }\n return \"webcodecs\";\n}\n"]}
@@ -0,0 +1,200 @@
1
+ // src/util/debug.ts
2
+ function isDebugEnabled() {
3
+ if (typeof globalThis === "undefined") return false;
4
+ const g = globalThis;
5
+ if (g.AVBRIDGE_DEBUG === true) return true;
6
+ if (typeof location !== "undefined" && typeof URLSearchParams !== "undefined") {
7
+ try {
8
+ const p = new URLSearchParams(location.search);
9
+ if (p.has("avbridge_debug")) {
10
+ g.AVBRIDGE_DEBUG = true;
11
+ return true;
12
+ }
13
+ } catch {
14
+ }
15
+ }
16
+ return false;
17
+ }
18
+ function fmt(tag) {
19
+ return `[avbridge:${tag}]`;
20
+ }
21
+ var dbg = {
22
+ /** Verbose — only when debug is enabled. The hot-path normal case. */
23
+ info(tag, ...args) {
24
+ if (isDebugEnabled()) console.info(fmt(tag), ...args);
25
+ },
26
+ /** Warning — only when debug is enabled. Non-fatal oddities. */
27
+ warn(tag, ...args) {
28
+ if (isDebugEnabled()) console.warn(fmt(tag), ...args);
29
+ },
30
+ /**
31
+ * Self-diagnosis warning. **Always** emits regardless of debug flag.
32
+ * Use this only for conditions that mean something is actually wrong
33
+ * or degraded — not for routine chatter.
34
+ */
35
+ diag(tag, ...args) {
36
+ console.warn(fmt(tag), ...args);
37
+ },
38
+ /**
39
+ * Timing helper: wraps an async call and logs its elapsed time when
40
+ * debug is on. The callback runs whether debug is on or off — this is
41
+ * just for the `dbg.info` at the end.
42
+ *
43
+ * Also unconditionally fires `dbg.diag` if the elapsed time exceeds
44
+ * `slowMs`, so "the bootstrap took 8 seconds" shows up even without
45
+ * debug mode enabled.
46
+ */
47
+ async timed(tag, label, slowMs, fn) {
48
+ const start = performance.now();
49
+ try {
50
+ const result = await fn();
51
+ const elapsed = performance.now() - start;
52
+ if (isDebugEnabled()) {
53
+ console.info(fmt(tag), `${label} ${elapsed.toFixed(0)}ms`);
54
+ }
55
+ if (elapsed > slowMs) {
56
+ console.warn(
57
+ fmt(tag),
58
+ `${label} took ${elapsed.toFixed(0)}ms (>${slowMs}ms expected) \u2014 this is unusually slow; possible causes: ${hintForTag(tag)}`
59
+ );
60
+ }
61
+ return result;
62
+ } catch (err) {
63
+ const elapsed = performance.now() - start;
64
+ console.warn(
65
+ fmt(tag),
66
+ `${label} FAILED after ${elapsed.toFixed(0)}ms:`,
67
+ err
68
+ );
69
+ throw err;
70
+ }
71
+ }
72
+ };
73
+ function hintForTag(tag) {
74
+ switch (tag) {
75
+ case "probe":
76
+ return "slow network (range request), large sniff window, or libav cold-start";
77
+ case "libav-load":
78
+ return "large .wasm download, misconfigured AVBRIDGE_LIBAV_BASE, or server-side MIME type";
79
+ case "bootstrap":
80
+ return "probe+classify+strategy-init chain; enable AVBRIDGE_DEBUG for a phase breakdown";
81
+ case "cold-start":
82
+ return "decoder is producing output slower than realtime \u2014 check framesDecoded in getDiagnostics()";
83
+ default:
84
+ return "unknown stage \u2014 enable globalThis.AVBRIDGE_DEBUG for more detail";
85
+ }
86
+ }
87
+
88
+ // src/strategies/fallback/libav-loader.ts
89
+ var cache = /* @__PURE__ */ new Map();
90
+ function cacheKey(variant, threads) {
91
+ return `${variant}:${threads ? "thr" : "wasm"}`;
92
+ }
93
+ function loadLibav(variant = "webcodecs", opts = {}) {
94
+ const env = globalThis;
95
+ const wantThreads = opts.threads !== void 0 ? opts.threads : env.AVBRIDGE_LIBAV_THREADS === true;
96
+ const key = cacheKey(variant, wantThreads);
97
+ let entry = cache.get(key);
98
+ if (!entry) {
99
+ entry = loadVariant(variant, wantThreads);
100
+ cache.set(key, entry);
101
+ }
102
+ return entry;
103
+ }
104
+ async function loadVariant(variant, wantThreads) {
105
+ return dbg.timed(
106
+ "libav-load",
107
+ `load "${variant}" (threads=${wantThreads})`,
108
+ 5e3,
109
+ () => loadVariantInner(variant, wantThreads)
110
+ );
111
+ }
112
+ async function loadVariantInner(variant, wantThreads) {
113
+ const key = cacheKey(variant, wantThreads);
114
+ const base = `${libavBaseUrl()}/${variant}`;
115
+ const variantUrl = `${base}/libav-${variant}.mjs`;
116
+ dbg.info("libav-load", `fetching ${variantUrl}`);
117
+ if (typeof fetch === "function") {
118
+ try {
119
+ const head = await fetch(variantUrl, { method: "GET", headers: { Range: "bytes=0-0" } });
120
+ if (!head.ok && head.status !== 206) {
121
+ throw new Error(
122
+ `HTTP ${head.status} ${head.statusText} \u2014 check that libav files are served at ${base}/ (override via globalThis.AVBRIDGE_LIBAV_BASE)`
123
+ );
124
+ }
125
+ try {
126
+ await head.arrayBuffer();
127
+ } catch {
128
+ }
129
+ } catch (err) {
130
+ cache.delete(key);
131
+ throw chain(
132
+ `libav.js "${variant}" variant not reachable at ${variantUrl}`,
133
+ err
134
+ );
135
+ }
136
+ }
137
+ let mod;
138
+ try {
139
+ const imported = await import(
140
+ /* @vite-ignore */
141
+ variantUrl
142
+ );
143
+ if (!imported || typeof imported.LibAV !== "function") {
144
+ throw new Error(`module at ${variantUrl} did not export LibAV`);
145
+ }
146
+ mod = imported;
147
+ } catch (err) {
148
+ cache.delete(key);
149
+ const hint = variant === "avbridge" ? `The "avbridge" variant is a custom local build. Run \`./scripts/build-libav.sh\` to produce it (requires Emscripten; ~15-30 min the first time).` : `Make sure the variant files are present at ${base}/ (set globalThis.AVBRIDGE_LIBAV_BASE to override the default lookup path).`;
150
+ throw new Error(
151
+ `failed to load libav.js "${variant}" variant from ${variantUrl}. ${hint} Original error: ${err.message || String(err)}`
152
+ );
153
+ }
154
+ try {
155
+ const inst = await mod.LibAV(buildOpts(base, wantThreads));
156
+ await silenceLibavLogs(inst);
157
+ return inst;
158
+ } catch (err) {
159
+ cache.delete(key);
160
+ throw chain(`LibAV() factory failed for "${variant}" variant (threads=${wantThreads})`, err);
161
+ }
162
+ }
163
+ async function silenceLibavLogs(inst) {
164
+ try {
165
+ const setLevel = inst.av_log_set_level;
166
+ if (typeof setLevel === "function") {
167
+ const quiet = inst.AV_LOG_QUIET ?? -8;
168
+ await setLevel(quiet);
169
+ }
170
+ } catch {
171
+ }
172
+ }
173
+ function buildOpts(base, wantThreads) {
174
+ return {
175
+ base,
176
+ nothreads: !wantThreads,
177
+ yesthreads: wantThreads
178
+ };
179
+ }
180
+ function libavBaseUrl() {
181
+ const override = typeof globalThis !== "undefined" ? globalThis.AVBRIDGE_LIBAV_BASE : void 0;
182
+ if (override) return override;
183
+ try {
184
+ return new URL("../vendor/libav", import.meta.url).href;
185
+ } catch {
186
+ if (typeof location !== "undefined" && location.protocol.startsWith("http")) {
187
+ return `${location.origin}/libav`;
188
+ }
189
+ return "/libav";
190
+ }
191
+ }
192
+ function chain(message, err) {
193
+ const inner = err instanceof Error ? err.message : String(err);
194
+ console.error(`[avbridge] ${message}:`, err);
195
+ return new Error(`${message}: ${inner || "(no message \u2014 see browser console)"}`);
196
+ }
197
+
198
+ export { dbg, loadLibav };
199
+ //# sourceMappingURL=chunk-IAYKFGFG.js.map
200
+ //# sourceMappingURL=chunk-IAYKFGFG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/util/debug.ts","../src/strategies/fallback/libav-loader.ts"],"names":[],"mappings":";AA8BA,SAAS,cAAA,GAA0B;AACjC,EAAA,IAAI,OAAO,UAAA,KAAe,WAAA,EAAa,OAAO,KAAA;AAC9C,EAAA,MAAM,CAAA,GAAI,UAAA;AACV,EAAA,IAAI,CAAA,CAAE,cAAA,KAAmB,IAAA,EAAM,OAAO,IAAA;AAItC,EAAA,IAAI,OAAO,QAAA,KAAa,WAAA,IAAe,OAAO,oBAAoB,WAAA,EAAa;AAC7E,IAAA,IAAI;AACF,MAAA,MAAM,CAAA,GAAI,IAAI,eAAA,CAAgB,QAAA,CAAS,MAAM,CAAA;AAC7C,MAAA,IAAI,CAAA,CAAE,GAAA,CAAI,gBAAgB,CAAA,EAAG;AAC3B,QAAA,CAAA,CAAE,cAAA,GAAiB,IAAA;AACnB,QAAA,OAAO,IAAA;AAAA,MACT;AAAA,IACF,CAAA,CAAA,MAAQ;AAAA,IAAe;AAAA,EACzB;AACA,EAAA,OAAO,KAAA;AACT;AAEA,SAAS,IAAI,GAAA,EAAqB;AAChC,EAAA,OAAO,aA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AAQ,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAE7D,EAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,WAAA,EAAc,OAAO,CAAA,CAAA,CAAA,EAAK,GAAG,CAAA;AAC3C,EAAA,OAAO,IAAI,KAAA,CAAM,CAAA,EAAG,OAAO,CAAA,EAAA,EAAK,KAAA,IAAS,yCAAoC,CAAA,CAAE,CAAA;AACjF","file":"chunk-IAYKFGFG.js","sourcesContent":["/**\n * Debug + self-diagnosis helper.\n *\n * avbridge has a lot of async stages (probe → classify → libav load →\n * strategy.execute → decoder pump → cold-start gate → first paint) and\n * when something's slow or wrong the symptom — \"it hangs\", \"it stutters\",\n * \"it plays audio without video\" — is usually nowhere near the actual\n * cause. This module gives us two things:\n *\n * 1. **Gated verbose logging.** `dbg.info(tag, ...)` etc. are no-ops\n * unless the consumer sets `globalThis.AVBRIDGE_DEBUG = true` (or\n * uses the matching `?avbridge_debug` URL search param at dev time).\n * When enabled, every log is prefixed with `[avbridge:<tag>]` so the\n * console is filterable.\n *\n * 2. **Unconditional self-diagnosis.** `dbg.warnIf(cond, tag, ...)`\n * always fires when a suspicious condition is detected, even with\n * debug off. These are the things we *know* mean something is\n * broken or degraded and the user would want to know about — e.g.\n * the cold-start gate timing out, the decoder running slower than\n * realtime, a libav variant taking longer to load than any network\n * should take, >20% of packets getting rejected.\n *\n * The guiding principle: **if a symptom caused more than 10 minutes of\n * human debugging once, add a targeted warning so the next instance\n * self-identifies in the console.** This module is where those\n * warnings live.\n */\n\n/** Read the debug flag fresh on every call so it's runtime-toggleable. */\nfunction isDebugEnabled(): boolean {\n if (typeof globalThis === \"undefined\") return false;\n const g = globalThis as { AVBRIDGE_DEBUG?: unknown };\n if (g.AVBRIDGE_DEBUG === true) return true;\n // Convenience: if running in a browser with a `?avbridge_debug` search\n // param, flip the flag on automatically. Useful for demos and quick\n // user reproduction without editing code.\n if (typeof location !== \"undefined\" && typeof URLSearchParams !== \"undefined\") {\n try {\n const p = new URLSearchParams(location.search);\n if (p.has(\"avbridge_debug\")) {\n g.AVBRIDGE_DEBUG = true;\n return true;\n }\n } catch { /* ignore */ }\n }\n return false;\n}\n\nfunction fmt(tag: string): string {\n return `[avbridge:${tag}]`;\n}\n\n/* eslint-disable no-console */\n\nexport const dbg = {\n /** Verbose — only when debug is enabled. The hot-path normal case. */\n info(tag: string, ...args: unknown[]): void {\n if (isDebugEnabled()) console.info(fmt(tag), ...args);\n },\n\n /** Warning — only when debug is enabled. Non-fatal oddities. */\n warn(tag: string, ...args: unknown[]): void {\n if (isDebugEnabled()) console.warn(fmt(tag), ...args);\n },\n\n /**\n * Self-diagnosis warning. **Always** emits regardless of debug flag.\n * Use this only for conditions that mean something is actually wrong\n * or degraded — not for routine chatter.\n */\n diag(tag: string, ...args: unknown[]): void {\n console.warn(fmt(tag), ...args);\n },\n\n /**\n * Timing helper: wraps an async call and logs its elapsed time when\n * debug is on. The callback runs whether debug is on or off — this is\n * just for the `dbg.info` at the end.\n *\n * Also unconditionally fires `dbg.diag` if the elapsed time exceeds\n * `slowMs`, so \"the bootstrap took 8 seconds\" shows up even without\n * debug mode enabled.\n */\n async timed<T>(\n tag: string,\n label: string,\n slowMs: number,\n fn: () => Promise<T>,\n ): Promise<T> {\n const start = performance.now();\n try {\n const result = await fn();\n const elapsed = performance.now() - start;\n if (isDebugEnabled()) {\n console.info(fmt(tag), `${label} ${elapsed.toFixed(0)}ms`);\n }\n if (elapsed > slowMs) {\n console.warn(\n fmt(tag),\n `${label} took ${elapsed.toFixed(0)}ms (>${slowMs}ms expected) — ` +\n `this is unusually slow; possible causes: ${hintForTag(tag)}`,\n );\n }\n return result;\n } catch (err) {\n const elapsed = performance.now() - start;\n console.warn(\n fmt(tag),\n `${label} FAILED after ${elapsed.toFixed(0)}ms:`,\n err,\n );\n throw err;\n }\n },\n};\n\nfunction hintForTag(tag: string): string {\n switch (tag) {\n case \"probe\":\n return \"slow network (range request), large sniff window, or libav cold-start\";\n case \"libav-load\":\n return \"large .wasm download, misconfigured AVBRIDGE_LIBAV_BASE, or server-side MIME type\";\n case \"bootstrap\":\n return \"probe+classify+strategy-init chain; enable AVBRIDGE_DEBUG for a phase breakdown\";\n case \"cold-start\":\n return \"decoder is producing output slower than realtime — check framesDecoded in getDiagnostics()\";\n default:\n return \"unknown stage — enable globalThis.AVBRIDGE_DEBUG for more detail\";\n }\n}\n","/**\n * Lazy libav.js loader supporting multiple variants.\n *\n * avbridge recognises three libav variants:\n *\n * - **webcodecs** — npm `@libav.js/variant-webcodecs`, ~5 MB. Modern formats\n * only (mp4/mkv/webm/ogg/wav/...) — designed to bridge to WebCodecs.\n *\n * - **default** — npm `@libav.js/variant-default`, ~12 MB. Audio-only build\n * (Opus, FLAC, WAV) despite the name. Useful for audio fallback.\n *\n * - **avbridge** — a custom build produced by `scripts/build-libav.sh` and\n * landing in `vendor/libav/`. Includes the AVI/ASF/FLV/MKV demuxers plus\n * the legacy decoders (WMV3, MPEG-4 Part 2, MS-MPEG4 v1/2/3, VC-1, MPEG-1/2,\n * AC-3/E-AC-3, WMAv1/v2/Pro). This is the only variant that can read AVI;\n * the npm variants are intentionally minimal and ship none of the legacy\n * demuxers.\n *\n * Variant resolution always goes through a runtime URL + `/* @vite-ignore *\\/`\n * dynamic import. Static imports trigger Vite's optimized-deps pipeline,\n * which rewrites `import.meta.url` away from the real `dist/` directory and\n * breaks libav's sibling-binary loading.\n */\n\nimport { dbg } from \"../../util/debug.js\";\n\nexport type LibavVariant = \"webcodecs\" | \"default\" | \"avbridge\";\n\nexport interface LoadLibavOptions {\n /**\n * Force threading on/off for this load. If unspecified, defaults to\n * \"true if `crossOriginIsolated`, otherwise false\". Some libav.js code\n * paths (notably the cross-thread reader-device protocol used during\n * `avformat_find_stream_info` for AVI) are unreliable in threaded mode,\n * so probing forces this to `false` while decode keeps it default.\n */\n threads?: boolean;\n}\n\n// Cache key includes both variant and threading mode so probe and decode\n// can run different libav instances of the same variant.\nconst cache: Map<string, Promise<LibavInstance>> = new Map();\n\nfunction cacheKey(variant: LibavVariant, threads: boolean): string {\n return `${variant}:${threads ? \"thr\" : \"wasm\"}`;\n}\n\n/**\n * Load (and cache) a libav.js variant. Pass `\"webcodecs\"` for the small\n * default; pass `\"default\"` for the audio fallback; pass `\"avbridge\"` for the\n * custom build that supports AVI/WMV/legacy codecs.\n */\nexport function loadLibav(\n variant: LibavVariant = \"webcodecs\",\n opts: LoadLibavOptions = {},\n): Promise<LibavInstance> {\n // Threading is OFF by default. The threaded libav.js variant is too\n // fragile in practice for our usage:\n // - Probe (`avformat_find_stream_info` for AVI) throws an `undefined`\n // exception out of `ff_init_demuxer_file`, apparently due to the\n // cross-thread reader-device protocol racing with the main thread.\n // - Decode hits a `TypeError: Cannot read properties of undefined\n // (reading 'apply')` inside libav.js's own worker message handler\n // within seconds of starting — a bug in libav.js's threaded message\n // dispatch that we can't fix from outside.\n //\n // Performance work for the fallback strategy needs to come from elsewhere\n // (WASM SIMD, OffscreenCanvas, larger decode batches) instead of libav's\n // pthreads. Threading can still be force-enabled with\n // `globalThis.AVBRIDGE_LIBAV_THREADS = true` for testing if libav.js fixes\n // those bugs in a future release.\n const env = globalThis as { AVBRIDGE_LIBAV_THREADS?: boolean };\n const wantThreads =\n opts.threads !== undefined\n ? opts.threads\n : env.AVBRIDGE_LIBAV_THREADS === true;\n\n const key = cacheKey(variant, wantThreads);\n let entry = cache.get(key);\n if (!entry) {\n entry = loadVariant(variant, wantThreads);\n cache.set(key, entry);\n }\n return entry;\n}\n\nasync function loadVariant(\n variant: LibavVariant,\n wantThreads: boolean,\n): Promise<LibavInstance> {\n return dbg.timed(\"libav-load\", `load \"${variant}\" (threads=${wantThreads})`, 5000, () =>\n loadVariantInner(variant, wantThreads),\n );\n}\n\nasync function loadVariantInner(\n variant: LibavVariant,\n wantThreads: boolean,\n): Promise<LibavInstance> {\n const key = cacheKey(variant, wantThreads);\n const base = `${libavBaseUrl()}/${variant}`;\n // The custom variant is named `libav-avbridge.mjs`; the npm variants follow\n // the same convention (`libav-webcodecs.mjs`, `libav-default.mjs`).\n const variantUrl = `${base}/libav-${variant}.mjs`;\n dbg.info(\"libav-load\", `fetching ${variantUrl}`);\n\n // Preflight HEAD-ish check: issue a bytes=0-0 range request so a missing\n // file fails fast with a clear error instead of hanging deep inside the\n // dynamic import or inside libav's own WASM instantiation. Surfaces the\n // most common mistake (\"libav base path is wrong\") in <100 ms instead of\n // an indeterminate stall.\n if (typeof fetch === \"function\") {\n try {\n const head = await fetch(variantUrl, { method: \"GET\", headers: { Range: \"bytes=0-0\" } });\n if (!head.ok && head.status !== 206) {\n throw new Error(\n `HTTP ${head.status} ${head.statusText} — check that libav files are served ` +\n `at ${base}/ (override via globalThis.AVBRIDGE_LIBAV_BASE)`,\n );\n }\n // Drain the tiny response so the connection can be reused.\n try { await head.arrayBuffer(); } catch { /* ignore */ }\n } catch (err) {\n cache.delete(key);\n throw chain(\n `libav.js \"${variant}\" variant not reachable at ${variantUrl}`,\n err,\n );\n }\n }\n\n let mod: LoadedVariant;\n try {\n // @ts-ignore runtime URL\n const imported: unknown = await import(/* @vite-ignore */ variantUrl);\n if (!imported || typeof (imported as { LibAV?: unknown }).LibAV !== \"function\") {\n throw new Error(`module at ${variantUrl} did not export LibAV`);\n }\n mod = imported as LoadedVariant;\n } catch (err) {\n cache.delete(key);\n const hint =\n variant === \"avbridge\"\n ? `The \"avbridge\" variant is a custom local build. Run \\`./scripts/build-libav.sh\\` ` +\n `to produce it (requires Emscripten; ~15-30 min the first time).`\n : `Make sure the variant files are present at ${base}/ (set ` +\n `globalThis.AVBRIDGE_LIBAV_BASE to override the default lookup path).`;\n throw new Error(\n `failed to load libav.js \"${variant}\" variant from ${variantUrl}. ${hint} ` +\n `Original error: ${(err as Error).message || String(err)}`,\n );\n }\n\n try {\n const inst = (await mod.LibAV(buildOpts(base, wantThreads))) as LibavInstance;\n await silenceLibavLogs(inst);\n return inst;\n } catch (err) {\n cache.delete(key);\n throw chain(`LibAV() factory failed for \"${variant}\" variant (threads=${wantThreads})`, err);\n }\n}\n\n/**\n * Lower libav's internal log level so the console doesn't get flooded with\n * `[mp3 @ ...] Header missing` and `Video uses a non-standard and wasteful\n * way to store B-frames` warnings on every legacy file. We still get any\n * actual JS-level errors via the normal Error path; this only affects\n * libav's own ffmpeg log channel.\n *\n * AV_LOG_QUIET = -8 (no output at all). If you want to keep fatal errors,\n * use AV_LOG_FATAL = 8 instead.\n */\nasync function silenceLibavLogs(inst: LibavInstance): Promise<void> {\n try {\n const setLevel = (inst as { av_log_set_level?: (n: number) => Promise<void> })\n .av_log_set_level;\n if (typeof setLevel === \"function\") {\n const quiet = (inst as { AV_LOG_QUIET?: number }).AV_LOG_QUIET ?? -8;\n await setLevel(quiet);\n }\n } catch {\n /* not fatal — verbose logs are noise, not an error */\n }\n}\n\nfunction buildOpts(base: string, wantThreads: boolean): Record<string, unknown> {\n // The wantThreads decision is made by `loadLibav()` so callers (probe,\n // decoder) can override per-load. Decode wants pthreads for speed; probe\n // forces them off because libav.js's cross-thread reader-device protocol\n // is unreliable mid-`avformat_find_stream_info` for some AVI files.\n return {\n base,\n nothreads: !wantThreads,\n yesthreads: wantThreads,\n };\n}\n\nfunction libavBaseUrl(): string {\n // Consumer override — the documented \"LGPL replaceability\" hook.\n // Setting `globalThis.AVBRIDGE_LIBAV_BASE = \"/my/path\"` lets anyone swap\n // in a different libav build (custom fragments, security patches, etc.)\n // without rebuilding avbridge.\n const override =\n typeof globalThis !== \"undefined\"\n ? (globalThis as { AVBRIDGE_LIBAV_BASE?: string }).AVBRIDGE_LIBAV_BASE\n : undefined;\n if (override) return override;\n\n // Default: resolve relative to this module's URL. When avbridge is installed\n // under `node_modules/avbridge/`, this module lives at `dist/chunk-*.js` (or\n // `dist/element-browser.js` for the browser entry) and `../vendor/libav`\n // resolves to `node_modules/avbridge/vendor/libav`, where the build step\n // vendored every variant's binaries. That's the zero-config path.\n //\n // `import.meta.url` throws in some synthetic environments (CJS tests, some\n // SSR evaluators). If it fails, fall back to the legacy `/libav` path so\n // consumers who relied on the pre-2.1 behavior still work.\n try {\n return new URL(\"../vendor/libav\", import.meta.url).href;\n } catch {\n if (typeof location !== \"undefined\" && location.protocol.startsWith(\"http\")) {\n return `${location.origin}/libav`;\n }\n return \"/libav\";\n }\n}\n\nfunction chain(message: string, err: unknown): Error {\n const inner = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.error(`[avbridge] ${message}:`, err);\n return new Error(`${message}: ${inner || \"(no message — see browser console)\"}`);\n}\n\ninterface LoadedVariant {\n LibAV: (opts?: Record<string, unknown>) => Promise<Record<string, unknown>>;\n}\n\n/** Loose structural type — the AVI probe and the fallback decoder add fields. */\nexport type LibavInstance = Record<string, unknown> & {\n mkreadaheadfile(name: string, blob: Blob): Promise<void>;\n unlinkreadaheadfile(name: string): Promise<void>;\n};\n"]}
@@ -0,0 +1,204 @@
1
+ 'use strict';
2
+
3
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
4
+ // src/util/debug.ts
5
+ function isDebugEnabled() {
6
+ if (typeof globalThis === "undefined") return false;
7
+ const g = globalThis;
8
+ if (g.AVBRIDGE_DEBUG === true) return true;
9
+ if (typeof location !== "undefined" && typeof URLSearchParams !== "undefined") {
10
+ try {
11
+ const p = new URLSearchParams(location.search);
12
+ if (p.has("avbridge_debug")) {
13
+ g.AVBRIDGE_DEBUG = true;
14
+ return true;
15
+ }
16
+ } catch {
17
+ }
18
+ }
19
+ return false;
20
+ }
21
+ function fmt(tag) {
22
+ return `[avbridge:${tag}]`;
23
+ }
24
+ var dbg = {
25
+ /** Verbose — only when debug is enabled. The hot-path normal case. */
26
+ info(tag, ...args) {
27
+ if (isDebugEnabled()) console.info(fmt(tag), ...args);
28
+ },
29
+ /** Warning — only when debug is enabled. Non-fatal oddities. */
30
+ warn(tag, ...args) {
31
+ if (isDebugEnabled()) console.warn(fmt(tag), ...args);
32
+ },
33
+ /**
34
+ * Self-diagnosis warning. **Always** emits regardless of debug flag.
35
+ * Use this only for conditions that mean something is actually wrong
36
+ * or degraded — not for routine chatter.
37
+ */
38
+ diag(tag, ...args) {
39
+ console.warn(fmt(tag), ...args);
40
+ },
41
+ /**
42
+ * Timing helper: wraps an async call and logs its elapsed time when
43
+ * debug is on. The callback runs whether debug is on or off — this is
44
+ * just for the `dbg.info` at the end.
45
+ *
46
+ * Also unconditionally fires `dbg.diag` if the elapsed time exceeds
47
+ * `slowMs`, so "the bootstrap took 8 seconds" shows up even without
48
+ * debug mode enabled.
49
+ */
50
+ async timed(tag, label, slowMs, fn) {
51
+ const start = performance.now();
52
+ try {
53
+ const result = await fn();
54
+ const elapsed = performance.now() - start;
55
+ if (isDebugEnabled()) {
56
+ console.info(fmt(tag), `${label} ${elapsed.toFixed(0)}ms`);
57
+ }
58
+ if (elapsed > slowMs) {
59
+ console.warn(
60
+ fmt(tag),
61
+ `${label} took ${elapsed.toFixed(0)}ms (>${slowMs}ms expected) \u2014 this is unusually slow; possible causes: ${hintForTag(tag)}`
62
+ );
63
+ }
64
+ return result;
65
+ } catch (err) {
66
+ const elapsed = performance.now() - start;
67
+ console.warn(
68
+ fmt(tag),
69
+ `${label} FAILED after ${elapsed.toFixed(0)}ms:`,
70
+ err
71
+ );
72
+ throw err;
73
+ }
74
+ }
75
+ };
76
+ function hintForTag(tag) {
77
+ switch (tag) {
78
+ case "probe":
79
+ return "slow network (range request), large sniff window, or libav cold-start";
80
+ case "libav-load":
81
+ return "large .wasm download, misconfigured AVBRIDGE_LIBAV_BASE, or server-side MIME type";
82
+ case "bootstrap":
83
+ return "probe+classify+strategy-init chain; enable AVBRIDGE_DEBUG for a phase breakdown";
84
+ case "cold-start":
85
+ return "decoder is producing output slower than realtime \u2014 check framesDecoded in getDiagnostics()";
86
+ default:
87
+ return "unknown stage \u2014 enable globalThis.AVBRIDGE_DEBUG for more detail";
88
+ }
89
+ }
90
+
91
+ // src/strategies/fallback/libav-loader.ts
92
+ var cache = /* @__PURE__ */ new Map();
93
+ function cacheKey(variant, threads) {
94
+ return `${variant}:${threads ? "thr" : "wasm"}`;
95
+ }
96
+ function loadLibav(variant = "webcodecs", opts = {}) {
97
+ const env = globalThis;
98
+ const wantThreads = opts.threads !== void 0 ? opts.threads : env.AVBRIDGE_LIBAV_THREADS === true;
99
+ const key = cacheKey(variant, wantThreads);
100
+ let entry = cache.get(key);
101
+ if (!entry) {
102
+ entry = loadVariant(variant, wantThreads);
103
+ cache.set(key, entry);
104
+ }
105
+ return entry;
106
+ }
107
+ async function loadVariant(variant, wantThreads) {
108
+ return dbg.timed(
109
+ "libav-load",
110
+ `load "${variant}" (threads=${wantThreads})`,
111
+ 5e3,
112
+ () => loadVariantInner(variant, wantThreads)
113
+ );
114
+ }
115
+ async function loadVariantInner(variant, wantThreads) {
116
+ const key = cacheKey(variant, wantThreads);
117
+ const base = `${libavBaseUrl()}/${variant}`;
118
+ const variantUrl = `${base}/libav-${variant}.mjs`;
119
+ dbg.info("libav-load", `fetching ${variantUrl}`);
120
+ if (typeof fetch === "function") {
121
+ try {
122
+ const head = await fetch(variantUrl, { method: "GET", headers: { Range: "bytes=0-0" } });
123
+ if (!head.ok && head.status !== 206) {
124
+ throw new Error(
125
+ `HTTP ${head.status} ${head.statusText} \u2014 check that libav files are served at ${base}/ (override via globalThis.AVBRIDGE_LIBAV_BASE)`
126
+ );
127
+ }
128
+ try {
129
+ await head.arrayBuffer();
130
+ } catch {
131
+ }
132
+ } catch (err) {
133
+ cache.delete(key);
134
+ throw chain(
135
+ `libav.js "${variant}" variant not reachable at ${variantUrl}`,
136
+ err
137
+ );
138
+ }
139
+ }
140
+ let mod;
141
+ try {
142
+ const imported = await import(
143
+ /* @vite-ignore */
144
+ variantUrl
145
+ );
146
+ if (!imported || typeof imported.LibAV !== "function") {
147
+ throw new Error(`module at ${variantUrl} did not export LibAV`);
148
+ }
149
+ mod = imported;
150
+ } catch (err) {
151
+ cache.delete(key);
152
+ const hint = variant === "avbridge" ? `The "avbridge" variant is a custom local build. Run \`./scripts/build-libav.sh\` to produce it (requires Emscripten; ~15-30 min the first time).` : `Make sure the variant files are present at ${base}/ (set globalThis.AVBRIDGE_LIBAV_BASE to override the default lookup path).`;
153
+ throw new Error(
154
+ `failed to load libav.js "${variant}" variant from ${variantUrl}. ${hint} Original error: ${err.message || String(err)}`
155
+ );
156
+ }
157
+ try {
158
+ const inst = await mod.LibAV(buildOpts(base, wantThreads));
159
+ await silenceLibavLogs(inst);
160
+ return inst;
161
+ } catch (err) {
162
+ cache.delete(key);
163
+ throw chain(`LibAV() factory failed for "${variant}" variant (threads=${wantThreads})`, err);
164
+ }
165
+ }
166
+ async function silenceLibavLogs(inst) {
167
+ try {
168
+ const setLevel = inst.av_log_set_level;
169
+ if (typeof setLevel === "function") {
170
+ const quiet = inst.AV_LOG_QUIET ?? -8;
171
+ await setLevel(quiet);
172
+ }
173
+ } catch {
174
+ }
175
+ }
176
+ function buildOpts(base, wantThreads) {
177
+ return {
178
+ base,
179
+ nothreads: !wantThreads,
180
+ yesthreads: wantThreads
181
+ };
182
+ }
183
+ function libavBaseUrl() {
184
+ const override = typeof globalThis !== "undefined" ? globalThis.AVBRIDGE_LIBAV_BASE : void 0;
185
+ if (override) return override;
186
+ try {
187
+ return new URL("../vendor/libav", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-NNVOHKXJ.cjs', document.baseURI).href))).href;
188
+ } catch {
189
+ if (typeof location !== "undefined" && location.protocol.startsWith("http")) {
190
+ return `${location.origin}/libav`;
191
+ }
192
+ return "/libav";
193
+ }
194
+ }
195
+ function chain(message, err) {
196
+ const inner = err instanceof Error ? err.message : String(err);
197
+ console.error(`[avbridge] ${message}:`, err);
198
+ return new Error(`${message}: ${inner || "(no message \u2014 see browser console)"}`);
199
+ }
200
+
201
+ exports.dbg = dbg;
202
+ exports.loadLibav = loadLibav;
203
+ //# sourceMappingURL=chunk-NNVOHKXJ.cjs.map
204
+ //# sourceMappingURL=chunk-NNVOHKXJ.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/util/debug.ts","../src/strategies/fallback/libav-loader.ts"],"names":[],"mappings":";;;;AA8BA,SAAS,cAAA,GAA0B;AACjC,EAAA,IAAI,OAAO,UAAA,KAAe,WAAA,EAAa,OAAO,KAAA;AAC9C,EAAA,MAAM,CAAA,GAAI,UAAA;AACV,EAAA,IAAI,CAAA,CAAE,cAAA,KAAmB,IAAA,EAAM,OAAO,IAAA;AAItC,EAAA,IAAI,OAAO,QAAA,KAAa,WAAA,IAAe,OAAO,oBAAoB,WAAA,EAAa;AAC7E,IAAA,IAAI;AACF,MAAA,MAAM,CAAA,GAAI,IAAI,eAAA,CAAgB,QAAA,CAAS,MAAM,CAAA;AAC7C,MAAA,IAAI,CAAA,CAAE,GAAA,CAAI,gBAAgB,CAAA,EAAG;AAC3B,QAAA,CAAA,CAAE,cAAA,GAAiB,IAAA;AACnB,QAAA,OAAO,IAAA;AAAA,MACT;AAAA,IACF,CAAA,CAAA,MAAQ;AAAA,IAAe;AAAA,EACzB;AACA,EAAA,OAAO,KAAA;AACT;AAEA,SAAS,IAAI,GAAA,EAAqB;AAChC,EAAA,OAAO,aAAa,GAAG,CAAA,CAAA,CAAA;AACzB;AAIO,IAAM,GAAA,GAAM;AAAA;AAAA,EAEjB,IAAA,CAAK,QAAgB,IAAA,EAAuB;AAC1C,IAAA,IAAI,cAAA,IAAkB,OAAA,CAAQ,IAAA,CAAK,IAAI,GAAG,CAAA,EAAG,GAAG,IAAI,CAAA;AAAA,EACtD,CAAA;AAAA;AAAA,EAGA,IAAA,CAAK,QAAgB,IAAA,EAAuB;AAC1C,IAAA,IAAI,cAAA,IAAkB,OAAA,CAAQ,IAAA,CAAK,IAAI,GAAG,CAAA,EAAG,GAAG,IAAI,CAAA;AAAA,EACtD,CAAA;AAAA;AAAA;AAA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AAA,CAAA;AAClE,MAAA,MAAM,SAAS,KAAK,CAAA;AAAA,IACtB;AAAA,EACF,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;AAEA,SAAS,SAAA,CAAU,MAAc,WAAA,EAA+C;AAK9E,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,WAAW,CAAC,WAAA;AAAA,IACZ,UAAA,EAAY;AAAA,GACd;AACF;AAEA,SAAS,YAAA,GAAuB;AAK9B,EAAA,MAAM,QAAA,GACJ,OAAO,UAAA,KAAe,WAAA,GACjB,WAAgD,mBAAA,GACjD,MAAA;AACN,EAAA,IAAI,UAAU,OAAO,QAAA;AAWrB,EAAA,IAAI;AACF,IAAA,OAAO,IAAI,GAAA,CAAI,iBAAA,EAAmB,oQAAe,CAAA,CAAE,IAAA;AAAA,EACrD,CAAA,CAAA,MAAQ;AACN,IAAA,IAAI,OAAO,QAAA,KAAa,WAAA,IAAe,SAAS,QAAA,CAAS,UAAA,CAAW,MAAM,CAAA,EAAG;AAC3E,MAAA,OAAO,CAAA,EAAG,SAAS,MAAM,CAAA,MAAA,CAAA;AAAA,IAC3B;AACA,IAAA,OAAO,QAAA;AAAA,EACT;AACF;AAEA,SAAS,KAAA,CAAM,SAAiB,GAAA,EAAqB;AACnD,EAAA,MAAM,QAAQ,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAE7D,EAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,WAAA,EAAc,OAAO,CAAA,CAAA,CAAA,EAAK,GAAG,CAAA;AAC3C,EAAA,OAAO,IAAI,KAAA,CAAM,CAAA,EAAG,OAAO,CAAA,EAAA,EAAK,KAAA,IAAS,yCAAoC,CAAA,CAAE,CAAA;AACjF","file":"chunk-NNVOHKXJ.cjs","sourcesContent":["/**\n * Debug + self-diagnosis helper.\n *\n * avbridge has a lot of async stages (probe → classify → libav load →\n * strategy.execute → decoder pump → cold-start gate → first paint) and\n * when something's slow or wrong the symptom — \"it hangs\", \"it stutters\",\n * \"it plays audio without video\" — is usually nowhere near the actual\n * cause. This module gives us two things:\n *\n * 1. **Gated verbose logging.** `dbg.info(tag, ...)` etc. are no-ops\n * unless the consumer sets `globalThis.AVBRIDGE_DEBUG = true` (or\n * uses the matching `?avbridge_debug` URL search param at dev time).\n * When enabled, every log is prefixed with `[avbridge:<tag>]` so the\n * console is filterable.\n *\n * 2. **Unconditional self-diagnosis.** `dbg.warnIf(cond, tag, ...)`\n * always fires when a suspicious condition is detected, even with\n * debug off. These are the things we *know* mean something is\n * broken or degraded and the user would want to know about — e.g.\n * the cold-start gate timing out, the decoder running slower than\n * realtime, a libav variant taking longer to load than any network\n * should take, >20% of packets getting rejected.\n *\n * The guiding principle: **if a symptom caused more than 10 minutes of\n * human debugging once, add a targeted warning so the next instance\n * self-identifies in the console.** This module is where those\n * warnings live.\n */\n\n/** Read the debug flag fresh on every call so it's runtime-toggleable. */\nfunction isDebugEnabled(): boolean {\n if (typeof globalThis === \"undefined\") return false;\n const g = globalThis as { AVBRIDGE_DEBUG?: unknown };\n if (g.AVBRIDGE_DEBUG === true) return true;\n // Convenience: if running in a browser with a `?avbridge_debug` search\n // param, flip the flag on automatically. Useful for demos and quick\n // user reproduction without editing code.\n if (typeof location !== \"undefined\" && typeof URLSearchParams !== \"undefined\") {\n try {\n const p = new URLSearchParams(location.search);\n if (p.has(\"avbridge_debug\")) {\n g.AVBRIDGE_DEBUG = true;\n return true;\n }\n } catch { /* ignore */ }\n }\n return false;\n}\n\nfunction fmt(tag: string): string {\n return `[avbridge:${tag}]`;\n}\n\n/* eslint-disable no-console */\n\nexport const dbg = {\n /** Verbose — only when debug is enabled. The hot-path normal case. */\n info(tag: string, ...args: unknown[]): void {\n if (isDebugEnabled()) console.info(fmt(tag), ...args);\n },\n\n /** Warning — only when debug is enabled. Non-fatal oddities. */\n warn(tag: string, ...args: unknown[]): void {\n if (isDebugEnabled()) console.warn(fmt(tag), ...args);\n },\n\n /**\n * Self-diagnosis warning. **Always** emits regardless of debug flag.\n * Use this only for conditions that mean something is actually wrong\n * or degraded — not for routine chatter.\n */\n diag(tag: string, ...args: unknown[]): void {\n console.warn(fmt(tag), ...args);\n },\n\n /**\n * Timing helper: wraps an async call and logs its elapsed time when\n * debug is on. The callback runs whether debug is on or off — this is\n * just for the `dbg.info` at the end.\n *\n * Also unconditionally fires `dbg.diag` if the elapsed time exceeds\n * `slowMs`, so \"the bootstrap took 8 seconds\" shows up even without\n * debug mode enabled.\n */\n async timed<T>(\n tag: string,\n label: string,\n slowMs: number,\n fn: () => Promise<T>,\n ): Promise<T> {\n const start = performance.now();\n try {\n const result = await fn();\n const elapsed = performance.now() - start;\n if (isDebugEnabled()) {\n console.info(fmt(tag), `${label} ${elapsed.toFixed(0)}ms`);\n }\n if (elapsed > slowMs) {\n console.warn(\n fmt(tag),\n `${label} took ${elapsed.toFixed(0)}ms (>${slowMs}ms expected) — ` +\n `this is unusually slow; possible causes: ${hintForTag(tag)}`,\n );\n }\n return result;\n } catch (err) {\n const elapsed = performance.now() - start;\n console.warn(\n fmt(tag),\n `${label} FAILED after ${elapsed.toFixed(0)}ms:`,\n err,\n );\n throw err;\n }\n },\n};\n\nfunction hintForTag(tag: string): string {\n switch (tag) {\n case \"probe\":\n return \"slow network (range request), large sniff window, or libav cold-start\";\n case \"libav-load\":\n return \"large .wasm download, misconfigured AVBRIDGE_LIBAV_BASE, or server-side MIME type\";\n case \"bootstrap\":\n return \"probe+classify+strategy-init chain; enable AVBRIDGE_DEBUG for a phase breakdown\";\n case \"cold-start\":\n return \"decoder is producing output slower than realtime — check framesDecoded in getDiagnostics()\";\n default:\n return \"unknown stage — enable globalThis.AVBRIDGE_DEBUG for more detail\";\n }\n}\n","/**\n * Lazy libav.js loader supporting multiple variants.\n *\n * avbridge recognises three libav variants:\n *\n * - **webcodecs** — npm `@libav.js/variant-webcodecs`, ~5 MB. Modern formats\n * only (mp4/mkv/webm/ogg/wav/...) — designed to bridge to WebCodecs.\n *\n * - **default** — npm `@libav.js/variant-default`, ~12 MB. Audio-only build\n * (Opus, FLAC, WAV) despite the name. Useful for audio fallback.\n *\n * - **avbridge** — a custom build produced by `scripts/build-libav.sh` and\n * landing in `vendor/libav/`. Includes the AVI/ASF/FLV/MKV demuxers plus\n * the legacy decoders (WMV3, MPEG-4 Part 2, MS-MPEG4 v1/2/3, VC-1, MPEG-1/2,\n * AC-3/E-AC-3, WMAv1/v2/Pro). This is the only variant that can read AVI;\n * the npm variants are intentionally minimal and ship none of the legacy\n * demuxers.\n *\n * Variant resolution always goes through a runtime URL + `/* @vite-ignore *\\/`\n * dynamic import. Static imports trigger Vite's optimized-deps pipeline,\n * which rewrites `import.meta.url` away from the real `dist/` directory and\n * breaks libav's sibling-binary loading.\n */\n\nimport { dbg } from \"../../util/debug.js\";\n\nexport type LibavVariant = \"webcodecs\" | \"default\" | \"avbridge\";\n\nexport interface LoadLibavOptions {\n /**\n * Force threading on/off for this load. If unspecified, defaults to\n * \"true if `crossOriginIsolated`, otherwise false\". Some libav.js code\n * paths (notably the cross-thread reader-device protocol used during\n * `avformat_find_stream_info` for AVI) are unreliable in threaded mode,\n * so probing forces this to `false` while decode keeps it default.\n */\n threads?: boolean;\n}\n\n// Cache key includes both variant and threading mode so probe and decode\n// can run different libav instances of the same variant.\nconst cache: Map<string, Promise<LibavInstance>> = new Map();\n\nfunction cacheKey(variant: LibavVariant, threads: boolean): string {\n return `${variant}:${threads ? \"thr\" : \"wasm\"}`;\n}\n\n/**\n * Load (and cache) a libav.js variant. Pass `\"webcodecs\"` for the small\n * default; pass `\"default\"` for the audio fallback; pass `\"avbridge\"` for the\n * custom build that supports AVI/WMV/legacy codecs.\n */\nexport function loadLibav(\n variant: LibavVariant = \"webcodecs\",\n opts: LoadLibavOptions = {},\n): Promise<LibavInstance> {\n // Threading is OFF by default. The threaded libav.js variant is too\n // fragile in practice for our usage:\n // - Probe (`avformat_find_stream_info` for AVI) throws an `undefined`\n // exception out of `ff_init_demuxer_file`, apparently due to the\n // cross-thread reader-device protocol racing with the main thread.\n // - Decode hits a `TypeError: Cannot read properties of undefined\n // (reading 'apply')` inside libav.js's own worker message handler\n // within seconds of starting — a bug in libav.js's threaded message\n // dispatch that we can't fix from outside.\n //\n // Performance work for the fallback strategy needs to come from elsewhere\n // (WASM SIMD, OffscreenCanvas, larger decode batches) instead of libav's\n // pthreads. Threading can still be force-enabled with\n // `globalThis.AVBRIDGE_LIBAV_THREADS = true` for testing if libav.js fixes\n // those bugs in a future release.\n const env = globalThis as { AVBRIDGE_LIBAV_THREADS?: boolean };\n const wantThreads =\n opts.threads !== undefined\n ? opts.threads\n : env.AVBRIDGE_LIBAV_THREADS === true;\n\n const key = cacheKey(variant, wantThreads);\n let entry = cache.get(key);\n if (!entry) {\n entry = loadVariant(variant, wantThreads);\n cache.set(key, entry);\n }\n return entry;\n}\n\nasync function loadVariant(\n variant: LibavVariant,\n wantThreads: boolean,\n): Promise<LibavInstance> {\n return dbg.timed(\"libav-load\", `load \"${variant}\" (threads=${wantThreads})`, 5000, () =>\n loadVariantInner(variant, wantThreads),\n );\n}\n\nasync function loadVariantInner(\n variant: LibavVariant,\n wantThreads: boolean,\n): Promise<LibavInstance> {\n const key = cacheKey(variant, wantThreads);\n const base = `${libavBaseUrl()}/${variant}`;\n // The custom variant is named `libav-avbridge.mjs`; the npm variants follow\n // the same convention (`libav-webcodecs.mjs`, `libav-default.mjs`).\n const variantUrl = `${base}/libav-${variant}.mjs`;\n dbg.info(\"libav-load\", `fetching ${variantUrl}`);\n\n // Preflight HEAD-ish check: issue a bytes=0-0 range request so a missing\n // file fails fast with a clear error instead of hanging deep inside the\n // dynamic import or inside libav's own WASM instantiation. Surfaces the\n // most common mistake (\"libav base path is wrong\") in <100 ms instead of\n // an indeterminate stall.\n if (typeof fetch === \"function\") {\n try {\n const head = await fetch(variantUrl, { method: \"GET\", headers: { Range: \"bytes=0-0\" } });\n if (!head.ok && head.status !== 206) {\n throw new Error(\n `HTTP ${head.status} ${head.statusText} — check that libav files are served ` +\n `at ${base}/ (override via globalThis.AVBRIDGE_LIBAV_BASE)`,\n );\n }\n // Drain the tiny response so the connection can be reused.\n try { await head.arrayBuffer(); } catch { /* ignore */ }\n } catch (err) {\n cache.delete(key);\n throw chain(\n `libav.js \"${variant}\" variant not reachable at ${variantUrl}`,\n err,\n );\n }\n }\n\n let mod: LoadedVariant;\n try {\n // @ts-ignore runtime URL\n const imported: unknown = await import(/* @vite-ignore */ variantUrl);\n if (!imported || typeof (imported as { LibAV?: unknown }).LibAV !== \"function\") {\n throw new Error(`module at ${variantUrl} did not export LibAV`);\n }\n mod = imported as LoadedVariant;\n } catch (err) {\n cache.delete(key);\n const hint =\n variant === \"avbridge\"\n ? `The \"avbridge\" variant is a custom local build. Run \\`./scripts/build-libav.sh\\` ` +\n `to produce it (requires Emscripten; ~15-30 min the first time).`\n : `Make sure the variant files are present at ${base}/ (set ` +\n `globalThis.AVBRIDGE_LIBAV_BASE to override the default lookup path).`;\n throw new Error(\n `failed to load libav.js \"${variant}\" variant from ${variantUrl}. ${hint} ` +\n `Original error: ${(err as Error).message || String(err)}`,\n );\n }\n\n try {\n const inst = (await mod.LibAV(buildOpts(base, wantThreads))) as LibavInstance;\n await silenceLibavLogs(inst);\n return inst;\n } catch (err) {\n cache.delete(key);\n throw chain(`LibAV() factory failed for \"${variant}\" variant (threads=${wantThreads})`, err);\n }\n}\n\n/**\n * Lower libav's internal log level so the console doesn't get flooded with\n * `[mp3 @ ...] Header missing` and `Video uses a non-standard and wasteful\n * way to store B-frames` warnings on every legacy file. We still get any\n * actual JS-level errors via the normal Error path; this only affects\n * libav's own ffmpeg log channel.\n *\n * AV_LOG_QUIET = -8 (no output at all). If you want to keep fatal errors,\n * use AV_LOG_FATAL = 8 instead.\n */\nasync function silenceLibavLogs(inst: LibavInstance): Promise<void> {\n try {\n const setLevel = (inst as { av_log_set_level?: (n: number) => Promise<void> })\n .av_log_set_level;\n if (typeof setLevel === \"function\") {\n const quiet = (inst as { AV_LOG_QUIET?: number }).AV_LOG_QUIET ?? -8;\n await setLevel(quiet);\n }\n } catch {\n /* not fatal — verbose logs are noise, not an error */\n }\n}\n\nfunction buildOpts(base: string, wantThreads: boolean): Record<string, unknown> {\n // The wantThreads decision is made by `loadLibav()` so callers (probe,\n // decoder) can override per-load. Decode wants pthreads for speed; probe\n // forces them off because libav.js's cross-thread reader-device protocol\n // is unreliable mid-`avformat_find_stream_info` for some AVI files.\n return {\n base,\n nothreads: !wantThreads,\n yesthreads: wantThreads,\n };\n}\n\nfunction libavBaseUrl(): string {\n // Consumer override — the documented \"LGPL replaceability\" hook.\n // Setting `globalThis.AVBRIDGE_LIBAV_BASE = \"/my/path\"` lets anyone swap\n // in a different libav build (custom fragments, security patches, etc.)\n // without rebuilding avbridge.\n const override =\n typeof globalThis !== \"undefined\"\n ? (globalThis as { AVBRIDGE_LIBAV_BASE?: string }).AVBRIDGE_LIBAV_BASE\n : undefined;\n if (override) return override;\n\n // Default: resolve relative to this module's URL. When avbridge is installed\n // under `node_modules/avbridge/`, this module lives at `dist/chunk-*.js` (or\n // `dist/element-browser.js` for the browser entry) and `../vendor/libav`\n // resolves to `node_modules/avbridge/vendor/libav`, where the build step\n // vendored every variant's binaries. That's the zero-config path.\n //\n // `import.meta.url` throws in some synthetic environments (CJS tests, some\n // SSR evaluators). If it fails, fall back to the legacy `/libav` path so\n // consumers who relied on the pre-2.1 behavior still work.\n try {\n return new URL(\"../vendor/libav\", import.meta.url).href;\n } catch {\n if (typeof location !== \"undefined\" && location.protocol.startsWith(\"http\")) {\n return `${location.origin}/libav`;\n }\n return \"/libav\";\n }\n}\n\nfunction chain(message: string, err: unknown): Error {\n const inner = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.error(`[avbridge] ${message}:`, err);\n return new Error(`${message}: ${inner || \"(no message — see browser console)\"}`);\n}\n\ninterface LoadedVariant {\n LibAV: (opts?: Record<string, unknown>) => Promise<Record<string, unknown>>;\n}\n\n/** Loose structural type — the AVI probe and the fallback decoder add fields. */\nexport type LibavInstance = Record<string, unknown> & {\n mkreadaheadfile(name: string, blob: Blob): Promise<void>;\n unlinkreadaheadfile(name: string): Promise<void>;\n};\n"]}