{"version":3,"file":"lib.mjs","sources":["../ts-lib/node_modules/wasm-tgg/wasm_tgg.js","../ts-lib/node_modules/favico.js/favico.js","../ts-lib/src/badge.ts","../ts-lib/node_modules/mediabunny/dist/modules/src/misc.js","../ts-lib/node_modules/mediabunny/dist/modules/src/logging.js","../ts-lib/node_modules/mediabunny/dist/modules/src/metadata.js","../ts-lib/node_modules/mediabunny/dist/modules/shared/bitstream.js","../ts-lib/node_modules/mediabunny/dist/modules/shared/aac-misc.js","../ts-lib/node_modules/mediabunny/dist/modules/shared/ac3-misc.js","../ts-lib/node_modules/mediabunny/dist/modules/src/version.js","../ts-lib/node_modules/mediabunny/dist/modules/src/codec-data.js","../ts-lib/node_modules/mediabunny/dist/modules/src/codec.js","../ts-lib/node_modules/mediabunny/dist/modules/shared/mp3-misc.js","../ts-lib/node_modules/mediabunny/dist/modules/src/demuxer.js","../ts-lib/node_modules/mediabunny/dist/modules/src/packet.js","../ts-lib/node_modules/mediabunny/dist/modules/src/isobmff/isobmff-misc.js","../ts-lib/node_modules/mediabunny/dist/modules/src/isobmff/isobmff-reader.js","../ts-lib/node_modules/mediabunny/dist/modules/src/aes.js","../ts-lib/node_modules/mediabunny/dist/modules/src/isobmff/isobmff-demuxer.js","../ts-lib/node_modules/mediabunny/dist/modules/src/matroska/ebml.js","../ts-lib/node_modules/mediabunny/dist/modules/src/matroska/matroska-misc.js","../ts-lib/node_modules/mediabunny/dist/modules/src/matroska/matroska-demuxer.js","../ts-lib/node_modules/mediabunny/dist/modules/src/adts/adts-reader.js","../ts-lib/node_modules/mediabunny/dist/modules/src/adts/adts-demuxer.js","../ts-lib/node_modules/mediabunny/dist/modules/src/mpeg-ts/mpeg-ts-misc.js","../ts-lib/node_modules/mediabunny/dist/modules/src/mpeg-ts/mpeg-ts-demuxer.js","../ts-lib/node_modules/mediabunny/dist/modules/src/source.js","../ts-lib/node_modules/mediabunny/dist/modules/src/input-format.js","../ts-lib/node_modules/mediabunny/dist/modules/src/sample.js","../ts-lib/node_modules/mediabunny/dist/modules/src/encode.js","../ts-lib/node_modules/mediabunny/dist/modules/src/custom-coder.js","../ts-lib/node_modules/mediabunny/dist/modules/src/pcm.js","../ts-lib/node_modules/mediabunny/dist/modules/src/media-sink.js","../ts-lib/node_modules/mediabunny/dist/modules/src/input-track.js","../ts-lib/node_modules/mediabunny/dist/modules/src/input.js","../ts-lib/node_modules/mediabunny/dist/modules/src/reader.js","../ts-lib/node_modules/mediabunny/dist/modules/src/muxer.js","../ts-lib/node_modules/mediabunny/dist/modules/src/subtitles.js","../ts-lib/node_modules/mediabunny/dist/modules/src/isobmff/isobmff-boxes.js","../ts-lib/node_modules/mediabunny/dist/modules/src/writer.js","../ts-lib/node_modules/mediabunny/dist/modules/src/target.js","../ts-lib/node_modules/mediabunny/dist/modules/src/isobmff/isobmff-muxer.js","../ts-lib/node_modules/mediabunny/dist/modules/src/resample.js","../ts-lib/node_modules/mediabunny/dist/modules/src/media-source.js","../ts-lib/node_modules/mediabunny/dist/modules/src/output-format.js","../ts-lib/node_modules/mediabunny/dist/modules/src/output.js","../ts-lib/node_modules/mediabunny/dist/modules/src/conversion.js","../ts-lib/src/videoConvert.ts","../ts-lib/src/index.ts"],"sourcesContent":["let wasm;\n\nfunction getStringFromWasm0(ptr, len) {\n    ptr = ptr >>> 0;\n    return decodeText(ptr, len);\n}\n\nlet cachedUint8ArrayMemory0 = null;\nfunction getUint8ArrayMemory0() {\n    if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {\n        cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);\n    }\n    return cachedUint8ArrayMemory0;\n}\n\nfunction passStringToWasm0(arg, malloc, realloc) {\n    if (realloc === undefined) {\n        const buf = cachedTextEncoder.encode(arg);\n        const ptr = malloc(buf.length, 1) >>> 0;\n        getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);\n        WASM_VECTOR_LEN = buf.length;\n        return ptr;\n    }\n\n    let len = arg.length;\n    let ptr = malloc(len, 1) >>> 0;\n\n    const mem = getUint8ArrayMemory0();\n\n    let offset = 0;\n\n    for (; offset < len; offset++) {\n        const code = arg.charCodeAt(offset);\n        if (code > 0x7F) break;\n        mem[ptr + offset] = code;\n    }\n    if (offset !== len) {\n        if (offset !== 0) {\n            arg = arg.slice(offset);\n        }\n        ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;\n        const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);\n        const ret = cachedTextEncoder.encodeInto(arg, view);\n\n        offset += ret.written;\n        ptr = realloc(ptr, len, offset, 1) >>> 0;\n    }\n\n    WASM_VECTOR_LEN = offset;\n    return ptr;\n}\n\nlet cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\ncachedTextDecoder.decode();\nconst MAX_SAFARI_DECODE_BYTES = 2146435072;\nlet numBytesDecoded = 0;\nfunction decodeText(ptr, len) {\n    numBytesDecoded += len;\n    if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {\n        cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\n        cachedTextDecoder.decode();\n        numBytesDecoded = len;\n    }\n    return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));\n}\n\nconst cachedTextEncoder = new TextEncoder();\n\nif (!('encodeInto' in cachedTextEncoder)) {\n    cachedTextEncoder.encodeInto = function (arg, view) {\n        const buf = cachedTextEncoder.encode(arg);\n        view.set(buf);\n        return {\n            read: arg.length,\n            written: buf.length\n        };\n    }\n}\n\nlet WASM_VECTOR_LEN = 0;\n\n/**\n * @param {string} data\n * @returns {string}\n */\nexport function xxh3_64(data) {\n    let deferred2_0;\n    let deferred2_1;\n    try {\n        const ptr0 = passStringToWasm0(data, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n        const len0 = WASM_VECTOR_LEN;\n        const ret = wasm.xxh3_64(ptr0, len0);\n        deferred2_0 = ret[0];\n        deferred2_1 = ret[1];\n        return getStringFromWasm0(ret[0], ret[1]);\n    } finally {\n        wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);\n    }\n}\n\nconst EXPECTED_RESPONSE_TYPES = new Set(['basic', 'cors', 'default']);\n\nasync function __wbg_load(module, imports) {\n    if (typeof Response === 'function' && module instanceof Response) {\n        if (typeof WebAssembly.instantiateStreaming === 'function') {\n            try {\n                return await WebAssembly.instantiateStreaming(module, imports);\n            } catch (e) {\n                const validResponse = module.ok && EXPECTED_RESPONSE_TYPES.has(module.type);\n\n                if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {\n                    console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n                } else {\n                    throw e;\n                }\n            }\n        }\n\n        const bytes = await module.arrayBuffer();\n        return await WebAssembly.instantiate(bytes, imports);\n    } else {\n        const instance = await WebAssembly.instantiate(module, imports);\n\n        if (instance instanceof WebAssembly.Instance) {\n            return { instance, module };\n        } else {\n            return instance;\n        }\n    }\n}\n\nfunction __wbg_get_imports() {\n    const imports = {};\n    imports.wbg = {};\n    imports.wbg.__wbindgen_init_externref_table = function() {\n        const table = wasm.__wbindgen_externrefs;\n        const offset = table.grow(4);\n        table.set(0, undefined);\n        table.set(offset + 0, undefined);\n        table.set(offset + 1, null);\n        table.set(offset + 2, true);\n        table.set(offset + 3, false);\n    };\n\n    return imports;\n}\n\nfunction __wbg_finalize_init(instance, module) {\n    wasm = instance.exports;\n    __wbg_init.__wbindgen_wasm_module = module;\n    cachedUint8ArrayMemory0 = null;\n\n\n    wasm.__wbindgen_start();\n    return wasm;\n}\n\nfunction initSync(module) {\n    if (wasm !== undefined) return wasm;\n\n\n    if (typeof module !== 'undefined') {\n        if (Object.getPrototypeOf(module) === Object.prototype) {\n            ({module} = module)\n        } else {\n            console.warn('using deprecated parameters for `initSync()`; pass a single object instead')\n        }\n    }\n\n    const imports = __wbg_get_imports();\n    if (!(module instanceof WebAssembly.Module)) {\n        module = new WebAssembly.Module(module);\n    }\n    const instance = new WebAssembly.Instance(module, imports);\n    return __wbg_finalize_init(instance, module);\n}\n\nasync function __wbg_init(module_or_path) {\n    if (wasm !== undefined) return wasm;\n\n\n    if (typeof module_or_path !== 'undefined') {\n        if (Object.getPrototypeOf(module_or_path) === Object.prototype) {\n            ({module_or_path} = module_or_path)\n        } else {\n            console.warn('using deprecated parameters for the initialization function; pass a single object instead')\n        }\n    }\n\n    if (typeof module_or_path === 'undefined') {\n        module_or_path = new URL('wasm_tgg_bg.wasm', import.meta.url);\n    }\n    const imports = __wbg_get_imports();\n\n    if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {\n        module_or_path = fetch(module_or_path);\n    }\n\n    const { instance, module } = await __wbg_load(await module_or_path, imports);\n\n    return __wbg_finalize_init(instance, module);\n}\n\nexport { initSync };\nexport default __wbg_init;\n","/**\n * @license MIT\n * @fileOverview Favico animations\n * @author Miroslav Magda, http://blog.ejci.net\n * @version 0.3.10\n */\n\n/**\n * Create new favico instance\n * @param {Object} Options\n * @return {Object} Favico object\n * @example\n * var favico = new Favico({\n *    bgColor : '#d00',\n *    textColor : '#fff',\n *    fontFamily : 'sans-serif',\n *    fontStyle : 'bold',\n *    position : 'down',\n *    type : 'circle',\n *    animation : 'slide',\n *    dataUrl: function(url){},\n *    win: top\n * });\n */\n(function () {\n\n\tvar Favico = (function (opt) {\n\t\t'use strict';\n\t\topt = (opt) ? opt : {};\n\t\tvar _def = {\n\t\t\tbgColor: '#d00',\n\t\t\ttextColor: '#fff',\n\t\t\tfontFamily: 'sans-serif', //Arial,Verdana,Times New Roman,serif,sans-serif,...\n\t\t\tfontStyle: 'bold', //normal,italic,oblique,bold,bolder,lighter,100,200,300,400,500,600,700,800,900\n\t\t\ttype: 'circle',\n\t\t\tposition: 'down', // down, up, left, leftup (upleft)\n\t\t\tanimation: 'slide',\n\t\t\telementId: false,\n\t\t\tdataUrl: false,\n\t\t\twin: window\n\t\t};\n\t\tvar _opt, _orig, _h, _w, _canvas, _context, _img, _ready, _lastBadge, _running, _readyCb, _stop, _browser, _animTimeout, _drawTimeout, _doc;\n\n\t\t_browser = {};\n\t\t_browser.ff = typeof InstallTrigger != 'undefined';\n\t\t_browser.chrome = !!window.chrome;\n\t\t_browser.opera = !!window.opera || navigator.userAgent.indexOf('Opera') >= 0;\n\t\t_browser.ie = /*@cc_on!@*/false;\n\t\t_browser.safari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;\n\t\t_browser.supported = (_browser.chrome || _browser.ff || _browser.opera);\n\n\t\tvar _queue = [];\n\t\t_readyCb = function () {\n\t\t};\n\t\t_ready = _stop = false;\n\t\t/**\n\t\t * Initialize favico\n\t\t */\n\t\tvar init = function () {\n\t\t\t//merge initial options\n\t\t\t_opt = merge(_def, opt);\n\t\t\t_opt.bgColor = hexToRgb(_opt.bgColor);\n\t\t\t_opt.textColor = hexToRgb(_opt.textColor);\n\t\t\t_opt.position = _opt.position.toLowerCase();\n\t\t\t_opt.animation = (animation.types['' + _opt.animation]) ? _opt.animation : _def.animation;\n\n\t\t\t_doc = _opt.win.document;\n\n\t\t\tvar isUp = _opt.position.indexOf('up') > -1;\n\t\t\tvar isLeft = _opt.position.indexOf('left') > -1;\n\n\t\t\t//transform animation\n\t\t\tif (isUp || isLeft) {\n\t\t\t\tfor (var i = 0; i < animation.types['' + _opt.animation].length; i++) {\n\t\t\t\t\tvar step = animation.types['' + _opt.animation][i];\n\n\t\t\t\t\tif (isUp) {\n\t\t\t\t\t\tif (step.y < 0.6) {\n\t\t\t\t\t\t\tstep.y = step.y - 0.4;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tstep.y = step.y - 2 * step.y + (1 - step.w);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (isLeft) {\n\t\t\t\t\t\tif (step.x < 0.6) {\n\t\t\t\t\t\t\tstep.x = step.x - 0.4;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tstep.x = step.x - 2 * step.x + (1 - step.h);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tanimation.types['' + _opt.animation][i] = step;\n\t\t\t\t}\n\t\t\t}\n\t\t\t_opt.type = (type['' + _opt.type]) ? _opt.type : _def.type;\n\n\t\t\t_orig = link.getIcon();\n\t\t\t//create temp canvas\n\t\t\t_canvas = document.createElement('canvas');\n\t\t\t//create temp image\n\t\t\t_img = document.createElement('img');\n\t\t\tif (_orig.hasAttribute('href')) {\n\t\t\t\t_img.setAttribute('crossOrigin', 'anonymous');\n\t\t\t\t//get width/height\n\t\t\t\t_img.onload = function () {\n\t\t\t\t\t_h = (_img.height > 0) ? _img.height : 32;\n\t\t\t\t\t_w = (_img.width > 0) ? _img.width : 32;\n\t\t\t\t\t_canvas.height = _h;\n\t\t\t\t\t_canvas.width = _w;\n\t\t\t\t\t_context = _canvas.getContext('2d');\n\t\t\t\t\ticon.ready();\n\t\t\t\t};\n\t\t\t\t_img.setAttribute('src', _orig.getAttribute('href'));\n\t\t\t} else {\n\t\t\t\t_img.onload = function () {\n\t\t\t\t\t_h = 32;\n\t\t\t\t\t_w = 32;\n\t\t\t\t\t_img.height = _h;\n\t\t\t\t\t_img.width = _w;\n\t\t\t\t\t_canvas.height = _h;\n\t\t\t\t\t_canvas.width = _w;\n\t\t\t\t\t_context = _canvas.getContext('2d');\n\t\t\t\t\ticon.ready();\n\t\t\t\t};\n\t\t\t\t_img.setAttribute('src', '');\n\t\t\t}\n\n\t\t};\n\t\t/**\n\t\t * Icon namespace\n\t\t */\n\t\tvar icon = {};\n\t\t/**\n\t\t * Icon is ready (reset icon) and start animation (if ther is any)\n\t\t */\n\t\ticon.ready = function () {\n\t\t\t_ready = true;\n\t\t\ticon.reset();\n\t\t\t_readyCb();\n\t\t};\n\t\t/**\n\t\t * Reset icon to default state\n\t\t */\n\t\ticon.reset = function () {\n\t\t\t//reset\n\t\t\tif (!_ready) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t_queue = [];\n\t\t\t_lastBadge = false;\n\t\t\t_running = false;\n\t\t\t_context.clearRect(0, 0, _w, _h);\n\t\t\t_context.drawImage(_img, 0, 0, _w, _h);\n\t\t\t//_stop=true;\n\t\t\tlink.setIcon(_canvas);\n\t\t\t//webcam('stop');\n\t\t\t//video('stop');\n\t\t\twindow.clearTimeout(_animTimeout);\n\t\t\twindow.clearTimeout(_drawTimeout);\n\t\t};\n\t\t/**\n\t\t * Start animation\n\t\t */\n\t\ticon.start = function () {\n\t\t\tif (!_ready || _running) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tvar finished = function () {\n\t\t\t\t_lastBadge = _queue[0];\n\t\t\t\t_running = false;\n\t\t\t\tif (_queue.length > 0) {\n\t\t\t\t\t_queue.shift();\n\t\t\t\t\ticon.start();\n\t\t\t\t} else {\n\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (_queue.length > 0) {\n\t\t\t\t_running = true;\n\t\t\t\tvar run = function () {\n\t\t\t\t\t// apply options for this animation\n\t\t\t\t\t['type', 'animation', 'bgColor', 'textColor', 'fontFamily', 'fontStyle'].forEach(function (a) {\n\t\t\t\t\t\tif (a in _queue[0].options) {\n\t\t\t\t\t\t\t_opt[a] = _queue[0].options[a];\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tanimation.run(_queue[0].options, function () {\n\t\t\t\t\t\tfinished();\n\t\t\t\t\t}, false);\n\t\t\t\t};\n\t\t\t\tif (_lastBadge) {\n\t\t\t\t\tanimation.run(_lastBadge.options, function () {\n\t\t\t\t\t\trun();\n\t\t\t\t\t}, true);\n\t\t\t\t} else {\n\t\t\t\t\trun();\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\t/**\n\t\t * Badge types\n\t\t */\n\t\tvar type = {};\n\t\tvar options = function (opt) {\n\t\t\topt.n = ((typeof opt.n) === 'number') ? Math.abs(opt.n | 0) : opt.n;\n\t\t\topt.x = _w * opt.x;\n\t\t\topt.y = _h * opt.y;\n\t\t\topt.w = _w * opt.w;\n\t\t\topt.h = _h * opt.h;\n\t\t\topt.len = (\"\" + opt.n).length;\n\t\t\treturn opt;\n\t\t};\n\t\t/**\n\t\t * Generate circle\n\t\t * @param {Object} opt Badge options\n\t\t */\n\t\ttype.circle = function (opt) {\n\t\t\topt = options(opt);\n\t\t\tvar more = false;\n\t\t\tif (opt.len === 2) {\n\t\t\t\topt.x = opt.x - opt.w * 0.4;\n\t\t\t\topt.w = opt.w * 1.4;\n\t\t\t\tmore = true;\n\t\t\t} else if (opt.len >= 3) {\n\t\t\t\topt.x = opt.x - opt.w * 0.65;\n\t\t\t\topt.w = opt.w * 1.65;\n\t\t\t\tmore = true;\n\t\t\t}\n\t\t\t_context.clearRect(0, 0, _w, _h);\n\t\t\t_context.drawImage(_img, 0, 0, _w, _h);\n\t\t\t_context.beginPath();\n\t\t\t_context.font = _opt.fontStyle + \" \" + Math.floor(opt.h * (opt.n > 99 ? 0.85 : 1)) + \"px \" + _opt.fontFamily;\n\t\t\t_context.textAlign = 'center';\n\t\t\tif (more) {\n\t\t\t\t_context.moveTo(opt.x + opt.w / 2, opt.y);\n\t\t\t\t_context.lineTo(opt.x + opt.w - opt.h / 2, opt.y);\n\t\t\t\t_context.quadraticCurveTo(opt.x + opt.w, opt.y, opt.x + opt.w, opt.y + opt.h / 2);\n\t\t\t\t_context.lineTo(opt.x + opt.w, opt.y + opt.h - opt.h / 2);\n\t\t\t\t_context.quadraticCurveTo(opt.x + opt.w, opt.y + opt.h, opt.x + opt.w - opt.h / 2, opt.y + opt.h);\n\t\t\t\t_context.lineTo(opt.x + opt.h / 2, opt.y + opt.h);\n\t\t\t\t_context.quadraticCurveTo(opt.x, opt.y + opt.h, opt.x, opt.y + opt.h - opt.h / 2);\n\t\t\t\t_context.lineTo(opt.x, opt.y + opt.h / 2);\n\t\t\t\t_context.quadraticCurveTo(opt.x, opt.y, opt.x + opt.h / 2, opt.y);\n\t\t\t} else {\n\t\t\t\t_context.arc(opt.x + opt.w / 2, opt.y + opt.h / 2, opt.h / 2, 0, 2 * Math.PI);\n\t\t\t}\n\t\t\t_context.fillStyle = 'rgba(' + _opt.bgColor.r + ',' + _opt.bgColor.g + ',' + _opt.bgColor.b + ',' + opt.o + ')';\n\t\t\t_context.fill();\n\t\t\t_context.closePath();\n\t\t\t_context.beginPath();\n\t\t\t_context.stroke();\n\t\t\t_context.fillStyle = 'rgba(' + _opt.textColor.r + ',' + _opt.textColor.g + ',' + _opt.textColor.b + ',' + opt.o + ')';\n\t\t\t//_context.fillText((more) ? '9+' : opt.n, Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.15));\n\t\t\tif ((typeof opt.n) === 'number' && opt.n > 999) {\n\t\t\t\t_context.fillText(((opt.n > 9999) ? 9 : Math.floor(opt.n / 1000)) + 'k+', Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.2));\n\t\t\t} else {\n\t\t\t\t_context.fillText(opt.n, Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.15));\n\t\t\t}\n\t\t\t_context.closePath();\n\t\t};\n\t\t/**\n\t\t * Generate rectangle\n\t\t * @param {Object} opt Badge options\n\t\t */\n\t\ttype.rectangle = function (opt) {\n\t\t\topt = options(opt);\n\t\t\tvar more = false;\n\t\t\tif (opt.len === 2) {\n\t\t\t\topt.x = opt.x - opt.w * 0.4;\n\t\t\t\topt.w = opt.w * 1.4;\n\t\t\t\tmore = true;\n\t\t\t} else if (opt.len >= 3) {\n\t\t\t\topt.x = opt.x - opt.w * 0.65;\n\t\t\t\topt.w = opt.w * 1.65;\n\t\t\t\tmore = true;\n\t\t\t}\n\t\t\t_context.clearRect(0, 0, _w, _h);\n\t\t\t_context.drawImage(_img, 0, 0, _w, _h);\n\t\t\t_context.beginPath();\n\t\t\t_context.font = _opt.fontStyle + \" \" + Math.floor(opt.h * (opt.n > 99 ? 0.9 : 1)) + \"px \" + _opt.fontFamily;\n\t\t\t_context.textAlign = 'center';\n\t\t\t_context.fillStyle = 'rgba(' + _opt.bgColor.r + ',' + _opt.bgColor.g + ',' + _opt.bgColor.b + ',' + opt.o + ')';\n\t\t\t_context.fillRect(opt.x, opt.y, opt.w, opt.h);\n\t\t\t_context.fillStyle = 'rgba(' + _opt.textColor.r + ',' + _opt.textColor.g + ',' + _opt.textColor.b + ',' + opt.o + ')';\n\t\t\t//_context.fillText((more) ? '9+' : opt.n, Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.15));\n\t\t\tif ((typeof opt.n) === 'number' && opt.n > 999) {\n\t\t\t\t_context.fillText(((opt.n > 9999) ? 9 : Math.floor(opt.n / 1000)) + 'k+', Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.2));\n\t\t\t} else {\n\t\t\t\t_context.fillText(opt.n, Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.15));\n\t\t\t}\n\t\t\t_context.closePath();\n\t\t};\n\n\t\t/**\n\t\t * Set badge\n\t\t */\n\t\tvar badge = function (number, opts) {\n\t\t\topts = ((typeof opts) === 'string' ? {\n\t\t\t\tanimation: opts\n\t\t\t} : opts) || {};\n\t\t\t_readyCb = function () {\n\t\t\t\ttry {\n\t\t\t\t\tif (typeof (number) === 'number' ? (number > 0) : (number !== '')) {\n\t\t\t\t\t\tvar q = {\n\t\t\t\t\t\t\ttype: 'badge',\n\t\t\t\t\t\t\toptions: {\n\t\t\t\t\t\t\t\tn: number\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\tif ('animation' in opts && animation.types['' + opts.animation]) {\n\t\t\t\t\t\t\tq.options.animation = '' + opts.animation;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ('type' in opts && type['' + opts.type]) {\n\t\t\t\t\t\t\tq.options.type = '' + opts.type;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t['bgColor', 'textColor'].forEach(function (o) {\n\t\t\t\t\t\t\tif (o in opts) {\n\t\t\t\t\t\t\t\tq.options[o] = hexToRgb(opts[o]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t\t['fontStyle', 'fontFamily'].forEach(function (o) {\n\t\t\t\t\t\t\tif (o in opts) {\n\t\t\t\t\t\t\t\tq.options[o] = opts[o];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t\t_queue.push(q);\n\t\t\t\t\t\tif (_queue.length > 100) {\n\t\t\t\t\t\t\tthrow new Error('Too many badges requests in queue.');\n\t\t\t\t\t\t}\n\t\t\t\t\t\ticon.start();\n\t\t\t\t\t} else {\n\t\t\t\t\t\ticon.reset();\n\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\tthrow new Error('Error setting badge. Message: ' + e.message);\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (_ready) {\n\t\t\t\t_readyCb();\n\t\t\t}\n\t\t};\n\n\t\t/**\n\t\t * Set image as icon\n\t\t */\n\t\tvar image = function (imageElement) {\n\t\t\t_readyCb = function () {\n\t\t\t\ttry {\n\t\t\t\t\tvar w = imageElement.width;\n\t\t\t\t\tvar h = imageElement.height;\n\t\t\t\t\tvar newImg = document.createElement('img');\n\t\t\t\t\tvar ratio = (w / _w < h / _h) ? (w / _w) : (h / _h);\n\t\t\t\t\tnewImg.setAttribute('crossOrigin', 'anonymous');\n\t\t\t\t\tnewImg.onload=function(){\n\t\t\t\t\t\t_context.clearRect(0, 0, _w, _h);\n\t\t\t\t\t\t_context.drawImage(newImg, 0, 0, _w, _h);\n\t\t\t\t\t\tlink.setIcon(_canvas);\n\t\t\t\t\t};\n\t\t\t\t\tnewImg.setAttribute('src', imageElement.getAttribute('src'));\n\t\t\t\t\tnewImg.height = (h / ratio);\n\t\t\t\t\tnewImg.width = (w / ratio);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tthrow new Error('Error setting image. Message: ' + e.message);\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (_ready) {\n\t\t\t\t_readyCb();\n\t\t\t}\n\t\t};\n\t\t/**\n\t\t * Set video as icon\n\t\t */\n\t\tvar video = function (videoElement) {\n\t\t\t_readyCb = function () {\n\t\t\t\ttry {\n\t\t\t\t\tif (videoElement === 'stop') {\n\t\t\t\t\t\t_stop = true;\n\t\t\t\t\t\ticon.reset();\n\t\t\t\t\t\t_stop = false;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t//var w = videoElement.width;\n\t\t\t\t\t//var h = videoElement.height;\n\t\t\t\t\t//var ratio = (w / _w < h / _h) ? (w / _w) : (h / _h);\n\t\t\t\t\tvideoElement.addEventListener('play', function () {\n\t\t\t\t\t\tdrawVideo(this);\n\t\t\t\t\t}, false);\n\n\t\t\t\t} catch (e) {\n\t\t\t\t\tthrow new Error('Error setting video. Message: ' + e.message);\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (_ready) {\n\t\t\t\t_readyCb();\n\t\t\t}\n\t\t};\n\t\t/**\n\t\t * Set video as icon\n\t\t */\n\t\tvar webcam = function (action) {\n\t\t\t//UR\n\t\t\tif (!window.URL || !window.URL.createObjectURL) {\n\t\t\t\twindow.URL = window.URL || {};\n\t\t\t\twindow.URL.createObjectURL = function (obj) {\n\t\t\t\t\treturn obj;\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (_browser.supported) {\n\t\t\t\tvar newVideo = false;\n\t\t\t\tnavigator.getUserMedia = navigator.getUserMedia || navigator.oGetUserMedia || navigator.msGetUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia;\n\t\t\t\t_readyCb = function () {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (action === 'stop') {\n\t\t\t\t\t\t\t_stop = true;\n\t\t\t\t\t\t\ticon.reset();\n\t\t\t\t\t\t\t_stop = false;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnewVideo = document.createElement('video');\n\t\t\t\t\t\tnewVideo.width = _w;\n\t\t\t\t\t\tnewVideo.height = _h;\n\t\t\t\t\t\tnavigator.getUserMedia({\n\t\t\t\t\t\t\tvideo: true,\n\t\t\t\t\t\t\taudio: false\n\t\t\t\t\t\t}, function (stream) {\n\t\t\t\t\t\t\tnewVideo.src = URL.createObjectURL(stream);\n\t\t\t\t\t\t\tnewVideo.play();\n\t\t\t\t\t\t\tdrawVideo(newVideo);\n\t\t\t\t\t\t}, function () {\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tthrow new Error('Error setting webcam. Message: ' + e.message);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tif (_ready) {\n\t\t\t\t\t_readyCb();\n\t\t\t\t}\n\t\t\t}\n\n\t\t};\n\n\t\t/**\n\t\t * Draw video to context and repeat :)\n\t\t */\n\t\tfunction drawVideo(video) {\n\t\t\tif (video.paused || video.ended || _stop) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t//nasty hack for FF webcam (Thanks to Julian Ćwirko, kontakt@redsunmedia.pl)\n\t\t\ttry {\n\t\t\t\t_context.clearRect(0, 0, _w, _h);\n\t\t\t\t_context.drawImage(video, 0, 0, _w, _h);\n\t\t\t} catch (e) {\n\n\t\t\t}\n\t\t\t_drawTimeout = setTimeout(function () {\n\t\t\t\tdrawVideo(video);\n\t\t\t}, animation.duration);\n\t\t\tlink.setIcon(_canvas);\n\t\t}\n\n\t\tvar link = {};\n\t\t/**\n\t\t * Get icon from HEAD tag or create a new <link> element\n\t\t */\n\t\tlink.getIcon = function () {\n\t\t\tvar elm = false;\n\t\t\t//get link element\n\t\t\tvar getLink = function () {\n\t\t\t\tvar link = _doc.getElementsByTagName('head')[0].getElementsByTagName('link');\n\t\t\t\tfor (var l = link.length, i = (l - 1); i >= 0; i--) {\n\t\t\t\t\tif ((/(^|\\s)icon(\\s|$)/i).test(link[i].getAttribute('rel'))) {\n\t\t\t\t\t\treturn link[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t};\n\t\t\tif (_opt.element) {\n\t\t\t\telm = _opt.element;\n\t\t\t} else if (_opt.elementId) {\n\t\t\t\t//if img element identified by elementId\n\t\t\t\telm = _doc.getElementById(_opt.elementId);\n\t\t\t\telm.setAttribute('href', elm.getAttribute('src'));\n\t\t\t} else {\n\t\t\t\t//if link element\n\t\t\t\telm = getLink();\n\t\t\t\tif (elm === false) {\n\t\t\t\t\telm = _doc.createElement('link');\n\t\t\t\t\telm.setAttribute('rel', 'icon');\n\t\t\t\t\t_doc.getElementsByTagName('head')[0].appendChild(elm);\n\t\t\t\t}\n\t\t\t}\n\t\t\telm.setAttribute('type', 'image/png');\n\t\t\treturn elm;\n\t\t};\n\t\tlink.setIcon = function (canvas) {\n\t\t\tvar url = canvas.toDataURL('image/png');\n\t\t\tif (_opt.dataUrl) {\n\t\t\t\t//if using custom exporter\n\t\t\t\t_opt.dataUrl(url);\n\t\t\t}\n\t\t\tif (_opt.element) {\n\t\t\t\t_opt.element.setAttribute('href', url);\n\t\t\t\t_opt.element.setAttribute('src', url);\n\t\t\t} else if (_opt.elementId) {\n\t\t\t\t//if is attached to element (image)\n\t\t\t\tvar elm = _doc.getElementById(_opt.elementId);\n\t\t\t\telm.setAttribute('href', url);\n\t\t\t\telm.setAttribute('src', url);\n\t\t\t} else {\n\t\t\t\t//if is attached to fav icon\n\t\t\t\tif (_browser.ff || _browser.opera) {\n\t\t\t\t\t//for FF we need to \"recreate\" element, atach to dom and remove old <link>\n\t\t\t\t\t//var originalType = _orig.getAttribute('rel');\n\t\t\t\t\tvar old = _orig;\n\t\t\t\t\t_orig = _doc.createElement('link');\n\t\t\t\t\t//_orig.setAttribute('rel', originalType);\n\t\t\t\t\tif (_browser.opera) {\n\t\t\t\t\t\t_orig.setAttribute('rel', 'icon');\n\t\t\t\t\t}\n\t\t\t\t\t_orig.setAttribute('rel', 'icon');\n\t\t\t\t\t_orig.setAttribute('type', 'image/png');\n\t\t\t\t\t_doc.getElementsByTagName('head')[0].appendChild(_orig);\n\t\t\t\t\t_orig.setAttribute('href', url);\n\t\t\t\t\tif (old.parentNode) {\n\t\t\t\t\t\told.parentNode.removeChild(old);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t_orig.setAttribute('href', url);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\t//http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb#answer-5624139\n\t\t//HEX to RGB convertor\n\t\tfunction hexToRgb(hex) {\n\t\t\tvar shorthandRegex = /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i;\n\t\t\thex = hex.replace(shorthandRegex, function (m, r, g, b) {\n\t\t\t\treturn r + r + g + g + b + b;\n\t\t\t});\n\t\t\tvar result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n\t\t\treturn result ? {\n\t\t\t\tr: parseInt(result[1], 16),\n\t\t\t\tg: parseInt(result[2], 16),\n\t\t\t\tb: parseInt(result[3], 16)\n\t\t\t} : false;\n\t\t}\n\n\t\t/**\n\t\t * Merge options\n\t\t */\n\t\tfunction merge(def, opt) {\n\t\t\tvar mergedOpt = {};\n\t\t\tvar attrname;\n\t\t\tfor (attrname in def) {\n\t\t\t\tmergedOpt[attrname] = def[attrname];\n\t\t\t}\n\t\t\tfor (attrname in opt) {\n\t\t\t\tmergedOpt[attrname] = opt[attrname];\n\t\t\t}\n\t\t\treturn mergedOpt;\n\t\t}\n\n\t\t/**\n\t\t * Cross-browser page visibility shim\n\t\t * http://stackoverflow.com/questions/12536562/detect-whether-a-window-is-visible\n\t\t */\n\t\tfunction isPageHidden() {\n\t\t\treturn _doc.hidden || _doc.msHidden || _doc.webkitHidden || _doc.mozHidden;\n\t\t}\n\n\t\t/**\n\t\t * @namespace animation\n\t\t */\n\t\tvar animation = {};\n\t\t/**\n\t\t * Animation \"frame\" duration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 0.6,\n\t\t\t\th: 0.6,\n\t\t\t\to: 1\n\t\t\t}, {\n\t\t\t\tx: 0.4,\n\t\t\t\ty: 0.4,\n\t\t\t\tw: 0.6,\n\t\t\t\th: 0.6,\n\t\t\t\to: 1\n\t\t\t}];\n\t\t/**\n\t\t * Run animation\n\t\t * @param {Object} opt Animation options\n\t\t * @param {Object} cb Callabak after all steps are done\n\t\t * @param {Object} revert Reverse order? true|false\n\t\t * @param {Object} step Optional step number (frame bumber)\n\t\t */\n\t\tanimation.run = function (opt, cb, revert, step) {\n\t\t\tvar animationType = animation.types[isPageHidden() ? 'none' : _opt.animation];\n\t\t\tif (revert === true) {\n\t\t\t\tstep = (typeof step !== 'undefined') ? step : animationType.length - 1;\n\t\t\t} else {\n\t\t\t\tstep = (typeof step !== 'undefined') ? step : 0;\n\t\t\t}\n\t\t\tcb = (cb) ? cb : function () {\n\t\t\t};\n\t\t\tif ((step < animationType.length) && (step >= 0)) {\n\t\t\t\ttype[_opt.type](merge(opt, animationType[step]));\n\t\t\t\t_animTimeout = setTimeout(function () {\n\t\t\t\t\tif (revert) {\n\t\t\t\t\t\tstep = step - 1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstep = step + 1;\n\t\t\t\t\t}\n\t\t\t\t\tanimation.run(opt, cb, revert, step);\n\t\t\t\t}, animation.duration);\n\n\t\t\t\tlink.setIcon(_canvas);\n\t\t\t} else {\n\t\t\t\tcb();\n\t\t\t\treturn;\n\t\t\t}\n\t\t};\n\t\t//auto init\n\t\tinit();\n\t\treturn {\n\t\t\tbadge: badge,\n\t\t\tvideo: video,\n\t\t\timage: image,\n\t\t\twebcam: webcam,\n\t\t\treset: icon.reset,\n\t\t\tbrowser: {\n\t\t\t\tsupported: _browser.supported\n\t\t\t}\n\t\t};\n\t});\n\n\t// AMD / RequireJS\n\tif (typeof define !== 'undefined' && define.amd) {\n\t\tdefine([], function () {\n\t\t\treturn Favico;\n\t\t});\n\t}\n\t// CommonJS\n\telse if (typeof module !== 'undefined' && module.exports) {\n\t\tmodule.exports = Favico;\n\t}\n\t// included directly via <script> tag\n\telse {\n\t\tthis.Favico = Favico;\n\t}\n\n})();\n","// @ts-expect-error: No types available for favico.js\nimport Favico from \"favico.js\";\n\nconst favicon = new Favico({ animation: \"none\" });\n\nlet currentBadgeValue: number | null = null;\n\nvar originalTitle = document.title;\n\nfunction updateTitleWithBadge(title: string) {\n  if (currentBadgeValue !== null && currentBadgeValue > 0) {\n    document.title = `(${currentBadgeValue}) ${title}`;\n  } else {\n    document.title = title;\n  }\n}\n\nexport function setBadge(value: number) {\n  currentBadgeValue = value;\n  favicon.badge(value);\n  updateTitleWithBadge(originalTitle);\n}\n\nexport function clearBadge() {\n  currentBadgeValue = null;\n  favicon.reset();\n  document.title = originalTitle;\n}\n\n// Observe title changes and preserve badge\nconst observer = new MutationObserver(() => {\n  if (document.title !== originalTitle && currentBadgeValue !== null) {\n    // Extract the new title without the badge prefix\n    const match = document.title.match(/^\\(\\d+\\)\\s+(.+)$/);\n    const newTitle = match ? match[1] : document.title;\n    if (newTitle !== originalTitle) {\n      originalTitle = newTitle;\n      updateTitleWithBadge(newTitle);\n    }\n  }\n});\n\nobserver.observe(document.querySelector(\"title\") || document.head, {\n  characterData: true,\n});\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { Logging } from './logging.js';\nexport function assert(x) {\n    if (!x) {\n        throw new Error('Assertion failed.');\n    }\n}\nexport const DEG_TO_RAD = Math.PI / 180;\nexport const RAD_TO_DEG = 180 / Math.PI;\nexport const normalizeRotation = (rotation) => {\n    const mappedRotation = (rotation % 360 + 360) % 360;\n    if (mappedRotation === 0 || mappedRotation === 90 || mappedRotation === 180 || mappedRotation === 270) {\n        return mappedRotation;\n    }\n    else {\n        throw new Error(`Invalid rotation ${rotation}.`);\n    }\n};\nexport const IDENTITY_MATRIX = [1, 0, 0, 0, 1, 0, 0, 0, 1];\n/**\n * Applies a linear transformation (no translation) to a width-by-height frame about its center, with the result\n * sitting in the positive quadrant.\n */\nexport const centeredTransformationMatrix = (linear, width, height) => {\n    const [a, b, , c, d] = linear;\n    // Bounding box of the transformed frame\n    const transformedWidth = Math.abs(a) * width + Math.abs(c) * height;\n    const transformedHeight = Math.abs(b) * width + Math.abs(d) * height;\n    // The transformation happens about the origin (the frame's top-left corner), so we move the center to the\n    // origin, transform, then move it back\n    return multiplyMatrices(multiplyMatrices(translationMatrix(-width / 2, -height / 2), linear), translationMatrix(transformedWidth / 2, transformedHeight / 2));\n};\n/**\n * Extracts the rotation from a transformation matrix, assuming the matrix has the form \"rotate, then maybe flip\n * horizontally\", and snapping to the nearest multiple of 90 degrees.\n */\nexport const extractRotationFromMatrix = (matrix) => {\n    const [a, b] = matrix;\n    // (1, 0) projects onto (a, b), so that's all we need. The rotation is applied before flipping though, so we\n    // first need to undo the flip to isolate the rotation.\n    const radians = Math.atan2(b, matrixIsFlipped(matrix) ? -a : a);\n    return normalizeRotation(roundToMultiple(radians * RAD_TO_DEG, 90));\n};\n/** Whether the transformation matrix flips the frame, i.e. has a negative determinant. */\nexport const matrixIsFlipped = (matrix) => {\n    const [a, b, , c, d] = matrix;\n    const det = a * d - b * c;\n    return det < 0;\n};\nexport const rotationMatrix = (rotationInDegrees) => {\n    const theta = rotationInDegrees * DEG_TO_RAD;\n    const cosTheta = Math.round(Math.cos(theta));\n    const sinTheta = Math.round(Math.sin(theta));\n    // Points are row vectors, meaning this is the transpose of your typical rotation matrix\n    return [\n        cosTheta, sinTheta, 0,\n        -sinTheta, cosTheta, 0,\n        0, 0, 1,\n    ];\n};\nexport const translationMatrix = (x, y) => {\n    // Points are row vectors, meaning this is the transpose of your typical translation matrix\n    return [\n        1, 0, 0,\n        0, 1, 0,\n        x, y, 1,\n    ];\n};\nexport const scaleMatrix = (x, y) => {\n    return [\n        x, 0, 0,\n        0, y, 0,\n        0, 0, 1,\n    ];\n};\n/** Computes a * b. Since points are row vectors, this applies a first, then b. */\nexport const multiplyMatrices = (a, b) => {\n    const result = new Array(9);\n    for (let i = 0; i < 3; i++) {\n        for (let j = 0; j < 3; j++) {\n            result[3 * i + j] = a[3 * i] * b[j] + a[3 * i + 1] * b[3 + j] + a[3 * i + 2] * b[6 + j];\n        }\n    }\n    return result;\n};\n/**\n * Composes two \"rotate, then flip\" transformations into one. A flip conjugates any rotation that follows it, meaning\n * the second rotation flips direction if the first flip is set.\n */\nexport const composeRotationAndFlip = (rotation1, flip1, rotation2, flip2) => {\n    return {\n        rotation: normalizeRotation(rotation1 + (flip1 ? -rotation2 : rotation2)),\n        flip: flip1 !== flip2,\n    };\n};\nexport const last = (arr) => {\n    return arr && arr[arr.length - 1];\n};\nexport const isU32 = (value) => {\n    return value >= 0 && value < 2 ** 32;\n};\nexport const isI32 = (value) => {\n    return value >= -(2 ** 31) && value < 2 ** 31;\n};\n/** Reads an exponential-Golomb universal code from a Bitstream.  */\nexport const readExpGolomb = (bitstream) => {\n    let leadingZeroBits = 0;\n    while (bitstream.readBits(1) === 0 && leadingZeroBits < 32) {\n        leadingZeroBits++;\n    }\n    if (leadingZeroBits >= 32) {\n        throw new Error('Invalid exponential-Golomb code.');\n    }\n    // Not using bit shifts here, since they'd overflow into negative numbers for 31 leading zeros\n    const result = 2 ** leadingZeroBits - 1 + bitstream.readBits(leadingZeroBits);\n    return result;\n};\nexport const writeExpGolomb = (bitstream, value) => {\n    const codeNum = value + 1;\n    const leadingZeroBits = Math.floor(Math.log2(codeNum));\n    bitstream.writeBits(leadingZeroBits, 0);\n    bitstream.writeBits(1, 1);\n    bitstream.writeBits(leadingZeroBits, codeNum - 2 ** leadingZeroBits);\n};\n/** Reads a signed exponential-Golomb universal code from a Bitstream. */\nexport const readSignedExpGolomb = (bitstream) => {\n    const codeNum = readExpGolomb(bitstream);\n    // Division instead of bit shifts, since codeNum may exceed the 32-bit signed range\n    return codeNum % 2 === 0\n        ? -(codeNum / 2)\n        : (codeNum + 1) / 2;\n};\nexport const writeBits = (bytes, start, end, value) => {\n    for (let i = start; i < end; i++) {\n        const byteIndex = Math.floor(i / 8);\n        let byte = bytes[byteIndex];\n        const bitIndex = 0b111 - (i & 0b111);\n        byte &= ~(1 << bitIndex);\n        byte |= ((value & (1 << (end - i - 1))) >> (end - i - 1)) << bitIndex;\n        bytes[byteIndex] = byte;\n    }\n};\nexport const toUint8Array = (source) => {\n    if (source.constructor === Uint8Array) { // We want a true Uint8Array, not something that extends it like Buffer\n        return source;\n    }\n    else if (ArrayBuffer.isView(source)) {\n        return new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n    }\n    else {\n        return new Uint8Array(source);\n    }\n};\nexport const toDataView = (source) => {\n    if (source.constructor === DataView) {\n        return source;\n    }\n    else if (ArrayBuffer.isView(source)) {\n        return new DataView(source.buffer, source.byteOffset, source.byteLength);\n    }\n    else {\n        return new DataView(source);\n    }\n};\n// Include a polyfill for environments that don't have TextEncoder (like AudioWorkletGlobalScope)\nexport const TextEncoder = typeof globalThis.TextEncoder !== 'undefined'\n    ? globalThis.TextEncoder\n    : class TextEncoder {\n        constructor() {\n            this.encoding = 'utf-8';\n        }\n        encode(input = '') {\n            // UTF-8 needs at most 3 bytes per UTF-16 code unit\n            const bytes = new Uint8Array(3 * input.length);\n            let n = 0;\n            for (let i = 0; i < input.length; i++) {\n                let c = input.charCodeAt(i);\n                if (c < 0x80) {\n                    bytes[n++] = c;\n                }\n                else if (c < 0x800) {\n                    bytes[n++] = 0xc0 | (c >> 6);\n                    bytes[n++] = 0x80 | (c & 63);\n                }\n                else if (c < 0xd800 || c > 0xdfff) {\n                    bytes[n++] = 0xe0 | (c >> 12);\n                    bytes[n++] = 0x80 | ((c >> 6) & 63);\n                    bytes[n++] = 0x80 | (c & 63);\n                }\n                else {\n                    const next = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;\n                    if (c < 0xdc00 && next >= 0xdc00 && next <= 0xdfff) {\n                        c = 0x10000 + ((c - 0xd800) << 10) + (next - 0xdc00);\n                        i++;\n                        bytes[n++] = 0xf0 | (c >> 18);\n                        bytes[n++] = 0x80 | ((c >> 12) & 63);\n                        bytes[n++] = 0x80 | ((c >> 6) & 63);\n                        bytes[n++] = 0x80 | (c & 63);\n                    }\n                    else {\n                        bytes[n++] = 0xef;\n                        bytes[n++] = 0xbf;\n                        bytes[n++] = 0xbd;\n                    }\n                }\n            }\n            return bytes.slice(0, n);\n        }\n    };\n// Include a polyfill for environments that don't have TextEncoder (like AudioWorkletGlobalScope)\nexport const TextDecoder = typeof globalThis.TextDecoder !== 'undefined'\n    ? globalThis.TextDecoder\n    : class TextDecoder {\n        constructor(label = 'utf-8') {\n            const normalized = label.trim().toLowerCase();\n            if (normalized === 'utf-8' || normalized === 'utf8' || normalized === 'unicode-1-1-utf-8') {\n                this.encoding = 'utf-8';\n            }\n            else if (normalized === 'utf-16le' || normalized === 'utf-16') {\n                this.encoding = 'utf-16le';\n            }\n            else if (normalized === 'utf-16be') {\n                this.encoding = 'utf-16be';\n            }\n            else {\n                throw new RangeError(`The encoding label provided ('${label}') is invalid.`);\n            }\n        }\n        decode(input) {\n            const bytes = input ? toUint8Array(input) : new Uint8Array(0);\n            const units = [];\n            if (this.encoding === 'utf-8') {\n                let i = bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf ? 3 : 0;\n                while (i < bytes.length) {\n                    const lead = bytes[i];\n                    if (lead < 0x80) {\n                        units.push(lead);\n                        i++;\n                        continue;\n                    }\n                    let continuationCount;\n                    let codePoint;\n                    if (lead >= 0xc2 && lead < 0xe0) {\n                        continuationCount = 1;\n                        codePoint = lead & 0x1f;\n                    }\n                    else if (lead >= 0xe0 && lead < 0xf0) {\n                        continuationCount = 2;\n                        codePoint = lead & 0x0f;\n                    }\n                    else if (lead >= 0xf0 && lead < 0xf5) {\n                        continuationCount = 3;\n                        codePoint = lead & 0x07;\n                    }\n                    else {\n                        units.push(0xfffd);\n                        i++;\n                        continue;\n                    }\n                    let lowerBound = lead === 0xe0 ? 0xa0 : lead === 0xf0 ? 0x90 : 0x80;\n                    let upperBound = lead === 0xed ? 0x9f : lead === 0xf4 ? 0x8f : 0xbf;\n                    let j = 1;\n                    for (; j <= continuationCount; j++) {\n                        const byte = i + j < bytes.length ? bytes[i + j] : 0;\n                        if (byte < lowerBound || byte > upperBound) {\n                            break;\n                        }\n                        codePoint = (codePoint << 6) | (byte & 0x3f);\n                        lowerBound = 0x80;\n                        upperBound = 0xbf;\n                    }\n                    i += j;\n                    if (j <= continuationCount) {\n                        units.push(0xfffd);\n                    }\n                    else if (codePoint >= 0x10000) {\n                        codePoint -= 0x10000;\n                        units.push(0xd800 | (codePoint >> 10), 0xdc00 | (codePoint & 0x3ff));\n                    }\n                    else {\n                        units.push(codePoint);\n                    }\n                }\n            }\n            else {\n                const littleEndian = this.encoding === 'utf-16le';\n                const bomLow = littleEndian ? 0xff : 0xfe;\n                const bomHigh = littleEndian ? 0xfe : 0xff;\n                let i = bytes.length >= 2 && bytes[0] === bomLow && bytes[1] === bomHigh ? 2 : 0;\n                while (i + 1 < bytes.length) {\n                    const unit = littleEndian\n                        ? bytes[i] | (bytes[i + 1] << 8)\n                        : (bytes[i] << 8) | bytes[i + 1];\n                    i += 2;\n                    if (unit >= 0xd800 && unit <= 0xdbff) {\n                        const next = i + 1 < bytes.length\n                            ? (littleEndian ? bytes[i] | (bytes[i + 1] << 8) : (bytes[i] << 8) | bytes[i + 1])\n                            : -1;\n                        if (next >= 0xdc00 && next <= 0xdfff) {\n                            units.push(unit, next);\n                            i += 2;\n                        }\n                        else {\n                            units.push(0xfffd);\n                        }\n                    }\n                    else if (unit >= 0xdc00 && unit <= 0xdfff) {\n                        units.push(0xfffd);\n                    }\n                    else {\n                        units.push(unit);\n                    }\n                }\n                if (i < bytes.length) {\n                    units.push(0xfffd); // Dangling odd byte\n                }\n            }\n            let result = '';\n            for (let i = 0; i < units.length; i += 8192) {\n                result += String.fromCharCode(...units.slice(i, i + 8192));\n            }\n            return result;\n        }\n    };\nexport const textDecoder = /* #__PURE__ */ new TextDecoder();\nexport const textEncoder = /* #__PURE__ */ new TextEncoder();\nexport const isIso88591Compatible = (text) => {\n    for (let i = 0; i < text.length; i++) {\n        const code = text.charCodeAt(i);\n        if (code > 255) {\n            return false;\n        }\n    }\n    return true;\n};\nconst invertObject = (object) => {\n    return Object.fromEntries(Object.entries(object).map(([key, value]) => [value, key]));\n};\n// For the color space mappings, see Rec. ITU-T H.273.\nexport const COLOR_PRIMARIES_MAP = {\n    bt709: 1, // ITU-R BT.709\n    bt470bg: 5, // ITU-R BT.470BG\n    smpte170m: 6, // ITU-R BT.601 525 - SMPTE 170M\n    bt2020: 9, // ITU-R BT.202\n    smpte432: 12, // SMPTE EG 432-1\n};\nexport const COLOR_PRIMARIES_MAP_INVERSE = /* #__PURE__ */ invertObject(COLOR_PRIMARIES_MAP);\nexport const TRANSFER_CHARACTERISTICS_MAP = {\n    'bt709': 1, // ITU-R BT.709\n    'smpte170m': 6, // SMPTE 170M\n    'linear': 8, // Linear transfer characteristics\n    'iec61966-2-1': 13, // IEC 61966-2-1\n    'pq': 16, // Rec. ITU-R BT.2100-2 perceptual quantization (PQ) system\n    'hlg': 18, // Rec. ITU-R BT.2100-2 hybrid loggamma (HLG) system\n};\nexport const TRANSFER_CHARACTERISTICS_MAP_INVERSE = /* #__PURE__ */ invertObject(TRANSFER_CHARACTERISTICS_MAP);\nexport const MATRIX_COEFFICIENTS_MAP = {\n    'rgb': 0, // Identity\n    'bt709': 1, // ITU-R BT.709\n    'bt470bg': 5, // ITU-R BT.470BG\n    'smpte170m': 6, // SMPTE 170M\n    'bt2020-ncl': 9, // ITU-R BT.2020-2 (non-constant luminance)\n};\nexport const MATRIX_COEFFICIENTS_MAP_INVERSE = /* #__PURE__ */ invertObject(MATRIX_COEFFICIENTS_MAP);\nexport const colorSpaceIsComplete = (colorSpace) => {\n    return (!!colorSpace\n        && !!colorSpace.primaries\n        && !!colorSpace.transfer\n        && !!colorSpace.matrix\n        && colorSpace.fullRange !== undefined);\n};\nexport const colorSpaceIsEmpty = (colorSpace) => {\n    return (!colorSpace\n        || (colorSpace.primaries == null\n            && colorSpace.transfer == null\n            && colorSpace.matrix == null\n            && colorSpace.fullRange == null));\n};\nexport const EMPTY_COLOR_SPACE = {\n    primaries: undefined,\n    transfer: undefined,\n    matrix: undefined,\n    fullRange: undefined,\n};\nexport const isAllowSharedBufferSource = (x) => {\n    return (x instanceof ArrayBuffer\n        || (typeof SharedArrayBuffer !== 'undefined' && x instanceof SharedArrayBuffer)\n        || ArrayBuffer.isView(x));\n};\nexport class AsyncMutex {\n    constructor() {\n        this.currentPromise = Promise.resolve();\n        this.pending = 0;\n    }\n    async acquire() {\n        let resolver;\n        const nextPromise = new Promise((resolve) => {\n            let resolved = false;\n            resolver = () => {\n                if (resolved) {\n                    return;\n                }\n                resolve();\n                this.pending--;\n                resolved = true;\n            };\n        });\n        const currentPromiseAlias = this.currentPromise;\n        this.currentPromise = nextPromise;\n        this.pending++;\n        await currentPromiseAlias;\n        return resolver;\n    }\n}\nexport const HEX_STRING_REGEX = /^[0-9a-fA-F]+$/;\nexport const bytesToHexString = (bytes) => {\n    return [...bytes].map(x => x.toString(16).padStart(2, '0')).join('');\n};\nexport const hexStringToBytes = (hexString) => {\n    assert(hexString.length % 2 === 0);\n    const bytes = new Uint8Array(hexString.length / 2);\n    for (let i = 0; i < hexString.length; i += 2) {\n        bytes[i / 2] = parseInt(hexString.slice(i, i + 2), 16);\n    }\n    return bytes;\n};\nexport const reverseBitsU32 = (x) => {\n    x = ((x >> 1) & 0x55555555) | ((x & 0x55555555) << 1);\n    x = ((x >> 2) & 0x33333333) | ((x & 0x33333333) << 2);\n    x = ((x >> 4) & 0x0f0f0f0f) | ((x & 0x0f0f0f0f) << 4);\n    x = ((x >> 8) & 0x00ff00ff) | ((x & 0x00ff00ff) << 8);\n    x = ((x >> 16) & 0x0000ffff) | ((x & 0x0000ffff) << 16);\n    return x >>> 0; // Ensure it's treated as an unsigned 32-bit integer\n};\n/** Returns the smallest index i such that val[i] === key, or -1 if no such index exists. */\nexport const binarySearchExact = (arr, key, valueGetter) => {\n    let low = 0;\n    let high = arr.length - 1;\n    let ans = -1;\n    while (low <= high) {\n        const mid = (low + high) >> 1;\n        const midVal = valueGetter(arr[mid]);\n        if (midVal === key) {\n            ans = mid;\n            high = mid - 1; // Continue searching left to find the lowest index\n        }\n        else if (midVal < key) {\n            low = mid + 1;\n        }\n        else {\n            high = mid - 1;\n        }\n    }\n    return ans;\n};\n/** Returns the largest index i such that val[i] <= key, or -1 if no such index exists. */\nexport const binarySearchLessOrEqual = (arr, key, valueGetter) => {\n    let low = 0;\n    let high = arr.length - 1;\n    let ans = -1;\n    while (low <= high) {\n        const mid = (low + (high - low + 1) / 2) | 0;\n        const midVal = valueGetter(arr[mid]);\n        if (midVal <= key) {\n            ans = mid;\n            low = mid + 1;\n        }\n        else {\n            high = mid - 1;\n        }\n    }\n    return ans;\n};\n/** Assumes the array is already sorted. */\nexport const insertSorted = (arr, item, valueGetter) => {\n    const insertionIndex = binarySearchLessOrEqual(arr, valueGetter(item), valueGetter);\n    arr.splice(insertionIndex + 1, 0, item); // This even behaves correctly for the -1 case\n};\nexport const promiseWithResolvers = () => {\n    let resolve;\n    let reject;\n    const promise = new Promise((res, rej) => {\n        resolve = res;\n        reject = rej;\n    });\n    return { promise, resolve: resolve, reject: reject };\n};\nexport const removeItem = (arr, item) => {\n    const index = arr.indexOf(item);\n    if (index !== -1) {\n        arr.splice(index, 1);\n    }\n};\nexport const findLast = (arr, predicate) => {\n    for (let i = arr.length - 1; i >= 0; i--) {\n        if (predicate(arr[i])) {\n            return arr[i];\n        }\n    }\n    return undefined;\n};\nexport const findLastIndex = (arr, predicate) => {\n    for (let i = arr.length - 1; i >= 0; i--) {\n        if (predicate(arr[i])) {\n            return i;\n        }\n    }\n    return -1;\n};\nexport const toAsyncIterator = async function* (source) {\n    if (Symbol.iterator in source) {\n        // @ts-expect-error Trust me\n        yield* source[Symbol.iterator]();\n    }\n    else {\n        // @ts-expect-error Trust me\n        yield* source[Symbol.asyncIterator]();\n    }\n};\nexport const validateAnyIterable = (iterable) => {\n    if (!(Symbol.iterator in iterable) && !(Symbol.asyncIterator in iterable)) {\n        throw new TypeError('Argument must be an iterable or async iterable.');\n    }\n};\nexport const assertNever = (x) => {\n    // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n    throw new Error(`Unexpected value: ${x}`);\n};\nexport const getUint24 = (view, byteOffset, littleEndian) => {\n    const byte1 = view.getUint8(byteOffset);\n    const byte2 = view.getUint8(byteOffset + 1);\n    const byte3 = view.getUint8(byteOffset + 2);\n    if (littleEndian) {\n        return byte1 | (byte2 << 8) | (byte3 << 16);\n    }\n    else {\n        return (byte1 << 16) | (byte2 << 8) | byte3;\n    }\n};\nexport const getInt24 = (view, byteOffset, littleEndian) => {\n    // The left shift pushes the most significant bit into the sign bit region, and the subsequent right shift\n    // then correctly interprets the sign bit.\n    return getUint24(view, byteOffset, littleEndian) << 8 >> 8;\n};\nexport const setUint24 = (view, byteOffset, value, littleEndian) => {\n    // Ensure the value is within 24-bit unsigned range (0 to 16777215)\n    value = value >>> 0; // Convert to unsigned 32-bit\n    value = value & 0xFFFFFF; // Mask to 24 bits\n    if (littleEndian) {\n        view.setUint8(byteOffset, value & 0xFF);\n        view.setUint8(byteOffset + 1, (value >>> 8) & 0xFF);\n        view.setUint8(byteOffset + 2, (value >>> 16) & 0xFF);\n    }\n    else {\n        view.setUint8(byteOffset, (value >>> 16) & 0xFF);\n        view.setUint8(byteOffset + 1, (value >>> 8) & 0xFF);\n        view.setUint8(byteOffset + 2, value & 0xFF);\n    }\n};\nexport const setInt24 = (view, byteOffset, value, littleEndian) => {\n    // Ensure the value is within 24-bit signed range (-8388608 to 8388607)\n    value = clamp(value, -8388608, 8388607);\n    // Convert negative values to their 24-bit representation\n    if (value < 0) {\n        value = (value + 0x1000000) & 0xFFFFFF;\n    }\n    setUint24(view, byteOffset, value, littleEndian);\n};\nexport const setInt64 = (view, byteOffset, value, littleEndian) => {\n    if (littleEndian) {\n        view.setUint32(byteOffset + 0, value, true);\n        view.setInt32(byteOffset + 4, Math.floor(value / 2 ** 32), true);\n    }\n    else {\n        view.setInt32(byteOffset + 0, Math.floor(value / 2 ** 32), true);\n        view.setUint32(byteOffset + 4, value, true);\n    }\n};\n/**\n * Calls a function on each value spat out by an async generator. The reason for writing this manually instead of\n * using a generator function is that the generator function queues return() calls - here, we forward them immediately.\n */\nexport const mapAsyncGenerator = (generator, map) => {\n    return {\n        async next() {\n            const result = await generator.next();\n            if (result.done) {\n                return { value: undefined, done: true };\n            }\n            else {\n                return { value: map(result.value), done: false };\n            }\n        },\n        return() {\n            return generator.return();\n        },\n        throw(error) {\n            return generator.throw(error);\n        },\n        [Symbol.asyncIterator]() {\n            return this;\n        },\n    };\n};\nexport const clamp = (value, min, max) => {\n    return Math.max(min, Math.min(max, value));\n};\nexport const lerp = (from, to, t) => {\n    return from + (to - from) * t;\n};\nexport const modEuclid = (value, modulus) => {\n    return value - Math.floor(value / modulus) * modulus;\n};\nexport const UNDETERMINED_LANGUAGE = 'und';\nexport const roundIfAlmostInteger = (value) => {\n    const rounded = Math.round(value);\n    if (Math.abs(value / rounded - 1) < 10 * Number.EPSILON) {\n        return rounded;\n    }\n    else {\n        return value;\n    }\n};\nexport const roundToMultiple = (value, multiple) => {\n    return Math.round(value / multiple) * multiple;\n};\nexport const roundToDivisor = (value, multiple) => {\n    return Math.round(value * multiple) / multiple;\n};\nexport const floorToMultiple = (value, multiple) => {\n    return Math.floor(value / multiple) * multiple;\n};\nexport const floorToDivisor = (value, multiple) => {\n    return Math.floor(value * multiple) / multiple;\n};\nexport const ilog = (x) => {\n    let ret = 0;\n    while (x) {\n        ret++;\n        x >>= 1;\n    }\n    return ret;\n};\nexport const popcount = (value) => {\n    let count = 0;\n    while (value !== 0) {\n        value &= value - 1;\n        count++;\n    }\n    return count;\n};\nconst ISO_639_2_REGEX = /^[a-z]{3}$/;\nexport const isIso639Dash2LanguageCode = (x) => {\n    return ISO_639_2_REGEX.test(x);\n};\n// Since the result will be truncated, add a bit of eps to compensate for floating point errors\nexport const SECOND_TO_MICROSECOND_FACTOR = 1e6 * (1 + Number.EPSILON);\n/**\n * Merges two RequestInit objects with special handling for headers.\n * Headers are merged case-insensitively, but original casing is preserved.\n * init2 headers take precedence and will override case-insensitive matches from init1.\n */\nexport const mergeRequestInit = (init1, init2) => {\n    const merged = { ...init1, ...init2 };\n    // Special handling for headers\n    if (init1.headers || init2.headers) {\n        const headers1 = init1.headers ? normalizeHeaders(init1.headers) : {};\n        const headers2 = init2.headers ? normalizeHeaders(init2.headers) : {};\n        const mergedHeaders = { ...headers1 };\n        // For each header in headers2, check if a case-insensitive match exists in mergedHeaders\n        Object.entries(headers2).forEach(([key2, value2]) => {\n            const existingKey = Object.keys(mergedHeaders).find(key1 => key1.toLowerCase() === key2.toLowerCase());\n            if (existingKey) {\n                delete mergedHeaders[existingKey];\n            }\n            mergedHeaders[key2] = value2;\n        });\n        merged.headers = mergedHeaders;\n    }\n    return merged;\n};\n/** Normalizes HeadersInit to a Record<string, string> format. */\nexport const normalizeHeaders = (headers) => {\n    if (headers instanceof Headers) {\n        const result = {};\n        headers.forEach((value, key) => {\n            result[key] = value;\n        });\n        return result;\n    }\n    if (Array.isArray(headers)) {\n        const result = {};\n        headers.forEach(([key, value]) => {\n            result[key] = value;\n        });\n        return result;\n    }\n    return headers;\n};\nexport const retriedFetch = async (fetchFn, url, requestInit, getRetryDelay, shouldStop) => {\n    let attempts = 0;\n    while (true) {\n        try {\n            return await fetchFn(url, requestInit);\n        }\n        catch (error) {\n            if (shouldStop()) {\n                throw error;\n            }\n            attempts++;\n            const retryDelayInSeconds = getRetryDelay(attempts, error, url);\n            if (retryDelayInSeconds === null) {\n                throw error;\n            }\n            Logging._error('Retrying failed fetch. Error:', error);\n            if (!Number.isFinite(retryDelayInSeconds) || retryDelayInSeconds < 0) {\n                throw new TypeError('Retry delay must be a non-negative finite number.');\n            }\n            if (retryDelayInSeconds > 0) {\n                await wait(1000 * retryDelayInSeconds);\n            }\n            if (shouldStop()) {\n                throw error;\n            }\n        }\n    }\n};\nexport const computeRationalApproximation = (x, maxDenominator) => {\n    // Handle negative numbers\n    const sign = x < 0 ? -1 : 1;\n    x = Math.abs(x);\n    let prevNumerator = 0, prevDenominator = 1;\n    let currNumerator = 1, currDenominator = 0;\n    // Continued fraction algorithm\n    let remainder = x;\n    while (true) {\n        const integer = Math.floor(remainder);\n        // Calculate next convergent\n        const nextNumerator = integer * currNumerator + prevNumerator;\n        const nextDenominator = integer * currDenominator + prevDenominator;\n        if (nextDenominator > maxDenominator) {\n            return {\n                num: sign * currNumerator,\n                den: currDenominator,\n            };\n        }\n        prevNumerator = currNumerator;\n        prevDenominator = currDenominator;\n        currNumerator = nextNumerator;\n        currDenominator = nextDenominator;\n        remainder = 1 / (remainder - integer);\n        // Guard against precision issues\n        if (!isFinite(remainder)) {\n            break;\n        }\n    }\n    return {\n        num: sign * currNumerator,\n        den: currDenominator,\n    };\n};\nexport class CallSerializer {\n    constructor() {\n        this.currentPromise = Promise.resolve();\n    }\n    call(fn) {\n        return this.currentPromise = this.currentPromise.then(fn);\n    }\n}\nlet isWebKitCache = null;\nexport const isWebKit = () => {\n    if (isWebKitCache !== null) {\n        return isWebKitCache;\n    }\n    // This even returns true for WebKit-wrapping browsers such as Chrome on iOS\n    return isWebKitCache = !!(typeof navigator !== 'undefined'\n        && (\n        // eslint-disable-next-line @typescript-eslint/no-deprecated\n        navigator.vendor?.match(/apple/i)\n            // Or, in workers:\n            || (/AppleWebKit/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent))\n            || /\\b(iPad|iPhone|iPod)\\b/.test(navigator.userAgent)));\n};\nlet isFirefoxCache = null;\nexport const isFirefox = () => {\n    if (isFirefoxCache !== null) {\n        return isFirefoxCache;\n    }\n    return isFirefoxCache = typeof navigator !== 'undefined' && navigator.userAgent?.includes('Firefox');\n};\nlet isChromiumCache = null;\nexport const isChromium = () => {\n    if (isChromiumCache !== null) {\n        return isChromiumCache;\n    }\n    return isChromiumCache = !!(typeof navigator !== 'undefined'\n        // eslint-disable-next-line @typescript-eslint/no-deprecated\n        && (navigator.vendor?.includes('Google Inc') || /Chrome/.test(navigator.userAgent)));\n};\nlet chromiumVersionCache = null;\nexport const getChromiumVersion = () => {\n    if (chromiumVersionCache !== null) {\n        return chromiumVersionCache;\n    }\n    if (typeof navigator === 'undefined') {\n        return null;\n    }\n    const match = /\\bChrome\\/(\\d+)/.exec(navigator.userAgent);\n    if (!match) {\n        return null;\n    }\n    return chromiumVersionCache = Number(match[1]);\n};\nexport const missingWebCodecsClassMessage = (className) => {\n    if (typeof globalThis.isSecureContext !== 'undefined' && !globalThis.isSecureContext) {\n        // WebCodecs is not exposed in insecure contexts\n        return `${className} is not available in this environment; this may be because this page is running in an`\n            + ` insecure context. Try serving your page over HTTPS or use localhost.`;\n    }\n    return `${className} is not available in this environment.`;\n};\n// Browsers (at least Chromium) close codecs that have been idle for a long time and report this error\nexport const isCodecReclaimedError = (error) => {\n    return error instanceof DOMException\n        && error.name === 'QuotaExceededError'\n        && /reclaimed/i.test(error.message);\n};\nconst NativePromiseConstructor = /* #__PURE__ */ (async () => { })().constructor;\n/**\n * Needed to properly deal with custom Promise implementations and because this is closer to how the JS spec does it.\n */\nexport const isThenable = (value) => {\n    if (value instanceof NativePromiseConstructor || value instanceof Promise) {\n        return true;\n    }\n    // Fall back to a crude duck typing check\n    return typeof value?.then === 'function';\n};\n/** Acts like `??` except the condition is -1 and not null/undefined. */\nexport const coalesceIndex = (a, b) => {\n    return a !== -1 ? a : b;\n};\nexport const closedIntervalsOverlap = (startA, endA, startB, endB) => {\n    return startA <= endB && startB <= endA;\n};\nexport const keyValueIterator = function* (object) {\n    for (const key in object) {\n        const value = object[key];\n        if (value === undefined) {\n            continue;\n        }\n        yield { key, value };\n    }\n};\nexport const imageMimeTypeToExtension = (mimeType) => {\n    switch (mimeType.toLowerCase()) {\n        case 'image/jpeg':\n        case 'image/jpg':\n            return '.jpg';\n        case 'image/png':\n            return '.png';\n        case 'image/gif':\n            return '.gif';\n        case 'image/webp':\n            return '.webp';\n        case 'image/bmp':\n            return '.bmp';\n        case 'image/svg+xml':\n            return '.svg';\n        case 'image/tiff':\n            return '.tiff';\n        case 'image/avif':\n            return '.avif';\n        case 'image/x-icon':\n        case 'image/vnd.microsoft.icon':\n            return '.ico';\n        default:\n            return null;\n    }\n};\nexport const base64ToBytes = (base64) => {\n    let decoded;\n    try {\n        decoded = atob(base64);\n    }\n    catch {\n        throw new Error('Invalid base64 string.');\n    }\n    const bytes = new Uint8Array(decoded.length);\n    for (let i = 0; i < decoded.length; i++) {\n        bytes[i] = decoded.charCodeAt(i);\n    }\n    return bytes;\n};\nexport const bytesToBase64 = (bytes) => {\n    let string = '';\n    for (let i = 0; i < bytes.length; i++) {\n        string += String.fromCharCode(bytes[i]);\n    }\n    return btoa(string);\n};\nexport const uint8ArraysAreEqual = (a, b) => {\n    if (a.length !== b.length) {\n        return false;\n    }\n    for (let i = 0; i < a.length; i++) {\n        if (a[i] !== b[i]) {\n            return false;\n        }\n    }\n    return true;\n};\nexport const polyfillSymbolDispose = () => {\n    // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html\n    // @ts-expect-error Readonly\n    Symbol.dispose ??= Symbol('Symbol.dispose');\n};\nexport const isNumber = (x) => {\n    return typeof x === 'number' && !Number.isNaN(x);\n};\nexport const joinPaths = (basePath, relativePath) => {\n    // If relativePath is a full URL with protocol, return it as-is\n    if (relativePath.includes('://')) {\n        return relativePath;\n    }\n    // Strip query parameters from URL base paths so their contents don't mess up the join\n    if (basePath.includes('://')) {\n        const queryIndex = basePath.indexOf('?');\n        if (queryIndex !== -1) {\n            basePath = basePath.slice(0, queryIndex);\n        }\n    }\n    let result;\n    if (relativePath.startsWith('/')) {\n        const protocolIndex = basePath.indexOf('://');\n        if (protocolIndex === -1) {\n            result = relativePath;\n        }\n        else {\n            const pathStart = basePath.indexOf('/', protocolIndex + 3);\n            if (pathStart === -1) {\n                result = basePath + relativePath;\n            }\n            else {\n                result = basePath.slice(0, pathStart) + relativePath;\n            }\n        }\n    }\n    else {\n        const lastSlash = basePath.lastIndexOf('/');\n        if (lastSlash === -1) {\n            result = relativePath;\n        }\n        else {\n            result = basePath.slice(0, lastSlash + 1) + relativePath;\n        }\n    }\n    // Normalize ./ and ../\n    let prefix = '';\n    const protocolIndex = result.indexOf('://');\n    if (protocolIndex !== -1) {\n        const pathStart = result.indexOf('/', protocolIndex + 3);\n        if (pathStart !== -1) {\n            prefix = result.slice(0, pathStart);\n            result = result.slice(pathStart);\n        }\n    }\n    const segments = result.split('/');\n    const normalized = [];\n    for (const segment of segments) {\n        if (segment === '..') {\n            normalized.pop();\n        }\n        else if (segment !== '.') {\n            normalized.push(segment);\n        }\n    }\n    return prefix + normalized.join('/');\n};\n// eg. path `/media.m3u8?token=abc%20123` and name `token` resolve to `abc 123`\nexport const getQueryParameter = (path, name) => {\n    const queryIndex = path.indexOf('?');\n    if (queryIndex === -1) {\n        return null;\n    }\n    const fragmentIndex = path.indexOf('#', queryIndex);\n    const query = path.slice(queryIndex + 1, fragmentIndex === -1 ? undefined : fragmentIndex);\n    for (const parameter of query.split('&')) {\n        const equalsIndex = parameter.indexOf('=');\n        const encodedName = equalsIndex === -1 ? parameter : parameter.slice(0, equalsIndex);\n        const encodedValue = equalsIndex === -1 ? '' : parameter.slice(equalsIndex + 1);\n        try {\n            if (decodeURIComponent(encodedName) === name) {\n                return decodeURIComponent(encodedValue);\n            }\n        }\n        catch {\n            // Malformed percent-encoding, so let's not treat this as the parameter we're looking for\n        }\n    }\n    return null;\n};\nexport const arrayCount = (array, predicate) => {\n    let count = 0;\n    for (let i = 0; i < array.length; i++) {\n        if (predicate(array[i])) {\n            count++;\n        }\n    }\n    return count;\n};\nexport const arrayArgmin = (array, getValue) => {\n    let minIndex = -1;\n    let minValue = Infinity;\n    for (let i = 0; i < array.length; i++) {\n        const value = getValue(array[i]);\n        if (value < minValue) {\n            minValue = value;\n            minIndex = i;\n        }\n    }\n    return minIndex;\n};\nexport const arrayArgmax = (array, getValue) => {\n    let maxIndex = -1;\n    let maxValue = -Infinity;\n    for (let i = 0; i < array.length; i++) {\n        const value = getValue(array[i]);\n        if (value > maxValue) {\n            maxValue = value;\n            maxIndex = i;\n        }\n    }\n    return maxIndex;\n};\nexport const simplifyRational = (rational) => {\n    assert(Number.isInteger(rational.num));\n    assert(Number.isInteger(rational.den));\n    assert(rational.den !== 0);\n    let a = Math.abs(rational.num);\n    let b = Math.abs(rational.den);\n    // Euclidean algorithm\n    while (b !== 0) {\n        const t = a % b;\n        a = b;\n        b = t;\n    }\n    const gcd = a || 1;\n    return {\n        num: rational.num / gcd,\n        den: rational.den / gcd,\n    };\n};\nexport const validateRectangle = (rect, propertyPath) => {\n    if (typeof rect !== 'object' || !rect) {\n        throw new TypeError(`${propertyPath} must be an object.`);\n    }\n    if (!Number.isInteger(rect.left) || rect.left < 0) {\n        throw new TypeError(`${propertyPath}.left must be a non-negative integer.`);\n    }\n    if (!Number.isInteger(rect.top) || rect.top < 0) {\n        throw new TypeError(`${propertyPath}.top must be a non-negative integer.`);\n    }\n    if (!Number.isInteger(rect.width) || rect.width < 0) {\n        throw new TypeError(`${propertyPath}.width must be a non-negative integer.`);\n    }\n    if (!Number.isInteger(rect.height) || rect.height < 0) {\n        throw new TypeError(`${propertyPath}.height must be a non-negative integer.`);\n    }\n};\nlet unthrottledTimerWorker;\nlet nextUnthrottledTimerId = 1;\nconst unthrottledTimeoutCallbacks = new Map();\nconst unthrottledIntervalCallbacks = new Map();\nconst shouldUseNativeTimers = () => {\n    return typeof window === 'undefined';\n};\nconst unthrottledTimerWorkerMain = () => {\n    const timeoutHandles = new Map();\n    const intervalHandles = new Map();\n    self.onmessage = (event) => {\n        const message = event.data;\n        switch (message.type) {\n            case 'set-timeout':\n                {\n                    const handle = setTimeout(() => {\n                        timeoutHandles.delete(message.timerId);\n                        self.postMessage({ type: 'fire', timerId: message.timerId });\n                    }, message.delay);\n                    timeoutHandles.set(message.timerId, handle);\n                }\n                ;\n                break;\n            case 'set-interval':\n                {\n                    const handle = setInterval(() => {\n                        self.postMessage({ type: 'fire', timerId: message.timerId });\n                    }, message.delay);\n                    intervalHandles.set(message.timerId, handle);\n                }\n                ;\n                break;\n            case 'clear-timeout':\n                {\n                    const handle = timeoutHandles.get(message.timerId);\n                    if (handle !== undefined) {\n                        clearTimeout(handle);\n                        timeoutHandles.delete(message.timerId);\n                    }\n                }\n                ;\n                break;\n            case 'clear-interval':\n                {\n                    const handle = intervalHandles.get(message.timerId);\n                    if (handle !== undefined) {\n                        clearInterval(handle);\n                        intervalHandles.delete(message.timerId);\n                    }\n                }\n                ;\n                break;\n        }\n    };\n};\nconst getUnthrottledTimerWorker = () => {\n    if (unthrottledTimerWorker) {\n        return unthrottledTimerWorker;\n    }\n    const workerSource = `(${unthrottledTimerWorkerMain.toString()})();`;\n    const workerURL = URL.createObjectURL(new Blob([workerSource], { type: 'text/javascript' }));\n    unthrottledTimerWorker = new Worker(workerURL);\n    URL.revokeObjectURL(workerURL);\n    unthrottledTimerWorker.onmessage = (event) => {\n        const message = event.data;\n        const timeoutCallback = unthrottledTimeoutCallbacks.get(message.timerId);\n        if (timeoutCallback) {\n            unthrottledTimeoutCallbacks.delete(message.timerId);\n            timeoutCallback();\n            return;\n        }\n        const intervalCallback = unthrottledIntervalCallbacks.get(message.timerId);\n        if (intervalCallback) {\n            intervalCallback();\n        }\n    };\n    return unthrottledTimerWorker;\n};\nexport const setTimeoutUnthrottled = (\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\ncallback, delay) => {\n    if (shouldUseNativeTimers()) {\n        return { id: setTimeout(callback, delay) };\n    }\n    const timerId = nextUnthrottledTimerId++;\n    unthrottledTimeoutCallbacks.set(timerId, () => {\n        callback();\n    });\n    getUnthrottledTimerWorker().postMessage({\n        type: 'set-timeout',\n        timerId,\n        delay,\n    });\n    return { id: timerId };\n};\nexport const clearTimeoutUnthrottled = (timer) => {\n    if (shouldUseNativeTimers()) {\n        clearTimeout(timer.id);\n        return;\n    }\n    assert(typeof timer.id === 'number');\n    unthrottledTimeoutCallbacks.delete(timer.id);\n    getUnthrottledTimerWorker().postMessage({\n        type: 'clear-timeout',\n        timerId: timer.id,\n    });\n};\nexport const setIntervalUnthrottled = (\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\ncallback, delay) => {\n    if (shouldUseNativeTimers()) {\n        return { id: setInterval(callback, delay) };\n    }\n    const timerId = nextUnthrottledTimerId++;\n    unthrottledIntervalCallbacks.set(timerId, () => {\n        callback();\n    });\n    getUnthrottledTimerWorker().postMessage({\n        type: 'set-interval',\n        timerId,\n        delay,\n    });\n    return { id: timerId };\n};\nexport const clearIntervalUnthrottled = (timer) => {\n    if (shouldUseNativeTimers()) {\n        clearInterval(timer.id);\n        return;\n    }\n    assert(typeof timer.id === 'number');\n    unthrottledIntervalCallbacks.delete(timer.id);\n    getUnthrottledTimerWorker().postMessage({\n        type: 'clear-interval',\n        timerId: timer.id,\n    });\n};\nexport const wait = (ms) => {\n    return new Promise(resolve => setTimeout(resolve, ms));\n};\nexport const rejectAfter = (ms, message = 'Promise rejected') => {\n    return new Promise((_, reject) => {\n        setTimeout(() => reject(new Error(message)), ms);\n    });\n};\nexport const toArray = (x) => {\n    if (Array.isArray(x)) {\n        return x;\n    }\n    else {\n        return [x];\n    }\n};\n/**\n * A class that manages event listeners and dispatches events to them.\n *\n * @group Miscellaneous\n * @public\n */\nexport class EventEmitter {\n    constructor() {\n        /** @internal */\n        this._listeners = new Map();\n    }\n    /** Registers a listener for the given event. Returns a function that, when called, removes the listener again. */\n    on(event, listener, options) {\n        if (!this._listeners.has(event)) {\n            this._listeners.set(event, new Set());\n        }\n        const entry = { fn: listener, once: options?.once ?? false };\n        this._listeners.get(event).add(entry);\n        return () => {\n            this._listeners.get(event)?.delete(entry);\n        };\n    }\n    /** @internal */\n    _emit(...args) {\n        const [event, data] = args;\n        const listeners = this._listeners.get(event);\n        if (!listeners) {\n            return;\n        }\n        for (const entry of listeners) {\n            try {\n                entry.fn(data);\n            }\n            catch (error) {\n                // Deliberately not routed through Logging here: Logging emits via an EventEmitter, so a throwing\n                // log listener would recurse straight back into this handler.\n                console.error(error);\n            }\n            if (entry.once) {\n                listeners.delete(entry);\n            }\n        }\n    }\n}\nexport const ceilToMultipleOfTwo = (value) => Math.ceil(value / 2) * 2;\n/**\n * Utility class for running async functions in parallel up to a certain level of parallelism. Can be used to apply\n * backpressure only if the concurrency level would be exceeded.\n *\n * @group Miscellaneous\n * @public\n*/\nexport class ConcurrentRunner {\n    constructor(parallelism) {\n        /** @internal */\n        this._queue = [];\n        /** @internal */\n        this._errored = false;\n        this.parallelism = parallelism;\n    }\n    /** Whether any function has errored. The runner is effectively bricked if this is `true`, by design. */\n    get errored() {\n        return this._errored;\n    }\n    /** The number of tasks currently running. */\n    get inFlightCount() {\n        return this._queue.length;\n    }\n    /**\n     * Schedules an async function to be run. If the maximum allowed level of parallelism has not yet been reached,\n     * the function will be executed immediately and `run()` will resolve immediately. Otherwise, the function will be\n     * called as soon as any currently-running function finishes, and `run()` will only resolve then.\n     *\n     * Throws if the runner is errored.\n     */\n    async run(fn) {\n        if (this._errored) {\n            await Promise.race(this._queue); // Will surface the error\n        }\n        while (this._queue.length >= this.parallelism) {\n            await Promise.race(this._queue);\n        }\n        const promise = fn();\n        this._queue.push(promise);\n        void promise\n            .then(() => removeItem(this._queue, promise))\n            .catch(() => this._errored = true);\n    }\n    /** Waits for all currently running functions to finish. Throws if the runner is errored. */\n    async flush() {\n        await Promise.all(this._queue);\n    }\n}\nexport const isRecordStringString = (value) => {\n    return value !== null\n        && typeof value === 'object'\n        && Object.getPrototypeOf(value) === Object.prototype\n        && Object.values(value).every(x => typeof x === 'string');\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { EventEmitter } from './misc.js';\n/**\n * Controls how much information Mediabunny prints to the console. Higher levels include all lower levels.\n *\n * @group Logging\n * @public\n */\nexport var LogLevel;\n(function (LogLevel) {\n    /** Nothing is printed to the console. */\n    LogLevel[LogLevel[\"Silent\"] = 0] = \"Silent\";\n    /** Only errors are printed. */\n    LogLevel[LogLevel[\"Errors\"] = 1] = \"Errors\";\n    /** Errors and warnings are printed. */\n    LogLevel[LogLevel[\"Warnings\"] = 2] = \"Warnings\";\n    /** Errors, warnings, and informational messages are printed. */\n    LogLevel[LogLevel[\"Info\"] = 3] = \"Info\";\n})(LogLevel || (LogLevel = {}));\n/**\n * Mediabunny's central logging singleton. Use {@link Logging.level} to control how much is printed to the console,\n * and subscribe to log events using {@link Logging.on}.\n *\n * Having manual control over logging is useful for command-line applications where you want full say over the output.\n *\n * @group Logging\n * @public\n */\nexport class Logging {\n    constructor() { }\n    /** The current log level. Defaults to {@link LogLevel.Info}. */\n    static get level() {\n        return Logging._level;\n    }\n    static set level(value) {\n        if (value !== LogLevel.Silent\n            && value !== LogLevel.Errors\n            && value !== LogLevel.Warnings\n            && value !== LogLevel.Info) {\n            throw new TypeError('Invalid log level. Use one of the values of the LogLevel enum.');\n        }\n        Logging._level = value;\n    }\n    /** @internal */\n    static get _emitter() {\n        // Created lazily to avoid touching the EventEmitter binding at module-eval time\n        return Logging._emitterInstance ??= new EventEmitter();\n    }\n    /** Registers a listener for a log event. Returns a function that, when called, removes the listener again. */\n    static on(event, listener, options) {\n        return Logging._emitter.on(event, listener, options);\n    }\n    /** @internal */\n    static _error(...args) {\n        Logging._emitter._emit('error', args);\n        if (Logging._level >= LogLevel.Errors) {\n            console.error(...args);\n        }\n    }\n    /** @internal */\n    static _warn(...args) {\n        Logging._emitter._emit('warn', args);\n        if (Logging._level >= LogLevel.Warnings) {\n            console.warn(...args);\n        }\n    }\n    /** @internal */\n    static _info(...args) {\n        Logging._emitter._emit('info', args);\n        if (Logging._level >= LogLevel.Info) {\n            console.info(...args);\n        }\n    }\n}\n/** @internal */\nLogging._level = LogLevel.Info;\n/** @internal */\nLogging._emitterInstance = null;\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { isRecordStringString } from './misc.js';\n/**\n * Image data with additional metadata.\n *\n * @group Metadata tags\n * @public\n */\nexport class RichImageData {\n    /** Creates a new {@link RichImageData}. */\n    constructor(\n    /** The raw image data. */\n    data, \n    /** An RFC 6838 MIME type (e.g. image/jpeg, image/png, etc.) */\n    mimeType) {\n        this.data = data;\n        this.mimeType = mimeType;\n        if (!(data instanceof Uint8Array)) {\n            throw new TypeError('data must be a Uint8Array.');\n        }\n        if (typeof mimeType !== 'string') {\n            throw new TypeError('mimeType must be a string.');\n        }\n    }\n}\n/**\n * A file attached to a media file.\n *\n * @group Metadata tags\n * @public\n */\nexport class AttachedFile {\n    /** Creates a new {@link AttachedFile}. */\n    constructor(\n    /** The raw file data. */\n    data, \n    /** An RFC 6838 MIME type (e.g. image/jpeg, image/png, font/ttf, etc.) */\n    mimeType, \n    /** The name of the file. */\n    name, \n    /** A description of the file. */\n    description) {\n        this.data = data;\n        this.mimeType = mimeType;\n        this.name = name;\n        this.description = description;\n        if (!(data instanceof Uint8Array)) {\n            throw new TypeError('data must be a Uint8Array.');\n        }\n        if (mimeType !== undefined && typeof mimeType !== 'string') {\n            throw new TypeError('mimeType, when provided, must be a string.');\n        }\n        if (name !== undefined && typeof name !== 'string') {\n            throw new TypeError('name, when provided, must be a string.');\n        }\n        if (description !== undefined && typeof description !== 'string') {\n            throw new TypeError('description, when provided, must be a string.');\n        }\n    }\n}\n;\nexport const validateMetadataTags = (tags) => {\n    if (!tags || typeof tags !== 'object') {\n        throw new TypeError('tags must be an object.');\n    }\n    if (tags.title !== undefined && typeof tags.title !== 'string') {\n        throw new TypeError('tags.title, when provided, must be a string.');\n    }\n    if (tags.description !== undefined && typeof tags.description !== 'string') {\n        throw new TypeError('tags.description, when provided, must be a string.');\n    }\n    if (tags.artist !== undefined && typeof tags.artist !== 'string') {\n        throw new TypeError('tags.artist, when provided, must be a string.');\n    }\n    if (tags.album !== undefined && typeof tags.album !== 'string') {\n        throw new TypeError('tags.album, when provided, must be a string.');\n    }\n    if (tags.albumArtist !== undefined && typeof tags.albumArtist !== 'string') {\n        throw new TypeError('tags.albumArtist, when provided, must be a string.');\n    }\n    if (tags.trackNumber !== undefined && (!Number.isInteger(tags.trackNumber) || tags.trackNumber <= 0)) {\n        throw new TypeError('tags.trackNumber, when provided, must be a positive integer.');\n    }\n    if (tags.tracksTotal !== undefined\n        && (!Number.isInteger(tags.tracksTotal) || tags.tracksTotal <= 0)) {\n        throw new TypeError('tags.tracksTotal, when provided, must be a positive integer.');\n    }\n    if (tags.discNumber !== undefined && (!Number.isInteger(tags.discNumber) || tags.discNumber <= 0)) {\n        throw new TypeError('tags.discNumber, when provided, must be a positive integer.');\n    }\n    if (tags.discsTotal !== undefined\n        && (!Number.isInteger(tags.discsTotal) || tags.discsTotal <= 0)) {\n        throw new TypeError('tags.discsTotal, when provided, must be a positive integer.');\n    }\n    if (tags.genre !== undefined && typeof tags.genre !== 'string') {\n        throw new TypeError('tags.genre, when provided, must be a string.');\n    }\n    if (tags.date !== undefined && (!(tags.date instanceof Date) || Number.isNaN(tags.date.getTime()))) {\n        throw new TypeError('tags.date, when provided, must be a valid Date.');\n    }\n    if (tags.beatsPerMinute !== undefined\n        && (!Number.isInteger(tags.beatsPerMinute) || tags.beatsPerMinute <= 0)) {\n        throw new TypeError('tags.beatsPerMinute, when provided, must be a positive integer.');\n    }\n    if (tags.lyrics !== undefined && typeof tags.lyrics !== 'string') {\n        throw new TypeError('tags.lyrics, when provided, must be a string.');\n    }\n    if (tags.images !== undefined) {\n        if (!Array.isArray(tags.images)) {\n            throw new TypeError('tags.images, when provided, must be an array.');\n        }\n        for (const image of tags.images) {\n            if (!image || typeof image !== 'object') {\n                throw new TypeError('Each image in tags.images must be an object.');\n            }\n            if (!(image.data instanceof Uint8Array)) {\n                throw new TypeError('Each image.data must be a Uint8Array.');\n            }\n            if (typeof image.mimeType !== 'string') {\n                throw new TypeError('Each image.mimeType must be a string.');\n            }\n            if (!['coverFront', 'coverBack', 'unknown'].includes(image.kind)) {\n                throw new TypeError('Each image.kind must be \\'coverFront\\', \\'coverBack\\', or \\'unknown\\'.');\n            }\n        }\n    }\n    if (tags.comment !== undefined && typeof tags.comment !== 'string') {\n        throw new TypeError('tags.comment, when provided, must be a string.');\n    }\n    if (tags.raw !== undefined) {\n        if (!tags.raw || typeof tags.raw !== 'object') {\n            throw new TypeError('tags.raw, when provided, must be an object.');\n        }\n        for (const value of Object.values(tags.raw)) {\n            if (value !== null\n                && typeof value !== 'string'\n                && !(Array.isArray(value) && value.every(x => typeof x === 'string'))\n                && !(value instanceof Uint8Array)\n                && !(value instanceof RichImageData)\n                && !(value instanceof AttachedFile)\n                && !isRecordStringString(value)) {\n                throw new TypeError('Each value in tags.raw must be a string, string array, Uint8Array, RichImageData, AttachedFile, '\n                    + 'Record<string, string>, or null.');\n            }\n        }\n    }\n};\nexport const metadataTagsAreEmpty = (tags) => {\n    return tags.title === undefined\n        && tags.description === undefined\n        && tags.artist === undefined\n        && tags.album === undefined\n        && tags.albumArtist === undefined\n        && tags.trackNumber === undefined\n        && tags.tracksTotal === undefined\n        && tags.discNumber === undefined\n        && tags.discsTotal === undefined\n        && tags.genre === undefined\n        && tags.beatsPerMinute === undefined\n        && tags.date === undefined\n        && tags.lyrics === undefined\n        && (!tags.images || tags.images.length === 0)\n        && tags.comment === undefined\n        && (tags.raw === undefined || Object.keys(tags.raw).length === 0);\n};\nexport const DEFAULT_TRACK_DISPOSITION = {\n    default: true,\n    primary: true,\n    forced: false,\n    original: false,\n    commentary: false,\n    hearingImpaired: false,\n    visuallyImpaired: false,\n};\nexport const validateTrackDisposition = (disposition) => {\n    if (!disposition || typeof disposition !== 'object') {\n        throw new TypeError('disposition must be an object.');\n    }\n    if (disposition.default !== undefined && typeof disposition.default !== 'boolean') {\n        throw new TypeError('disposition.default must be a boolean.');\n    }\n    if (disposition.primary !== undefined && typeof disposition.primary !== 'boolean') {\n        throw new TypeError('disposition.primary must be a boolean.');\n    }\n    if (disposition.forced !== undefined && typeof disposition.forced !== 'boolean') {\n        throw new TypeError('disposition.forced must be a boolean.');\n    }\n    if (disposition.original !== undefined && typeof disposition.original !== 'boolean') {\n        throw new TypeError('disposition.original must be a boolean.');\n    }\n    if (disposition.commentary !== undefined && typeof disposition.commentary !== 'boolean') {\n        throw new TypeError('disposition.commentary must be a boolean.');\n    }\n    if (disposition.hearingImpaired !== undefined && typeof disposition.hearingImpaired !== 'boolean') {\n        throw new TypeError('disposition.hearingImpaired must be a boolean.');\n    }\n    if (disposition.visuallyImpaired !== undefined && typeof disposition.visuallyImpaired !== 'boolean') {\n        throw new TypeError('disposition.visuallyImpaired must be a boolean.');\n    }\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nexport class Bitstream {\n    constructor(bytes) {\n        this.bytes = bytes;\n        /** Current offset in bits. */\n        this.pos = 0;\n    }\n    seekToByte(byteOffset) {\n        this.pos = 8 * byteOffset;\n    }\n    readBit() {\n        const byteIndex = Math.floor(this.pos / 8);\n        const byte = this.bytes[byteIndex] ?? 0;\n        const bitIndex = 0b111 - (this.pos & 0b111);\n        const bit = (byte & (1 << bitIndex)) >> bitIndex;\n        this.pos++;\n        return bit;\n    }\n    readBits(n) {\n        if (n === 1) {\n            return this.readBit();\n        }\n        let result = 0;\n        for (let i = 0; i < n; i++) {\n            result <<= 1;\n            result |= this.readBit();\n        }\n        return result;\n    }\n    writeBits(n, value) {\n        const end = this.pos + n;\n        for (let i = this.pos; i < end; i++) {\n            const byteIndex = Math.floor(i / 8);\n            let byte = this.bytes[byteIndex];\n            const bitIndex = 0b111 - (i & 0b111);\n            byte &= ~(1 << bitIndex);\n            byte |= ((value & (1 << (end - i - 1))) >> (end - i - 1)) << bitIndex;\n            this.bytes[byteIndex] = byte;\n        }\n        this.pos = end;\n    }\n    copyBits(n, other) {\n        let i = 0;\n        for (i; i < n - 7; i += 8) {\n            this.writeBits(8, other.readBits(8));\n        }\n        const leftover = n - i;\n        if (leftover > 0) {\n            this.writeBits(leftover, other.readBits(leftover));\n        }\n    }\n    readAlignedByte() {\n        if (this.pos % 8 !== 0) {\n            throw new Error('Bitstream is not byte-aligned.');\n        }\n        const byteIndex = this.pos / 8;\n        const byte = this.bytes[byteIndex] ?? 0;\n        this.pos += 8;\n        return byte;\n    }\n    skipBits(n) {\n        this.pos += n;\n    }\n    getBitsLeft() {\n        return this.bytes.length * 8 - this.pos;\n    }\n    clone() {\n        const clone = new Bitstream(this.bytes);\n        clone.pos = this.pos;\n        return clone;\n    }\n}\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { Bitstream } from './bitstream.js';\nexport const aacFrequencyTable = [\n    96000, 88200, 64000, 48000, 44100, 32000,\n    24000, 22050, 16000, 12000, 11025, 8000, 7350,\n];\nexport const aacChannelMap = [-1, 1, 2, 3, 4, 5, 6, 8];\nexport const parseAacAudioSpecificConfig = (bytes) => {\n    if (!bytes || bytes.byteLength < 2) {\n        throw new TypeError('AAC description must be at least 2 bytes long.');\n    }\n    const bitstream = new Bitstream(bytes);\n    const objectType = readAacObjectType(bitstream);\n    const { frequencyIndex, sampleRate } = readAacSamplingFrequency(bitstream);\n    const channelConfiguration = bitstream.readBits(4);\n    let numberOfChannels = null;\n    if (channelConfiguration >= 1 && channelConfiguration <= 7) {\n        numberOfChannels = aacChannelMap[channelConfiguration];\n    }\n    let coreObjectType = objectType;\n    let psPresent = false;\n    let outputSampleRate = sampleRate;\n    if (objectType === 5 || objectType === 29) {\n        // Explicit hierarchical signaling: everything read so far describes the core coder, and the rate the\n        // decoder actually outputs follows right here\n        psPresent = objectType === 29;\n        outputSampleRate = readAacSamplingFrequency(bitstream).sampleRate;\n        coreObjectType = readAacObjectType(bitstream);\n        if (coreObjectType === 22) {\n            bitstream.skipBits(4); // extensionChannelConfiguration\n        }\n    }\n    else {\n        // There may be SBR/PS flags sitting behind a sync word after the config of the core coder. We find them by\n        // scanning for the sync word, just like FFmpeg does.\n        while (bitstream.getBitsLeft() > 15) {\n            const searchStart = bitstream.pos;\n            if (bitstream.readBits(11) !== 0x2b7) {\n                bitstream.pos = searchStart + 1;\n                continue;\n            }\n            if (readAacObjectType(bitstream) === 5 && bitstream.readBits(1)) {\n                outputSampleRate = readAacSamplingFrequency(bitstream).sampleRate;\n                if (bitstream.getBitsLeft() > 11 && bitstream.readBits(11) === 0x548) {\n                    psPresent = !!bitstream.readBits(1);\n                }\n            }\n            break;\n        }\n    }\n    if (numberOfChannels !== null && numberOfChannels > 1) {\n        // PS only ever upmixes a mono core. A stereo signal means whatever we read was bogus\n        psPresent = false;\n    }\n    return {\n        objectType,\n        coreObjectType,\n        frequencyIndex,\n        channelConfiguration,\n        outputSampleRate,\n        outputNumberOfChannels: psPresent && numberOfChannels === 1\n            ? 2\n            : numberOfChannels,\n    };\n};\nconst readAacObjectType = (bitstream) => {\n    const objectType = bitstream.readBits(5);\n    return objectType === 31 ? 32 + bitstream.readBits(6) : objectType;\n};\nconst readAacSamplingFrequency = (bitstream) => {\n    const frequencyIndex = bitstream.readBits(4);\n    if (frequencyIndex === 15) {\n        return {\n            frequencyIndex,\n            sampleRate: bitstream.readBits(24),\n        };\n    }\n    return {\n        frequencyIndex,\n        sampleRate: frequencyIndex < aacFrequencyTable.length\n            ? aacFrequencyTable[frequencyIndex]\n            : null,\n    };\n};\nexport const buildAacAudioSpecificConfig = (config) => {\n    const usesSbr = config.objectType === 5 || config.objectType === 29;\n    const usesPs = config.objectType === 29;\n    // SBR runs the core coder at half the output rate, and PS upmixes a mono core to stereo\n    const coreSampleRate = usesSbr ? config.outputSampleRate / 2 : config.outputSampleRate;\n    const coreNumberOfChannels = usesPs ? 1 : config.outputNumberOfChannels;\n    const channelConfiguration = aacChannelMap.indexOf(coreNumberOfChannels);\n    if (channelConfiguration === -1) {\n        throw new TypeError(`Unsupported number of channels: ${config.outputNumberOfChannels}`);\n    }\n    // Object type, sampling frequency, channel configuration, then a bare GASpecificConfig\n    let bitCount = 5 + 4 + 4 + 3;\n    if (config.objectType >= 32) {\n        bitCount += 6;\n    }\n    if (findAacFrequencyIndex(coreSampleRate) === 15) {\n        bitCount += 24;\n    }\n    if (usesSbr) {\n        bitCount += 4 + 5; // Extension sampling frequency and the object type of the core coder\n        if (findAacFrequencyIndex(config.outputSampleRate) === 15) {\n            bitCount += 24;\n        }\n    }\n    const byteCount = Math.ceil(bitCount / 8);\n    const bytes = new Uint8Array(byteCount);\n    const bitstream = new Bitstream(bytes);\n    writeAacObjectType(bitstream, config.objectType);\n    writeAacSamplingFrequency(bitstream, coreSampleRate);\n    bitstream.writeBits(4, channelConfiguration);\n    if (usesSbr) {\n        writeAacSamplingFrequency(bitstream, config.outputSampleRate);\n        writeAacObjectType(bitstream, 2); // AAC-LC underneath\n    }\n    bitstream.writeBits(3, 0); // frameLengthFlag, dependsOnCoreCoder, extensionFlag\n    return bytes;\n};\nconst writeAacObjectType = (bitstream, objectType) => {\n    if (objectType < 32) {\n        bitstream.writeBits(5, objectType);\n    }\n    else {\n        bitstream.writeBits(5, 31);\n        bitstream.writeBits(6, objectType - 32);\n    }\n};\nconst writeAacSamplingFrequency = (bitstream, sampleRate) => {\n    const frequencyIndex = findAacFrequencyIndex(sampleRate);\n    bitstream.writeBits(4, frequencyIndex);\n    if (frequencyIndex === 15) {\n        bitstream.writeBits(24, sampleRate);\n    }\n};\nconst findAacFrequencyIndex = (sampleRate) => {\n    const index = aacFrequencyTable.indexOf(sampleRate);\n    return index === -1 ? 15 : index;\n};\nexport const buildAdtsHeaderTemplate = (config) => {\n    const header = new Uint8Array(7);\n    const bitstream = new Bitstream(header);\n    const { coreObjectType, frequencyIndex, channelConfiguration } = config;\n    const profile = coreObjectType - 1;\n    bitstream.writeBits(12, 0b1111_11111111); // Syncword\n    bitstream.writeBits(1, 0); // MPEG Version\n    bitstream.writeBits(2, 0); // Layer\n    bitstream.writeBits(1, 1); // Protection absence\n    bitstream.writeBits(2, profile); // Profile\n    bitstream.writeBits(4, frequencyIndex); // MPEG-4 Sampling Frequency Index\n    bitstream.writeBits(1, 0); // Private bit\n    bitstream.writeBits(3, channelConfiguration); // MPEG-4 Channel Configuration\n    bitstream.writeBits(1, 0); // Originality\n    bitstream.writeBits(1, 0); // Home\n    bitstream.writeBits(1, 0); // Copyright ID bit\n    bitstream.writeBits(1, 0); // Copyright ID start\n    bitstream.skipBits(13); // Frame length (to be filled per packet)\n    bitstream.writeBits(11, 0x7ff); // Buffer fullness\n    bitstream.writeBits(2, 0); // Number of AAC frames minus 1\n    // Omit CRC check\n    return { header, bitstream };\n};\nexport const writeAdtsFrameLength = (bitstream, frameLength) => {\n    bitstream.pos = 30;\n    bitstream.writeBits(13, frameLength);\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\n/** Sample rates indexed by fscod (Table 4.1) */\nexport const AC3_SAMPLE_RATES = [48000, 44100, 32000];\n/** E-AC-3 reduced sample rates for fscod2 per ATSC A/52:2018 */\nexport const EAC3_REDUCED_SAMPLE_RATES = [24000, 22050, 16000];\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\n// This file is generated by scripts/write-version.ts. Do not edit manually.\nexport const VERSION = '1.62.1';\nexport const VERSIONED_NAME = `Mediabunny v${VERSION}`;\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { AVC_LEVEL_TABLE, VP9_LEVEL_TABLE } from './codec.js';\nimport { assert, assertNever, base64ToBytes, bytesToBase64, keyValueIterator, getUint24, last, readExpGolomb, readSignedExpGolomb, textDecoder, textEncoder, toDataView, toUint8Array, isChromium, popcount, setUint24, writeExpGolomb, } from './misc.js';\nimport { Logging } from './logging.js';\nimport { AC3_SAMPLE_RATES, EAC3_REDUCED_SAMPLE_RATES } from '../shared/ac3-misc.js';\nimport { Bitstream } from '../shared/bitstream.js';\nimport { VERSIONED_NAME } from './version.js';\n// References for AVC/HEVC code:\n// ISO 14496-15\n// Rec. ITU-T H.264\n// Rec. ITU-T H.265\n// https://stackoverflow.com/questions/24884827\nexport var AvcNalUnitType;\n(function (AvcNalUnitType) {\n    AvcNalUnitType[AvcNalUnitType[\"NON_IDR_SLICE\"] = 1] = \"NON_IDR_SLICE\";\n    AvcNalUnitType[AvcNalUnitType[\"SLICE_DPA\"] = 2] = \"SLICE_DPA\";\n    AvcNalUnitType[AvcNalUnitType[\"SLICE_DPB\"] = 3] = \"SLICE_DPB\";\n    AvcNalUnitType[AvcNalUnitType[\"SLICE_DPC\"] = 4] = \"SLICE_DPC\";\n    AvcNalUnitType[AvcNalUnitType[\"IDR\"] = 5] = \"IDR\";\n    AvcNalUnitType[AvcNalUnitType[\"SEI\"] = 6] = \"SEI\";\n    AvcNalUnitType[AvcNalUnitType[\"SPS\"] = 7] = \"SPS\";\n    AvcNalUnitType[AvcNalUnitType[\"PPS\"] = 8] = \"PPS\";\n    AvcNalUnitType[AvcNalUnitType[\"AUD\"] = 9] = \"AUD\";\n    AvcNalUnitType[AvcNalUnitType[\"SPS_EXT\"] = 13] = \"SPS_EXT\";\n})(AvcNalUnitType || (AvcNalUnitType = {}));\nexport var HevcNalUnitType;\n(function (HevcNalUnitType) {\n    HevcNalUnitType[HevcNalUnitType[\"RASL_N\"] = 8] = \"RASL_N\";\n    HevcNalUnitType[HevcNalUnitType[\"RASL_R\"] = 9] = \"RASL_R\";\n    HevcNalUnitType[HevcNalUnitType[\"BLA_W_LP\"] = 16] = \"BLA_W_LP\";\n    HevcNalUnitType[HevcNalUnitType[\"RSV_IRAP_VCL23\"] = 23] = \"RSV_IRAP_VCL23\";\n    HevcNalUnitType[HevcNalUnitType[\"VPS_NUT\"] = 32] = \"VPS_NUT\";\n    HevcNalUnitType[HevcNalUnitType[\"SPS_NUT\"] = 33] = \"SPS_NUT\";\n    HevcNalUnitType[HevcNalUnitType[\"PPS_NUT\"] = 34] = \"PPS_NUT\";\n    HevcNalUnitType[HevcNalUnitType[\"AUD_NUT\"] = 35] = \"AUD_NUT\";\n    HevcNalUnitType[HevcNalUnitType[\"PREFIX_SEI_NUT\"] = 39] = \"PREFIX_SEI_NUT\";\n    HevcNalUnitType[HevcNalUnitType[\"SUFFIX_SEI_NUT\"] = 40] = \"SUFFIX_SEI_NUT\";\n})(HevcNalUnitType || (HevcNalUnitType = {}));\nexport const iterateNalUnitsInAnnexB = function* (packetData) {\n    let i = 0;\n    let nalStart = -1;\n    while (i < packetData.length - 2) {\n        const zeroIndex = packetData.indexOf(0, i);\n        if (zeroIndex === -1 || zeroIndex >= packetData.length - 2) {\n            break;\n        }\n        i = zeroIndex;\n        let startCodeLength = 0;\n        // Check for 4-byte start code (0x00000001)\n        if (i + 3 < packetData.length\n            && packetData[i + 1] === 0\n            && packetData[i + 2] === 0\n            && packetData[i + 3] === 1) {\n            startCodeLength = 4;\n        }\n        else if (packetData[i + 1] === 0 && packetData[i + 2] === 1) {\n            // Check for 3-byte start code (0x000001)\n            startCodeLength = 3;\n        }\n        if (startCodeLength === 0) {\n            i++;\n            continue;\n        }\n        // If we had a previous NAL unit, yield it\n        if (nalStart !== -1 && i > nalStart) {\n            yield {\n                offset: nalStart,\n                length: i - nalStart,\n            };\n        }\n        nalStart = i + startCodeLength;\n        i = nalStart;\n    }\n    // Yield the last NAL unit if there is one\n    if (nalStart !== -1 && nalStart < packetData.length) {\n        yield {\n            offset: nalStart,\n            length: packetData.length - nalStart,\n        };\n    }\n};\nexport const iterateNalUnitsInLengthPrefixed = function* (packetData, lengthSize) {\n    let offset = 0;\n    const dataView = new DataView(packetData.buffer, packetData.byteOffset, packetData.byteLength);\n    while (offset + lengthSize <= packetData.length) {\n        let nalUnitLength;\n        if (lengthSize === 1) {\n            nalUnitLength = dataView.getUint8(offset);\n        }\n        else if (lengthSize === 2) {\n            nalUnitLength = dataView.getUint16(offset, false);\n        }\n        else if (lengthSize === 3) {\n            nalUnitLength = getUint24(dataView, offset, false);\n        }\n        else {\n            assert(lengthSize === 4);\n            nalUnitLength = dataView.getUint32(offset, false);\n        }\n        offset += lengthSize;\n        yield {\n            offset,\n            length: nalUnitLength,\n        };\n        offset += nalUnitLength;\n    }\n};\nexport const iterateAvcNalUnits = (packetData, decoderConfig) => {\n    if (decoderConfig.description) {\n        const bytes = toUint8Array(decoderConfig.description);\n        const lengthSizeMinusOne = bytes[4] & 0b11;\n        const lengthSize = (lengthSizeMinusOne + 1);\n        return iterateNalUnitsInLengthPrefixed(packetData, lengthSize);\n    }\n    else {\n        return iterateNalUnitsInAnnexB(packetData);\n    }\n};\nexport const extractNalUnitTypeForAvc = (byte) => {\n    return byte & 0x1F;\n};\nconst removeEmulationPreventionBytes = (data) => {\n    const result = new Uint8Array(data.length); // The result can only be shorter\n    const len = data.length;\n    let resultLength = 0;\n    for (let i = 0; i < len; i++) {\n        // Look for the 0x000003 pattern\n        if (i + 2 < len && data[i] === 0x00 && data[i + 1] === 0x00 && data[i + 2] === 0x03) {\n            // Push the first two bytes\n            result[resultLength++] = 0x00;\n            result[resultLength++] = 0x00;\n            i += 2; // Skip the 0x03 byte\n        }\n        else {\n            result[resultLength++] = data[i];\n        }\n    }\n    return result.subarray(0, resultLength);\n};\nexport const addEmulationPreventionBytes = (data) => {\n    const result = [];\n    let zeroCount = 0;\n    for (const byte of data) {\n        if (zeroCount === 2 && byte <= 0x03) {\n            result.push(0x03);\n            zeroCount = 0;\n        }\n        result.push(byte);\n        zeroCount = byte === 0 ? zeroCount + 1 : 0;\n    }\n    return new Uint8Array(result);\n};\nconst ANNEX_B_START_CODE = new Uint8Array([0, 0, 0, 1]);\nexport const concatNalUnitsInAnnexB = (nalUnits) => {\n    const totalLength = nalUnits.reduce((a, b) => a + ANNEX_B_START_CODE.byteLength + b.byteLength, 0);\n    const result = new Uint8Array(totalLength);\n    let offset = 0;\n    for (const nalUnit of nalUnits) {\n        result.set(ANNEX_B_START_CODE, offset);\n        offset += ANNEX_B_START_CODE.byteLength;\n        result.set(nalUnit, offset);\n        offset += nalUnit.byteLength;\n    }\n    return result;\n};\nexport const concatNalUnitsInLengthPrefixed = (nalUnits, lengthSize) => {\n    const totalLength = nalUnits.reduce((a, b) => a + lengthSize + b.byteLength, 0);\n    const result = new Uint8Array(totalLength);\n    let offset = 0;\n    for (const nalUnit of nalUnits) {\n        const dataView = new DataView(result.buffer, result.byteOffset, result.byteLength);\n        switch (lengthSize) {\n            case 1:\n                dataView.setUint8(offset, nalUnit.byteLength);\n                break;\n            case 2:\n                dataView.setUint16(offset, nalUnit.byteLength, false);\n                break;\n            case 3:\n                setUint24(dataView, offset, nalUnit.byteLength, false);\n                break;\n            case 4:\n                dataView.setUint32(offset, nalUnit.byteLength, false);\n                break;\n        }\n        offset += lengthSize;\n        result.set(nalUnit, offset);\n        offset += nalUnit.byteLength;\n    }\n    return result;\n};\nexport const concatAvcNalUnits = (nalUnits, decoderConfig) => {\n    if (decoderConfig.description) {\n        // Stream is length-prefixed. Let's extract the size of the length prefix from the decoder config\n        const bytes = toUint8Array(decoderConfig.description);\n        const lengthSizeMinusOne = bytes[4] & 0b11;\n        const lengthSize = (lengthSizeMinusOne + 1);\n        return concatNalUnitsInLengthPrefixed(nalUnits, lengthSize);\n    }\n    else {\n        // Stream is in Annex B format\n        return concatNalUnitsInAnnexB(nalUnits);\n    }\n};\n/** Builds an AvcDecoderConfigurationRecord from an AVC packet in Annex B format. */\nexport const extractAvcDecoderConfigurationRecord = (packetData) => {\n    try {\n        const spsUnits = [];\n        const ppsUnits = [];\n        const spsExtUnits = [];\n        for (const loc of iterateNalUnitsInAnnexB(packetData)) {\n            const nalUnit = packetData.subarray(loc.offset, loc.offset + loc.length);\n            const type = extractNalUnitTypeForAvc(nalUnit[0]);\n            // The counts are capped at what the record can hold\n            if (type === AvcNalUnitType.SPS && spsUnits.length < 31) {\n                spsUnits.push(nalUnit);\n            }\n            else if (type === AvcNalUnitType.PPS && ppsUnits.length < 255) {\n                ppsUnits.push(nalUnit);\n            }\n            else if (type === AvcNalUnitType.SPS_EXT && spsExtUnits.length < 255) {\n                spsExtUnits.push(nalUnit);\n            }\n        }\n        if (spsUnits.length === 0) {\n            return null;\n        }\n        if (ppsUnits.length === 0) {\n            return null;\n        }\n        // Let's get the first SPS for profile and level information\n        const spsData = spsUnits[0];\n        const spsInfo = parseAvcSps(spsData);\n        if (!spsInfo) {\n            return null;\n        }\n        const hasExtendedData = spsInfo.profileIdc === 100\n            || spsInfo.profileIdc === 110\n            || spsInfo.profileIdc === 122\n            || spsInfo.profileIdc === 144;\n        return {\n            configurationVersion: 1,\n            avcProfileIndication: spsInfo.profileIdc,\n            profileCompatibility: spsInfo.constraintFlags,\n            avcLevelIndication: spsInfo.levelIdc,\n            lengthSizeMinusOne: 3, // Typically 4 bytes for length field\n            sequenceParameterSets: spsUnits,\n            pictureParameterSets: ppsUnits,\n            chromaFormat: hasExtendedData ? spsInfo.chromaFormatIdc : null,\n            bitDepthLumaMinus8: hasExtendedData ? spsInfo.bitDepthLumaMinus8 : null,\n            bitDepthChromaMinus8: hasExtendedData ? spsInfo.bitDepthChromaMinus8 : null,\n            sequenceParameterSetExt: hasExtendedData ? spsExtUnits : null,\n        };\n    }\n    catch (error) {\n        Logging._error('Error building AVC Decoder Configuration Record:', error);\n        return null;\n    }\n};\n/** Serializes an AvcDecoderConfigurationRecord into the format specified in Section 5.3.3.1 of ISO 14496-15. */\nexport const serializeAvcDecoderConfigurationRecord = (record) => {\n    const bytes = [];\n    // Write header\n    bytes.push(record.configurationVersion);\n    bytes.push(record.avcProfileIndication);\n    bytes.push(record.profileCompatibility);\n    bytes.push(record.avcLevelIndication);\n    bytes.push(0xFC | (record.lengthSizeMinusOne & 0x03)); // Reserved bits (6) + lengthSizeMinusOne (2)\n    // Reserved bits (3) + numOfSequenceParameterSets (5)\n    bytes.push(0xE0 | (record.sequenceParameterSets.length & 0x1F));\n    // Write SPS\n    for (const sps of record.sequenceParameterSets) {\n        const length = sps.byteLength;\n        bytes.push(length >> 8); // High byte\n        bytes.push(length & 0xFF); // Low byte\n        for (let i = 0; i < length; i++) {\n            bytes.push(sps[i]);\n        }\n    }\n    bytes.push(record.pictureParameterSets.length);\n    // Write PPS\n    for (const pps of record.pictureParameterSets) {\n        const length = pps.byteLength;\n        bytes.push(length >> 8); // High byte\n        bytes.push(length & 0xFF); // Low byte\n        for (let i = 0; i < length; i++) {\n            bytes.push(pps[i]);\n        }\n    }\n    if ((record.avcProfileIndication === 100\n        || record.avcProfileIndication === 110\n        || record.avcProfileIndication === 122\n        || record.avcProfileIndication === 144)\n        && record.chromaFormat !== null // Can happen if the data was too short\n    ) {\n        assert(record.bitDepthLumaMinus8 !== null);\n        assert(record.bitDepthChromaMinus8 !== null);\n        assert(record.sequenceParameterSetExt !== null);\n        bytes.push(0xFC | (record.chromaFormat & 0x03)); // Reserved bits + chroma_format\n        bytes.push(0xF8 | (record.bitDepthLumaMinus8 & 0x07)); // Reserved bits + bit_depth_luma_minus8\n        bytes.push(0xF8 | (record.bitDepthChromaMinus8 & 0x07)); // Reserved bits + bit_depth_chroma_minus8\n        bytes.push(record.sequenceParameterSetExt.length);\n        // Write SPS Ext\n        for (const spsExt of record.sequenceParameterSetExt) {\n            const length = spsExt.byteLength;\n            bytes.push(length >> 8); // High byte\n            bytes.push(length & 0xFF); // Low byte\n            for (let i = 0; i < length; i++) {\n                bytes.push(spsExt[i]);\n            }\n        }\n    }\n    return new Uint8Array(bytes);\n};\n/** Deserializes an AvcDecoderConfigurationRecord from the format specified in Section 5.3.3.1 of ISO 14496-15. */\nexport const deserializeAvcDecoderConfigurationRecord = (data) => {\n    try {\n        const view = toDataView(data);\n        let offset = 0;\n        // Read header\n        const configurationVersion = view.getUint8(offset++);\n        const avcProfileIndication = view.getUint8(offset++);\n        const profileCompatibility = view.getUint8(offset++);\n        const avcLevelIndication = view.getUint8(offset++);\n        const lengthSizeMinusOne = view.getUint8(offset++) & 0x03;\n        const numOfSequenceParameterSets = view.getUint8(offset++) & 0x1F;\n        // Read SPS\n        const sequenceParameterSets = [];\n        for (let i = 0; i < numOfSequenceParameterSets; i++) {\n            const length = view.getUint16(offset, false);\n            offset += 2;\n            sequenceParameterSets.push(data.subarray(offset, offset + length));\n            offset += length;\n        }\n        const numOfPictureParameterSets = view.getUint8(offset++);\n        // Read PPS\n        const pictureParameterSets = [];\n        for (let i = 0; i < numOfPictureParameterSets; i++) {\n            const length = view.getUint16(offset, false);\n            offset += 2;\n            pictureParameterSets.push(data.subarray(offset, offset + length));\n            offset += length;\n        }\n        const record = {\n            configurationVersion,\n            avcProfileIndication,\n            profileCompatibility,\n            avcLevelIndication,\n            lengthSizeMinusOne,\n            sequenceParameterSets,\n            pictureParameterSets,\n            chromaFormat: null,\n            bitDepthLumaMinus8: null,\n            bitDepthChromaMinus8: null,\n            sequenceParameterSetExt: null,\n        };\n        // Check if there are extended profile fields\n        if ((avcProfileIndication === 100\n            || avcProfileIndication === 110\n            || avcProfileIndication === 122\n            || avcProfileIndication === 144)\n            && offset + 4 <= data.length) {\n            const chromaFormat = view.getUint8(offset++) & 0x03;\n            const bitDepthLumaMinus8 = view.getUint8(offset++) & 0x07;\n            const bitDepthChromaMinus8 = view.getUint8(offset++) & 0x07;\n            const numOfSequenceParameterSetExt = view.getUint8(offset++);\n            record.chromaFormat = chromaFormat;\n            record.bitDepthLumaMinus8 = bitDepthLumaMinus8;\n            record.bitDepthChromaMinus8 = bitDepthChromaMinus8;\n            // Read SPS Ext\n            const sequenceParameterSetExt = [];\n            for (let i = 0; i < numOfSequenceParameterSetExt; i++) {\n                const length = view.getUint16(offset, false);\n                offset += 2;\n                sequenceParameterSetExt.push(data.subarray(offset, offset + length));\n                offset += length;\n            }\n            record.sequenceParameterSetExt = sequenceParameterSetExt;\n        }\n        return record;\n    }\n    catch (error) {\n        Logging._error('Error deserializing AVC Decoder Configuration Record:', error);\n        return null;\n    }\n};\nconst AVC_HEVC_ASPECT_RATIO_IDC_TABLE = {\n    1: { num: 1, den: 1 },\n    2: { num: 12, den: 11 },\n    3: { num: 10, den: 11 },\n    4: { num: 16, den: 11 },\n    5: { num: 40, den: 33 },\n    6: { num: 24, den: 11 },\n    7: { num: 20, den: 11 },\n    8: { num: 32, den: 11 },\n    9: { num: 80, den: 33 },\n    10: { num: 18, den: 11 },\n    11: { num: 15, den: 11 },\n    12: { num: 64, den: 33 },\n    13: { num: 160, den: 99 },\n    14: { num: 4, den: 3 },\n    15: { num: 3, den: 2 },\n    16: { num: 2, den: 1 },\n};\n/** Parses an AVC SPS (Sequence Parameter Set) to extract basic information. */\nexport const parseAvcSps = (sps) => {\n    try {\n        const emulationUnpreventedBytes = removeEmulationPreventionBytes(sps);\n        const bitstream = new Bitstream(emulationUnpreventedBytes);\n        bitstream.skipBits(1); // forbidden_zero_bit\n        bitstream.skipBits(2); // nal_ref_idc\n        const nalUnitType = bitstream.readBits(5);\n        if (nalUnitType !== 7) { // SPS NAL unit type is 7\n            return null;\n        }\n        const profileIdc = bitstream.readAlignedByte();\n        const constraintFlags = bitstream.readAlignedByte();\n        const levelIdc = bitstream.readAlignedByte();\n        readExpGolomb(bitstream); // seq_parameter_set_id\n        // \"When chroma_format_idc is not present, it shall be inferred to be equal to 1 (4:2:0 chroma format).\"\n        let chromaFormatIdc = 1;\n        // \"When bit_depth_luma_minus8 is not present, it shall be inferred to be equal to 0.\"\"\n        let bitDepthLumaMinus8 = 0;\n        // \"When bit_depth_chroma_minus8 is not present, it shall be inferred to be equal to 0.\"\n        let bitDepthChromaMinus8 = 0;\n        // \"When separate_colour_plane_flag is not present, it shall be inferred to be equal to 0.\"\n        let separateColourPlaneFlag = 0;\n        // Handle high profile chroma_format_idc\n        if (profileIdc === 100\n            || profileIdc === 110\n            || profileIdc === 122\n            || profileIdc === 244\n            || profileIdc === 44\n            || profileIdc === 83\n            || profileIdc === 86\n            || profileIdc === 118\n            || profileIdc === 128) {\n            chromaFormatIdc = readExpGolomb(bitstream);\n            if (chromaFormatIdc === 3) {\n                separateColourPlaneFlag = bitstream.readBits(1);\n            }\n            bitDepthLumaMinus8 = readExpGolomb(bitstream);\n            bitDepthChromaMinus8 = readExpGolomb(bitstream);\n            bitstream.skipBits(1); // qpprime_y_zero_transform_bypass_flag\n            const seqScalingMatrixPresentFlag = bitstream.readBits(1);\n            if (seqScalingMatrixPresentFlag) {\n                for (let i = 0; i < (chromaFormatIdc !== 3 ? 8 : 12); i++) {\n                    const seqScalingListPresentFlag = bitstream.readBits(1);\n                    if (seqScalingListPresentFlag) {\n                        const sizeOfScalingList = i < 6 ? 16 : 64;\n                        let lastScale = 8;\n                        let nextScale = 8;\n                        for (let j = 0; j < sizeOfScalingList; j++) {\n                            if (nextScale !== 0) {\n                                const deltaScale = readSignedExpGolomb(bitstream);\n                                nextScale = (lastScale + deltaScale + 256) % 256;\n                            }\n                            lastScale = nextScale === 0 ? lastScale : nextScale;\n                        }\n                    }\n                }\n            }\n        }\n        readExpGolomb(bitstream); // log2_max_frame_num_minus4\n        const picOrderCntType = readExpGolomb(bitstream);\n        if (picOrderCntType === 0) {\n            readExpGolomb(bitstream); // log2_max_pic_order_cnt_lsb_minus4\n        }\n        else if (picOrderCntType === 1) {\n            bitstream.skipBits(1); // delta_pic_order_always_zero_flag\n            readSignedExpGolomb(bitstream); // offset_for_non_ref_pic\n            readSignedExpGolomb(bitstream); // offset_for_top_to_bottom_field\n            const numRefFramesInPicOrderCntCycle = readExpGolomb(bitstream);\n            for (let i = 0; i < numRefFramesInPicOrderCntCycle; i++) {\n                readSignedExpGolomb(bitstream); // offset_for_ref_frame[i]\n            }\n        }\n        readExpGolomb(bitstream); // max_num_ref_frames\n        bitstream.skipBits(1); // gaps_in_frame_num_value_allowed_flag\n        const picWidthInMbsMinus1 = readExpGolomb(bitstream);\n        const picHeightInMapUnitsMinus1 = readExpGolomb(bitstream);\n        const codedWidth = 16 * (picWidthInMbsMinus1 + 1);\n        const codedHeight = 16 * (picHeightInMapUnitsMinus1 + 1);\n        let displayWidth = codedWidth;\n        let displayHeight = codedHeight;\n        const frameMbsOnlyFlag = bitstream.readBits(1);\n        if (!frameMbsOnlyFlag) {\n            bitstream.skipBits(1); // mb_adaptive_frame_field_flag\n        }\n        bitstream.skipBits(1); // direct_8x8_inference_flag\n        const frameCroppingFlag = bitstream.readBits(1);\n        if (frameCroppingFlag) {\n            const frameCropLeftOffset = readExpGolomb(bitstream);\n            const frameCropRightOffset = readExpGolomb(bitstream);\n            const frameCropTopOffset = readExpGolomb(bitstream);\n            const frameCropBottomOffset = readExpGolomb(bitstream);\n            let cropUnitX;\n            let cropUnitY;\n            const chromaArrayType = separateColourPlaneFlag === 0 ? chromaFormatIdc : 0;\n            if (chromaArrayType === 0) {\n                // \"If ChromaArrayType is equal to 0, CropUnitX and CropUnitY are derived as:\"\n                cropUnitX = 1;\n                cropUnitY = 2 - frameMbsOnlyFlag;\n            }\n            else {\n                // \"Otherwise (ChromaArrayType is equal to 1, 2, or 3), CropUnitX and CropUnitY are derived as:\"\n                const subWidthC = chromaFormatIdc === 3 ? 1 : 2;\n                const subHeightC = chromaFormatIdc === 1 ? 2 : 1;\n                cropUnitX = subWidthC;\n                cropUnitY = subHeightC * (2 - frameMbsOnlyFlag);\n            }\n            displayWidth -= (cropUnitX * (frameCropLeftOffset + frameCropRightOffset));\n            displayHeight -= (cropUnitY * (frameCropTopOffset + frameCropBottomOffset));\n        }\n        if (displayWidth <= 0 || displayHeight <= 0) {\n            return null; // Cropped away everything, invalid\n        }\n        // 2 = unspecified\n        let colourPrimaries = 2;\n        let transferCharacteristics = 2;\n        let matrixCoefficients = 2;\n        let fullRangeFlag = 0;\n        let pixelAspectRatio = { num: 1, den: 1 };\n        let numReorderFrames = null;\n        let maxDecFrameBuffering = null;\n        let bitstreamRestrictionFlagBitOffset = null;\n        let bitstreamRestrictionFlag = null;\n        const vuiParametersFlagBitOffset = bitstream.pos;\n        const vuiParametersPresentFlag = bitstream.readBits(1);\n        if (vuiParametersPresentFlag) {\n            const aspectRatioInfoPresentFlag = bitstream.readBits(1);\n            if (aspectRatioInfoPresentFlag) {\n                const aspectRatioIdc = bitstream.readBits(8);\n                if (aspectRatioIdc === 255) { // Extended_SAR\n                    pixelAspectRatio = {\n                        num: bitstream.readBits(16),\n                        den: bitstream.readBits(16),\n                    };\n                }\n                else {\n                    const aspectRatio = AVC_HEVC_ASPECT_RATIO_IDC_TABLE[aspectRatioIdc];\n                    if (aspectRatio) {\n                        pixelAspectRatio = aspectRatio;\n                    }\n                }\n            }\n            const overscanInfoPresentFlag = bitstream.readBits(1);\n            if (overscanInfoPresentFlag) {\n                bitstream.skipBits(1); // overscan_appropriate_flag\n            }\n            const videoSignalTypePresentFlag = bitstream.readBits(1);\n            if (videoSignalTypePresentFlag) {\n                bitstream.skipBits(3); // video_format\n                fullRangeFlag = bitstream.readBits(1);\n                const colourDescriptionPresentFlag = bitstream.readBits(1);\n                if (colourDescriptionPresentFlag) {\n                    colourPrimaries = bitstream.readBits(8);\n                    transferCharacteristics = bitstream.readBits(8);\n                    matrixCoefficients = bitstream.readBits(8);\n                }\n            }\n            const chromaLocInfoPresentFlag = bitstream.readBits(1);\n            if (chromaLocInfoPresentFlag) {\n                readExpGolomb(bitstream); // chroma_sample_loc_type_top_field\n                readExpGolomb(bitstream); // chroma_sample_loc_type_bottom_field\n            }\n            const timingInfoPresentFlag = bitstream.readBits(1);\n            if (timingInfoPresentFlag) {\n                bitstream.skipBits(32); // num_units_in_tick\n                bitstream.skipBits(32); // time_scale\n                bitstream.skipBits(1); // fixed_frame_rate_flag\n            }\n            const nalHrdParametersPresentFlag = bitstream.readBits(1);\n            if (nalHrdParametersPresentFlag) {\n                skipAvcHrdParameters(bitstream);\n            }\n            const vclHrdParametersPresentFlag = bitstream.readBits(1);\n            if (vclHrdParametersPresentFlag) {\n                skipAvcHrdParameters(bitstream);\n            }\n            if (nalHrdParametersPresentFlag || vclHrdParametersPresentFlag) {\n                bitstream.skipBits(1); // low_delay_hrd_flag\n            }\n            bitstream.skipBits(1); // pic_struct_present_flag\n            bitstreamRestrictionFlagBitOffset = bitstream.pos;\n            bitstreamRestrictionFlag = bitstream.readBits(1);\n            if (bitstreamRestrictionFlag) {\n                bitstream.skipBits(1); // motion_vectors_over_pic_boundaries_flag\n                readExpGolomb(bitstream); // max_bytes_per_pic_denom\n                readExpGolomb(bitstream); // max_bits_per_mb_denom\n                readExpGolomb(bitstream); // log2_max_mv_length_horizontal\n                readExpGolomb(bitstream); // log2_max_mv_length_vertical\n                // Both can't exceed MaxDpbFrames, which is at most 16. Bigger values would make us buffer absurd\n                // amounts of frames\n                numReorderFrames = Math.min(readExpGolomb(bitstream), 16);\n                maxDecFrameBuffering = Math.min(readExpGolomb(bitstream), 16);\n            }\n        }\n        if (numReorderFrames === null) {\n            assert(maxDecFrameBuffering === null);\n            const constraintSet3Flag = constraintFlags & 0b00010000;\n            if ((profileIdc === 44 || profileIdc === 86 || profileIdc === 100\n                || profileIdc === 110 || profileIdc === 122 || profileIdc === 244) && constraintSet3Flag) {\n                // \"If profile_idc is equal to 44, 86, 100, 110, 122, or 244 and constraint_set3_flag is equal to 1, the\n                // value of num_reorder_frames shall be inferred to be equal to 0.\"\n                numReorderFrames = 0;\n                maxDecFrameBuffering = 0;\n            }\n            else {\n                const picWidthInMbs = picWidthInMbsMinus1 + 1;\n                const picHeightInMapUnits = picHeightInMapUnitsMinus1 + 1;\n                const frameHeightInMbs = (2 - frameMbsOnlyFlag) * picHeightInMapUnits;\n                const levelInfo = AVC_LEVEL_TABLE.find(x => x.level >= levelIdc) ?? last(AVC_LEVEL_TABLE);\n                // \"MaxDpbFrames is equal to\n                // Min( MaxDpbMbs / ( picWidthInMbs * frameHeightInMbs ), 16 ) and MaxDpbMbs is given in Table A-1.\"\n                const maxDpbFrames = Math.min(Math.floor(levelInfo.maxDpbMbs / (picWidthInMbs * frameHeightInMbs)), 16);\n                // \"Otherwise, [...] the value of num_reorder_frames shall be inferred to be equal to MaxDpbFrames.\"\n                numReorderFrames = maxDpbFrames;\n                maxDecFrameBuffering = maxDpbFrames;\n            }\n        }\n        assert(maxDecFrameBuffering !== null);\n        return {\n            emulationUnpreventedBytes,\n            profileIdc,\n            constraintFlags,\n            levelIdc,\n            frameMbsOnlyFlag,\n            chromaFormatIdc,\n            bitDepthLumaMinus8,\n            bitDepthChromaMinus8,\n            codedWidth,\n            codedHeight,\n            displayWidth,\n            displayHeight,\n            pixelAspectRatio,\n            colourPrimaries,\n            matrixCoefficients,\n            transferCharacteristics,\n            fullRangeFlag,\n            numReorderFrames,\n            maxDecFrameBuffering,\n            vuiParametersFlagBitOffset,\n            bitstreamRestrictionFlagBitOffset,\n            bitstreamRestrictionFlag,\n        };\n    }\n    catch (error) {\n        Logging._error('Error parsing AVC SPS:', error);\n        return null;\n    }\n};\nconst skipAvcHrdParameters = (bitstream) => {\n    const cpb_cnt_minus1 = readExpGolomb(bitstream);\n    bitstream.skipBits(4); // bit_rate_scale\n    bitstream.skipBits(4); // cpb_size_scale\n    for (let i = 0; i <= cpb_cnt_minus1; i++) {\n        readExpGolomb(bitstream); // bit_rate_value_minus1[i]\n        readExpGolomb(bitstream); // cpb_size_value_minus1[i]\n        bitstream.skipBits(1); // cbr_flag[i]\n    }\n    bitstream.skipBits(5); // initial_cpb_removal_delay_length_minus1\n    bitstream.skipBits(5); // cpb_removal_delay_length_minus1\n    bitstream.skipBits(5); // dpb_output_delay_length_minus1\n    bitstream.skipBits(5); // time_offset_length\n};\n/**\n * Adds the missing \"bitstream restriction\" section within the VUI parameter section. This is done to communicate\n * frame reorder buffer size to the decoder, which may otherwise, in its absence, assume no B-frames and drop or skip\n * them.\n * See https://github.com/Vanilagy/mediabunny/issues/488\n */\nexport const addAvcBitstreamRestriction = (sps) => {\n    assert(sps.bitstreamRestrictionFlag !== 1);\n    const modifiedBytes = new Uint8Array(sps.emulationUnpreventedBytes.byteLength + 64);\n    const oldBitstream = new Bitstream(sps.emulationUnpreventedBytes);\n    const newBitstream = new Bitstream(modifiedBytes);\n    if (sps.bitstreamRestrictionFlag === null) {\n        // No VUI at all; let's write a minimal one\n        newBitstream.copyBits(sps.vuiParametersFlagBitOffset, oldBitstream);\n        newBitstream.writeBits(1, 1); // vui_parameters_present_flag\n        newBitstream.writeBits(1, 0); // aspect_ratio_info_present_flag\n        newBitstream.writeBits(1, 0); // overscan_info_present_flag\n        newBitstream.writeBits(1, 0); // video_signal_type_present_flag\n        newBitstream.writeBits(1, 0); // chroma_loc_info_present_flag\n        newBitstream.writeBits(1, 0); // timing_info_present_flag\n        newBitstream.writeBits(1, 0); // nal_hrd_parameters_present_flag\n        newBitstream.writeBits(1, 0); // vcl_hrd_parameters_present_flag\n        newBitstream.writeBits(1, 0); // pic_struct_present_flag\n    }\n    else {\n        // We have a VUI but no bitstream restriction info\n        assert(sps.bitstreamRestrictionFlagBitOffset !== null);\n        newBitstream.copyBits(sps.bitstreamRestrictionFlagBitOffset, oldBitstream);\n    }\n    newBitstream.writeBits(1, 1); // bitstream_restriction_flag\n    // Defaults from the H.264 spec:\n    newBitstream.writeBits(1, 1); // motion_vectors_over_pic_boundaries_flag\n    writeExpGolomb(newBitstream, 2); // max_bytes_per_pic_denom\n    writeExpGolomb(newBitstream, 1); // max_bits_per_mb_denom\n    writeExpGolomb(newBitstream, 16); // log2_max_mv_length_horizontal\n    writeExpGolomb(newBitstream, 16); // log2_max_mv_length_vertical\n    writeExpGolomb(newBitstream, sps.numReorderFrames);\n    writeExpGolomb(newBitstream, sps.maxDecFrameBuffering);\n    // There's nothing after this (VUI is at the end of SPS)\n    newBitstream.writeBits(1, 1); // rbsp_stop_one_bit\n    newBitstream.writeBits((8 - newBitstream.pos % 8) % 8, 0);\n    const byteLength = newBitstream.pos / 8;\n    assert(Number.isInteger(byteLength));\n    return addEmulationPreventionBytes(modifiedBytes.subarray(0, byteLength));\n};\nexport const concatHevcNalUnits = (nalUnits, decoderConfig) => {\n    if (decoderConfig.description) {\n        // Stream is length-prefixed. Let's extract the size of the length prefix from the decoder config\n        const bytes = toUint8Array(decoderConfig.description);\n        const lengthSizeMinusOne = bytes[21] & 0b11;\n        const lengthSize = (lengthSizeMinusOne + 1);\n        return concatNalUnitsInLengthPrefixed(nalUnits, lengthSize);\n    }\n    else {\n        // Stream is in Annex B format\n        return concatNalUnitsInAnnexB(nalUnits);\n    }\n};\nexport const iterateHevcNalUnits = (packetData, decoderConfig) => {\n    if (decoderConfig.description) {\n        const bytes = toUint8Array(decoderConfig.description);\n        const lengthSizeMinusOne = bytes[21] & 0b11;\n        const lengthSize = (lengthSizeMinusOne + 1);\n        return iterateNalUnitsInLengthPrefixed(packetData, lengthSize);\n    }\n    else {\n        return iterateNalUnitsInAnnexB(packetData);\n    }\n};\nexport const extractNalUnitTypeForHevc = (byte) => {\n    return (byte >> 1) & 0x3F;\n};\n/** Parses an HEVC SPS (Sequence Parameter Set) to extract video information. */\nexport const parseHevcSps = (sps) => {\n    try {\n        const bitstream = new Bitstream(removeEmulationPreventionBytes(sps));\n        bitstream.skipBits(16); // NAL header\n        bitstream.readBits(4); // sps_video_parameter_set_id\n        const spsMaxSubLayersMinus1 = bitstream.readBits(3);\n        const spsTemporalIdNestingFlag = bitstream.readBits(1);\n        const { general_profile_space, general_tier_flag, general_profile_idc, general_profile_compatibility_flags, general_constraint_indicator_flags, general_level_idc, } = parseProfileTierLevel(bitstream, spsMaxSubLayersMinus1);\n        readExpGolomb(bitstream); // sps_seq_parameter_set_id\n        const chromaFormatIdc = readExpGolomb(bitstream);\n        let separateColourPlaneFlag = 0;\n        if (chromaFormatIdc === 3) {\n            separateColourPlaneFlag = bitstream.readBits(1);\n        }\n        const picWidthInLumaSamples = readExpGolomb(bitstream);\n        const picHeightInLumaSamples = readExpGolomb(bitstream);\n        let displayWidth = picWidthInLumaSamples;\n        let displayHeight = picHeightInLumaSamples;\n        if (bitstream.readBits(1)) { // conformance_window_flag\n            const confWinLeftOffset = readExpGolomb(bitstream);\n            const confWinRightOffset = readExpGolomb(bitstream);\n            const confWinTopOffset = readExpGolomb(bitstream);\n            const confWinBottomOffset = readExpGolomb(bitstream);\n            // SubWidthC and SubHeightC depend on chroma_format_idc and separate_colour_plane_flag\n            let subWidthC = 1;\n            let subHeightC = 1;\n            const chromaArrayType = separateColourPlaneFlag === 0 ? chromaFormatIdc : 0;\n            if (chromaArrayType === 1) {\n                subWidthC = 2;\n                subHeightC = 2;\n            }\n            else if (chromaArrayType === 2) {\n                subWidthC = 2;\n                subHeightC = 1;\n            }\n            displayWidth -= (confWinLeftOffset + confWinRightOffset) * subWidthC;\n            displayHeight -= (confWinTopOffset + confWinBottomOffset) * subHeightC;\n        }\n        if (displayWidth <= 0 || displayHeight <= 0) {\n            return null; // Cropped away everything, invalid\n        }\n        const bitDepthLumaMinus8 = readExpGolomb(bitstream);\n        const bitDepthChromaMinus8 = readExpGolomb(bitstream);\n        readExpGolomb(bitstream); // log2_max_pic_order_cnt_lsb_minus4\n        const spsSubLayerOrderingInfoPresentFlag = bitstream.readBits(1);\n        const startI = spsSubLayerOrderingInfoPresentFlag ? 0 : spsMaxSubLayersMinus1;\n        let spsMaxNumReorderPics = 0;\n        for (let i = startI; i <= spsMaxSubLayersMinus1; i++) {\n            readExpGolomb(bitstream); // sps_max_dec_pic_buffering_minus1[i]\n            spsMaxNumReorderPics = readExpGolomb(bitstream); // sps_max_num_reorder_pics[i]\n            readExpGolomb(bitstream); // sps_max_latency_increase_plus1[i]\n        }\n        readExpGolomb(bitstream); // log2_min_luma_coding_block_size_minus3\n        readExpGolomb(bitstream); // log2_diff_max_min_luma_coding_block_size\n        readExpGolomb(bitstream); // log2_min_luma_transform_block_size_minus2\n        readExpGolomb(bitstream); // log2_diff_max_min_luma_transform_block_size\n        readExpGolomb(bitstream); // max_transform_hierarchy_depth_inter\n        readExpGolomb(bitstream); // max_transform_hierarchy_depth_intra\n        if (bitstream.readBits(1)) { // scaling_list_enabled_flag\n            if (bitstream.readBits(1)) {\n                skipScalingListData(bitstream);\n            }\n        }\n        bitstream.skipBits(1); // amp_enabled_flag\n        bitstream.skipBits(1); // sample_adaptive_offset_enabled_flag\n        if (bitstream.readBits(1)) { // pcm_enabled_flag\n            bitstream.skipBits(4); // pcm_sample_bit_depth_luma_minus1\n            bitstream.skipBits(4); // pcm_sample_bit_depth_chroma_minus1\n            readExpGolomb(bitstream); // log2_min_pcm_luma_coding_block_size_minus3\n            readExpGolomb(bitstream); // log2_diff_max_min_pcm_luma_coding_block_size\n            bitstream.skipBits(1); // pcm_loop_filter_disabled_flag\n        }\n        const numShortTermRefPicSets = readExpGolomb(bitstream);\n        skipAllStRefPicSets(bitstream, numShortTermRefPicSets);\n        if (bitstream.readBits(1)) { // long_term_ref_pics_present_flag\n            const numLongTermRefPicsSps = readExpGolomb(bitstream);\n            for (let i = 0; i < numLongTermRefPicsSps; i++) {\n                readExpGolomb(bitstream); // lt_ref_pic_poc_lsb_sps[i]\n                bitstream.skipBits(1); // used_by_curr_pic_lt_sps_flag[i]\n            }\n        }\n        bitstream.skipBits(1); // sps_temporal_mvp_enabled_flag\n        bitstream.skipBits(1); // strong_intra_smoothing_enabled_flag\n        let colourPrimaries = 2;\n        let transferCharacteristics = 2;\n        let matrixCoefficients = 2;\n        let fullRangeFlag = 0;\n        let minSpatialSegmentationIdc = 0;\n        let pixelAspectRatio = { num: 1, den: 1 };\n        if (bitstream.readBits(1)) { // vui_parameters_present_flag\n            const vui = parseHevcVui(bitstream, spsMaxSubLayersMinus1);\n            pixelAspectRatio = vui.pixelAspectRatio;\n            colourPrimaries = vui.colourPrimaries;\n            transferCharacteristics = vui.transferCharacteristics;\n            matrixCoefficients = vui.matrixCoefficients;\n            fullRangeFlag = vui.fullRangeFlag;\n            minSpatialSegmentationIdc = vui.minSpatialSegmentationIdc;\n        }\n        return {\n            displayWidth,\n            displayHeight,\n            pixelAspectRatio,\n            colourPrimaries,\n            transferCharacteristics,\n            matrixCoefficients,\n            fullRangeFlag,\n            // Can't exceed MaxDpbSize, which is at most 16. Bigger values would make us buffer absurd amounts of\n            // frames\n            maxDecFrameBuffering: Math.min(spsMaxNumReorderPics + 1, 16),\n            spsMaxSubLayersMinus1,\n            spsTemporalIdNestingFlag,\n            generalProfileSpace: general_profile_space,\n            generalTierFlag: general_tier_flag,\n            generalProfileIdc: general_profile_idc,\n            generalProfileCompatibilityFlags: general_profile_compatibility_flags,\n            generalConstraintIndicatorFlags: general_constraint_indicator_flags,\n            generalLevelIdc: general_level_idc,\n            chromaFormatIdc,\n            bitDepthLumaMinus8,\n            bitDepthChromaMinus8,\n            minSpatialSegmentationIdc,\n        };\n    }\n    catch (error) {\n        Logging._error('Error parsing HEVC SPS:', error);\n        return null;\n    }\n};\n/** Builds a HevcDecoderConfigurationRecord from an HEVC packet in Annex B format. */\nexport const extractHevcDecoderConfigurationRecord = (packetData) => {\n    try {\n        const vpsUnits = [];\n        const spsUnits = [];\n        const ppsUnits = [];\n        const seiUnits = [];\n        // The counts are capped at what the record can hold\n        const MAX_NAL_UNITS_PER_ARRAY = 0xffff;\n        for (const loc of iterateNalUnitsInAnnexB(packetData)) {\n            const nalUnit = packetData.subarray(loc.offset, loc.offset + loc.length);\n            const type = extractNalUnitTypeForHevc(nalUnit[0]);\n            if (type === HevcNalUnitType.VPS_NUT && vpsUnits.length < MAX_NAL_UNITS_PER_ARRAY) {\n                vpsUnits.push(nalUnit);\n            }\n            else if (type === HevcNalUnitType.SPS_NUT && spsUnits.length < MAX_NAL_UNITS_PER_ARRAY) {\n                spsUnits.push(nalUnit);\n            }\n            else if (type === HevcNalUnitType.PPS_NUT && ppsUnits.length < MAX_NAL_UNITS_PER_ARRAY) {\n                ppsUnits.push(nalUnit);\n            }\n            else if ((type === HevcNalUnitType.PREFIX_SEI_NUT || type === HevcNalUnitType.SUFFIX_SEI_NUT)\n                && seiUnits.length < MAX_NAL_UNITS_PER_ARRAY) {\n                seiUnits.push(nalUnit);\n            }\n        }\n        if (spsUnits.length === 0 || ppsUnits.length === 0)\n            return null;\n        const spsInfo = parseHevcSps(spsUnits[0]);\n        if (!spsInfo)\n            return null;\n        // Parse PPS for parallelismType\n        let parallelismType = 0;\n        if (ppsUnits.length > 0) {\n            const pps = ppsUnits[0];\n            const ppsBitstream = new Bitstream(removeEmulationPreventionBytes(pps));\n            ppsBitstream.skipBits(16); // NAL header\n            readExpGolomb(ppsBitstream); // pps_pic_parameter_set_id\n            readExpGolomb(ppsBitstream); // pps_seq_parameter_set_id\n            ppsBitstream.skipBits(1); // dependent_slice_segments_enabled_flag\n            ppsBitstream.skipBits(1); // output_flag_present_flag\n            ppsBitstream.skipBits(3); // num_extra_slice_header_bits\n            ppsBitstream.skipBits(1); // sign_data_hiding_enabled_flag\n            ppsBitstream.skipBits(1); // cabac_init_present_flag\n            readExpGolomb(ppsBitstream); // num_ref_idx_l0_default_active_minus1\n            readExpGolomb(ppsBitstream); // num_ref_idx_l1_default_active_minus1\n            readSignedExpGolomb(ppsBitstream); // init_qp_minus26\n            ppsBitstream.skipBits(1); // constrained_intra_pred_flag\n            ppsBitstream.skipBits(1); // transform_skip_enabled_flag\n            if (ppsBitstream.readBits(1)) { // cu_qp_delta_enabled_flag\n                readExpGolomb(ppsBitstream); // diff_cu_qp_delta_depth\n            }\n            readSignedExpGolomb(ppsBitstream); // pps_cb_qp_offset\n            readSignedExpGolomb(ppsBitstream); // pps_cr_qp_offset\n            ppsBitstream.skipBits(1); // pps_slice_chroma_qp_offsets_present_flag\n            ppsBitstream.skipBits(1); // weighted_pred_flag\n            ppsBitstream.skipBits(1); // weighted_bipred_flag\n            ppsBitstream.skipBits(1); // transquant_bypass_enabled_flag\n            const tiles_enabled_flag = ppsBitstream.readBits(1);\n            const entropy_coding_sync_enabled_flag = ppsBitstream.readBits(1);\n            if (!tiles_enabled_flag && !entropy_coding_sync_enabled_flag)\n                parallelismType = 0;\n            else if (tiles_enabled_flag && !entropy_coding_sync_enabled_flag)\n                parallelismType = 2;\n            else if (!tiles_enabled_flag && entropy_coding_sync_enabled_flag)\n                parallelismType = 3;\n            else\n                parallelismType = 0;\n        }\n        const arrays = [\n            ...(vpsUnits.length\n                ? [\n                    {\n                        arrayCompleteness: 1,\n                        nalUnitType: HevcNalUnitType.VPS_NUT,\n                        nalUnits: vpsUnits,\n                    },\n                ]\n                : []),\n            ...(spsUnits.length\n                ? [\n                    {\n                        arrayCompleteness: 1,\n                        nalUnitType: HevcNalUnitType.SPS_NUT,\n                        nalUnits: spsUnits,\n                    },\n                ]\n                : []),\n            ...(ppsUnits.length\n                ? [\n                    {\n                        arrayCompleteness: 1,\n                        nalUnitType: HevcNalUnitType.PPS_NUT,\n                        nalUnits: ppsUnits,\n                    },\n                ]\n                : []),\n            ...(seiUnits.length\n                ? [\n                    {\n                        arrayCompleteness: 1,\n                        nalUnitType: extractNalUnitTypeForHevc(seiUnits[0][0]),\n                        nalUnits: seiUnits,\n                    },\n                ]\n                : []),\n        ];\n        const record = {\n            configurationVersion: 1,\n            generalProfileSpace: spsInfo.generalProfileSpace,\n            generalTierFlag: spsInfo.generalTierFlag,\n            generalProfileIdc: spsInfo.generalProfileIdc,\n            generalProfileCompatibilityFlags: spsInfo.generalProfileCompatibilityFlags,\n            generalConstraintIndicatorFlags: spsInfo.generalConstraintIndicatorFlags,\n            generalLevelIdc: spsInfo.generalLevelIdc,\n            minSpatialSegmentationIdc: spsInfo.minSpatialSegmentationIdc,\n            parallelismType,\n            chromaFormatIdc: spsInfo.chromaFormatIdc,\n            bitDepthLumaMinus8: spsInfo.bitDepthLumaMinus8,\n            bitDepthChromaMinus8: spsInfo.bitDepthChromaMinus8,\n            avgFrameRate: 0,\n            constantFrameRate: 0,\n            numTemporalLayers: spsInfo.spsMaxSubLayersMinus1 + 1,\n            temporalIdNested: spsInfo.spsTemporalIdNestingFlag,\n            lengthSizeMinusOne: 3,\n            arrays,\n        };\n        return record;\n    }\n    catch (error) {\n        Logging._error('Error building HEVC Decoder Configuration Record:', error);\n        return null;\n    }\n};\nconst parseProfileTierLevel = (bitstream, maxNumSubLayersMinus1) => {\n    const general_profile_space = bitstream.readBits(2);\n    const general_tier_flag = bitstream.readBits(1);\n    const general_profile_idc = bitstream.readBits(5);\n    let general_profile_compatibility_flags = 0;\n    for (let i = 0; i < 32; i++) {\n        general_profile_compatibility_flags = (general_profile_compatibility_flags << 1) | bitstream.readBits(1);\n    }\n    const general_constraint_indicator_flags = new Uint8Array(6);\n    for (let i = 0; i < 6; i++) {\n        general_constraint_indicator_flags[i] = bitstream.readBits(8);\n    }\n    const general_level_idc = bitstream.readBits(8);\n    const sub_layer_profile_present_flag = [];\n    const sub_layer_level_present_flag = [];\n    for (let i = 0; i < maxNumSubLayersMinus1; i++) {\n        sub_layer_profile_present_flag.push(bitstream.readBits(1));\n        sub_layer_level_present_flag.push(bitstream.readBits(1));\n    }\n    if (maxNumSubLayersMinus1 > 0) {\n        for (let i = maxNumSubLayersMinus1; i < 8; i++) {\n            bitstream.skipBits(2); // reserved_zero_2bits\n        }\n    }\n    for (let i = 0; i < maxNumSubLayersMinus1; i++) {\n        if (sub_layer_profile_present_flag[i])\n            bitstream.skipBits(88);\n        if (sub_layer_level_present_flag[i])\n            bitstream.skipBits(8);\n    }\n    return {\n        general_profile_space,\n        general_tier_flag,\n        general_profile_idc,\n        general_profile_compatibility_flags,\n        general_constraint_indicator_flags,\n        general_level_idc,\n    };\n};\nconst skipScalingListData = (bitstream) => {\n    for (let sizeId = 0; sizeId < 4; sizeId++) {\n        for (let matrixId = 0; matrixId < (sizeId === 3 ? 2 : 6); matrixId++) {\n            const scaling_list_pred_mode_flag = bitstream.readBits(1);\n            if (!scaling_list_pred_mode_flag) {\n                readExpGolomb(bitstream); // scaling_list_pred_matrix_id_delta\n            }\n            else {\n                const coefNum = Math.min(64, 1 << (4 + (sizeId << 1)));\n                if (sizeId > 1) {\n                    readSignedExpGolomb(bitstream); // scaling_list_dc_coef_minus8\n                }\n                for (let i = 0; i < coefNum; i++) {\n                    readSignedExpGolomb(bitstream); // scaling_list_delta_coef\n                }\n            }\n        }\n    }\n};\nconst skipAllStRefPicSets = (bitstream, num_short_term_ref_pic_sets) => {\n    const NumDeltaPocs = [];\n    for (let stRpsIdx = 0; stRpsIdx < num_short_term_ref_pic_sets; stRpsIdx++) {\n        NumDeltaPocs[stRpsIdx] = skipStRefPicSet(bitstream, stRpsIdx, num_short_term_ref_pic_sets, NumDeltaPocs);\n    }\n};\nconst skipStRefPicSet = (bitstream, stRpsIdx, num_short_term_ref_pic_sets, NumDeltaPocs) => {\n    let NumDeltaPocsThis = 0;\n    let inter_ref_pic_set_prediction_flag = 0;\n    let RefRpsIdx = 0;\n    if (stRpsIdx !== 0) {\n        inter_ref_pic_set_prediction_flag = bitstream.readBits(1);\n    }\n    if (inter_ref_pic_set_prediction_flag) {\n        if (stRpsIdx === num_short_term_ref_pic_sets) {\n            const delta_idx_minus1 = readExpGolomb(bitstream);\n            RefRpsIdx = stRpsIdx - (delta_idx_minus1 + 1);\n        }\n        else {\n            RefRpsIdx = stRpsIdx - 1;\n        }\n        bitstream.readBits(1); // delta_rps_sign\n        readExpGolomb(bitstream); // abs_delta_rps_minus1\n        // The number of iterations is NumDeltaPocs[RefRpsIdx] + 1\n        const numDelta = NumDeltaPocs[RefRpsIdx] ?? 0;\n        for (let j = 0; j <= numDelta; j++) {\n            const used_by_curr_pic_flag = bitstream.readBits(1);\n            if (!used_by_curr_pic_flag) {\n                bitstream.readBits(1); // use_delta_flag\n            }\n        }\n        NumDeltaPocsThis = NumDeltaPocs[RefRpsIdx];\n    }\n    else {\n        const num_negative_pics = readExpGolomb(bitstream);\n        const num_positive_pics = readExpGolomb(bitstream);\n        for (let i = 0; i < num_negative_pics; i++) {\n            readExpGolomb(bitstream); // delta_poc_s0_minus1[i]\n            bitstream.readBits(1); // used_by_curr_pic_s0_flag[i]\n        }\n        for (let i = 0; i < num_positive_pics; i++) {\n            readExpGolomb(bitstream); // delta_poc_s1_minus1[i]\n            bitstream.readBits(1); // used_by_curr_pic_s1_flag[i]\n        }\n        NumDeltaPocsThis = num_negative_pics + num_positive_pics;\n    }\n    return NumDeltaPocsThis;\n};\nconst parseHevcVui = (bitstream, sps_max_sub_layers_minus1) => {\n    // Defaults: 2 = unspecified\n    let colourPrimaries = 2;\n    let transferCharacteristics = 2;\n    let matrixCoefficients = 2;\n    let fullRangeFlag = 0;\n    let minSpatialSegmentationIdc = 0;\n    let pixelAspectRatio = { num: 1, den: 1 };\n    if (bitstream.readBits(1)) { // aspect_ratio_info_present_flag\n        const aspect_ratio_idc = bitstream.readBits(8);\n        if (aspect_ratio_idc === 255) {\n            pixelAspectRatio = {\n                num: bitstream.readBits(16),\n                den: bitstream.readBits(16),\n            };\n        }\n        else {\n            const aspectRatio = AVC_HEVC_ASPECT_RATIO_IDC_TABLE[aspect_ratio_idc];\n            if (aspectRatio) {\n                pixelAspectRatio = aspectRatio;\n            }\n        }\n    }\n    if (bitstream.readBits(1)) { // overscan_info_present_flag\n        bitstream.readBits(1); // overscan_appropriate_flag\n    }\n    if (bitstream.readBits(1)) { // video_signal_type_present_flag\n        bitstream.readBits(3); // video_format\n        fullRangeFlag = bitstream.readBits(1);\n        if (bitstream.readBits(1)) { // colour_description_present_flag\n            colourPrimaries = bitstream.readBits(8);\n            transferCharacteristics = bitstream.readBits(8);\n            matrixCoefficients = bitstream.readBits(8);\n        }\n    }\n    if (bitstream.readBits(1)) { // chroma_loc_info_present_flag\n        readExpGolomb(bitstream); // chroma_sample_loc_type_top_field\n        readExpGolomb(bitstream); // chroma_sample_loc_type_bottom_field\n    }\n    bitstream.readBits(1); // neutral_chroma_indication_flag\n    bitstream.readBits(1); // field_seq_flag\n    bitstream.readBits(1); // frame_field_info_present_flag\n    if (bitstream.readBits(1)) { // default_display_window_flag\n        readExpGolomb(bitstream); // def_disp_win_left_offset\n        readExpGolomb(bitstream); // def_disp_win_right_offset\n        readExpGolomb(bitstream); // def_disp_win_top_offset\n        readExpGolomb(bitstream); // def_disp_win_bottom_offset\n    }\n    if (bitstream.readBits(1)) { // vui_timing_info_present_flag\n        bitstream.readBits(32); // vui_num_units_in_tick\n        bitstream.readBits(32); // vui_time_scale\n        if (bitstream.readBits(1)) { // vui_poc_proportional_to_timing_flag\n            readExpGolomb(bitstream); // vui_num_ticks_poc_diff_one_minus1\n        }\n        if (bitstream.readBits(1)) {\n            skipHevcHrdParameters(bitstream, true, sps_max_sub_layers_minus1);\n        }\n    }\n    if (bitstream.readBits(1)) { // bitstream_restriction_flag\n        bitstream.readBits(1); // tiles_fixed_structure_flag\n        bitstream.readBits(1); // motion_vectors_over_pic_boundaries_flag\n        bitstream.readBits(1); // restricted_ref_pic_lists_flag\n        minSpatialSegmentationIdc = readExpGolomb(bitstream);\n        readExpGolomb(bitstream); // max_bytes_per_pic_denom\n        readExpGolomb(bitstream); // max_bits_per_min_cu_denom\n        readExpGolomb(bitstream); // log2_max_mv_length_horizontal\n        readExpGolomb(bitstream); // log2_max_mv_length_vertical\n    }\n    return {\n        pixelAspectRatio,\n        colourPrimaries,\n        transferCharacteristics,\n        matrixCoefficients,\n        fullRangeFlag,\n        minSpatialSegmentationIdc,\n    };\n};\nconst skipHevcHrdParameters = (bitstream, commonInfPresentFlag, maxNumSubLayersMinus1) => {\n    let nal_hrd_parameters_present_flag = false;\n    let vcl_hrd_parameters_present_flag = false;\n    let sub_pic_hrd_params_present_flag = false;\n    if (commonInfPresentFlag) {\n        nal_hrd_parameters_present_flag = bitstream.readBits(1) === 1;\n        vcl_hrd_parameters_present_flag = bitstream.readBits(1) === 1;\n        if (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag) {\n            sub_pic_hrd_params_present_flag = bitstream.readBits(1) === 1;\n            if (sub_pic_hrd_params_present_flag) {\n                bitstream.readBits(8); // tick_divisor_minus2\n                bitstream.readBits(5); // du_cpb_removal_delay_increment_length_minus1\n                bitstream.readBits(1); // sub_pic_cpb_params_in_pic_timing_sei_flag\n                bitstream.readBits(5); // dpb_output_delay_du_length_minus1\n            }\n            bitstream.readBits(4); // bit_rate_scale\n            bitstream.readBits(4); // cpb_size_scale\n            if (sub_pic_hrd_params_present_flag) {\n                bitstream.readBits(4); // cpb_size_du_scale\n            }\n            bitstream.readBits(5); // initial_cpb_removal_delay_length_minus1\n            bitstream.readBits(5); // au_cpb_removal_delay_length_minus1\n            bitstream.readBits(5); // dpb_output_delay_length_minus1\n        }\n    }\n    for (let i = 0; i <= maxNumSubLayersMinus1; i++) {\n        const fixed_pic_rate_general_flag = bitstream.readBits(1) === 1;\n        let fixed_pic_rate_within_cvs_flag = true; // Default assumption if general is true\n        if (!fixed_pic_rate_general_flag) {\n            fixed_pic_rate_within_cvs_flag = bitstream.readBits(1) === 1;\n        }\n        let low_delay_hrd_flag = false; // Default assumption\n        if (fixed_pic_rate_within_cvs_flag) {\n            readExpGolomb(bitstream); // elemental_duration_in_tc_minus1[i]\n        }\n        else {\n            low_delay_hrd_flag = bitstream.readBits(1) === 1;\n        }\n        let CpbCnt = 1; // Default if low_delay is true\n        if (!low_delay_hrd_flag) {\n            const cpb_cnt_minus1 = readExpGolomb(bitstream); // cpb_cnt_minus1[i]\n            CpbCnt = cpb_cnt_minus1 + 1;\n        }\n        if (nal_hrd_parameters_present_flag) {\n            skipSubLayerHrdParameters(bitstream, CpbCnt, sub_pic_hrd_params_present_flag);\n        }\n        if (vcl_hrd_parameters_present_flag) {\n            skipSubLayerHrdParameters(bitstream, CpbCnt, sub_pic_hrd_params_present_flag);\n        }\n    }\n};\nconst skipSubLayerHrdParameters = (bitstream, CpbCnt, sub_pic_hrd_params_present_flag) => {\n    for (let i = 0; i < CpbCnt; i++) {\n        readExpGolomb(bitstream); // bit_rate_value_minus1[i]\n        readExpGolomb(bitstream); // cpb_size_value_minus1[i]\n        if (sub_pic_hrd_params_present_flag) {\n            readExpGolomb(bitstream); // cpb_size_du_value_minus1[i]\n            readExpGolomb(bitstream); // bit_rate_du_value_minus1[i]\n        }\n        bitstream.readBits(1); // cbr_flag[i]\n    }\n};\n/** Serializes an HevcDecoderConfigurationRecord into the format specified in Section 8.3.3.1 of ISO 14496-15. */\nexport const serializeHevcDecoderConfigurationRecord = (record) => {\n    const bytes = [];\n    bytes.push(record.configurationVersion);\n    bytes.push(((record.generalProfileSpace & 0x3) << 6)\n        | ((record.generalTierFlag & 0x1) << 5)\n        | (record.generalProfileIdc & 0x1F));\n    bytes.push((record.generalProfileCompatibilityFlags >>> 24) & 0xFF);\n    bytes.push((record.generalProfileCompatibilityFlags >>> 16) & 0xFF);\n    bytes.push((record.generalProfileCompatibilityFlags >>> 8) & 0xFF);\n    bytes.push(record.generalProfileCompatibilityFlags & 0xFF);\n    bytes.push(...record.generalConstraintIndicatorFlags);\n    bytes.push(record.generalLevelIdc & 0xFF);\n    bytes.push(0xF0 | ((record.minSpatialSegmentationIdc >> 8) & 0x0F)); // Reserved + high nibble\n    bytes.push(record.minSpatialSegmentationIdc & 0xFF); // Low byte\n    bytes.push(0xFC | (record.parallelismType & 0x03));\n    bytes.push(0xFC | (record.chromaFormatIdc & 0x03));\n    bytes.push(0xF8 | (record.bitDepthLumaMinus8 & 0x07));\n    bytes.push(0xF8 | (record.bitDepthChromaMinus8 & 0x07));\n    bytes.push((record.avgFrameRate >> 8) & 0xFF); // High byte\n    bytes.push(record.avgFrameRate & 0xFF); // Low byte\n    bytes.push(((record.constantFrameRate & 0x03) << 6)\n        | ((record.numTemporalLayers & 0x07) << 3)\n        | ((record.temporalIdNested & 0x01) << 2)\n        | (record.lengthSizeMinusOne & 0x03));\n    bytes.push(record.arrays.length & 0xFF);\n    for (const arr of record.arrays) {\n        bytes.push(((arr.arrayCompleteness & 0x01) << 7)\n            | (0 << 6)\n            | (arr.nalUnitType & 0x3F));\n        bytes.push((arr.nalUnits.length >> 8) & 0xFF); // High byte\n        bytes.push(arr.nalUnits.length & 0xFF); // Low byte\n        for (const nal of arr.nalUnits) {\n            bytes.push((nal.length >> 8) & 0xFF); // High byte\n            bytes.push(nal.length & 0xFF); // Low byte\n            for (let i = 0; i < nal.length; i++) {\n                bytes.push(nal[i]);\n            }\n        }\n    }\n    return new Uint8Array(bytes);\n};\n/** Deserializes an HevcDecoderConfigurationRecord from the format specified in Section 8.3.3.1 of ISO 14496-15. */\nexport const deserializeHevcDecoderConfigurationRecord = (data) => {\n    try {\n        const view = toDataView(data);\n        let offset = 0;\n        const configurationVersion = view.getUint8(offset++);\n        const byte1 = view.getUint8(offset++);\n        const generalProfileSpace = (byte1 >> 6) & 0x3;\n        const generalTierFlag = (byte1 >> 5) & 0x1;\n        const generalProfileIdc = byte1 & 0x1F;\n        const generalProfileCompatibilityFlags = view.getUint32(offset, false);\n        offset += 4;\n        const generalConstraintIndicatorFlags = data.subarray(offset, offset + 6);\n        offset += 6;\n        const generalLevelIdc = view.getUint8(offset++);\n        const minSpatialSegmentationIdc = ((view.getUint8(offset++) & 0x0F) << 8) | view.getUint8(offset++);\n        const parallelismType = view.getUint8(offset++) & 0x03;\n        const chromaFormatIdc = view.getUint8(offset++) & 0x03;\n        const bitDepthLumaMinus8 = view.getUint8(offset++) & 0x07;\n        const bitDepthChromaMinus8 = view.getUint8(offset++) & 0x07;\n        const avgFrameRate = view.getUint16(offset, false);\n        offset += 2;\n        const byte21 = view.getUint8(offset++);\n        const constantFrameRate = (byte21 >> 6) & 0x03;\n        const numTemporalLayers = (byte21 >> 3) & 0x07;\n        const temporalIdNested = (byte21 >> 2) & 0x01;\n        const lengthSizeMinusOne = byte21 & 0x03;\n        const numOfArrays = view.getUint8(offset++);\n        const arrays = [];\n        for (let i = 0; i < numOfArrays; i++) {\n            const arrByte = view.getUint8(offset++);\n            const arrayCompleteness = (arrByte >> 7) & 0x01;\n            const nalUnitType = arrByte & 0x3F;\n            const numNalus = view.getUint16(offset, false);\n            offset += 2;\n            const nalUnits = [];\n            for (let j = 0; j < numNalus; j++) {\n                const nalUnitLength = view.getUint16(offset, false);\n                offset += 2;\n                nalUnits.push(data.subarray(offset, offset + nalUnitLength));\n                offset += nalUnitLength;\n            }\n            arrays.push({\n                arrayCompleteness,\n                nalUnitType,\n                nalUnits,\n            });\n        }\n        return {\n            configurationVersion,\n            generalProfileSpace,\n            generalTierFlag,\n            generalProfileIdc,\n            generalProfileCompatibilityFlags,\n            generalConstraintIndicatorFlags,\n            generalLevelIdc,\n            minSpatialSegmentationIdc,\n            parallelismType,\n            chromaFormatIdc,\n            bitDepthLumaMinus8,\n            bitDepthChromaMinus8,\n            avgFrameRate,\n            constantFrameRate,\n            numTemporalLayers,\n            temporalIdNested,\n            lengthSizeMinusOne,\n            arrays,\n        };\n    }\n    catch (error) {\n        Logging._error('Error deserializing HEVC Decoder Configuration Record:', error);\n        return null;\n    }\n};\nvar HevcNaluOrderState;\n(function (HevcNaluOrderState) {\n    HevcNaluOrderState[HevcNaluOrderState[\"audAllowed\"] = 0] = \"audAllowed\";\n    HevcNaluOrderState[HevcNaluOrderState[\"beforeFirstVcl\"] = 1] = \"beforeFirstVcl\";\n    HevcNaluOrderState[HevcNaluOrderState[\"afterFirstVcl\"] = 2] = \"afterFirstVcl\";\n    HevcNaluOrderState[HevcNaluOrderState[\"eoBitstreamAllowed\"] = 3] = \"eoBitstreamAllowed\";\n    HevcNaluOrderState[HevcNaluOrderState[\"noMoreDataAllowed\"] = 4] = \"noMoreDataAllowed\";\n})(HevcNaluOrderState || (HevcNaluOrderState = {}));\n// This function sanitzes the contents of an HEVC packet such that\n// https://source.chromium.org/chromium/chromium/src/+/main:media/formats/mp4/hevc.cc's validation logic does not trip\n// up on its contents. The validation is often too strict and rejects packets that Chromium could decode just fine.\n// Chromium code retrieved on 2026-04-29.\n// See https://issues.chromium.org/issues/507611247.\nexport const sanitizeHevcPacketForChromium = (packetData, decoderConfig) => {\n    const removedNalUnits = new Set();\n    let orderState = HevcNaluOrderState.audAllowed;\n    for (const loc of iterateHevcNalUnits(packetData, decoderConfig)) {\n        if (orderState === HevcNaluOrderState.noMoreDataAllowed) {\n            removedNalUnits.add(loc.offset);\n            continue;\n        }\n        const type = extractNalUnitTypeForHevc(packetData[loc.offset]);\n        if (orderState === HevcNaluOrderState.eoBitstreamAllowed && type !== 37 /* EOB_NUT */) {\n            removedNalUnits.add(loc.offset);\n            continue;\n        }\n        let remove = false;\n        if (type === 35) { // AUD_NUT\n            if (orderState > HevcNaluOrderState.audAllowed) {\n                remove = true;\n            }\n            else {\n                orderState = HevcNaluOrderState.beforeFirstVcl;\n            }\n        }\n        else if (type <= 31) { // VCL (0-31)\n            if (orderState > HevcNaluOrderState.afterFirstVcl) {\n                remove = true;\n            }\n            else {\n                orderState = HevcNaluOrderState.afterFirstVcl;\n            }\n        }\n        else if (type === 36) { // EOS_NUT\n            if (orderState !== HevcNaluOrderState.afterFirstVcl) {\n                remove = true;\n            }\n            else {\n                orderState = HevcNaluOrderState.eoBitstreamAllowed;\n            }\n        }\n        else if (type === 37) { // EOB_NUT\n            if (orderState < HevcNaluOrderState.afterFirstVcl) {\n                remove = true;\n            }\n            else {\n                orderState = HevcNaluOrderState.noMoreDataAllowed;\n            }\n        }\n        else if (type === 32 || type === 33 || type === 34 || type === 39\n            || (type >= 41 && type <= 44) || (type >= 48 && type <= 55)) { // VPS, SPS, PPS, PREFIX_SEI, RSV_NVCL41..44, UNSPEC48..55\n            if (orderState > HevcNaluOrderState.beforeFirstVcl) {\n                remove = true;\n            }\n            else {\n                orderState = HevcNaluOrderState.beforeFirstVcl;\n            }\n        }\n        else if (type === 38 || type === 40\n            || (type >= 45 && type <= 47) || (type >= 56 && type <= 63)) { // FD, SUFFIX_SEI, RSV_NVCL45..47, UNSPEC56..63\n            if (orderState < HevcNaluOrderState.afterFirstVcl) {\n                remove = true;\n            }\n        }\n        if (remove) {\n            removedNalUnits.add(loc.offset);\n        }\n    }\n    // If nothing violated the rules, return null to signal that\n    if (removedNalUnits.size === 0) {\n        return null;\n    }\n    const filteredNalUnits = [];\n    for (const loc of iterateHevcNalUnits(packetData, decoderConfig)) {\n        if (!removedNalUnits.has(loc.offset)) {\n            filteredNalUnits.push(packetData.subarray(loc.offset, loc.offset + loc.length));\n        }\n    }\n    return concatHevcNalUnits(filteredNalUnits, decoderConfig);\n};\n// The color spaces from section 7.2.2 of the VP9 spec The matrix column is taken from FFmpeg's libavcodec/vp9.c\nconst VP9_COLOR_SPACE_TABLE = {\n    1: { colourPrimaries: 5, transferCharacteristics: 6, matrixCoefficients: 5 }, // CS_BT_601\n    2: { colourPrimaries: 1, transferCharacteristics: 1, matrixCoefficients: 1 }, // CS_BT_709\n    3: { colourPrimaries: 6, transferCharacteristics: 6, matrixCoefficients: 6 }, // CS_SMPTE_170\n    4: { colourPrimaries: 7, transferCharacteristics: 7, matrixCoefficients: 7 }, // CS_SMPTE_240\n    5: { colourPrimaries: 9, transferCharacteristics: 14, matrixCoefficients: 9 }, // CS_BT_2020\n    7: { colourPrimaries: 1, transferCharacteristics: 13, matrixCoefficients: 0 }, // CS_RGB (sRGB)\n};\nexport const extractVp9CodecInfoFromPacket = (packet) => {\n    // eslint-disable-next-line @stylistic/max-len\n    // https://storage.googleapis.com/downloads.webmproject.org/docs/vp9/vp9-bitstream-specification-v0.7-20170222-draft.pdf\n    // http://downloads.webmproject.org/docs/vp9/vp9-bitstream_superframe-and-uncompressed-header_v1.0.pdf\n    const bitstream = new Bitstream(packet);\n    // Frame marker (0b10)\n    const frameMarker = bitstream.readBits(2);\n    if (frameMarker !== 2) {\n        return null;\n    }\n    // Profile\n    const profileLowBit = bitstream.readBits(1);\n    const profileHighBit = bitstream.readBits(1);\n    const profile = (profileHighBit << 1) + profileLowBit;\n    // Skip reserved bit for profile 3\n    if (profile === 3) {\n        bitstream.skipBits(1);\n    }\n    // show_existing_frame\n    const showExistingFrame = bitstream.readBits(1);\n    if (showExistingFrame === 1) {\n        return null;\n    }\n    // frame_type (0 = key frame)\n    const frameType = bitstream.readBits(1);\n    if (frameType !== 0) {\n        return null;\n    }\n    // Skip show_frame and error_resilient_mode\n    bitstream.skipBits(2);\n    // Sync code (0x498342)\n    const syncCode = bitstream.readBits(24);\n    if (syncCode !== 0x498342) {\n        return null;\n    }\n    // Color config\n    let bitDepth = 8;\n    if (profile >= 2) {\n        const tenOrTwelveBit = bitstream.readBits(1);\n        bitDepth = tenOrTwelveBit ? 12 : 10;\n    }\n    // Color space\n    const colorSpace = bitstream.readBits(3);\n    let chromaSubsampling = 0;\n    let videoFullRangeFlag = 0;\n    if (colorSpace !== 7) { // 7 is CS_RGB\n        const colorRange = bitstream.readBits(1);\n        videoFullRangeFlag = colorRange;\n        if (profile === 1 || profile === 3) {\n            const subsamplingX = bitstream.readBits(1);\n            const subsamplingY = bitstream.readBits(1);\n            // 0 = 4:2:0 vertical\n            // 1 = 4:2:0 colocated\n            // 2 = 4:2:2\n            // 3 = 4:4:4\n            chromaSubsampling = !subsamplingX && !subsamplingY\n                ? 3 // 0,0 = 4:4:4\n                : subsamplingX && !subsamplingY\n                    ? 2 // 1,0 = 4:2:2\n                    : 1; // 1,1 = 4:2:0 colocated (default)\n            // Skip reserved bit\n            bitstream.skipBits(1);\n        }\n        else {\n            // For profile 0 and 2, always 4:2:0\n            chromaSubsampling = 1; // Using colocated as default\n        }\n    }\n    else {\n        // RGB is always 4:4:4\n        chromaSubsampling = 3;\n        videoFullRangeFlag = 1;\n    }\n    // Parse frame size\n    const widthMinusOne = bitstream.readBits(16);\n    const heightMinusOne = bitstream.readBits(16);\n    const width = widthMinusOne + 1;\n    const height = heightMinusOne + 1;\n    // Calculate level based on dimensions\n    const pictureSize = width * height;\n    let level = last(VP9_LEVEL_TABLE).level; // Default to highest level\n    for (const entry of VP9_LEVEL_TABLE) {\n        if (pictureSize <= entry.maxPictureSize) {\n            level = entry.level;\n            break;\n        }\n    }\n    const colorSpaceValues = VP9_COLOR_SPACE_TABLE[colorSpace];\n    const colourPrimaries = colorSpaceValues?.colourPrimaries ?? 2;\n    const transferCharacteristics = colorSpaceValues?.transferCharacteristics ?? 2;\n    const matrixCoefficients = colorSpaceValues?.matrixCoefficients ?? 2;\n    return {\n        profile,\n        level,\n        bitDepth,\n        chromaSubsampling,\n        videoFullRangeFlag,\n        colourPrimaries,\n        transferCharacteristics,\n        matrixCoefficients,\n    };\n};\nexport const vp9CodecInfoHasColorInfo = (info) => {\n    return info.colourPrimaries !== 2\n        || info.transferCharacteristics !== 2\n        || info.matrixCoefficients !== 2;\n};\n/** Iterates over all OBUs in an AV1 packet bitstream. */\nexport const iterateAv1PacketObus = function* (packet) {\n    // https://aomediacodec.github.io/av1-spec/av1-spec.pdf\n    const bitstream = new Bitstream(packet);\n    const readLeb128 = () => {\n        let value = 0;\n        for (let i = 0; i < 8; i++) {\n            const byte = bitstream.readAlignedByte();\n            // No bit shift since the value can get big\n            value += (byte & 0x7f) * 2 ** (i * 7);\n            if (!(byte & 0x80)) {\n                break;\n            }\n            // Spec requirement\n            if (i === 7 && (byte & 0x80)) {\n                return null;\n            }\n        }\n        // Spec requirement\n        if (value > 2 ** 32 - 1) {\n            return null;\n        }\n        return value;\n    };\n    while (bitstream.getBitsLeft() >= 8) {\n        // Parse OBU header\n        bitstream.skipBits(1);\n        const obuType = bitstream.readBits(4);\n        const obuExtension = bitstream.readBits(1);\n        const obuHasSizeField = bitstream.readBits(1);\n        bitstream.skipBits(1);\n        // Skip extension header if present\n        if (obuExtension) {\n            bitstream.skipBits(8);\n        }\n        // Read OBU size if present\n        let obuSize;\n        if (obuHasSizeField) {\n            const obuSizeValue = readLeb128();\n            if (obuSizeValue === null)\n                return; // It was invalid\n            obuSize = obuSizeValue;\n        }\n        else {\n            // Calculate remaining bits and convert to bytes, rounding down\n            obuSize = Math.floor(bitstream.getBitsLeft() / 8);\n        }\n        assert(bitstream.pos % 8 === 0);\n        yield {\n            type: obuType,\n            data: packet.subarray(bitstream.pos / 8, bitstream.pos / 8 + obuSize),\n        };\n        // Move to next OBU\n        bitstream.skipBits(obuSize * 8);\n    }\n};\n/**\n * When AV1 codec information is not provided by the container, we can still try to extract the information by digging\n * into the AV1 bitstream.\n */\nexport const extractAv1CodecInfoFromPacket = (packet) => {\n    // https://aomediacodec.github.io/av1-spec/av1-spec.pdf\n    for (const { type, data } of iterateAv1PacketObus(packet)) {\n        if (type !== 1) {\n            continue; // 1 == OBU_SEQUENCE_HEADER\n        }\n        const bitstream = new Bitstream(data);\n        // Read sequence header fields\n        const seqProfile = bitstream.readBits(3);\n        // eslint-disable-next-line @typescript-eslint/no-unused-vars\n        const stillPicture = bitstream.readBits(1);\n        const reducedStillPictureHeader = bitstream.readBits(1);\n        let seqLevel = 0;\n        let seqTier = 0;\n        let bufferDelayLengthMinus1 = 0;\n        if (reducedStillPictureHeader) {\n            seqLevel = bitstream.readBits(5);\n        }\n        else {\n            const timingInfoPresentFlag = bitstream.readBits(1);\n            let decoderModelInfoPresentFlag = 0;\n            if (timingInfoPresentFlag) {\n                bitstream.skipBits(32); // num_units_in_display_tick\n                bitstream.skipBits(32); // time_scale\n                const equalPictureInterval = bitstream.readBits(1);\n                if (equalPictureInterval) {\n                    // num_ticks_per_picture_minus_1 is uvlc-coded, so we need to seek past it manually\n                    let leadingZeros = 0;\n                    while (leadingZeros < 32 && !bitstream.readBits(1)) {\n                        leadingZeros++;\n                    }\n                    if (leadingZeros < 32) {\n                        bitstream.skipBits(leadingZeros);\n                    }\n                }\n                decoderModelInfoPresentFlag = bitstream.readBits(1);\n                if (decoderModelInfoPresentFlag) {\n                    bufferDelayLengthMinus1 = bitstream.readBits(5);\n                    bitstream.skipBits(32); // num_units_in_decoding_tick\n                    bitstream.skipBits(5); // buffer_removal_time_length_minus_1\n                    bitstream.skipBits(5); // frame_presentation_time_length_minus_1\n                }\n            }\n            const initialDisplayDelayPresentFlag = bitstream.readBits(1);\n            const operatingPointsCntMinus1 = bitstream.readBits(5);\n            for (let i = 0; i <= operatingPointsCntMinus1; i++) {\n                bitstream.skipBits(12); // operating_point_idc[i]\n                const seqLevelIdx = bitstream.readBits(5);\n                if (i === 0) {\n                    seqLevel = seqLevelIdx;\n                }\n                if (seqLevelIdx > 7) {\n                    const seqTierTemp = bitstream.readBits(1);\n                    if (i === 0) {\n                        seqTier = seqTierTemp;\n                    }\n                }\n                if (decoderModelInfoPresentFlag) {\n                    const decoderModelPresentForThisOp = bitstream.readBits(1);\n                    if (decoderModelPresentForThisOp) {\n                        const n = bufferDelayLengthMinus1 + 1;\n                        bitstream.skipBits(n); // decoder_buffer_delay[op]\n                        bitstream.skipBits(n); // encoder_buffer_delay[op]\n                        bitstream.skipBits(1); // low_delay_mode_flag[op]\n                    }\n                }\n                if (initialDisplayDelayPresentFlag) {\n                    const initialDisplayDelayPresentForThisOp = bitstream.readBits(1);\n                    if (initialDisplayDelayPresentForThisOp) {\n                        bitstream.skipBits(4); // initial_display_delay_minus_1[i]\n                    }\n                }\n            }\n        }\n        // Frame size\n        const frameWidthBitsMinus1 = bitstream.readBits(4);\n        const frameHeightBitsMinus1 = bitstream.readBits(4);\n        const n1 = frameWidthBitsMinus1 + 1;\n        bitstream.skipBits(n1); // max_frame_width_minus_1\n        const n2 = frameHeightBitsMinus1 + 1;\n        bitstream.skipBits(n2); // max_frame_height_minus_1\n        // Frame IDs\n        let frameIdNumbersPresentFlag = 0;\n        if (reducedStillPictureHeader) {\n            frameIdNumbersPresentFlag = 0;\n        }\n        else {\n            frameIdNumbersPresentFlag = bitstream.readBits(1);\n        }\n        if (frameIdNumbersPresentFlag) {\n            bitstream.skipBits(4); // delta_frame_id_length_minus_2\n            bitstream.skipBits(3); // additional_frame_id_length_minus_1\n        }\n        bitstream.skipBits(1); // use_128x128_superblock\n        bitstream.skipBits(1); // enable_filter_intra\n        bitstream.skipBits(1); // enable_intra_edge_filter\n        if (!reducedStillPictureHeader) {\n            bitstream.skipBits(1); // enable_interintra_compound\n            bitstream.skipBits(1); // enable_masked_compound\n            bitstream.skipBits(1); // enable_warped_motion\n            bitstream.skipBits(1); // enable_dual_filter\n            const enableOrderHint = bitstream.readBits(1);\n            if (enableOrderHint) {\n                bitstream.skipBits(1); // enable_jnt_comp\n                bitstream.skipBits(1); // enable_ref_frame_mvs\n            }\n            const seqChooseScreenContentTools = bitstream.readBits(1);\n            let seqForceScreenContentTools = 0;\n            if (seqChooseScreenContentTools) {\n                seqForceScreenContentTools = 2; // SELECT_SCREEN_CONTENT_TOOLS\n            }\n            else {\n                seqForceScreenContentTools = bitstream.readBits(1);\n            }\n            if (seqForceScreenContentTools > 0) {\n                const seqChooseIntegerMv = bitstream.readBits(1);\n                if (!seqChooseIntegerMv) {\n                    bitstream.skipBits(1); // seq_force_integer_mv\n                }\n            }\n            if (enableOrderHint) {\n                bitstream.skipBits(3); // order_hint_bits_minus_1\n            }\n        }\n        bitstream.skipBits(1); // enable_superres\n        bitstream.skipBits(1); // enable_cdef\n        bitstream.skipBits(1); // enable_restoration\n        // color_config()\n        const highBitdepth = bitstream.readBits(1);\n        let bitDepth = 8;\n        if (seqProfile === 2 && highBitdepth) {\n            const twelveBit = bitstream.readBits(1);\n            bitDepth = twelveBit ? 12 : 10;\n        }\n        else if (seqProfile <= 2) {\n            bitDepth = highBitdepth ? 10 : 8;\n        }\n        let monochrome = 0;\n        if (seqProfile !== 1) {\n            monochrome = bitstream.readBits(1);\n        }\n        let colourPrimaries = 2; // CP_UNSPECIFIED\n        let transferCharacteristics = 2; // TC_UNSPECIFIED\n        let matrixCoefficients = 2; // MC_UNSPECIFIED\n        const colorDescriptionPresentFlag = bitstream.readBits(1);\n        if (colorDescriptionPresentFlag) {\n            colourPrimaries = bitstream.readBits(8);\n            transferCharacteristics = bitstream.readBits(8);\n            matrixCoefficients = bitstream.readBits(8);\n        }\n        let videoFullRangeFlag = 0;\n        let chromaSubsamplingX = 1;\n        let chromaSubsamplingY = 1;\n        let chromaSamplePosition = 0; // CSP_UNKNOWN\n        if (monochrome) {\n            videoFullRangeFlag = bitstream.readBits(1);\n        }\n        else if (colourPrimaries === 1 && transferCharacteristics === 13 && matrixCoefficients === 0) {\n            // sRGB with an identity matrix, which is always full range 4:4:4\n            videoFullRangeFlag = 1;\n            chromaSubsamplingX = 0;\n            chromaSubsamplingY = 0;\n        }\n        else {\n            videoFullRangeFlag = bitstream.readBits(1);\n            if (seqProfile === 0) {\n                chromaSubsamplingX = 1;\n                chromaSubsamplingY = 1;\n            }\n            else if (seqProfile === 1) {\n                chromaSubsamplingX = 0;\n                chromaSubsamplingY = 0;\n            }\n            else {\n                if (bitDepth === 12) {\n                    chromaSubsamplingX = bitstream.readBits(1);\n                    chromaSubsamplingY = chromaSubsamplingX ? bitstream.readBits(1) : 0;\n                }\n                else {\n                    chromaSubsamplingX = 1;\n                    chromaSubsamplingY = 0;\n                }\n            }\n            if (chromaSubsamplingX && chromaSubsamplingY) {\n                chromaSamplePosition = bitstream.readBits(2);\n            }\n        }\n        return {\n            profile: seqProfile,\n            level: seqLevel,\n            tier: seqTier,\n            bitDepth,\n            monochrome,\n            chromaSubsamplingX,\n            chromaSubsamplingY,\n            chromaSamplePosition,\n            videoFullRangeFlag,\n            colourPrimaries,\n            transferCharacteristics,\n            matrixCoefficients,\n        };\n    }\n    return null;\n};\nexport const av1CodecInfoHasColorInfo = (info) => {\n    return info.colourPrimaries !== 2\n        || info.transferCharacteristics !== 2\n        || info.matrixCoefficients !== 2;\n};\nexport const extractProresCodecInfoFromPacket = (packet) => {\n    // https://wiki.multimedia.cx/index.php/Apple_ProRes\n    const frameHeaderStart = 8;\n    if (packet.length < frameHeaderStart + 28) {\n        return null;\n    }\n    const view = toDataView(packet);\n    if (view.getUint32(4) !== 0x69637066) { // 'icpf'\n        return null;\n    }\n    const headerSize = view.getUint16(frameHeaderStart);\n    if (headerSize < 28) {\n        return null;\n    }\n    return {\n        fullRange: false, // ProRes is always limited range\n        colourPrimaries: view.getUint8(frameHeaderStart + 14),\n        transferCharacteristics: view.getUint8(frameHeaderStart + 15),\n        matrixCoefficients: view.getUint8(frameHeaderStart + 16),\n    };\n};\nexport const parseOpusIdentificationHeader = (bytes) => {\n    if (bytes.byteLength < 19) {\n        throw new Error('Invalid Opus identification header: too short.');\n    }\n    const view = toDataView(bytes);\n    const outputChannelCount = view.getUint8(9);\n    const preSkip = view.getUint16(10, true);\n    const inputSampleRate = view.getUint32(12, true);\n    const outputGain = view.getInt16(16, true);\n    const channelMappingFamily = view.getUint8(18);\n    let channelMappingTable = null;\n    if (channelMappingFamily) {\n        channelMappingTable = bytes.subarray(19, 19 + 2 + outputChannelCount);\n    }\n    return {\n        outputChannelCount,\n        preSkip,\n        inputSampleRate,\n        outputGain,\n        channelMappingFamily,\n        channelMappingTable,\n    };\n};\n// From https://datatracker.ietf.org/doc/html/rfc6716, in 48 kHz samples\nconst OPUS_FRAME_DURATION_TABLE = [\n    480, 960, 1920, 2880,\n    480, 960, 1920, 2880,\n    480, 960, 1920, 2880,\n    480, 960,\n    480, 960,\n    120, 240, 480, 960,\n    120, 240, 480, 960,\n    120, 240, 480, 960,\n    120, 240, 480, 960,\n];\nexport const parseOpusTocByte = (packet) => {\n    const config = packet[0] >> 3;\n    const code = packet[0] & 0b11;\n    // A packet may pack more than one frame, in which case its duration is the frame duration times the number of\n    // frames it carries. See https://datatracker.ietf.org/doc/html/rfc6716, section 3.2.\n    let frameCount;\n    if (code === 0) {\n        frameCount = 1;\n    }\n    else if (code === 1 || code === 2) {\n        frameCount = 2;\n    }\n    else {\n        // Code 3: the frame count sits in the six low bits of the frame count byte\n        frameCount = packet[1] & 0b111111;\n    }\n    return {\n        durationInSamples: OPUS_FRAME_DURATION_TABLE[config] * frameCount,\n    };\n};\n// Based on vorbis_parser.c from FFmpeg.\nexport const parseModesFromVorbisSetupPacket = (setupHeader) => {\n    // Verify that this is a Setup header.\n    if (setupHeader.length < 7) {\n        throw new Error('Setup header is too short.');\n    }\n    if (setupHeader[0] !== 5) {\n        throw new Error('Wrong packet type in Setup header.');\n    }\n    const signature = String.fromCharCode(...setupHeader.slice(1, 7));\n    if (signature !== 'vorbis') {\n        throw new Error('Invalid packet signature in Setup header.');\n    }\n    // Reverse the entire buffer.\n    const bufSize = setupHeader.length;\n    const revBuffer = new Uint8Array(bufSize);\n    for (let i = 0; i < bufSize; i++) {\n        revBuffer[i] = setupHeader[bufSize - 1 - i];\n    }\n    // Initialize a Bitstream on the reversed buffer.\n    const bitstream = new Bitstream(revBuffer);\n    // --- Find the framing bit.\n    // In FFmpeg code, we scan until get_bits1() returns 1.\n    let gotFramingBit = 0;\n    while (bitstream.getBitsLeft() > 97) {\n        if (bitstream.readBits(1) === 1) {\n            gotFramingBit = bitstream.pos;\n            break;\n        }\n    }\n    if (gotFramingBit === 0) {\n        throw new Error('Invalid Setup header: framing bit not found.');\n    }\n    // --- Search backwards for a valid mode header.\n    // We try to “guess” the number of modes by reading a fixed pattern.\n    let modeCount = 0;\n    let gotModeHeader = false;\n    let lastModeCount = 0;\n    while (bitstream.getBitsLeft() >= 97) {\n        const tempPos = bitstream.pos;\n        const a = bitstream.readBits(8);\n        const b = bitstream.readBits(16);\n        const c = bitstream.readBits(16);\n        // If a > 63 or b or c nonzero, assume we’ve gone too far.\n        if (a > 63 || b !== 0 || c !== 0) {\n            bitstream.pos = tempPos;\n            break;\n        }\n        bitstream.skipBits(1);\n        modeCount++;\n        if (modeCount > 64) {\n            break;\n        }\n        const bsClone = bitstream.clone();\n        const candidate = bsClone.readBits(6) + 1;\n        if (candidate === modeCount) {\n            gotModeHeader = true;\n            lastModeCount = modeCount;\n        }\n    }\n    if (!gotModeHeader) {\n        throw new Error('Invalid Setup header: mode header not found.');\n    }\n    if (lastModeCount > 63) {\n        throw new Error(`Unsupported mode count: ${lastModeCount}.`);\n    }\n    const finalModeCount = lastModeCount;\n    // --- Reinitialize the bitstream.\n    bitstream.pos = 0;\n    // Skip the bits up to the found framing bit.\n    bitstream.skipBits(gotFramingBit);\n    // --- Now read, for each mode (in reverse order), 40 bits then one bit.\n    // That one bit is the mode blockflag.\n    const modeBlockflags = Array(finalModeCount).fill(0);\n    for (let i = finalModeCount - 1; i >= 0; i--) {\n        bitstream.skipBits(40);\n        modeBlockflags[i] = bitstream.readBits(1);\n    }\n    return { modeBlockflags };\n};\n/** Determines a packet's type (key or delta) by digging into the packet bitstream. */\nexport const determineVideoPacketType = (codec, decoderConfig, packetData) => {\n    switch (codec) {\n        case 'avc':\n            {\n                for (const loc of iterateAvcNalUnits(packetData, decoderConfig)) {\n                    const nalTypeByte = packetData[loc.offset];\n                    const type = extractNalUnitTypeForAvc(nalTypeByte);\n                    if (type >= AvcNalUnitType.NON_IDR_SLICE && type <= AvcNalUnitType.SLICE_DPC) {\n                        return 'delta';\n                    }\n                    if (type === AvcNalUnitType.IDR) {\n                        return 'key';\n                    }\n                    // In addition to IDR, Recovery Point SEI also counts as a valid H.264 keyframe by current consensus.\n                    // See https://github.com/w3c/webcodecs/issues/650 for the relevant discussion. WebKit and Firefox have\n                    // always supported them, but Chromium hasn't.\n                    if (type === AvcNalUnitType.SEI && !isChromium()) {\n                        const nalUnit = packetData.subarray(loc.offset, loc.offset + loc.length);\n                        const bytes = removeEmulationPreventionBytes(nalUnit);\n                        let pos = 1; // Skip NALU header\n                        // sei_rbsp()\n                        do {\n                            // sei_message()\n                            let payloadType = 0;\n                            while (true) {\n                                const nextByte = bytes[pos++];\n                                if (nextByte === undefined)\n                                    break;\n                                payloadType += nextByte;\n                                if (nextByte < 255) {\n                                    break;\n                                }\n                            }\n                            let payloadSize = 0;\n                            while (true) {\n                                const nextByte = bytes[pos++];\n                                if (nextByte === undefined)\n                                    break;\n                                payloadSize += nextByte;\n                                if (nextByte < 255) {\n                                    break;\n                                }\n                            }\n                            // sei_payload()\n                            const PAYLOAD_TYPE_RECOVERY_POINT = 6;\n                            if (payloadType === PAYLOAD_TYPE_RECOVERY_POINT) {\n                                const bitstream = new Bitstream(bytes);\n                                bitstream.pos = 8 * pos;\n                                let recoveryFrameCount = -1;\n                                try {\n                                    recoveryFrameCount = readExpGolomb(bitstream);\n                                }\n                                catch {\n                                    // Malformed SEI payload, so it's surely no recovery point\n                                }\n                                const exactMatchFlag = bitstream.readBits(1);\n                                if (recoveryFrameCount === 0 && exactMatchFlag === 1) {\n                                    // https://github.com/w3c/webcodecs/pull/910\n                                    // \"recovery_frame_cnt == 0 and exact_match_flag=1 in the SEI recovery payload\"\n                                    return 'key';\n                                }\n                            }\n                            pos += payloadSize;\n                        } while (pos < bytes.length - 1);\n                    }\n                }\n                return 'delta';\n            }\n            ;\n        case 'hevc':\n            {\n                for (const loc of iterateHevcNalUnits(packetData, decoderConfig)) {\n                    const type = extractNalUnitTypeForHevc(packetData[loc.offset]);\n                    if (type < HevcNalUnitType.BLA_W_LP) {\n                        return 'delta';\n                    }\n                    if (type <= HevcNalUnitType.RSV_IRAP_VCL23) {\n                        return 'key';\n                    }\n                }\n                return 'delta';\n            }\n            ;\n        case 'vp8':\n            {\n                // VP8, once again, by far the easiest to deal with.\n                const frameType = packetData[0] & 0b1;\n                return frameType === 0 ? 'key' : 'delta';\n            }\n            ;\n        case 'vp9':\n            {\n                const bitstream = new Bitstream(packetData);\n                if (bitstream.readBits(2) !== 2) {\n                    return null;\n                }\n                ;\n                const profileLowBit = bitstream.readBits(1);\n                const profileHighBit = bitstream.readBits(1);\n                const profile = (profileHighBit << 1) + profileLowBit;\n                // Skip reserved bit for profile 3\n                if (profile === 3) {\n                    bitstream.skipBits(1);\n                }\n                const showExistingFrame = bitstream.readBits(1);\n                if (showExistingFrame) {\n                    return null;\n                }\n                const frameType = bitstream.readBits(1);\n                return frameType === 0 ? 'key' : 'delta';\n            }\n            ;\n        case 'av1':\n            {\n                let reducedStillPictureHeader = false;\n                for (const { type, data } of iterateAv1PacketObus(packetData)) {\n                    if (type === 1) { // OBU_SEQUENCE_HEADER\n                        const bitstream = new Bitstream(data);\n                        bitstream.skipBits(4);\n                        reducedStillPictureHeader = !!bitstream.readBits(1);\n                    }\n                    else if (type === 3 // OBU_FRAME_HEADER\n                        || type === 6 // OBU_FRAME\n                        || type === 7 // OBU_REDUNDANT_FRAME_HEADER\n                    ) {\n                        if (reducedStillPictureHeader) {\n                            return 'key';\n                        }\n                        const bitstream = new Bitstream(data);\n                        const showExistingFrame = bitstream.readBits(1);\n                        if (showExistingFrame) {\n                            return null;\n                        }\n                        const frameType = bitstream.readBits(2);\n                        return frameType === 0 ? 'key' : 'delta';\n                    }\n                }\n                return null;\n            }\n            ;\n        case 'prores':\n            {\n                return 'key';\n            }\n            ;\n        default:\n            {\n                assertNever(codec);\n                assert(false);\n            }\n            ;\n    }\n};\nexport var FlacBlockType;\n(function (FlacBlockType) {\n    FlacBlockType[FlacBlockType[\"STREAMINFO\"] = 0] = \"STREAMINFO\";\n    FlacBlockType[FlacBlockType[\"VORBIS_COMMENT\"] = 4] = \"VORBIS_COMMENT\";\n    FlacBlockType[FlacBlockType[\"PICTURE\"] = 6] = \"PICTURE\";\n})(FlacBlockType || (FlacBlockType = {}));\nexport const readVorbisComments = (bytes, metadataTags) => {\n    // https://datatracker.ietf.org/doc/html/rfc7845#section-5.2\n    const commentView = toDataView(bytes);\n    let commentPos = 0;\n    if (bytes.length < 4) {\n        return;\n    }\n    const vendorStringLength = commentView.getUint32(commentPos, true);\n    commentPos += 4;\n    const vendorString = textDecoder.decode(bytes.subarray(commentPos, commentPos + vendorStringLength));\n    commentPos += vendorStringLength;\n    if (vendorStringLength > 0) {\n        // Expose the vendor string in the raw metadata\n        metadataTags.raw ??= {};\n        metadataTags.raw['vendor'] ??= vendorString;\n    }\n    if (commentPos + 4 > bytes.length) {\n        return;\n    }\n    const listLength = commentView.getUint32(commentPos, true);\n    commentPos += 4;\n    // Loop over all metadata tags\n    for (let i = 0; i < listLength; i++) {\n        if (commentPos + 4 > bytes.length) {\n            break; // The list is cut off, keep what we have\n        }\n        const stringLength = commentView.getUint32(commentPos, true);\n        commentPos += 4;\n        const string = textDecoder.decode(bytes.subarray(commentPos, commentPos + stringLength));\n        commentPos += stringLength;\n        const separatorIndex = string.indexOf('=');\n        if (separatorIndex === -1) {\n            continue;\n        }\n        const key = string.slice(0, separatorIndex).toUpperCase();\n        const value = string.slice(separatorIndex + 1);\n        metadataTags.raw ??= {};\n        if (Array.isArray(metadataTags.raw[key])) {\n            metadataTags.raw[key].push(value);\n        }\n        else if (typeof metadataTags.raw[key] === 'string') {\n            metadataTags.raw[key] = [metadataTags.raw[key], value];\n        }\n        else {\n            metadataTags.raw[key] ??= value;\n        }\n        switch (key) {\n            case 'TITLE':\n                {\n                    metadataTags.title ??= value;\n                }\n                ;\n                break;\n            case 'DESCRIPTION':\n                {\n                    metadataTags.description ??= value;\n                }\n                ;\n                break;\n            case 'ARTIST':\n                {\n                    metadataTags.artist ??= value;\n                }\n                ;\n                break;\n            case 'ALBUM':\n                {\n                    metadataTags.album ??= value;\n                }\n                ;\n                break;\n            case 'ALBUMARTIST':\n                {\n                    metadataTags.albumArtist ??= value;\n                }\n                ;\n                break;\n            case 'COMMENT':\n                {\n                    metadataTags.comment ??= value;\n                }\n                ;\n                break;\n            case 'LYRICS':\n                {\n                    metadataTags.lyrics ??= value;\n                }\n                ;\n                break;\n            case 'TRACKNUMBER':\n                {\n                    const parts = value.split('/');\n                    const trackNum = Number.parseInt(parts[0], 10);\n                    const tracksTotal = parts[1] && Number.parseInt(parts[1], 10);\n                    if (Number.isInteger(trackNum) && trackNum > 0) {\n                        metadataTags.trackNumber ??= trackNum;\n                    }\n                    if (tracksTotal && Number.isInteger(tracksTotal) && tracksTotal > 0) {\n                        metadataTags.tracksTotal ??= tracksTotal;\n                    }\n                }\n                ;\n                break;\n            case 'TRACKTOTAL':\n                {\n                    const tracksTotal = Number.parseInt(value, 10);\n                    if (Number.isInteger(tracksTotal) && tracksTotal > 0) {\n                        metadataTags.tracksTotal ??= tracksTotal;\n                    }\n                }\n                ;\n                break;\n            case 'DISCNUMBER':\n                {\n                    const parts = value.split('/');\n                    const discNum = Number.parseInt(parts[0], 10);\n                    const discsTotal = parts[1] && Number.parseInt(parts[1], 10);\n                    if (Number.isInteger(discNum) && discNum > 0) {\n                        metadataTags.discNumber ??= discNum;\n                    }\n                    if (discsTotal && Number.isInteger(discsTotal) && discsTotal > 0) {\n                        metadataTags.discsTotal ??= discsTotal;\n                    }\n                }\n                ;\n                break;\n            case 'DISCTOTAL':\n                {\n                    const discsTotal = Number.parseInt(value, 10);\n                    if (Number.isInteger(discsTotal) && discsTotal > 0) {\n                        metadataTags.discsTotal ??= discsTotal;\n                    }\n                }\n                ;\n                break;\n            case 'DATE':\n                {\n                    const date = new Date(value);\n                    if (!Number.isNaN(date.getTime())) {\n                        metadataTags.date ??= date;\n                    }\n                }\n                ;\n                break;\n            case 'BPM':\n                {\n                    const bpm = Number.parseInt(value, 10);\n                    if (Number.isInteger(bpm) && bpm > 0) {\n                        metadataTags.beatsPerMinute ??= bpm;\n                    }\n                }\n                ;\n                break;\n            case 'GENRE':\n                {\n                    metadataTags.genre ??= value;\n                }\n                ;\n                break;\n            case 'METADATA_BLOCK_PICTURE':\n                {\n                    // https://datatracker.ietf.org/doc/rfc9639/ Section 8.8\n                    try {\n                        const decoded = base64ToBytes(value);\n                        const view = toDataView(decoded);\n                        const pictureType = view.getUint32(0, false);\n                        const mediaTypeLength = view.getUint32(4, false);\n                        const mediaType = textDecoder.decode(decoded.subarray(8, 8 + mediaTypeLength)); // ASCII\n                        const descriptionLength = view.getUint32(8 + mediaTypeLength, false);\n                        const description = textDecoder.decode(decoded.subarray(12 + mediaTypeLength, 12 + mediaTypeLength + descriptionLength));\n                        const dataLength = view.getUint32(mediaTypeLength + descriptionLength + 28);\n                        const data = decoded.subarray(mediaTypeLength + descriptionLength + 32, mediaTypeLength + descriptionLength + 32 + dataLength);\n                        metadataTags.images ??= [];\n                        metadataTags.images.push({\n                            data,\n                            mimeType: mediaType,\n                            kind: pictureType === 3 ? 'coverFront' : pictureType === 4 ? 'coverBack' : 'unknown',\n                            name: undefined,\n                            description: description || undefined,\n                        });\n                    }\n                    catch {\n                        // Malformed picture, let's just skip it\n                    }\n                }\n                ;\n                break;\n        }\n    }\n};\nexport const createVorbisComments = (headerBytes, tags, writeImages) => {\n    // https://datatracker.ietf.org/doc/html/rfc7845#section-5.2\n    const commentHeaderParts = [\n        headerBytes,\n    ];\n    const encodedVendorString = textEncoder.encode(VERSIONED_NAME);\n    let currentBuffer = new Uint8Array(4 + encodedVendorString.length);\n    let currentView = new DataView(currentBuffer.buffer);\n    currentView.setUint32(0, encodedVendorString.length, true);\n    currentBuffer.set(encodedVendorString, 4);\n    commentHeaderParts.push(currentBuffer);\n    const writtenTags = [];\n    const addCommentTag = (key, value) => {\n        const joined = `${key}=${value}`;\n        const encoded = textEncoder.encode(joined);\n        currentBuffer = new Uint8Array(4 + encoded.length);\n        currentView = new DataView(currentBuffer.buffer);\n        currentView.setUint32(0, encoded.length, true);\n        currentBuffer.set(encoded, 4);\n        commentHeaderParts.push(currentBuffer);\n        writtenTags.push(key);\n    };\n    for (const { key, value } of keyValueIterator(tags)) {\n        switch (key) {\n            case 'title':\n                {\n                    addCommentTag('TITLE', value);\n                }\n                ;\n                break;\n            case 'description':\n                {\n                    addCommentTag('DESCRIPTION', value);\n                }\n                ;\n                break;\n            case 'artist':\n                {\n                    addCommentTag('ARTIST', value);\n                }\n                ;\n                break;\n            case 'album':\n                {\n                    addCommentTag('ALBUM', value);\n                }\n                ;\n                break;\n            case 'albumArtist':\n                {\n                    addCommentTag('ALBUMARTIST', value);\n                }\n                ;\n                break;\n            case 'genre':\n                {\n                    addCommentTag('GENRE', value);\n                }\n                ;\n                break;\n            case 'date':\n                {\n                    addCommentTag('DATE', value.toISOString().slice(0, 10));\n                }\n                ;\n                break;\n            case 'comment':\n                {\n                    addCommentTag('COMMENT', value);\n                }\n                ;\n                break;\n            case 'lyrics':\n                {\n                    addCommentTag('LYRICS', value);\n                }\n                ;\n                break;\n            case 'trackNumber':\n                {\n                    addCommentTag('TRACKNUMBER', value.toString());\n                }\n                ;\n                break;\n            case 'tracksTotal':\n                {\n                    addCommentTag('TRACKTOTAL', value.toString());\n                }\n                ;\n                break;\n            case 'discNumber':\n                {\n                    addCommentTag('DISCNUMBER', value.toString());\n                }\n                ;\n                break;\n            case 'discsTotal':\n                {\n                    addCommentTag('DISCTOTAL', value.toString());\n                }\n                ;\n                break;\n            case 'beatsPerMinute':\n                {\n                    addCommentTag('BPM', value.toString());\n                }\n                ;\n                break;\n            case 'images':\n                {\n                    // For example, in .flac, we put the pictures in a different section, not in the Vorbis comment header.\n                    if (!writeImages) {\n                        break;\n                    }\n                    for (const image of value) {\n                        // https://datatracker.ietf.org/doc/rfc9639/ Section 8.8\n                        const pictureType = image.kind === 'coverFront' ? 3 : image.kind === 'coverBack' ? 4 : 0;\n                        const encodedMediaType = new Uint8Array(image.mimeType.length);\n                        for (let i = 0; i < image.mimeType.length; i++) {\n                            encodedMediaType[i] = image.mimeType.charCodeAt(i);\n                        }\n                        const encodedDescription = textEncoder.encode(image.description ?? '');\n                        const buffer = new Uint8Array(4 // Picture type\n                            + 4 // MIME type length\n                            + encodedMediaType.length // MIME type\n                            + 4 // Description length\n                            + encodedDescription.length // Description\n                            + 16 // Width, height, color depth, number of colors\n                            + 4 // Picture data length\n                            + image.data.length);\n                        const view = toDataView(buffer);\n                        view.setUint32(0, pictureType, false);\n                        view.setUint32(4, encodedMediaType.length, false);\n                        buffer.set(encodedMediaType, 8);\n                        view.setUint32(8 + encodedMediaType.length, encodedDescription.length, false);\n                        buffer.set(encodedDescription, 12 + encodedMediaType.length);\n                        // Skip a bunch of fields (width, height, color depth, number of colors)\n                        view.setUint32(28 + encodedMediaType.length + encodedDescription.length, image.data.length, false);\n                        buffer.set(image.data, 32 + encodedMediaType.length + encodedDescription.length);\n                        const encoded = bytesToBase64(buffer);\n                        addCommentTag('METADATA_BLOCK_PICTURE', encoded);\n                    }\n                }\n                ;\n                break;\n            case 'raw':\n                {\n                    // Handled later\n                }\n                ;\n                break;\n            default: assertNever(key);\n        }\n    }\n    if (tags.raw) {\n        for (const key in tags.raw) {\n            const value = tags.raw[key] ?? tags.raw[key.toLowerCase()];\n            if (key === 'vendor' || value == null || writtenTags.includes(key)) {\n                continue;\n            }\n            if (typeof value === 'string') {\n                addCommentTag(key, value);\n            }\n            else if (Array.isArray(value)) {\n                // String arrays turn into the tag being repeated for each element\n                const isOnlyStrings = value.every(x => typeof x === 'string');\n                if (isOnlyStrings) {\n                    for (const elem of value) {\n                        addCommentTag(key, elem);\n                    }\n                }\n            }\n        }\n    }\n    const listLengthBuffer = new Uint8Array(4);\n    toDataView(listLengthBuffer).setUint32(0, writtenTags.length, true);\n    commentHeaderParts.splice(2, 0, listLengthBuffer); // Insert after the header and vendor section\n    // Merge all comment header parts into a single buffer\n    const commentHeaderLength = commentHeaderParts.reduce((a, b) => a + b.length, 0);\n    const commentHeader = new Uint8Array(commentHeaderLength);\n    let pos = 0;\n    for (const part of commentHeaderParts) {\n        commentHeader.set(part, pos);\n        pos += part.length;\n    }\n    return commentHeader;\n};\n// ============================================================================\n// AC-3 / E-AC-3 Parsing\n// Reference: ETSI TS 102 366 V1.4.1\n// ============================================================================\n/**\n * Channel counts indexed by acmod (Table 4.3).\n * Does NOT include LFE - add lfeon to get total channel count.\n */\nexport const AC3_ACMOD_CHANNEL_COUNTS = [2, 1, 2, 3, 3, 4, 4, 5];\n/**\n * Parse an AC-3 syncframe to extract BSI (Bit Stream Information) fields.\n * Section 4.3\n */\nexport const parseAc3SyncFrame = (data) => {\n    if (data.length < 7) {\n        return null;\n    }\n    // Check sync word (0x0B77)\n    if (data[0] !== 0x0B || data[1] !== 0x77) {\n        return null;\n    }\n    const bitstream = new Bitstream(data);\n    bitstream.skipBits(16); // sync word\n    bitstream.skipBits(16); // crc1\n    const fscod = bitstream.readBits(2);\n    if (fscod === 3) {\n        return null; // Reserved, invalid\n    }\n    const frmsizecod = bitstream.readBits(6);\n    const bsid = bitstream.readBits(5);\n    // Verify this is AC-3\n    if (bsid > 8) {\n        return null;\n    }\n    const bsmod = bitstream.readBits(3);\n    const acmod = bitstream.readBits(3);\n    // Skip cmixlev (center downmix level) if three front channels are in use (L, C, R).\n    if ((acmod & 0x1) !== 0 && acmod !== 0x1) {\n        bitstream.skipBits(2);\n    }\n    // Skip surmixlev (surround downmix level) if surround channels are in use.\n    if ((acmod & 0x4) !== 0) {\n        bitstream.skipBits(2);\n    }\n    // Skip dsurmod if stereo (acmod === 2)\n    if (acmod === 0x2) {\n        bitstream.skipBits(2);\n    }\n    const lfeon = bitstream.readBits(1);\n    const bitRateCode = Math.floor(frmsizecod / 2);\n    return { fscod, bsid, bsmod, acmod, lfeon, bitRateCode };\n};\n/**\n * AC-3 frame sizes in bytes, indexed by [3 * frmsizecod + fscod].\n * fscod: 0=48kHz, 1=44.1kHz, 2=32kHz\n * Values are 16-bit words * 2 (to convert to bytes).\n * Table 4.13\n */\nexport const AC3_FRAME_SIZES = [\n    // frmsizecod, [48kHz, 44.1kHz, 32kHz] in bytes\n    64 * 2, 69 * 2, 96 * 2,\n    64 * 2, 70 * 2, 96 * 2,\n    80 * 2, 87 * 2, 120 * 2,\n    80 * 2, 88 * 2, 120 * 2,\n    96 * 2, 104 * 2, 144 * 2,\n    96 * 2, 105 * 2, 144 * 2,\n    112 * 2, 121 * 2, 168 * 2,\n    112 * 2, 122 * 2, 168 * 2,\n    128 * 2, 139 * 2, 192 * 2,\n    128 * 2, 140 * 2, 192 * 2,\n    160 * 2, 174 * 2, 240 * 2,\n    160 * 2, 175 * 2, 240 * 2,\n    192 * 2, 208 * 2, 288 * 2,\n    192 * 2, 209 * 2, 288 * 2,\n    224 * 2, 243 * 2, 336 * 2,\n    224 * 2, 244 * 2, 336 * 2,\n    256 * 2, 278 * 2, 384 * 2,\n    256 * 2, 279 * 2, 384 * 2,\n    320 * 2, 348 * 2, 480 * 2,\n    320 * 2, 349 * 2, 480 * 2,\n    384 * 2, 417 * 2, 576 * 2,\n    384 * 2, 418 * 2, 576 * 2,\n    448 * 2, 487 * 2, 672 * 2,\n    448 * 2, 488 * 2, 672 * 2,\n    512 * 2, 557 * 2, 768 * 2,\n    512 * 2, 558 * 2, 768 * 2,\n    640 * 2, 696 * 2, 960 * 2,\n    640 * 2, 697 * 2, 960 * 2,\n    768 * 2, 835 * 2, 1152 * 2,\n    768 * 2, 836 * 2, 1152 * 2,\n    896 * 2, 975 * 2, 1344 * 2,\n    896 * 2, 976 * 2, 1344 * 2,\n    1024 * 2, 1114 * 2, 1536 * 2,\n    1024 * 2, 1115 * 2, 1536 * 2,\n    1152 * 2, 1253 * 2, 1728 * 2,\n    1152 * 2, 1254 * 2, 1728 * 2,\n    1280 * 2, 1393 * 2, 1920 * 2,\n    1280 * 2, 1394 * 2, 1920 * 2,\n];\n/** Number of samples per AC-3 syncframe (always 1536) */\nexport const AC3_SAMPLES_PER_FRAME = 1536;\n/**\n * AC-3 registration_descriptor for MPEG-TS.\n * Section A.2.3\n */\nexport const AC3_REGISTRATION_DESCRIPTOR = new Uint8Array([0x05, 0x04, 0x41, 0x43, 0x2d, 0x33]);\n/** E-AC-3 registration_descriptor for MPEG-TS/ */\nexport const EAC3_REGISTRATION_DESCRIPTOR = new Uint8Array([0x05, 0x04, 0x45, 0x41, 0x43, 0x33]);\n/** Number of audio blocks per syncframe, indexed by numblkscod */\nexport const EAC3_NUMBLKS_TABLE = [1, 2, 3, 6];\n/**\n * Parse an E-AC-3 syncframe to extract BSI fields.\n * Section E.1.2\n */\nexport const parseEac3SyncFrame = (data) => {\n    if (data.length < 6) {\n        return null;\n    }\n    // Check sync word (0x0B77)\n    if (data[0] !== 0x0B || data[1] !== 0x77) {\n        return null;\n    }\n    const bitstream = new Bitstream(data);\n    bitstream.skipBits(16); // sync word\n    const strmtyp = bitstream.readBits(2);\n    bitstream.skipBits(3); // substreamid\n    // Only parse independent substreams (strmtyp 0 or 2)\n    if (strmtyp !== 0 && strmtyp !== 2) {\n        return null;\n    }\n    const frmsiz = bitstream.readBits(11);\n    const fscod = bitstream.readBits(2);\n    let fscod2 = 0;\n    let numblkscod;\n    if (fscod === 3) {\n        // fscod2 enables reduced sample rates (24/22.05/16 kHz) per ATSC A/52:2018\n        fscod2 = bitstream.readBits(2);\n        numblkscod = 3; // Implicitly 6 blocks when fscod=3\n    }\n    else {\n        numblkscod = bitstream.readBits(2);\n    }\n    const acmod = bitstream.readBits(3);\n    const lfeon = bitstream.readBits(1);\n    const bsid = bitstream.readBits(5);\n    // Verify this is E-AC-3\n    if (bsid < 11 || bsid > 16) {\n        return null;\n    }\n    // Calculate data rate: ((frmsiz + 1) * fs) / (numblks * 16)\n    const numblks = EAC3_NUMBLKS_TABLE[numblkscod];\n    let fs;\n    if (fscod < 3) {\n        fs = AC3_SAMPLE_RATES[fscod] / 1000;\n    }\n    else {\n        fs = EAC3_REDUCED_SAMPLE_RATES[fscod2] / 1000;\n    }\n    const dataRate = Math.round(((frmsiz + 1) * fs) / (numblks * 16));\n    // These fields require parsing beyond the first frame.\n    // Defaults are correct for almost all content.\n    const bsmod = 0;\n    const numDepSub = 0;\n    const chanLoc = 0;\n    const substream = {\n        fscod,\n        fscod2,\n        bsid,\n        bsmod,\n        acmod,\n        lfeon,\n        numDepSub,\n        chanLoc,\n    };\n    return {\n        dataRate,\n        substreams: [substream],\n    };\n};\n/**\n * Parse a dec3 box to extract E-AC-3 parameters.\n * Section F.6\n */\nexport const parseEac3Config = (data) => {\n    if (data.length < 2) {\n        return null;\n    }\n    const bitstream = new Bitstream(data);\n    const dataRate = bitstream.readBits(13);\n    const numIndSub = bitstream.readBits(3);\n    const substreams = [];\n    for (let i = 0; i <= numIndSub; i++) {\n        // Check we have enough data for this substream\n        // Each substream needs at least 24 bits (3 bytes) without dependent subs\n        if (Math.ceil(bitstream.pos / 8) + 3 > data.length) {\n            break;\n        }\n        const fscod = bitstream.readBits(2);\n        const bsid = bitstream.readBits(5);\n        bitstream.skipBits(1); // reserved\n        bitstream.skipBits(1); // asvc\n        const bsmod = bitstream.readBits(3);\n        const acmod = bitstream.readBits(3);\n        const lfeon = bitstream.readBits(1);\n        bitstream.skipBits(3); // reserved\n        const numDepSub = bitstream.readBits(4);\n        let chanLoc = 0;\n        if (numDepSub > 0) {\n            chanLoc = bitstream.readBits(9);\n        }\n        else {\n            bitstream.skipBits(1); // reserved\n        }\n        substreams.push({\n            fscod,\n            fscod2: null,\n            bsid,\n            bsmod,\n            acmod,\n            lfeon,\n            numDepSub,\n            chanLoc,\n        });\n    }\n    if (substreams.length === 0) {\n        return null;\n    }\n    return { dataRate, substreams };\n};\n/**\n * Get sample rate from E-AC-3 config.\n * See ATSC A/52:2018 for handling fscod2.\n */\nexport const getEac3SampleRate = (config) => {\n    const sub = config.substreams[0];\n    assert(sub);\n    if (sub.fscod < 3) {\n        return AC3_SAMPLE_RATES[sub.fscod];\n    }\n    else if (sub.fscod2 !== null && sub.fscod2 < 3) {\n        return EAC3_REDUCED_SAMPLE_RATES[sub.fscod2];\n    }\n    return null;\n};\n/**\n * Get channel count from E-AC-3 config (first independent substream only).\n */\nexport const getEac3ChannelCount = (config) => {\n    const sub = config.substreams[0];\n    assert(sub);\n    let channels = AC3_ACMOD_CHANNEL_COUNTS[sub.acmod] + sub.lfeon;\n    // Add channels from dependent substreams\n    if (sub.numDepSub > 0) {\n        const CHAN_LOC_COUNTS = [2, 2, 1, 1, 2, 2, 2, 1, 1];\n        for (let bit = 0; bit < 9; bit++) {\n            if (sub.chanLoc & (1 << (8 - bit))) {\n                channels += CHAN_LOC_COUNTS[bit];\n            }\n        }\n    }\n    return channels;\n};\n// ============================================================================\n// DTS Parsing\n// Reference: ETSI TS 102 114 V1.6.1\n// ============================================================================\n/** Core substream sync word, in the 16-bit big-endian packing that the registry mandates. */\nexport const DTS_CORE_SYNC_WORD = 0x7ffe8001;\n/** Extension substream sync word. Section 7.4.1 */\nexport const DTS_EXSS_SYNC_WORD = 0x64582025;\n/** The core frame header never reaches beyond this many bytes. */\nexport const DTS_CORE_FRAME_HEADER_SIZE = 18;\n/** An extension substream always declares its own size within this many bytes. */\nexport const DTS_EXSS_HEADER_PREFIX_SIZE = 10;\n/** The largest nuExtSSHeaderSize can get, and therefore how far the asset descriptors can reach. */\nexport const DTS_EXSS_MAX_HEADER_SIZE = 4096;\n/** Number of PCM samples in one core PCM block; the core codes its length as a count of these. */\nexport const DTS_PCM_BLOCK_SAMPLES = 32;\n/** Size of the DTSSpecificBox (ddts) payload in bytes. */\nexport const DTS_SPECIFIC_BOX_SIZE = 20;\n/** Number of PCM blocks that a core frame's length must be a multiple of. */\nconst DTS_SUBBAND_SAMPLES = 8;\n/** Core sample rates indexed by SFREQ. Zeroes mark invalid codes. Table 5-4 */\nconst DTS_CORE_SAMPLE_RATES = [\n    0, 8000, 16000, 32000, 0, 0, 11025, 22050,\n    44100, 0, 0, 12000, 24000, 48000, 96000, 192000,\n];\n/**\n * Core bit rates in bps indexed by RATE, where a zero means the code isn't a constant rate. Table 5-7\n *\n * Note that FFmpeg's ff_dca_bit_rates has 896000 where the spec has 960, and defines rates for codes 25 to 28\n * which this revision of the spec calls invalid. We keep the latter, since they cost nothing and some content\n * predating the spec revision uses them.\n */\nconst DTS_CORE_BIT_RATES = [\n    32000, 56000, 64000, 96000, 112000, 128000, 192000, 224000,\n    256000, 320000, 384000, 448000, 512000, 576000, 640000, 768000,\n    960000, 1024000, 1152000, 1280000, 1344000, 1408000, 1411200, 1472000,\n    1536000, 1920000, 2048000, 3072000, 3840000, 0, 0, 0,\n];\n/** Source PCM resolutions in bits indexed by PCMR. Zeroes mark invalid codes. */\nconst DTS_PCM_RESOLUTIONS = [16, 16, 20, 20, 0, 24, 24, 0];\n/** Channel counts indexed by AMODE, not counting LFE. */\nconst DTS_AMODE_CHANNEL_COUNTS = [1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 8];\n/**\n * Speaker layout masks indexed by AMODE, expressed with the same bits as `ChannelLayout` in the DTSSpecificBox\n * and `nuSpkrActivityMask` in an extension substream asset descriptor.\n */\nconst DTS_AMODE_CHANNEL_LAYOUTS = [\n    0x0001, 0x0002, 0x0002, 0x0002, 0x0002, 0x0003, 0x0012, 0x0013,\n    0x0006, 0x0007, 0x0206, 0x0143, 0x0053, 0x0207, 0x0246, 0x0217,\n];\n/** The LFE1 speaker bit in a channel layout mask. */\nconst DTS_CHANNEL_LAYOUT_LFE1 = 0x0008;\n/** The channel layout bits that stand for a pair of speakers rather than a single one. */\nconst DTS_CHANNEL_LAYOUT_PAIR_MASK = 0xae66;\n/** Reference clock rates indexed by nuRefClockCode. The last code is unused. Table 7-3 */\nconst DTS_EXSS_REF_CLOCKS = [32000, 44100, 48000, 0];\n/** Sample rates used by extension substream assets, indexed by nuMaxSampleRate. */\nconst DTS_EXSS_SAMPLE_RATES = [\n    8000, 16000, 32000, 64000, 128000, 22050, 44100, 88200,\n    176400, 352800, 12000, 24000, 48000, 96000, 192000, 384000,\n];\n/** Frame durations that the DTSSpecificBox can express, indexed by FrameDuration. */\nconst DTS_SPECIFIC_BOX_FRAME_DURATIONS = [512, 1024, 2048, 4096];\n/**\n * Parse one complete DTS frame, being a core substream frame followed by any number of extension substreams,\n * or an extension substream on its own. Section 5 and Section 7.4.1\n */\nexport const parseDtsFrame = (data) => {\n    const core = parseDtsCoreFrameHeader(data);\n    const view = toDataView(data);\n    // The core substream is padded out to a 4-byte boundary before the first extension substream starts\n    let offset = core ? Math.ceil(core.frameSize / 4) * 4 : 0;\n    let firstExss = null;\n    while (offset + 4 <= data.length && view.getUint32(offset) === DTS_EXSS_SYNC_WORD) {\n        const exss = parseDtsExssHeader(data.subarray(offset));\n        if (!exss) {\n            break;\n        }\n        firstExss ??= exss;\n        offset += exss.frameSize;\n    }\n    if (core) {\n        // The core describes what every DTS decoder can play back; the extension substreams only build on top of\n        // it, so the core's parameters are the ones we report.\n        return {\n            frameSize: firstExss ? offset : core.frameSize,\n            sampleRate: core.sampleRate,\n            numberOfChannels: core.numberOfChannels,\n            sampleCount: core.sampleCount,\n            channelLayout: core.channelLayout,\n            pcmResolution: core.pcmResolution,\n            bitRate: core.bitRate,\n            core,\n            hasExtensions: firstExss !== null,\n        };\n    }\n    if (!firstExss?.asset) {\n        return null;\n    }\n    const { asset } = firstExss;\n    return {\n        frameSize: offset,\n        sampleRate: asset.sampleRate,\n        numberOfChannels: asset.numberOfChannels,\n        sampleCount: asset.sampleCount,\n        channelLayout: asset.channelLayout,\n        pcmResolution: asset.pcmResolution,\n        bitRate: 0,\n        core: null,\n        hasExtensions: true,\n    };\n};\n/**\n * Works out which four-character code describes a packet, or null when the packet doesn't say. Telling 'dtsl'\n * from 'dtse' would mean working out whether the asset holds XLL or LBR data, which sits behind the speaker\n * remapping and mixing metadata deep in the asset descriptor, so we don't do it.\n */\nexport const extractDtsFourCcFromPacket = (data) => {\n    const frameInfo = parseDtsFrame(data);\n    if (!frameInfo?.core) {\n        return null;\n    }\n    return frameInfo.hasExtensions ? 'dtsh' : 'dtsc';\n};\n/** Parse the header of a core substream frame. Section 5.3 */\nexport const parseDtsCoreFrameHeader = (data) => {\n    if (data.length < DTS_CORE_FRAME_HEADER_SIZE) {\n        return null;\n    }\n    if (data[0] !== 0x7f || data[1] !== 0xfe || data[2] !== 0x80 || data[3] !== 0x01) {\n        return null;\n    }\n    const bitstream = new Bitstream(data);\n    bitstream.skipBits(32); // SYNC\n    bitstream.skipBits(1); // FTYPE\n    // Terminating frames carry fewer samples than a full PCM block; we don't handle those\n    if (bitstream.readBits(5) !== DTS_PCM_BLOCK_SAMPLES - 1) {\n        return null;\n    }\n    const cpf = bitstream.readBits(1);\n    const npcmblocks = bitstream.readBits(7) + 1;\n    if (npcmblocks % DTS_SUBBAND_SAMPLES !== 0) {\n        return null;\n    }\n    const frameSize = bitstream.readBits(14) + 1;\n    if (frameSize < 96) {\n        return null;\n    }\n    const amode = bitstream.readBits(6);\n    if (amode >= DTS_AMODE_CHANNEL_COUNTS.length) {\n        return null;\n    }\n    const sampleRate = DTS_CORE_SAMPLE_RATES[bitstream.readBits(4)];\n    if (sampleRate === 0) {\n        return null;\n    }\n    const bitRate = DTS_CORE_BIT_RATES[bitstream.readBits(5)];\n    if (bitstream.readBits(1) !== 0) {\n        return null; // A reserved bit that must be zero, so a cheap way to reject false sync words\n    }\n    bitstream.skipBits(1 + 1 + 1 + 1); // DYNF, TIMEF, AUXF, HDCD\n    bitstream.skipBits(3 + 1 + 1); // EXT_AUDIO_ID, EXT_AUDIO, ASPF\n    const lff = bitstream.readBits(2);\n    if (lff === 3) {\n        return null;\n    }\n    bitstream.skipBits(1); // HFLAG\n    if (cpf) {\n        bitstream.skipBits(16); // HCRC\n    }\n    bitstream.skipBits(1 + 4 + 2); // FILTS, VERNUM, CHIST\n    const pcmResolution = DTS_PCM_RESOLUTIONS[bitstream.readBits(3)];\n    if (pcmResolution === 0) {\n        return null;\n    }\n    const lfePresent = lff !== 0;\n    return {\n        frameSize,\n        sampleRate,\n        numberOfChannels: DTS_AMODE_CHANNEL_COUNTS[amode] + (lfePresent ? 1 : 0),\n        sampleCount: npcmblocks * DTS_PCM_BLOCK_SAMPLES,\n        channelLayout: DTS_AMODE_CHANNEL_LAYOUTS[amode] | (lfePresent ? DTS_CHANNEL_LAYOUT_LFE1 : 0),\n        amode,\n        lfePresent,\n        bitRate,\n        pcmResolution,\n    };\n};\n/** Parse the header of an extension substream, along with its first audio asset descriptor. Section 7.4.1 */\nexport const parseDtsExssHeader = (data) => {\n    if (data.length < DTS_EXSS_HEADER_PREFIX_SIZE) {\n        return null;\n    }\n    if (data[0] !== 0x64 || data[1] !== 0x58 || data[2] !== 0x20 || data[3] !== 0x25) {\n        return null;\n    }\n    const bitstream = new Bitstream(data);\n    bitstream.skipBits(32); // SYNC\n    bitstream.skipBits(8); // nuUserDefinedBits\n    const extSsIndex = bitstream.readBits(2);\n    const wideHeader = bitstream.readBits(1);\n    const headerSizeBits = 8 + 4 * wideHeader;\n    const frameSizeBits = 16 + 4 * wideHeader;\n    bitstream.skipBits(headerSizeBits); // nuExtSSHeaderSize\n    const frameSize = bitstream.readBits(frameSizeBits) + 1;\n    // Everything past this point can run off the end of what we were given, in which case the Bitstream keeps\n    // handing out zeroes; the bounds check further down catches that\n    const incomplete = { frameSize, asset: null };\n    if (!bitstream.readBits(1)) { // bStaticFieldsPresent\n        return incomplete;\n    }\n    const refClock = DTS_EXSS_REF_CLOCKS[bitstream.readBits(2)]; // nuRefClockCode\n    // The frame duration is a count of reference clock cycles, not of samples\n    const frameDurationCycles = 512 * (bitstream.readBits(3) + 1); // nuExSSFrameDurationCode\n    if (bitstream.readBits(1)) { // bTimeStampFlag\n        bitstream.skipBits(32 + 4); // nuTimeStamp, nLSB\n    }\n    const numAudioPresentations = bitstream.readBits(3) + 1;\n    const numAssets = bitstream.readBits(3) + 1;\n    const activeExssMasks = [];\n    for (let i = 0; i < numAudioPresentations; i++) {\n        activeExssMasks.push(bitstream.readBits(extSsIndex + 1));\n    }\n    for (const mask of activeExssMasks) {\n        bitstream.skipBits(8 * popcount(mask)); // nuActiveAssetMask\n    }\n    if (bitstream.readBits(1)) { // bMixMetadataEnbl\n        bitstream.skipBits(2); // nuMixMetadataAdjLevel\n        const spkrMaskBits = (bitstream.readBits(2) + 1) << 2;\n        const numMixOutConfigs = bitstream.readBits(2) + 1;\n        bitstream.skipBits(numMixOutConfigs * spkrMaskBits); // nuMixOutChMask\n    }\n    for (let i = 0; i < numAssets; i++) {\n        bitstream.skipBits(frameSizeBits); // nuAssetFsize\n    }\n    // From here on we're inside the first audio asset descriptor\n    bitstream.skipBits(9); // nuAssetDescriptFsize\n    bitstream.skipBits(3); // nuAssetIndex\n    if (bitstream.readBits(1)) { // bAssetTypeDescrPresent\n        bitstream.skipBits(4); // nuAssetTypeDescriptor\n    }\n    if (bitstream.readBits(1)) { // bLanguageDescrPresent\n        bitstream.skipBits(24); // LanguageDescriptor\n    }\n    if (bitstream.readBits(1)) { // bInfoTextPresent\n        bitstream.skipBits(8 * (bitstream.readBits(10) + 1)); // nuInfoTextByteSize, InfoTextString\n    }\n    const pcmResolution = bitstream.readBits(5) + 1;\n    const sampleRate = DTS_EXSS_SAMPLE_RATES[bitstream.readBits(4)];\n    const numberOfChannels = bitstream.readBits(8) + 1;\n    let channelLayout = 0;\n    if (bitstream.readBits(1)) { // bOne2OneMapChannels2Speakers\n        if (numberOfChannels > 2) {\n            bitstream.skipBits(1); // bEmbeddedStereoFlag\n        }\n        if (numberOfChannels > 6) {\n            bitstream.skipBits(1); // bEmbeddedSixChFlag\n        }\n        if (bitstream.readBits(1)) { // bSpkrMaskEnabled\n            const spkrMaskBits = (bitstream.readBits(2) + 1) << 2;\n            channelLayout = bitstream.readBits(spkrMaskBits); // nuSpkrActivityMask\n        }\n    }\n    if (refClock === 0 || bitstream.getBitsLeft() < 0) {\n        return incomplete;\n    }\n    return {\n        frameSize,\n        asset: {\n            sampleRate,\n            numberOfChannels,\n            sampleCount: Math.round(frameDurationCycles * sampleRate / refClock),\n            channelLayout,\n            pcmResolution,\n        },\n    };\n};\n/** Parse a DTSSpecificBox (ddts). */\nexport const parseDtsSpecificBox = (data) => {\n    if (data.length < DTS_SPECIFIC_BOX_SIZE) {\n        return null;\n    }\n    const view = toDataView(data);\n    const sampleRate = view.getUint32(0);\n    if (sampleRate === 0) {\n        return null;\n    }\n    const bitstream = new Bitstream(data);\n    bitstream.seekToByte(13);\n    const frameDuration = bitstream.readBits(2);\n    bitstream.skipBits(5); // StreamConstruction\n    const coreLfePresent = bitstream.readBits(1);\n    const coreLayout = bitstream.readBits(6);\n    bitstream.skipBits(14); // CoreSize\n    bitstream.skipBits(1); // StereoDownmix\n    bitstream.skipBits(3); // RepresentationType\n    const channelLayout = bitstream.readBits(16);\n    let numberOfChannels = null;\n    if (channelLayout !== 0) {\n        numberOfChannels = getDtsChannelCount(channelLayout);\n    }\n    else if (coreLayout < DTS_AMODE_CHANNEL_COUNTS.length) {\n        numberOfChannels = DTS_AMODE_CHANNEL_COUNTS[coreLayout] + coreLfePresent;\n    }\n    return {\n        sampleRate,\n        maxBitrate: view.getUint32(4),\n        avgBitrate: view.getUint32(8),\n        pcmSampleDepth: data[12],\n        sampleCount: DTS_SPECIFIC_BOX_FRAME_DURATIONS[frameDuration],\n        channelLayout,\n        numberOfChannels,\n    };\n};\n/** Build the payload of a DTSSpecificBox (ddts) from a frame of the stream it describes. */\nexport const buildDtsSpecificBox = (frameInfo) => {\n    const bytes = new Uint8Array(DTS_SPECIFIC_BOX_SIZE);\n    const view = toDataView(bytes);\n    view.setUint32(0, frameInfo.sampleRate);\n    view.setUint32(4, frameInfo.bitRate);\n    view.setUint32(8, frameInfo.bitRate);\n    bytes[12] = frameInfo.pcmResolution;\n    // The spec only defines codes for streams built out of a known set of substreams. Anything else is required\n    // to be signaled as 0, meaning the construction is left unspecified.\n    const streamConstruction = frameInfo.core && !frameInfo.hasExtensions ? 1 : 0;\n    const bitstream = new Bitstream(bytes);\n    bitstream.seekToByte(13);\n    bitstream.writeBits(2, Math.max(DTS_SPECIFIC_BOX_FRAME_DURATIONS.indexOf(frameInfo.sampleCount), 0));\n    bitstream.writeBits(5, streamConstruction);\n    bitstream.writeBits(1, frameInfo.core?.lfePresent ? 1 : 0);\n    bitstream.writeBits(6, frameInfo.core?.amode ?? 0);\n    bitstream.writeBits(14, frameInfo.core ? frameInfo.core.frameSize - 1 : 0);\n    bitstream.writeBits(1, 0); // StereoDownmix\n    bitstream.writeBits(3, 0); // RepresentationType\n    bitstream.writeBits(16, frameInfo.channelLayout);\n    bitstream.writeBits(1, 0); // MultiAssetFlag\n    bitstream.writeBits(1, 0); // LBRDurationMod\n    bitstream.writeBits(1, 0); // ReservedBoxPresent\n    bitstream.writeBits(5, 0); // Reserved\n    return bytes;\n};\n/** Count the channels in a DTS speaker layout mask, where some bits stand for a pair of speakers. */\nconst getDtsChannelCount = (channelLayout) => {\n    return popcount(channelLayout) + popcount(channelLayout & DTS_CHANNEL_LAYOUT_PAIR_MASK);\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { parseAacAudioSpecificConfig } from '../shared/aac-misc.js';\nimport { av1CodecInfoHasColorInfo, deserializeAvcDecoderConfigurationRecord, deserializeHevcDecoderConfigurationRecord, HevcNalUnitType, parseAvcSps, parseHevcSps, } from './codec-data.js';\nimport { COLOR_PRIMARIES_MAP, COLOR_PRIMARIES_MAP_INVERSE, MATRIX_COEFFICIENTS_MAP, MATRIX_COEFFICIENTS_MAP_INVERSE, TRANSFER_CHARACTERISTICS_MAP, TRANSFER_CHARACTERISTICS_MAP_INVERSE, assert, assertNever, base64ToBytes, bytesToHexString, isAllowSharedBufferSource, last, reverseBitsU32, toDataView, } from './misc.js';\n/**\n * List of known video codecs, ordered by encoding preference.\n * @group Codecs\n * @public\n */\nexport const VIDEO_CODECS = [\n    'avc',\n    'hevc',\n    'vp9',\n    'av1',\n    'vp8',\n    'prores',\n];\n/**\n * List of known PCM (uncompressed) audio codecs, ordered by encoding preference.\n * @group Codecs\n * @public\n */\nexport const PCM_AUDIO_CODECS = [\n    'pcm-s16', // We don't prefix 'le' so we're compatible with the WebCodecs-registered PCM codec strings\n    'pcm-s16be',\n    'pcm-s24',\n    'pcm-s24be',\n    'pcm-s32',\n    'pcm-s32be',\n    'pcm-f32',\n    'pcm-f32be',\n    'pcm-f64',\n    'pcm-f64be',\n    'pcm-u8',\n    'pcm-s8',\n    'ulaw',\n    'alaw',\n];\n/**\n * List of known compressed audio codecs, ordered by encoding preference.\n * @group Codecs\n * @public\n */\nexport const NON_PCM_AUDIO_CODECS = [\n    'aac',\n    'opus',\n    'mp3',\n    'vorbis',\n    'flac',\n    'ac3',\n    'eac3',\n    'dts',\n];\n/**\n * List of known audio codecs, ordered by encoding preference.\n * @group Codecs\n * @public\n */\nexport const AUDIO_CODECS = [\n    ...NON_PCM_AUDIO_CODECS,\n    ...PCM_AUDIO_CODECS,\n];\n/**\n * List of known subtitle codecs, ordered by encoding preference.\n * @group Codecs\n * @public\n */\nexport const SUBTITLE_CODECS = [\n    'webvtt',\n]; // TODO add the rest\n// https://en.wikipedia.org/wiki/Advanced_Video_Coding\nexport const AVC_LEVEL_TABLE = [\n    { maxMacroblocks: 99, maxBitrate: 64000, maxDpbMbs: 396, level: 0x0A }, // Level 1\n    { maxMacroblocks: 396, maxBitrate: 192000, maxDpbMbs: 900, level: 0x0B }, // Level 1.1\n    { maxMacroblocks: 396, maxBitrate: 384000, maxDpbMbs: 2376, level: 0x0C }, // Level 1.2\n    { maxMacroblocks: 396, maxBitrate: 768000, maxDpbMbs: 2376, level: 0x0D }, // Level 1.3\n    { maxMacroblocks: 396, maxBitrate: 2000000, maxDpbMbs: 2376, level: 0x14 }, // Level 2\n    { maxMacroblocks: 792, maxBitrate: 4000000, maxDpbMbs: 4752, level: 0x15 }, // Level 2.1\n    { maxMacroblocks: 1620, maxBitrate: 4000000, maxDpbMbs: 8100, level: 0x16 }, // Level 2.2\n    { maxMacroblocks: 1620, maxBitrate: 10000000, maxDpbMbs: 8100, level: 0x1E }, // Level 3\n    { maxMacroblocks: 3600, maxBitrate: 14000000, maxDpbMbs: 18000, level: 0x1F }, // Level 3.1\n    { maxMacroblocks: 5120, maxBitrate: 20000000, maxDpbMbs: 20480, level: 0x20 }, // Level 3.2\n    { maxMacroblocks: 8192, maxBitrate: 20000000, maxDpbMbs: 32768, level: 0x28 }, // Level 4\n    { maxMacroblocks: 8192, maxBitrate: 50000000, maxDpbMbs: 32768, level: 0x29 }, // Level 4.1\n    { maxMacroblocks: 8704, maxBitrate: 50000000, maxDpbMbs: 34816, level: 0x2A }, // Level 4.2\n    { maxMacroblocks: 22080, maxBitrate: 135000000, maxDpbMbs: 110400, level: 0x32 }, // Level 5\n    { maxMacroblocks: 36864, maxBitrate: 240000000, maxDpbMbs: 184320, level: 0x33 }, // Level 5.1\n    { maxMacroblocks: 36864, maxBitrate: 240000000, maxDpbMbs: 184320, level: 0x34 }, // Level 5.2\n    { maxMacroblocks: 139264, maxBitrate: 240000000, maxDpbMbs: 696320, level: 0x3C }, // Level 6\n    { maxMacroblocks: 139264, maxBitrate: 480000000, maxDpbMbs: 696320, level: 0x3D }, // Level 6.1\n    { maxMacroblocks: 139264, maxBitrate: 800000000, maxDpbMbs: 696320, level: 0x3E }, // Level 6.2\n];\n// https://en.wikipedia.org/wiki/High_Efficiency_Video_Coding\nconst HEVC_LEVEL_TABLE = [\n    { maxPictureSize: 36864, maxBitrate: 128000, tier: 'L', level: 30 }, // Level 1 (Low Tier)\n    { maxPictureSize: 122880, maxBitrate: 1500000, tier: 'L', level: 60 }, // Level 2 (Low Tier)\n    { maxPictureSize: 245760, maxBitrate: 3000000, tier: 'L', level: 63 }, // Level 2.1 (Low Tier)\n    { maxPictureSize: 552960, maxBitrate: 6000000, tier: 'L', level: 90 }, // Level 3 (Low Tier)\n    { maxPictureSize: 983040, maxBitrate: 10000000, tier: 'L', level: 93 }, // Level 3.1 (Low Tier)\n    { maxPictureSize: 2228224, maxBitrate: 12000000, tier: 'L', level: 120 }, // Level 4 (Low Tier)\n    { maxPictureSize: 2228224, maxBitrate: 30000000, tier: 'H', level: 120 }, // Level 4 (High Tier)\n    { maxPictureSize: 2228224, maxBitrate: 20000000, tier: 'L', level: 123 }, // Level 4.1 (Low Tier)\n    { maxPictureSize: 2228224, maxBitrate: 50000000, tier: 'H', level: 123 }, // Level 4.1 (High Tier)\n    { maxPictureSize: 8912896, maxBitrate: 25000000, tier: 'L', level: 150 }, // Level 5 (Low Tier)\n    { maxPictureSize: 8912896, maxBitrate: 100000000, tier: 'H', level: 150 }, // Level 5 (High Tier)\n    { maxPictureSize: 8912896, maxBitrate: 40000000, tier: 'L', level: 153 }, // Level 5.1 (Low Tier)\n    { maxPictureSize: 8912896, maxBitrate: 160000000, tier: 'H', level: 153 }, // Level 5.1 (High Tier)\n    { maxPictureSize: 8912896, maxBitrate: 60000000, tier: 'L', level: 156 }, // Level 5.2 (Low Tier)\n    { maxPictureSize: 8912896, maxBitrate: 240000000, tier: 'H', level: 156 }, // Level 5.2 (High Tier)\n    { maxPictureSize: 35651584, maxBitrate: 60000000, tier: 'L', level: 180 }, // Level 6 (Low Tier)\n    { maxPictureSize: 35651584, maxBitrate: 240000000, tier: 'H', level: 180 }, // Level 6 (High Tier)\n    { maxPictureSize: 35651584, maxBitrate: 120000000, tier: 'L', level: 183 }, // Level 6.1 (Low Tier)\n    { maxPictureSize: 35651584, maxBitrate: 480000000, tier: 'H', level: 183 }, // Level 6.1 (High Tier)\n    { maxPictureSize: 35651584, maxBitrate: 240000000, tier: 'L', level: 186 }, // Level 6.2 (Low Tier)\n    { maxPictureSize: 35651584, maxBitrate: 800000000, tier: 'H', level: 186 }, // Level 6.2 (High Tier)\n];\n// https://en.wikipedia.org/wiki/VP9\nexport const VP9_LEVEL_TABLE = [\n    { maxPictureSize: 36864, maxBitrate: 200000, level: 10 }, // Level 1\n    { maxPictureSize: 73728, maxBitrate: 800000, level: 11 }, // Level 1.1\n    { maxPictureSize: 122880, maxBitrate: 1800000, level: 20 }, // Level 2\n    { maxPictureSize: 245760, maxBitrate: 3600000, level: 21 }, // Level 2.1\n    { maxPictureSize: 552960, maxBitrate: 7200000, level: 30 }, // Level 3\n    { maxPictureSize: 983040, maxBitrate: 12000000, level: 31 }, // Level 3.1\n    { maxPictureSize: 2228224, maxBitrate: 18000000, level: 40 }, // Level 4\n    { maxPictureSize: 2228224, maxBitrate: 30000000, level: 41 }, // Level 4.1\n    { maxPictureSize: 8912896, maxBitrate: 60000000, level: 50 }, // Level 5\n    { maxPictureSize: 8912896, maxBitrate: 120000000, level: 51 }, // Level 5.1\n    { maxPictureSize: 8912896, maxBitrate: 180000000, level: 52 }, // Level 5.2\n    { maxPictureSize: 35651584, maxBitrate: 180000000, level: 60 }, // Level 6\n    { maxPictureSize: 35651584, maxBitrate: 240000000, level: 61 }, // Level 6.1\n    { maxPictureSize: 35651584, maxBitrate: 480000000, level: 62 }, // Level 6.2\n];\n// https://en.wikipedia.org/wiki/AV1\nconst AV1_LEVEL_TABLE = [\n    { maxPictureSize: 147456, maxBitrate: 1500000, tier: 'M', level: 0 }, // Level 2.0 (Main Tier)\n    { maxPictureSize: 278784, maxBitrate: 3000000, tier: 'M', level: 1 }, // Level 2.1 (Main Tier)\n    { maxPictureSize: 665856, maxBitrate: 6000000, tier: 'M', level: 4 }, // Level 3.0 (Main Tier)\n    { maxPictureSize: 1065024, maxBitrate: 10000000, tier: 'M', level: 5 }, // Level 3.1 (Main Tier)\n    { maxPictureSize: 2359296, maxBitrate: 12000000, tier: 'M', level: 8 }, // Level 4.0 (Main Tier)\n    { maxPictureSize: 2359296, maxBitrate: 30000000, tier: 'H', level: 8 }, // Level 4.0 (High Tier)\n    { maxPictureSize: 2359296, maxBitrate: 20000000, tier: 'M', level: 9 }, // Level 4.1 (Main Tier)\n    { maxPictureSize: 2359296, maxBitrate: 50000000, tier: 'H', level: 9 }, // Level 4.1 (High Tier)\n    { maxPictureSize: 8912896, maxBitrate: 30000000, tier: 'M', level: 12 }, // Level 5.0 (Main Tier)\n    { maxPictureSize: 8912896, maxBitrate: 100000000, tier: 'H', level: 12 }, // Level 5.0 (High Tier)\n    { maxPictureSize: 8912896, maxBitrate: 40000000, tier: 'M', level: 13 }, // Level 5.1 (Main Tier)\n    { maxPictureSize: 8912896, maxBitrate: 160000000, tier: 'H', level: 13 }, // Level 5.1 (High Tier)\n    { maxPictureSize: 8912896, maxBitrate: 60000000, tier: 'M', level: 14 }, // Level 5.2 (Main Tier)\n    { maxPictureSize: 8912896, maxBitrate: 240000000, tier: 'H', level: 14 }, // Level 5.2 (High Tier)\n    { maxPictureSize: 35651584, maxBitrate: 60000000, tier: 'M', level: 15 }, // Level 5.3 (Main Tier)\n    { maxPictureSize: 35651584, maxBitrate: 240000000, tier: 'H', level: 15 }, // Level 5.3 (High Tier)\n    { maxPictureSize: 35651584, maxBitrate: 60000000, tier: 'M', level: 16 }, // Level 6.0 (Main Tier)\n    { maxPictureSize: 35651584, maxBitrate: 240000000, tier: 'H', level: 16 }, // Level 6.0 (High Tier)\n    { maxPictureSize: 35651584, maxBitrate: 100000000, tier: 'M', level: 17 }, // Level 6.1 (Main Tier)\n    { maxPictureSize: 35651584, maxBitrate: 480000000, tier: 'H', level: 17 }, // Level 6.1 (High Tier)\n    { maxPictureSize: 35651584, maxBitrate: 160000000, tier: 'M', level: 18 }, // Level 6.2 (Main Tier)\n    { maxPictureSize: 35651584, maxBitrate: 800000000, tier: 'H', level: 18 }, // Level 6.2 (High Tier)\n    { maxPictureSize: 35651584, maxBitrate: 160000000, tier: 'M', level: 19 }, // Level 6.3 (Main Tier)\n    { maxPictureSize: 35651584, maxBitrate: 800000000, tier: 'H', level: 19 }, // Level 6.3 (High Tier)\n];\nconst VP9_DEFAULT_SUFFIX = '.01.01.01.01.00';\nconst AV1_DEFAULT_SUFFIX = '.0.110.01.01.01.0';\nexport const PRORES_FOURCCS = [\n    'ap4x', // ProRes 4444 XQ\n    'ap4h', // ProRes 4444\n    'apch', // ProRes 422 High Quality\n    'apcn', // ProRes 422 Standard Definition\n    'apcs', // ProRes 422 LT\n    'apco', // ProRes 422 Proxy\n];\nexport const DTS_FOURCCS = [\n    'dtsc', // DTS core\n    'dtsh', // DTS-HD, core plus extension substreams\n    'dtsl', // DTS-HD Lossless, no core\n    'dtse', // DTS Express\n];\n// Target data rates of the ProRes profiles at 1920x1080 ~30fps, as published by Apple\nconst PRORES_PROFILE_TARGET_BITRATES = [\n    { fourCc: 'apco', bitrate: 45_000_000, alpha: false }, // 422 Proxy\n    { fourCc: 'apcs', bitrate: 102_000_000, alpha: false }, // 422 LT\n    { fourCc: 'apcn', bitrate: 147_000_000, alpha: false }, // 422 Standard\n    { fourCc: 'apch', bitrate: 220_000_000, alpha: false }, // 422 HQ\n    { fourCc: 'ap4h', bitrate: 330_000_000, alpha: true }, // 4444\n    { fourCc: 'ap4x', bitrate: 500_000_000, alpha: true }, // 4444 XQ\n];\nexport const buildVideoCodecString = (codec, width, height, bitrate, alpha) => {\n    if (codec === 'avc') {\n        const profileIndication = 0x64; // High Profile\n        const totalMacroblocks = Math.ceil(width / 16) * Math.ceil(height / 16);\n        // Determine the level based on the table\n        const levelInfo = AVC_LEVEL_TABLE.find(level => totalMacroblocks <= level.maxMacroblocks && bitrate <= level.maxBitrate) ?? last(AVC_LEVEL_TABLE);\n        const levelIndication = levelInfo ? levelInfo.level : 0;\n        const hexProfileIndication = profileIndication.toString(16).padStart(2, '0');\n        const hexProfileCompatibility = '00';\n        const hexLevelIndication = levelIndication.toString(16).padStart(2, '0');\n        return `avc1.${hexProfileIndication}${hexProfileCompatibility}${hexLevelIndication}`;\n    }\n    else if (codec === 'hevc') {\n        const profilePrefix = ''; // Profile space 0\n        const profileIdc = 1; // Main Profile\n        const compatibilityFlags = '6'; // Taken from the example in ISO 14496-15\n        const pictureSize = width * height;\n        const levelInfo = HEVC_LEVEL_TABLE.find(level => pictureSize <= level.maxPictureSize && bitrate <= level.maxBitrate) ?? last(HEVC_LEVEL_TABLE);\n        const constraintFlags = 'B0'; // Progressive source flag\n        return 'hev1.'\n            + `${profilePrefix}${profileIdc}.`\n            + `${compatibilityFlags}.`\n            + `${levelInfo.tier}${levelInfo.level}.`\n            + `${constraintFlags}`;\n    }\n    else if (codec === 'vp8') {\n        return 'vp8'; // Easy, this one\n    }\n    else if (codec === 'vp9') {\n        const profile = '00'; // Profile 0\n        const pictureSize = width * height;\n        const levelInfo = VP9_LEVEL_TABLE.find(level => pictureSize <= level.maxPictureSize && bitrate <= level.maxBitrate) ?? last(VP9_LEVEL_TABLE);\n        const bitDepth = '08'; // 8-bit\n        return `vp09.${profile}.${levelInfo.level.toString().padStart(2, '0')}.${bitDepth}`;\n    }\n    else if (codec === 'av1') {\n        const profile = 0; // Main Profile, single digit\n        const pictureSize = width * height;\n        const levelInfo = AV1_LEVEL_TABLE.find(level => pictureSize <= level.maxPictureSize && bitrate <= level.maxBitrate) ?? last(AV1_LEVEL_TABLE);\n        const level = levelInfo.level.toString().padStart(2, '0');\n        const bitDepth = '08'; // 8-bit\n        return `av01.${profile}.${level}${levelInfo.tier}.${bitDepth}`;\n    }\n    else if (codec === 'prores') {\n        const referencePixels = 1920 * 1080;\n        const scaleFactor = Math.pow((width * height) / referencePixels, 0.95);\n        const candidates = PRORES_PROFILE_TARGET_BITRATES.filter(x => x.alpha === alpha);\n        let bestFourCc = candidates[0].fourCc;\n        let smallestDifference = Infinity;\n        for (const { fourCc, bitrate: targetBitrate } of candidates) {\n            const difference = Math.abs(targetBitrate * scaleFactor - bitrate);\n            if (difference < smallestDifference) {\n                smallestDifference = difference;\n                bestFourCc = fourCc;\n            }\n        }\n        return bestFourCc;\n    }\n    else {\n        assertNever(codec);\n    }\n    throw new TypeError(`Unhandled codec '${String(codec)}'.`);\n};\nexport const generateVp9CodecConfigurationFromCodecString = (codecString) => {\n    // Reference: https://www.webmproject.org/docs/container/#vp9-codec-feature-metadata-codecprivate\n    const parts = codecString.split('.'); // We can derive the required values from the codec string\n    const profile = Number(parts[1]);\n    const level = Number(parts[2]);\n    const bitDepth = Number(parts[3]);\n    const chromaSubsampling = parts[4] ? Number(parts[4]) : 1;\n    return [\n        1, 1, profile,\n        2, 1, level,\n        3, 1, bitDepth,\n        4, 1, chromaSubsampling,\n    ];\n};\nexport const generateAv1CodecConfigurationFromCodecString = (codecString) => {\n    // Reference: https://aomediacodec.github.io/av1-isobmff/\n    const parts = codecString.split('.'); // We can derive the required values from the codec string\n    const marker = 1;\n    const version = 1;\n    const firstByte = (marker << 7) + version;\n    const profile = Number(parts[1]);\n    const levelAndTier = parts[2];\n    const level = Number(levelAndTier.slice(0, -1));\n    const secondByte = (profile << 5) + level;\n    const tier = levelAndTier.slice(-1) === 'H' ? 1 : 0;\n    const bitDepth = Number(parts[3]);\n    const highBitDepth = bitDepth === 8 ? 0 : 1;\n    const twelveBit = bitDepth === 12 ? 1 : 0;\n    const monochrome = parts[4] ? Number(parts[4]) : 0;\n    const chromaSubsamplingX = parts[5] ? Number(parts[5][0]) : 1;\n    const chromaSubsamplingY = parts[5] ? Number(parts[5][1]) : 1;\n    const chromaSamplePosition = parts[5] ? Number(parts[5][2]) : 0; // CSP_UNKNOWN\n    const thirdByte = (tier << 7)\n        + (highBitDepth << 6)\n        + (twelveBit << 5)\n        + (monochrome << 4)\n        + (chromaSubsamplingX << 3)\n        + (chromaSubsamplingY << 2)\n        + chromaSamplePosition;\n    const initialPresentationDelayPresent = 0; // Should be fine\n    const fourthByte = initialPresentationDelayPresent;\n    return [firstByte, secondByte, thirdByte, fourthByte];\n};\nexport const extractVideoCodecString = (trackInfo) => {\n    const { codec, codecDescription, colorSpace, avcCodecInfo, hevcCodecInfo, vp9CodecInfo, av1CodecInfo, proresFormat, } = trackInfo;\n    if (codec === 'avc') {\n        assert(trackInfo.avcType !== null);\n        if (avcCodecInfo) {\n            const bytes = new Uint8Array([\n                avcCodecInfo.avcProfileIndication,\n                avcCodecInfo.profileCompatibility,\n                avcCodecInfo.avcLevelIndication,\n            ]);\n            return `avc${trackInfo.avcType}.${bytesToHexString(bytes)}`;\n        }\n        if (!codecDescription || codecDescription.byteLength < 4) {\n            throw new TypeError('AVC decoder description is not provided or is not at least 4 bytes long.');\n        }\n        return `avc${trackInfo.avcType}.${bytesToHexString(codecDescription.subarray(1, 4))}`;\n    }\n    else if (codec === 'hevc') {\n        let generalProfileSpace;\n        let generalProfileIdc;\n        let compatibilityFlags;\n        let generalTierFlag;\n        let generalLevelIdc;\n        let constraintFlags;\n        if (hevcCodecInfo) {\n            generalProfileSpace = hevcCodecInfo.generalProfileSpace;\n            generalProfileIdc = hevcCodecInfo.generalProfileIdc;\n            compatibilityFlags = reverseBitsU32(hevcCodecInfo.generalProfileCompatibilityFlags);\n            generalTierFlag = hevcCodecInfo.generalTierFlag;\n            generalLevelIdc = hevcCodecInfo.generalLevelIdc;\n            constraintFlags = [...hevcCodecInfo.generalConstraintIndicatorFlags];\n        }\n        else {\n            if (!codecDescription || codecDescription.byteLength < 23) {\n                throw new TypeError('HEVC decoder description is not provided or is not at least 23 bytes long.');\n            }\n            const view = toDataView(codecDescription);\n            const profileByte = view.getUint8(1);\n            generalProfileSpace = (profileByte >> 6) & 0x03;\n            generalProfileIdc = profileByte & 0x1F;\n            compatibilityFlags = reverseBitsU32(view.getUint32(2));\n            generalTierFlag = (profileByte >> 5) & 0x01;\n            generalLevelIdc = view.getUint8(12);\n            constraintFlags = [];\n            for (let i = 0; i < 6; i++) {\n                constraintFlags.push(view.getUint8(6 + i));\n            }\n        }\n        let codecString = 'hev1.';\n        codecString += ['', 'A', 'B', 'C'][generalProfileSpace] + generalProfileIdc;\n        codecString += '.';\n        codecString += compatibilityFlags.toString(16).toUpperCase();\n        codecString += '.';\n        codecString += generalTierFlag === 0 ? 'L' : 'H';\n        codecString += generalLevelIdc;\n        while (constraintFlags.length > 0 && constraintFlags[constraintFlags.length - 1] === 0) {\n            constraintFlags.pop();\n        }\n        if (constraintFlags.length > 0) {\n            codecString += '.';\n            codecString += constraintFlags.map(x => x.toString(16).toUpperCase()).join('.');\n        }\n        return codecString;\n    }\n    else if (codec === 'vp8') {\n        return 'vp8'; // Easy, this one\n    }\n    else if (codec === 'vp9') {\n        if (!vp9CodecInfo) {\n            // Calculate level based on dimensions\n            const pictureSize = trackInfo.width * trackInfo.height;\n            let level = last(VP9_LEVEL_TABLE).level; // Default to highest level\n            for (const entry of VP9_LEVEL_TABLE) {\n                if (pictureSize <= entry.maxPictureSize) {\n                    level = entry.level;\n                    break;\n                }\n            }\n            // We don't really know better, so let's return a general-purpose, common codec string and hope for the best\n            return `vp09.00.${level.toString().padStart(2, '0')}.08`;\n        }\n        const profile = vp9CodecInfo.profile.toString().padStart(2, '0');\n        const level = vp9CodecInfo.level.toString().padStart(2, '0');\n        const bitDepth = vp9CodecInfo.bitDepth.toString().padStart(2, '0');\n        const chromaSubsampling = vp9CodecInfo.chromaSubsampling.toString().padStart(2, '0');\n        const colourPrimaries = vp9CodecInfo.colourPrimaries.toString().padStart(2, '0');\n        const transferCharacteristics = vp9CodecInfo.transferCharacteristics.toString().padStart(2, '0');\n        const matrixCoefficients = vp9CodecInfo.matrixCoefficients.toString().padStart(2, '0');\n        const videoFullRangeFlag = vp9CodecInfo.videoFullRangeFlag.toString().padStart(2, '0');\n        let string = `vp09.${profile}.${level}.${bitDepth}.${chromaSubsampling}`;\n        string += `.${colourPrimaries}.${transferCharacteristics}.${matrixCoefficients}.${videoFullRangeFlag}`;\n        if (string.endsWith(VP9_DEFAULT_SUFFIX)) {\n            string = string.slice(0, -VP9_DEFAULT_SUFFIX.length);\n        }\n        return string;\n    }\n    else if (codec === 'av1') {\n        if (!av1CodecInfo) {\n            // Calculate level based on dimensions\n            const pictureSize = trackInfo.width * trackInfo.height;\n            let level = last(VP9_LEVEL_TABLE).level; // Default to highest level\n            for (const entry of VP9_LEVEL_TABLE) {\n                if (pictureSize <= entry.maxPictureSize) {\n                    level = entry.level;\n                    break;\n                }\n            }\n            // We don't really know better, so let's return a general-purpose, common codec string and hope for the best\n            return `av01.0.${level.toString().padStart(2, '0')}M.08`;\n        }\n        // https://aomediacodec.github.io/av1-isobmff/#codecsparam\n        const profile = av1CodecInfo.profile; // Single digit\n        const level = av1CodecInfo.level.toString().padStart(2, '0');\n        const tier = av1CodecInfo.tier ? 'H' : 'M';\n        const bitDepth = av1CodecInfo.bitDepth.toString().padStart(2, '0');\n        const monochrome = av1CodecInfo.monochrome ? '1' : '0';\n        const chromaSubsampling = 100 * av1CodecInfo.chromaSubsamplingX\n            + 10 * av1CodecInfo.chromaSubsamplingY\n            + 1 * (av1CodecInfo.chromaSubsamplingX && av1CodecInfo.chromaSubsamplingY\n                ? av1CodecInfo.chromaSamplePosition\n                : 0);\n        let colorPrimaries;\n        let transferCharacteristics;\n        let matrixCoefficients;\n        let videoFullRangeFlag;\n        if (av1CodecInfoHasColorInfo(av1CodecInfo)) {\n            colorPrimaries = av1CodecInfo.colourPrimaries;\n            transferCharacteristics = av1CodecInfo.transferCharacteristics;\n            matrixCoefficients = av1CodecInfo.matrixCoefficients;\n            videoFullRangeFlag = av1CodecInfo.videoFullRangeFlag;\n        }\n        else {\n            // The defaults are 1 (ITU-R BT.709)\n            colorPrimaries = colorSpace?.primaries ? COLOR_PRIMARIES_MAP[colorSpace.primaries] : 1;\n            transferCharacteristics = colorSpace?.transfer ? TRANSFER_CHARACTERISTICS_MAP[colorSpace.transfer] : 1;\n            matrixCoefficients = colorSpace?.matrix ? MATRIX_COEFFICIENTS_MAP[colorSpace.matrix] : 1;\n            videoFullRangeFlag = colorSpace?.fullRange ? 1 : 0;\n        }\n        let string = `av01.${profile}.${level}${tier}.${bitDepth}`;\n        string += `.${monochrome}.${chromaSubsampling.toString().padStart(3, '0')}`;\n        string += `.${colorPrimaries.toString().padStart(2, '0')}`;\n        string += `.${transferCharacteristics.toString().padStart(2, '0')}`;\n        string += `.${matrixCoefficients.toString().padStart(2, '0')}`;\n        string += `.${videoFullRangeFlag}`;\n        if (string.endsWith(AV1_DEFAULT_SUFFIX)) {\n            string = string.slice(0, -AV1_DEFAULT_SUFFIX.length);\n        }\n        return string;\n    }\n    else if (codec === 'prores') {\n        return proresFormat ?? 'apch';\n    }\n    else if (codec !== null) {\n        assertNever(codec);\n    }\n    throw new TypeError(`Unhandled codec '${codec}'.`);\n};\nexport const extractColorSpace = (info) => {\n    switch (info.codec) {\n        case 'avc':\n            {\n                let spsData = info.avcCodecInfo?.sequenceParameterSets[0];\n                if (!spsData && info.codecDescription) {\n                    spsData = deserializeAvcDecoderConfigurationRecord(info.codecDescription)?.sequenceParameterSets[0];\n                }\n                if (spsData) {\n                    const spsInfo = parseAvcSps(spsData);\n                    if (spsInfo) {\n                        return {\n                            primaries: COLOR_PRIMARIES_MAP_INVERSE[spsInfo.colourPrimaries],\n                            transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[spsInfo.transferCharacteristics],\n                            matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[spsInfo.matrixCoefficients],\n                            fullRange: !!spsInfo.fullRangeFlag,\n                        };\n                    }\n                }\n            }\n            ;\n            break;\n        case 'hevc':\n            {\n                let spsData = info.hevcCodecInfo?.arrays\n                    .find(x => x.nalUnitType === HevcNalUnitType.SPS_NUT)?.nalUnits[0];\n                if (!spsData && info.codecDescription) {\n                    spsData = deserializeHevcDecoderConfigurationRecord(info.codecDescription)?.arrays\n                        .find(x => x.nalUnitType === HevcNalUnitType.SPS_NUT)?.nalUnits[0];\n                }\n                if (spsData) {\n                    const spsInfo = parseHevcSps(spsData);\n                    if (spsInfo) {\n                        return {\n                            primaries: COLOR_PRIMARIES_MAP_INVERSE[spsInfo.colourPrimaries],\n                            transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[spsInfo.transferCharacteristics],\n                            matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[spsInfo.matrixCoefficients],\n                            fullRange: !!spsInfo.fullRangeFlag,\n                        };\n                    }\n                }\n            }\n            ;\n            break;\n        case 'vp8':\n            {\n                // The situation is fucky; do nothing for now.\n            }\n            ;\n            break;\n        case 'vp9':\n            {\n                if (info.vp9CodecInfo) {\n                    return {\n                        primaries: COLOR_PRIMARIES_MAP_INVERSE[info.vp9CodecInfo.colourPrimaries],\n                        transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[info.vp9CodecInfo.transferCharacteristics],\n                        matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[info.vp9CodecInfo.matrixCoefficients],\n                        fullRange: !!info.vp9CodecInfo.videoFullRangeFlag,\n                    };\n                }\n            }\n            ;\n            break;\n        case 'av1':\n            {\n                if (info.av1CodecInfo) {\n                    return {\n                        primaries: COLOR_PRIMARIES_MAP_INVERSE[info.av1CodecInfo.colourPrimaries],\n                        transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[info.av1CodecInfo.transferCharacteristics],\n                        matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[info.av1CodecInfo.matrixCoefficients],\n                        fullRange: !!info.av1CodecInfo.videoFullRangeFlag,\n                    };\n                }\n            }\n            ;\n            break;\n        case 'prores':\n            {\n                if (info.proresCodecInfo) {\n                    return {\n                        primaries: COLOR_PRIMARIES_MAP_INVERSE[info.proresCodecInfo.colourPrimaries],\n                        transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[info.proresCodecInfo.transferCharacteristics],\n                        matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[info.proresCodecInfo.matrixCoefficients],\n                        fullRange: info.proresCodecInfo.fullRange,\n                    };\n                }\n            }\n            ;\n            break;\n    }\n    return {\n        primaries: undefined,\n        transfer: undefined,\n        matrix: undefined,\n        fullRange: undefined,\n    };\n};\nexport const buildAudioCodecString = (codec, numberOfChannels, sampleRate) => {\n    if (codec === 'aac') {\n        // If stereo or higher channels and lower sample rate, likely using HE-AAC v2 with PS\n        if (numberOfChannels >= 2 && sampleRate <= 24000) {\n            return 'mp4a.40.29'; // HE-AAC v2 (AAC LC + SBR + PS)\n        }\n        // If sample rate is low, likely using HE-AAC v1 with SBR\n        if (sampleRate <= 24000) {\n            return 'mp4a.40.5'; // HE-AAC v1 (AAC LC + SBR)\n        }\n        // Default to standard AAC-LC for higher sample rates\n        return 'mp4a.40.2'; // AAC-LC\n    }\n    else if (codec === 'mp3') {\n        return 'mp3';\n    }\n    else if (codec === 'opus') {\n        return 'opus';\n    }\n    else if (codec === 'vorbis') {\n        return 'vorbis';\n    }\n    else if (codec === 'flac') {\n        return 'flac';\n    }\n    else if (codec === 'ac3') {\n        return 'ac-3';\n    }\n    else if (codec === 'eac3') {\n        return 'ec-3';\n    }\n    else if (codec === 'dts') {\n        return 'dtsc';\n    }\n    else if (PCM_AUDIO_CODECS.includes(codec)) {\n        return codec;\n    }\n    throw new TypeError(`Unhandled codec '${codec}'.`);\n};\nexport const extractAudioCodecString = (trackInfo) => {\n    const { codec, codecDescription, aacCodecInfo, dtsFormat } = trackInfo;\n    if (codec === 'aac') {\n        if (!aacCodecInfo) {\n            throw new TypeError('AAC codec info must be provided.');\n        }\n        if (aacCodecInfo.isMpeg2) {\n            return 'mp4a.67';\n        }\n        else {\n            let objectType;\n            if (aacCodecInfo.objectType !== null) {\n                objectType = aacCodecInfo.objectType;\n            }\n            else {\n                const audioSpecificConfig = parseAacAudioSpecificConfig(codecDescription);\n                objectType = audioSpecificConfig.objectType;\n            }\n            return `mp4a.40.${objectType}`;\n        }\n    }\n    else if (codec === 'mp3') {\n        return 'mp3';\n    }\n    else if (codec === 'opus') {\n        return 'opus';\n    }\n    else if (codec === 'vorbis') {\n        return 'vorbis';\n    }\n    else if (codec === 'flac') {\n        return 'flac';\n    }\n    else if (codec === 'ac3') {\n        return 'ac-3';\n    }\n    else if (codec === 'eac3') {\n        return 'ec-3';\n    }\n    else if (codec === 'dts') {\n        return dtsFormat ?? 'dtsc';\n    }\n    else if (codec && PCM_AUDIO_CODECS.includes(codec)) {\n        return codec;\n    }\n    throw new TypeError(`Unhandled codec '${codec}'.`);\n};\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport const guessDescriptionForVideo = (decoderConfig) => {\n    return undefined; // All codecs allow an undefined description\n};\nexport const guessDescriptionForAudio = (decoderConfig) => {\n    switch (decoderConfig.codec) {\n        case 'flac':\n            {\n                const referenceDescription = base64ToBytes('ZkxhQ4AAACIQABAAAAYtACWtCsRC8AANRBhVFucAcYu5ASE2m1Dxv8tw');\n                if (decoderConfig.sampleRate >= (1 << 20) || decoderConfig.numberOfChannels > 8) {\n                    return false;\n                }\n                referenceDescription[18] = decoderConfig.sampleRate >>> 12;\n                referenceDescription[19] = decoderConfig.sampleRate >>> 4;\n                referenceDescription[20]\n                    = ((decoderConfig.sampleRate & 0x0f) << 4) | ((decoderConfig.numberOfChannels - 1) << 1);\n                return referenceDescription;\n            }\n            ;\n        case 'vorbis':\n            {\n                // eslint-disable-next-line @stylistic/max-len\n                const referenceDescription = base64ToBytes('Ah7/AgF2b3JiaXMAAAAAAoC7AAAAAAAAgLUBAAAAAAC4AQN2b3JiaXMNAAAATGF2ZjU4Ljc2LjEwMAgAAAAMAAAAbGFuZ3VhZ2U9dW5kGQAAAGhhbmRsZXJfbmFtZT1Tb3VuZEhhbmRsZXIWAAAAdmVuZG9yX2lkPVswXVswXVswXVswXSAAAABlbmNvZGVyPUxhdmM1OC4xMzQuMTAwIGxpYnZvcmJpcxAAAABtYWpvcl9icmFuZD1pc29tEQAAAG1pbm9yX3ZlcnNpb249NTEyIgAAAGNvbXBhdGlibGVfYnJhbmRzPWlzb21pc28yYXZjMW1wNDEmAAAAREVTQ1JJUFRJT049TWFkZSB3aXRoIFJlbW90aW9uIDQuMC4yNzgBBXZvcmJpcyVCQ1YBAEAAACRzGCpGpXMWhBAaQlAZ4xxCzmvsGUJMEYIcMkxbyyVzkCGkoEKIWyiB0JBVAABAAACHQXgUhIpBCCGEJT1YkoMnPQghhIg5eBSEaUEIIYQQQgghhBBCCCGERTlokoMnQQgdhOMwOAyD5Tj4HIRFOVgQgydB6CCED0K4moOsOQghhCQ1SFCDBjnoHITCLCiKgsQwuBaEBDUojILkMMjUgwtCiJqDSTX4GoRnQXgWhGlBCCGEJEFIkIMGQcgYhEZBWJKDBjm4FITLQagahCo5CB+EIDRkFQCQAACgoiiKoigKEBqyCgDIAAAQQFEUx3EcyZEcybEcCwgNWQUAAAEACAA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yQFVV1XVdV5YBqqqqruu6sgxQVdd1XVmWZQCu67qyLMsCAAAOHAAAAoygk4wqi7DRhAsPQKEhKwKAKAAAwBimFFPKMCYhpBAaxiSEFEImJaXSUqogpFJSKRWEVEoqJaOUUmopVRBSKamUCkIqJZVSAADYgQMA2IGFUGjISgAgDwCAMEYpxhhzTiKkFGPOOScRUoox55yTSjHmnHPOSSkZc8w556SUzjnnnHNSSuacc845KaVzzjnnnJRSSuecc05KKSWEzkEnpZTSOeecEwAAVOAAABBgo8jmBCNBhYasBABSAQAMjmNZmuZ5omialiRpmud5niiapiZJmuZ5nieKqsnzPE8URdE0VZXneZ4oiqJpqirXFUXTNE1VVV2yLIqmaZqq6rowTdNUVdd1XZimaaqq67oubFtVVdV1ZRm2raqq6rqyDFzXdWXZloEsu67s2rIAAPAEBwCgAhtWRzgpGgssNGQlAJABAEAYg5BCCCFlEEIKIYSUUggJAAAYcAAACDChDBQashIASAUAAIyx1lprrbXWQGettdZaa62AzFprrbXWWmuttdZaa6211lJrrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmstpZRSSimllFJKKaWUUkoppZRSSgUA+lU4APg/2LA6wknRWGChISsBgHAAAMAYpRhzDEIppVQIMeacdFRai7FCiDHnJKTUWmzFc85BKCGV1mIsnnMOQikpxVZjUSmEUlJKLbZYi0qho5JSSq3VWIwxqaTWWoutxmKMSSm01FqLMRYjbE2ptdhqq7EYY2sqLbQYY4zFCF9kbC2m2moNxggjWywt1VprMMYY3VuLpbaaizE++NpSLDHWXAAAd4MDAESCjTOsJJ0VjgYXGrISAAgJACAQUooxxhhzzjnnpFKMOeaccw5CCKFUijHGnHMOQgghlIwx5pxzEEIIIYRSSsaccxBCCCGEkFLqnHMQQgghhBBKKZ1zDkIIIYQQQimlgxBCCCGEEEoopaQUQgghhBBCCKmklEIIIYRSQighlZRSCCGEEEIpJaSUUgohhFJCCKGElFJKKYUQQgillJJSSimlEkoJJYQSUikppRRKCCGUUkpKKaVUSgmhhBJKKSWllFJKIYQQSikFAAAcOAAABBhBJxlVFmGjCRcegEJDVgIAZAAAkKKUUiktRYIipRikGEtGFXNQWoqocgxSzalSziDmJJaIMYSUk1Qy5hRCDELqHHVMKQYtlRhCxhik2HJLoXMOAAAAQQCAgJAAAAMEBTMAwOAA4XMQdAIERxsAgCBEZohEw0JweFAJEBFTAUBigkIuAFRYXKRdXECXAS7o4q4DIQQhCEEsDqCABByccMMTb3jCDU7QKSp1IAAAAAAADADwAACQXAAREdHMYWRobHB0eHyAhIiMkAgAAAAAABcAfAAAJCVAREQ0cxgZGhscHR4fICEiIyQBAIAAAgAAAAAggAAEBAQAAAAAAAIAAAAEBA==');\n                const view = toDataView(referenceDescription);\n                view.setUint8(15, decoderConfig.numberOfChannels);\n                view.setUint32(16, decoderConfig.sampleRate, true);\n                return referenceDescription;\n            }\n            ;\n        default: return undefined; // All other codecs allow an undefined description\n    }\n};\nexport const OPUS_SAMPLE_RATE = 48_000;\nconst PCM_CODEC_REGEX = /^pcm-([usf])(\\d+)(be)?$/;\nexport const parsePcmCodec = (codec) => {\n    assert(PCM_AUDIO_CODECS.includes(codec));\n    if (codec === 'ulaw') {\n        return { dataType: 'ulaw', sampleSize: 1, littleEndian: true, silentValue: 255 };\n    }\n    else if (codec === 'alaw') {\n        return { dataType: 'alaw', sampleSize: 1, littleEndian: true, silentValue: 213 };\n    }\n    const match = PCM_CODEC_REGEX.exec(codec);\n    assert(match);\n    let dataType;\n    if (match[1] === 'u') {\n        dataType = 'unsigned';\n    }\n    else if (match[1] === 's') {\n        dataType = 'signed';\n    }\n    else {\n        dataType = 'float';\n    }\n    const sampleSize = (Number(match[2]) / 8);\n    const littleEndian = match[3] !== 'be';\n    const silentValue = codec === 'pcm-u8' ? 2 ** 7 : 0;\n    return { dataType, sampleSize, littleEndian, silentValue };\n};\nexport const inferCodecFromCodecString = (codecString) => {\n    // Video codecs\n    if (codecString.startsWith('avc1') || codecString.startsWith('avc3')) {\n        return 'avc';\n    }\n    else if (codecString.startsWith('hev1') || codecString.startsWith('hvc1')) {\n        return 'hevc';\n    }\n    else if (codecString === 'vp8') {\n        return 'vp8';\n    }\n    else if (codecString.startsWith('vp09')) {\n        return 'vp9';\n    }\n    else if (codecString.startsWith('av01')) {\n        return 'av1';\n    }\n    else if (PRORES_FOURCCS.includes(codecString)) {\n        return 'prores';\n    }\n    // Audio codecs\n    if (codecString === 'mp3'\n        || codecString === 'mp4a.69'\n        || codecString === 'mp4a.6B'\n        || codecString === 'mp4a.6b'\n        || codecString === 'mp4a.40.34') {\n        return 'mp3';\n    }\n    else if (codecString.startsWith('mp4a.40.') || codecString === 'mp4a.67') {\n        return 'aac';\n    }\n    else if (codecString === 'opus' || codecString === 'Opus' /* HLS variant */) {\n        return 'opus';\n    }\n    else if (codecString === 'vorbis') {\n        return 'vorbis';\n    }\n    else if (codecString === 'flac') {\n        return 'flac';\n    }\n    else if (codecString === 'ac-3' || codecString === 'ac3') {\n        return 'ac3';\n    }\n    else if (codecString === 'ec-3' || codecString === 'eac3') {\n        return 'eac3';\n    }\n    else if (DTS_FOURCCS.includes(codecString)) {\n        return 'dts';\n    }\n    else if (codecString === 'ulaw') {\n        return 'ulaw';\n    }\n    else if (codecString === 'alaw') {\n        return 'alaw';\n    }\n    else if (PCM_CODEC_REGEX.test(codecString)) {\n        return codecString;\n    }\n    // Subtitle codecs\n    if (codecString === 'webvtt') {\n        return 'webvtt';\n    }\n    return null;\n};\nexport const getVideoEncoderConfigExtension = (codec) => {\n    if (codec === 'avc') {\n        return {\n            avc: {\n                format: 'avc', // Ensure the format is not Annex B\n            },\n        };\n    }\n    else if (codec === 'hevc') {\n        return {\n            hevc: {\n                format: 'hevc', // Ensure the format is not Annex B\n            },\n        };\n    }\n    return {};\n};\nexport const getAudioEncoderConfigExtension = (codec) => {\n    if (codec === 'aac') {\n        return {\n            aac: {\n                format: 'aac', // Ensure the format is not ADTS\n            },\n        };\n    }\n    else if (codec === 'opus') {\n        return {\n            opus: {\n                format: 'opus',\n            },\n        };\n    }\n    return {};\n};\nconst VALID_VIDEO_CODEC_STRING_PREFIXES = ['avc1', 'avc3', 'hev1', 'hvc1', 'vp8', 'vp09', 'av01', ...PRORES_FOURCCS];\nconst AVC_CODEC_STRING_REGEX = /^(avc1|avc3)\\.[0-9a-fA-F]{6}$/;\nconst HEVC_CODEC_STRING_REGEX = /^(hev1|hvc1)\\.(?:[ABC]?\\d+)\\.[0-9a-fA-F]{1,8}\\.[LH]\\d+(?:\\.[0-9a-fA-F]{1,2}){0,6}$/;\nconst VP9_CODEC_STRING_REGEX = /^vp09(?:\\.\\d{2}){3}(?:(?:\\.\\d{2}){5})?$/;\nconst AV1_CODEC_STRING_REGEX = /^av01\\.\\d\\.\\d{2}[MH]\\.\\d{2}(?:\\.\\d\\.\\d{3}\\.\\d{2}\\.\\d{2}\\.\\d{2}\\.\\d)?$/;\nexport const validateVideoChunkMetadata = (metadata, trackCodec) => {\n    if (!metadata) {\n        throw new TypeError('Video chunk metadata must be provided.');\n    }\n    if (typeof metadata !== 'object') {\n        throw new TypeError('Video chunk metadata must be an object.');\n    }\n    if (!metadata.decoderConfig) {\n        throw new TypeError('Video chunk metadata must include a decoder configuration.');\n    }\n    if (typeof metadata.decoderConfig !== 'object') {\n        throw new TypeError('Video chunk metadata decoder configuration must be an object.');\n    }\n    if (typeof metadata.decoderConfig.codec !== 'string') {\n        throw new TypeError('Video chunk metadata decoder configuration must specify a codec string.');\n    }\n    if (!VALID_VIDEO_CODEC_STRING_PREFIXES.some(prefix => metadata.decoderConfig.codec.startsWith(prefix))) {\n        throw new TypeError('Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in'\n            + ' the Mediabunny Codec Registry.');\n    }\n    if (!Number.isInteger(metadata.decoderConfig.codedWidth) || metadata.decoderConfig.codedWidth <= 0) {\n        throw new TypeError('Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).');\n    }\n    if (!Number.isInteger(metadata.decoderConfig.codedHeight) || metadata.decoderConfig.codedHeight <= 0) {\n        throw new TypeError('Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).');\n    }\n    if (metadata.decoderConfig.displayAspectWidth !== undefined\n        && (!Number.isInteger(metadata.decoderConfig.displayAspectWidth)\n            || metadata.decoderConfig.displayAspectWidth <= 0)) {\n        throw new TypeError('Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.');\n    }\n    if (metadata.decoderConfig.displayAspectHeight !== undefined\n        && (!Number.isInteger(metadata.decoderConfig.displayAspectHeight)\n            || metadata.decoderConfig.displayAspectHeight <= 0)) {\n        throw new TypeError('Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.');\n    }\n    if ((metadata.decoderConfig.displayAspectWidth !== undefined)\n        !== (metadata.decoderConfig.displayAspectHeight !== undefined)) {\n        throw new TypeError('Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight,'\n            + ' or neither.');\n    }\n    if (metadata.decoderConfig.description !== undefined) {\n        if (!isAllowSharedBufferSource(metadata.decoderConfig.description)) {\n            throw new TypeError('Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an'\n                + ' ArrayBuffer view.');\n        }\n    }\n    if (metadata.decoderConfig.colorSpace !== undefined) {\n        const { colorSpace } = metadata.decoderConfig;\n        if (typeof colorSpace !== 'object') {\n            throw new TypeError('Video chunk metadata decoder configuration colorSpace, when provided, must be an object.');\n        }\n        const primariesValues = Object.keys(COLOR_PRIMARIES_MAP);\n        if (colorSpace.primaries != null && !primariesValues.includes(colorSpace.primaries)) {\n            throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of`\n                + ` ${primariesValues.join(', ')}.`);\n        }\n        const transferValues = Object.keys(TRANSFER_CHARACTERISTICS_MAP);\n        if (colorSpace.transfer != null && !transferValues.includes(colorSpace.transfer)) {\n            throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of`\n                + ` ${transferValues.join(', ')}.`);\n        }\n        const matrixValues = Object.keys(MATRIX_COEFFICIENTS_MAP);\n        if (colorSpace.matrix != null && !matrixValues.includes(colorSpace.matrix)) {\n            throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of`\n                + ` ${matrixValues.join(', ')}.`);\n        }\n        if (colorSpace.fullRange != null && typeof colorSpace.fullRange !== 'boolean') {\n            throw new TypeError('Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.');\n        }\n    }\n    if (metadata.decoderConfig.codec.startsWith('avc1') || metadata.decoderConfig.codec.startsWith('avc3')) {\n        // AVC-specific validation\n        if (!AVC_CODEC_STRING_REGEX.test(metadata.decoderConfig.codec)) {\n            throw new TypeError('Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as'\n                + ' specified in Section 3.4 of RFC 6381.');\n        }\n        // `description` may or may not be set, depending on if the format is AVCC or Annex B, so don't perform any\n        // validation for it.\n        // https://www.w3.org/TR/webcodecs-avc-codec-registration\n    }\n    else if (metadata.decoderConfig.codec.startsWith('hev1') || metadata.decoderConfig.codec.startsWith('hvc1')) {\n        // HEVC-specific validation\n        if (!HEVC_CODEC_STRING_REGEX.test(metadata.decoderConfig.codec)) {\n            throw new TypeError('Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as'\n                + ' specified in Section E.3 of ISO 14496-15.');\n        }\n        // `description` may or may not be set, depending on if the format is HEVC or Annex B, so don't perform any\n        // validation for it.\n        // https://www.w3.org/TR/webcodecs-hevc-codec-registration\n    }\n    else if (metadata.decoderConfig.codec.startsWith('vp8')) {\n        // VP8-specific validation\n        if (metadata.decoderConfig.codec !== 'vp8') {\n            throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be \"vp8\".');\n        }\n    }\n    else if (metadata.decoderConfig.codec.startsWith('vp09')) {\n        // VP9-specific validation\n        if (!VP9_CODEC_STRING_REGEX.test(metadata.decoderConfig.codec)) {\n            throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as'\n                + ' specified in Section \"Codecs Parameter String\" of https://www.webmproject.org/vp9/mp4/.');\n        }\n    }\n    else if (metadata.decoderConfig.codec.startsWith('av01')) {\n        // AV1-specific validation\n        if (!AV1_CODEC_STRING_REGEX.test(metadata.decoderConfig.codec)) {\n            throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as'\n                + ' specified in Section \"Codecs Parameter String\" of https://aomediacodec.github.io/av1-isobmff/.');\n        }\n    }\n    else if (PRORES_FOURCCS.some(x => metadata.decoderConfig.codec.startsWith(x))) {\n        // ProRes-specific validation\n        if (!PRORES_FOURCCS.some(x => metadata.decoderConfig.codec === x)) {\n            throw new TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes`\n                + ` four-character codes: ${PRORES_FOURCCS.join(', ')}.`);\n        }\n    }\n    if (trackCodec !== null && inferCodecFromCodecString(metadata.decoderConfig.codec) !== trackCodec) {\n        throw new TypeError(`Video chunk metadata decoder configuration codec string '${metadata.decoderConfig.codec}' does not fit to`\n            + ` the track codec '${trackCodec}'.`);\n    }\n};\nconst VALID_AUDIO_CODEC_STRING_PREFIXES = [\n    'mp4a', 'mp3', 'opus', 'vorbis', 'flac', 'ulaw', 'alaw', 'pcm', 'ac-3', 'ec-3', 'dts',\n];\nexport const validateAudioChunkMetadata = (metadata, trackCodec) => {\n    if (!metadata) {\n        throw new TypeError('Audio chunk metadata must be provided.');\n    }\n    if (typeof metadata !== 'object') {\n        throw new TypeError('Audio chunk metadata must be an object.');\n    }\n    if (!metadata.decoderConfig) {\n        throw new TypeError('Audio chunk metadata must include a decoder configuration.');\n    }\n    if (typeof metadata.decoderConfig !== 'object') {\n        throw new TypeError('Audio chunk metadata decoder configuration must be an object.');\n    }\n    if (typeof metadata.decoderConfig.codec !== 'string') {\n        throw new TypeError('Audio chunk metadata decoder configuration must specify a codec string.');\n    }\n    if (!VALID_AUDIO_CODEC_STRING_PREFIXES.some(prefix => metadata.decoderConfig.codec.startsWith(prefix))) {\n        throw new TypeError('Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in'\n            + ' the Mediabunny Codec Registry.');\n    }\n    if (!Number.isInteger(metadata.decoderConfig.sampleRate) || metadata.decoderConfig.sampleRate <= 0) {\n        throw new TypeError('Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).');\n    }\n    if (!Number.isInteger(metadata.decoderConfig.numberOfChannels) || metadata.decoderConfig.numberOfChannels <= 0) {\n        throw new TypeError('Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).');\n    }\n    if (metadata.decoderConfig.description !== undefined) {\n        if (!isAllowSharedBufferSource(metadata.decoderConfig.description)) {\n            throw new TypeError('Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an'\n                + ' ArrayBuffer view.');\n        }\n    }\n    if (metadata.decoderConfig.codec.startsWith('mp4a')\n        // These three refer to MP3:\n        && metadata.decoderConfig.codec !== 'mp4a.69'\n        && metadata.decoderConfig.codec !== 'mp4a.6B'\n        && metadata.decoderConfig.codec !== 'mp4a.6b') {\n        // AAC-specific validation\n        const validStrings = ['mp4a.40.2', 'mp4a.40.02', 'mp4a.40.5', 'mp4a.40.05', 'mp4a.40.29', 'mp4a.67'];\n        if (!validStrings.includes(metadata.decoderConfig.codec)) {\n            throw new TypeError('Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as'\n                + ' specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.');\n        }\n        // `description` may or may not be set, depending on if the format is AAC or ADTS, so don't perform any\n        // validation for it.\n        // https://www.w3.org/TR/webcodecs-aac-codec-registration\n    }\n    else if (metadata.decoderConfig.codec.startsWith('mp3') || metadata.decoderConfig.codec.startsWith('mp4a')) {\n        // MP3-specific validation\n        if (metadata.decoderConfig.codec !== 'mp3'\n            && metadata.decoderConfig.codec !== 'mp4a.69'\n            && metadata.decoderConfig.codec !== 'mp4a.6B'\n            && metadata.decoderConfig.codec !== 'mp4a.6b') {\n            throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be \"mp3\", \"mp4a.69\" or'\n                + ' \"mp4a.6B\".');\n        }\n    }\n    else if (metadata.decoderConfig.codec.startsWith('opus')) {\n        // Opus-specific validation\n        if (metadata.decoderConfig.codec !== 'opus') {\n            throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be \"opus\".');\n        }\n        if (metadata.decoderConfig.description && metadata.decoderConfig.description.byteLength < 18) {\n            // Description is optional for Opus per-spec, so we shouldn't enforce it\n            throw new TypeError('Audio chunk metadata decoder configuration description, when specified, is expected to be an'\n                + ' Identification Header as specified in Section 5.1 of RFC 7845.');\n        }\n    }\n    else if (metadata.decoderConfig.codec.startsWith('vorbis')) {\n        // Vorbis-specific validation\n        if (metadata.decoderConfig.codec !== 'vorbis') {\n            throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be \"vorbis\".');\n        }\n        if (!metadata.decoderConfig.description) {\n            throw new TypeError('Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to'\n                + ' adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.');\n        }\n    }\n    else if (metadata.decoderConfig.codec.startsWith('flac')) {\n        // FLAC-specific validation\n        if (metadata.decoderConfig.codec !== 'flac') {\n            throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be \"flac\".');\n        }\n        const minDescriptionSize = 4 + 4 + 34; // 'fLaC' + metadata block header + STREAMINFO block\n        if (!metadata.decoderConfig.description || metadata.decoderConfig.description.byteLength < minDescriptionSize) {\n            throw new TypeError('Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to'\n                + ' adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.');\n        }\n    }\n    else if (metadata.decoderConfig.codec.startsWith('ac-3') || metadata.decoderConfig.codec.startsWith('ac3')) {\n        // AC3-specific validation\n        if (metadata.decoderConfig.codec !== 'ac-3') {\n            throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be \"ac-3\".');\n        }\n    }\n    else if (metadata.decoderConfig.codec.startsWith('ec-3') || metadata.decoderConfig.codec.startsWith('eac3')) {\n        // EAC3-specific validation\n        if (metadata.decoderConfig.codec !== 'ec-3') {\n            throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be \"ec-3\".');\n        }\n    }\n    else if (metadata.decoderConfig.codec.startsWith('dts')) {\n        // DTS-specific validation\n        if (!DTS_FOURCCS.includes(metadata.decoderConfig.codec)) {\n            throw new TypeError('Audio chunk metadata decoder configuration codec string for DTS must be one of the following'\n                + ` four-character codes: ${DTS_FOURCCS.join(', ')}.`);\n        }\n    }\n    else if (metadata.decoderConfig.codec.startsWith('pcm')\n        || metadata.decoderConfig.codec.startsWith('ulaw')\n        || metadata.decoderConfig.codec.startsWith('alaw')) {\n        // PCM-specific validation\n        if (!PCM_AUDIO_CODECS.includes(metadata.decoderConfig.codec)) {\n            throw new TypeError('Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM'\n                + ` codecs (${PCM_AUDIO_CODECS.join(', ')}).`);\n        }\n    }\n    if (trackCodec !== null && inferCodecFromCodecString(metadata.decoderConfig.codec) !== trackCodec) {\n        throw new TypeError(`Audio chunk metadata decoder configuration codec string '${metadata.decoderConfig.codec}' does not fit to`\n            + ` the track codec '${trackCodec}'.`);\n    }\n};\nexport const validateSubtitleMetadata = (metadata) => {\n    if (!metadata) {\n        throw new TypeError('Subtitle metadata must be provided.');\n    }\n    if (typeof metadata !== 'object') {\n        throw new TypeError('Subtitle metadata must be an object.');\n    }\n    if (!metadata.config) {\n        throw new TypeError('Subtitle metadata must include a config object.');\n    }\n    if (typeof metadata.config !== 'object') {\n        throw new TypeError('Subtitle metadata config must be an object.');\n    }\n    if (typeof metadata.config.description !== 'string') {\n        throw new TypeError('Subtitle metadata config description must be a string.');\n    }\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nexport const MP3_FRAME_HEADER_SIZE = 4;\nexport const SAMPLING_RATES = [44100, 48000, 32000];\nexport const KILOBIT_RATES = [\n    // lowSamplingFrequency === 0\n    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // layer = 0\n    -1, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1, // layer 1\n    -1, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, -1, // layer = 2\n    -1, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, -1, // layer = 3\n    // lowSamplingFrequency === 1\n    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // layer = 0\n    -1, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, -1, // layer = 1\n    -1, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, -1, // layer = 2\n    -1, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, -1, // layer = 3\n];\n/** 'Xing' */\nexport const XING = 0x58696e67;\n/** 'Info' */\nexport const INFO = 0x496e666f;\nexport const computeMp3FrameSize = (lowSamplingFrequency, layer, bitrate, sampleRate, padding) => {\n    if (layer === 0) {\n        return 0; // Not expected that this is hit\n    }\n    else if (layer === 1) {\n        return Math.floor(144 * bitrate / (sampleRate << lowSamplingFrequency)) + padding;\n    }\n    else if (layer === 2) {\n        return Math.floor(144 * bitrate / sampleRate) + padding;\n    }\n    else { // layer === 3\n        return (Math.floor(12 * bitrate / sampleRate) + padding) * 4;\n    }\n};\nexport const computeAverageMp3FrameSize = (lowSamplingFrequency, layer, bitrate, sampleRate) => {\n    if (layer === 0) {\n        return 0; // Not expected that this is hit\n    }\n    else if (layer === 1) {\n        return 144 * bitrate / (sampleRate << lowSamplingFrequency);\n    }\n    else if (layer === 2) {\n        return 144 * bitrate / sampleRate;\n    }\n    else { // layer === 3\n        return (12 * bitrate / sampleRate) * 4;\n    }\n};\nexport const getXingOffset = (mpegVersionId, channel) => {\n    return mpegVersionId === 3\n        ? (channel === 3 ? 21 : 36)\n        : (channel === 3 ? 13 : 21);\n};\nexport const readMp3FrameHeader = (word, remainingBytes) => {\n    const firstByte = word >>> 24;\n    const secondByte = (word >>> 16) & 0xff;\n    const thirdByte = (word >>> 8) & 0xff;\n    const fourthByte = word & 0xff;\n    if (firstByte !== 0xff && secondByte !== 0xff && thirdByte !== 0xff && fourthByte !== 0xff) {\n        return {\n            header: null,\n            bytesAdvanced: 4,\n        };\n    }\n    if (firstByte !== 0xff) {\n        return { header: null, bytesAdvanced: 1 };\n    }\n    if ((secondByte & 0xe0) !== 0xe0) {\n        return { header: null, bytesAdvanced: 1 };\n    }\n    let lowSamplingFrequency = 0;\n    let mpeg25 = 0;\n    if (secondByte & (1 << 4)) {\n        lowSamplingFrequency = (secondByte & (1 << 3)) ? 0 : 1;\n    }\n    else {\n        lowSamplingFrequency = 1;\n        mpeg25 = 1;\n    }\n    const mpegVersionId = (secondByte >> 3) & 0x3;\n    const layer = (secondByte >> 1) & 0x3;\n    const bitrateIndex = (thirdByte >> 4) & 0xf;\n    const frequencyIndex = ((thirdByte >> 2) & 0x3) % 3; // FFmpeg effectively does % 3 (but in a roundabout way)\n    const padding = (thirdByte >> 1) & 0x1;\n    const channel = (fourthByte >> 6) & 0x3;\n    const modeExtension = (fourthByte >> 4) & 0x3;\n    const copyright = (fourthByte >> 3) & 0x1;\n    const original = (fourthByte >> 2) & 0x1;\n    const emphasis = fourthByte & 0x3;\n    const kilobitRate = KILOBIT_RATES[lowSamplingFrequency * 16 * 4 + layer * 16 + bitrateIndex];\n    if (kilobitRate === -1) {\n        return { header: null, bytesAdvanced: 1 };\n    }\n    const bitrate = kilobitRate * 1000;\n    const sampleRate = SAMPLING_RATES[frequencyIndex] >> (lowSamplingFrequency + mpeg25);\n    const frameLength = computeMp3FrameSize(lowSamplingFrequency, layer, bitrate, sampleRate, padding);\n    if (remainingBytes !== null && remainingBytes < frameLength) {\n        // The frame doesn't fit into the rest of the file\n        return { header: null, bytesAdvanced: 1 };\n    }\n    let audioSamplesInFrame;\n    if (mpegVersionId === 3) {\n        audioSamplesInFrame = layer === 3 ? 384 : 1152;\n    }\n    else {\n        if (layer === 3) {\n            audioSamplesInFrame = 384;\n        }\n        else if (layer === 2) {\n            audioSamplesInFrame = 1152;\n        }\n        else {\n            audioSamplesInFrame = 576;\n        }\n    }\n    return {\n        header: {\n            totalSize: frameLength,\n            mpegVersionId,\n            lowSamplingFrequency,\n            layer,\n            bitrate,\n            frequencyIndex,\n            sampleRate,\n            channel,\n            modeExtension,\n            copyright,\n            original,\n            emphasis,\n            audioSamplesInFrame,\n        },\n        bytesAdvanced: 1,\n    };\n};\nexport const encodeSynchsafe = (unsynchsafed) => {\n    let mask = 0x7f;\n    let synchsafed = 0;\n    let unsynchsafedRest = unsynchsafed;\n    while ((mask ^ 0x7fffffff) !== 0) {\n        synchsafed = unsynchsafedRest & ~mask;\n        synchsafed <<= 1;\n        synchsafed |= unsynchsafedRest & mask;\n        mask = ((mask + 1) << 8) - 1;\n        unsynchsafedRest = synchsafed;\n    }\n    return synchsafed;\n};\nexport const decodeSynchsafe = (synchsafed) => {\n    let mask = 0x7f000000;\n    let unsynchsafed = 0;\n    while (mask !== 0) {\n        unsynchsafed >>= 1;\n        unsynchsafed |= synchsafed & mask;\n        mask >>= 8;\n    }\n    return unsynchsafed;\n};\nexport var XingFlags;\n(function (XingFlags) {\n    XingFlags[XingFlags[\"FrameCount\"] = 1] = \"FrameCount\";\n    XingFlags[XingFlags[\"FileSize\"] = 2] = \"FileSize\";\n    XingFlags[XingFlags[\"Toc\"] = 4] = \"Toc\";\n})(XingFlags || (XingFlags = {}));\nexport const getMp3ChannelCount = (channel) => {\n    return channel === 3 ? 1 : 2;\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nexport class Demuxer {\n    constructor(input) {\n        this.input = input;\n    }\n    dispose() {\n        // Can be overridden\n    }\n}\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { SECOND_TO_MICROSECOND_FACTOR } from './misc.js';\nexport const PLACEHOLDER_DATA = /* #__PURE__ */ new Uint8Array(0);\n/**\n * Represents an encoded chunk of media. Mainly used as an expressive wrapper around WebCodecs API's\n * [`EncodedVideoChunk`](https://developer.mozilla.org/en-US/docs/Web/API/EncodedVideoChunk) and\n * [`EncodedAudioChunk`](https://developer.mozilla.org/en-US/docs/Web/API/EncodedAudioChunk), but can also be used\n * standalone.\n * @group Packets\n * @public\n */\nexport class EncodedPacket {\n    /** Creates a new {@link EncodedPacket} from raw bytes and timing information. */\n    constructor(\n    /**\n     * The encoded data of this packet. For any given codec, this data must adhere to the format specified in the\n     * Mediabunny Codec Registry.\n     */\n    data, \n    /** The type of this packet. */\n    type, \n    /**\n     * The presentation timestamp of this packet in seconds. May be negative. Samples with negative end timestamps\n     * should not be presented.\n     */\n    timestamp, \n    /** The duration of this packet in seconds. */\n    duration, \n    /**\n     * The sequence number indicates the decode order of the packets. Packet A  must be decoded before packet B if A\n     * has a lower sequence number than B. If two packets have the same sequence number, they are the same packet.\n     * Otherwise, sequence numbers are arbitrary and are not guaranteed to have any meaning besides their relative\n     * ordering. Negative sequence numbers mean the sequence number is undefined.\n     */\n    sequenceNumber = -1, byteLength, sideData) {\n        this.data = data;\n        this.type = type;\n        this.timestamp = timestamp;\n        this.duration = duration;\n        this.sequenceNumber = sequenceNumber;\n        if (data === PLACEHOLDER_DATA && byteLength === undefined) {\n            throw new Error('Internal error: byteLength must be explicitly provided when constructing metadata-only packets.');\n        }\n        if (byteLength === undefined) {\n            byteLength = data.byteLength;\n        }\n        if (!(data instanceof Uint8Array)) {\n            throw new TypeError('data must be a Uint8Array.');\n        }\n        if (type !== 'key' && type !== 'delta') {\n            throw new TypeError('type must be either \"key\" or \"delta\".');\n        }\n        if (!Number.isFinite(timestamp)) {\n            throw new TypeError('timestamp must be a number.');\n        }\n        if (!Number.isFinite(duration) || duration < 0) {\n            throw new TypeError('duration must be a non-negative number.');\n        }\n        if (!Number.isFinite(sequenceNumber)) {\n            throw new TypeError('sequenceNumber must be a number.');\n        }\n        if (!Number.isInteger(byteLength) || byteLength < 0) {\n            throw new TypeError('byteLength must be a non-negative integer.');\n        }\n        if (sideData !== undefined && (typeof sideData !== 'object' || !sideData)) {\n            throw new TypeError('sideData, when provided, must be an object.');\n        }\n        if (sideData?.alpha !== undefined && !(sideData.alpha instanceof Uint8Array)) {\n            throw new TypeError('sideData.alpha, when provided, must be a Uint8Array.');\n        }\n        if (sideData?.alphaByteLength !== undefined\n            && (!Number.isInteger(sideData.alphaByteLength) || sideData.alphaByteLength < 0)) {\n            throw new TypeError('sideData.alphaByteLength, when provided, must be a non-negative integer.');\n        }\n        this.byteLength = byteLength;\n        this.sideData = sideData ?? {};\n        if (this.sideData.alpha && this.sideData.alphaByteLength === undefined) {\n            this.sideData.alphaByteLength = this.sideData.alpha.byteLength;\n        }\n    }\n    /**\n     * If this packet is a metadata-only packet. Metadata-only packets don't contain their packet data. They are the\n     * result of retrieving packets with {@link PacketRetrievalOptions.metadataOnly} set to `true`.\n     */\n    get isMetadataOnly() {\n        return this.data === PLACEHOLDER_DATA;\n    }\n    /** The timestamp of this packet in microseconds. */\n    get microsecondTimestamp() {\n        return Math.trunc(SECOND_TO_MICROSECOND_FACTOR * this.timestamp);\n    }\n    /** The duration of this packet in microseconds. */\n    get microsecondDuration() {\n        return Math.trunc(SECOND_TO_MICROSECOND_FACTOR * this.duration);\n    }\n    /** Converts this packet to an\n     * [`EncodedVideoChunk`](https://developer.mozilla.org/en-US/docs/Web/API/EncodedVideoChunk) for use with the\n     * WebCodecs API. */\n    toEncodedVideoChunk() {\n        if (this.isMetadataOnly) {\n            throw new TypeError('Metadata-only packets cannot be converted to a video chunk.');\n        }\n        if (typeof EncodedVideoChunk === 'undefined') {\n            throw new Error('EncodedVideoChunk is not available in this environment.');\n        }\n        return new EncodedVideoChunk({\n            data: this.data,\n            type: this.type,\n            timestamp: this.microsecondTimestamp,\n            duration: this.microsecondDuration,\n        });\n    }\n    /**\n     * Converts this packet to an\n     * [`EncodedVideoChunk`](https://developer.mozilla.org/en-US/docs/Web/API/EncodedVideoChunk) for use with the\n     * WebCodecs API, using the alpha side data instead of the color data. Throws if no alpha side data is defined.\n     */\n    alphaToEncodedVideoChunk(type = this.type) {\n        if (!this.sideData.alpha) {\n            throw new TypeError('This packet does not contain alpha side data.');\n        }\n        if (this.isMetadataOnly) {\n            throw new TypeError('Metadata-only packets cannot be converted to a video chunk.');\n        }\n        if (typeof EncodedVideoChunk === 'undefined') {\n            throw new Error('EncodedVideoChunk is not available in this environment.');\n        }\n        return new EncodedVideoChunk({\n            data: this.sideData.alpha,\n            type,\n            timestamp: this.microsecondTimestamp,\n            duration: this.microsecondDuration,\n        });\n    }\n    /** Converts this packet to an\n     * [`EncodedAudioChunk`](https://developer.mozilla.org/en-US/docs/Web/API/EncodedAudioChunk) for use with the\n     * WebCodecs API. */\n    toEncodedAudioChunk() {\n        if (this.isMetadataOnly) {\n            throw new TypeError('Metadata-only packets cannot be converted to an audio chunk.');\n        }\n        if (typeof EncodedAudioChunk === 'undefined') {\n            throw new Error('EncodedAudioChunk is not available in this environment.');\n        }\n        return new EncodedAudioChunk({\n            data: this.data,\n            type: this.type,\n            timestamp: this.microsecondTimestamp,\n            duration: this.microsecondDuration,\n        });\n    }\n    /**\n     * Creates an {@link EncodedPacket} from an\n     * [`EncodedVideoChunk`](https://developer.mozilla.org/en-US/docs/Web/API/EncodedVideoChunk) or\n     * [`EncodedAudioChunk`](https://developer.mozilla.org/en-US/docs/Web/API/EncodedAudioChunk). This method is useful\n     * for converting chunks from the WebCodecs API to `EncodedPacket` instances.\n     */\n    static fromEncodedChunk(chunk, sideData) {\n        if (!(chunk instanceof EncodedVideoChunk || chunk instanceof EncodedAudioChunk)) {\n            throw new TypeError('chunk must be an EncodedVideoChunk or EncodedAudioChunk.');\n        }\n        const data = new Uint8Array(chunk.byteLength);\n        chunk.copyTo(data);\n        return new EncodedPacket(data, chunk.type, chunk.timestamp / 1e6, (chunk.duration ?? 0) / 1e6, undefined, undefined, sideData);\n    }\n    /** Clones this packet while optionally modifying the new packet's data. */\n    clone(options) {\n        if (options !== undefined && (typeof options !== 'object' || options === null)) {\n            throw new TypeError('options, when provided, must be an object.');\n        }\n        if (options?.data !== undefined && !(options.data instanceof Uint8Array)) {\n            throw new TypeError('options.data, when provided, must be a Uint8Array.');\n        }\n        if (options?.type !== undefined && options.type !== 'key' && options.type !== 'delta') {\n            throw new TypeError('options.type, when provided, must be either \"key\" or \"delta\".');\n        }\n        if (options?.timestamp !== undefined && !Number.isFinite(options.timestamp)) {\n            throw new TypeError('options.timestamp, when provided, must be a number.');\n        }\n        if (options?.duration !== undefined && !Number.isFinite(options.duration)) {\n            throw new TypeError('options.duration, when provided, must be a number.');\n        }\n        if (options?.sequenceNumber !== undefined && !Number.isFinite(options.sequenceNumber)) {\n            throw new TypeError('options.sequenceNumber, when provided, must be a number.');\n        }\n        if (options?.sideData !== undefined && (typeof options.sideData !== 'object' || options.sideData === null)) {\n            throw new TypeError('options.sideData, when provided, must be an object.');\n        }\n        return new EncodedPacket(options?.data ?? this.data, options?.type ?? this.type, options?.timestamp ?? this.timestamp, options?.duration ?? this.duration, options?.sequenceNumber ?? this.sequenceNumber, this.byteLength, options?.sideData ?? this.sideData);\n    }\n}\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { bytesToHexString, toDataView, uint8ArraysAreEqual } from '../misc.js';\nexport const buildIsobmffMimeType = (info) => {\n    const base = info.hasVideo\n        ? 'video/'\n        : info.hasAudio\n            ? 'audio/'\n            : 'application/';\n    let string = base + (info.isQuickTime ? 'quicktime' : 'mp4');\n    if (info.codecStrings.length > 0) {\n        const uniqueCodecMimeTypes = [...new Set(info.codecStrings)];\n        string += `; codecs=\"${uniqueCodecMimeTypes.join(', ')}\"`;\n    }\n    return string;\n};\nexport const parsePsshBoxContents = (contents) => {\n    if (contents.length < 24) {\n        throw new Error('Invalid pssh box: too small.');\n    }\n    const view = toDataView(contents);\n    let pos = 0;\n    const version = view.getUint8(pos);\n    pos += 1;\n    pos += 3; // Flags\n    const systemId = bytesToHexString(contents.subarray(pos, pos + 16));\n    pos += 16;\n    let keyIds = null;\n    if (version > 0) {\n        const kidCount = view.getUint32(pos);\n        pos += 4;\n        if (pos + 16 * kidCount + 4 > contents.length) {\n            throw new Error('Invalid pssh box: key ID count exceeds box size.');\n        }\n        if (kidCount > 0) {\n            keyIds = [];\n            for (let i = 0; i < kidCount; i++) {\n                keyIds.push(bytesToHexString(contents.subarray(pos, pos + 16)));\n                pos += 16;\n            }\n        }\n    }\n    const dataSize = view.getUint32(pos);\n    pos += 4;\n    return {\n        systemId,\n        keyIds,\n        data: contents.slice(pos, pos + dataSize),\n    };\n};\nexport const psshBoxesAreEqual = (a, b) => (a.systemId === b.systemId\n    && uint8ArraysAreEqual(a.data, b.data));\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { RichImageData } from '../metadata.js';\nimport { TextDecoder, textDecoder } from '../misc.js';\nimport { readAscii, readBytes, readI32Be, readU16Be, readU32Be, readU64Be, readU8 } from '../reader.js';\nexport const MIN_BOX_HEADER_SIZE = 8;\nexport const MAX_BOX_HEADER_SIZE = 16;\nexport const readBoxHeader = (slice) => {\n    let totalSize = readU32Be(slice);\n    const name = readAscii(slice, 4);\n    let headerSize = 8;\n    const hasLargeSize = totalSize === 1;\n    if (hasLargeSize) {\n        totalSize = readU64Be(slice);\n        headerSize = 16;\n    }\n    const contentSize = totalSize - headerSize;\n    if (contentSize < 0) {\n        return null; // Hardly a box is it\n    }\n    return { name, totalSize, headerSize, contentSize };\n};\nexport const readFixed_16_16 = (slice) => {\n    return readI32Be(slice) / 0x10000;\n};\nexport const readFixed_2_30 = (slice) => {\n    return readI32Be(slice) / 0x40000000;\n};\nexport const readIsomVariableInteger = (slice) => {\n    let result = 0;\n    for (let i = 0; i < 4; i++) {\n        result <<= 7;\n        const nextByte = readU8(slice);\n        result |= nextByte & 0x7f;\n        if ((nextByte & 0x80) === 0) {\n            break;\n        }\n    }\n    return result;\n};\nexport const readEsDescriptor = (slice) => {\n    const tag = readU8(slice);\n    if (tag !== 0x03) {\n        throw new Error('Invalid esds: expected ES_Descriptor.');\n    }\n    readIsomVariableInteger(slice); // Length\n    slice.skip(2); // ES ID\n    const mixed = readU8(slice);\n    const streamDependenceFlag = (mixed & 0x80) !== 0;\n    const urlFlag = (mixed & 0x40) !== 0;\n    const ocrStreamFlag = (mixed & 0x20) !== 0;\n    if (streamDependenceFlag) {\n        slice.skip(2);\n    }\n    if (urlFlag) {\n        const urlLength = readU8(slice);\n        slice.skip(urlLength);\n    }\n    if (ocrStreamFlag) {\n        slice.skip(2);\n    }\n    const decoderConfigTag = readU8(slice);\n    if (decoderConfigTag !== 0x04) {\n        throw new Error('Invalid esds: expected DecoderConfigDescriptor.');\n    }\n    const decoderConfigDescriptorLength = readIsomVariableInteger(slice); // Length\n    const payloadStart = slice.filePos;\n    const objectTypeIndication = readU8(slice);\n    slice.skip(1 + 3 + 4 + 4);\n    let decoderSpecificInfo = null;\n    if (decoderConfigDescriptorLength > slice.filePos - payloadStart) {\n        // There's a DecoderSpecificInfo at the end, let's read it\n        const decoderSpecificInfoTag = readU8(slice);\n        if (decoderSpecificInfoTag !== 0x05) {\n            throw new Error('Invalid esds: expected DecoderSpecificInfo.');\n        }\n        const decoderSpecificInfoLength = readIsomVariableInteger(slice);\n        decoderSpecificInfo = readBytes(slice, decoderSpecificInfoLength);\n    }\n    return {\n        objectTypeIndication,\n        decoderSpecificInfo,\n    };\n};\nexport const readMetadataStringShort = (slice) => {\n    let stringLength = readU16Be(slice);\n    slice.skip(2); // Language\n    stringLength = Math.min(stringLength, slice.remainingLength);\n    return textDecoder.decode(readBytes(slice, stringLength));\n};\nexport const readDataBox = (slice) => {\n    const header = readBoxHeader(slice);\n    if (!header || header.name !== 'data') {\n        return null;\n    }\n    if (header.contentSize < 8 || slice.remainingLength < 8) {\n        // Box is too small\n        return null;\n    }\n    const typeIndicator = readU32Be(slice);\n    slice.skip(4); // Locale indicator\n    const data = readBytes(slice, header.contentSize - 8);\n    switch (typeIndicator) {\n        case 1: return textDecoder.decode(data); // UTF-8\n        case 2: return new TextDecoder('utf-16be').decode(data); // UTF-16-BE\n        case 13: return new RichImageData(data, 'image/jpeg');\n        case 14: return new RichImageData(data, 'image/png');\n        case 27: return new RichImageData(data, 'image/bmp');\n        default: return data;\n    }\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { assert, isThenable } from './misc.js';\nimport { readBytes } from './reader.js';\n// Inspired in part by https://github.com/halloweeks/AES-128-CBC/blob/main/AES_128_CBC.h\nexport const AES_128_BLOCK_SIZE = 16;\nconst Te4 = new Uint32Array(256);\nconst Td0 = new Uint32Array(256);\nconst Td1 = new Uint32Array(256);\nconst Td2 = new Uint32Array(256);\nconst Td3 = new Uint32Array(256);\nconst Td4 = new Uint32Array(256);\nconst rcon = new Uint32Array(10);\nlet tablesGenerated = false;\n// Generating the tables once is much more bundle size-efficient than shipping them in the bundle (entropy ftw)\nconst generateAesTables = () => {\n    const sbox = new Uint8Array(256);\n    const log = new Uint8Array(256);\n    const pow = new Uint8Array(256);\n    // 1. Generate GF(2^8) log/exp tables\n    // Primitive polynomial: x^8 + x^4 + x^3 + x + 1 (0x11B)\n    for (let i = 0, p = 1; i < 256; i++) {\n        pow[i] = p;\n        log[p] = i;\n        p = p ^ (p << 1) ^ (p & 0x80 ? 0x11B : 0);\n    }\n    // Helper: GF(2^8) multiplication\n    const mul = (a, b) => (a && b) ? pow[(log[a] + log[b]) % 255] : 0;\n    // 2. Generate S-Box and Inverse S-Box\n    sbox[0] = 0x63; // Special case for 0\n    // Loop for inverse (using log/exp) and Affine Transform\n    for (let i = 1; i < 256; i++) {\n        const x = pow[255 - log[i]]; // Multiplicative inverse\n        let s = x ^ (x << 1) ^ (x << 2) ^ (x << 3) ^ (x << 4);\n        s = (s >>> 8) ^ (s & 0xFF) ^ 0x63; // Affine transform\n        sbox[i] = s;\n    }\n    // 3. Fill Tables\n    for (let i = 0; i < 256; i++) {\n        const s = sbox[i]; // Forward S-Box value\n        const is = sbox.indexOf(i); // Inverse S-Box value\n        // Te4: Forward S-Box packed\n        Te4[i] = (s << 24) | (s << 16) | (s << 8) | s;\n        // Td4: Inverse S-Box packed\n        Td4[i] = (is << 24) | (is << 16) | (is << 8) | is;\n        // Td0-Td3: Inverse MixColumns applied to Inverse S-Box\n        // Coefficients: 0x0E, 0x09, 0x0D, 0x0B (Order specific to Td0 structure)\n        const b0 = mul(is, 0x0E);\n        const b1 = mul(is, 0x09);\n        const b2 = mul(is, 0x0D);\n        const b3 = mul(is, 0x0B);\n        const w = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;\n        Td0[i] = w;\n        Td1[i] = (w >>> 8) | (w << 24); // Rotate right 8\n        Td2[i] = (w >>> 16) | (w << 16); // Rotate right 16\n        Td3[i] = (w >>> 24) | (w << 8); // Rotate right 24\n    }\n    // 4. Generate Rcon\n    let r = 1;\n    for (let i = 0; i < 10; i++) {\n        rcon[i] = r << 24;\n        r = (r << 1) ^ (r & 0x80 ? 0x11B : 0);\n    }\n    tablesGenerated = true;\n};\n/** A context for doing AES-128-CBC operations. Better than the Web Crypto API since we can stream it. */\nexport class Aes128CbcContext {\n    constructor() {\n        this.roundkey = new Uint32Array(44);\n        this.iv = new Uint32Array(AES_128_BLOCK_SIZE / Uint32Array.BYTES_PER_ELEMENT);\n        this.in = new Uint8Array(AES_128_BLOCK_SIZE);\n        this.out = new Uint8Array(AES_128_BLOCK_SIZE);\n        this.inView = new DataView(this.in.buffer);\n        this.outView = new DataView(this.out.buffer);\n    }\n    init({ key, iv }) {\n        assert(key.byteLength === 16);\n        assert(iv.byteLength === 16);\n        if (!tablesGenerated) {\n            generateAesTables();\n        }\n        const keyView = new DataView(key.buffer, key.byteOffset, key.byteLength);\n        const ivView = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);\n        this.roundkey[0] = keyView.getUint32(0, false);\n        this.roundkey[1] = keyView.getUint32(4, false);\n        this.roundkey[2] = keyView.getUint32(8, false);\n        this.roundkey[3] = keyView.getUint32(12, false);\n        this.iv[0] = ivView.getUint32(0, false);\n        this.iv[1] = ivView.getUint32(4, false);\n        this.iv[2] = ivView.getUint32(8, false);\n        this.iv[3] = ivView.getUint32(12, false);\n        for (let index = 4; index < 44; index += 4) {\n            const temp = this.roundkey[index - 1];\n            this.roundkey[index] = this.roundkey[index - 4]\n                ^ (Te4[(temp >>> 16) & 0xff] & 0xff000000)\n                ^ (Te4[(temp >>> 8) & 0xff] & 0x00ff0000)\n                ^ (Te4[(temp >>> 0) & 0xff] & 0x0000ff00)\n                ^ (Te4[(temp >>> 24) & 0xff] & 0x000000ff)\n                ^ rcon[(index / 4) - 1];\n            this.roundkey[index + 1] = this.roundkey[index - 3] ^ this.roundkey[index];\n            this.roundkey[index + 2] = this.roundkey[index - 2] ^ this.roundkey[index + 1];\n            this.roundkey[index + 3] = this.roundkey[index - 1] ^ this.roundkey[index + 2];\n        }\n        // Invert the order of the round keys\n        for (let i = 0, j = 40; i < j; i += 4, j -= 4) {\n            for (let k = 0; k < 4; k++) {\n                const temp = this.roundkey[i + k];\n                this.roundkey[i + k] = this.roundkey[j + k];\n                this.roundkey[j + k] = temp;\n            }\n        }\n        // Apply Inverse MixColumn transform to all round keys except first and last\n        for (let index = 4; index < 40; index += 4) {\n            for (let k = 0; k < 4; k++) {\n                const rk = this.roundkey[index + k];\n                this.roundkey[index + k]\n                    = Td0[Te4[(rk >>> 24) & 0xff] & 0xff]\n                        ^ Td1[Te4[(rk >>> 16) & 0xff] & 0xff]\n                        ^ Td2[Te4[(rk >>> 8) & 0xff] & 0xff]\n                        ^ Td3[Te4[(rk >>> 0) & 0xff] & 0xff];\n            }\n        }\n    }\n    decrypt() {\n        let s0 = this.inView.getUint32(0, false) ^ this.roundkey[0];\n        let s1 = this.inView.getUint32(4, false) ^ this.roundkey[1];\n        let s2 = this.inView.getUint32(8, false) ^ this.roundkey[2];\n        let s3 = this.inView.getUint32(12, false) ^ this.roundkey[3];\n        // Store input for CBC XOR later\n        const temp0 = this.inView.getUint32(0, false);\n        const temp1 = this.inView.getUint32(4, false);\n        const temp2 = this.inView.getUint32(8, false);\n        const temp3 = this.inView.getUint32(12, false);\n        let t0, t1, t2, t3;\n        // Rounds 1-9\n        for (let round = 1; round < 10; round++) {\n            const offset = round * 4;\n            t0 = Td0[s0 >>> 24]\n                ^ Td1[(s3 >>> 16) & 0xff]\n                ^ Td2[(s2 >>> 8) & 0xff]\n                ^ Td3[s1 & 0xff]\n                ^ this.roundkey[offset];\n            t1 = Td0[s1 >>> 24]\n                ^ Td1[(s0 >>> 16) & 0xff]\n                ^ Td2[(s3 >>> 8) & 0xff]\n                ^ Td3[s2 & 0xff]\n                ^ this.roundkey[offset + 1];\n            t2 = Td0[s2 >>> 24]\n                ^ Td1[(s1 >>> 16) & 0xff]\n                ^ Td2[(s0 >>> 8) & 0xff]\n                ^ Td3[s3 & 0xff]\n                ^ this.roundkey[offset + 2];\n            t3 = Td0[s3 >>> 24]\n                ^ Td1[(s2 >>> 16) & 0xff]\n                ^ Td2[(s1 >>> 8) & 0xff]\n                ^ Td3[s0 & 0xff]\n                ^ this.roundkey[offset + 3];\n            s0 = t0;\n            s1 = t1;\n            s2 = t2;\n            s3 = t3;\n        }\n        // Final Round (10)\n        const f0 = (Td4[(s0 >>> 24) & 0xff] & 0xff000000)\n            ^ (Td4[(s3 >>> 16) & 0xff] & 0x00ff0000)\n            ^ (Td4[(s2 >>> 8) & 0xff] & 0x0000ff00)\n            ^ (Td4[(s1 >>> 0) & 0xff] & 0x000000ff)\n            ^ this.roundkey[40];\n        const f1 = (Td4[(s1 >>> 24) & 0xff] & 0xff000000)\n            ^ (Td4[(s0 >>> 16) & 0xff] & 0x00ff0000)\n            ^ (Td4[(s3 >>> 8) & 0xff] & 0x0000ff00)\n            ^ (Td4[(s2 >>> 0) & 0xff] & 0x000000ff)\n            ^ this.roundkey[41];\n        const f2 = (Td4[(s2 >>> 24) & 0xff] & 0xff000000)\n            ^ (Td4[(s1 >>> 16) & 0xff] & 0x00ff0000)\n            ^ (Td4[(s0 >>> 8) & 0xff] & 0x0000ff00)\n            ^ (Td4[(s3 >>> 0) & 0xff] & 0x000000ff)\n            ^ this.roundkey[42];\n        const f3 = (Td4[(s3 >>> 24) & 0xff] & 0xff000000)\n            ^ (Td4[(s2 >>> 16) & 0xff] & 0x00ff0000)\n            ^ (Td4[(s1 >>> 8) & 0xff] & 0x0000ff00)\n            ^ (Td4[(s0 >>> 0) & 0xff] & 0x000000ff)\n            ^ this.roundkey[43];\n        // CBC XOR and output\n        this.outView.setUint32(0, f0 ^ this.iv[0], false);\n        this.outView.setUint32(4, f1 ^ this.iv[1], false);\n        this.outView.setUint32(8, f2 ^ this.iv[2], false);\n        this.outView.setUint32(12, f3 ^ this.iv[3], false);\n        // Update IV for next block\n        this.iv[0] = temp0;\n        this.iv[1] = temp1;\n        this.iv[2] = temp2;\n        this.iv[3] = temp3;\n    }\n}\nexport const createAes128CbcDecryptStream = (reader, getInit, close) => {\n    let initted = false;\n    let pos = 0;\n    const CHUNK_SIZE = 2 ** 16;\n    const BLOCK_SIZE = 16;\n    const aesContext = new Aes128CbcContext();\n    return new ReadableStream({\n        pull: async (controller) => {\n            if (!initted) {\n                aesContext.init(await getInit());\n                initted = true;\n            }\n            const requestedLength = CHUNK_SIZE + BLOCK_SIZE;\n            let nextSlice = reader.requestSliceRange(pos, 0, requestedLength);\n            if (isThenable(nextSlice))\n                nextSlice = await nextSlice;\n            if (!nextSlice || nextSlice.length === 0) {\n                // Due to padding, this should never happen\n                throw new Error('Invalid ciphertext.');\n            }\n            const sliceLength = nextSlice.length;\n            if (sliceLength % 16 !== 0) {\n                throw new Error('Invalid ciphertext.');\n            }\n            const bytesToRead = sliceLength === requestedLength\n                ? sliceLength - BLOCK_SIZE // Don't read the last block\n                : sliceLength;\n            const input = readBytes(nextSlice, bytesToRead);\n            const output = new Uint8Array(bytesToRead);\n            for (let i = 0; i < bytesToRead; i += 16) {\n                aesContext.in.set(input.subarray(i, i + 16));\n                aesContext.decrypt();\n                output.set(aesContext.out, i);\n            }\n            if (bytesToRead < sliceLength) {\n                controller.enqueue(output);\n                pos += bytesToRead;\n            }\n            else {\n                // This is the last chunk\n                const paddingLength = output[bytesToRead - 1];\n                if (paddingLength === 0 || paddingLength > 16) {\n                    throw new Error('Invalid PKCS#7 padding. Incorrect key or corrupted data.');\n                }\n                const trimmedOutput = output.subarray(0, bytesToRead - paddingLength); // PKCS#7 padding\n                controller.enqueue(trimmedOutput);\n                controller.close();\n                close();\n            }\n        },\n        cancel: () => {\n            close();\n        },\n    });\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { parseAacAudioSpecificConfig } from '../../shared/aac-misc.js';\nimport { DTS_FOURCCS, extractAudioCodecString, extractColorSpace, extractVideoCodecString, OPUS_SAMPLE_RATE, parsePcmCodec, PCM_AUDIO_CODECS, PRORES_FOURCCS, } from '../codec.js';\nimport { av1CodecInfoHasColorInfo, extractAv1CodecInfoFromPacket, extractProresCodecInfoFromPacket, extractVp9CodecInfoFromPacket, FlacBlockType, vp9CodecInfoHasColorInfo, parseEac3Config, getEac3SampleRate, getEac3ChannelCount, extractDtsFourCcFromPacket, parseDtsSpecificBox, DTS_SPECIFIC_BOX_SIZE, AC3_ACMOD_CHANNEL_COUNTS, extractAvcDecoderConfigurationRecord, extractHevcDecoderConfigurationRecord, deserializeAvcDecoderConfigurationRecord, deserializeHevcDecoderConfigurationRecord, HevcNalUnitType, parseAvcSps, parseHevcSps, } from '../codec-data.js';\nimport { Demuxer } from '../demuxer.js';\nimport { assert, binarySearchExact, binarySearchLessOrEqual, bytesToHexString, COLOR_PRIMARIES_MAP_INVERSE, findLastIndex, IDENTITY_MATRIX, isIso639Dash2LanguageCode, isThenable, last, MATRIX_COEFFICIENTS_MAP_INVERSE, multiplyMatrices, textDecoder, TRANSFER_CHARACTERISTICS_MAP_INVERSE, UNDETERMINED_LANGUAGE, toDataView, roundIfAlmostInteger, hexStringToBytes, HEX_STRING_REGEX, EMPTY_COLOR_SPACE, colorSpaceIsComplete, } from '../misc.js';\nimport { EncodedPacket, PLACEHOLDER_DATA } from '../packet.js';\nimport { buildIsobmffMimeType, parsePsshBoxContents, psshBoxesAreEqual } from './isobmff-misc.js';\nimport { MAX_BOX_HEADER_SIZE, MIN_BOX_HEADER_SIZE, readBoxHeader, readDataBox, readFixed_16_16, readFixed_2_30, readEsDescriptor, readMetadataStringShort, } from './isobmff-reader.js';\nimport { readBytes, readF64Be, readI16Be, readI32Be, readI64Be, readU16Be, readU24Be, readU32Be, readU64Be, readU8, readAscii, } from '../reader.js';\nimport { DEFAULT_TRACK_DISPOSITION, RichImageData } from '../metadata.js';\nimport { AC3_SAMPLE_RATES } from '../../shared/ac3-misc.js';\nimport { Bitstream } from '../../shared/bitstream.js';\nimport { Aes128CbcContext } from '../aes.js';\nimport { Logging } from '../logging.js';\n// Anything beyond this is malicious\nconst MAX_BOX_NESTING_DEPTH = 64;\nexport class IsobmffDemuxer extends Demuxer {\n    constructor(input) {\n        super(input);\n        this.moovSlice = null;\n        this.currentTrack = null;\n        this.tracks = [];\n        this.idToTrack = new Map();\n        this.metadataPromise = null;\n        this.movieTimescale = -1;\n        this.movieDurationInTimescale = -1;\n        this.movieMatrix = IDENTITY_MATRIX;\n        this.isQuickTime = false;\n        this.metadataTags = {};\n        this.currentMetadataKeys = null;\n        this.isFragmented = false;\n        this.fragmentTrackDefaults = new Map();\n        this.psshBoxes = [];\n        this.currentFragment = null;\n        this.isReadingTraf = false;\n        /**\n         * Caches the last fragment that was read. Based on the assumption that there will be multiple reads to the\n         * same fragment in quick succession.\n         */\n        this.lastReadFragment = null;\n        this.fragmentSummaries = new Map(); // Keyed by moof offset\n        this.decryptionKeyCache = new Map();\n        this.boxNestingDepth = 0;\n        this.reader = input._reader;\n    }\n    async getTrackBackings() {\n        await this.readMetadata();\n        return this.tracks.map(track => track.trackBacking);\n    }\n    async getMimeType() {\n        await this.readMetadata();\n        const backings = await this.getTrackBackings();\n        const codecStrings = await Promise.all(backings.map(x => x.getDecoderConfig().then(c => c?.codec ?? null)));\n        return buildIsobmffMimeType({\n            isQuickTime: this.isQuickTime,\n            hasVideo: this.tracks.some(x => x.info?.type === 'video'),\n            hasAudio: this.tracks.some(x => x.info?.type === 'audio'),\n            codecStrings: codecStrings.filter(Boolean),\n        });\n    }\n    async getMetadataTags() {\n        await this.readMetadata();\n        return this.metadataTags;\n    }\n    readMetadata() {\n        return this.metadataPromise ??= (async () => {\n            let currentPos = 0;\n            let lookForMfraBox = false;\n            let foundMovieBoxes = false;\n            while (true) {\n                let slice = this.reader.requestSliceRange(currentPos, MIN_BOX_HEADER_SIZE, MAX_BOX_HEADER_SIZE);\n                if (isThenable(slice))\n                    slice = await slice;\n                if (!slice)\n                    break;\n                const startPos = currentPos;\n                const boxInfo = readBoxHeader(slice);\n                if (!boxInfo) {\n                    break;\n                }\n                if ((boxInfo.name === 'ftyp' || boxInfo.name === 'styp') && slice.remainingLength >= 4) {\n                    const majorBrand = readAscii(slice, 4);\n                    this.isQuickTime = majorBrand === 'qt  ';\n                }\n                else if (boxInfo.name === 'moov') {\n                    // Found moov, load it\n                    let moovSlice = this.reader.requestSlice(slice.filePos, boxInfo.contentSize);\n                    if (isThenable(moovSlice))\n                        moovSlice = await moovSlice;\n                    if (!moovSlice)\n                        break;\n                    this.moovSlice = moovSlice;\n                    this.readContiguousBoxes(this.moovSlice);\n                    if (this.movieTimescale === -1) {\n                        throw new Error('Invalid moov box: missing mvhd box.');\n                    }\n                    for (const track of this.tracks) {\n                        // Modify the edit list offset based on the previous segment durations. They are in different\n                        // timescales, so we first convert to seconds and then into the track timescale.\n                        const previousSegmentDurationsInSeconds = track.editListPreviousSegmentDurations / this.movieTimescale;\n                        track.editListOffset -= Math.round(previousSegmentDurationsInSeconds * track.timescale);\n                    }\n                    lookForMfraBox = this.isFragmented\n                        && this.reader.fileSize !== null\n                        && this.reader.fileSize > startPos + boxInfo.totalSize; // There's more after the moov box\n                    foundMovieBoxes = true;\n                    break;\n                }\n                else if (boxInfo.name === 'moof') {\n                    if (!this.input._initInput) {\n                        throw new Error('\"moof\" box encountered with no \"moov\" box present; this file is likely a Segment as'\n                            + ' described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a \"moov\"'\n                            + ' box is required to read this file, please provide it using InputOptions.initInput.');\n                    }\n                    await this.copyMetadataFromInitInput(this.input._initInput);\n                    lookForMfraBox = false; // No point in doing it for segment files\n                    foundMovieBoxes = true;\n                    break;\n                }\n                currentPos = startPos + boxInfo.totalSize;\n            }\n            if (!foundMovieBoxes && this.input._initInput) {\n                // A segment file is allowed to hold zero fragments, in which case there's no moof box to key off of.\n                // It's still a perfectly valid segment, so let's take the tracks from the init input.\n                await this.copyMetadataFromInitInput(this.input._initInput);\n            }\n            if (lookForMfraBox) {\n                assert(this.reader.fileSize !== null);\n                // The last 4 bytes may contain the size of the mfra box at the end of the file\n                let lastWordSlice = this.reader.requestSlice(this.reader.fileSize - 4, 4);\n                if (isThenable(lastWordSlice))\n                    lastWordSlice = await lastWordSlice;\n                assert(lastWordSlice);\n                const lastWord = readU32Be(lastWordSlice);\n                const potentialMfraPos = this.reader.fileSize - lastWord;\n                if (potentialMfraPos >= 0 && potentialMfraPos <= this.reader.fileSize - MAX_BOX_HEADER_SIZE) {\n                    let mfraHeaderSlice = this.reader.requestSliceRange(potentialMfraPos, MIN_BOX_HEADER_SIZE, MAX_BOX_HEADER_SIZE);\n                    if (isThenable(mfraHeaderSlice))\n                        mfraHeaderSlice = await mfraHeaderSlice;\n                    if (mfraHeaderSlice) {\n                        const boxInfo = readBoxHeader(mfraHeaderSlice);\n                        if (boxInfo && boxInfo.name === 'mfra') {\n                            // We found the mfra box, allowing for much better random access. Let's parse it.\n                            let mfraSlice = this.reader.requestSlice(mfraHeaderSlice.filePos, boxInfo.contentSize);\n                            if (isThenable(mfraSlice))\n                                mfraSlice = await mfraSlice;\n                            if (mfraSlice) {\n                                this.readContiguousBoxes(mfraSlice);\n                            }\n                        }\n                    }\n                }\n            }\n            for (const track of this.tracks) {\n                // Sort by timestamp in case it's not naturally sorted, and remove multiple entries for the same time\n                const table = track.fragmentLookupTable;\n                table.sort((a, b) => a.timestamp - b.timestamp);\n                let writeIndex = 0;\n                for (const entry of table) {\n                    if (writeIndex === 0 || entry.timestamp !== table[writeIndex - 1].timestamp) {\n                        table[writeIndex++] = entry;\n                    }\n                }\n                table.length = writeIndex;\n            }\n        })();\n    }\n    async copyMetadataFromInitInput(initInput) {\n        const initDemuxer = (await initInput._getDemuxer());\n        if (initDemuxer.constructor !== IsobmffDemuxer) {\n            throw new Error('Init input must match the input\\'s format.');\n        }\n        await initDemuxer.readMetadata();\n        this.movieTimescale = initDemuxer.movieTimescale;\n        this.movieDurationInTimescale = initDemuxer.movieDurationInTimescale;\n        this.movieMatrix = initDemuxer.movieMatrix;\n        this.metadataTags = initDemuxer.metadataTags;\n        this.isFragmented = true;\n        this.fragmentTrackDefaults = initDemuxer.fragmentTrackDefaults;\n        this.psshBoxes = initDemuxer.psshBoxes;\n        // Create tracks from the init input's tracks\n        for (const foreignTrack of initDemuxer.tracks) {\n            const track = {\n                id: foreignTrack.id,\n                demuxer: this,\n                trackBacking: null,\n                disposition: foreignTrack.disposition,\n                timescale: foreignTrack.timescale,\n                durationInMediaTimescale: foreignTrack.durationInMediaTimescale,\n                durationInMovieTimescale: foreignTrack.durationInMovieTimescale,\n                matrix: foreignTrack.matrix,\n                internalCodecId: foreignTrack.internalCodecId,\n                name: foreignTrack.name,\n                languageCode: foreignTrack.languageCode,\n                sampleTableByteOffset: null,\n                sampleTable: null,\n                fragmentLookupTable: [],\n                currentFragmentState: null,\n                fragmentPositionCache: [],\n                editListPreviousSegmentDurations: foreignTrack.editListPreviousSegmentDurations,\n                editListOffset: foreignTrack.editListOffset,\n                encryptionInfo: foreignTrack.encryptionInfo,\n                encryptionAuxInfo: null,\n                frmaCodecString: null,\n                maxBitrate: foreignTrack.maxBitrate,\n                avgBitrate: foreignTrack.avgBitrate,\n                info: foreignTrack.info,\n            };\n            if (foreignTrack.trackBacking) {\n                assert(track.info);\n                if (track.info.type === 'video' && track.info.width !== -1) {\n                    const videoTrack = track;\n                    track.trackBacking = new IsobmffVideoTrackBacking(videoTrack);\n                    this.tracks.push(track);\n                    this.idToTrack.set(track.id, track);\n                }\n                else if (track.info.type === 'audio' && track.info.numberOfChannels !== -1) {\n                    const audioTrack = track;\n                    track.trackBacking = new IsobmffAudioTrackBacking(audioTrack);\n                    this.tracks.push(track);\n                    this.idToTrack.set(track.id, track);\n                }\n            }\n            else {\n                // The track didn't have enough info to warrant a backing\n            }\n        }\n    }\n    getSampleTableForTrack(internalTrack) {\n        if (internalTrack.sampleTable) {\n            return internalTrack.sampleTable;\n        }\n        const sampleTable = {\n            sampleTimingEntries: [],\n            sampleCompositionTimeOffsets: [],\n            sampleSizes: [],\n            sampleCount: 0,\n            cumulativeSampleSizes: null,\n            keySampleIndices: null,\n            chunkOffsets: [],\n            sampleToChunk: [],\n            sortedCompositionTimeOffsets: null,\n        };\n        internalTrack.sampleTable = sampleTable;\n        if (internalTrack.sampleTableByteOffset === null) {\n            // There's no sample table to read, it's in another file (happens with segments)\n            return sampleTable;\n        }\n        assert(this.moovSlice);\n        const stblContainerSlice = this.moovSlice.slice(internalTrack.sampleTableByteOffset);\n        this.currentTrack = internalTrack;\n        try {\n            this.traverseBox(stblContainerSlice);\n        }\n        catch (error) {\n            internalTrack.sampleTable = null;\n            throw error;\n        }\n        finally {\n            this.currentTrack = null;\n        }\n        const lastTimingEntry = last(sampleTable.sampleTimingEntries);\n        const lastChunkEntryIndex = binarySearchLessOrEqual(sampleTable.sampleToChunk, sampleTable.chunkOffsets.length - 1, x => x.startChunkIndex);\n        const lastChunkEntry = sampleTable.sampleToChunk[lastChunkEntryIndex];\n        // Clamp the sample count on the minimum of what all the subentries tell us\n        sampleTable.sampleCount = Math.min(sampleTable.sampleCount, lastTimingEntry ? lastTimingEntry.startIndex + lastTimingEntry.count : 0, lastChunkEntry\n            ? lastChunkEntry.startSampleIndex\n                + (sampleTable.chunkOffsets.length - lastChunkEntry.startChunkIndex) * lastChunkEntry.samplesPerChunk\n            : 0);\n        capEntryCounts(sampleTable.sampleTimingEntries, sampleTable.sampleCount);\n        capEntryCounts(sampleTable.sampleCompositionTimeOffsets, sampleTable.sampleCount);\n        const isPcmCodec = internalTrack.info?.type === 'audio'\n            && internalTrack.info.codec\n            && PCM_AUDIO_CODECS.includes(internalTrack.info.codec);\n        if (isPcmCodec\n            && sampleTable.sampleCompositionTimeOffsets.length === 0\n            && sampleTable.sampleTimingEntries.length > 0) {\n            // If the audio has PCM samples, the way the samples are defined in the sample table is somewhat\n            // suboptimal: Each individual audio sample is its own sample, meaning we can have 48000 samples per second.\n            // Because we treat each sample as its own atomic unit that can be decoded, this would lead to a huge\n            // amount of very short samples for PCM audio. So instead, we make a transformation: If the audio is in PCM,\n            // we say that each chunk (that normally holds many samples) now is one big sample. We can this because\n            // the samples in the chunk are contiguous and the format is PCM, so the entire chunk as one thing still\n            // encodes valid audio information.\n            assert(internalTrack.info?.type === 'audio');\n            const pcmInfo = parsePcmCodec(internalTrack.info.codec);\n            const newSampleTimingEntries = [];\n            const newSampleSizes = [];\n            for (let i = 0; i < sampleTable.sampleToChunk.length; i++) {\n                const chunkEntry = sampleTable.sampleToChunk[i];\n                const nextEntry = sampleTable.sampleToChunk[i + 1];\n                const chunkCount = Math.min(nextEntry ? nextEntry.startChunkIndex : Infinity, sampleTable.chunkOffsets.length) - chunkEntry.startChunkIndex;\n                const newStartSampleIndex = newSampleSizes.length;\n                for (let j = 0; j < chunkCount; j++) {\n                    const startSampleIndex = chunkEntry.startSampleIndex + j * chunkEntry.samplesPerChunk;\n                    const endSampleIndex = startSampleIndex + chunkEntry.samplesPerChunk; // Exclusive, outside of chunk\n                    const startTimingEntryIndex = binarySearchLessOrEqual(sampleTable.sampleTimingEntries, startSampleIndex, x => x.startIndex);\n                    const startTimingEntry = sampleTable.sampleTimingEntries[startTimingEntryIndex];\n                    const endTimingEntryIndex = binarySearchLessOrEqual(sampleTable.sampleTimingEntries, endSampleIndex, x => x.startIndex);\n                    const endTimingEntry = sampleTable.sampleTimingEntries[endTimingEntryIndex];\n                    const firstSampleTimestamp = startTimingEntry.startDecodeTimestamp\n                        + (startSampleIndex - startTimingEntry.startIndex) * startTimingEntry.delta;\n                    const lastSampleTimestamp = endTimingEntry.startDecodeTimestamp\n                        + (endSampleIndex - endTimingEntry.startIndex) * endTimingEntry.delta;\n                    const delta = lastSampleTimestamp - firstSampleTimestamp;\n                    const lastSampleTimingEntry = last(newSampleTimingEntries);\n                    if (lastSampleTimingEntry && lastSampleTimingEntry.delta === delta) {\n                        lastSampleTimingEntry.count++;\n                    }\n                    else {\n                        // One sample for the entire chunk\n                        newSampleTimingEntries.push({\n                            startIndex: newSampleSizes.length,\n                            startDecodeTimestamp: firstSampleTimestamp,\n                            count: 1,\n                            delta,\n                        });\n                    }\n                    // Instead of determining the chunk's size by looping over the samples sizes in the sample table, we\n                    // can directly compute it as we know how many PCM frames are in this chunk, and the size of each\n                    // PCM frame. This also improves compatibility with some files which fail to write proper sample\n                    // size values into their sample tables in the PCM case.\n                    const chunkSize = chunkEntry.samplesPerChunk\n                        * pcmInfo.sampleSize\n                        * internalTrack.info.numberOfChannels;\n                    newSampleSizes.push(chunkSize);\n                }\n                // The new samples are numbered consecutively, even if the chunks don't start at the first one\n                chunkEntry.startSampleIndex = newStartSampleIndex;\n                chunkEntry.samplesPerChunk = 1;\n            }\n            sampleTable.sampleTimingEntries = newSampleTimingEntries;\n            sampleTable.sampleSizes = newSampleSizes;\n            sampleTable.sampleCount = newSampleSizes.length;\n        }\n        if (sampleTable.sampleCompositionTimeOffsets.length > 0) {\n            // Presentation order differs from decode order. Let's prepare the offset entries for timestamped-keyed\n            // random access later\n            const entries = sampleTable.sampleCompositionTimeOffsets;\n            const lastEntry = last(entries);\n            const coveredSampleCount = lastEntry.startIndex + lastEntry.count;\n            if (coveredSampleCount < sampleTable.sampleCount) {\n                // The remaining samples have no offset\n                entries.push({\n                    startIndex: coveredSampleCount,\n                    count: sampleTable.sampleCount - coveredSampleCount,\n                    offset: 0,\n                    startTimestamp: -1,\n                    lastTimestamp: -1,\n                    maxLastTimestamp: -1,\n                });\n            }\n            const sortedEntries = entries.filter(entry => entry.count > 0);\n            const timingEntries = sampleTable.sampleTimingEntries;\n            let timingEntryIndex = 0;\n            const getDecodeTimestampAhead = (sampleIndex) => {\n                while (timingEntryIndex + 1 < timingEntries.length\n                    && timingEntries[timingEntryIndex + 1].startIndex <= sampleIndex) {\n                    timingEntryIndex++;\n                }\n                const timingEntry = timingEntries[timingEntryIndex];\n                return timingEntry.startDecodeTimestamp + (sampleIndex - timingEntry.startIndex) * timingEntry.delta;\n            };\n            for (const entry of sortedEntries) {\n                const lastSampleIndex = entry.startIndex + entry.count - 1;\n                entry.startTimestamp = getDecodeTimestampAhead(entry.startIndex) + entry.offset;\n                entry.lastTimestamp = getDecodeTimestampAhead(lastSampleIndex) + entry.offset;\n            }\n            sortedEntries.sort((a, b) => a.startTimestamp - b.startTimestamp || a.startIndex - b.startIndex);\n            let maxLastTimestamp = -Infinity;\n            for (const entry of sortedEntries) {\n                maxLastTimestamp = Math.max(maxLastTimestamp, entry.lastTimestamp);\n                entry.maxLastTimestamp = maxLastTimestamp;\n            }\n            sampleTable.sortedCompositionTimeOffsets = sortedEntries;\n        }\n        else {\n            // If they're not defined, we can simply use the decode timestamps as presentation timestamps\n        }\n        if (sampleTable.sampleSizes.length > 1) {\n            sampleTable.cumulativeSampleSizes = [0];\n            for (let i = 0; i < sampleTable.sampleSizes.length; i++) {\n                sampleTable.cumulativeSampleSizes.push(sampleTable.cumulativeSampleSizes[i] + sampleTable.sampleSizes[i]);\n            }\n        }\n        return sampleTable;\n    }\n    async readFragment(startPos) {\n        if (this.lastReadFragment?.moofOffset === startPos) {\n            return this.lastReadFragment;\n        }\n        let headerSlice = this.reader.requestSliceRange(startPos, MIN_BOX_HEADER_SIZE, MAX_BOX_HEADER_SIZE);\n        if (isThenable(headerSlice))\n            headerSlice = await headerSlice;\n        assert(headerSlice);\n        const moofBoxInfo = readBoxHeader(headerSlice);\n        assert(moofBoxInfo?.name === 'moof');\n        let entireSlice = this.reader.requestSlice(startPos, moofBoxInfo.totalSize);\n        if (isThenable(entireSlice))\n            entireSlice = await entireSlice;\n        if (!entireSlice)\n            return null; // The moof box is cut off\n        this.traverseBox(entireSlice);\n        const fragment = this.lastReadFragment;\n        assert(fragment && fragment.moofOffset === startPos);\n        this.fragmentSummaries.set(startPos, {\n            moofSize: fragment.moofSize,\n            trackIds: new Set(fragment.trackData.keys()),\n        });\n        for (const [, trackData] of fragment.trackData) {\n            const track = trackData.track;\n            const { fragmentPositionCache } = track;\n            if (!trackData.startTimestampIsFinal) {\n                // It may be that some tracks don't define the base decode time, i.e. when the fragment begins. This\n                // we'll need to figure out the start timestamp another way. We'll compute the timestamp by accessing\n                // the lookup entries and fragment cache, which works out nicely with the lookup algorithm: If these\n                // exist, then the lookup will automatically start at the furthest possible point. If they don't, the\n                // lookup starts sequentially from the start, incrementally summing up all fragment durations. It's sort\n                // of implicit, but it ends up working nicely.\n                // The table is sorted by timestamp, which for any sane file means it's also sorted by offset\n                const lookupEntryIndex = binarySearchExact(track.fragmentLookupTable, fragment.moofOffset, x => x.moofOffset);\n                const lookupEntry = track.fragmentLookupTable[lookupEntryIndex];\n                const lookupEntryIsValid = lookupEntry\n                    && trackData.trunSampleCounts.length >= lookupEntry.trunNumber\n                    && trackData.trunSampleCounts[lookupEntry.trunNumber - 1] >= lookupEntry.sampleNumber;\n                if (lookupEntryIsValid) {\n                    // We ignore traf number here, since we've already matched based on track ID\n                    let sampleIndex = 0;\n                    for (let i = 1; i < lookupEntry.trunNumber; i++) {\n                        sampleIndex += trackData.trunSampleCounts[i - 1];\n                    }\n                    sampleIndex += lookupEntry.sampleNumber - 1;\n                    const sample = trackData.samples[sampleIndex];\n                    assert(sample); // Must hold due to the above range checks\n                    // The timestamp in the lookup entry describes the timestamp of the referenced sample\n                    const timestampOffset = lookupEntry.timestamp - sample.presentationTimestamp;\n                    offsetFragmentTrackDataByTimestamp(trackData, timestampOffset);\n                }\n                else {\n                    const lastCacheIndex = binarySearchLessOrEqual(fragmentPositionCache, fragment.moofOffset - 1, x => x.moofOffset);\n                    if (lastCacheIndex !== -1) {\n                        // Let's use the end timestamp of the previous fragment in the cache\n                        const lastCache = fragmentPositionCache[lastCacheIndex];\n                        offsetFragmentTrackDataByTimestamp(trackData, lastCache.endTimestamp);\n                    }\n                    else {\n                        // We're the first fragment I guess, \"offset by 0\"\n                    }\n                }\n                trackData.startTimestampIsFinal = true;\n            }\n            // Let's remember that a fragment with a given timestamp is here, speeding up future lookups if no\n            // lookup table exists\n            const insertionIndex = binarySearchLessOrEqual(fragmentPositionCache, trackData.startTimestamp, x => x.startTimestamp);\n            const previousEntry = fragmentPositionCache[insertionIndex];\n            const nextEntry = fragmentPositionCache[insertionIndex + 1];\n            // Only remember it if the timestamp order matches the moof offset order\n            if ((!previousEntry || previousEntry.moofOffset < fragment.moofOffset)\n                && (!nextEntry || nextEntry.moofOffset > fragment.moofOffset)) {\n                fragmentPositionCache.splice(insertionIndex + 1, 0, {\n                    moofOffset: fragment.moofOffset,\n                    startTimestamp: trackData.startTimestamp,\n                    endTimestamp: trackData.endTimestamp,\n                });\n            }\n            // If senc wasn't parsed but saiz+saio were, fetch the aux info now and stamp each sample with it\n            if (trackData.encryptionAuxInfo && track.encryptionInfo) {\n                const entries = await resolveEncryptionAuxInfo(this.reader, track.encryptionInfo, trackData.encryptionAuxInfo);\n                for (let i = 0; i < Math.min(trackData.samples.length, entries.length); i++) {\n                    const entry = entries[i];\n                    trackData.samples[i].encryption = entry;\n                }\n            }\n        }\n        return fragment;\n    }\n    readContiguousBoxes(slice) {\n        if (this.boxNestingDepth === MAX_BOX_NESTING_DEPTH) {\n            throw new Error('Invalid file: boxes are nested too deeply.');\n        }\n        const startIndex = slice.filePos;\n        this.boxNestingDepth++;\n        try {\n            while (slice.filePos - startIndex <= slice.length - MIN_BOX_HEADER_SIZE) {\n                const foundBox = this.traverseBox(slice);\n                if (!foundBox) {\n                    break;\n                }\n            }\n        }\n        finally {\n            this.boxNestingDepth--;\n        }\n    }\n    // eslint-disable-next-line @stylistic/generator-star-spacing\n    *iterateContiguousBoxes(slice) {\n        const startIndex = slice.filePos;\n        while (slice.filePos - startIndex <= slice.length - MIN_BOX_HEADER_SIZE) {\n            const startPos = slice.filePos;\n            const boxInfo = readBoxHeader(slice);\n            if (!boxInfo) {\n                break;\n            }\n            yield { boxInfo, slice };\n            slice.filePos = startPos + boxInfo.totalSize;\n        }\n    }\n    traverseBox(slice) {\n        const startPos = slice.filePos;\n        const boxInfo = readBoxHeader(slice);\n        if (!boxInfo) {\n            return false;\n        }\n        const contentStartPos = slice.filePos;\n        const boxEndPos = startPos + boxInfo.totalSize;\n        switch (boxInfo.name) {\n            case 'mdia':\n            case 'minf':\n            case 'dinf':\n            case 'mfra':\n            case 'edts':\n            case 'sinf':\n            case 'schi':\n                {\n                    this.readContiguousBoxes(slice.slice(contentStartPos, boxInfo.contentSize));\n                }\n                ;\n                break;\n            case 'mvhd':\n                {\n                    const version = readU8(slice);\n                    slice.skip(3); // Flags\n                    if (version === 1) {\n                        slice.skip(8 + 8);\n                        this.movieTimescale = readU32Be(slice);\n                        this.movieDurationInTimescale = readU64Be(slice);\n                    }\n                    else {\n                        slice.skip(4 + 4);\n                        this.movieTimescale = readU32Be(slice);\n                        this.movieDurationInTimescale = readU32Be(slice);\n                    }\n                    if (this.movieTimescale === 0) {\n                        throw new Error('Invalid mvhd box: timescale must not be 0.');\n                    }\n                    slice.skip(4 + 2 + 2 + 2 * 4); // Rate, volume, reserved\n                    this.movieMatrix = readMatrix(slice);\n                }\n                ;\n                break;\n            case 'trak':\n                {\n                    if (this.currentFragment || this.currentTrack) {\n                        break; // Misplaced\n                    }\n                    const track = {\n                        id: -1,\n                        demuxer: this,\n                        trackBacking: null,\n                        disposition: {\n                            ...DEFAULT_TRACK_DISPOSITION,\n                            primary: false,\n                        },\n                        info: null,\n                        timescale: -1,\n                        durationInMovieTimescale: -1,\n                        durationInMediaTimescale: -1,\n                        matrix: IDENTITY_MATRIX,\n                        internalCodecId: null,\n                        name: null,\n                        languageCode: UNDETERMINED_LANGUAGE,\n                        sampleTableByteOffset: -1,\n                        sampleTable: null,\n                        fragmentLookupTable: [],\n                        currentFragmentState: null,\n                        fragmentPositionCache: [],\n                        editListPreviousSegmentDurations: 0,\n                        editListOffset: 0,\n                        encryptionInfo: null,\n                        encryptionAuxInfo: null,\n                        frmaCodecString: null,\n                        maxBitrate: null,\n                        avgBitrate: null,\n                    };\n                    this.currentTrack = track;\n                    this.readContiguousBoxes(slice.slice(contentStartPos, boxInfo.contentSize));\n                    if (track.id !== -1\n                        && track.timescale !== -1\n                        && track.info !== null\n                        && track.sampleTableByteOffset !== -1) {\n                        if (track.info.type === 'video' && track.info.width !== -1) {\n                            const videoTrack = track;\n                            track.trackBacking = new IsobmffVideoTrackBacking(videoTrack);\n                            this.tracks.push(track);\n                            this.idToTrack.set(track.id, track);\n                        }\n                        else if (track.info.type === 'audio' && track.info.numberOfChannels !== -1) {\n                            const audioTrack = track;\n                            track.trackBacking = new IsobmffAudioTrackBacking(audioTrack);\n                            this.tracks.push(track);\n                            this.idToTrack.set(track.id, track);\n                        }\n                    }\n                    this.currentTrack = null;\n                }\n                ;\n                break;\n            case 'tkhd':\n                {\n                    const track = this.currentTrack;\n                    if (!track || this.currentFragment) {\n                        break;\n                    }\n                    const version = readU8(slice);\n                    const flags = readU24Be(slice);\n                    // Spec says disabled tracks are to be treated like they don't exist, but in practice, they are treated\n                    // more like non-default tracks.\n                    const trackEnabled = !!(flags & 0x1);\n                    track.disposition.default = trackEnabled;\n                    // Skip over creation & modification time to reach the track ID\n                    if (version === 0) {\n                        slice.skip(8);\n                        track.id = readU32Be(slice);\n                        slice.skip(4);\n                        track.durationInMovieTimescale = readU32Be(slice);\n                    }\n                    else if (version === 1) {\n                        slice.skip(16);\n                        track.id = readU32Be(slice);\n                        slice.skip(4);\n                        track.durationInMovieTimescale = readU64Be(slice);\n                    }\n                    else {\n                        throw new Error(`Incorrect track header version ${version}.`);\n                    }\n                    slice.skip(2 * 4 + 2 + 2 + 2 + 2);\n                    const trackMatrix = readMatrix(slice);\n                    // The track matrix maps into movie space, and the movie matrix then maps into the final output space\n                    track.matrix = multiplyMatrices(trackMatrix, this.movieMatrix);\n                }\n                ;\n                break;\n            case 'elst':\n                {\n                    const track = this.currentTrack;\n                    if (!track) {\n                        break;\n                    }\n                    const version = readU8(slice);\n                    slice.skip(3); // Flags\n                    let relevantEntryFound = false;\n                    let previousSegmentDurations = 0;\n                    const entryCount = readU32Be(slice);\n                    for (let i = 0; i < entryCount; i++) {\n                        const segmentDuration = version === 1\n                            ? readU64Be(slice)\n                            : readU32Be(slice);\n                        const mediaTime = version === 1\n                            ? readI64Be(slice)\n                            : readI32Be(slice);\n                        const mediaRate = readFixed_16_16(slice);\n                        if (relevantEntryFound) {\n                            Logging._warn('Unsupported edit list: multiple edits are not currently supported. Only using first edit.');\n                            break;\n                        }\n                        if (mediaTime === -1) {\n                            previousSegmentDurations += segmentDuration;\n                            continue;\n                        }\n                        if (mediaRate !== 1) {\n                            Logging._warn('Unsupported edit list entry: media rate must be 1.');\n                            break;\n                        }\n                        track.editListPreviousSegmentDurations = previousSegmentDurations;\n                        track.editListOffset = mediaTime;\n                        relevantEntryFound = true;\n                    }\n                }\n                ;\n                break;\n            case 'mdhd':\n                {\n                    const track = this.currentTrack;\n                    if (!track) {\n                        break;\n                    }\n                    const version = readU8(slice);\n                    slice.skip(3); // Flags\n                    if (version === 0) {\n                        slice.skip(8);\n                        track.timescale = readU32Be(slice);\n                        track.durationInMediaTimescale = readU32Be(slice);\n                    }\n                    else if (version === 1) {\n                        slice.skip(16);\n                        track.timescale = readU32Be(slice);\n                        track.durationInMediaTimescale = readU64Be(slice);\n                    }\n                    if (track.timescale === 0) {\n                        throw new Error('Invalid mdhd box: timescale must not be 0.');\n                    }\n                    let language = readU16Be(slice);\n                    if (language > 0) {\n                        track.languageCode = '';\n                        for (let i = 0; i < 3; i++) {\n                            track.languageCode = String.fromCharCode(0x60 + (language & 0b11111)) + track.languageCode;\n                            language >>= 5;\n                        }\n                        if (!isIso639Dash2LanguageCode(track.languageCode)) {\n                            // Sometimes the bytes are garbage\n                            track.languageCode = UNDETERMINED_LANGUAGE;\n                        }\n                    }\n                }\n                ;\n                break;\n            case 'hdlr':\n                {\n                    const track = this.currentTrack;\n                    if (!track) {\n                        break;\n                    }\n                    slice.skip(8); // Version + flags + pre-defined\n                    const handlerType = readAscii(slice, 4);\n                    if (handlerType === 'vide') {\n                        track.info = {\n                            type: 'video',\n                            width: -1,\n                            height: -1,\n                            squarePixelWidth: -1,\n                            squarePixelHeight: -1,\n                            codec: null,\n                            codecDescription: null,\n                            colorSpace: { ...EMPTY_COLOR_SPACE },\n                            avcType: null,\n                            avcCodecInfo: null,\n                            hevcCodecInfo: null,\n                            vp9CodecInfo: null,\n                            av1CodecInfo: null,\n                            proresCodecInfo: null,\n                            proresFormat: null,\n                        };\n                    }\n                    else if (handlerType === 'soun') {\n                        track.info = {\n                            type: 'audio',\n                            numberOfChannels: -1,\n                            sampleRate: -1,\n                            codec: null,\n                            codecDescription: null,\n                            aacCodecInfo: null,\n                            dtsFormat: null,\n                            pcmLittleEndian: false,\n                            pcmSampleSize: null,\n                        };\n                    }\n                }\n                ;\n                break;\n            case 'stbl':\n                {\n                    const track = this.currentTrack;\n                    if (!track) {\n                        break;\n                    }\n                    track.sampleTableByteOffset = startPos;\n                    this.readContiguousBoxes(slice.slice(contentStartPos, boxInfo.contentSize));\n                }\n                ;\n                break;\n            case 'stsd':\n                {\n                    const track = this.currentTrack;\n                    if (!track) {\n                        break;\n                    }\n                    if (track.info === null || track.sampleTable) {\n                        break;\n                    }\n                    const stsdVersion = readU8(slice);\n                    slice.skip(3); // Flags\n                    const entries = readU32Be(slice);\n                    for (let i = 0; i < entries; i++) {\n                        const sampleBoxStartPos = slice.filePos;\n                        const sampleBoxInfo = readBoxHeader(slice);\n                        if (!sampleBoxInfo) {\n                            break;\n                        }\n                        track.internalCodecId = sampleBoxInfo.name;\n                        const lowercaseBoxName = sampleBoxInfo.name.toLowerCase();\n                        if (track.info.type === 'video') {\n                            slice.skip(6 * 1 + 2 + 2 + 2 + 3 * 4);\n                            track.info.width = readU16Be(slice);\n                            track.info.height = readU16Be(slice);\n                            track.info.squarePixelWidth = track.info.width;\n                            track.info.squarePixelHeight = track.info.height;\n                            slice.skip(4 + 4 + 4 + 2 + 32 + 2 + 2);\n                            track.frmaCodecString = null;\n                            this.readContiguousBoxes(slice.slice(slice.filePos, (sampleBoxStartPos + sampleBoxInfo.totalSize) - slice.filePos));\n                            const codecName = lowercaseBoxName === 'encv'\n                                ? track.frmaCodecString\n                                : lowercaseBoxName;\n                            track.frmaCodecString = null;\n                            if (codecName === 'avc1' || codecName === 'avc3') {\n                                track.info.codec = 'avc';\n                                track.info.avcType = codecName === 'avc1' ? 1 : 3;\n                            }\n                            else if (codecName === 'hvc1' || codecName === 'hev1') {\n                                track.info.codec = 'hevc';\n                            }\n                            else if (codecName === 'vp08') {\n                                track.info.codec = 'vp8';\n                            }\n                            else if (codecName === 'vp09') {\n                                track.info.codec = 'vp9';\n                            }\n                            else if (codecName === 'av01') {\n                                track.info.codec = 'av1';\n                            }\n                            else if (PRORES_FOURCCS.includes(lowercaseBoxName)) {\n                                track.info.codec = 'prores';\n                                track.info.proresFormat = lowercaseBoxName;\n                            }\n                            else if (codecName === null) {\n                                Logging._warn(`Unknown encrypted video codec due to missing frma box.`);\n                            }\n                            else {\n                                Logging._warn(`Unsupported video codec (sample entry type '${sampleBoxInfo.name}').`);\n                            }\n                        }\n                        else {\n                            slice.skip(6 * 1 + 2);\n                            const version = readU16Be(slice);\n                            slice.skip(3 * 2);\n                            let channelCount = readU16Be(slice);\n                            let sampleSize = readU16Be(slice);\n                            slice.skip(2 * 2);\n                            // Can't use fixed16_16 as that's signed\n                            let sampleRate = readU32Be(slice) / 0x10000;\n                            let lpcmFlags = null;\n                            if (stsdVersion === 0 && version > 0) {\n                                // Additional QuickTime fields\n                                if (version === 1) {\n                                    slice.skip(4);\n                                    sampleSize = 8 * readU32Be(slice);\n                                    slice.skip(2 * 4);\n                                }\n                                else if (version === 2) {\n                                    slice.skip(4);\n                                    sampleRate = readF64Be(slice);\n                                    channelCount = readU32Be(slice);\n                                    slice.skip(4); // Always 0x7f000000\n                                    sampleSize = readU32Be(slice);\n                                    lpcmFlags = readU32Be(slice);\n                                    slice.skip(2 * 4);\n                                }\n                            }\n                            track.info.numberOfChannels = channelCount;\n                            track.info.sampleRate = sampleRate;\n                            track.frmaCodecString = null;\n                            this.readContiguousBoxes(slice.slice(slice.filePos, (sampleBoxStartPos + sampleBoxInfo.totalSize) - slice.filePos));\n                            const codecName = lowercaseBoxName === 'enca'\n                                ? track.frmaCodecString\n                                : lowercaseBoxName;\n                            track.frmaCodecString = null;\n                            // developer.apple.com/documentation/quicktime-file-format/sound_sample_descriptions/\n                            if (codecName === 'mp4a') {\n                                // The codec is set by the esds box\n                            }\n                            else if (codecName === 'opus') {\n                                track.info.codec = 'opus';\n                                track.info.sampleRate = OPUS_SAMPLE_RATE; // Always the same\n                            }\n                            else if (codecName === 'flac') {\n                                track.info.codec = 'flac';\n                            }\n                            else if (codecName === 'ulaw') {\n                                track.info.codec = 'ulaw';\n                            }\n                            else if (codecName === 'alaw') {\n                                track.info.codec = 'alaw';\n                            }\n                            else if (codecName === 'ac-3') {\n                                track.info.codec = 'ac3';\n                            }\n                            else if (codecName === 'ec-3') {\n                                track.info.codec = 'eac3';\n                            }\n                            else if (DTS_FOURCCS.includes(codecName)) {\n                                track.info.codec = 'dts';\n                                track.info.dtsFormat = codecName;\n                            }\n                            else if (codecName === 'twos') {\n                                if (sampleSize === 8) {\n                                    track.info.codec = 'pcm-s8';\n                                }\n                                else if (sampleSize === 16) {\n                                    track.info.codec = track.info.pcmLittleEndian ? 'pcm-s16' : 'pcm-s16be';\n                                }\n                                else {\n                                    Logging._warn(`Unsupported sample size ${sampleSize} for codec 'twos'.`);\n                                    track.info.codec = null;\n                                }\n                            }\n                            else if (codecName === 'sowt') {\n                                if (sampleSize === 8) {\n                                    track.info.codec = 'pcm-s8';\n                                }\n                                else if (sampleSize === 16) {\n                                    track.info.codec = 'pcm-s16';\n                                }\n                                else {\n                                    Logging._warn(`Unsupported sample size ${sampleSize} for codec 'sowt'.`);\n                                    track.info.codec = null;\n                                }\n                            }\n                            else if (codecName === 'raw ') {\n                                track.info.codec = 'pcm-u8';\n                            }\n                            else if (codecName === 'in24') {\n                                track.info.codec = track.info.pcmLittleEndian ? 'pcm-s24' : 'pcm-s24be';\n                            }\n                            else if (codecName === 'in32') {\n                                track.info.codec = track.info.pcmLittleEndian ? 'pcm-s32' : 'pcm-s32be';\n                            }\n                            else if (codecName === 'fl32') {\n                                track.info.codec = track.info.pcmLittleEndian ? 'pcm-f32' : 'pcm-f32be';\n                            }\n                            else if (codecName === 'fl64') {\n                                track.info.codec = track.info.pcmLittleEndian ? 'pcm-f64' : 'pcm-f64be';\n                            }\n                            else if (codecName === 'ipcm') {\n                                const pcmSampleSize = track.info.pcmSampleSize;\n                                if (track.info.pcmLittleEndian) {\n                                    if (pcmSampleSize === 16) {\n                                        track.info.codec = 'pcm-s16';\n                                    }\n                                    else if (pcmSampleSize === 24) {\n                                        track.info.codec = 'pcm-s24';\n                                    }\n                                    else if (pcmSampleSize === 32) {\n                                        track.info.codec = 'pcm-s32';\n                                    }\n                                    else {\n                                        Logging._warn(`Invalid ipcm sample size ${pcmSampleSize}.`);\n                                        track.info.codec = null;\n                                    }\n                                }\n                                else {\n                                    if (pcmSampleSize === 16) {\n                                        track.info.codec = 'pcm-s16be';\n                                    }\n                                    else if (pcmSampleSize === 24) {\n                                        track.info.codec = 'pcm-s24be';\n                                    }\n                                    else if (pcmSampleSize === 32) {\n                                        track.info.codec = 'pcm-s32be';\n                                    }\n                                    else {\n                                        Logging._warn(`Invalid ipcm sample size ${pcmSampleSize}.`);\n                                        track.info.codec = null;\n                                    }\n                                }\n                            }\n                            else if (codecName === 'fpcm') {\n                                const pcmSampleSize = track.info.pcmSampleSize;\n                                if (track.info.pcmLittleEndian) {\n                                    if (pcmSampleSize === 32) {\n                                        track.info.codec = 'pcm-f32';\n                                    }\n                                    else if (pcmSampleSize === 64) {\n                                        track.info.codec = 'pcm-f64';\n                                    }\n                                    else {\n                                        Logging._warn(`Invalid fpcm sample size ${pcmSampleSize}.`);\n                                        track.info.codec = null;\n                                    }\n                                }\n                                else {\n                                    if (pcmSampleSize === 32) {\n                                        track.info.codec = 'pcm-f32be';\n                                    }\n                                    else if (pcmSampleSize === 64) {\n                                        track.info.codec = 'pcm-f64be';\n                                    }\n                                    else {\n                                        Logging._warn(`Invalid fpcm sample size ${pcmSampleSize}.`);\n                                        track.info.codec = null;\n                                    }\n                                }\n                            }\n                            else if (codecName === 'lpcm' && lpcmFlags !== null) {\n                                const bytesPerSample = (sampleSize + 7) >> 3;\n                                const isFloat = Boolean(lpcmFlags & 1);\n                                const isBigEndian = Boolean(lpcmFlags & 2);\n                                const sFlags = lpcmFlags & 4 ? -1 : 0; // I guess it means \"signed flags\" or something?\n                                if (sampleSize > 0 && sampleSize <= 64) {\n                                    if (isFloat) {\n                                        if (sampleSize === 32) {\n                                            track.info.codec = isBigEndian ? 'pcm-f32be' : 'pcm-f32';\n                                        }\n                                    }\n                                    else {\n                                        if (sFlags & (1 << (bytesPerSample - 1))) {\n                                            if (bytesPerSample === 1) {\n                                                track.info.codec = 'pcm-s8';\n                                            }\n                                            else if (bytesPerSample === 2) {\n                                                track.info.codec = isBigEndian ? 'pcm-s16be' : 'pcm-s16';\n                                            }\n                                            else if (bytesPerSample === 3) {\n                                                track.info.codec = isBigEndian ? 'pcm-s24be' : 'pcm-s24';\n                                            }\n                                            else if (bytesPerSample === 4) {\n                                                track.info.codec = isBigEndian ? 'pcm-s32be' : 'pcm-s32';\n                                            }\n                                        }\n                                        else {\n                                            if (bytesPerSample === 1) {\n                                                track.info.codec = 'pcm-u8';\n                                            }\n                                        }\n                                    }\n                                }\n                                if (track.info.codec === null) {\n                                    Logging._warn('Unsupported PCM format.');\n                                }\n                            }\n                            else if (codecName === null) {\n                                Logging._warn(`Unknown encrypted audio codec due to missing frma box.`);\n                            }\n                            else {\n                                Logging._warn(`Unsupported audio codec (sample entry type '${sampleBoxInfo.name}').`);\n                            }\n                        }\n                        slice.filePos = sampleBoxStartPos + sampleBoxInfo.totalSize;\n                    }\n                }\n                ;\n                break;\n            case 'frma':\n                {\n                    const track = this.currentTrack;\n                    if (!track) {\n                        break;\n                    }\n                    const format = readAscii(slice, 4);\n                    const lowercase = format.toLowerCase();\n                    // Tells us what codec the encrypted track actually uses\n                    track.frmaCodecString = lowercase;\n                }\n                ;\n                break;\n            case 'schm':\n                {\n                    const track = this.currentTrack;\n                    if (!track) {\n                        break;\n                    }\n                    slice.skip(4); // Version + flags\n                    const schemeType = readAscii(slice, 4);\n                    if (schemeType === 'cenc' || schemeType === 'cens' || schemeType === 'cbcs') {\n                        track.encryptionInfo = {\n                            scheme: schemeType,\n                            defaultKid: null,\n                            defaultIsProtected: null,\n                            defaultPerSampleIvSize: null,\n                            defaultConstantIv: null,\n                            defaultCryptByteBlock: null,\n                            defaultSkipByteBlock: null,\n                        };\n                    }\n                    else {\n                        Logging._warn(`Unsupported encryption scheme '${schemeType}'.`);\n                    }\n                }\n                ;\n                break;\n            case 'tenc':\n                {\n                    const track = this.currentTrack;\n                    if (!track || !track.encryptionInfo) {\n                        break;\n                    }\n                    const version = readU8(slice);\n                    slice.skip(3); // Flags\n                    slice.skip(1); // Reserved\n                    const patternByte = readU8(slice);\n                    if (version > 0) {\n                        track.encryptionInfo.defaultCryptByteBlock = patternByte >> 4;\n                        track.encryptionInfo.defaultSkipByteBlock = patternByte & 0xf;\n                    }\n                    else {\n                        track.encryptionInfo.defaultCryptByteBlock = 0;\n                        track.encryptionInfo.defaultSkipByteBlock = 0;\n                    }\n                    track.encryptionInfo.defaultIsProtected = readU8(slice) !== 0;\n                    track.encryptionInfo.defaultPerSampleIvSize = readU8(slice);\n                    track.encryptionInfo.defaultKid = bytesToHexString(readBytes(slice, 16));\n                    if (track.encryptionInfo.defaultPerSampleIvSize > 16) {\n                        throw new Error('Invalid tenc box: IV size must not exceed 16 bytes.');\n                    }\n                    if (track.encryptionInfo.defaultIsProtected && track.encryptionInfo.defaultPerSampleIvSize === 0) {\n                        const constantIvSize = readU8(slice);\n                        if (constantIvSize > 16) {\n                            throw new Error('Invalid tenc box: IV size must not exceed 16 bytes.');\n                        }\n                        const constantIv = new Uint8Array(16);\n                        constantIv.set(readBytes(slice, constantIvSize), 0);\n                        track.encryptionInfo.defaultConstantIv = constantIv;\n                    }\n                }\n                ;\n                break;\n            case 'avcC':\n                {\n                    const track = this.currentTrack;\n                    if (!track || track.info?.type !== 'video') {\n                        break;\n                    }\n                    if (boxInfo.contentSize === 0) {\n                        // avcC box is empty, let's treat this like an Annex B stream\n                        break;\n                    }\n                    track.info.codecDescription = readBytes(slice, boxInfo.contentSize);\n                    const sps = deserializeAvcDecoderConfigurationRecord(track.info.codecDescription)\n                        ?.sequenceParameterSets[0];\n                    const spsInfo = sps && parseAvcSps(sps);\n                    if (spsInfo) {\n                        applySpsPixelAspectRatio(track, spsInfo.pixelAspectRatio);\n                    }\n                }\n                ;\n                break;\n            case 'hvcC':\n                {\n                    const track = this.currentTrack;\n                    if (!track || track.info?.type !== 'video') {\n                        break;\n                    }\n                    if (boxInfo.contentSize === 0) {\n                        // hvcC box is empty, let's treat this like an Annex B stream\n                        break;\n                    }\n                    track.info.codecDescription = readBytes(slice, boxInfo.contentSize);\n                    const sps = deserializeHevcDecoderConfigurationRecord(track.info.codecDescription)\n                        ?.arrays.find(x => x.nalUnitType === HevcNalUnitType.SPS_NUT)?.nalUnits[0];\n                    const spsInfo = sps && parseHevcSps(sps);\n                    if (spsInfo) {\n                        applySpsPixelAspectRatio(track, spsInfo.pixelAspectRatio);\n                    }\n                }\n                ;\n                break;\n            case 'vpcC':\n                {\n                    const track = this.currentTrack;\n                    if (!track || track.info?.type !== 'video') {\n                        break;\n                    }\n                    slice.skip(4); // Version + flags\n                    const profile = readU8(slice);\n                    const level = readU8(slice);\n                    const thirdByte = readU8(slice);\n                    const bitDepth = thirdByte >> 4;\n                    const chromaSubsampling = (thirdByte >> 1) & 0b111;\n                    const videoFullRangeFlag = thirdByte & 1;\n                    const colourPrimaries = readU8(slice);\n                    const transferCharacteristics = readU8(slice);\n                    const matrixCoefficients = readU8(slice);\n                    track.info.vp9CodecInfo = {\n                        profile,\n                        level,\n                        bitDepth,\n                        chromaSubsampling,\n                        videoFullRangeFlag,\n                        colourPrimaries,\n                        transferCharacteristics,\n                        matrixCoefficients,\n                    };\n                }\n                ;\n                break;\n            case 'av1C':\n                {\n                    const track = this.currentTrack;\n                    if (!track || track.info?.type !== 'video') {\n                        break;\n                    }\n                    slice.skip(1); // Marker + version\n                    const secondByte = readU8(slice);\n                    const profile = secondByte >> 5;\n                    const level = secondByte & 0b11111;\n                    const thirdByte = readU8(slice);\n                    const tier = thirdByte >> 7;\n                    const highBitDepth = (thirdByte >> 6) & 1;\n                    const twelveBit = (thirdByte >> 5) & 1;\n                    const monochrome = (thirdByte >> 4) & 1;\n                    const chromaSubsamplingX = (thirdByte >> 3) & 1;\n                    const chromaSubsamplingY = (thirdByte >> 2) & 1;\n                    const chromaSamplePosition = thirdByte & 0b11;\n                    // Logic from https://aomediacodec.github.io/av1-spec/av1-spec.pdf\n                    const bitDepth = profile === 2 && highBitDepth ? (twelveBit ? 12 : 10) : (highBitDepth ? 10 : 8);\n                    slice.skip(1); // Reserved bits + initial presentation delay\n                    // Parse config OBUs if there are any\n                    const configObus = readBytes(slice, boxInfo.contentSize - 4);\n                    const configObuInfo = extractAv1CodecInfoFromPacket(configObus);\n                    track.info.av1CodecInfo = {\n                        profile,\n                        level,\n                        tier,\n                        bitDepth,\n                        monochrome,\n                        chromaSubsamplingX,\n                        chromaSubsamplingY,\n                        chromaSamplePosition,\n                        videoFullRangeFlag: configObuInfo?.videoFullRangeFlag ?? 0,\n                        colourPrimaries: configObuInfo?.colourPrimaries ?? 2,\n                        transferCharacteristics: configObuInfo?.transferCharacteristics ?? 2,\n                        matrixCoefficients: configObuInfo?.matrixCoefficients ?? 2,\n                    };\n                }\n                ;\n                break;\n            case 'colr':\n                {\n                    const track = this.currentTrack;\n                    if (!track || track.info?.type !== 'video') {\n                        break;\n                    }\n                    const colourType = readAscii(slice, 4);\n                    if (colourType !== 'nclx' && colourType !== 'nclc') {\n                        break;\n                    }\n                    const colourPrimaries = readU16Be(slice);\n                    const transferCharacteristics = readU16Be(slice);\n                    const matrixCoefficients = readU16Be(slice);\n                    let fullRange = undefined;\n                    if (colourType === 'nclx') {\n                        fullRange = Boolean(readU8(slice) & 0x80);\n                    }\n                    track.info.colorSpace = {\n                        primaries: COLOR_PRIMARIES_MAP_INVERSE[colourPrimaries],\n                        transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[transferCharacteristics],\n                        matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[matrixCoefficients],\n                        fullRange,\n                    };\n                }\n                ;\n                break;\n            case 'pasp':\n                {\n                    const track = this.currentTrack;\n                    if (!track || track.info?.type !== 'video') {\n                        break;\n                    }\n                    const num = readU32Be(slice);\n                    const den = readU32Be(slice);\n                    // https://github.com/Vanilagy/mediabunny/issues/362\n                    if (num > 0 && den > 0) {\n                        // The ratio may already be set by the SPS, but the pasp box wins\n                        track.info.squarePixelWidth = track.info.width;\n                        track.info.squarePixelHeight = track.info.height;\n                        if (num > den) {\n                            track.info.squarePixelWidth = Math.round(track.info.width * num / den);\n                        }\n                        else {\n                            track.info.squarePixelHeight = Math.round(track.info.height * den / num);\n                        }\n                    }\n                }\n                ;\n                break;\n            case 'btrt':\n                {\n                    const track = this.currentTrack;\n                    if (!track) {\n                        break;\n                    }\n                    slice.skip(4); // Buffer size\n                    const maxBitrate = readU32Be(slice);\n                    const avgBitrate = readU32Be(slice);\n                    track.maxBitrate = maxBitrate > 0 ? maxBitrate : null;\n                    track.avgBitrate = avgBitrate > 0 ? avgBitrate : null;\n                }\n                ;\n                break;\n            case 'wave':\n                {\n                    this.readContiguousBoxes(slice.slice(contentStartPos, boxInfo.contentSize));\n                }\n                ;\n                break;\n            case 'esds':\n                {\n                    const track = this.currentTrack;\n                    if (!track || track.info?.type !== 'audio') {\n                        break;\n                    }\n                    slice.skip(4); // Version + flags\n                    const { objectTypeIndication, decoderSpecificInfo } = readEsDescriptor(slice);\n                    if (objectTypeIndication === 0x40 || objectTypeIndication === 0x67) {\n                        track.info.codec = 'aac';\n                        track.info.aacCodecInfo = {\n                            isMpeg2: objectTypeIndication === 0x67,\n                            objectType: null,\n                        };\n                    }\n                    else if (objectTypeIndication === 0x69 || objectTypeIndication === 0x6b) {\n                        track.info.codec = 'mp3';\n                    }\n                    else if (objectTypeIndication === 0xdd) {\n                        track.info.codec = 'vorbis'; // \"nonstandard, gpac uses it\" - FFmpeg\n                    }\n                    else if (objectTypeIndication === 0xa9) {\n                        track.info.codec = 'dts';\n                    }\n                    else {\n                        Logging._warn(`Unsupported audio codec (objectTypeIndication ${objectTypeIndication}) - discarding track.`);\n                    }\n                    if (decoderSpecificInfo) {\n                        track.info.codecDescription = decoderSpecificInfo;\n                        if (track.info.codec === 'aac') {\n                            // Let's try to deduce more accurate values directly from the AudioSpecificConfig:\n                            const audioSpecificConfig = parseAacAudioSpecificConfig(track.info.codecDescription);\n                            if (audioSpecificConfig.outputNumberOfChannels !== null) {\n                                track.info.numberOfChannels = audioSpecificConfig.outputNumberOfChannels;\n                            }\n                            if (audioSpecificConfig.outputSampleRate !== null) {\n                                track.info.sampleRate = audioSpecificConfig.outputSampleRate;\n                            }\n                        }\n                    }\n                }\n                ;\n                break;\n            case 'enda':\n                {\n                    const track = this.currentTrack;\n                    if (!track || track.info?.type !== 'audio') {\n                        break;\n                    }\n                    track.info.pcmLittleEndian = !!(readU16Be(slice) & 0xff); // 0xff is from FFmpeg\n                }\n                ;\n                break;\n            case 'pcmC':\n                {\n                    const track = this.currentTrack;\n                    if (!track || track.info?.type !== 'audio') {\n                        break;\n                    }\n                    slice.skip(1 + 3); // Version + flags\n                    // ISO/IEC 23003-5\n                    const formatFlags = readU8(slice);\n                    track.info.pcmLittleEndian = Boolean(formatFlags & 0x01);\n                    track.info.pcmSampleSize = readU8(slice);\n                }\n                ;\n                break;\n            case 'dOps':\n                { // Used for Opus audio\n                    const track = this.currentTrack;\n                    if (!track || track.info?.type !== 'audio') {\n                        break;\n                    }\n                    slice.skip(1); // Version\n                    // https://www.opus-codec.org/docs/opus_in_isobmff.html\n                    const outputChannelCount = readU8(slice);\n                    const preSkip = readU16Be(slice);\n                    const inputSampleRate = readU32Be(slice);\n                    const outputGain = readI16Be(slice);\n                    const channelMappingFamily = readU8(slice);\n                    let channelMappingTable;\n                    if (channelMappingFamily !== 0) {\n                        channelMappingTable = readBytes(slice, 2 + outputChannelCount);\n                    }\n                    else {\n                        channelMappingTable = new Uint8Array(0);\n                    }\n                    // https://datatracker.ietf.org/doc/html/draft-ietf-codec-oggopus-06\n                    const description = new Uint8Array(8 + 1 + 1 + 2 + 4 + 2 + 1 + channelMappingTable.byteLength);\n                    const view = new DataView(description.buffer);\n                    view.setUint32(0, 0x4f707573, false); // 'Opus'\n                    view.setUint32(4, 0x48656164, false); // 'Head'\n                    view.setUint8(8, 1); // Version\n                    view.setUint8(9, outputChannelCount);\n                    view.setUint16(10, preSkip, true);\n                    view.setUint32(12, inputSampleRate, true);\n                    view.setInt16(16, outputGain, true);\n                    view.setUint8(18, channelMappingFamily);\n                    description.set(channelMappingTable, 19);\n                    track.info.codecDescription = description;\n                    track.info.numberOfChannels = outputChannelCount;\n                    // Don't copy the input sample rate, irrelevant, and output sample rate is fixed\n                }\n                ;\n                break;\n            case 'dfLa':\n                { // Used for FLAC audio\n                    const track = this.currentTrack;\n                    if (!track || track.info?.type !== 'audio') {\n                        break;\n                    }\n                    slice.skip(4); // Version + flags\n                    // https://datatracker.ietf.org/doc/rfc9639/\n                    const BLOCK_TYPE_MASK = 0x7f;\n                    const LAST_METADATA_BLOCK_FLAG_MASK = 0x80;\n                    const startPos = slice.filePos;\n                    while (slice.filePos < boxEndPos) {\n                        const flagAndType = readU8(slice);\n                        const metadataBlockLength = readU24Be(slice);\n                        const type = flagAndType & BLOCK_TYPE_MASK;\n                        // It's a STREAMINFO block; let's extract the actual sample rate and channel count\n                        if (type === FlacBlockType.STREAMINFO) {\n                            slice.skip(10);\n                            // Extract sample rate and channel count\n                            const word = readU32Be(slice);\n                            const sampleRate = word >>> 12;\n                            const numberOfChannels = ((word >> 9) & 0b111) + 1;\n                            track.info.sampleRate = sampleRate;\n                            track.info.numberOfChannels = numberOfChannels;\n                            slice.skip(20);\n                        }\n                        else {\n                            // Simply skip ahead to the next block\n                            slice.skip(metadataBlockLength);\n                        }\n                        if (flagAndType & LAST_METADATA_BLOCK_FLAG_MASK) {\n                            break;\n                        }\n                    }\n                    const endPos = slice.filePos;\n                    slice.filePos = startPos;\n                    const bytes = readBytes(slice, endPos - startPos);\n                    const description = new Uint8Array(4 + bytes.byteLength);\n                    const view = new DataView(description.buffer);\n                    view.setUint32(0, 0x664c6143, false); // 'fLaC'\n                    description.set(bytes, 4);\n                    // Set the codec description to be 'fLaC' + all metadata blocks\n                    track.info.codecDescription = description;\n                }\n                ;\n                break;\n            case 'dac3':\n                { // AC3SpecificBox\n                    const track = this.currentTrack;\n                    if (!track || track.info?.type !== 'audio') {\n                        break;\n                    }\n                    const bytes = readBytes(slice, 3);\n                    const bitstream = new Bitstream(bytes);\n                    const fscod = bitstream.readBits(2);\n                    bitstream.skipBits(5 + 3); // Skip bsid and bsmod\n                    const acmod = bitstream.readBits(3);\n                    const lfeon = bitstream.readBits(1);\n                    if (fscod < 3) {\n                        track.info.sampleRate = AC3_SAMPLE_RATES[fscod];\n                    }\n                    track.info.numberOfChannels = AC3_ACMOD_CHANNEL_COUNTS[acmod] + lfeon;\n                }\n                ;\n                break;\n            case 'dec3':\n                { // EC3SpecificBox\n                    const track = this.currentTrack;\n                    if (!track || track.info?.type !== 'audio') {\n                        break;\n                    }\n                    const bytes = readBytes(slice, boxInfo.contentSize);\n                    const config = parseEac3Config(bytes);\n                    if (!config) {\n                        Logging._warn('Invalid dec3 box contents, ignoring.');\n                        break;\n                    }\n                    const sampleRate = getEac3SampleRate(config);\n                    if (sampleRate !== null) {\n                        track.info.sampleRate = sampleRate;\n                    }\n                    track.info.numberOfChannels = getEac3ChannelCount(config);\n                }\n                ;\n                break;\n            case 'ddts':\n                { // DTSSpecificBox\n                    const track = this.currentTrack;\n                    if (!track || track.info?.type !== 'audio') {\n                        break;\n                    }\n                    const bytes = readBytes(slice, Math.min(boxInfo.contentSize, DTS_SPECIFIC_BOX_SIZE));\n                    const config = parseDtsSpecificBox(bytes);\n                    if (!config) {\n                        Logging._warn('Invalid ddts box contents, ignoring.');\n                        break;\n                    }\n                    track.info.sampleRate = config.sampleRate;\n                    if (config.numberOfChannels !== null) {\n                        track.info.numberOfChannels = config.numberOfChannels;\n                    }\n                }\n                ;\n                break;\n            case 'stts':\n                {\n                    const track = this.currentTrack;\n                    if (!track) {\n                        break;\n                    }\n                    if (!track.sampleTable) {\n                        break;\n                    }\n                    slice.skip(4); // Version + flags\n                    const entryCount = readU32Be(slice);\n                    let currentIndex = 0;\n                    let currentTimestamp = 0;\n                    for (let i = 0; i < entryCount; i++) {\n                        const sampleCount = readU32Be(slice);\n                        const sampleDelta = readU32Be(slice);\n                        track.sampleTable.sampleTimingEntries.push({\n                            startIndex: currentIndex,\n                            startDecodeTimestamp: currentTimestamp,\n                            count: sampleCount,\n                            delta: sampleDelta,\n                        });\n                        currentIndex += sampleCount;\n                        currentTimestamp += sampleCount * sampleDelta;\n                    }\n                }\n                ;\n                break;\n            case 'ctts':\n                {\n                    const track = this.currentTrack;\n                    if (!track) {\n                        break;\n                    }\n                    if (!track.sampleTable) {\n                        break;\n                    }\n                    slice.skip(1 + 3); // Version + flags\n                    const entryCount = readU32Be(slice);\n                    let sampleIndex = 0;\n                    for (let i = 0; i < entryCount; i++) {\n                        const sampleCount = readU32Be(slice);\n                        const sampleOffset = readI32Be(slice);\n                        track.sampleTable.sampleCompositionTimeOffsets.push({\n                            startIndex: sampleIndex,\n                            count: sampleCount,\n                            offset: sampleOffset,\n                            startTimestamp: -1,\n                            lastTimestamp: -1,\n                            maxLastTimestamp: -1,\n                        });\n                        sampleIndex += sampleCount;\n                    }\n                }\n                ;\n                break;\n            case 'stsz':\n                {\n                    const track = this.currentTrack;\n                    if (!track) {\n                        break;\n                    }\n                    if (!track.sampleTable) {\n                        break;\n                    }\n                    slice.skip(4); // Version + flags\n                    const sampleSize = readU32Be(slice);\n                    const sampleCount = readU32Be(slice);\n                    if (sampleSize === 0) {\n                        for (let i = 0; i < sampleCount; i++) {\n                            const sampleSize = readU32Be(slice);\n                            track.sampleTable.sampleSizes.push(sampleSize);\n                        }\n                    }\n                    else {\n                        track.sampleTable.sampleSizes.push(sampleSize);\n                    }\n                    track.sampleTable.sampleCount = sampleCount;\n                }\n                ;\n                break;\n            case 'stz2':\n                {\n                    const track = this.currentTrack;\n                    if (!track) {\n                        break;\n                    }\n                    if (!track.sampleTable) {\n                        break;\n                    }\n                    slice.skip(4); // Version + flags\n                    slice.skip(3); // Reserved\n                    const fieldSize = readU8(slice); // in bits\n                    const sampleCount = readU32Be(slice);\n                    if (fieldSize !== 4 && fieldSize !== 8 && fieldSize !== 16) {\n                        throw new Error(`Invalid stz2 box: unsupported field size ${fieldSize}.`);\n                    }\n                    const bytes = readBytes(slice, Math.ceil(sampleCount * fieldSize / 8));\n                    const bitstream = new Bitstream(bytes);\n                    for (let i = 0; i < sampleCount; i++) {\n                        const sampleSize = bitstream.readBits(fieldSize);\n                        track.sampleTable.sampleSizes.push(sampleSize);\n                    }\n                    track.sampleTable.sampleCount = sampleCount;\n                }\n                ;\n                break;\n            case 'stss':\n                {\n                    const track = this.currentTrack;\n                    if (!track) {\n                        break;\n                    }\n                    if (!track.sampleTable) {\n                        break;\n                    }\n                    slice.skip(4); // Version + flags\n                    track.sampleTable.keySampleIndices = [];\n                    const entryCount = readU32Be(slice);\n                    for (let i = 0; i < entryCount; i++) {\n                        const sampleIndex = readU32Be(slice) - 1; // Convert to 0-indexed\n                        track.sampleTable.keySampleIndices.push(sampleIndex);\n                    }\n                    // We binary search this list, so it must be sorted\n                    track.sampleTable.keySampleIndices.sort((a, b) => a - b);\n                    if (track.sampleTable.keySampleIndices[0] !== 0) {\n                        // Some files don't mark the first sample a key sample, which is basically almost always incorrect.\n                        // Here, we correct for that mistake:\n                        track.sampleTable.keySampleIndices.unshift(0);\n                    }\n                }\n                ;\n                break;\n            case 'stsc':\n                {\n                    const track = this.currentTrack;\n                    if (!track) {\n                        break;\n                    }\n                    if (!track.sampleTable) {\n                        break;\n                    }\n                    slice.skip(4);\n                    const entryCount = readU32Be(slice);\n                    let skippedEntryCount = 0;\n                    for (let i = 0; i < entryCount; i++) {\n                        const startChunkIndex = readU32Be(slice) - 1; // Convert to 0-indexed\n                        const samplesPerChunk = readU32Be(slice);\n                        const sampleDescriptionIndex = readU32Be(slice);\n                        const lastEntry = last(track.sampleTable.sampleToChunk);\n                        if (lastEntry && startChunkIndex <= lastEntry.startChunkIndex) {\n                            // Keeping it would mess up the sample-to-chunk mapping and make chunk iteration blow up\n                            skippedEntryCount++;\n                            continue;\n                        }\n                        track.sampleTable.sampleToChunk.push({\n                            startSampleIndex: -1,\n                            startChunkIndex,\n                            samplesPerChunk,\n                            sampleDescriptionIndex,\n                        });\n                    }\n                    if (skippedEntryCount > 0) {\n                        Logging._warn(`Skipped ${skippedEntryCount} invalid stsc entries whose chunk indices weren't strictly`\n                            + ' increasing.');\n                    }\n                    let startSampleIndex = 0;\n                    for (let i = 0; i < track.sampleTable.sampleToChunk.length; i++) {\n                        track.sampleTable.sampleToChunk[i].startSampleIndex = startSampleIndex;\n                        if (i < track.sampleTable.sampleToChunk.length - 1) {\n                            const nextChunk = track.sampleTable.sampleToChunk[i + 1];\n                            const chunkCount = nextChunk.startChunkIndex\n                                - track.sampleTable.sampleToChunk[i].startChunkIndex;\n                            startSampleIndex += chunkCount * track.sampleTable.sampleToChunk[i].samplesPerChunk;\n                        }\n                    }\n                }\n                ;\n                break;\n            case 'stco':\n                {\n                    const track = this.currentTrack;\n                    if (!track) {\n                        break;\n                    }\n                    if (!track.sampleTable) {\n                        break;\n                    }\n                    slice.skip(4); // Version + flags\n                    const entryCount = readU32Be(slice);\n                    for (let i = 0; i < entryCount; i++) {\n                        const chunkOffset = readU32Be(slice);\n                        track.sampleTable.chunkOffsets.push(chunkOffset);\n                    }\n                }\n                ;\n                break;\n            case 'co64':\n                {\n                    const track = this.currentTrack;\n                    if (!track) {\n                        break;\n                    }\n                    if (!track.sampleTable) {\n                        break;\n                    }\n                    slice.skip(4); // Version + flags\n                    const entryCount = readU32Be(slice);\n                    for (let i = 0; i < entryCount; i++) {\n                        const chunkOffset = readU64Be(slice);\n                        track.sampleTable.chunkOffsets.push(chunkOffset);\n                    }\n                }\n                ;\n                break;\n            case 'mvex':\n                {\n                    this.isFragmented = true;\n                    this.readContiguousBoxes(slice.slice(contentStartPos, boxInfo.contentSize));\n                }\n                ;\n                break;\n            case 'mehd':\n                {\n                    const version = readU8(slice);\n                    slice.skip(3); // Flags\n                    const fragmentDuration = version === 1 ? readU64Be(slice) : readU32Be(slice);\n                    this.movieDurationInTimescale = fragmentDuration;\n                }\n                ;\n                break;\n            case 'trex':\n                {\n                    slice.skip(4); // Version + flags\n                    const trackId = readU32Be(slice);\n                    const defaultSampleDescriptionIndex = readU32Be(slice);\n                    const defaultSampleDuration = readU32Be(slice);\n                    const defaultSampleSize = readU32Be(slice);\n                    const defaultSampleFlags = readU32Be(slice);\n                    // We store these separately rather than in the tracks since the tracks may not exist yet\n                    this.fragmentTrackDefaults.set(trackId, {\n                        trackId,\n                        defaultSampleDescriptionIndex,\n                        defaultSampleDuration,\n                        defaultSampleSize,\n                        defaultSampleFlags,\n                    });\n                }\n                ;\n                break;\n            case 'tfra':\n                {\n                    const version = readU8(slice);\n                    slice.skip(3); // Flags\n                    const trackId = readU32Be(slice);\n                    const track = this.idToTrack.get(trackId);\n                    if (!track) {\n                        break;\n                    }\n                    const word = readU32Be(slice);\n                    const lengthSizeOfTrafNum = (word & 0b110000) >> 4;\n                    const lengthSizeOfTrunNum = (word & 0b001100) >> 2;\n                    const lengthSizeOfSampleNum = word & 0b000011;\n                    const functions = [readU8, readU16Be, readU24Be, readU32Be];\n                    const readTrafNum = functions[lengthSizeOfTrafNum];\n                    const readTrunNum = functions[lengthSizeOfTrunNum];\n                    const readSampleNum = functions[lengthSizeOfSampleNum];\n                    const numberOfEntries = readU32Be(slice);\n                    for (let i = 0; i < numberOfEntries; i++) {\n                        const time = version === 1 ? readU64Be(slice) : readU32Be(slice);\n                        const moofOffset = version === 1 ? readU64Be(slice) : readU32Be(slice);\n                        readTrafNum(slice); // Not used\n                        const trunNumber = readTrunNum(slice);\n                        const sampleNumber = readSampleNum(slice);\n                        if (trunNumber >= 1 && sampleNumber >= 1) {\n                            track.fragmentLookupTable.push({\n                                timestamp: time,\n                                moofOffset,\n                                trunNumber,\n                                sampleNumber,\n                            });\n                        }\n                        else {\n                            // Invalid\n                        }\n                    }\n                    // The table gets sorted and deduplicated once all metadata has been read\n                }\n                ;\n                break;\n            case 'moof':\n                {\n                    if (this.currentFragment) {\n                        break; // Nested moof boxes make no sense\n                    }\n                    this.currentFragment = {\n                        moofOffset: startPos,\n                        moofSize: boxInfo.totalSize,\n                        implicitBaseDataOffset: startPos,\n                        trackData: new Map(),\n                        psshBoxes: [],\n                        sampleCount: 0,\n                    };\n                    try {\n                        this.readContiguousBoxes(slice.slice(contentStartPos, boxInfo.contentSize));\n                        this.lastReadFragment = this.currentFragment;\n                    }\n                    finally {\n                        this.currentFragment = null;\n                        this.currentTrack = null;\n                    }\n                }\n                ;\n                break;\n            case 'traf':\n                {\n                    if (!this.currentFragment || this.isReadingTraf) {\n                        break;\n                    }\n                    this.isReadingTraf = true;\n                    try {\n                        this.readContiguousBoxes(slice.slice(contentStartPos, boxInfo.contentSize));\n                    }\n                    finally {\n                        this.isReadingTraf = false;\n                    }\n                    // It is possible that there is no current track, for example when we don't care about the track\n                    // referenced in the track fragment header.\n                    if (this.currentTrack) {\n                        const trackData = this.currentFragment.trackData.get(this.currentTrack.id);\n                        cond: if (trackData) {\n                            if (trackData.samples.length === 0) {\n                                // Don't associate the fragment with the track if it has no samples, this simplifies\n                                // other code\n                                this.currentFragment.trackData.delete(this.currentTrack.id);\n                                break cond;\n                            }\n                            trackData.presentationTimestamps = trackData.samples\n                                .map((x, i) => ({ presentationTimestamp: x.presentationTimestamp, sampleIndex: i }))\n                                .sort((a, b) => a.presentationTimestamp - b.presentationTimestamp);\n                            for (let i = 0; i < trackData.presentationTimestamps.length; i++) {\n                                const currentEntry = trackData.presentationTimestamps[i];\n                                const currentSample = trackData.samples[currentEntry.sampleIndex];\n                                if (trackData.firstKeyFrameTimestamp === null && currentSample.isKeyFrame) {\n                                    trackData.firstKeyFrameTimestamp = currentSample.presentationTimestamp;\n                                }\n                                if (i < trackData.presentationTimestamps.length - 1) {\n                                    // Update sample durations based on presentation order\n                                    const nextEntry = trackData.presentationTimestamps[i + 1];\n                                    const duration = nextEntry.presentationTimestamp - currentEntry.presentationTimestamp;\n                                    currentSample.duration = duration;\n                                }\n                            }\n                            const firstSample = trackData.samples[trackData.presentationTimestamps[0].sampleIndex];\n                            const lastSample = trackData.samples[last(trackData.presentationTimestamps).sampleIndex];\n                            trackData.startTimestamp = firstSample.presentationTimestamp;\n                            trackData.endTimestamp = lastSample.presentationTimestamp + lastSample.duration;\n                            const { currentFragmentState } = this.currentTrack;\n                            assert(currentFragmentState);\n                            if (currentFragmentState.startTimestamp !== null) {\n                                offsetFragmentTrackDataByTimestamp(trackData, currentFragmentState.startTimestamp);\n                                trackData.startTimestampIsFinal = true;\n                            }\n                            // Transfer the buffered saiz+saio state onto the track data, so readFragment can resolve it\n                            // once all boxes are parsed. Only relevant if senc wasn't already used to populate samples.\n                            if (currentFragmentState.encryptionAuxInfo && !trackData.samples[0].encryption) {\n                                trackData.encryptionAuxInfo = currentFragmentState.encryptionAuxInfo;\n                            }\n                        }\n                        this.currentTrack.currentFragmentState = null;\n                        this.currentTrack = null;\n                    }\n                }\n                ;\n                break;\n            case 'pssh':\n                {\n                    if (this.input._formatOptions.isobmff?._suppressPsshParsing) {\n                        break;\n                    }\n                    const psshBox = parsePsshBoxContents(readBytes(slice, boxInfo.contentSize));\n                    if (this.currentFragment) {\n                        this.currentFragment.psshBoxes.push(psshBox);\n                    }\n                    else if (!this.currentTrack) {\n                        this.psshBoxes.push(psshBox);\n                    }\n                }\n                ;\n                break;\n            case 'tfhd':\n                {\n                    // Only the first tfhd of a traf counts; anywhere else, there'd be no traf to finish the track data\n                    if (!this.currentFragment || !this.isReadingTraf || this.currentTrack) {\n                        break;\n                    }\n                    slice.skip(1); // Version\n                    const flags = readU24Be(slice);\n                    const baseDataOffsetPresent = Boolean(flags & 0x000001);\n                    const sampleDescriptionIndexPresent = Boolean(flags & 0x000002);\n                    const defaultSampleDurationPresent = Boolean(flags & 0x000008);\n                    const defaultSampleSizePresent = Boolean(flags & 0x000010);\n                    const defaultSampleFlagsPresent = Boolean(flags & 0x000020);\n                    const durationIsEmpty = Boolean(flags & 0x010000);\n                    const defaultBaseIsMoof = Boolean(flags & 0x020000);\n                    const trackId = readU32Be(slice);\n                    const track = this.idToTrack.get(trackId);\n                    if (!track) {\n                        // We don't care about this track\n                        break;\n                    }\n                    if (this.currentFragment.trackData.has(trackId)) {\n                        Logging._warn(`Multiple traf boxes for track ${trackId} in the same moof box; skipping.`);\n                        break;\n                    }\n                    const defaults = this.fragmentTrackDefaults.get(trackId);\n                    this.currentTrack = track;\n                    track.currentFragmentState = {\n                        baseDataOffset: this.currentFragment.implicitBaseDataOffset,\n                        sampleDescriptionIndex: defaults?.defaultSampleDescriptionIndex ?? null,\n                        defaultSampleDuration: defaults?.defaultSampleDuration ?? null,\n                        defaultSampleSize: defaults?.defaultSampleSize ?? null,\n                        defaultSampleFlags: defaults?.defaultSampleFlags ?? null,\n                        startTimestamp: null,\n                        encryptionAuxInfo: null,\n                    };\n                    if (baseDataOffsetPresent) {\n                        track.currentFragmentState.baseDataOffset = readU64Be(slice);\n                    }\n                    else if (defaultBaseIsMoof) {\n                        track.currentFragmentState.baseDataOffset = this.currentFragment.moofOffset;\n                    }\n                    if (sampleDescriptionIndexPresent) {\n                        track.currentFragmentState.sampleDescriptionIndex = readU32Be(slice);\n                    }\n                    if (defaultSampleDurationPresent) {\n                        track.currentFragmentState.defaultSampleDuration = readU32Be(slice);\n                    }\n                    if (defaultSampleSizePresent) {\n                        track.currentFragmentState.defaultSampleSize = readU32Be(slice);\n                    }\n                    if (defaultSampleFlagsPresent) {\n                        track.currentFragmentState.defaultSampleFlags = readU32Be(slice);\n                    }\n                    if (durationIsEmpty) {\n                        track.currentFragmentState.defaultSampleDuration = 0;\n                    }\n                }\n                ;\n                break;\n            case 'tfdt':\n                {\n                    const track = this.currentTrack;\n                    if (!track?.currentFragmentState) {\n                        break;\n                    }\n                    const version = readU8(slice);\n                    slice.skip(3); // Flags\n                    const baseMediaDecodeTime = version === 0 ? readU32Be(slice) : readU64Be(slice);\n                    track.currentFragmentState.startTimestamp = baseMediaDecodeTime;\n                }\n                ;\n                break;\n            case 'trun':\n                {\n                    const track = this.currentTrack;\n                    if (!track?.currentFragmentState || !this.currentFragment) {\n                        break;\n                    }\n                    slice.skip(1); // Version\n                    const flags = readU24Be(slice);\n                    const dataOffsetPresent = Boolean(flags & 0x000001);\n                    const firstSampleFlagsPresent = Boolean(flags & 0x000004);\n                    const sampleDurationPresent = Boolean(flags & 0x000100);\n                    const sampleSizePresent = Boolean(flags & 0x000200);\n                    const sampleFlagsPresent = Boolean(flags & 0x000400);\n                    const sampleCompositionTimeOffsetsPresent = Boolean(flags & 0x000800);\n                    const sampleCount = readU32Be(slice);\n                    const { defaultSampleDuration, defaultSampleSize, defaultSampleFlags } = track.currentFragmentState;\n                    if (sampleCount > 0\n                        && ((!sampleDurationPresent && defaultSampleDuration === null)\n                            || (!sampleSizePresent && defaultSampleSize === null)\n                            || (!sampleFlagsPresent && defaultSampleFlags === null))) {\n                        throw new Error('Invalid trun box: sample values are missing and there are no defaults.');\n                    }\n                    this.currentFragment.sampleCount += sampleCount;\n                    if (this.currentFragment.sampleCount > 2 ** 20) {\n                        // Safety measure\n                        throw new Error('Too many (> 2^20) samples in fragment.');\n                    }\n                    let dataOffset = null;\n                    if (dataOffsetPresent) {\n                        dataOffset = readI32Be(slice);\n                    }\n                    let firstSampleFlags = null;\n                    if (firstSampleFlagsPresent) {\n                        firstSampleFlags = readU32Be(slice);\n                    }\n                    let trackData;\n                    if (this.currentFragment.trackData.has(track.id)) {\n                        trackData = this.currentFragment.trackData.get(track.id);\n                        if (dataOffset !== null) {\n                            trackData.currentOffset = track.currentFragmentState.baseDataOffset + dataOffset;\n                        }\n                        else {\n                            // \"If the data-offset is not present, then the data for this run starts immediately after the\n                            // data of the previous run\"\n                        }\n                    }\n                    else {\n                        trackData = {\n                            track,\n                            currentTimestamp: 0,\n                            currentOffset: track.currentFragmentState.baseDataOffset + (dataOffset ?? 0),\n                            startTimestamp: 0,\n                            endTimestamp: 0,\n                            firstKeyFrameTimestamp: null,\n                            samples: [],\n                            presentationTimestamps: [],\n                            startTimestampIsFinal: false,\n                            trunSampleCounts: [],\n                            encryptionAuxInfo: null,\n                        };\n                        this.currentFragment.trackData.set(track.id, trackData);\n                    }\n                    trackData.trunSampleCounts.push(sampleCount);\n                    for (let i = 0; i < sampleCount; i++) {\n                        let sampleDuration;\n                        if (sampleDurationPresent) {\n                            sampleDuration = readU32Be(slice);\n                        }\n                        else {\n                            sampleDuration = defaultSampleDuration;\n                        }\n                        let sampleSize;\n                        if (sampleSizePresent) {\n                            sampleSize = readU32Be(slice);\n                        }\n                        else {\n                            sampleSize = defaultSampleSize;\n                        }\n                        let sampleFlags;\n                        if (sampleFlagsPresent) {\n                            sampleFlags = readU32Be(slice);\n                        }\n                        else {\n                            sampleFlags = defaultSampleFlags;\n                        }\n                        if (i === 0 && firstSampleFlags !== null) {\n                            sampleFlags = firstSampleFlags;\n                        }\n                        let sampleCompositionTimeOffset = 0;\n                        if (sampleCompositionTimeOffsetsPresent) {\n                            // Technically unsigned for version 0, but some writers write signed values here without\n                            // changing the version. Since the large unsigned values make little sense anyway, it should be\n                            // safe to do this.\n                            sampleCompositionTimeOffset = readI32Be(slice);\n                        }\n                        const isKeyFrame = !(sampleFlags & 0x00010000);\n                        trackData.samples.push({\n                            presentationTimestamp: trackData.currentTimestamp + sampleCompositionTimeOffset,\n                            duration: sampleDuration,\n                            byteOffset: trackData.currentOffset,\n                            byteSize: sampleSize,\n                            isKeyFrame,\n                            encryption: null,\n                        });\n                        trackData.currentOffset += sampleSize;\n                        trackData.currentTimestamp += sampleDuration;\n                    }\n                    this.currentFragment.implicitBaseDataOffset = trackData.currentOffset;\n                }\n                ;\n                break;\n            case 'saiz':\n                {\n                    // Sample Auxiliary Information Sizes - per-sample sizes of (typically) the encryption aux info.\n                    const track = this.currentTrack;\n                    if (!track || !track.encryptionInfo) {\n                        break;\n                    }\n                    slice.skip(1); // Version\n                    const flags = readU24Be(slice);\n                    if (flags & 0x01) {\n                        const auxInfoType = readAscii(slice, 4);\n                        const auxInfoTypeParam = readU32Be(slice);\n                        if (auxInfoType !== track.encryptionInfo.scheme || auxInfoTypeParam !== 0) {\n                            // Not the encryption aux info\n                            break;\n                        }\n                    }\n                    const defaultSampleInfoSize = readU8(slice);\n                    const sampleCount = readU32Be(slice);\n                    let sampleSizes = null;\n                    if (defaultSampleInfoSize === 0 && sampleCount > 0) {\n                        sampleSizes = readBytes(slice, sampleCount);\n                    }\n                    const aux = getOrCreateEncryptionAuxInfo(track);\n                    aux.defaultSampleInfoSize = defaultSampleInfoSize;\n                    aux.sampleSizes = sampleSizes;\n                    aux.sampleCount = sampleCount;\n                }\n                ;\n                break;\n            case 'saio':\n                {\n                    // Sample Auxiliary Information Offsets - file offset(s) where the aux info lives.\n                    const track = this.currentTrack;\n                    if (!track || !track.encryptionInfo) {\n                        break;\n                    }\n                    const version = readU8(slice);\n                    const flags = readU24Be(slice);\n                    if (flags & 0x01) {\n                        const auxInfoType = readAscii(slice, 4);\n                        const auxInfoTypeParam = readU32Be(slice);\n                        if (auxInfoType !== track.encryptionInfo.scheme || auxInfoTypeParam !== 0) {\n                            break;\n                        }\n                    }\n                    const entryCount = readU32Be(slice);\n                    if (entryCount === 0) {\n                        break;\n                    }\n                    if (entryCount > 1) {\n                        Logging._warn('Multiple saio entries are not supported; using the first offset only.');\n                    }\n                    let offset = version === 0 ? readU32Be(slice) : Number(readU64Be(slice));\n                    // Per ISO/IEC 23001-7: when saio is inside a moof, offsets are relative to the start of the moof box.\n                    if (this.currentFragment) {\n                        offset += this.currentFragment.moofOffset;\n                    }\n                    const aux = getOrCreateEncryptionAuxInfo(track);\n                    aux.offset = offset;\n                }\n                ;\n                break;\n            case 'senc':\n                {\n                    // Per-sample encryption info inside a 'traf'. Holds per-sample IV and optional subsample breakdown\n                    // for CENC-protected samples\n                    const track = this.currentTrack;\n                    if (!track || !track.encryptionInfo) {\n                        break;\n                    }\n                    const trackData = this.currentFragment?.trackData.get(track.id);\n                    if (!trackData) {\n                        break;\n                    }\n                    slice.skip(1); // Version\n                    const flags = readU24Be(slice);\n                    const useSubsamples = Boolean(flags & 0x000002);\n                    const sampleCount = readU32Be(slice);\n                    const ivSize = track.encryptionInfo.defaultPerSampleIvSize;\n                    if (ivSize === null) {\n                        throw new Error('Invalid file: encrypted track is missing its tenc box.');\n                    }\n                    for (let i = 0; i < Math.min(sampleCount, trackData.samples.length); i++) {\n                        // Normalize the IV to 16 bytes so downstream code can assume a full-length buffer. For CTR with\n                        // an 8-byte per-sample IV the lower 8 bytes are zero (that's the CENC spec's block counter start);\n                        // for CBC/cbcs the IV is always 16 bytes by spec.\n                        const iv = new Uint8Array(16);\n                        if (ivSize > 0) {\n                            iv.set(readBytes(slice, ivSize), 0);\n                        }\n                        else if (track.encryptionInfo.defaultConstantIv) {\n                            iv.set(track.encryptionInfo.defaultConstantIv, 0);\n                        }\n                        else {\n                            throw new Error('Invalid file: encrypted sample has no IV.');\n                        }\n                        let subsamples = null;\n                        if (useSubsamples) {\n                            const subsampleCount = readU16Be(slice);\n                            subsamples = [];\n                            for (let j = 0; j < subsampleCount; j++) {\n                                const clearLen = readU16Be(slice);\n                                const protectedLen = readU32Be(slice);\n                                subsamples.push({ clearLen, protectedLen });\n                            }\n                        }\n                        const sample = trackData.samples[i];\n                        sample.encryption = { iv, subsamples };\n                    }\n                }\n                ;\n                break;\n            // Metadata section\n            // https://exiftool.org/TagNames/QuickTime.html\n            // https://mp4workshop.com/about\n            case 'udta':\n                { // Contains either movie metadata or track metadata\n                    const iterator = this.iterateContiguousBoxes(slice.slice(contentStartPos, boxInfo.contentSize));\n                    for (const { boxInfo, slice } of iterator) {\n                        if (boxInfo.name !== 'meta' && !this.currentTrack) {\n                            const startPos = slice.filePos;\n                            this.metadataTags.raw ??= {};\n                            if (boxInfo.name[0] === '©') {\n                                // https://mp4workshop.com/about\n                                // Box name starting with © indicates \"international text\"\n                                this.metadataTags.raw[boxInfo.name] ??= readMetadataStringShort(slice);\n                            }\n                            else {\n                                this.metadataTags.raw[boxInfo.name] ??= readBytes(slice, boxInfo.contentSize);\n                            }\n                            slice.filePos = startPos;\n                        }\n                        switch (boxInfo.name) {\n                            case 'meta':\n                                {\n                                    slice.skip(-boxInfo.headerSize);\n                                    this.traverseBox(slice);\n                                }\n                                ;\n                                break;\n                            case '©nam':\n                            case 'name':\n                                {\n                                    if (this.currentTrack) {\n                                        this.currentTrack.name = textDecoder.decode(readBytes(slice, boxInfo.contentSize));\n                                    }\n                                    else {\n                                        this.metadataTags.title ??= readMetadataStringShort(slice);\n                                    }\n                                }\n                                ;\n                                break;\n                            case '©des':\n                                {\n                                    if (!this.currentTrack) {\n                                        this.metadataTags.description ??= readMetadataStringShort(slice);\n                                    }\n                                }\n                                ;\n                                break;\n                            case '©ART':\n                                {\n                                    if (!this.currentTrack) {\n                                        this.metadataTags.artist ??= readMetadataStringShort(slice);\n                                    }\n                                }\n                                ;\n                                break;\n                            case '©alb':\n                                {\n                                    if (!this.currentTrack) {\n                                        this.metadataTags.album ??= readMetadataStringShort(slice);\n                                    }\n                                }\n                                ;\n                                break;\n                            case 'albr':\n                                {\n                                    if (!this.currentTrack) {\n                                        this.metadataTags.albumArtist ??= readMetadataStringShort(slice);\n                                    }\n                                }\n                                ;\n                                break;\n                            case '©gen':\n                                {\n                                    if (!this.currentTrack) {\n                                        this.metadataTags.genre ??= readMetadataStringShort(slice);\n                                    }\n                                }\n                                ;\n                                break;\n                            case '©day':\n                                {\n                                    if (!this.currentTrack) {\n                                        const date = new Date(readMetadataStringShort(slice));\n                                        if (!Number.isNaN(date.getTime())) {\n                                            this.metadataTags.date ??= date;\n                                        }\n                                    }\n                                }\n                                ;\n                                break;\n                            case '©cmt':\n                                {\n                                    if (!this.currentTrack) {\n                                        this.metadataTags.comment ??= readMetadataStringShort(slice);\n                                    }\n                                }\n                                ;\n                                break;\n                            case '©lyr':\n                                {\n                                    if (!this.currentTrack) {\n                                        this.metadataTags.lyrics ??= readMetadataStringShort(slice);\n                                    }\n                                }\n                                ;\n                                break;\n                        }\n                    }\n                }\n                ;\n                break;\n            case 'meta':\n                {\n                    if (this.currentTrack) {\n                        break; // Only care about movie-level metadata for now\n                    }\n                    // The 'meta' box comes in two flavors, one with flags/version and one without. To know which is which,\n                    // let's read the next 4 bytes, which are either the version or the size of the first subbox.\n                    const word = readU32Be(slice);\n                    const isQuickTime = word !== 0;\n                    this.currentMetadataKeys = new Map();\n                    if (isQuickTime) {\n                        this.readContiguousBoxes(slice.slice(contentStartPos, boxInfo.contentSize));\n                    }\n                    else {\n                        this.readContiguousBoxes(slice.slice(contentStartPos + 4, boxInfo.contentSize - 4));\n                    }\n                    this.currentMetadataKeys = null;\n                }\n                ;\n                break;\n            case 'keys':\n                {\n                    if (!this.currentMetadataKeys) {\n                        break;\n                    }\n                    slice.skip(4); // Version + flags\n                    const entryCount = readU32Be(slice);\n                    for (let i = 0; i < entryCount; i++) {\n                        const keySize = readU32Be(slice);\n                        if (keySize < 8) {\n                            throw new Error('Invalid keys box: key size must be at least 8.');\n                        }\n                        slice.skip(4); // Key namespace\n                        const keyName = textDecoder.decode(readBytes(slice, keySize - 8));\n                        this.currentMetadataKeys.set(i + 1, keyName);\n                    }\n                }\n                ;\n                break;\n            case 'ilst':\n                {\n                    if (!this.currentMetadataKeys) {\n                        break;\n                    }\n                    const iterator = this.iterateContiguousBoxes(slice.slice(contentStartPos, boxInfo.contentSize));\n                    for (const { boxInfo, slice } of iterator) {\n                        let metadataKey = boxInfo.name;\n                        // Interpret the box name as a u32be\n                        const nameAsNumber = (metadataKey.charCodeAt(0) << 24)\n                            + (metadataKey.charCodeAt(1) << 16)\n                            + (metadataKey.charCodeAt(2) << 8)\n                            + metadataKey.charCodeAt(3);\n                        if (this.currentMetadataKeys.has(nameAsNumber)) {\n                            // An entry exists for this number\n                            metadataKey = this.currentMetadataKeys.get(nameAsNumber);\n                        }\n                        const data = readDataBox(slice);\n                        this.metadataTags.raw ??= {};\n                        this.metadataTags.raw[metadataKey] ??= data;\n                        switch (metadataKey) {\n                            case '©nam':\n                            case 'titl':\n                            case 'com.apple.quicktime.title':\n                            case 'title':\n                                {\n                                    if (typeof data === 'string') {\n                                        this.metadataTags.title ??= data;\n                                    }\n                                }\n                                ;\n                                break;\n                            case '©des':\n                            case 'desc':\n                            case 'dscp':\n                            case 'com.apple.quicktime.description':\n                            case 'description':\n                                {\n                                    if (typeof data === 'string') {\n                                        this.metadataTags.description ??= data;\n                                    }\n                                }\n                                ;\n                                break;\n                            case '©ART':\n                            case 'com.apple.quicktime.artist':\n                            case 'artist':\n                                {\n                                    if (typeof data === 'string') {\n                                        this.metadataTags.artist ??= data;\n                                    }\n                                }\n                                ;\n                                break;\n                            case '©alb':\n                            case 'albm':\n                            case 'com.apple.quicktime.album':\n                            case 'album':\n                                {\n                                    if (typeof data === 'string') {\n                                        this.metadataTags.album ??= data;\n                                    }\n                                }\n                                ;\n                                break;\n                            case 'aART':\n                            case 'album_artist':\n                                {\n                                    if (typeof data === 'string') {\n                                        this.metadataTags.albumArtist ??= data;\n                                    }\n                                }\n                                ;\n                                break;\n                            case '©cmt':\n                            case 'com.apple.quicktime.comment':\n                            case 'comment':\n                                {\n                                    if (typeof data === 'string') {\n                                        this.metadataTags.comment ??= data;\n                                    }\n                                }\n                                ;\n                                break;\n                            case '©gen':\n                            case 'gnre':\n                            case 'com.apple.quicktime.genre':\n                            case 'genre':\n                                {\n                                    if (typeof data === 'string') {\n                                        this.metadataTags.genre ??= data;\n                                    }\n                                }\n                                ;\n                                break;\n                            case '©lyr':\n                            case 'lyrics':\n                                {\n                                    if (typeof data === 'string') {\n                                        this.metadataTags.lyrics ??= data;\n                                    }\n                                }\n                                ;\n                                break;\n                            case '©day':\n                            case 'rldt':\n                            case 'com.apple.quicktime.creationdate':\n                            case 'date':\n                                {\n                                    if (typeof data === 'string') {\n                                        const date = new Date(data);\n                                        if (!Number.isNaN(date.getTime())) {\n                                            this.metadataTags.date ??= date;\n                                        }\n                                    }\n                                }\n                                ;\n                                break;\n                            case 'tmpo':\n                                {\n                                    if (data instanceof Uint8Array && data.length >= 2) {\n                                        const bpm = toDataView(data).getInt16(0, false);\n                                        if (bpm > 0) {\n                                            this.metadataTags.beatsPerMinute ??= bpm;\n                                        }\n                                    }\n                                }\n                                ;\n                                break;\n                            case 'covr':\n                            case 'com.apple.quicktime.artwork':\n                                {\n                                    if (data instanceof RichImageData) {\n                                        this.metadataTags.images ??= [];\n                                        this.metadataTags.images.push({\n                                            data: data.data,\n                                            kind: 'coverFront',\n                                            mimeType: data.mimeType,\n                                        });\n                                    }\n                                    else if (data instanceof Uint8Array) {\n                                        this.metadataTags.images ??= [];\n                                        this.metadataTags.images.push({\n                                            data,\n                                            kind: 'coverFront',\n                                            mimeType: 'image/*',\n                                        });\n                                    }\n                                }\n                                ;\n                                break;\n                            case 'track':\n                                {\n                                    if (typeof data === 'string') {\n                                        const parts = data.split('/');\n                                        const trackNum = Number.parseInt(parts[0], 10);\n                                        const tracksTotal = parts[1] && Number.parseInt(parts[1], 10);\n                                        if (Number.isInteger(trackNum) && trackNum > 0) {\n                                            this.metadataTags.trackNumber ??= trackNum;\n                                        }\n                                        if (tracksTotal && Number.isInteger(tracksTotal) && tracksTotal > 0) {\n                                            this.metadataTags.tracksTotal ??= tracksTotal;\n                                        }\n                                    }\n                                }\n                                ;\n                                break;\n                            case 'trkn':\n                                {\n                                    if (data instanceof Uint8Array && data.length >= 6) {\n                                        const view = toDataView(data);\n                                        const trackNumber = view.getUint16(2, false);\n                                        const tracksTotal = view.getUint16(4, false);\n                                        if (trackNumber > 0) {\n                                            this.metadataTags.trackNumber ??= trackNumber;\n                                        }\n                                        if (tracksTotal > 0) {\n                                            this.metadataTags.tracksTotal ??= tracksTotal;\n                                        }\n                                    }\n                                }\n                                ;\n                                break;\n                            case 'disc':\n                            case 'disk':\n                                {\n                                    if (data instanceof Uint8Array && data.length >= 6) {\n                                        const view = toDataView(data);\n                                        const discNumber = view.getUint16(2, false);\n                                        const discNumberMax = view.getUint16(4, false);\n                                        if (discNumber > 0) {\n                                            this.metadataTags.discNumber ??= discNumber;\n                                        }\n                                        if (discNumberMax > 0) {\n                                            this.metadataTags.discsTotal ??= discNumberMax;\n                                        }\n                                    }\n                                }\n                                ;\n                                break;\n                        }\n                    }\n                }\n                ;\n                break;\n        }\n        slice.filePos = boxEndPos;\n        return true;\n    }\n}\nclass IsobmffTrackBacking {\n    constructor(internalTrack) {\n        this.internalTrack = internalTrack;\n        this.packetToSampleIndex = new WeakMap();\n        this.packetToFragmentLocation = new WeakMap();\n    }\n    getId() {\n        return this.internalTrack.id;\n    }\n    getNumber() {\n        const demuxer = this.internalTrack.demuxer;\n        const trackType = this.internalTrack.trackBacking.getType();\n        let number = 0;\n        for (const track of demuxer.tracks) {\n            if (track.trackBacking.getType() === trackType) {\n                number++;\n            }\n            if (track === this.internalTrack) {\n                break;\n            }\n        }\n        return number;\n    }\n    getCodec() {\n        throw new Error('Not implemented on base class.');\n    }\n    getInternalCodecId() {\n        return this.internalTrack.internalCodecId;\n    }\n    getName() {\n        return this.internalTrack.name;\n    }\n    getLanguageCode() {\n        return this.internalTrack.languageCode;\n    }\n    getTimeResolution() {\n        return this.internalTrack.timescale;\n    }\n    isRelativeToUnixEpoch() {\n        return false;\n    }\n    getUnixTimeForTimestamp() {\n        return null;\n    }\n    getDisposition() {\n        return this.internalTrack.disposition;\n    }\n    getPairingMask() {\n        return 1n;\n    }\n    getBitrate() {\n        return this.internalTrack.maxBitrate;\n    }\n    getAverageBitrate() {\n        return this.internalTrack.avgBitrate;\n    }\n    async getDurationFromMetadata() {\n        const track = this.internalTrack;\n        if (track.durationInMediaTimescale <= 0) {\n            // The duration is often zero for fragmented files for example; return `null` to signal that the duration\n            // must be computed instead.\n            return null;\n        }\n        assert(track.trackBacking);\n        const firstPacket = await track.trackBacking.getFirstPacket({ metadataOnly: true });\n        return (firstPacket?.timestamp ?? 0) + track.durationInMediaTimescale / track.timescale;\n    }\n    async getLiveRefreshInterval() {\n        return null;\n    }\n    async getFirstPacket(options) {\n        const regularPacket = await this.fetchPacketForSampleIndex(0, options);\n        if (regularPacket || !this.internalTrack.demuxer.isFragmented) {\n            // If there's a non-fragmented packet, always prefer that\n            return regularPacket;\n        }\n        return this.performFragmentedLookup(null, (fragment) => {\n            const trackData = fragment.trackData.get(this.internalTrack.id);\n            if (trackData) {\n                return {\n                    sampleIndex: 0,\n                    correctSampleFound: true,\n                };\n            }\n            return {\n                sampleIndex: -1,\n                correctSampleFound: false,\n            };\n        }, -Infinity, // Use -Infinity as a search timestamp to avoid using the lookup entries\n        Infinity, options);\n    }\n    mapTimestampIntoTimescale(timestamp) {\n        // Do a little rounding to catch cases where the result is very close to an integer. If it is, it's likely\n        // that the number was originally an integer divided by the timescale. For stability, it's best\n        // to return the integer in this case.\n        return roundIfAlmostInteger(timestamp * this.internalTrack.timescale) + this.internalTrack.editListOffset;\n    }\n    async getPacket(timestamp, options) {\n        const timestampInTimescale = this.mapTimestampIntoTimescale(timestamp);\n        const sampleTable = this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack);\n        const sampleIndex = getSampleIndexForTimestamp(sampleTable, timestampInTimescale);\n        const regularPacket = await this.fetchPacketForSampleIndex(sampleIndex, options);\n        if (!sampleTableIsEmpty(sampleTable) || !this.internalTrack.demuxer.isFragmented) {\n            // Prefer the non-fragmented packet\n            return regularPacket;\n        }\n        return this.performFragmentedLookup(null, (fragment) => {\n            const trackData = fragment.trackData.get(this.internalTrack.id);\n            if (!trackData) {\n                return { sampleIndex: -1, correctSampleFound: false };\n            }\n            const index = binarySearchLessOrEqual(trackData.presentationTimestamps, timestampInTimescale, x => x.presentationTimestamp);\n            const sampleIndex = index !== -1 ? trackData.presentationTimestamps[index].sampleIndex : -1;\n            const correctSampleFound = index !== -1 && timestampInTimescale < trackData.endTimestamp;\n            return { sampleIndex, correctSampleFound };\n        }, timestampInTimescale, timestampInTimescale, options);\n    }\n    async getNextPacket(packet, options) {\n        const regularSampleIndex = this.packetToSampleIndex.get(packet);\n        if (regularSampleIndex !== undefined) {\n            // Prefer the non-fragmented packet\n            return this.fetchPacketForSampleIndex(regularSampleIndex + 1, options);\n        }\n        const locationInFragment = this.packetToFragmentLocation.get(packet);\n        if (locationInFragment === undefined) {\n            throw new Error('Packet was not created from this track.');\n        }\n        return this.performFragmentedLookup(locationInFragment.fragment, (fragment) => {\n            if (fragment === locationInFragment.fragment) {\n                const trackData = fragment.trackData.get(this.internalTrack.id);\n                if (locationInFragment.sampleIndex + 1 < trackData.samples.length) {\n                    // We can simply take the next sample in the fragment\n                    return {\n                        sampleIndex: locationInFragment.sampleIndex + 1,\n                        correctSampleFound: true,\n                    };\n                }\n            }\n            else {\n                const trackData = fragment.trackData.get(this.internalTrack.id);\n                if (trackData) {\n                    return {\n                        sampleIndex: 0,\n                        correctSampleFound: true,\n                    };\n                }\n            }\n            return {\n                sampleIndex: -1,\n                correctSampleFound: false,\n            };\n        }, -Infinity, // Use -Infinity as a search timestamp to avoid using the lookup entries\n        Infinity, options);\n    }\n    async getKeyPacket(timestamp, options) {\n        const timestampInTimescale = this.mapTimestampIntoTimescale(timestamp);\n        const sampleTable = this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack);\n        const sampleIndex = getKeyframeSampleIndexForTimestamp(sampleTable, timestampInTimescale);\n        const regularPacket = await this.fetchPacketForSampleIndex(sampleIndex, options);\n        if (!sampleTableIsEmpty(sampleTable) || !this.internalTrack.demuxer.isFragmented) {\n            // Prefer the non-fragmented packet\n            return regularPacket;\n        }\n        return this.performFragmentedLookup(null, (fragment) => {\n            const trackData = fragment.trackData.get(this.internalTrack.id);\n            if (!trackData) {\n                return { sampleIndex: -1, correctSampleFound: false };\n            }\n            const index = findLastIndex(trackData.presentationTimestamps, (x) => {\n                const sample = trackData.samples[x.sampleIndex];\n                return sample.isKeyFrame && x.presentationTimestamp <= timestampInTimescale;\n            });\n            const sampleIndex = index !== -1 ? trackData.presentationTimestamps[index].sampleIndex : -1;\n            const correctSampleFound = index !== -1 && timestampInTimescale < trackData.endTimestamp;\n            return { sampleIndex, correctSampleFound };\n        }, timestampInTimescale, timestampInTimescale, options);\n    }\n    async getNextKeyPacket(packet, options) {\n        const regularSampleIndex = this.packetToSampleIndex.get(packet);\n        if (regularSampleIndex !== undefined) {\n            // Prefer the non-fragmented packet\n            const sampleTable = this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack);\n            const nextKeyFrameSampleIndex = getNextKeyframeIndexForSample(sampleTable, regularSampleIndex);\n            return this.fetchPacketForSampleIndex(nextKeyFrameSampleIndex, options);\n        }\n        const locationInFragment = this.packetToFragmentLocation.get(packet);\n        if (locationInFragment === undefined) {\n            throw new Error('Packet was not created from this track.');\n        }\n        return this.performFragmentedLookup(locationInFragment.fragment, (fragment) => {\n            if (fragment === locationInFragment.fragment) {\n                const trackData = fragment.trackData.get(this.internalTrack.id);\n                for (let i = locationInFragment.sampleIndex + 1; i < trackData.samples.length; i++) {\n                    if (trackData.samples[i].isKeyFrame) {\n                        // We can simply take the next key frame in the fragment\n                        return {\n                            sampleIndex: i,\n                            correctSampleFound: true,\n                        };\n                    }\n                }\n            }\n            else {\n                const trackData = fragment.trackData.get(this.internalTrack.id);\n                if (trackData && trackData.firstKeyFrameTimestamp !== null) {\n                    const keyFrameIndex = trackData.samples.findIndex(x => x.isKeyFrame);\n                    assert(keyFrameIndex !== -1); // There must be one\n                    return {\n                        sampleIndex: keyFrameIndex,\n                        correctSampleFound: true,\n                    };\n                }\n            }\n            return {\n                sampleIndex: -1,\n                correctSampleFound: false,\n            };\n        }, -Infinity, // Use -Infinity as a search timestamp to avoid using the lookup entries\n        Infinity, options);\n    }\n    async fetchPacketForSampleIndex(sampleIndex, options) {\n        if (sampleIndex === -1) {\n            return null;\n        }\n        const sampleTable = this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack);\n        const sampleInfo = getSampleInfo(sampleTable, sampleIndex);\n        if (!sampleInfo) {\n            return null;\n        }\n        let data;\n        if (options.metadataOnly) {\n            data = PLACEHOLDER_DATA;\n        }\n        else {\n            let slice = this.internalTrack.demuxer.reader.requestSlice(sampleInfo.sampleOffset, sampleInfo.sampleSize);\n            if (isThenable(slice))\n                slice = await slice;\n            if (!slice) {\n                return null; // Data is outside\n            }\n            data = readBytes(slice, sampleInfo.sampleSize);\n            if (this.internalTrack.encryptionInfo) {\n                let sampleEncryption = null;\n                if (this.internalTrack.encryptionAuxInfo) {\n                    const entries = await resolveEncryptionAuxInfo(this.internalTrack.demuxer.reader, this.internalTrack.encryptionInfo, this.internalTrack.encryptionAuxInfo);\n                    if (sampleIndex < entries.length) {\n                        sampleEncryption = entries[sampleIndex];\n                    }\n                }\n                sampleEncryption ??= getDefaultSampleEncryption(this.internalTrack.encryptionInfo);\n                if (sampleEncryption) {\n                    data = await decryptSample(this.internalTrack, sampleEncryption, data, null);\n                }\n            }\n        }\n        const timestamp = (sampleInfo.presentationTimestamp - this.internalTrack.editListOffset)\n            / this.internalTrack.timescale;\n        const duration = sampleInfo.duration / this.internalTrack.timescale;\n        const packet = new EncodedPacket(data, sampleInfo.isKeyFrame ? 'key' : 'delta', timestamp, duration, sampleIndex, sampleInfo.sampleSize);\n        this.packetToSampleIndex.set(packet, sampleIndex);\n        return packet;\n    }\n    async fetchPacketInFragment(fragment, sampleIndex, options) {\n        if (sampleIndex === -1) {\n            return null;\n        }\n        const trackData = fragment.trackData.get(this.internalTrack.id);\n        const fragmentSample = trackData.samples[sampleIndex];\n        assert(fragmentSample);\n        let data;\n        if (options.metadataOnly) {\n            data = PLACEHOLDER_DATA;\n        }\n        else {\n            let slice = this.internalTrack.demuxer.reader.requestSlice(fragmentSample.byteOffset, fragmentSample.byteSize);\n            if (isThenable(slice))\n                slice = await slice;\n            if (!slice) {\n                return null; // Data is outside\n            }\n            data = readBytes(slice, fragmentSample.byteSize);\n            if (this.internalTrack.encryptionInfo) {\n                const sampleEncryption = fragmentSample.encryption\n                    ?? getDefaultSampleEncryption(this.internalTrack.encryptionInfo);\n                if (sampleEncryption) {\n                    data = await decryptSample(this.internalTrack, sampleEncryption, data, fragment);\n                }\n            }\n        }\n        const timestamp = (fragmentSample.presentationTimestamp - this.internalTrack.editListOffset)\n            / this.internalTrack.timescale;\n        const duration = fragmentSample.duration / this.internalTrack.timescale;\n        const packet = new EncodedPacket(data, fragmentSample.isKeyFrame ? 'key' : 'delta', timestamp, duration, fragment.moofOffset + sampleIndex, fragmentSample.byteSize);\n        this.packetToFragmentLocation.set(packet, { fragment, sampleIndex });\n        return packet;\n    }\n    /** Looks for a packet in the fragments while trying to load as few fragments as possible to retrieve it. */\n    async performFragmentedLookup(\n    // The fragment where we start looking\n    startFragment, \n    // This function returns the best-matching sample in a given fragment\n    getMatchInFragment, \n    // The timestamp with which we can search the lookup table\n    searchTimestamp, \n    // The timestamp for which we know the correct sample will not come after it\n    latestTimestamp, options, \n    // The position for which we know the correct sample will not come after it\n    stopPos = Infinity, \n    // How many times we've retried due to a faulty lookup table entry\n    lookupRetryCount = 0) {\n        const demuxer = this.internalTrack.demuxer;\n        let currentFragment = null;\n        let bestFragment = null;\n        let bestSampleIndex = -1;\n        if (startFragment) {\n            const { sampleIndex, correctSampleFound } = getMatchInFragment(startFragment);\n            if (correctSampleFound) {\n                return this.fetchPacketInFragment(startFragment, sampleIndex, options);\n            }\n            if (sampleIndex !== -1) {\n                bestFragment = startFragment;\n                bestSampleIndex = sampleIndex;\n            }\n        }\n        // Search for a lookup entry; this way, we won't need to start searching from the start of the file\n        // but can jump right into the correct fragment (or at least nearby).\n        const lookupEntryIndex = binarySearchLessOrEqual(this.internalTrack.fragmentLookupTable, searchTimestamp, x => x.timestamp);\n        const lookupEntry = lookupEntryIndex !== -1\n            ? this.internalTrack.fragmentLookupTable[lookupEntryIndex]\n            : null;\n        const positionCacheIndex = binarySearchLessOrEqual(this.internalTrack.fragmentPositionCache, searchTimestamp, x => x.startTimestamp);\n        const positionCacheEntry = positionCacheIndex !== -1\n            ? this.internalTrack.fragmentPositionCache[positionCacheIndex]\n            : null;\n        const lookupEntryPosition = Math.max(lookupEntry?.moofOffset ?? 0, positionCacheEntry?.moofOffset ?? 0) || null;\n        const lookupTableWins = !!lookupEntry && lookupEntry.moofOffset >= (positionCacheEntry?.moofOffset ?? 0);\n        let currentPos;\n        if (!startFragment) {\n            currentPos = lookupEntryPosition ?? 0;\n        }\n        else {\n            if (lookupEntryPosition === null || startFragment.moofOffset >= lookupEntryPosition) {\n                currentPos = startFragment.moofOffset + startFragment.moofSize;\n                currentFragment = startFragment;\n            }\n            else {\n                // Use the lookup entry\n                currentPos = lookupEntryPosition;\n            }\n        }\n        const scanStartPos = currentFragment ? currentFragment.moofOffset : currentPos;\n        while (currentPos < stopPos) {\n            if (currentFragment) {\n                const trackData = currentFragment.trackData.get(this.internalTrack.id);\n                if (trackData && trackData.startTimestamp > latestTimestamp) {\n                    // We're already past the upper bound, no need to keep searching\n                    break;\n                }\n                currentFragment = null; // So we don't process it again next iteration\n            }\n            const summary = demuxer.fragmentSummaries.get(currentPos);\n            if (summary && !summary.trackIds.has(this.internalTrack.id)) {\n                // We've read this fragment before and know it has nothing for this track, so let's not read it again\n                currentPos += summary.moofSize;\n                continue;\n            }\n            // Load the header\n            let slice = demuxer.reader.requestSliceRange(currentPos, MIN_BOX_HEADER_SIZE, MAX_BOX_HEADER_SIZE);\n            if (isThenable(slice))\n                slice = await slice;\n            if (!slice)\n                break;\n            const boxStartPos = currentPos;\n            const boxInfo = readBoxHeader(slice);\n            if (!boxInfo) {\n                break;\n            }\n            if (boxInfo.name === 'moof') {\n                currentFragment = await demuxer.readFragment(boxStartPos);\n                if (!currentFragment) {\n                    break;\n                }\n                const { sampleIndex, correctSampleFound } = getMatchInFragment(currentFragment);\n                if (correctSampleFound) {\n                    return this.fetchPacketInFragment(currentFragment, sampleIndex, options);\n                }\n                if (sampleIndex !== -1) {\n                    bestFragment = currentFragment;\n                    bestSampleIndex = sampleIndex;\n                }\n            }\n            currentPos = boxStartPos + boxInfo.totalSize;\n        }\n        // Handle unsatisfactory lookup table entries or position cache entries\n        if (lookupEntryPosition !== null && (!bestFragment || bestFragment.moofOffset < lookupEntryPosition)) {\n            // We found a lookup entry but no fragment from there on that satisfied the match. In this case, let's\n            // search again but using a previous entry of the kind we started from. Each time this happens, we double\n            // the backwards step to perform better (and have more sequential reads) if it takes us a long time to find\n            // the media.\n            const step = 1 << lookupRetryCount;\n            const previousEntryTimestamp = lookupTableWins\n                ? this.internalTrack.fragmentLookupTable[lookupEntryIndex - step]?.timestamp\n                : this.internalTrack.fragmentPositionCache[positionCacheIndex - step]?.startTimestamp;\n            const newSearchTimestamp = previousEntryTimestamp ?? -Infinity;\n            return this.performFragmentedLookup(null, getMatchInFragment, newSearchTimestamp, latestTimestamp, options, scanStartPos, // So we don't read the same fragments again\n            lookupRetryCount + 1);\n        }\n        if (bestFragment) {\n            // If we finished looping but didn't find a perfect match, still return the best match we found\n            return this.fetchPacketInFragment(bestFragment, bestSampleIndex, options);\n        }\n        return null;\n    }\n}\nclass IsobmffVideoTrackBacking extends IsobmffTrackBacking {\n    constructor(internalTrack) {\n        super(internalTrack);\n        this.decoderConfigPromise = null;\n    }\n    getType() {\n        return 'video';\n    }\n    getCodec() {\n        return this.internalTrack.info.codec;\n    }\n    getCodedWidth() {\n        return this.internalTrack.info.width;\n    }\n    getCodedHeight() {\n        return this.internalTrack.info.height;\n    }\n    getSquarePixelWidth() {\n        return this.internalTrack.info.squarePixelWidth;\n    }\n    getSquarePixelHeight() {\n        return this.internalTrack.info.squarePixelHeight;\n    }\n    getTransformationMatrix() {\n        return [...this.internalTrack.matrix];\n    }\n    async getColorSpace() {\n        const decoderConfig = await this.getDecoderConfig();\n        if (!decoderConfig) {\n            return this.internalTrack.info.colorSpace;\n        }\n        return {\n            primaries: decoderConfig.colorSpace?.primaries,\n            transfer: decoderConfig.colorSpace?.transfer,\n            matrix: decoderConfig.colorSpace?.matrix,\n            fullRange: decoderConfig.colorSpace?.fullRange,\n        };\n    }\n    async canBeTransparent() {\n        return this.internalTrack.info.codec === 'prores' && (this.internalTrack.info.proresFormat === 'ap4h'\n            || this.internalTrack.info.proresFormat === 'ap4x');\n    }\n    async getDecoderConfig() {\n        if (!this.internalTrack.info.codec) {\n            return null;\n        }\n        return this.decoderConfigPromise ??= (async () => {\n            if (this.internalTrack.info.codec === 'avc' && !this.internalTrack.info.codecDescription) {\n                const firstPacket = await this.getFirstPacket({});\n                this.internalTrack.info.avcCodecInfo\n                    = firstPacket && extractAvcDecoderConfigurationRecord(firstPacket.data);\n            }\n            else if (this.internalTrack.info.codec === 'hevc' && !this.internalTrack.info.codecDescription) {\n                const firstPacket = await this.getFirstPacket({});\n                this.internalTrack.info.hevcCodecInfo\n                    = firstPacket && extractHevcDecoderConfigurationRecord(firstPacket.data);\n            }\n            else if (this.internalTrack.info.codec === 'vp9'\n                && (!this.internalTrack.info.vp9CodecInfo\n                    // The codec info extracted from vpcC may claim the color space is \"undefined\"\n                    || !vp9CodecInfoHasColorInfo(this.internalTrack.info.vp9CodecInfo))) {\n                const firstPacket = await this.getFirstPacket({});\n                const packetInfo = firstPacket && extractVp9CodecInfoFromPacket(firstPacket.data);\n                if (packetInfo) {\n                    this.internalTrack.info.vp9CodecInfo = {\n                        ...(this.internalTrack.info.vp9CodecInfo ?? packetInfo),\n                        videoFullRangeFlag: packetInfo.videoFullRangeFlag,\n                        colourPrimaries: packetInfo.colourPrimaries,\n                        transferCharacteristics: packetInfo.transferCharacteristics,\n                        matrixCoefficients: packetInfo.matrixCoefficients,\n                    };\n                }\n            }\n            else if (this.internalTrack.info.codec === 'av1'\n                && (!this.internalTrack.info.av1CodecInfo\n                    // The codec info extracted from av1C may not contain color space information\n                    || !av1CodecInfoHasColorInfo(this.internalTrack.info.av1CodecInfo))) {\n                const firstPacket = await this.getFirstPacket({});\n                const packetInfo = firstPacket && extractAv1CodecInfoFromPacket(firstPacket.data);\n                if (packetInfo) {\n                    this.internalTrack.info.av1CodecInfo = packetInfo;\n                }\n            }\n            else if (this.internalTrack.info.codec === 'prores' && !this.internalTrack.info.proresCodecInfo) {\n                const firstPacket = await this.getFirstPacket({});\n                this.internalTrack.info.proresCodecInfo\n                    = firstPacket && extractProresCodecInfoFromPacket(firstPacket.data);\n            }\n            if (!colorSpaceIsComplete(this.internalTrack.info.colorSpace)) {\n                const colorSpace = extractColorSpace(this.internalTrack.info);\n                // Fill the missing values\n                this.internalTrack.info.colorSpace.primaries ??= colorSpace.primaries;\n                this.internalTrack.info.colorSpace.transfer ??= colorSpace.transfer;\n                this.internalTrack.info.colorSpace.matrix ??= colorSpace.matrix;\n                this.internalTrack.info.colorSpace.fullRange ??= colorSpace.fullRange;\n            }\n            const config = {\n                codec: extractVideoCodecString(this.internalTrack.info),\n                codedWidth: this.internalTrack.info.width,\n                codedHeight: this.internalTrack.info.height,\n                description: this.internalTrack.info.codecDescription ?? undefined,\n                colorSpace: this.internalTrack.info.colorSpace,\n            };\n            if (this.internalTrack.info.width !== this.internalTrack.info.squarePixelWidth\n                || this.internalTrack.info.height !== this.internalTrack.info.squarePixelHeight) {\n                config.displayAspectWidth = this.internalTrack.info.squarePixelWidth;\n                config.displayAspectHeight = this.internalTrack.info.squarePixelHeight;\n            }\n            return config;\n        })();\n    }\n}\nclass IsobmffAudioTrackBacking extends IsobmffTrackBacking {\n    constructor(internalTrack) {\n        super(internalTrack);\n        this.decoderConfigPromise = null;\n    }\n    getType() {\n        return 'audio';\n    }\n    getCodec() {\n        return this.internalTrack.info.codec;\n    }\n    getNumberOfChannels() {\n        return this.internalTrack.info.numberOfChannels;\n    }\n    getSampleRate() {\n        return this.internalTrack.info.sampleRate;\n    }\n    async getDecoderConfig() {\n        if (!this.internalTrack.info.codec) {\n            return null;\n        }\n        return this.decoderConfigPromise ??= (async () => {\n            if (this.internalTrack.info.codec === 'dts' && !this.internalTrack.info.dtsFormat) {\n                // Gotta check the packet to determine the DTS variant\n                const firstPacket = await this.getFirstPacket({});\n                this.internalTrack.info.dtsFormat = firstPacket && extractDtsFourCcFromPacket(firstPacket.data);\n            }\n            return {\n                codec: extractAudioCodecString(this.internalTrack.info),\n                numberOfChannels: this.internalTrack.info.numberOfChannels,\n                sampleRate: this.internalTrack.info.sampleRate,\n                description: this.internalTrack.info.codecDescription ?? undefined,\n            };\n        })();\n    }\n}\nconst getSampleIndexForTimestamp = (sampleTable, timescaleUnits) => {\n    if (sampleTable.sortedCompositionTimeOffsets) {\n        return performPresentationTimeLookup(sampleTable, timescaleUnits, false);\n    }\n    else {\n        const index = binarySearchLessOrEqual(sampleTable.sampleTimingEntries, timescaleUnits, x => x.startDecodeTimestamp);\n        if (index === -1) {\n            return -1;\n        }\n        const entry = sampleTable.sampleTimingEntries[index];\n        if (entry.delta === 0) {\n            return entry.startIndex + entry.count - 1; // All samples share the same timestamp\n        }\n        return entry.startIndex\n            + Math.min(Math.floor((timescaleUnits - entry.startDecodeTimestamp) / entry.delta), entry.count - 1);\n    }\n};\nconst getKeyframeSampleIndexForTimestamp = (sampleTable, timescaleUnits) => {\n    if (!sampleTable.keySampleIndices) {\n        // Every sample is a keyframe\n        return getSampleIndexForTimestamp(sampleTable, timescaleUnits);\n    }\n    if (sampleTable.sortedCompositionTimeOffsets) {\n        return performPresentationTimeLookup(sampleTable, timescaleUnits, true);\n    }\n    else {\n        const sampleIndex = getSampleIndexForTimestamp(sampleTable, timescaleUnits);\n        const index = binarySearchLessOrEqual(sampleTable.keySampleIndices, sampleIndex, x => x);\n        return sampleTable.keySampleIndices[index] ?? -1;\n    }\n};\nconst getSampleInfo = (sampleTable, sampleIndex) => {\n    if (sampleIndex >= sampleTable.sampleCount) {\n        return null;\n    }\n    const timingEntryIndex = binarySearchLessOrEqual(sampleTable.sampleTimingEntries, sampleIndex, x => x.startIndex);\n    const timingEntry = sampleTable.sampleTimingEntries[timingEntryIndex];\n    const decodeTimestamp = timingEntry.startDecodeTimestamp\n        + (sampleIndex - timingEntry.startIndex) * timingEntry.delta;\n    let presentationTimestamp = decodeTimestamp;\n    const offsetEntryIndex = binarySearchLessOrEqual(sampleTable.sampleCompositionTimeOffsets, sampleIndex, x => x.startIndex);\n    const offsetEntry = sampleTable.sampleCompositionTimeOffsets[offsetEntryIndex];\n    if (offsetEntry && sampleIndex - offsetEntry.startIndex < offsetEntry.count) {\n        presentationTimestamp += offsetEntry.offset;\n    }\n    const sampleSize = sampleTable.sampleSizes[Math.min(sampleIndex, sampleTable.sampleSizes.length - 1)];\n    const chunkEntryIndex = binarySearchLessOrEqual(sampleTable.sampleToChunk, sampleIndex, x => x.startSampleIndex);\n    const chunkEntry = sampleTable.sampleToChunk[chunkEntryIndex];\n    const chunkIndex = chunkEntry.startChunkIndex\n        + Math.floor((sampleIndex - chunkEntry.startSampleIndex) / chunkEntry.samplesPerChunk);\n    const chunkOffset = sampleTable.chunkOffsets[chunkIndex];\n    const startSampleIndexOfChunk = chunkEntry.startSampleIndex\n        + (chunkIndex - chunkEntry.startChunkIndex) * chunkEntry.samplesPerChunk;\n    let sampleOffset = chunkOffset;\n    if (sampleTable.sampleSizes.length === 1) {\n        sampleOffset += sampleSize * (sampleIndex - startSampleIndexOfChunk);\n    }\n    else {\n        sampleOffset += sampleTable.cumulativeSampleSizes[sampleIndex]\n            - sampleTable.cumulativeSampleSizes[startSampleIndexOfChunk];\n    }\n    let duration = timingEntry.delta;\n    if (sampleTable.sortedCompositionTimeOffsets) {\n        // In order to accurately compute the duration, we need to take the duration to the next sample in presentation\n        // order, not in decode order\n        const nextPresentationTimestamp = getNextPresentationTimestamp(sampleTable, sampleIndex, presentationTimestamp);\n        if (nextPresentationTimestamp !== null) {\n            duration = nextPresentationTimestamp - presentationTimestamp;\n        }\n    }\n    return {\n        presentationTimestamp,\n        duration,\n        sampleOffset,\n        sampleSize,\n        chunkOffset,\n        isKeyFrame: sampleTable.keySampleIndices\n            ? binarySearchExact(sampleTable.keySampleIndices, sampleIndex, x => x) !== -1\n            : true,\n    };\n};\nconst performPresentationTimeLookup = (sampleTable, timestamp, keyFramesOnly) => {\n    const entries = sampleTable.sortedCompositionTimeOffsets;\n    let bestSampleIndex = -1;\n    let bestTimestamp = -Infinity;\n    // Walk back until no entry can beat the best sample found so far anymore\n    const startIndex = binarySearchLessOrEqual(entries, timestamp, x => x.startTimestamp);\n    for (let i = startIndex; i >= 0; i--) {\n        const entry = entries[i];\n        if (entry.maxLastTimestamp < bestTimestamp) {\n            break;\n        }\n        let sampleIndex = entry.lastTimestamp <= timestamp\n            ? entry.startIndex + entry.count - 1\n            : findFirstSampleInEntry(sampleTable, entry, (_, otherTimestamp) => otherTimestamp > timestamp) - 1;\n        if (keyFramesOnly) {\n            const keySampleIndex = binarySearchLessOrEqual(sampleTable.keySampleIndices, sampleIndex, x => x);\n            sampleIndex = sampleTable.keySampleIndices[keySampleIndex] ?? -1;\n        }\n        if (sampleIndex < entry.startIndex) {\n            continue; // Nothing suitable in this entry\n        }\n        const presentationTimestamp = getDecodeTimestamp(sampleTable, sampleIndex) + entry.offset;\n        if (presentationTimestamp > bestTimestamp\n            || (presentationTimestamp === bestTimestamp && sampleIndex > bestSampleIndex)) {\n            bestSampleIndex = sampleIndex;\n            bestTimestamp = presentationTimestamp;\n        }\n    }\n    return bestSampleIndex;\n};\nconst getNextPresentationTimestamp = (sampleTable, sampleIndex, presentationTimestamp) => {\n    const entries = sampleTable.sortedCompositionTimeOffsets;\n    const lastStartedEntryIndex = binarySearchLessOrEqual(entries, presentationTimestamp, x => x.startTimestamp);\n    // No entry starting later can beat the first one of them\n    let nextTimestamp = entries[lastStartedEntryIndex + 1]?.startTimestamp ?? null;\n    // Walk back until no entry can beat the best sample found so far anymore\n    for (let i = lastStartedEntryIndex; i >= 0; i--) {\n        const entry = entries[i];\n        if (entry.maxLastTimestamp < presentationTimestamp) {\n            break;\n        }\n        const nextSampleIndex = findFirstSampleInEntry(sampleTable, entry, (otherSampleIndex, otherTimestamp) => otherTimestamp > presentationTimestamp\n            || (otherTimestamp === presentationTimestamp && otherSampleIndex > sampleIndex));\n        if (nextSampleIndex === entry.startIndex + entry.count) {\n            continue; // Nothing after the sample in this entry\n        }\n        const timestamp = getDecodeTimestamp(sampleTable, nextSampleIndex) + entry.offset;\n        if (nextTimestamp === null || timestamp < nextTimestamp) {\n            nextTimestamp = timestamp;\n        }\n    }\n    return nextTimestamp;\n};\nconst findFirstSampleInEntry = (sampleTable, entry, predicate) => {\n    // The samples of an entry are in presentation order, so this binary searches for the first one satisfying the\n    // predicate\n    let low = entry.startIndex;\n    let high = entry.startIndex + entry.count;\n    while (low < high) {\n        const mid = Math.floor((low + high) / 2);\n        if (predicate(mid, getDecodeTimestamp(sampleTable, mid) + entry.offset)) {\n            high = mid;\n        }\n        else {\n            low = mid + 1;\n        }\n    }\n    return low;\n};\nconst getDecodeTimestamp = (sampleTable, sampleIndex) => {\n    const timingEntryIndex = binarySearchLessOrEqual(sampleTable.sampleTimingEntries, sampleIndex, x => x.startIndex);\n    const timingEntry = sampleTable.sampleTimingEntries[timingEntryIndex];\n    return timingEntry.startDecodeTimestamp + (sampleIndex - timingEntry.startIndex) * timingEntry.delta;\n};\nconst getNextKeyframeIndexForSample = (sampleTable, sampleIndex) => {\n    if (!sampleTable.keySampleIndices) {\n        return sampleIndex + 1;\n    }\n    const index = binarySearchLessOrEqual(sampleTable.keySampleIndices, sampleIndex, x => x);\n    return sampleTable.keySampleIndices[index + 1] ?? -1;\n};\nconst offsetFragmentTrackDataByTimestamp = (trackData, timestamp) => {\n    trackData.startTimestamp += timestamp;\n    trackData.endTimestamp += timestamp;\n    for (const sample of trackData.samples) {\n        sample.presentationTimestamp += timestamp;\n    }\n    for (const entry of trackData.presentationTimestamps) {\n        entry.presentationTimestamp += timestamp;\n    }\n};\nconst readMatrix = (slice) => {\n    return [\n        readFixed_16_16(slice),\n        readFixed_16_16(slice),\n        readFixed_2_30(slice),\n        readFixed_16_16(slice),\n        readFixed_16_16(slice),\n        readFixed_2_30(slice),\n        readFixed_16_16(slice),\n        readFixed_16_16(slice),\n        readFixed_2_30(slice),\n    ];\n};\nconst applySpsPixelAspectRatio = (track, pixelAspectRatio) => {\n    const info = track.info;\n    if (info.type !== 'video') {\n        return;\n    }\n    const { num, den } = pixelAspectRatio;\n    if (!(num > 0 && den > 0) || num === den) {\n        return;\n    }\n    if (num > den) {\n        info.squarePixelWidth = Math.round(info.width * num / den);\n        info.squarePixelHeight = info.height;\n    }\n    else {\n        info.squarePixelWidth = info.width;\n        info.squarePixelHeight = Math.round(info.height * den / num);\n    }\n};\nconst sampleTableIsEmpty = (sampleTable) => {\n    return sampleTable.sampleSizes.length === 0;\n};\nconst capEntryCounts = (entries, sampleCount) => {\n    while (entries.length > 0 && last(entries).startIndex >= sampleCount) {\n        entries.pop();\n    }\n    const lastEntry = last(entries);\n    if (lastEntry) {\n        lastEntry.count = Math.min(lastEntry.count, sampleCount - lastEntry.startIndex);\n    }\n};\nconst getOrCreateEncryptionAuxInfo = (track) => {\n    if (track.currentFragmentState) {\n        return track.currentFragmentState.encryptionAuxInfo ??= {\n            defaultSampleInfoSize: 0,\n            sampleSizes: null,\n            sampleCount: 0,\n            offset: null,\n            resolved: null,\n        };\n    }\n    else {\n        return track.encryptionAuxInfo ??= {\n            defaultSampleInfoSize: 0,\n            sampleSizes: null,\n            sampleCount: 0,\n            offset: null,\n            resolved: null,\n        };\n    }\n};\nconst resolveEncryptionAuxInfo = async (reader, encryptionInfo, aux) => {\n    if (aux.resolved) {\n        return aux.resolved;\n    }\n    if (aux.offset === null || aux.sampleCount === 0) {\n        throw new Error('Incomplete saiz/saio info; cannot resolve encryption data.');\n    }\n    let totalSize = 0;\n    if (aux.defaultSampleInfoSize > 0) {\n        totalSize = aux.defaultSampleInfoSize * aux.sampleCount;\n    }\n    else {\n        assert(aux.sampleSizes);\n        for (let i = 0; i < aux.sampleCount; i++) {\n            totalSize += aux.sampleSizes[i];\n        }\n    }\n    let slice = reader.requestSlice(aux.offset, totalSize);\n    if (isThenable(slice))\n        slice = await slice;\n    if (!slice) {\n        throw new Error('Failed to read auxiliary encryption info.');\n    }\n    const ivSize = encryptionInfo.defaultPerSampleIvSize;\n    if (ivSize === null) {\n        throw new Error('Invalid file: encrypted track is missing its tenc box.');\n    }\n    // Each aux entry has the same byte layout as a senc entry: IV (of size ivSize, or the constant IV from tenc\n    // when ivSize is 0), then optionally subsample count + [clearLen, protectedLen] pairs. Subsamples are present\n    // iff the entry is larger than the IV.\n    const entries = [];\n    for (let i = 0; i < aux.sampleCount; i++) {\n        const entrySize = aux.defaultSampleInfoSize > 0\n            ? aux.defaultSampleInfoSize\n            : aux.sampleSizes[i];\n        const iv = new Uint8Array(16);\n        if (ivSize > 0) {\n            iv.set(readBytes(slice, ivSize), 0);\n        }\n        else if (encryptionInfo.defaultConstantIv) {\n            iv.set(encryptionInfo.defaultConstantIv, 0);\n        }\n        else {\n            throw new Error('Invalid file: encrypted sample has no IV.');\n        }\n        let subsamples = null;\n        if (entrySize > ivSize) {\n            const subsampleCount = readU16Be(slice);\n            subsamples = [];\n            for (let j = 0; j < subsampleCount; j++) {\n                const clearLen = readU16Be(slice);\n                const protectedLen = readU32Be(slice);\n                subsamples.push({ clearLen, protectedLen });\n            }\n        }\n        entries.push({ iv, subsamples });\n    }\n    aux.resolved = entries;\n    return entries;\n};\nconst getDefaultSampleEncryption = (encryptionInfo) => {\n    if (!encryptionInfo.defaultConstantIv) {\n        return null;\n    }\n    return {\n        iv: encryptionInfo.defaultConstantIv,\n        subsamples: null,\n    };\n};\nconst decryptSample = async (track, sampleEncryption, data, fragment) => {\n    assert(track.encryptionInfo);\n    const encryptionInfo = track.encryptionInfo;\n    if (encryptionInfo.defaultKid === null) {\n        throw new Error('Invalid file: encrypted track is missing its tenc box.');\n    }\n    const keyId = encryptionInfo.defaultKid;\n    let keyBytes;\n    const cacheEntry = track.demuxer.decryptionKeyCache.get(keyId);\n    if (cacheEntry) {\n        keyBytes = await cacheEntry;\n    }\n    else {\n        if (!track.demuxer.input._formatOptions.isobmff?.resolveKeyId) {\n            throw new Error('Encrypted media samples encountered. To decrypt them, please provide a callback for'\n                + ' InputOptions.formatOptions.isobmff.resolveKeyId.');\n        }\n        const promise = (async () => {\n            let psshBoxes = track.demuxer.psshBoxes;\n            if (fragment) {\n                psshBoxes = [\n                    ...psshBoxes,\n                    ...fragment.psshBoxes,\n                ].filter(x => x.keyIds === null || x.keyIds.includes(keyId));\n                // Filter out duplicates\n                for (let i = 0; i < psshBoxes.length - 1; i++) {\n                    for (let j = i + 1; j < psshBoxes.length; j++) {\n                        if (psshBoxesAreEqual(psshBoxes[i], psshBoxes[j])) {\n                            psshBoxes.splice(j, 1);\n                            j--;\n                        }\n                    }\n                }\n            }\n            const keyResult = await track.demuxer.input._formatOptions.isobmff.resolveKeyId({ keyId, psshBoxes });\n            if (!((typeof keyResult === 'string' && keyResult.length === 32 && HEX_STRING_REGEX.test(keyResult))\n                || (keyResult instanceof Uint8Array && keyResult.byteLength === 16))) {\n                throw new TypeError('resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the'\n                    + ' decryption key.');\n            }\n            return keyResult instanceof Uint8Array\n                ? keyResult\n                : hexStringToBytes(keyResult);\n        })();\n        track.demuxer.decryptionKeyCache.set(keyId, promise);\n        keyBytes = await promise;\n    }\n    if (encryptionInfo.scheme === 'cenc' || encryptionInfo.scheme === 'cens') {\n        return decryptCtr(keyBytes, encryptionInfo, sampleEncryption, data);\n    }\n    else {\n        return decryptCbcs(keyBytes, encryptionInfo, sampleEncryption, data);\n    }\n};\nconst decryptCtr = async (key, encryptionInfo, sampleEncryption, data) => {\n    const counter = new Uint8Array(16);\n    counter.set(sampleEncryption.iv, 0);\n    const cryptoKey = await crypto.subtle.importKey('raw', key, { name: 'AES-CTR' }, false, ['decrypt']);\n    const cryptApply = async (input) => {\n        const plaintext = await crypto.subtle.decrypt({ name: 'AES-CTR', counter, length: 64 }, cryptoKey, input);\n        return new Uint8Array(plaintext);\n    };\n    if (!sampleEncryption.subsamples) {\n        // Whole sample is protected, no pattern\n        return cryptApply(data);\n    }\n    assert(encryptionInfo.defaultCryptByteBlock !== null && encryptionInfo.defaultSkipByteBlock !== null);\n    const cryptRanges = collectCryptRanges(sampleEncryption.subsamples, encryptionInfo.defaultCryptByteBlock, encryptionInfo.defaultSkipByteBlock, data.length);\n    // Concatenate all crypt ranges into a single buffer so the continuous CTR counter behavior is preserved\n    let totalCryptLen = 0;\n    for (const range of cryptRanges) {\n        for (const seg of range.perSubsample) {\n            totalCryptLen += seg.length;\n        }\n    }\n    const cryptBuffer = new Uint8Array(totalCryptLen);\n    let writePos = 0;\n    for (const range of cryptRanges) {\n        for (const seg of range.perSubsample) {\n            cryptBuffer.set(data.subarray(seg.offset, seg.offset + seg.length), writePos);\n            writePos += seg.length;\n        }\n    }\n    const plain = await cryptApply(cryptBuffer);\n    // Now let's build the output\n    const output = new Uint8Array(data);\n    let readPos = 0;\n    for (const range of cryptRanges) {\n        for (const seg of range.perSubsample) {\n            output.set(plain.subarray(readPos, readPos + seg.length), seg.offset);\n            readPos += seg.length;\n        }\n    }\n    return output;\n};\nconst decryptCbcs = (key, encryptionInfo, sampleEncryption, data) => {\n    const ctx = new Aes128CbcContext();\n    ctx.init({ key, iv: sampleEncryption.iv });\n    const cryptByteBlock = encryptionInfo.defaultCryptByteBlock;\n    const skipByteBlock = encryptionInfo.defaultSkipByteBlock;\n    assert(cryptByteBlock !== null && skipByteBlock !== null);\n    if (!sampleEncryption.subsamples) {\n        // Whole-sample encryption: straightforward CBC over floor(size / 16) blocks, any trailing bytes stay clear\n        const output = new Uint8Array(data);\n        const numBlocks = Math.floor(data.length / 16);\n        for (let b = 0; b < numBlocks; b++) {\n            const off = b * 16;\n            ctx.in.set(data.subarray(off, off + 16));\n            ctx.decrypt();\n            output.set(ctx.out, off);\n        }\n        return output;\n    }\n    if (cryptByteBlock === 0 && skipByteBlock === 0) {\n        throw new Error('cbcs with subsamples requires pattern encryption.');\n    }\n    const output = new Uint8Array(data);\n    // Pattern decryption: IV is reset at the start of each subsample. Within a subsample, the CBC chain continues\n    // across skipped blocks (the IV after a crypt group carries over to the next crypt group's first block).\n    const cryptRanges = collectCryptRanges(sampleEncryption.subsamples, cryptByteBlock, skipByteBlock, data.length);\n    const ivView = new DataView(sampleEncryption.iv.buffer, sampleEncryption.iv.byteOffset, 16);\n    for (const range of cryptRanges) {\n        // Reset IV per subsample\n        ctx.iv[0] = ivView.getUint32(0, false);\n        ctx.iv[1] = ivView.getUint32(4, false);\n        ctx.iv[2] = ivView.getUint32(8, false);\n        ctx.iv[3] = ivView.getUint32(12, false);\n        for (const seg of range.perSubsample) {\n            // Decrypt length / 16 blocks at this offset\n            const numBlocks = seg.length / 16;\n            for (let b = 0; b < numBlocks; b++) {\n                const offset = seg.offset + b * 16;\n                ctx.in.set(data.subarray(offset, offset + 16));\n                ctx.decrypt();\n                output.set(ctx.out, offset);\n            }\n        }\n    }\n    return output;\n};\nconst collectCryptRanges = (subsamples, cryptByteBlock, skipByteBlock, dataLength) => {\n    const ranges = [];\n    const hasPattern = cryptByteBlock !== 0 || skipByteBlock !== 0;\n    let cursor = 0;\n    for (const subsample of subsamples) {\n        if (cursor + subsample.clearLen + subsample.protectedLen > dataLength) {\n            throw new Error('Invalid encryption info: subsamples exceed the sample size.');\n        }\n        cursor += subsample.clearLen;\n        const perSubsample = [];\n        if (!hasPattern) {\n            if (subsample.protectedLen > 0) {\n                perSubsample.push({ offset: cursor, length: subsample.protectedLen });\n            }\n            cursor += subsample.protectedLen;\n        }\n        else {\n            let remaining = subsample.protectedLen;\n            let pos = cursor;\n            while (remaining > 0) {\n                if (remaining < 16 * cryptByteBlock) {\n                    break; // Partial final crypt group stays clear\n                }\n                const cryptBytes = 16 * cryptByteBlock;\n                perSubsample.push({ offset: pos, length: cryptBytes });\n                pos += cryptBytes;\n                remaining -= cryptBytes;\n                const skipBytes = Math.min(16 * skipByteBlock, remaining);\n                pos += skipBytes;\n                remaining -= skipBytes;\n            }\n            cursor += subsample.protectedLen;\n        }\n        ranges.push({ perSubsample });\n    }\n    return ranges;\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { assert, assertNever, isThenable, textDecoder, textEncoder } from '../misc.js';\nimport { readBytes, readF32Be, readF64Be, readU8 } from '../reader.js';\n/** Wrapper around a number to be able to differentiate it in the writer. */\nexport class EBMLFloat32 {\n    constructor(value) {\n        this.value = value;\n    }\n}\n/** Wrapper around a number to be able to differentiate it in the writer. */\nexport class EBMLFloat64 {\n    constructor(value) {\n        this.value = value;\n    }\n}\n/** Wrapper around a number to be able to differentiate it in the writer. */\nexport class EBMLSignedInt {\n    constructor(value) {\n        this.value = value;\n    }\n}\nexport class EBMLUnicodeString {\n    constructor(value) {\n        this.value = value;\n    }\n}\n/** Defines some of the EBML IDs used by Matroska files. */\nexport var EBMLId;\n(function (EBMLId) {\n    EBMLId[EBMLId[\"EBML\"] = 440786851] = \"EBML\";\n    EBMLId[EBMLId[\"EBMLVersion\"] = 17030] = \"EBMLVersion\";\n    EBMLId[EBMLId[\"EBMLReadVersion\"] = 17143] = \"EBMLReadVersion\";\n    EBMLId[EBMLId[\"EBMLMaxIDLength\"] = 17138] = \"EBMLMaxIDLength\";\n    EBMLId[EBMLId[\"EBMLMaxSizeLength\"] = 17139] = \"EBMLMaxSizeLength\";\n    EBMLId[EBMLId[\"DocType\"] = 17026] = \"DocType\";\n    EBMLId[EBMLId[\"DocTypeVersion\"] = 17031] = \"DocTypeVersion\";\n    EBMLId[EBMLId[\"DocTypeReadVersion\"] = 17029] = \"DocTypeReadVersion\";\n    EBMLId[EBMLId[\"Void\"] = 236] = \"Void\";\n    EBMLId[EBMLId[\"Segment\"] = 408125543] = \"Segment\";\n    EBMLId[EBMLId[\"SeekHead\"] = 290298740] = \"SeekHead\";\n    EBMLId[EBMLId[\"Seek\"] = 19899] = \"Seek\";\n    EBMLId[EBMLId[\"SeekID\"] = 21419] = \"SeekID\";\n    EBMLId[EBMLId[\"SeekPosition\"] = 21420] = \"SeekPosition\";\n    EBMLId[EBMLId[\"Duration\"] = 17545] = \"Duration\";\n    EBMLId[EBMLId[\"Info\"] = 357149030] = \"Info\";\n    EBMLId[EBMLId[\"TimestampScale\"] = 2807729] = \"TimestampScale\";\n    EBMLId[EBMLId[\"MuxingApp\"] = 19840] = \"MuxingApp\";\n    EBMLId[EBMLId[\"WritingApp\"] = 22337] = \"WritingApp\";\n    EBMLId[EBMLId[\"Tracks\"] = 374648427] = \"Tracks\";\n    EBMLId[EBMLId[\"TrackEntry\"] = 174] = \"TrackEntry\";\n    EBMLId[EBMLId[\"TrackNumber\"] = 215] = \"TrackNumber\";\n    EBMLId[EBMLId[\"TrackUID\"] = 29637] = \"TrackUID\";\n    EBMLId[EBMLId[\"TrackType\"] = 131] = \"TrackType\";\n    EBMLId[EBMLId[\"FlagEnabled\"] = 185] = \"FlagEnabled\";\n    EBMLId[EBMLId[\"FlagDefault\"] = 136] = \"FlagDefault\";\n    EBMLId[EBMLId[\"FlagForced\"] = 21930] = \"FlagForced\";\n    EBMLId[EBMLId[\"FlagOriginal\"] = 21934] = \"FlagOriginal\";\n    EBMLId[EBMLId[\"FlagHearingImpaired\"] = 21931] = \"FlagHearingImpaired\";\n    EBMLId[EBMLId[\"FlagVisualImpaired\"] = 21932] = \"FlagVisualImpaired\";\n    EBMLId[EBMLId[\"FlagCommentary\"] = 21935] = \"FlagCommentary\";\n    EBMLId[EBMLId[\"FlagLacing\"] = 156] = \"FlagLacing\";\n    EBMLId[EBMLId[\"Name\"] = 21358] = \"Name\";\n    EBMLId[EBMLId[\"Language\"] = 2274716] = \"Language\";\n    EBMLId[EBMLId[\"LanguageBCP47\"] = 2274717] = \"LanguageBCP47\";\n    EBMLId[EBMLId[\"CodecID\"] = 134] = \"CodecID\";\n    EBMLId[EBMLId[\"CodecPrivate\"] = 25506] = \"CodecPrivate\";\n    EBMLId[EBMLId[\"CodecDelay\"] = 22186] = \"CodecDelay\";\n    EBMLId[EBMLId[\"SeekPreRoll\"] = 22203] = \"SeekPreRoll\";\n    EBMLId[EBMLId[\"DefaultDuration\"] = 2352003] = \"DefaultDuration\";\n    EBMLId[EBMLId[\"Video\"] = 224] = \"Video\";\n    EBMLId[EBMLId[\"PixelWidth\"] = 176] = \"PixelWidth\";\n    EBMLId[EBMLId[\"PixelHeight\"] = 186] = \"PixelHeight\";\n    EBMLId[EBMLId[\"DisplayWidth\"] = 21680] = \"DisplayWidth\";\n    EBMLId[EBMLId[\"DisplayHeight\"] = 21690] = \"DisplayHeight\";\n    EBMLId[EBMLId[\"DisplayUnit\"] = 21682] = \"DisplayUnit\";\n    EBMLId[EBMLId[\"AlphaMode\"] = 21440] = \"AlphaMode\";\n    EBMLId[EBMLId[\"Audio\"] = 225] = \"Audio\";\n    EBMLId[EBMLId[\"SamplingFrequency\"] = 181] = \"SamplingFrequency\";\n    EBMLId[EBMLId[\"Channels\"] = 159] = \"Channels\";\n    EBMLId[EBMLId[\"BitDepth\"] = 25188] = \"BitDepth\";\n    EBMLId[EBMLId[\"SimpleBlock\"] = 163] = \"SimpleBlock\";\n    EBMLId[EBMLId[\"BlockGroup\"] = 160] = \"BlockGroup\";\n    EBMLId[EBMLId[\"Block\"] = 161] = \"Block\";\n    EBMLId[EBMLId[\"BlockAdditions\"] = 30113] = \"BlockAdditions\";\n    EBMLId[EBMLId[\"BlockMore\"] = 166] = \"BlockMore\";\n    EBMLId[EBMLId[\"BlockAdditional\"] = 165] = \"BlockAdditional\";\n    EBMLId[EBMLId[\"BlockAddID\"] = 238] = \"BlockAddID\";\n    EBMLId[EBMLId[\"BlockDuration\"] = 155] = \"BlockDuration\";\n    EBMLId[EBMLId[\"ReferenceBlock\"] = 251] = \"ReferenceBlock\";\n    EBMLId[EBMLId[\"Cluster\"] = 524531317] = \"Cluster\";\n    EBMLId[EBMLId[\"Timestamp\"] = 231] = \"Timestamp\";\n    EBMLId[EBMLId[\"Cues\"] = 475249515] = \"Cues\";\n    EBMLId[EBMLId[\"CuePoint\"] = 187] = \"CuePoint\";\n    EBMLId[EBMLId[\"CueTime\"] = 179] = \"CueTime\";\n    EBMLId[EBMLId[\"CueTrackPositions\"] = 183] = \"CueTrackPositions\";\n    EBMLId[EBMLId[\"CueTrack\"] = 247] = \"CueTrack\";\n    EBMLId[EBMLId[\"CueClusterPosition\"] = 241] = \"CueClusterPosition\";\n    EBMLId[EBMLId[\"Colour\"] = 21936] = \"Colour\";\n    EBMLId[EBMLId[\"MatrixCoefficients\"] = 21937] = \"MatrixCoefficients\";\n    EBMLId[EBMLId[\"TransferCharacteristics\"] = 21946] = \"TransferCharacteristics\";\n    EBMLId[EBMLId[\"Primaries\"] = 21947] = \"Primaries\";\n    EBMLId[EBMLId[\"Range\"] = 21945] = \"Range\";\n    EBMLId[EBMLId[\"Projection\"] = 30320] = \"Projection\";\n    EBMLId[EBMLId[\"ProjectionType\"] = 30321] = \"ProjectionType\";\n    EBMLId[EBMLId[\"ProjectionPoseYaw\"] = 30323] = \"ProjectionPoseYaw\";\n    EBMLId[EBMLId[\"ProjectionPosePitch\"] = 30324] = \"ProjectionPosePitch\";\n    EBMLId[EBMLId[\"ProjectionPoseRoll\"] = 30325] = \"ProjectionPoseRoll\";\n    EBMLId[EBMLId[\"Attachments\"] = 423732329] = \"Attachments\";\n    EBMLId[EBMLId[\"AttachedFile\"] = 24999] = \"AttachedFile\";\n    EBMLId[EBMLId[\"FileDescription\"] = 18046] = \"FileDescription\";\n    EBMLId[EBMLId[\"FileName\"] = 18030] = \"FileName\";\n    EBMLId[EBMLId[\"FileMediaType\"] = 18016] = \"FileMediaType\";\n    EBMLId[EBMLId[\"FileData\"] = 18012] = \"FileData\";\n    EBMLId[EBMLId[\"FileUID\"] = 18094] = \"FileUID\";\n    EBMLId[EBMLId[\"Chapters\"] = 272869232] = \"Chapters\";\n    EBMLId[EBMLId[\"Tags\"] = 307544935] = \"Tags\";\n    EBMLId[EBMLId[\"Tag\"] = 29555] = \"Tag\";\n    EBMLId[EBMLId[\"Targets\"] = 25536] = \"Targets\";\n    EBMLId[EBMLId[\"TargetTypeValue\"] = 26826] = \"TargetTypeValue\";\n    EBMLId[EBMLId[\"TargetType\"] = 25546] = \"TargetType\";\n    EBMLId[EBMLId[\"TagTrackUID\"] = 25541] = \"TagTrackUID\";\n    EBMLId[EBMLId[\"TagEditionUID\"] = 25545] = \"TagEditionUID\";\n    EBMLId[EBMLId[\"TagChapterUID\"] = 25540] = \"TagChapterUID\";\n    EBMLId[EBMLId[\"TagAttachmentUID\"] = 25542] = \"TagAttachmentUID\";\n    EBMLId[EBMLId[\"SimpleTag\"] = 26568] = \"SimpleTag\";\n    EBMLId[EBMLId[\"TagName\"] = 17827] = \"TagName\";\n    EBMLId[EBMLId[\"TagLanguage\"] = 17530] = \"TagLanguage\";\n    EBMLId[EBMLId[\"TagString\"] = 17543] = \"TagString\";\n    EBMLId[EBMLId[\"TagBinary\"] = 17541] = \"TagBinary\";\n    EBMLId[EBMLId[\"ContentEncodings\"] = 28032] = \"ContentEncodings\";\n    EBMLId[EBMLId[\"ContentEncoding\"] = 25152] = \"ContentEncoding\";\n    EBMLId[EBMLId[\"ContentEncodingOrder\"] = 20529] = \"ContentEncodingOrder\";\n    EBMLId[EBMLId[\"ContentEncodingScope\"] = 20530] = \"ContentEncodingScope\";\n    EBMLId[EBMLId[\"ContentCompression\"] = 20532] = \"ContentCompression\";\n    EBMLId[EBMLId[\"ContentCompAlgo\"] = 16980] = \"ContentCompAlgo\";\n    EBMLId[EBMLId[\"ContentCompSettings\"] = 16981] = \"ContentCompSettings\";\n    EBMLId[EBMLId[\"ContentEncryption\"] = 20533] = \"ContentEncryption\";\n})(EBMLId || (EBMLId = {}));\nexport const LEVEL_0_EBML_IDS = [\n    EBMLId.EBML,\n    EBMLId.Segment,\n];\n// All the stuff that can appear in a segment, basically\nexport const LEVEL_1_EBML_IDS = [\n    EBMLId.SeekHead,\n    EBMLId.Info,\n    EBMLId.Cluster,\n    EBMLId.Tracks,\n    EBMLId.Cues,\n    EBMLId.Attachments,\n    EBMLId.Chapters,\n    EBMLId.Tags,\n];\nexport const LEVEL_0_AND_1_EBML_IDS = [\n    ...LEVEL_0_EBML_IDS,\n    ...LEVEL_1_EBML_IDS,\n];\nexport const measureUnsignedInt = (value) => {\n    if (value < (1 << 8)) {\n        return 1;\n    }\n    else if (value < (1 << 16)) {\n        return 2;\n    }\n    else if (value < (1 << 24)) {\n        return 3;\n    }\n    else if (value < 2 ** 32) {\n        return 4;\n    }\n    else if (value < 2 ** 40) {\n        return 5;\n    }\n    else {\n        return 6;\n    }\n};\nexport const measureUnsignedBigInt = (value) => {\n    if (value < (1n << 8n)) {\n        return 1;\n    }\n    else if (value < (1n << 16n)) {\n        return 2;\n    }\n    else if (value < (1n << 24n)) {\n        return 3;\n    }\n    else if (value < (1n << 32n)) {\n        return 4;\n    }\n    else if (value < (1n << 40n)) {\n        return 5;\n    }\n    else if (value < (1n << 48n)) {\n        return 6;\n    }\n    else if (value < (1n << 56n)) {\n        return 7;\n    }\n    else {\n        return 8;\n    }\n};\nexport const measureSignedInt = (value) => {\n    if (value >= -(1 << 6) && value < (1 << 6)) {\n        return 1;\n    }\n    else if (value >= -(1 << 13) && value < (1 << 13)) {\n        return 2;\n    }\n    else if (value >= -(1 << 20) && value < (1 << 20)) {\n        return 3;\n    }\n    else if (value >= -(1 << 27) && value < (1 << 27)) {\n        return 4;\n    }\n    else if (value >= -(2 ** 34) && value < 2 ** 34) {\n        return 5;\n    }\n    else {\n        return 6;\n    }\n};\nexport const measureVarInt = (value) => {\n    if (value < (1 << 7) - 1) {\n        /** Top bit is set, leaving 7 bits to hold the integer, but we can't store\n         * 127 because \"all bits set to one\" is a reserved value. Same thing for the\n         * other cases below:\n         */\n        return 1;\n    }\n    else if (value < (1 << 14) - 1) {\n        return 2;\n    }\n    else if (value < (1 << 21) - 1) {\n        return 3;\n    }\n    else if (value < (1 << 28) - 1) {\n        return 4;\n    }\n    else if (value < 2 ** 35 - 1) {\n        return 5;\n    }\n    else if (value < 2 ** 42 - 1) {\n        return 6;\n    }\n    else {\n        throw new Error('EBML varint size not supported ' + value);\n    }\n};\nexport class EBMLWriter {\n    constructor(writer) {\n        this.writer = writer;\n        this.helper = new Uint8Array(8);\n        this.helperView = new DataView(this.helper.buffer);\n        /**\n         * Stores the position from the start of the file to where EBML elements have been written. This is used to\n         * rewrite/edit elements that were already added before, and to measure sizes of things.\n         */\n        this.offsets = new WeakMap();\n        /** Same as offsets, but stores position where the element's data starts (after ID and size fields). */\n        this.dataOffsets = new WeakMap();\n    }\n    writeByte(value) {\n        this.helperView.setUint8(0, value);\n        this.writer.write(this.helper.subarray(0, 1));\n    }\n    writeFloat32(value) {\n        this.helperView.setFloat32(0, value, false);\n        this.writer.write(this.helper.subarray(0, 4));\n    }\n    writeFloat64(value) {\n        this.helperView.setFloat64(0, value, false);\n        this.writer.write(this.helper);\n    }\n    writeUnsignedInt(value, width = measureUnsignedInt(value)) {\n        let pos = 0;\n        // Each case falls through:\n        switch (width) {\n            case 6:\n                // Need to use division to access >32 bits of floating point var\n                this.helperView.setUint8(pos++, (value / 2 ** 40) | 0);\n            // eslint-disable-next-line no-fallthrough\n            case 5:\n                this.helperView.setUint8(pos++, (value / 2 ** 32) | 0);\n            // eslint-disable-next-line no-fallthrough\n            case 4:\n                this.helperView.setUint8(pos++, value >> 24);\n            // eslint-disable-next-line no-fallthrough\n            case 3:\n                this.helperView.setUint8(pos++, value >> 16);\n            // eslint-disable-next-line no-fallthrough\n            case 2:\n                this.helperView.setUint8(pos++, value >> 8);\n            // eslint-disable-next-line no-fallthrough\n            case 1:\n                this.helperView.setUint8(pos++, value);\n                break;\n            default:\n                throw new Error('Bad unsigned int size ' + width);\n        }\n        this.writer.write(this.helper.subarray(0, pos));\n    }\n    writeUnsignedBigInt(value, width = measureUnsignedBigInt(value)) {\n        let pos = 0;\n        for (let i = width - 1; i >= 0; i--) {\n            this.helperView.setUint8(pos++, Number((value >> BigInt(i * 8)) & 0xffn));\n        }\n        this.writer.write(this.helper.subarray(0, pos));\n    }\n    writeSignedInt(value, width = measureSignedInt(value)) {\n        if (value < 0) {\n            // Two's complement stuff\n            value += 2 ** (width * 8);\n        }\n        this.writeUnsignedInt(value, width);\n    }\n    writeVarInt(value, width = measureVarInt(value)) {\n        let pos = 0;\n        switch (width) {\n            case 1:\n                this.helperView.setUint8(pos++, (1 << 7) | value);\n                break;\n            case 2:\n                this.helperView.setUint8(pos++, (1 << 6) | (value >> 8));\n                this.helperView.setUint8(pos++, value);\n                break;\n            case 3:\n                this.helperView.setUint8(pos++, (1 << 5) | (value >> 16));\n                this.helperView.setUint8(pos++, value >> 8);\n                this.helperView.setUint8(pos++, value);\n                break;\n            case 4:\n                this.helperView.setUint8(pos++, (1 << 4) | (value >> 24));\n                this.helperView.setUint8(pos++, value >> 16);\n                this.helperView.setUint8(pos++, value >> 8);\n                this.helperView.setUint8(pos++, value);\n                break;\n            case 5:\n                /**\n                 * JavaScript converts its doubles to 32-bit integers for bitwise\n                 * operations, so we need to do a division by 2^32 instead of a\n                 * right-shift of 32 to retain those top 3 bits\n                 */\n                this.helperView.setUint8(pos++, (1 << 3) | ((value / 2 ** 32) & 0x7));\n                this.helperView.setUint8(pos++, value >> 24);\n                this.helperView.setUint8(pos++, value >> 16);\n                this.helperView.setUint8(pos++, value >> 8);\n                this.helperView.setUint8(pos++, value);\n                break;\n            case 6:\n                this.helperView.setUint8(pos++, (1 << 2) | ((value / 2 ** 40) & 0x3));\n                this.helperView.setUint8(pos++, (value / 2 ** 32) | 0);\n                this.helperView.setUint8(pos++, value >> 24);\n                this.helperView.setUint8(pos++, value >> 16);\n                this.helperView.setUint8(pos++, value >> 8);\n                this.helperView.setUint8(pos++, value);\n                break;\n            default:\n                throw new Error('Bad EBML varint size ' + width);\n        }\n        this.writer.write(this.helper.subarray(0, pos));\n    }\n    writeAsciiString(str) {\n        this.writer.write(new Uint8Array(str.split('').map(x => x.charCodeAt(0))));\n    }\n    writeEBML(data) {\n        if (data === null)\n            return;\n        if (data instanceof Uint8Array) {\n            this.writer.write(data);\n        }\n        else if (Array.isArray(data)) {\n            for (const elem of data) {\n                this.writeEBML(elem);\n            }\n        }\n        else {\n            this.offsets.set(data, this.writer.getPos());\n            this.writeUnsignedInt(data.id); // ID field\n            if (Array.isArray(data.data)) {\n                const sizePos = this.writer.getPos();\n                const sizeSize = data.size === -1 ? 1 : (data.size ?? 4);\n                if (data.size === -1) {\n                    // Write the reserved all-one-bits marker for unknown/unbounded size.\n                    this.writeByte(0xff);\n                }\n                else {\n                    this.writer.seek(this.writer.getPos() + sizeSize);\n                }\n                const startPos = this.writer.getPos();\n                this.dataOffsets.set(data, startPos);\n                this.writeEBML(data.data);\n                if (data.size !== -1) {\n                    const size = this.writer.getPos() - startPos;\n                    const endPos = this.writer.getPos();\n                    this.writer.seek(sizePos);\n                    this.writeVarInt(size, sizeSize);\n                    this.writer.seek(endPos);\n                }\n            }\n            else if (typeof data.data === 'number') {\n                const size = data.size ?? measureUnsignedInt(data.data);\n                this.writeVarInt(size);\n                this.writeUnsignedInt(data.data, size);\n            }\n            else if (typeof data.data === 'bigint') {\n                const size = data.size ?? measureUnsignedBigInt(data.data);\n                this.writeVarInt(size);\n                this.writeUnsignedBigInt(data.data, size);\n            }\n            else if (typeof data.data === 'string') {\n                this.writeVarInt(data.data.length);\n                this.writeAsciiString(data.data);\n            }\n            else if (data.data instanceof Uint8Array) {\n                this.writeVarInt(data.data.byteLength, data.size);\n                this.writer.write(data.data);\n            }\n            else if (data.data instanceof EBMLFloat32) {\n                this.writeVarInt(4);\n                this.writeFloat32(data.data.value);\n            }\n            else if (data.data instanceof EBMLFloat64) {\n                this.writeVarInt(8);\n                this.writeFloat64(data.data.value);\n            }\n            else if (data.data instanceof EBMLSignedInt) {\n                const size = data.size ?? measureSignedInt(data.data.value);\n                this.writeVarInt(size);\n                this.writeSignedInt(data.data.value, size);\n            }\n            else if (data.data instanceof EBMLUnicodeString) {\n                const bytes = textEncoder.encode(data.data.value);\n                this.writeVarInt(bytes.length);\n                this.writer.write(bytes);\n            }\n            else {\n                assertNever(data.data);\n            }\n        }\n    }\n}\nexport const MAX_VAR_INT_SIZE = 8;\nexport const MIN_HEADER_SIZE = 2; // 1-byte ID and 1-byte size\nexport const MAX_HEADER_SIZE = 2 * MAX_VAR_INT_SIZE; // 8-byte ID and 8-byte size\nexport const readVarIntSize = (slice) => {\n    if (slice.remainingLength < 1) {\n        return null;\n    }\n    const firstByte = readU8(slice);\n    slice.skip(-1);\n    if (firstByte === 0) {\n        return null; // Invalid VINT\n    }\n    let width = 1;\n    let mask = 0x80;\n    while ((firstByte & mask) === 0) {\n        width++;\n        mask >>= 1;\n    }\n    // Check if we have enough bytes to read the full varint\n    if (slice.remainingLength < width) {\n        return null;\n    }\n    return width;\n};\nexport const readVarInt = (slice) => {\n    if (slice.remainingLength < 1) {\n        return null;\n    }\n    // Read the first byte to determine the width of the variable-length integer\n    const firstByte = readU8(slice);\n    if (firstByte === 0) {\n        return null; // Invalid VINT\n    }\n    // Find the position of VINT_MARKER, which determines the width\n    let width = 1;\n    let mask = 1 << 7;\n    while ((firstByte & mask) === 0) {\n        width++;\n        mask >>= 1;\n    }\n    if (slice.remainingLength < width - 1) {\n        // Not enough bytes\n        return null;\n    }\n    // First byte's value needs the marker bit cleared\n    let value = firstByte & (mask - 1);\n    // Read remaining bytes\n    for (let i = 1; i < width; i++) {\n        value *= 1 << 8;\n        value += readU8(slice);\n    }\n    return value;\n};\nexport const readUnsignedInt = (slice, width) => {\n    // Zero width is valid and means zero\n    if (width > 8) {\n        throw new Error('Bad unsigned int size ' + width);\n    }\n    let value = 0;\n    // Read bytes from most significant to least significant\n    for (let i = 0; i < width; i++) {\n        value *= 1 << 8;\n        value += readU8(slice);\n    }\n    return value;\n};\nexport const readUnsignedBigInt = (slice, width) => {\n    if (width < 1 || width > 8) {\n        throw new Error('Bad unsigned int size ' + width);\n    }\n    let value = 0n;\n    for (let i = 0; i < width; i++) {\n        value <<= 8n;\n        value += BigInt(readU8(slice));\n    }\n    return value;\n};\nexport const readSignedInt = (slice, width) => {\n    let value = readUnsignedInt(slice, width);\n    // If the highest bit is set, convert from two's complement\n    if (value & (1 << (width * 8 - 1))) {\n        value -= 2 ** (width * 8);\n    }\n    return value;\n};\nexport const readElementId = (slice) => {\n    const size = readVarIntSize(slice);\n    if (size === null) {\n        return null;\n    }\n    if (slice.remainingLength < size) {\n        return null; // It don't fit\n    }\n    const id = readUnsignedInt(slice, size);\n    return id;\n};\n/** Returns `undefined` to indicate the EBML undefined size. Returns `null` if the size couldn't be read. */\nexport const readElementSize = (slice) => {\n    // Need at least 1 byte to read the size\n    if (slice.remainingLength < 1) {\n        return null;\n    }\n    const firstByte = readU8(slice);\n    if (firstByte === 0xff) {\n        return undefined;\n    }\n    slice.skip(-1);\n    const size = readVarInt(slice);\n    if (size === null) {\n        return null;\n    }\n    // In some (livestreamed) files, this is the value of the size field. While this technically is just a very\n    // large number, it is intended to behave like the reserved size 0xFF, meaning the size is undefined. We\n    // catch the number here. Note that it cannot be perfectly represented as a double, but the comparison works\n    // nonetheless.\n    // eslint-disable-next-line no-loss-of-precision\n    if (size === 0x00ffffffffffffff) {\n        return undefined;\n    }\n    return size;\n};\nexport const readElementHeader = (slice) => {\n    assert(slice.remainingLength >= MIN_HEADER_SIZE);\n    const id = readElementId(slice);\n    if (id === null) {\n        return null;\n    }\n    const size = readElementSize(slice);\n    if (size === null) {\n        return null;\n    }\n    return { id, size };\n};\nexport const readAsciiString = (slice, length) => {\n    const bytes = readBytes(slice, length);\n    // Actual string length might be shorter due to null terminators\n    let str = '';\n    for (let i = 0; i < length && bytes[i] !== 0; i++) {\n        str += String.fromCharCode(bytes[i]);\n    }\n    return str;\n};\nexport const readUnicodeString = (slice, length) => {\n    const bytes = readBytes(slice, length);\n    // Actual string length might be shorter due to null terminators\n    let strLength = 0;\n    while (strLength < length && bytes[strLength] !== 0) {\n        strLength += 1;\n    }\n    return textDecoder.decode(bytes.subarray(0, strLength));\n};\nexport const readFloat = (slice, width) => {\n    if (width === 0) {\n        return 0;\n    }\n    if (width !== 4 && width !== 8) {\n        throw new Error('Bad float size ' + width);\n    }\n    return width === 4 ? readF32Be(slice) : readF64Be(slice);\n};\n/** Returns the byte offset in the file of the next element with a matching ID. */\nexport const searchForNextElementId = async (reader, startPos, ids, until) => {\n    const idsSet = new Set(ids);\n    let currentPos = startPos;\n    while (until === null || currentPos < until) {\n        let slice = reader.requestSliceRange(currentPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE);\n        if (isThenable(slice))\n            slice = await slice;\n        if (!slice)\n            break;\n        const elementHeader = readElementHeader(slice);\n        if (!elementHeader) {\n            break;\n        }\n        if (idsSet.has(elementHeader.id)) {\n            return { pos: currentPos, found: true };\n        }\n        assertDefinedSize(elementHeader.size);\n        currentPos = slice.filePos + elementHeader.size;\n    }\n    return { pos: (until !== null && until > currentPos) ? until : currentPos, found: false };\n};\n/** Searches for the next occurrence of an element ID using a naive byte-wise search. */\nexport const resync = async (reader, startPos, ids, until) => {\n    const CHUNK_SIZE = 2 ** 16; // So we don't need to grab thousands of slices\n    const idsSet = new Set(ids);\n    let currentPos = startPos;\n    while (currentPos < until) {\n        let slice = reader.requestSliceRange(currentPos, 0, Math.min(CHUNK_SIZE, until - currentPos));\n        if (isThenable(slice))\n            slice = await slice;\n        if (!slice || slice.length === 0)\n            break;\n        // The last few positions are left for the next chunk so their IDs can be read in full. Close to the end, there\n        // is no next chunk to speak of, so we must still make progress.\n        const positionsToCheck = Math.max(slice.length - MAX_VAR_INT_SIZE, 1);\n        for (let i = 0; i < positionsToCheck; i++) {\n            slice.filePos = currentPos;\n            const elementId = readElementId(slice);\n            if (elementId !== null && idsSet.has(elementId)) {\n                return currentPos;\n            }\n            currentPos++;\n        }\n    }\n    return null;\n};\nexport const CODEC_STRING_MAP = {\n    'avc': 'V_MPEG4/ISO/AVC',\n    'hevc': 'V_MPEGH/ISO/HEVC',\n    'vp8': 'V_VP8',\n    'vp9': 'V_VP9',\n    'av1': 'V_AV1',\n    'prores': 'V_PRORES',\n    'aac': 'A_AAC',\n    'mp3': 'A_MPEG/L3',\n    'opus': 'A_OPUS',\n    'vorbis': 'A_VORBIS',\n    'flac': 'A_FLAC',\n    'ac3': 'A_AC3',\n    'eac3': 'A_EAC3',\n    'dts': 'A_DTS',\n    'pcm-u8': 'A_PCM/INT/LIT',\n    'pcm-s16': 'A_PCM/INT/LIT',\n    'pcm-s16be': 'A_PCM/INT/BIG',\n    'pcm-s24': 'A_PCM/INT/LIT',\n    'pcm-s24be': 'A_PCM/INT/BIG',\n    'pcm-s32': 'A_PCM/INT/LIT',\n    'pcm-s32be': 'A_PCM/INT/BIG',\n    'pcm-f32': 'A_PCM/FLOAT/IEEE',\n    'pcm-f64': 'A_PCM/FLOAT/IEEE',\n    'webvtt': 'S_TEXT/WEBVTT',\n};\nexport function assertDefinedSize(size) {\n    if (size === undefined) {\n        throw new Error('Undefined element size is used in a place where it is not supported.');\n    }\n}\n;\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nexport const buildMatroskaMimeType = (info) => {\n    const base = info.hasVideo\n        ? 'video/'\n        : info.hasAudio\n            ? 'audio/'\n            : 'application/';\n    let string = base + (info.isWebM ? 'webm' : 'x-matroska');\n    if (info.codecStrings.length > 0) {\n        const uniqueCodecMimeTypes = [...new Set(info.codecStrings.filter(Boolean))];\n        string += `; codecs=\"${uniqueCodecMimeTypes.join(', ')}\"`;\n    }\n    return string;\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { extractAv1CodecInfoFromPacket, extractDtsFourCcFromPacket, extractAvcDecoderConfigurationRecord, extractHevcDecoderConfigurationRecord, extractProresCodecInfoFromPacket, extractVp9CodecInfoFromPacket, } from '../codec-data.js';\nimport { extractAudioCodecString, extractColorSpace, extractVideoCodecString, OPUS_SAMPLE_RATE, PRORES_FOURCCS, } from '../codec.js';\nimport { Demuxer } from '../demuxer.js';\nimport { Logging } from '../logging.js';\nimport { AttachedFile, DEFAULT_TRACK_DISPOSITION } from '../metadata.js';\nimport { assert, binarySearchLessOrEqual, COLOR_PRIMARIES_MAP_INVERSE, colorSpaceIsComplete, EMPTY_COLOR_SPACE, findLastIndex, isIso639Dash2LanguageCode, isThenable, last, MATRIX_COEFFICIENTS_MAP_INVERSE, centeredTransformationMatrix, DEG_TO_RAD, multiplyMatrices, normalizeRotation, rotationMatrix, roundIfAlmostInteger, scaleMatrix, textDecoder, toDataView, TRANSFER_CHARACTERISTICS_MAP_INVERSE, UNDETERMINED_LANGUAGE, } from '../misc.js';\nimport { EncodedPacket, PLACEHOLDER_DATA } from '../packet.js';\nimport { assertDefinedSize, CODEC_STRING_MAP, EBMLId, LEVEL_0_AND_1_EBML_IDS, LEVEL_1_EBML_IDS, MAX_HEADER_SIZE, MIN_HEADER_SIZE, readAsciiString, readUnicodeString, readElementHeader, readElementId, readFloat, readUnsignedInt, readVarInt, resync, searchForNextElementId, readUnsignedBigInt, } from './ebml.js';\nimport { buildMatroskaMimeType } from './matroska-misc.js';\nimport { FileSlice, readBytes, readI16Be, readU8 } from '../reader.js';\nvar BlockLacing;\n(function (BlockLacing) {\n    BlockLacing[BlockLacing[\"None\"] = 0] = \"None\";\n    BlockLacing[BlockLacing[\"Xiph\"] = 1] = \"Xiph\";\n    BlockLacing[BlockLacing[\"FixedSize\"] = 2] = \"FixedSize\";\n    BlockLacing[BlockLacing[\"Ebml\"] = 3] = \"Ebml\";\n})(BlockLacing || (BlockLacing = {}));\nvar ContentEncodingScope;\n(function (ContentEncodingScope) {\n    ContentEncodingScope[ContentEncodingScope[\"Block\"] = 1] = \"Block\";\n    ContentEncodingScope[ContentEncodingScope[\"Private\"] = 2] = \"Private\";\n    ContentEncodingScope[ContentEncodingScope[\"Next\"] = 4] = \"Next\";\n})(ContentEncodingScope || (ContentEncodingScope = {}));\nvar ContentCompAlgo;\n(function (ContentCompAlgo) {\n    ContentCompAlgo[ContentCompAlgo[\"Zlib\"] = 0] = \"Zlib\";\n    ContentCompAlgo[ContentCompAlgo[\"Bzlib\"] = 1] = \"Bzlib\";\n    ContentCompAlgo[ContentCompAlgo[\"lzo1x\"] = 2] = \"lzo1x\";\n    ContentCompAlgo[ContentCompAlgo[\"HeaderStripping\"] = 3] = \"HeaderStripping\";\n})(ContentCompAlgo || (ContentCompAlgo = {}));\nconst METADATA_ELEMENTS = [\n    { id: EBMLId.SeekHead, flag: 'seekHeadSeen' },\n    { id: EBMLId.Info, flag: 'infoSeen' },\n    { id: EBMLId.Tracks, flag: 'tracksSeen' },\n    { id: EBMLId.Cues, flag: 'cuesSeen' },\n];\nconst MAX_RESYNC_LENGTH = 10 * 2 ** 20; // 10 MiB\nconst MAX_ELEMENT_NESTING_DEPTH = 64;\nexport class MatroskaDemuxer extends Demuxer {\n    constructor(input) {\n        super(input);\n        this.readMetadataPromise = null;\n        this.segments = [];\n        this.currentSegment = null;\n        this.currentTrack = null;\n        this.currentCluster = null;\n        this.currentBlock = null;\n        this.currentBlockAdditional = null;\n        this.currentCueTime = null;\n        this.currentDecodingInstruction = null;\n        this.currentTagTargetIsMovie = true;\n        this.currentSimpleTagName = null;\n        this.currentAttachedFile = null;\n        this.isWebM = false;\n        this.claimedSeekTargets = new Set();\n        this.elementNestingDepth = 0;\n        this.reader = input._reader;\n    }\n    async getTrackBackings() {\n        await this.readMetadata();\n        return this.segments.flatMap(segment => segment.tracks.map(track => track.trackBacking));\n    }\n    async getMimeType() {\n        await this.readMetadata();\n        const backings = await this.getTrackBackings();\n        const codecStrings = await Promise.all(backings.map(x => x.getDecoderConfig().then(c => c?.codec ?? null)));\n        return buildMatroskaMimeType({\n            isWebM: this.isWebM,\n            hasVideo: this.segments.some(segment => segment.tracks.some(x => x.info?.type === 'video')),\n            hasAudio: this.segments.some(segment => segment.tracks.some(x => x.info?.type === 'audio')),\n            codecStrings: codecStrings.filter(Boolean),\n        });\n    }\n    async getMetadataTags() {\n        await this.readMetadata();\n        // Load metadata tags from each segment lazily (only once)\n        for (const segment of this.segments) {\n            if (!segment.metadataTagsPromise) {\n                if (this.reader.fileSize !== null) {\n                    segment.metadataTagsPromise = this.loadSegmentMetadata(segment);\n                }\n                else {\n                    // The seeking would be too crazy, let's not\n                    segment.metadataTagsPromise = Promise.resolve();\n                }\n            }\n            await segment.metadataTagsPromise;\n        }\n        // This is kinda handwavy, and how we handle multiple segments isn't suuuuper well-defined anyway; so we just\n        // shallow-merge metadata tags from all (usually just one) segments.\n        let metadataTags = {};\n        for (const segment of this.segments) {\n            metadataTags = { ...metadataTags, ...segment.metadataTags };\n        }\n        return metadataTags;\n    }\n    readMetadata() {\n        return this.readMetadataPromise ??= (async () => {\n            let currentPos = 0;\n            // Loop over all top-level elements in the file\n            while (true) {\n                let slice = this.reader.requestSliceRange(currentPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE);\n                if (isThenable(slice))\n                    slice = await slice;\n                if (!slice)\n                    break;\n                const header = readElementHeader(slice);\n                if (!header) {\n                    break; // Zero padding at the end of the file triggers this, for example\n                }\n                const id = header.id;\n                let size = header.size;\n                const dataStartPos = slice.filePos;\n                if (id === EBMLId.EBML) {\n                    assertDefinedSize(size);\n                    let slice = this.reader.requestSlice(dataStartPos, size);\n                    if (isThenable(slice))\n                        slice = await slice;\n                    if (!slice)\n                        break;\n                    this.readContiguousElements(slice);\n                }\n                else if (id === EBMLId.Segment) { // Segment found!\n                    await this.readSegment(dataStartPos, size);\n                    if (size === undefined) {\n                        // Segment sizes can be undefined (common in livestreamed files), so assume this is the last\n                        // and only segment\n                        break;\n                    }\n                    if (this.reader.fileSize === null) {\n                        break; // Stop at the first segment\n                    }\n                }\n                else if (id === EBMLId.Cluster) {\n                    if (this.reader.fileSize === null) {\n                        break; // Shouldn't be reached anyway, since we stop at the first segment\n                    }\n                    // Clusters are not a top-level element in Matroska, but some files contain a Segment whose size\n                    // doesn't contain any of the clusters that follow it. In the case, we apply the following logic: if\n                    // we find a top-level cluster, attribute it to the previous segment.\n                    if (size === undefined) {\n                        // Just in case this is one of those weird sizeless clusters, let's do our best and still try to\n                        // determine its size.\n                        const nextElementPos = await searchForNextElementId(this.reader, dataStartPos, LEVEL_0_AND_1_EBML_IDS, this.reader.fileSize);\n                        size = nextElementPos.pos - dataStartPos;\n                    }\n                    const lastSegment = last(this.segments);\n                    if (lastSegment) {\n                        // Extend the previous segment's size\n                        lastSegment.elementEndPos = dataStartPos + size;\n                    }\n                }\n                assertDefinedSize(size);\n                currentPos = dataStartPos + size;\n            }\n        })();\n    }\n    async readSegment(segmentDataStart, dataSize) {\n        this.currentSegment = {\n            seekHeadSeen: false,\n            infoSeen: false,\n            tracksSeen: false,\n            cuesSeen: false,\n            tagsSeen: false,\n            attachmentsSeen: false,\n            timestampScale: -1,\n            timestampFactor: -1,\n            duration: -1,\n            seekEntries: [],\n            tracks: [],\n            idToTrack: new Map(),\n            cuePoints: [],\n            dataStartPos: segmentDataStart,\n            elementEndPos: dataSize === undefined\n                ? null // Assume it goes until the end of the file\n                : segmentDataStart + dataSize,\n            clusterSeekStartPos: segmentDataStart,\n            lastReadCluster: null,\n            clusterSummaries: new Map(),\n            metadataTags: {},\n            metadataTagsPromise: null,\n        };\n        this.segments.push(this.currentSegment);\n        let currentPos = segmentDataStart;\n        const visitedSeekHeadPositions = new Set();\n        while (this.currentSegment.elementEndPos === null || currentPos < this.currentSegment.elementEndPos) {\n            let slice = this.reader.requestSliceRange(currentPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE);\n            if (isThenable(slice))\n                slice = await slice;\n            if (!slice)\n                break;\n            const elementStartPos = currentPos;\n            const header = readElementHeader(slice);\n            if (!header || (!LEVEL_1_EBML_IDS.includes(header.id) && header.id !== EBMLId.Void)) {\n                // Potential junk. Let's try to resync (skipping the current position, which might hold a valid ID\n                // followed by a broken size)\n                const nextPos = await resync(this.reader, elementStartPos + 1, LEVEL_1_EBML_IDS, Math.min(this.currentSegment.elementEndPos ?? Infinity, elementStartPos + MAX_RESYNC_LENGTH));\n                if (nextPos) {\n                    currentPos = nextPos;\n                    continue;\n                }\n                else {\n                    break; // Resync failed\n                }\n            }\n            const { id, size } = header;\n            const dataStartPos = slice.filePos;\n            const metadataElementIndex = METADATA_ELEMENTS.findIndex(x => x.id === id);\n            if (metadataElementIndex !== -1) {\n                const field = METADATA_ELEMENTS[metadataElementIndex].flag;\n                this.currentSegment[field] = true;\n                if (id === EBMLId.SeekHead) {\n                    visitedSeekHeadPositions.add(elementStartPos - segmentDataStart);\n                }\n                assertDefinedSize(size);\n                let slice = this.reader.requestSlice(dataStartPos, size);\n                if (isThenable(slice))\n                    slice = await slice;\n                if (slice) {\n                    this.readContiguousElements(slice);\n                }\n            }\n            else if (id === EBMLId.Tags || id === EBMLId.Attachments) {\n                // Metadata found at the beginning of the segment, great, let's parse it\n                if (id === EBMLId.Tags) {\n                    this.currentSegment.tagsSeen = true;\n                }\n                else {\n                    this.currentSegment.attachmentsSeen = true;\n                }\n                assertDefinedSize(size);\n                let slice = this.reader.requestSlice(dataStartPos, size);\n                if (isThenable(slice))\n                    slice = await slice;\n                if (slice) {\n                    this.readContiguousElements(slice);\n                }\n            }\n            else if (id === EBMLId.Cluster) {\n                this.currentSegment.clusterSeekStartPos = elementStartPos;\n                break; // Stop at the first cluster\n            }\n            if (size === undefined) {\n                break;\n            }\n            else {\n                currentPos = dataStartPos + size;\n            }\n        }\n        if (this.reader.fileSize !== null) {\n            // Seek heads can sometimes point to other seek heads, so follow them until there are no unvisited\n            // ones left. Following a seek head appends its entries to the list we're iterating over.\n            for (let i = 0; i < this.currentSegment.seekEntries.length; i++) {\n                const seekEntry = this.currentSegment.seekEntries[i];\n                if (seekEntry.id !== EBMLId.SeekHead || visitedSeekHeadPositions.has(seekEntry.segmentPosition)) {\n                    continue;\n                }\n                visitedSeekHeadPositions.add(seekEntry.segmentPosition);\n                if (!this.claimSeekTarget(segmentDataStart + seekEntry.segmentPosition)) {\n                    continue;\n                }\n                let slice = this.reader.requestSliceRange(segmentDataStart + seekEntry.segmentPosition, MIN_HEADER_SIZE, MAX_HEADER_SIZE);\n                if (isThenable(slice))\n                    slice = await slice;\n                if (!slice)\n                    continue;\n                const header = readElementHeader(slice);\n                if (!header || header.id !== EBMLId.SeekHead)\n                    continue;\n                const { size } = header;\n                assertDefinedSize(size);\n                let dataSlice = this.reader.requestSlice(slice.filePos, size);\n                if (isThenable(dataSlice))\n                    dataSlice = await dataSlice;\n                if (!dataSlice)\n                    continue;\n                this.readContiguousElements(dataSlice);\n            }\n        }\n        // Sort the seek entries by file position so reading them exhibits a sequential pattern\n        this.currentSegment.seekEntries.sort((a, b) => a.segmentPosition - b.segmentPosition);\n        if (this.reader.fileSize !== null) {\n            // Use the seek head to read missing metadata elements\n            for (const seekEntry of this.currentSegment.seekEntries) {\n                const target = METADATA_ELEMENTS.find(x => x.id === seekEntry.id);\n                if (!target) {\n                    continue;\n                }\n                if (this.currentSegment[target.flag])\n                    continue;\n                if (!this.claimSeekTarget(segmentDataStart + seekEntry.segmentPosition))\n                    continue;\n                let slice = this.reader.requestSliceRange(segmentDataStart + seekEntry.segmentPosition, MIN_HEADER_SIZE, MAX_HEADER_SIZE);\n                if (isThenable(slice))\n                    slice = await slice;\n                if (!slice)\n                    continue;\n                const header = readElementHeader(slice);\n                if (!header)\n                    continue;\n                const { id, size } = header;\n                if (id !== target.id)\n                    continue;\n                assertDefinedSize(size);\n                this.currentSegment[target.flag] = true;\n                let dataSlice = this.reader.requestSlice(slice.filePos, size);\n                if (isThenable(dataSlice))\n                    dataSlice = await dataSlice;\n                if (!dataSlice)\n                    continue;\n                this.readContiguousElements(dataSlice);\n            }\n        }\n        if (this.currentSegment.timestampScale === -1) {\n            // TimestampScale element is missing. Technically an invalid file, but let's default to the typical value,\n            // which is 1e6.\n            this.currentSegment.timestampScale = 1e6;\n            this.currentSegment.timestampFactor = 1e9 / 1e6;\n        }\n        // Compute default duration for all tracks now that we have the timestamp factor\n        for (const track of this.currentSegment.tracks) {\n            if (track.defaultDurationNs !== null) {\n                track.defaultDuration = (this.currentSegment.timestampFactor * track.defaultDurationNs) / 1e9;\n            }\n        }\n        // Assign cue points to their respective tracks\n        for (const cuePoint of this.currentSegment.cuePoints) {\n            const track = this.currentSegment.idToTrack.get(cuePoint.trackId);\n            if (track) {\n                track.cuePoints.push(cuePoint);\n            }\n        }\n        for (const track of this.currentSegment.tracks) {\n            // Sort cue points by time and remove multiple cue points for the same time\n            const cuePoints = track.cuePoints;\n            cuePoints.sort((a, b) => a.time - b.time);\n            let writeIndex = 0;\n            for (const cuePoint of cuePoints) {\n                if (writeIndex === 0 || cuePoint.time !== cuePoints[writeIndex - 1].time) {\n                    cuePoints[writeIndex++] = cuePoint;\n                }\n            }\n            cuePoints.length = writeIndex;\n        }\n        let trackWithMostCuePoints = null;\n        let maxCuePointCount = -Infinity;\n        for (const track of this.currentSegment.tracks) {\n            if (track.cuePoints.length > maxCuePointCount) {\n                maxCuePointCount = track.cuePoints.length;\n                trackWithMostCuePoints = track;\n            }\n        }\n        // For every track that has received 0 cue points (can happen, often only the video track receives cue points),\n        // we still want to have better seeking. Therefore, let's give it the cue points of the track with the most cue\n        // points, which should provide us with the most fine-grained seeking.\n        for (const track of this.currentSegment.tracks) {\n            if (track.cuePoints.length === 0) {\n                track.cuePoints = trackWithMostCuePoints.cuePoints;\n            }\n        }\n        this.currentSegment = null;\n    }\n    async readCluster(startPos, segment) {\n        if (segment.lastReadCluster?.elementStartPos === startPos) {\n            return segment.lastReadCluster;\n        }\n        let headerSlice = this.reader.requestSliceRange(startPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE);\n        if (isThenable(headerSlice))\n            headerSlice = await headerSlice;\n        assert(headerSlice);\n        const elementStartPos = startPos;\n        const elementHeader = readElementHeader(headerSlice);\n        assert(elementHeader);\n        const id = elementHeader.id;\n        assert(id === EBMLId.Cluster);\n        let size = elementHeader.size;\n        const dataStartPos = headerSlice.filePos;\n        if (size === undefined) {\n            // The cluster's size is undefined (can happen in livestreamed files). We'd still like to know the size of\n            // it, so we have no other choice but to iterate over the EBML structure until we find an element at level\n            // 0 or 1, indicating the end of the cluster (all elements inside the cluster are at level 2).\n            const nextElementPos = await searchForNextElementId(this.reader, dataStartPos, LEVEL_0_AND_1_EBML_IDS, segment.elementEndPos);\n            size = nextElementPos.pos - dataStartPos;\n        }\n        // Load the entire cluster\n        let dataSlice = this.reader.requestSlice(dataStartPos, size);\n        if (isThenable(dataSlice))\n            dataSlice = await dataSlice;\n        const cluster = {\n            segment,\n            elementStartPos,\n            elementEndPos: dataStartPos + size,\n            dataStartPos,\n            timestamp: -1,\n            trackData: new Map(),\n        };\n        if (dataSlice) {\n            this.currentCluster = cluster;\n            try {\n                // Read the children of the cluster, stopping early at level 0 or 1 EBML elements. We do this because\n                // some clusters have incorrect sizes that are too large\n                const endPos = this.readContiguousElements(dataSlice, LEVEL_0_AND_1_EBML_IDS);\n                cluster.elementEndPos = endPos;\n            }\n            finally {\n                this.currentCluster = null;\n                this.currentBlock = null;\n            }\n        }\n        for (const [, trackData] of cluster.trackData) {\n            const track = trackData.track;\n            // This must hold, as track datas only get created if a block for that track is encountered\n            assert(trackData.blocks.length > 0);\n            let hasLacedBlocks = false;\n            for (let i = 0; i < trackData.blocks.length; i++) {\n                const block = trackData.blocks[i];\n                block.timestamp += cluster.timestamp;\n                hasLacedBlocks ||= block.lacing !== BlockLacing.None;\n            }\n            trackData.presentationTimestamps = trackData.blocks\n                .map((block, i) => ({ timestamp: block.timestamp, blockIndex: i }))\n                .sort((a, b) => a.timestamp - b.timestamp);\n            for (let i = 0; i < trackData.presentationTimestamps.length; i++) {\n                const currentEntry = trackData.presentationTimestamps[i];\n                const currentBlock = trackData.blocks[currentEntry.blockIndex];\n                if (trackData.firstKeyFrameTimestamp === null && currentBlock.isKeyFrame) {\n                    trackData.firstKeyFrameTimestamp = currentBlock.timestamp;\n                }\n                if (i < trackData.presentationTimestamps.length - 1) {\n                    // Update block durations based on presentation order\n                    const nextEntry = trackData.presentationTimestamps[i + 1];\n                    currentBlock.duration = nextEntry.timestamp - currentBlock.timestamp;\n                }\n                else if (currentBlock.duration === 0) {\n                    if (track.defaultDuration != null) {\n                        if (currentBlock.lacing === BlockLacing.None) {\n                            currentBlock.duration = track.defaultDuration;\n                        }\n                        else {\n                            // Handled by the lace resolution code\n                        }\n                    }\n                }\n            }\n            if (hasLacedBlocks) {\n                // Perform lace resolution. Here, we expand each laced block into multiple blocks where each contains\n                // one frame of the lace. We do this after determining block timestamps so we can properly distribute\n                // the block's duration across the laced frames.\n                trackData.blocks = this.expandLacedBlocks(trackData.blocks, track);\n                // Recompute since blocks have changed\n                trackData.presentationTimestamps = trackData.blocks\n                    .map((block, i) => ({ timestamp: block.timestamp, blockIndex: i }))\n                    .sort((a, b) => a.timestamp - b.timestamp);\n            }\n            const firstBlock = trackData.blocks[trackData.presentationTimestamps[0].blockIndex];\n            const lastBlock = trackData.blocks[last(trackData.presentationTimestamps).blockIndex];\n            trackData.startTimestamp = firstBlock.timestamp;\n            trackData.endTimestamp = lastBlock.timestamp + lastBlock.duration;\n            // Let's remember that a cluster with a given timestamp is here, speeding up future lookups if no cues exist\n            const insertionIndex = binarySearchLessOrEqual(track.clusterPositionCache, trackData.startTimestamp, x => x.startTimestamp);\n            const previousEntry = track.clusterPositionCache[insertionIndex];\n            const nextEntry = track.clusterPositionCache[insertionIndex + 1];\n            // Only remember it if the timestamp order matches the cluster position order\n            if ((!previousEntry || previousEntry.elementStartPos < elementStartPos)\n                && (!nextEntry || nextEntry.elementStartPos > elementStartPos)) {\n                track.clusterPositionCache.splice(insertionIndex + 1, 0, {\n                    elementStartPos: cluster.elementStartPos,\n                    startTimestamp: trackData.startTimestamp,\n                });\n            }\n        }\n        segment.lastReadCluster = cluster;\n        segment.clusterSummaries.set(startPos, {\n            elementEndPos: cluster.elementEndPos,\n            trackIds: new Set(cluster.trackData.keys()),\n        });\n        return cluster;\n    }\n    getTrackDataInCluster(cluster, trackNumber) {\n        let trackData = cluster.trackData.get(trackNumber);\n        if (!trackData) {\n            const track = cluster.segment.idToTrack.get(trackNumber);\n            if (!track) {\n                return null;\n            }\n            trackData = {\n                track,\n                startTimestamp: 0,\n                endTimestamp: 0,\n                firstKeyFrameTimestamp: null,\n                blocks: [],\n                presentationTimestamps: [],\n            };\n            cluster.trackData.set(trackNumber, trackData);\n        }\n        return trackData;\n    }\n    expandLacedBlocks(blocks, track) {\n        // https://www.matroska.org/technical/notes.html#block-lacing\n        const expandedBlocks = [];\n        for (const originalBlock of blocks) {\n            if (originalBlock.lacing === BlockLacing.None) {\n                expandedBlocks.push(originalBlock);\n                continue;\n            }\n            // Content encodings apply to each frame, excluding the lacing data, so the frames get decoded lazily later\n            const slice = FileSlice.tempFromBytes(originalBlock.data);\n            if (slice.length === 0) {\n                throw new Error('Invalid laced block: no data.');\n            }\n            const frameSizes = [];\n            const frameCount = readU8(slice) + 1;\n            switch (originalBlock.lacing) {\n                case BlockLacing.Xiph:\n                    {\n                        let totalUsedSize = 0;\n                        // Xiph lacing, just like in Ogg\n                        for (let i = 0; i < frameCount - 1; i++) {\n                            let frameSize = 0;\n                            while (slice.bufferPos < slice.length) {\n                                const value = readU8(slice);\n                                frameSize += value;\n                                if (value < 255) {\n                                    frameSizes.push(frameSize);\n                                    totalUsedSize += frameSize;\n                                    break;\n                                }\n                            }\n                        }\n                        // Compute the last frame's size from whatever's left\n                        frameSizes.push(slice.length - (slice.bufferPos + totalUsedSize));\n                    }\n                    ;\n                    break;\n                case BlockLacing.FixedSize:\n                    {\n                        // Fixed size lacing: all frames have same size\n                        const totalDataSize = slice.length - 1; // Minus the frame count byte\n                        const frameSize = Math.floor(totalDataSize / frameCount);\n                        for (let i = 0; i < frameCount; i++) {\n                            frameSizes.push(frameSize);\n                        }\n                    }\n                    ;\n                    break;\n                case BlockLacing.Ebml:\n                    {\n                        // EBML lacing: first size absolute, subsequent ones are coded as signed differences from the last\n                        const firstResult = readVarInt(slice);\n                        if (firstResult === null) {\n                            throw new Error('Invalid EBML lacing: bad frame size.');\n                        }\n                        let currentSize = firstResult;\n                        frameSizes.push(currentSize);\n                        let totalUsedSize = currentSize;\n                        for (let i = 1; i < frameCount - 1; i++) {\n                            const startPos = slice.bufferPos;\n                            const diffResult = readVarInt(slice);\n                            if (diffResult === null) {\n                                throw new Error('Invalid EBML lacing: bad frame size.');\n                            }\n                            const unsignedDiff = diffResult;\n                            const width = slice.bufferPos - startPos;\n                            const bias = (1 << (width * 7 - 1)) - 1; // Typo-corrected version of 2^((7*n)-1)^-1\n                            const diff = unsignedDiff - bias;\n                            currentSize += diff;\n                            frameSizes.push(currentSize);\n                            totalUsedSize += currentSize;\n                        }\n                        // Compute the last frame's size from whatever's left\n                        frameSizes.push(slice.length - (slice.bufferPos + totalUsedSize));\n                    }\n                    ;\n                    break;\n                default: assert(false);\n            }\n            // Every frame must hold actual data; this also catches frame sizes that exceed the block\n            if (frameSizes.length !== frameCount || frameSizes.some(x => x <= 0)) {\n                throw new Error('Invalid block lacing: frame sizes don\\'t match the block.');\n            }\n            const blockDuration = originalBlock.duration || frameCount * (track.defaultDuration ?? 0);\n            // Now, let's replace the block with one block per frame\n            for (let i = 0; i < frameCount; i++) {\n                const frameSize = frameSizes[i];\n                const frameData = readBytes(slice, frameSize);\n                // Distribute timestamps evenly across the block duration\n                const frameTimestamp = originalBlock.timestamp + (blockDuration * i / frameCount);\n                const frameDuration = blockDuration / frameCount;\n                expandedBlocks.push({\n                    timestamp: frameTimestamp,\n                    duration: frameDuration,\n                    isKeyFrame: originalBlock.isKeyFrame,\n                    data: frameData,\n                    lacing: BlockLacing.None,\n                    decoded: originalBlock.decoded,\n                    postProcessed: false,\n                    mainAdditional: originalBlock.mainAdditional,\n                });\n            }\n        }\n        return expandedBlocks;\n    }\n    async loadSegmentMetadata(segment) {\n        for (const seekEntry of segment.seekEntries) {\n            if (seekEntry.id === EBMLId.Tags && !segment.tagsSeen) {\n                // We need to load the tags\n            }\n            else if (seekEntry.id === EBMLId.Attachments && !segment.attachmentsSeen) {\n                // We need to load the attachments\n            }\n            else {\n                continue;\n            }\n            if (!this.claimSeekTarget(segment.dataStartPos + seekEntry.segmentPosition)) {\n                continue;\n            }\n            let slice = this.reader.requestSliceRange(segment.dataStartPos + seekEntry.segmentPosition, MIN_HEADER_SIZE, MAX_HEADER_SIZE);\n            if (isThenable(slice))\n                slice = await slice;\n            if (!slice)\n                continue;\n            const header = readElementHeader(slice);\n            if (!header || header.id !== seekEntry.id)\n                continue;\n            const { size } = header;\n            assertDefinedSize(size);\n            let dataSlice = this.reader.requestSlice(slice.filePos, size);\n            if (isThenable(dataSlice))\n                dataSlice = await dataSlice;\n            if (dataSlice) {\n                // No awaiting while the segment is set, so concurrent calls can't interfere with each other\n                assert(!this.currentSegment);\n                this.currentSegment = segment;\n                try {\n                    this.readContiguousElements(dataSlice);\n                }\n                finally {\n                    this.currentSegment = null;\n                }\n            }\n            // Mark as seen\n            if (seekEntry.id === EBMLId.Tags) {\n                segment.tagsSeen = true;\n            }\n            else if (seekEntry.id === EBMLId.Attachments) {\n                segment.attachmentsSeen = true;\n            }\n        }\n    }\n    claimSeekTarget(position) {\n        if (this.claimedSeekTargets.has(position)) {\n            return false;\n        }\n        this.claimedSeekTargets.add(position);\n        return true;\n    }\n    readContiguousElements(slice, stopIds) {\n        if (this.elementNestingDepth === MAX_ELEMENT_NESTING_DEPTH) {\n            throw new Error('Invalid file: elements are nested too deeply.');\n        }\n        this.elementNestingDepth++;\n        try {\n            while (slice.remainingLength >= MIN_HEADER_SIZE) {\n                const startPos = slice.filePos;\n                const foundElement = this.traverseElement(slice, stopIds);\n                if (!foundElement) {\n                    return startPos;\n                }\n            }\n            return slice.filePos;\n        }\n        finally {\n            this.elementNestingDepth--;\n        }\n    }\n    traverseElement(slice, stopIds) {\n        const header = readElementHeader(slice);\n        if (!header) {\n            return false;\n        }\n        if (stopIds && stopIds.includes(header.id)) {\n            return false;\n        }\n        const { id, size } = header;\n        const dataStartPos = slice.filePos;\n        assertDefinedSize(size);\n        if (dataStartPos + size > slice.end) {\n            return false; // The element doesn't fit into its parent\n        }\n        switch (id) {\n            case EBMLId.DocType:\n                {\n                    this.isWebM = readAsciiString(slice, size) === 'webm';\n                }\n                ;\n                break;\n            case EBMLId.Seek:\n                {\n                    if (!this.currentSegment)\n                        break;\n                    const seekEntry = { id: -1, segmentPosition: -1 };\n                    this.currentSegment.seekEntries.push(seekEntry);\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                    if (seekEntry.id === -1 || seekEntry.segmentPosition === -1) {\n                        this.currentSegment.seekEntries.pop();\n                    }\n                }\n                ;\n                break;\n            case EBMLId.SeekID:\n                {\n                    const lastSeekEntry = this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length - 1];\n                    if (!lastSeekEntry)\n                        break;\n                    lastSeekEntry.id = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.SeekPosition:\n                {\n                    const lastSeekEntry = this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length - 1];\n                    if (!lastSeekEntry)\n                        break;\n                    lastSeekEntry.segmentPosition = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.TimestampScale:\n                {\n                    if (!this.currentSegment)\n                        break;\n                    const timestampScale = readUnsignedInt(slice, size);\n                    if (timestampScale === 0) {\n                        throw new Error('Invalid TimestampScale element: must not be 0.');\n                    }\n                    this.currentSegment.timestampScale = timestampScale;\n                    this.currentSegment.timestampFactor = 1e9 / timestampScale;\n                }\n                ;\n                break;\n            case EBMLId.Duration:\n                {\n                    if (!this.currentSegment)\n                        break;\n                    this.currentSegment.duration = readFloat(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.TrackEntry:\n                {\n                    if (!this.currentSegment)\n                        break;\n                    this.currentTrack = {\n                        id: -1,\n                        segment: this.currentSegment,\n                        demuxer: this,\n                        clusterPositionCache: [],\n                        cuePoints: [],\n                        disposition: {\n                            ...DEFAULT_TRACK_DISPOSITION,\n                            primary: false,\n                        },\n                        trackBacking: null,\n                        codecId: null,\n                        codecPrivate: null,\n                        defaultDuration: null,\n                        defaultDurationNs: null,\n                        name: null,\n                        languageCode: 'eng', // The default in Matroska\n                        hasLanguageBcp47: false,\n                        decodingInstructions: [],\n                        info: null,\n                    };\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                    // Check if track was disabled during parsing (e.g., by FlagEnabled being 0)\n                    if (!this.currentTrack) {\n                        break;\n                    }\n                    if (this.currentTrack.decodingInstructions.some((instruction) => {\n                        return instruction.data?.type !== 'decompress'\n                            || instruction.scope !== ContentEncodingScope.Block\n                            || instruction.data.algorithm !== ContentCompAlgo.HeaderStripping;\n                    })) {\n                        Logging._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`);\n                        this.currentTrack = null;\n                    }\n                    if (this.currentTrack && this.currentSegment.idToTrack.has(this.currentTrack.id)) {\n                        // Blocks can't tell the tracks apart\n                        Logging._warn(`Track #${this.currentTrack.id} is defined more than once; dropping.`);\n                        this.currentTrack = null;\n                    }\n                    if (this.currentTrack\n                        && this.currentTrack.id !== -1\n                        && this.currentTrack.codecId\n                        && this.currentTrack.info) {\n                        const slashIndex = this.currentTrack.codecId.indexOf('/');\n                        const codecIdWithoutSuffix = slashIndex === -1\n                            ? this.currentTrack.codecId\n                            : this.currentTrack.codecId.slice(0, slashIndex);\n                        if (this.currentTrack.info.type === 'video'\n                            && this.currentTrack.info.width !== -1\n                            && this.currentTrack.info.height !== -1) {\n                            this.currentTrack.info.squarePixelWidth = this.currentTrack.info.width;\n                            this.currentTrack.info.squarePixelHeight = this.currentTrack.info.height;\n                            if (this.currentTrack.info.displayWidth !== null\n                                && this.currentTrack.info.displayHeight !== null) {\n                                const num = this.currentTrack.info.displayWidth * this.currentTrack.info.height;\n                                const den = this.currentTrack.info.displayHeight * this.currentTrack.info.width;\n                                if (num > 0 && den > 0) {\n                                    if (num > den) {\n                                        this.currentTrack.info.squarePixelWidth = Math.round(this.currentTrack.info.width * num / den);\n                                    }\n                                    else {\n                                        this.currentTrack.info.squarePixelHeight = Math.round(this.currentTrack.info.height * den / num);\n                                    }\n                                }\n                            }\n                            if (this.currentTrack.codecId === CODEC_STRING_MAP.avc) {\n                                this.currentTrack.info.codec = 'avc';\n                                this.currentTrack.info.codecDescription = this.currentTrack.codecPrivate;\n                            }\n                            else if (this.currentTrack.codecId === CODEC_STRING_MAP.hevc) {\n                                this.currentTrack.info.codec = 'hevc';\n                                this.currentTrack.info.codecDescription = this.currentTrack.codecPrivate;\n                            }\n                            else if (codecIdWithoutSuffix === CODEC_STRING_MAP.vp8) {\n                                this.currentTrack.info.codec = 'vp8';\n                            }\n                            else if (codecIdWithoutSuffix === CODEC_STRING_MAP.vp9) {\n                                this.currentTrack.info.codec = 'vp9';\n                            }\n                            else if (codecIdWithoutSuffix === CODEC_STRING_MAP.av1) {\n                                this.currentTrack.info.codec = 'av1';\n                            }\n                            else if (codecIdWithoutSuffix === CODEC_STRING_MAP.prores) {\n                                const format = this.currentTrack.codecPrivate\n                                    ? textDecoder.decode(this.currentTrack.codecPrivate)\n                                    : '';\n                                if (PRORES_FOURCCS.includes(format)) {\n                                    this.currentTrack.info.codec = 'prores';\n                                    this.currentTrack.info.proresFormat = format;\n                                }\n                                else {\n                                    // Either an invalid string or ProRes RAW, which we don't support yet (it's a\n                                    // different codec).\n                                }\n                            }\n                            const videoTrack = this.currentTrack;\n                            this.currentTrack.trackBacking = new MatroskaVideoTrackBacking(videoTrack);\n                            this.currentSegment.tracks.push(this.currentTrack);\n                            this.currentSegment.idToTrack.set(this.currentTrack.id, this.currentTrack);\n                        }\n                        else if (this.currentTrack.info.type === 'audio') {\n                            if (codecIdWithoutSuffix === CODEC_STRING_MAP.aac) {\n                                this.currentTrack.info.codec = 'aac';\n                                this.currentTrack.info.aacCodecInfo = {\n                                    isMpeg2: this.currentTrack.codecId.includes('MPEG2'),\n                                    objectType: null,\n                                };\n                                this.currentTrack.info.codecDescription = this.currentTrack.codecPrivate;\n                            }\n                            else if (this.currentTrack.codecId === CODEC_STRING_MAP.mp3) {\n                                this.currentTrack.info.codec = 'mp3';\n                            }\n                            else if (codecIdWithoutSuffix === CODEC_STRING_MAP.opus) {\n                                this.currentTrack.info.codec = 'opus';\n                                this.currentTrack.info.codecDescription = this.currentTrack.codecPrivate;\n                                this.currentTrack.info.sampleRate = OPUS_SAMPLE_RATE; // Always the same\n                            }\n                            else if (codecIdWithoutSuffix === CODEC_STRING_MAP.vorbis) {\n                                this.currentTrack.info.codec = 'vorbis';\n                                this.currentTrack.info.codecDescription = this.currentTrack.codecPrivate;\n                            }\n                            else if (codecIdWithoutSuffix === CODEC_STRING_MAP.flac) {\n                                this.currentTrack.info.codec = 'flac';\n                                this.currentTrack.info.codecDescription = this.currentTrack.codecPrivate;\n                            }\n                            else if (codecIdWithoutSuffix === CODEC_STRING_MAP.ac3) {\n                                this.currentTrack.info.codec = 'ac3';\n                                this.currentTrack.info.codecDescription = this.currentTrack.codecPrivate;\n                            }\n                            else if (codecIdWithoutSuffix === CODEC_STRING_MAP.eac3) {\n                                this.currentTrack.info.codec = 'eac3';\n                                this.currentTrack.info.codecDescription = this.currentTrack.codecPrivate;\n                            }\n                            else if (codecIdWithoutSuffix === CODEC_STRING_MAP.dts) {\n                                this.currentTrack.info.codec = 'dts';\n                                if (this.currentTrack.codecId === 'A_DTS/EXPRESS') {\n                                    this.currentTrack.info.dtsFormat = 'dtse';\n                                }\n                                else if (this.currentTrack.codecId === 'A_DTS/LOSSLESS') {\n                                    this.currentTrack.info.dtsFormat = 'dtsl';\n                                }\n                            }\n                            else if (this.currentTrack.codecId === 'A_PCM/INT/LIT') {\n                                if (this.currentTrack.info.bitDepth === 8) {\n                                    this.currentTrack.info.codec = 'pcm-u8';\n                                }\n                                else if (this.currentTrack.info.bitDepth === 16) {\n                                    this.currentTrack.info.codec = 'pcm-s16';\n                                }\n                                else if (this.currentTrack.info.bitDepth === 24) {\n                                    this.currentTrack.info.codec = 'pcm-s24';\n                                }\n                                else if (this.currentTrack.info.bitDepth === 32) {\n                                    this.currentTrack.info.codec = 'pcm-s32';\n                                }\n                            }\n                            else if (this.currentTrack.codecId === 'A_PCM/INT/BIG') {\n                                if (this.currentTrack.info.bitDepth === 8) {\n                                    this.currentTrack.info.codec = 'pcm-u8';\n                                }\n                                else if (this.currentTrack.info.bitDepth === 16) {\n                                    this.currentTrack.info.codec = 'pcm-s16be';\n                                }\n                                else if (this.currentTrack.info.bitDepth === 24) {\n                                    this.currentTrack.info.codec = 'pcm-s24be';\n                                }\n                                else if (this.currentTrack.info.bitDepth === 32) {\n                                    this.currentTrack.info.codec = 'pcm-s32be';\n                                }\n                            }\n                            else if (this.currentTrack.codecId === 'A_PCM/FLOAT/IEEE') {\n                                if (this.currentTrack.info.bitDepth === 32) {\n                                    this.currentTrack.info.codec = 'pcm-f32';\n                                }\n                                else if (this.currentTrack.info.bitDepth === 64) {\n                                    this.currentTrack.info.codec = 'pcm-f64';\n                                }\n                            }\n                            const audioTrack = this.currentTrack;\n                            this.currentTrack.trackBacking = new MatroskaAudioTrackBacking(audioTrack);\n                            this.currentSegment.tracks.push(this.currentTrack);\n                            this.currentSegment.idToTrack.set(this.currentTrack.id, this.currentTrack);\n                        }\n                    }\n                    this.currentTrack = null;\n                }\n                ;\n                break;\n            case EBMLId.TrackNumber:\n                {\n                    if (!this.currentTrack)\n                        break;\n                    this.currentTrack.id = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.TrackType:\n                {\n                    if (!this.currentTrack)\n                        break;\n                    const type = readUnsignedInt(slice, size);\n                    if (type === 1) {\n                        this.currentTrack.info = {\n                            type: 'video',\n                            width: -1,\n                            height: -1,\n                            displayWidth: null,\n                            displayHeight: null,\n                            displayUnit: null,\n                            squarePixelWidth: -1,\n                            squarePixelHeight: -1,\n                            horizontalScale: 1,\n                            verticalScale: 1,\n                            rotation: 0,\n                            codec: null,\n                            codecDescription: null,\n                            colorSpace: { ...EMPTY_COLOR_SPACE },\n                            alphaMode: false,\n                            proresFormat: null,\n                        };\n                    }\n                    else if (type === 2) {\n                        this.currentTrack.info = {\n                            type: 'audio',\n                            numberOfChannels: 1, // Default value\n                            sampleRate: 8000, // Default value\n                            bitDepth: -1,\n                            codec: null,\n                            codecDescription: null,\n                            aacCodecInfo: null,\n                            dtsFormat: null,\n                        };\n                    }\n                }\n                ;\n                break;\n            case EBMLId.FlagEnabled:\n                {\n                    if (!this.currentTrack)\n                        break;\n                    const enabled = readUnsignedInt(slice, size);\n                    if (!enabled) {\n                        this.currentTrack = null;\n                    }\n                }\n                ;\n                break;\n            case EBMLId.FlagDefault:\n                {\n                    if (!this.currentTrack)\n                        break;\n                    this.currentTrack.disposition.default = !!readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.FlagForced:\n                {\n                    if (!this.currentTrack)\n                        break;\n                    this.currentTrack.disposition.forced = !!readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.FlagOriginal:\n                {\n                    if (!this.currentTrack)\n                        break;\n                    this.currentTrack.disposition.original = !!readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.FlagHearingImpaired:\n                {\n                    if (!this.currentTrack)\n                        break;\n                    this.currentTrack.disposition.hearingImpaired = !!readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.FlagVisualImpaired:\n                {\n                    if (!this.currentTrack)\n                        break;\n                    this.currentTrack.disposition.visuallyImpaired = !!readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.FlagCommentary:\n                {\n                    if (!this.currentTrack)\n                        break;\n                    this.currentTrack.disposition.commentary = !!readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.CodecID:\n                {\n                    if (!this.currentTrack)\n                        break;\n                    this.currentTrack.codecId = readAsciiString(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.CodecPrivate:\n                {\n                    if (!this.currentTrack)\n                        break;\n                    this.currentTrack.codecPrivate = readBytes(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.DefaultDuration:\n                {\n                    if (!this.currentTrack)\n                        break;\n                    this.currentTrack.defaultDurationNs = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.Name:\n                {\n                    if (!this.currentTrack)\n                        break;\n                    this.currentTrack.name = readUnicodeString(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.Language:\n                {\n                    if (!this.currentTrack)\n                        break;\n                    if (this.currentTrack.hasLanguageBcp47) {\n                        // LanguageBCP47 was present, which takes precedence\n                        break;\n                    }\n                    this.currentTrack.languageCode = readAsciiString(slice, size);\n                    if (!isIso639Dash2LanguageCode(this.currentTrack.languageCode)) {\n                        this.currentTrack.languageCode = UNDETERMINED_LANGUAGE;\n                    }\n                }\n                ;\n                break;\n            case EBMLId.LanguageBCP47:\n                {\n                    if (!this.currentTrack)\n                        break;\n                    const bcp47 = readAsciiString(slice, size);\n                    const languageSubtag = bcp47.split('-')[0];\n                    if (languageSubtag) {\n                        // Technically invalid, for now: The language subtag might be a language code from ISO 639-1,\n                        // ISO 639-2, ISO 639-3, ISO 639-5 or some other thing (source: Wikipedia). But, `languageCode` is\n                        // documented as ISO 639-2. Changing the definition would be a breaking change. This will get\n                        // cleaned up in the future by defining languageCode to be BCP 47 instead.\n                        this.currentTrack.languageCode = languageSubtag;\n                    }\n                    else {\n                        this.currentTrack.languageCode = UNDETERMINED_LANGUAGE;\n                    }\n                    this.currentTrack.hasLanguageBcp47 = true;\n                }\n                ;\n                break;\n            case EBMLId.Video:\n                {\n                    if (this.currentTrack?.info?.type !== 'video')\n                        break;\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                }\n                ;\n                break;\n            case EBMLId.PixelWidth:\n                {\n                    if (this.currentTrack?.info?.type !== 'video')\n                        break;\n                    this.currentTrack.info.width = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.PixelHeight:\n                {\n                    if (this.currentTrack?.info?.type !== 'video')\n                        break;\n                    this.currentTrack.info.height = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.DisplayWidth:\n                {\n                    if (this.currentTrack?.info?.type !== 'video')\n                        break;\n                    this.currentTrack.info.displayWidth = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.DisplayHeight:\n                {\n                    if (this.currentTrack?.info?.type !== 'video')\n                        break;\n                    this.currentTrack.info.displayHeight = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.DisplayUnit:\n                {\n                    if (this.currentTrack?.info?.type !== 'video')\n                        break;\n                    this.currentTrack.info.displayUnit = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.AlphaMode:\n                {\n                    if (this.currentTrack?.info?.type !== 'video')\n                        break;\n                    this.currentTrack.info.alphaMode = readUnsignedInt(slice, size) === 1;\n                }\n                ;\n                break;\n            case EBMLId.Colour:\n                {\n                    if (this.currentTrack?.info?.type !== 'video')\n                        break;\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                }\n                ;\n                break;\n            case EBMLId.MatrixCoefficients:\n                {\n                    if (this.currentTrack?.info?.type !== 'video')\n                        break;\n                    const matrixCoefficients = readUnsignedInt(slice, size);\n                    const mapped = MATRIX_COEFFICIENTS_MAP_INVERSE[matrixCoefficients];\n                    this.currentTrack.info.colorSpace.matrix = mapped;\n                }\n                ;\n                break;\n            case EBMLId.Range:\n                {\n                    if (this.currentTrack?.info?.type !== 'video')\n                        break;\n                    const range = readUnsignedInt(slice, size);\n                    this.currentTrack.info.colorSpace.fullRange = range === 1 || range === 2\n                        ? range === 2\n                        : undefined;\n                }\n                ;\n                break;\n            case EBMLId.TransferCharacteristics:\n                {\n                    if (this.currentTrack?.info?.type !== 'video')\n                        break;\n                    const transferCharacteristics = readUnsignedInt(slice, size);\n                    const mapped = TRANSFER_CHARACTERISTICS_MAP_INVERSE[transferCharacteristics];\n                    this.currentTrack.info.colorSpace.transfer = mapped;\n                }\n                ;\n                break;\n            case EBMLId.Primaries:\n                {\n                    if (this.currentTrack?.info?.type !== 'video')\n                        break;\n                    const primaries = readUnsignedInt(slice, size);\n                    const mapped = COLOR_PRIMARIES_MAP_INVERSE[primaries];\n                    this.currentTrack.info.colorSpace.primaries = mapped;\n                }\n                ;\n                break;\n            case EBMLId.Projection:\n                {\n                    if (this.currentTrack?.info?.type !== 'video')\n                        break;\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                }\n                ;\n                break;\n            // Yaw and pitch rotate the frame in 3D space about the vertical and horizontal axis respectively. When\n            // snapped to multiples of 90 degrees, that amounts to scaling each axis by the cosine, which models flips.\n            case EBMLId.ProjectionPoseYaw:\n                {\n                    if (this.currentTrack?.info?.type !== 'video')\n                        break;\n                    const yaw = readFloat(slice, size);\n                    try {\n                        const normalized = normalizeRotation(yaw);\n                        this.currentTrack.info.horizontalScale = Math.round(Math.cos(normalized * DEG_TO_RAD));\n                    }\n                    catch {\n                        // It wasn't a valid rotation\n                    }\n                }\n                ;\n                break;\n            case EBMLId.ProjectionPosePitch:\n                {\n                    if (this.currentTrack?.info?.type !== 'video')\n                        break;\n                    const pitch = readFloat(slice, size);\n                    try {\n                        const normalized = normalizeRotation(pitch);\n                        this.currentTrack.info.verticalScale = Math.round(Math.cos(normalized * DEG_TO_RAD));\n                    }\n                    catch {\n                        // It wasn't a valid rotation\n                    }\n                }\n                ;\n                break;\n            case EBMLId.ProjectionPoseRoll:\n                {\n                    if (this.currentTrack?.info?.type !== 'video')\n                        break;\n                    const rotation = readFloat(slice, size);\n                    const flippedRotation = -rotation; // Convert counter-clockwise to clockwise\n                    try {\n                        this.currentTrack.info.rotation = normalizeRotation(flippedRotation);\n                    }\n                    catch {\n                        // It wasn't a valid rotation\n                    }\n                }\n                ;\n                break;\n            case EBMLId.Audio:\n                {\n                    if (this.currentTrack?.info?.type !== 'audio')\n                        break;\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                }\n                ;\n                break;\n            case EBMLId.SamplingFrequency:\n                {\n                    if (this.currentTrack?.info?.type !== 'audio')\n                        break;\n                    const sampleRate = readFloat(slice, size);\n                    if (!(sampleRate > 0) || !Number.isFinite(sampleRate)) {\n                        throw new Error('Invalid SamplingFrequency element: must be a positive, finite number.');\n                    }\n                    this.currentTrack.info.sampleRate = sampleRate;\n                }\n                ;\n                break;\n            case EBMLId.Channels:\n                {\n                    if (this.currentTrack?.info?.type !== 'audio')\n                        break;\n                    const numberOfChannels = readUnsignedInt(slice, size);\n                    if (numberOfChannels === 0) {\n                        throw new Error('Invalid Channels element: must not be 0.');\n                    }\n                    this.currentTrack.info.numberOfChannels = numberOfChannels;\n                }\n                ;\n                break;\n            case EBMLId.BitDepth:\n                {\n                    if (this.currentTrack?.info?.type !== 'audio')\n                        break;\n                    this.currentTrack.info.bitDepth = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.CuePoint:\n                {\n                    if (!this.currentSegment)\n                        break;\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                    this.currentCueTime = null;\n                }\n                ;\n                break;\n            case EBMLId.CueTime:\n                {\n                    this.currentCueTime = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.CueTrackPositions:\n                {\n                    if (this.currentCueTime === null || !this.currentSegment)\n                        break;\n                    const cuePoint = { time: this.currentCueTime, trackId: -1, clusterPosition: -1 };\n                    this.currentSegment.cuePoints.push(cuePoint);\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                    if (cuePoint.trackId === -1 || cuePoint.clusterPosition === -1) {\n                        this.currentSegment.cuePoints.pop();\n                    }\n                }\n                ;\n                break;\n            case EBMLId.CueTrack:\n                {\n                    const lastCuePoint = this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length - 1];\n                    if (!lastCuePoint)\n                        break;\n                    lastCuePoint.trackId = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.CueClusterPosition:\n                {\n                    const lastCuePoint = this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length - 1];\n                    if (!lastCuePoint)\n                        break;\n                    assert(this.currentSegment);\n                    lastCuePoint.clusterPosition = this.currentSegment.dataStartPos + readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.Timestamp:\n                {\n                    if (!this.currentCluster)\n                        break;\n                    this.currentCluster.timestamp = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.SimpleBlock:\n                {\n                    if (!this.currentCluster)\n                        break;\n                    const blockSlice = slice.slice(dataStartPos, size);\n                    const trackNumber = readVarInt(blockSlice);\n                    if (trackNumber === null || blockSlice.remainingLength < 3)\n                        break;\n                    const trackData = this.getTrackDataInCluster(this.currentCluster, trackNumber);\n                    if (!trackData)\n                        break; // Not a track we care about\n                    const relativeTimestamp = readI16Be(blockSlice);\n                    const flags = readU8(blockSlice);\n                    const lacing = (flags >> 1) & 0x3; // If the block is laced, we'll expand it later\n                    let isKeyFrame = !!(flags & 0x80);\n                    if (trackData.track.info?.type === 'audio' && trackData.track.info.codec) {\n                        // Some files don't mark their audio packets as key packets (I'm looking at you, Firefox). But, we\n                        // can fix this in most cases: if we recognize the codec of the track, then we know every packet is\n                        // necessarily a key packet, no matter what the container says.\n                        // https://github.com/Vanilagy/mediabunny/issues/192\n                        isKeyFrame = true;\n                    }\n                    const blockData = readBytes(blockSlice, blockSlice.remainingLength);\n                    const hasDecodingInstructions = trackData.track.decodingInstructions.length > 0;\n                    trackData.blocks.push({\n                        timestamp: relativeTimestamp, // We'll add the cluster's timestamp to this later\n                        duration: 0, // Will set later\n                        isKeyFrame,\n                        data: blockData,\n                        lacing,\n                        decoded: !hasDecodingInstructions,\n                        postProcessed: false,\n                        mainAdditional: null,\n                    });\n                }\n                ;\n                break;\n            case EBMLId.BlockGroup:\n                {\n                    if (!this.currentCluster)\n                        break;\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                    this.currentBlock = null;\n                }\n                ;\n                break;\n            case EBMLId.Block:\n                {\n                    if (!this.currentCluster)\n                        break;\n                    const blockSlice = slice.slice(dataStartPos, size);\n                    const trackNumber = readVarInt(blockSlice);\n                    if (trackNumber === null || blockSlice.remainingLength < 3)\n                        break;\n                    const trackData = this.getTrackDataInCluster(this.currentCluster, trackNumber);\n                    if (!trackData)\n                        break;\n                    const relativeTimestamp = readI16Be(blockSlice);\n                    const flags = readU8(blockSlice);\n                    const lacing = (flags >> 1) & 0x3; // If the block is laced, we'll expand it later\n                    const blockData = readBytes(blockSlice, blockSlice.remainingLength);\n                    const hasDecodingInstructions = trackData.track.decodingInstructions.length > 0;\n                    this.currentBlock = {\n                        timestamp: relativeTimestamp, // We'll add the cluster's timestamp to this later\n                        duration: 0, // Will set later\n                        isKeyFrame: true,\n                        data: blockData,\n                        lacing,\n                        decoded: !hasDecodingInstructions,\n                        postProcessed: false,\n                        mainAdditional: null,\n                    };\n                    trackData.blocks.push(this.currentBlock);\n                }\n                ;\n                break;\n            case EBMLId.BlockAdditions:\n                {\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                }\n                ;\n                break;\n            case EBMLId.BlockMore:\n                {\n                    // Nested elements may modify the current block, so hold onto it\n                    const block = this.currentBlock;\n                    if (!block)\n                        break;\n                    const blockAdditional = {\n                        addId: 1,\n                        data: null,\n                    };\n                    this.currentBlockAdditional = blockAdditional;\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                    if (blockAdditional.data && blockAdditional.addId === 1) {\n                        block.mainAdditional = blockAdditional.data;\n                    }\n                    this.currentBlockAdditional = null;\n                }\n                ;\n                break;\n            case EBMLId.BlockAdditional:\n                {\n                    if (!this.currentBlockAdditional)\n                        break;\n                    this.currentBlockAdditional.data = readBytes(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.BlockAddID:\n                {\n                    if (!this.currentBlockAdditional)\n                        break;\n                    this.currentBlockAdditional.addId = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.BlockDuration:\n                {\n                    if (!this.currentBlock)\n                        break;\n                    this.currentBlock.duration = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.ReferenceBlock:\n                {\n                    if (!this.currentBlock)\n                        break;\n                    this.currentBlock.isKeyFrame = false;\n                    // We ignore the actual value here, we just use the reference as an indicator for \"not a key frame\".\n                    // This is in line with FFmpeg's behavior.\n                }\n                ;\n                break;\n            case EBMLId.Tag:\n                {\n                    this.currentTagTargetIsMovie = true;\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                }\n                ;\n                break;\n            case EBMLId.Targets:\n                {\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                }\n                ;\n                break;\n            case EBMLId.TargetTypeValue:\n                {\n                    const targetTypeValue = readUnsignedInt(slice, size);\n                    if (targetTypeValue !== 50) {\n                        this.currentTagTargetIsMovie = false;\n                    }\n                }\n                ;\n                break;\n            case EBMLId.TagTrackUID:\n            case EBMLId.TagEditionUID:\n            case EBMLId.TagChapterUID:\n            case EBMLId.TagAttachmentUID:\n                {\n                    this.currentTagTargetIsMovie = false;\n                }\n                ;\n                break;\n            case EBMLId.SimpleTag:\n                {\n                    if (!this.currentTagTargetIsMovie)\n                        break;\n                    this.currentSimpleTagName = null;\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                }\n                ;\n                break;\n            case EBMLId.TagName:\n                {\n                    this.currentSimpleTagName = readUnicodeString(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.TagString:\n                {\n                    if (!this.currentSimpleTagName)\n                        break;\n                    const value = readUnicodeString(slice, size);\n                    this.processTagValue(this.currentSimpleTagName, value);\n                }\n                ;\n                break;\n            case EBMLId.TagBinary:\n                {\n                    if (!this.currentSimpleTagName)\n                        break;\n                    const value = readBytes(slice, size);\n                    this.processTagValue(this.currentSimpleTagName, value);\n                }\n                ;\n                break;\n            case EBMLId.AttachedFile:\n                {\n                    if (!this.currentSegment || this.currentAttachedFile)\n                        break; // Nested attached files make no sense\n                    this.currentAttachedFile = {\n                        fileUid: null,\n                        fileName: null,\n                        fileMediaType: null,\n                        fileData: null,\n                        fileDescription: null,\n                    };\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                    const tags = this.currentSegment.metadataTags;\n                    if (this.currentAttachedFile.fileUid && this.currentAttachedFile.fileData) {\n                        // All attached files get surfaced in the `raw` metadata tags\n                        tags.raw ??= {};\n                        tags.raw[this.currentAttachedFile.fileUid.toString()] = new AttachedFile(this.currentAttachedFile.fileData, this.currentAttachedFile.fileMediaType ?? undefined, this.currentAttachedFile.fileName ?? undefined, this.currentAttachedFile.fileDescription ?? undefined);\n                    }\n                    // Only process image attachments\n                    if (this.currentAttachedFile.fileMediaType?.startsWith('image/') && this.currentAttachedFile.fileData) {\n                        const fileName = this.currentAttachedFile.fileName;\n                        let kind = 'unknown';\n                        if (fileName) {\n                            const lowerName = fileName.toLowerCase();\n                            if (lowerName.startsWith('cover.')) {\n                                kind = 'coverFront';\n                            }\n                            else if (lowerName.startsWith('back.')) {\n                                kind = 'coverBack';\n                            }\n                        }\n                        tags.images ??= [];\n                        tags.images.push({\n                            data: this.currentAttachedFile.fileData,\n                            mimeType: this.currentAttachedFile.fileMediaType,\n                            kind,\n                            name: this.currentAttachedFile.fileName ?? undefined,\n                            description: this.currentAttachedFile.fileDescription ?? undefined,\n                        });\n                    }\n                    this.currentAttachedFile = null;\n                }\n                ;\n                break;\n            case EBMLId.FileUID:\n                {\n                    if (!this.currentAttachedFile)\n                        break;\n                    this.currentAttachedFile.fileUid = readUnsignedBigInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.FileName:\n                {\n                    if (!this.currentAttachedFile)\n                        break;\n                    this.currentAttachedFile.fileName = readUnicodeString(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.FileMediaType:\n                {\n                    if (!this.currentAttachedFile)\n                        break;\n                    this.currentAttachedFile.fileMediaType = readAsciiString(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.FileData:\n                {\n                    if (!this.currentAttachedFile)\n                        break;\n                    this.currentAttachedFile.fileData = readBytes(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.FileDescription:\n                {\n                    if (!this.currentAttachedFile)\n                        break;\n                    this.currentAttachedFile.fileDescription = readUnicodeString(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.ContentEncodings:\n                {\n                    // Nested elements may modify the current track, so hold onto it\n                    const track = this.currentTrack;\n                    if (!track)\n                        break;\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                    // \"**MUST** start with the `ContentEncoding` with the highest `ContentEncodingOrder`\"\n                    track.decodingInstructions.sort((a, b) => b.order - a.order);\n                }\n                ;\n                break;\n            case EBMLId.ContentEncoding:\n                {\n                    const track = this.currentTrack;\n                    if (!track)\n                        break;\n                    const instruction = {\n                        order: 0,\n                        scope: ContentEncodingScope.Block,\n                        data: null,\n                    };\n                    this.currentDecodingInstruction = instruction;\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                    if (instruction.data) {\n                        track.decodingInstructions.push(instruction);\n                    }\n                    this.currentDecodingInstruction = null;\n                }\n                ;\n                break;\n            case EBMLId.ContentEncodingOrder:\n                {\n                    if (!this.currentDecodingInstruction)\n                        break;\n                    this.currentDecodingInstruction.order = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.ContentEncodingScope:\n                {\n                    if (!this.currentDecodingInstruction)\n                        break;\n                    this.currentDecodingInstruction.scope = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.ContentCompression:\n                {\n                    if (!this.currentDecodingInstruction)\n                        break;\n                    this.currentDecodingInstruction.data = {\n                        type: 'decompress',\n                        algorithm: ContentCompAlgo.Zlib,\n                        settings: null,\n                    };\n                    this.readContiguousElements(slice.slice(dataStartPos, size));\n                }\n                ;\n                break;\n            case EBMLId.ContentCompAlgo:\n                {\n                    if (this.currentDecodingInstruction?.data?.type !== 'decompress')\n                        break;\n                    this.currentDecodingInstruction.data.algorithm = readUnsignedInt(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.ContentCompSettings:\n                {\n                    if (this.currentDecodingInstruction?.data?.type !== 'decompress')\n                        break;\n                    this.currentDecodingInstruction.data.settings = readBytes(slice, size);\n                }\n                ;\n                break;\n            case EBMLId.ContentEncryption:\n                {\n                    if (!this.currentDecodingInstruction)\n                        break;\n                    this.currentDecodingInstruction.data = {\n                        type: 'decrypt',\n                    };\n                }\n                ;\n                break;\n        }\n        slice.filePos = dataStartPos + size;\n        return true;\n    }\n    decodeBlockData(track, rawData) {\n        assert(track.decodingInstructions.length > 0); // This method shouldn't be called otherwise\n        let currentData = rawData;\n        for (const instruction of track.decodingInstructions) {\n            assert(instruction.data);\n            switch (instruction.data.type) {\n                case 'decompress':\n                    {\n                        switch (instruction.data.algorithm) {\n                            case ContentCompAlgo.HeaderStripping:\n                                {\n                                    if (instruction.data.settings && instruction.data.settings.length > 0) {\n                                        const prefix = instruction.data.settings;\n                                        const newData = new Uint8Array(prefix.length + currentData.length);\n                                        newData.set(prefix, 0);\n                                        newData.set(currentData, prefix.length);\n                                        currentData = newData;\n                                    }\n                                }\n                                ;\n                                break;\n                            default:\n                                {\n                                    // Unhandled\n                                }\n                                ;\n                        }\n                    }\n                    ;\n                    break;\n                default:\n                    {\n                        // Unhandled\n                    }\n                    ;\n            }\n        }\n        return currentData;\n    }\n    processTagValue(name, value) {\n        if (!this.currentSegment?.metadataTags)\n            return;\n        const metadataTags = this.currentSegment.metadataTags;\n        metadataTags.raw ??= {};\n        metadataTags.raw[name] ??= value;\n        if (typeof value === 'string') {\n            switch (name.toLowerCase()) {\n                case 'title':\n                    {\n                        metadataTags.title ??= value;\n                    }\n                    ;\n                    break;\n                case 'description':\n                    {\n                        metadataTags.description ??= value;\n                    }\n                    ;\n                    break;\n                case 'artist':\n                    {\n                        metadataTags.artist ??= value;\n                    }\n                    ;\n                    break;\n                case 'album':\n                    {\n                        metadataTags.album ??= value;\n                    }\n                    ;\n                    break;\n                case 'album_artist':\n                    {\n                        metadataTags.albumArtist ??= value;\n                    }\n                    ;\n                    break;\n                case 'genre':\n                    {\n                        metadataTags.genre ??= value;\n                    }\n                    ;\n                    break;\n                case 'bpm':\n                    {\n                        const bpm = Number.parseInt(value, 10);\n                        if (Number.isInteger(bpm) && bpm > 0) {\n                            metadataTags.beatsPerMinute ??= bpm;\n                        }\n                    }\n                    ;\n                    break;\n                case 'comment':\n                    {\n                        metadataTags.comment ??= value;\n                    }\n                    ;\n                    break;\n                case 'lyrics':\n                    {\n                        metadataTags.lyrics ??= value;\n                    }\n                    ;\n                    break;\n                case 'date':\n                    {\n                        const date = new Date(value);\n                        if (!Number.isNaN(date.getTime())) {\n                            metadataTags.date ??= date;\n                        }\n                    }\n                    ;\n                    break;\n                case 'track_number':\n                case 'part_number':\n                    {\n                        const parts = value.split('/');\n                        const trackNum = Number.parseInt(parts[0], 10);\n                        const tracksTotal = parts[1] && Number.parseInt(parts[1], 10);\n                        if (Number.isInteger(trackNum) && trackNum > 0) {\n                            metadataTags.trackNumber ??= trackNum;\n                        }\n                        if (tracksTotal && Number.isInteger(tracksTotal) && tracksTotal > 0) {\n                            metadataTags.tracksTotal ??= tracksTotal;\n                        }\n                    }\n                    ;\n                    break;\n                case 'disc_number':\n                case 'disc':\n                    {\n                        const discParts = value.split('/');\n                        const discNum = Number.parseInt(discParts[0], 10);\n                        const discsTotal = discParts[1] && Number.parseInt(discParts[1], 10);\n                        if (Number.isInteger(discNum) && discNum > 0) {\n                            metadataTags.discNumber ??= discNum;\n                        }\n                        if (discsTotal && Number.isInteger(discsTotal) && discsTotal > 0) {\n                            metadataTags.discsTotal ??= discsTotal;\n                        }\n                    }\n                    ;\n                    break;\n            }\n        }\n    }\n    getDurationFromMetadata(segment) {\n        if (segment.duration <= 0) {\n            return null;\n        }\n        // We treat the Duration field as the end timestamp of the segment, since this is what FFmpeg treats it as.\n        // The spec unfortunately does not clarify what it means by duration here.\n        return segment.duration / segment.timestampFactor;\n    }\n}\nclass MatroskaTrackBacking {\n    constructor(internalTrack) {\n        this.internalTrack = internalTrack;\n        this.packetToClusterLocation = new WeakMap();\n    }\n    getId() {\n        return this.internalTrack.id;\n    }\n    getNumber() {\n        const demuxer = this.internalTrack.demuxer;\n        const trackType = this.internalTrack.trackBacking.getType();\n        let number = 0;\n        for (const segment of demuxer.segments) {\n            for (const track of segment.tracks) {\n                if (track.trackBacking.getType() === trackType) {\n                    number++;\n                }\n                if (track === this.internalTrack) {\n                    break;\n                }\n            }\n        }\n        return number;\n    }\n    getCodec() {\n        throw new Error('Not implemented on base class.');\n    }\n    getInternalCodecId() {\n        return this.internalTrack.codecId;\n    }\n    getName() {\n        return this.internalTrack.name;\n    }\n    getLanguageCode() {\n        return this.internalTrack.languageCode;\n    }\n    getTimeResolution() {\n        return this.internalTrack.segment.timestampFactor;\n    }\n    isRelativeToUnixEpoch() {\n        return false;\n    }\n    getUnixTimeForTimestamp() {\n        return null;\n    }\n    getDisposition() {\n        return this.internalTrack.disposition;\n    }\n    getPairingMask() {\n        return 1n;\n    }\n    getBitrate() {\n        return null;\n    }\n    getAverageBitrate() {\n        return null;\n    }\n    async getDurationFromMetadata() {\n        return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment);\n    }\n    async getLiveRefreshInterval() {\n        return null;\n    }\n    async getFirstPacket(options) {\n        return this.performClusterLookup(null, (cluster) => {\n            const trackData = cluster.trackData.get(this.internalTrack.id);\n            if (trackData) {\n                return {\n                    blockIndex: 0,\n                    correctBlockFound: true,\n                };\n            }\n            return {\n                blockIndex: -1,\n                correctBlockFound: false,\n            };\n        }, -Infinity, // Use -Infinity as a search timestamp to avoid using the cues\n        Infinity, options);\n    }\n    intoTimescale(timestamp) {\n        // Do a little rounding to catch cases where the result is very close to an integer. If it is, it's likely\n        // that the number was originally an integer divided by the timescale. For stability, it's best\n        // to return the integer in this case.\n        return roundIfAlmostInteger(timestamp * this.internalTrack.segment.timestampFactor);\n    }\n    async getPacket(timestamp, options) {\n        const timestampInTimescale = this.intoTimescale(timestamp);\n        return this.performClusterLookup(null, (cluster) => {\n            const trackData = cluster.trackData.get(this.internalTrack.id);\n            if (!trackData) {\n                return { blockIndex: -1, correctBlockFound: false };\n            }\n            const index = binarySearchLessOrEqual(trackData.presentationTimestamps, timestampInTimescale, x => x.timestamp);\n            const blockIndex = index !== -1 ? trackData.presentationTimestamps[index].blockIndex : -1;\n            const correctBlockFound = index !== -1 && timestampInTimescale < trackData.endTimestamp;\n            return { blockIndex, correctBlockFound };\n        }, timestampInTimescale, timestampInTimescale, options);\n    }\n    async getNextPacket(packet, options) {\n        const locationInCluster = this.packetToClusterLocation.get(packet);\n        if (locationInCluster === undefined) {\n            throw new Error('Packet was not created from this track.');\n        }\n        return this.performClusterLookup(locationInCluster.cluster, (cluster) => {\n            if (cluster === locationInCluster.cluster) {\n                const trackData = cluster.trackData.get(this.internalTrack.id);\n                if (locationInCluster.blockIndex + 1 < trackData.blocks.length) {\n                    // We can simply take the next block in the cluster\n                    return {\n                        blockIndex: locationInCluster.blockIndex + 1,\n                        correctBlockFound: true,\n                    };\n                }\n            }\n            else {\n                const trackData = cluster.trackData.get(this.internalTrack.id);\n                if (trackData) {\n                    return {\n                        blockIndex: 0,\n                        correctBlockFound: true,\n                    };\n                }\n            }\n            return {\n                blockIndex: -1,\n                correctBlockFound: false,\n            };\n        }, -Infinity, // Use -Infinity as a search timestamp to avoid using the cues\n        Infinity, options);\n    }\n    async getKeyPacket(timestamp, options) {\n        const timestampInTimescale = this.intoTimescale(timestamp);\n        return this.performClusterLookup(null, (cluster) => {\n            const trackData = cluster.trackData.get(this.internalTrack.id);\n            if (!trackData) {\n                return { blockIndex: -1, correctBlockFound: false };\n            }\n            const index = findLastIndex(trackData.presentationTimestamps, (x) => {\n                const block = trackData.blocks[x.blockIndex];\n                return block.isKeyFrame && x.timestamp <= timestampInTimescale;\n            });\n            const blockIndex = index !== -1 ? trackData.presentationTimestamps[index].blockIndex : -1;\n            const correctBlockFound = index !== -1 && timestampInTimescale < trackData.endTimestamp;\n            return { blockIndex, correctBlockFound };\n        }, timestampInTimescale, timestampInTimescale, options);\n    }\n    async getNextKeyPacket(packet, options) {\n        const locationInCluster = this.packetToClusterLocation.get(packet);\n        if (locationInCluster === undefined) {\n            throw new Error('Packet was not created from this track.');\n        }\n        return this.performClusterLookup(locationInCluster.cluster, (cluster) => {\n            if (cluster === locationInCluster.cluster) {\n                const trackData = cluster.trackData.get(this.internalTrack.id);\n                for (let i = locationInCluster.blockIndex + 1; i < trackData.blocks.length; i++) {\n                    if (trackData.blocks[i].isKeyFrame) {\n                        // We can simply take the next key frame in the cluster\n                        return {\n                            blockIndex: i,\n                            correctBlockFound: true,\n                        };\n                    }\n                }\n            }\n            else {\n                const trackData = cluster.trackData.get(this.internalTrack.id);\n                if (trackData && trackData.firstKeyFrameTimestamp !== null) {\n                    const keyFrameIndex = trackData.blocks.findIndex(x => x.isKeyFrame);\n                    assert(keyFrameIndex !== -1); // There must be one\n                    return {\n                        blockIndex: keyFrameIndex,\n                        correctBlockFound: true,\n                    };\n                }\n            }\n            return {\n                blockIndex: -1,\n                correctBlockFound: false,\n            };\n        }, -Infinity, // Use -Infinity as a search timestamp to avoid using the cues\n        Infinity, options);\n    }\n    async fetchPacketInCluster(cluster, blockIndex, options) {\n        if (blockIndex === -1) {\n            return null;\n        }\n        const trackData = cluster.trackData.get(this.internalTrack.id);\n        const block = trackData.blocks[blockIndex];\n        assert(block);\n        // Perform lazy decoding if needed\n        if (!block.decoded) {\n            block.data = this.internalTrack.demuxer.decodeBlockData(this.internalTrack, block.data);\n            block.decoded = true;\n        }\n        if (!block.postProcessed) {\n            if (this.internalTrack.info?.codec === 'prores') {\n                // For some reason, ProRes packets are stored in Matroska without the frame container atom. FFmpeg cites\n                // the \"Matroska spec\" but the actual spec says nothing about this.\n                const hasFrameContainer = block.data.length >= 8\n                    && block.data[4] === 105 // 'i'\n                    && block.data[5] === 99 // 'c'\n                    && block.data[6] === 112 // 'p'\n                    && block.data[7] === 102; // 'f'\n                if (!hasFrameContainer) {\n                    // Wrap the frame in a frame container\n                    const newData = new Uint8Array(block.data.length + 8);\n                    const newDataView = toDataView(newData);\n                    newDataView.setUint32(0, newData.length, false);\n                    newData[4] = 105; // 'i'\n                    newData[5] = 99; // 'c'\n                    newData[6] = 112; // 'p'\n                    newData[7] = 102; // 'f'\n                    newData.set(block.data, 8);\n                    block.data = newData;\n                }\n            }\n            block.postProcessed = true;\n        }\n        const data = options.metadataOnly ? PLACEHOLDER_DATA : block.data;\n        const timestamp = block.timestamp / this.internalTrack.segment.timestampFactor;\n        const duration = block.duration / this.internalTrack.segment.timestampFactor;\n        const sideData = {};\n        if (block.mainAdditional && this.internalTrack.info?.type === 'video' && this.internalTrack.info.alphaMode) {\n            sideData.alpha = options.metadataOnly ? PLACEHOLDER_DATA : block.mainAdditional;\n            sideData.alphaByteLength = block.mainAdditional.byteLength;\n        }\n        const packet = new EncodedPacket(data, block.isKeyFrame ? 'key' : 'delta', timestamp, duration, cluster.dataStartPos + blockIndex, block.data.byteLength, sideData);\n        this.packetToClusterLocation.set(packet, { cluster, blockIndex });\n        return packet;\n    }\n    /** Looks for a packet in the clusters while trying to load as few clusters as possible to retrieve it. */\n    async performClusterLookup(\n    // The cluster where we start looking\n    startCluster, \n    // This function returns the best-matching block in a given cluster\n    getMatchInCluster, \n    // The timestamp with which we can search the lookup table\n    searchTimestamp, \n    // The timestamp for which we know the correct block will not come after it\n    latestTimestamp, options, \n    // The position for which we know the correct block will not come after it\n    stopPos = Infinity, \n    // How many times we've retried due to a faulty lookup entry\n    lookupRetryCount = 0) {\n        const { demuxer, segment } = this.internalTrack;\n        let currentCluster = null;\n        let bestCluster = null;\n        let bestBlockIndex = -1;\n        if (startCluster) {\n            const { blockIndex, correctBlockFound } = getMatchInCluster(startCluster);\n            if (correctBlockFound) {\n                return this.fetchPacketInCluster(startCluster, blockIndex, options);\n            }\n            if (blockIndex !== -1) {\n                bestCluster = startCluster;\n                bestBlockIndex = blockIndex;\n            }\n        }\n        // Search for a cue point; this way, we won't need to start searching from the start of the file\n        // but can jump right into the correct cluster (or at least nearby).\n        const cuePointIndex = binarySearchLessOrEqual(this.internalTrack.cuePoints, searchTimestamp, x => x.time);\n        const cuePoint = cuePointIndex !== -1\n            ? this.internalTrack.cuePoints[cuePointIndex]\n            : null;\n        // Also check the position cache\n        const positionCacheIndex = binarySearchLessOrEqual(this.internalTrack.clusterPositionCache, searchTimestamp, x => x.startTimestamp);\n        const positionCacheEntry = positionCacheIndex !== -1\n            ? this.internalTrack.clusterPositionCache[positionCacheIndex]\n            : null;\n        const lookupEntryPosition = Math.max(cuePoint?.clusterPosition ?? 0, positionCacheEntry?.elementStartPos ?? 0) || null;\n        const cuePointWins = !!cuePoint && cuePoint.clusterPosition >= (positionCacheEntry?.elementStartPos ?? 0);\n        let currentPos;\n        if (!startCluster) {\n            currentPos = lookupEntryPosition ?? segment.clusterSeekStartPos;\n        }\n        else {\n            if (lookupEntryPosition === null || startCluster.elementStartPos >= lookupEntryPosition) {\n                currentPos = startCluster.elementEndPos;\n                currentCluster = startCluster;\n            }\n            else {\n                // Use the lookup entry\n                currentPos = lookupEntryPosition;\n            }\n        }\n        const scanStartPos = currentCluster ? currentCluster.elementStartPos : currentPos;\n        while ((segment.elementEndPos === null || currentPos <= segment.elementEndPos - MIN_HEADER_SIZE)\n            && currentPos < stopPos) {\n            if (currentCluster) {\n                const trackData = currentCluster.trackData.get(this.internalTrack.id);\n                if (trackData && trackData.startTimestamp > latestTimestamp) {\n                    // We're already past the upper bound, no need to keep searching\n                    break;\n                }\n                currentCluster = null; // So we don't process it again next iteration\n            }\n            const summary = segment.clusterSummaries.get(currentPos);\n            if (summary && !summary.trackIds.has(this.internalTrack.id)) {\n                // We've read this cluster before and know it has nothing for this track, so let's not read it again\n                currentPos = summary.elementEndPos;\n                continue;\n            }\n            // Load the header\n            let slice = demuxer.reader.requestSliceRange(currentPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE);\n            if (isThenable(slice))\n                slice = await slice;\n            if (!slice)\n                break;\n            const elementStartPos = currentPos;\n            const elementHeader = readElementHeader(slice);\n            if (!elementHeader\n                || (!LEVEL_1_EBML_IDS.includes(elementHeader.id) && elementHeader.id !== EBMLId.Void)) {\n                // There's an element here that shouldn't be here. Might be garbage. In this case, let's\n                // try and resync to the next valid element.\n                const nextPos = await resync(demuxer.reader, elementStartPos + 1, LEVEL_1_EBML_IDS, Math.min(segment.elementEndPos ?? Infinity, elementStartPos + MAX_RESYNC_LENGTH));\n                if (nextPos) {\n                    currentPos = nextPos;\n                    continue;\n                }\n                else {\n                    break; // Resync failed\n                }\n            }\n            const id = elementHeader.id;\n            let size = elementHeader.size;\n            const dataStartPos = slice.filePos;\n            if (id === EBMLId.Cluster) {\n                currentCluster = await demuxer.readCluster(elementStartPos, segment);\n                // readCluster computes the proper size even if it's undefined in the header, so let's use that instead\n                size = currentCluster.elementEndPos - dataStartPos;\n                const { blockIndex, correctBlockFound } = getMatchInCluster(currentCluster);\n                if (correctBlockFound) {\n                    return this.fetchPacketInCluster(currentCluster, blockIndex, options);\n                }\n                if (blockIndex !== -1) {\n                    bestCluster = currentCluster;\n                    bestBlockIndex = blockIndex;\n                }\n            }\n            if (size === undefined) {\n                // Undefined element size (can happen in livestreamed files). In this case, we need to do some\n                // searching to determine the actual size of the element.\n                assert(id !== EBMLId.Cluster); // Undefined cluster sizes are fixed further up\n                // Search for the next element at level 0 or 1\n                const nextElementPos = await searchForNextElementId(demuxer.reader, dataStartPos, LEVEL_0_AND_1_EBML_IDS, segment.elementEndPos);\n                size = nextElementPos.pos - dataStartPos;\n            }\n            const endPos = dataStartPos + size;\n            if (segment.elementEndPos === null) {\n                // Check the next element. If it's a new segment, we know this segment ends here. The new\n                // segment is just ignored, since we're likely in a livestreamed file and thus only care about\n                // the first segment.\n                let slice = demuxer.reader.requestSliceRange(endPos, MIN_HEADER_SIZE, MAX_HEADER_SIZE);\n                if (isThenable(slice))\n                    slice = await slice;\n                if (!slice)\n                    break;\n                const elementId = readElementId(slice);\n                if (elementId === EBMLId.Segment) {\n                    segment.elementEndPos = endPos; // We now know the segment's size\n                    break;\n                }\n            }\n            currentPos = endPos;\n        }\n        // Handle unsatisfactoy cue points or position cache entries\n        if (lookupEntryPosition !== null && (!bestCluster || bestCluster.elementStartPos < lookupEntryPosition)) {\n            // We found a lookup entry but no cluster from there on that satisfied the match. In this case, let's search\n            // again but using a previous entry of the kind we started from. Each time this happens, we double the\n            // backwards step to perform better (and have more sequential reads) if it takes us a long time to find\n            // the media.\n            //\n            // Note that this doesn't only kick for faulty cue points but also for multi-track files where only one\n            // track has cue points. Since we distribute the cue points to the track with none, they might not\n            // accurately reflect where media can be found.\n            const step = 1 << lookupRetryCount;\n            const previousEntryTimestamp = cuePointWins\n                ? this.internalTrack.cuePoints[cuePointIndex - step]?.time\n                : this.internalTrack.clusterPositionCache[positionCacheIndex - step]?.startTimestamp;\n            const newSearchTimestamp = previousEntryTimestamp ?? -Infinity;\n            return this.performClusterLookup(null, getMatchInCluster, newSearchTimestamp, latestTimestamp, options, scanStartPos, // So we don't read the same clusters again\n            lookupRetryCount + 1);\n        }\n        if (bestCluster) {\n            // If we finished looping but didn't find a perfect match, still return the best match we found\n            return this.fetchPacketInCluster(bestCluster, bestBlockIndex, options);\n        }\n        return null;\n    }\n}\nclass MatroskaVideoTrackBacking extends MatroskaTrackBacking {\n    constructor(internalTrack) {\n        super(internalTrack);\n        this.decoderConfigPromise = null;\n    }\n    getType() {\n        return 'video';\n    }\n    getCodec() {\n        return this.internalTrack.info.codec;\n    }\n    getCodedWidth() {\n        return this.internalTrack.info.width;\n    }\n    getCodedHeight() {\n        return this.internalTrack.info.height;\n    }\n    getSquarePixelWidth() {\n        return this.internalTrack.info.squarePixelWidth;\n    }\n    getSquarePixelHeight() {\n        return this.internalTrack.info.squarePixelHeight;\n    }\n    getTransformationMatrix() {\n        const info = this.internalTrack.info;\n        // Yaw and pitch are applied before roll\n        const linear = multiplyMatrices(scaleMatrix(info.horizontalScale, info.verticalScale), rotationMatrix(info.rotation));\n        return centeredTransformationMatrix(linear, info.width, info.height);\n    }\n    async getColorSpace() {\n        const decoderConfig = await this.getDecoderConfig();\n        if (!decoderConfig) {\n            return this.internalTrack.info.colorSpace;\n        }\n        return {\n            primaries: decoderConfig.colorSpace?.primaries,\n            transfer: decoderConfig.colorSpace?.transfer,\n            matrix: decoderConfig.colorSpace?.matrix,\n            fullRange: decoderConfig.colorSpace?.fullRange,\n        };\n    }\n    async canBeTransparent() {\n        return this.internalTrack.info.alphaMode || (this.internalTrack.info.codec === 'prores' && (this.internalTrack.info.proresFormat === 'ap4h'\n            || this.internalTrack.info.proresFormat === 'ap4x'));\n    }\n    async getDecoderConfig() {\n        if (!this.internalTrack.info.codec) {\n            return null;\n        }\n        return this.decoderConfigPromise ??= (async () => {\n            let firstPacket = null;\n            const needsPacketForAdditionalInfo = this.internalTrack.info.codec === 'vp9'\n                || this.internalTrack.info.codec === 'av1'\n                || this.internalTrack.info.codec === 'prores'\n                // Packets are in Annex B format:\n                || (this.internalTrack.info.codec === 'avc' && !this.internalTrack.info.codecDescription)\n                // Packets are in Annex B format:\n                || (this.internalTrack.info.codec === 'hevc' && !this.internalTrack.info.codecDescription);\n            if (needsPacketForAdditionalInfo) {\n                firstPacket = await this.getFirstPacket({});\n            }\n            const codecInfo = {\n                width: this.internalTrack.info.width,\n                height: this.internalTrack.info.height,\n                codec: this.internalTrack.info.codec,\n                codecDescription: this.internalTrack.info.codecDescription,\n                colorSpace: this.internalTrack.info.colorSpace,\n                avcType: 1, // We don't know better (or do we?) so just assume 'avc1'\n                avcCodecInfo: this.internalTrack.info.codec === 'avc' && firstPacket\n                    ? extractAvcDecoderConfigurationRecord(firstPacket.data)\n                    : null,\n                hevcCodecInfo: this.internalTrack.info.codec === 'hevc' && firstPacket\n                    ? extractHevcDecoderConfigurationRecord(firstPacket.data)\n                    : null,\n                vp9CodecInfo: this.internalTrack.info.codec === 'vp9' && firstPacket\n                    ? extractVp9CodecInfoFromPacket(firstPacket.data)\n                    : null,\n                av1CodecInfo: this.internalTrack.info.codec === 'av1' && firstPacket\n                    ? extractAv1CodecInfoFromPacket(firstPacket.data)\n                    : null,\n                proresCodecInfo: this.internalTrack.info.codec === 'prores' && firstPacket\n                    ? extractProresCodecInfoFromPacket(firstPacket.data)\n                    : null,\n                proresFormat: this.internalTrack.info.proresFormat,\n            };\n            if (!colorSpaceIsComplete(this.internalTrack.info.colorSpace)) {\n                const colorSpace = extractColorSpace(codecInfo);\n                // Fill the missing values\n                this.internalTrack.info.colorSpace.primaries ??= colorSpace.primaries;\n                this.internalTrack.info.colorSpace.transfer ??= colorSpace.transfer;\n                this.internalTrack.info.colorSpace.matrix ??= colorSpace.matrix;\n                this.internalTrack.info.colorSpace.fullRange ??= colorSpace.fullRange;\n            }\n            const config = {\n                codec: extractVideoCodecString(codecInfo),\n                codedWidth: this.internalTrack.info.width,\n                codedHeight: this.internalTrack.info.height,\n                description: this.internalTrack.info.codecDescription ?? undefined,\n                colorSpace: this.internalTrack.info.colorSpace,\n            };\n            if (this.internalTrack.info.width !== this.internalTrack.info.squarePixelWidth\n                || this.internalTrack.info.height !== this.internalTrack.info.squarePixelHeight) {\n                config.displayAspectWidth = this.internalTrack.info.squarePixelWidth;\n                config.displayAspectHeight = this.internalTrack.info.squarePixelHeight;\n            }\n            return config;\n        })();\n    }\n}\nclass MatroskaAudioTrackBacking extends MatroskaTrackBacking {\n    constructor(internalTrack) {\n        super(internalTrack);\n        this.decoderConfigPromise = null;\n    }\n    getType() {\n        return 'audio';\n    }\n    getCodec() {\n        return this.internalTrack.info.codec;\n    }\n    getNumberOfChannels() {\n        return this.internalTrack.info.numberOfChannels;\n    }\n    getSampleRate() {\n        return this.internalTrack.info.sampleRate;\n    }\n    async getDecoderConfig() {\n        if (!this.internalTrack.info.codec) {\n            return null;\n        }\n        return this.decoderConfigPromise ??= (async () => {\n            if (this.internalTrack.info.codec === 'dts' && !this.internalTrack.info.dtsFormat) {\n                // Gotta check the packet to determine the DTS variant\n                const firstPacket = await this.getFirstPacket({});\n                this.internalTrack.info.dtsFormat = firstPacket && extractDtsFourCcFromPacket(firstPacket.data);\n            }\n            return {\n                codec: extractAudioCodecString({\n                    codec: this.internalTrack.info.codec,\n                    codecDescription: this.internalTrack.info.codecDescription,\n                    aacCodecInfo: this.internalTrack.info.aacCodecInfo,\n                    dtsFormat: this.internalTrack.info.dtsFormat,\n                }),\n                numberOfChannels: this.internalTrack.info.numberOfChannels,\n                sampleRate: this.internalTrack.info.sampleRate,\n                description: this.internalTrack.info.codecDescription ?? undefined,\n            };\n        })();\n    }\n}\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { Bitstream } from '../../shared/bitstream.js';\nimport { aacFrequencyTable } from '../../shared/aac-misc.js';\nimport { readBytes, readU16Be } from '../reader.js';\nexport const MIN_ADTS_FRAME_HEADER_SIZE = 7;\nexport const MAX_ADTS_FRAME_HEADER_SIZE = 9;\nexport const readAdtsFrameHeader = (slice) => {\n    // https://wiki.multimedia.cx/index.php/ADTS (last visited: 2025/08/17)\n    const startPos = slice.filePos;\n    if (slice.remainingLength < MIN_ADTS_FRAME_HEADER_SIZE) {\n        return null;\n    }\n    const bytes = readBytes(slice, MIN_ADTS_FRAME_HEADER_SIZE);\n    const bitstream = new Bitstream(bytes);\n    const syncword = bitstream.readBits(12);\n    if (syncword !== 0b1111_11111111) {\n        return null;\n    }\n    bitstream.skipBits(1); // MPEG version\n    const layer = bitstream.readBits(2);\n    if (layer !== 0) {\n        return null;\n    }\n    const protectionAbsence = bitstream.readBits(1);\n    const objectType = bitstream.readBits(2) + 1;\n    const samplingFrequencyIndex = bitstream.readBits(4);\n    if (samplingFrequencyIndex >= aacFrequencyTable.length) {\n        return null;\n    }\n    bitstream.skipBits(1); // Private bit\n    const channelConfiguration = bitstream.readBits(3);\n    if (channelConfiguration === 0) {\n        throw new Error('ADTS frames with channel configuration 0 are not supported.');\n    }\n    bitstream.skipBits(1); // Originality\n    bitstream.skipBits(1); // Home\n    bitstream.skipBits(1); // Copyright ID bit\n    bitstream.skipBits(1); // Copyright ID start\n    const frameLength = bitstream.readBits(13);\n    bitstream.skipBits(11); // Buffer fullness\n    const numberOfAacFrames = bitstream.readBits(2) + 1;\n    if (numberOfAacFrames !== 1) {\n        throw new Error('ADTS frames with more than one AAC frame are not supported.');\n    }\n    let crcCheck = null;\n    if (protectionAbsence === 0) { // CRC\n        if (slice.remainingLength < 2) {\n            return null;\n        }\n        crcCheck = readU16Be(slice);\n    }\n    if (frameLength < slice.filePos - startPos) {\n        return null; // The frame must at least contain its own header\n    }\n    return {\n        objectType,\n        samplingFrequencyIndex,\n        channelConfiguration,\n        frameLength,\n        numberOfAacFrames,\n        crcCheck,\n        startPos,\n    };\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { aacChannelMap, aacFrequencyTable } from '../../shared/aac-misc.js';\nimport { Demuxer } from '../demuxer.js';\nimport { ID3_V2_HEADER_SIZE, parseId3V2Tag, readId3V2Header, } from '../id3.js';\nimport { DEFAULT_TRACK_DISPOSITION } from '../metadata.js';\nimport { assert, AsyncMutex, binarySearchExact, binarySearchLessOrEqual, isThenable, UNDETERMINED_LANGUAGE, } from '../misc.js';\nimport { EncodedPacket, PLACEHOLDER_DATA } from '../packet.js';\nimport { readBytes } from '../reader.js';\nimport { MIN_ADTS_FRAME_HEADER_SIZE, MAX_ADTS_FRAME_HEADER_SIZE, readAdtsFrameHeader, } from './adts-reader.js';\nexport const SAMPLES_PER_AAC_FRAME = 1024;\nexport class AdtsDemuxer extends Demuxer {\n    constructor(input) {\n        super(input);\n        this.metadataPromise = null;\n        this.firstFrameHeader = null;\n        this.loadedSamples = [];\n        this.metadataTags = null;\n        this.trackBackings = [];\n        this.readingMutex = new AsyncMutex();\n        this.lastSampleLoaded = false;\n        this.lastLoadedPos = 0;\n        this.nextTimestampInSamples = 0;\n        this.reader = input._reader;\n    }\n    async readMetadata() {\n        return this.metadataPromise ??= (async () => {\n            // Keep loading until we find the first frame header\n            while (!this.firstFrameHeader && !this.lastSampleLoaded) {\n                await this.advanceReader();\n            }\n            // There has to be a frame if this demuxer got selected\n            assert(this.firstFrameHeader);\n            // Create the single audio track\n            this.trackBackings = [new AdtsAudioTrackBacking(this)];\n        })();\n    }\n    async advanceReader() {\n        if (this.lastLoadedPos === 0) {\n            // Skip all ID3v2 tags at the start of the file\n            while (true) {\n                let slice = this.reader.requestSlice(this.lastLoadedPos, ID3_V2_HEADER_SIZE);\n                if (isThenable(slice))\n                    slice = await slice;\n                if (!slice) {\n                    this.lastSampleLoaded = true;\n                    return;\n                }\n                const id3V2Header = readId3V2Header(slice);\n                if (!id3V2Header) {\n                    break;\n                }\n                this.lastLoadedPos = slice.filePos + id3V2Header.size;\n            }\n        }\n        let slice = this.reader.requestSliceRange(this.lastLoadedPos, MIN_ADTS_FRAME_HEADER_SIZE, MAX_ADTS_FRAME_HEADER_SIZE);\n        if (isThenable(slice))\n            slice = await slice;\n        if (!slice) {\n            this.lastSampleLoaded = true;\n            return;\n        }\n        const header = readAdtsFrameHeader(slice);\n        if (!header) {\n            this.lastSampleLoaded = true;\n            return;\n        }\n        if (this.reader.fileSize !== null && header.startPos + header.frameLength > this.reader.fileSize) {\n            // Frame doesn't fit in the rest of the file\n            this.lastSampleLoaded = true;\n            return;\n        }\n        if (!this.firstFrameHeader) {\n            this.firstFrameHeader = header;\n        }\n        const sampleRate = aacFrequencyTable[header.samplingFrequencyIndex];\n        assert(sampleRate !== undefined);\n        const sampleDuration = SAMPLES_PER_AAC_FRAME / sampleRate;\n        const sample = {\n            timestamp: this.nextTimestampInSamples / sampleRate,\n            duration: sampleDuration,\n            dataStart: header.startPos,\n            dataSize: header.frameLength,\n        };\n        this.loadedSamples.push(sample);\n        this.nextTimestampInSamples += SAMPLES_PER_AAC_FRAME;\n        this.lastLoadedPos = header.startPos + header.frameLength;\n    }\n    async getMimeType() {\n        return 'audio/aac';\n    }\n    async getTrackBackings() {\n        await this.readMetadata();\n        return this.trackBackings;\n    }\n    async getMetadataTags() {\n        const release = await this.readingMutex.acquire();\n        try {\n            await this.readMetadata();\n            if (this.metadataTags) {\n                return this.metadataTags;\n            }\n            this.metadataTags = {};\n            let currentPos = 0;\n            while (true) {\n                let headerSlice = this.reader.requestSlice(currentPos, ID3_V2_HEADER_SIZE);\n                if (isThenable(headerSlice))\n                    headerSlice = await headerSlice;\n                if (!headerSlice)\n                    break;\n                const id3V2Header = readId3V2Header(headerSlice);\n                if (!id3V2Header) {\n                    break;\n                }\n                let contentSlice = this.reader.requestSlice(headerSlice.filePos, id3V2Header.size);\n                if (isThenable(contentSlice))\n                    contentSlice = await contentSlice;\n                if (!contentSlice)\n                    break;\n                parseId3V2Tag(contentSlice, id3V2Header, this.metadataTags);\n                currentPos = headerSlice.filePos + id3V2Header.size;\n            }\n            return this.metadataTags;\n        }\n        finally {\n            release();\n        }\n    }\n}\nclass AdtsAudioTrackBacking {\n    constructor(demuxer) {\n        this.demuxer = demuxer;\n    }\n    getType() {\n        return 'audio';\n    }\n    getId() {\n        return 1;\n    }\n    getNumber() {\n        return 1;\n    }\n    getTimeResolution() {\n        const sampleRate = this.getSampleRate();\n        return sampleRate / SAMPLES_PER_AAC_FRAME;\n    }\n    isRelativeToUnixEpoch() {\n        return false;\n    }\n    getUnixTimeForTimestamp() {\n        return null;\n    }\n    getPairingMask() {\n        return 1n;\n    }\n    getBitrate() {\n        return null;\n    }\n    getAverageBitrate() {\n        return null;\n    }\n    async getDurationFromMetadata() {\n        return null; // No way\n    }\n    async getLiveRefreshInterval() {\n        return null;\n    }\n    getName() {\n        return null;\n    }\n    getLanguageCode() {\n        return UNDETERMINED_LANGUAGE;\n    }\n    getCodec() {\n        return 'aac';\n    }\n    getInternalCodecId() {\n        assert(this.demuxer.firstFrameHeader);\n        return this.demuxer.firstFrameHeader.objectType;\n    }\n    getNumberOfChannels() {\n        assert(this.demuxer.firstFrameHeader);\n        const numberOfChannels = aacChannelMap[this.demuxer.firstFrameHeader.channelConfiguration];\n        assert(numberOfChannels !== undefined);\n        return numberOfChannels;\n    }\n    getSampleRate() {\n        assert(this.demuxer.firstFrameHeader);\n        const sampleRate = aacFrequencyTable[this.demuxer.firstFrameHeader.samplingFrequencyIndex];\n        assert(sampleRate !== undefined);\n        return sampleRate;\n    }\n    getDisposition() {\n        return {\n            ...DEFAULT_TRACK_DISPOSITION,\n        };\n    }\n    async getDecoderConfig() {\n        assert(this.demuxer.firstFrameHeader);\n        return {\n            codec: `mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,\n            numberOfChannels: this.getNumberOfChannels(),\n            sampleRate: this.getSampleRate(),\n        };\n    }\n    async getPacketAtIndex(sampleIndex, options) {\n        if (sampleIndex === -1) {\n            return null;\n        }\n        const rawSample = this.demuxer.loadedSamples[sampleIndex];\n        if (!rawSample) {\n            return null;\n        }\n        let data;\n        if (options.metadataOnly) {\n            data = PLACEHOLDER_DATA;\n        }\n        else {\n            let slice = this.demuxer.reader.requestSlice(rawSample.dataStart, rawSample.dataSize);\n            if (isThenable(slice))\n                slice = await slice;\n            if (!slice) {\n                return null; // Data didn't fit into the rest of the file\n            }\n            data = readBytes(slice, rawSample.dataSize);\n        }\n        return new EncodedPacket(data, 'key', rawSample.timestamp, rawSample.duration, sampleIndex, rawSample.dataSize);\n    }\n    getFirstPacket(options) {\n        return this.getPacketAtIndex(0, options);\n    }\n    async getNextPacket(packet, options) {\n        const release = await this.demuxer.readingMutex.acquire();\n        try {\n            const sampleIndex = binarySearchExact(this.demuxer.loadedSamples, packet.timestamp, x => x.timestamp);\n            if (sampleIndex === -1) {\n                throw new Error('Packet was not created from this track.');\n            }\n            const nextIndex = sampleIndex + 1;\n            // Ensure the next sample exists\n            while (nextIndex >= this.demuxer.loadedSamples.length\n                && !this.demuxer.lastSampleLoaded) {\n                await this.demuxer.advanceReader();\n            }\n            return this.getPacketAtIndex(nextIndex, options);\n        }\n        finally {\n            release();\n        }\n    }\n    async getPacket(timestamp, options) {\n        const release = await this.demuxer.readingMutex.acquire();\n        try {\n            while (true) {\n                const index = binarySearchLessOrEqual(this.demuxer.loadedSamples, timestamp, x => x.timestamp);\n                if (index === -1 && this.demuxer.loadedSamples.length > 0) {\n                    // We're before the first sample\n                    return null;\n                }\n                if (this.demuxer.lastSampleLoaded) {\n                    // All data is loaded, return what we found\n                    return this.getPacketAtIndex(index, options);\n                }\n                if (index >= 0 && index + 1 < this.demuxer.loadedSamples.length) {\n                    // The next packet also exists, we're done\n                    return this.getPacketAtIndex(index, options);\n                }\n                // Otherwise, keep loading data\n                await this.demuxer.advanceReader();\n            }\n        }\n        finally {\n            release();\n        }\n    }\n    getKeyPacket(timestamp, options) {\n        return this.getPacket(timestamp, options);\n    }\n    getNextKeyPacket(packet, options) {\n        return this.getNextPacket(packet, options);\n    }\n}\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nexport const TIMESCALE = 90_000; // MPEG-TS timestamps run on a 90 kHz clock\nexport const TIMESTAMP_MODULUS = 2 ** 33;\nexport const TS_PACKET_SIZE = 188;\nexport const buildMpegTsMimeType = (codecStrings) => {\n    let string = 'video/MP2T';\n    const uniqueCodecStrings = [...new Set(codecStrings.filter(Boolean))];\n    if (uniqueCodecStrings.length > 0) {\n        string += `; codecs=\"${uniqueCodecStrings.join(', ')}\"`;\n    }\n    return string;\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { SAMPLES_PER_AAC_FRAME } from '../adts/adts-demuxer.js';\nimport { MAX_ADTS_FRAME_HEADER_SIZE, readAdtsFrameHeader } from '../adts/adts-reader.js';\nimport { aacChannelMap, aacFrequencyTable } from '../../shared/aac-misc.js';\nimport { extractAudioCodecString, extractVideoCodecString, } from '../codec.js';\nimport { AC3_ACMOD_CHANNEL_COUNTS, AC3_SAMPLES_PER_FRAME, AvcNalUnitType, determineVideoPacketType, extractAvcDecoderConfigurationRecord, extractHevcDecoderConfigurationRecord, EAC3_NUMBLKS_TABLE, getEac3ChannelCount, getEac3SampleRate, HevcNalUnitType, parseAc3SyncFrame, parseAvcSps, parseEac3SyncFrame, parseHevcSps, AC3_FRAME_SIZES, extractNalUnitTypeForAvc, extractNalUnitTypeForHevc, parseDtsFrame, parseDtsCoreFrameHeader, parseDtsExssHeader, DTS_CORE_FRAME_HEADER_SIZE, DTS_EXSS_HEADER_PREFIX_SIZE, DTS_EXSS_MAX_HEADER_SIZE, } from '../codec-data.js';\nimport { Demuxer } from '../demuxer.js';\nimport { Logging } from '../logging.js';\nimport { DEFAULT_TRACK_DISPOSITION } from '../metadata.js';\nimport { assert, binarySearchExact, binarySearchLessOrEqual, COLOR_PRIMARIES_MAP_INVERSE, findLastIndex, floorToMultiple, isThenable, IDENTITY_MATRIX, last, MATRIX_COEFFICIENTS_MAP_INVERSE, readExpGolomb, roundIfAlmostInteger, toDataView, TRANSFER_CHARACTERISTICS_MAP_INVERSE, UNDETERMINED_LANGUAGE, } from '../misc.js';\nimport { MP3_FRAME_HEADER_SIZE, getMp3ChannelCount, readMp3FrameHeader, } from '../../shared/mp3-misc.js';\nimport { EncodedPacket, PLACEHOLDER_DATA } from '../packet.js';\nimport { FileSlice, readBytes, readU16Be, readU32Be, readU8 } from '../reader.js';\nimport { buildMpegTsMimeType, TIMESCALE, TIMESTAMP_MODULUS, TS_PACKET_SIZE, } from './mpeg-ts-misc.js';\nimport { AC3_SAMPLE_RATES } from '../../shared/ac3-misc.js';\nimport { Bitstream } from '../../shared/bitstream.js';\n// Resources:\n// ISO/IEC 13818-1\nconst MISSING_PTS_ERROR_MESSAGE = 'PES packet is missing PTS where it was expected. PES packets without PTS are not'\n    + ' currently supported. If you think this file should be supported, please report it.';\nconst REGISTRATION_DESCRIPTOR_TAG = 0x05;\n// The 'HDMV' and 'HDPR' format identifiers, which mark a program as Blu-ray-derived\nconst HDMV_FORMAT_IDENTIFIER = 0x48444d56;\nconst HDPR_FORMAT_IDENTIFIER = 0x48445052;\n// 'DTS1', 'DTS2' and 'DTS3' all share this prefix\nconst DTS_FORMAT_IDENTIFIER_PREFIX = 0x44545300;\n// Stream types that only mean DTS within a Blu-ray-derived program\nconst BLU_RAY_DTS_STREAM_TYPES = new Set([\n    133 /* MpegTsStreamType.BLU_RAY_DTS_HD */,\n    134 /* MpegTsStreamType.BLU_RAY_DTS_HD_MASTER */,\n    162 /* MpegTsStreamType.BLU_RAY_DTS_EXPRESS_SECONDARY */,\n]);\n// Remember them so the warning doesn't get spammed\nconst ignoredStreamTypes = new Set();\nexport class MpegTsDemuxer extends Demuxer {\n    constructor(input) {\n        super(input);\n        this.metadataPromise = null;\n        this.elementaryStreams = [];\n        this.trackBackingEntries = [];\n        this.packetOffset = 0;\n        this.packetStride = -1;\n        this.sectionEndPositions = [];\n        this.seekChunkSize = 5 * 1024 * 1024; // 5 MiB, picked because most HLS segments are below this size\n        this.minReferencePointByteDistance = -1;\n        this.timestampWrapInfo = null;\n        this.reader = input._reader;\n    }\n    async readMetadata() {\n        return this.metadataPromise ??= (async () => {\n            const lengthToCheck = TS_PACKET_SIZE + 16 + 1;\n            let startingSlice = this.reader.requestSlice(0, lengthToCheck);\n            if (isThenable(startingSlice))\n                startingSlice = await startingSlice;\n            assert(startingSlice);\n            const startingBytes = readBytes(startingSlice, lengthToCheck);\n            if (startingBytes[0] === 0x47 && startingBytes[TS_PACKET_SIZE] === 0x47) {\n                // Regular MPEG-TS\n                this.packetOffset = 0;\n                this.packetStride = TS_PACKET_SIZE;\n            }\n            else if (startingBytes[0] === 0x47 && startingBytes[TS_PACKET_SIZE + 16] === 0x47) {\n                // MPEG-TS with Forward Error Correction\n                this.packetOffset = 0;\n                this.packetStride = TS_PACKET_SIZE + 16;\n            }\n            else if (startingBytes[4] === 0x47 && startingBytes[4 + TS_PACKET_SIZE + 4] === 0x47) {\n                // MPEG-2-TS (DVHS)\n                this.packetOffset = 4;\n                this.packetStride = TS_PACKET_SIZE + 4;\n            }\n            else {\n                throw new Error('Unreachable.');\n            }\n            const MIN_REFERENCE_POINT_PACKET_DISTANCE = 256;\n            this.minReferencePointByteDistance = MIN_REFERENCE_POINT_PACKET_DISTANCE * this.packetStride;\n            let currentPos = this.packetOffset;\n            let programMapPid = null;\n            // Some files contain these multiple times, but we only care about their first appearance\n            let hasProgramAssociationTable = false;\n            let hasProgramMap = false;\n            while (true) {\n                const packetHeader = await this.readPacketHeader(currentPos);\n                if (!packetHeader) {\n                    break;\n                }\n                if (packetHeader.payloadUnitStartIndicator === 0) {\n                    // Not the start of a section\n                    currentPos += this.packetStride;\n                    continue;\n                }\n                if (hasProgramMap\n                    && !this.elementaryStreams.some(x => x.pid === packetHeader.pid && !x.initialized)) {\n                    // Don't care about this PID (anymore)\n                    currentPos += this.packetStride;\n                    continue;\n                }\n                const section = await this.readSection(currentPos, true, !hasProgramMap);\n                if (!section) {\n                    break;\n                }\n                const BYTES_BEFORE_SECTION_LENGTH = 3;\n                const BITS_IN_CRC_32 = 32; // Duh\n                // Some streams don't contain a PAT for some reason, so we must do some guesswork to figure out where\n                // the PMT is.\n                let isProbablyProgramMap = false;\n                if (!hasProgramMap && section.pid !== 0) {\n                    const isPesPacket = section.payload[0] === 0x00 && section.payload[1] === 0x00 && section.payload[2] === 0x01;\n                    if (!isPesPacket) {\n                        // Assume it's a PSI\n                        const bitstream = new Bitstream(section.payload);\n                        const pointerField = bitstream.readAlignedByte();\n                        bitstream.skipBits(8 * pointerField);\n                        const tableId = bitstream.readBits(8);\n                        isProbablyProgramMap = tableId === 0x02; // 0x02 == TS_program_map_section\n                    }\n                }\n                if (section.pid === 0 && !hasProgramAssociationTable) {\n                    const bitstream = new Bitstream(section.payload);\n                    const pointerField = bitstream.readAlignedByte();\n                    bitstream.skipBits(8 * pointerField);\n                    bitstream.skipBits(14);\n                    const sectionLength = bitstream.readBits(10);\n                    bitstream.skipBits(40);\n                    while (8 * (sectionLength + BYTES_BEFORE_SECTION_LENGTH) - bitstream.pos > BITS_IN_CRC_32) {\n                        const programNumber = bitstream.readBits(16);\n                        bitstream.skipBits(3); // Reserved\n                        const id = bitstream.readBits(13);\n                        if (programNumber !== 0) {\n                            if (programMapPid !== null) {\n                                throw new Error('Only files with a single program are supported.');\n                            }\n                            else {\n                                programMapPid = id;\n                            }\n                        }\n                    }\n                    if (programMapPid === null) {\n                        throw new Error('Program Association Table must link to a Program Map Table.');\n                    }\n                    hasProgramAssociationTable = true;\n                }\n                else if ((section.pid === programMapPid || isProbablyProgramMap) && !hasProgramMap) {\n                    const bitstream = new Bitstream(section.payload);\n                    const pointerField = bitstream.readAlignedByte();\n                    bitstream.skipBits(8 * pointerField);\n                    bitstream.skipBits(12);\n                    const sectionLength = bitstream.readBits(12);\n                    bitstream.skipBits(43);\n                    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n                    const pcrPid = bitstream.readBits(13);\n                    bitstream.skipBits(6);\n                    // \"The remaining 10 bits specify the number of bytes of the descriptors immediately following the\n                    // program_info_length field\"\n                    const programInfoLength = bitstream.readBits(10);\n                    // A few stream types only mean what Blu-ray says they mean, and the program's registration\n                    // descriptor is what tells us we're looking at a Blu-ray-derived stream.\n                    const programInfoEndPos = bitstream.pos + 8 * programInfoLength;\n                    let isBluRayProgram = false;\n                    while (bitstream.pos < programInfoEndPos) {\n                        const descriptorTag = bitstream.readBits(8);\n                        const descriptorLength = bitstream.readBits(8);\n                        const descriptorEndPos = bitstream.pos + 8 * descriptorLength;\n                        if (descriptorTag === REGISTRATION_DESCRIPTOR_TAG && descriptorLength >= 4) {\n                            const formatIdentifier = bitstream.readBits(32);\n                            isBluRayProgram ||= formatIdentifier === HDMV_FORMAT_IDENTIFIER\n                                || formatIdentifier === HDPR_FORMAT_IDENTIFIER;\n                        }\n                        bitstream.pos = descriptorEndPos;\n                    }\n                    bitstream.pos = programInfoEndPos;\n                    while (8 * (sectionLength + BYTES_BEFORE_SECTION_LENGTH) - bitstream.pos > BITS_IN_CRC_32) {\n                        const streamType = bitstream.readBits(8);\n                        bitstream.skipBits(3);\n                        const elementaryPid = bitstream.readBits(13);\n                        bitstream.skipBits(6);\n                        const esInfoLength = bitstream.readBits(10);\n                        // Check ES descriptors to detect AC-3/E-AC-3/DTS in System B\n                        const esInfoEndPos = bitstream.pos + 8 * esInfoLength;\n                        let hasAc3Descriptor = false;\n                        let hasEac3Descriptor = false;\n                        let hasDtsDescriptor = false;\n                        while (bitstream.pos < esInfoEndPos) {\n                            const descriptorTag = bitstream.readBits(8);\n                            const descriptorLength = bitstream.readBits(8);\n                            const descriptorEndPos = bitstream.pos + 8 * descriptorLength;\n                            if (descriptorTag === 0x6a) {\n                                hasAc3Descriptor = true;\n                            }\n                            else if (descriptorTag === 0x7a || descriptorTag === 0xcc) {\n                                hasEac3Descriptor = true;\n                            }\n                            else if (descriptorTag === 0x7b) {\n                                hasDtsDescriptor = true;\n                            }\n                            else if (descriptorTag === REGISTRATION_DESCRIPTOR_TAG && descriptorLength >= 4) {\n                                // DTS uses 'DTS1', 'DTS2' and 'DTS3' to also signal the stream's frame size,\n                                // which we work out from the bitstream anyway\n                                const formatIdentifier = bitstream.readBits(32);\n                                hasDtsDescriptor ||= (formatIdentifier & 0xffffff00) === DTS_FORMAT_IDENTIFIER_PREFIX;\n                            }\n                            bitstream.pos = descriptorEndPos;\n                        }\n                        let info = null;\n                        // Blu-ray has its own stream types for the DTS extensions\n                        const effectiveStreamType = isBluRayProgram && BLU_RAY_DTS_STREAM_TYPES.has(streamType)\n                            ? 130 /* MpegTsStreamType.DTS */\n                            : streamType;\n                        switch (effectiveStreamType) {\n                            case 27 /* MpegTsStreamType.AVC */:\n                            case 36 /* MpegTsStreamType.HEVC */:\n                                {\n                                    const codec = streamType === 27 /* MpegTsStreamType.AVC */ ? 'avc' : 'hevc';\n                                    info = {\n                                        type: 'video',\n                                        codec,\n                                        decoderConfig: null,\n                                        avcCodecInfo: null,\n                                        hevcCodecInfo: null,\n                                        colorSpace: {\n                                            primaries: null,\n                                            transfer: null,\n                                            matrix: null,\n                                            fullRange: null,\n                                        },\n                                        width: -1,\n                                        height: -1,\n                                        squarePixelWidth: -1,\n                                        squarePixelHeight: -1,\n                                        reorderSize: -1,\n                                    };\n                                }\n                                ;\n                                break;\n                            case 3 /* MpegTsStreamType.MP3_MPEG1 */:\n                            case 4 /* MpegTsStreamType.MP3_MPEG2 */:\n                            case 15 /* MpegTsStreamType.AAC */:\n                            case 129 /* MpegTsStreamType.AC3_SYSTEM_A */:\n                            case 135 /* MpegTsStreamType.EAC3_SYSTEM_A */:\n                            case 130 /* MpegTsStreamType.DTS */:\n                            case 138 /* MpegTsStreamType.DTS_ATSC */:\n                                {\n                                    let codec;\n                                    if (effectiveStreamType === 3 /* MpegTsStreamType.MP3_MPEG1 */\n                                        || effectiveStreamType === 4 /* MpegTsStreamType.MP3_MPEG2 */) {\n                                        codec = 'mp3';\n                                    }\n                                    else if (effectiveStreamType === 15 /* MpegTsStreamType.AAC */) {\n                                        codec = 'aac';\n                                    }\n                                    else if (effectiveStreamType === 129 /* MpegTsStreamType.AC3_SYSTEM_A */) {\n                                        codec = 'ac3';\n                                    }\n                                    else if (effectiveStreamType === 135 /* MpegTsStreamType.EAC3_SYSTEM_A */) {\n                                        codec = 'eac3';\n                                    }\n                                    else {\n                                        codec = 'dts';\n                                    }\n                                    info = {\n                                        type: 'audio',\n                                        codec,\n                                        decoderConfig: null,\n                                        aacCodecInfo: null,\n                                        dtsFormat: null,\n                                        numberOfChannels: -1,\n                                        sampleRate: -1,\n                                    };\n                                }\n                                ;\n                                break;\n                            case 6 /* MpegTsStreamType.PRIVATE_DATA */:\n                                {\n                                    if (hasEac3Descriptor) {\n                                        info = {\n                                            type: 'audio',\n                                            codec: 'eac3',\n                                            decoderConfig: null,\n                                            aacCodecInfo: null,\n                                            dtsFormat: null,\n                                            numberOfChannels: -1,\n                                            sampleRate: -1,\n                                        };\n                                    }\n                                    else if (hasAc3Descriptor) {\n                                        info = {\n                                            type: 'audio',\n                                            codec: 'ac3',\n                                            decoderConfig: null,\n                                            aacCodecInfo: null,\n                                            dtsFormat: null,\n                                            numberOfChannels: -1,\n                                            sampleRate: -1,\n                                        };\n                                    }\n                                    else if (hasDtsDescriptor) {\n                                        info = {\n                                            type: 'audio',\n                                            codec: 'dts',\n                                            decoderConfig: null,\n                                            aacCodecInfo: null,\n                                            dtsFormat: null,\n                                            numberOfChannels: -1,\n                                            sampleRate: -1,\n                                        };\n                                    }\n                                }\n                                ;\n                                break;\n                            default: {\n                                // If we don't recognize the codec, we don't surface the track at all. This is because\n                                // we can't determine its metadata and also have no idea how to packetize its data.\n                                if (!ignoredStreamTypes.has(streamType)) {\n                                    Logging._warn(`Note: MPEG-TS streams with stream_type 0x${streamType.toString(16)} are not`\n                                        + ` currently supported.`);\n                                    ignoredStreamTypes.add(streamType);\n                                }\n                            }\n                        }\n                        if (info) {\n                            this.elementaryStreams.push({\n                                demuxer: this,\n                                pid: elementaryPid,\n                                streamType,\n                                initialized: false,\n                                firstSection: null,\n                                canBeTrustedWithKeyPackets: false,\n                                info,\n                                referencePesPackets: [],\n                            });\n                        }\n                    }\n                    hasProgramMap = true;\n                }\n                else {\n                    const elementaryStream = this.elementaryStreams.find(x => x.pid === section.pid);\n                    outer: if (elementaryStream && !elementaryStream.initialized) {\n                        const pesPacket = readPesPacket(this, section, true);\n                        if (!pesPacket) {\n                            throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${elementaryStream.pid}`);\n                        }\n                        elementaryStream.firstSection = section;\n                        elementaryStream.canBeTrustedWithKeyPackets = section.randomAccessIndicator === 1;\n                        if (this.input._initInput) {\n                            const initDemuxer = (await this.input._initInput._getDemuxer());\n                            const matchingStream = initDemuxer.elementaryStreams.find(x => (x.pid === section.pid && x.info.codec === elementaryStream.info.codec && x.initialized));\n                            if (matchingStream) {\n                                elementaryStream.info = matchingStream.info;\n                                elementaryStream.initialized = true;\n                                break outer; // We have the stream info, we're done\n                            }\n                        }\n                        const context = new PacketReadingContext(elementaryStream, pesPacket);\n                        if (elementaryStream.info.type === 'video') {\n                            // We loop because in some files, the video parameters are not in the first packet\n                            while (true) {\n                                const contextAlias = context; // TyyyyypeScript 😩\n                                contextAlias.suppliedPacket = null;\n                                await context.markNextPacket();\n                                if (elementaryStream.info.codec === 'avc') {\n                                    if (!context.suppliedPacket) {\n                                        throw new Error('Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord'\n                                            + ' from any packet.');\n                                    }\n                                    elementaryStream.info.avcCodecInfo\n                                        = extractAvcDecoderConfigurationRecord(context.suppliedPacket.data);\n                                    if (!elementaryStream.info.avcCodecInfo) {\n                                        continue; // Search the next packet for it\n                                    }\n                                    const spsUnit = elementaryStream.info.avcCodecInfo.sequenceParameterSets[0];\n                                    assert(spsUnit);\n                                    const spsInfo = parseAvcSps(spsUnit);\n                                    elementaryStream.info.width = spsInfo.displayWidth;\n                                    elementaryStream.info.height = spsInfo.displayHeight;\n                                    const num = spsInfo.pixelAspectRatio.num;\n                                    const den = spsInfo.pixelAspectRatio.den;\n                                    elementaryStream.info.squarePixelWidth = elementaryStream.info.width;\n                                    elementaryStream.info.squarePixelHeight = elementaryStream.info.height;\n                                    if (num > 0 && den > 0) {\n                                        if (num > den) {\n                                            elementaryStream.info.squarePixelWidth = Math.round(elementaryStream.info.width * num / den);\n                                        }\n                                        else {\n                                            elementaryStream.info.squarePixelHeight = Math.round(elementaryStream.info.height * den / num);\n                                        }\n                                    }\n                                    elementaryStream.info.colorSpace = {\n                                        primaries: COLOR_PRIMARIES_MAP_INVERSE[spsInfo.colourPrimaries],\n                                        transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[spsInfo.transferCharacteristics],\n                                        matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[spsInfo.matrixCoefficients],\n                                        fullRange: !!spsInfo.fullRangeFlag,\n                                    };\n                                    elementaryStream.info.reorderSize = spsInfo.maxDecFrameBuffering;\n                                    break;\n                                }\n                                else if (elementaryStream.info.codec === 'hevc') {\n                                    if (!context.suppliedPacket) {\n                                        throw new Error('Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord'\n                                            + ' from first packet.');\n                                    }\n                                    elementaryStream.info.hevcCodecInfo\n                                        = extractHevcDecoderConfigurationRecord(context.suppliedPacket.data);\n                                    if (!elementaryStream.info.hevcCodecInfo) {\n                                        continue; // Search the next packet for it\n                                    }\n                                    const spsArray = elementaryStream.info.hevcCodecInfo.arrays.find(a => a.nalUnitType === HevcNalUnitType.SPS_NUT);\n                                    const spsUnit = spsArray.nalUnits[0];\n                                    assert(spsUnit);\n                                    const spsInfo = parseHevcSps(spsUnit);\n                                    elementaryStream.info.width = spsInfo.displayWidth;\n                                    elementaryStream.info.height = spsInfo.displayHeight;\n                                    const num = spsInfo.pixelAspectRatio.num;\n                                    const den = spsInfo.pixelAspectRatio.den;\n                                    elementaryStream.info.squarePixelWidth = elementaryStream.info.width;\n                                    elementaryStream.info.squarePixelHeight = elementaryStream.info.height;\n                                    if (num > 0 && den > 0) {\n                                        if (num > den) {\n                                            elementaryStream.info.squarePixelWidth = Math.round(elementaryStream.info.width * num / den);\n                                        }\n                                        else {\n                                            elementaryStream.info.squarePixelHeight = Math.round(elementaryStream.info.height * den / num);\n                                        }\n                                    }\n                                    elementaryStream.info.colorSpace = {\n                                        primaries: COLOR_PRIMARIES_MAP_INVERSE[spsInfo.colourPrimaries],\n                                        transfer: TRANSFER_CHARACTERISTICS_MAP_INVERSE[spsInfo.transferCharacteristics],\n                                        matrix: MATRIX_COEFFICIENTS_MAP_INVERSE[spsInfo.matrixCoefficients],\n                                        fullRange: !!spsInfo.fullRangeFlag,\n                                    };\n                                    elementaryStream.info.reorderSize = spsInfo.maxDecFrameBuffering;\n                                    break;\n                                }\n                                else {\n                                    throw new Error('Unhandled.');\n                                }\n                            }\n                            elementaryStream.info.decoderConfig = {\n                                codec: extractVideoCodecString({\n                                    width: elementaryStream.info.width,\n                                    height: elementaryStream.info.height,\n                                    codec: elementaryStream.info.codec,\n                                    codecDescription: null,\n                                    colorSpace: elementaryStream.info.colorSpace,\n                                    avcType: 1,\n                                    avcCodecInfo: elementaryStream.info.avcCodecInfo,\n                                    hevcCodecInfo: elementaryStream.info.hevcCodecInfo,\n                                    vp9CodecInfo: null,\n                                    av1CodecInfo: null,\n                                    proresFormat: null,\n                                }),\n                                codedWidth: elementaryStream.info.width,\n                                codedHeight: elementaryStream.info.height,\n                                colorSpace: elementaryStream.info.colorSpace,\n                            };\n                            if (elementaryStream.info.width !== elementaryStream.info.squarePixelWidth\n                                || elementaryStream.info.height !== elementaryStream.info.squarePixelHeight) {\n                                elementaryStream.info.decoderConfig.displayAspectWidth\n                                    = elementaryStream.info.squarePixelWidth;\n                                elementaryStream.info.decoderConfig.displayAspectHeight\n                                    = elementaryStream.info.squarePixelHeight;\n                            }\n                            elementaryStream.initialized = true;\n                        }\n                        else {\n                            await context.markNextPacket();\n                            if (!context.suppliedPacket) {\n                                throw new Error(`Couldn't parse first media packet for Elementary Stream with`\n                                    + ` PID ${elementaryStream.pid}`);\n                            }\n                            if (elementaryStream.info.codec === 'aac') {\n                                const slice = FileSlice.tempFromBytes(context.suppliedPacket.data);\n                                const header = readAdtsFrameHeader(slice);\n                                if (!header) {\n                                    throw new Error('Invalid AAC audio stream; could not read ADTS frame header from first packet.');\n                                }\n                                elementaryStream.info.aacCodecInfo = {\n                                    isMpeg2: false,\n                                    objectType: header.objectType,\n                                };\n                                elementaryStream.info.numberOfChannels\n                                    = aacChannelMap[header.channelConfiguration];\n                                elementaryStream.info.sampleRate\n                                    = aacFrequencyTable[header.samplingFrequencyIndex];\n                            }\n                            else if (elementaryStream.info.codec === 'mp3') {\n                                const word = readU32Be(FileSlice.tempFromBytes(context.suppliedPacket.data));\n                                const result = readMp3FrameHeader(word, context.suppliedPacket.data.byteLength);\n                                if (!result.header) {\n                                    throw new Error('Invalid MP3 audio stream; could not read frame header from first packet.');\n                                }\n                                elementaryStream.info.numberOfChannels = getMp3ChannelCount(result.header.channel);\n                                elementaryStream.info.sampleRate = result.header.sampleRate;\n                            }\n                            else if (elementaryStream.info.codec === 'ac3') {\n                                const frameInfo = parseAc3SyncFrame(context.suppliedPacket.data);\n                                if (!frameInfo) {\n                                    throw new Error('Invalid AC-3 audio stream; could not read sync frame from first packet.');\n                                }\n                                if (frameInfo.fscod === 3) {\n                                    throw new Error('Invalid AC-3 audio stream; reserved sample rate code found in first packet.');\n                                }\n                                elementaryStream.info.numberOfChannels\n                                    = AC3_ACMOD_CHANNEL_COUNTS[frameInfo.acmod] + frameInfo.lfeon;\n                                elementaryStream.info.sampleRate = AC3_SAMPLE_RATES[frameInfo.fscod];\n                            }\n                            else if (elementaryStream.info.codec === 'eac3') {\n                                const frameInfo = parseEac3SyncFrame(context.suppliedPacket.data);\n                                if (!frameInfo) {\n                                    throw new Error('Invalid E-AC-3 audio stream; could not read sync frame from first packet.');\n                                }\n                                const sampleRate = getEac3SampleRate(frameInfo);\n                                if (sampleRate === null) {\n                                    throw new Error('Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.');\n                                }\n                                elementaryStream.info.numberOfChannels = getEac3ChannelCount(frameInfo);\n                                elementaryStream.info.sampleRate = sampleRate;\n                            }\n                            else if (elementaryStream.info.codec === 'dts') {\n                                const frameInfo = parseDtsFrame(context.suppliedPacket.data);\n                                if (!frameInfo) {\n                                    throw new Error('Invalid DTS audio stream; could not read frame header from first packet.');\n                                }\n                                elementaryStream.info.numberOfChannels = frameInfo.numberOfChannels;\n                                elementaryStream.info.sampleRate = frameInfo.sampleRate;\n                                if (frameInfo.core) {\n                                    // Telling the two extension-only variants apart would need us to work out\n                                    // whether the asset holds XLL or LBR data, so we leave those unlabeled\n                                    elementaryStream.info.dtsFormat = frameInfo.hasExtensions ? 'dtsh' : 'dtsc';\n                                }\n                            }\n                            else {\n                                throw new Error('Unhandled.');\n                            }\n                            elementaryStream.info.decoderConfig = {\n                                codec: extractAudioCodecString({\n                                    codec: elementaryStream.info.codec,\n                                    codecDescription: null,\n                                    aacCodecInfo: elementaryStream.info.aacCodecInfo,\n                                    dtsFormat: elementaryStream.info.dtsFormat,\n                                }),\n                                numberOfChannels: elementaryStream.info.numberOfChannels,\n                                sampleRate: elementaryStream.info.sampleRate,\n                            };\n                            elementaryStream.initialized = true;\n                        }\n                    }\n                }\n                const isDone = hasProgramMap && this.elementaryStreams.every(x => x.initialized);\n                if (isDone) {\n                    break;\n                }\n                currentPos += this.packetStride;\n            }\n            if (!hasProgramMap) {\n                if (!hasProgramAssociationTable) {\n                    throw new Error('No Program Association Table found in the file.');\n                }\n                throw new Error('No Program Map Table found in the file.');\n            }\n            for (const stream of this.elementaryStreams) {\n                if (!stream.initialized) {\n                    // Stream was declared but no initialization data for it was found\n                    continue;\n                }\n                if (stream.info.type === 'video') {\n                    this.trackBackingEntries.push(new MpegTsVideoTrackBacking(stream));\n                }\n                else {\n                    this.trackBackingEntries.push(new MpegTsAudioTrackBacking(stream));\n                }\n            }\n        })();\n    }\n    async getTrackBackings() {\n        await this.readMetadata();\n        return this.trackBackingEntries;\n    }\n    async getMetadataTags() {\n        return {}; // Nothing for now\n    }\n    async getMimeType() {\n        await this.readMetadata();\n        const codecStrings = await Promise.all(this.trackBackingEntries.map(x => x.getDecoderConfig().then(c => c?.codec ?? null)));\n        return buildMpegTsMimeType(codecStrings);\n    }\n    async readSection(startPos, full, contiguous = false) {\n        let endPos = startPos;\n        let currentPos = startPos;\n        const chunks = [];\n        let chunksByteLength = 0;\n        let firstPacket = null;\n        let mustAddSectionEnd = true;\n        let randomAccessIndicator = 0;\n        while (true) {\n            const packet = await this.readPacket(currentPos);\n            currentPos += this.packetStride;\n            if (!packet) {\n                break;\n            }\n            if (!firstPacket) {\n                if (packet.payloadUnitStartIndicator === 0) {\n                    break;\n                }\n                firstPacket = packet;\n            }\n            else {\n                if (packet.pid !== firstPacket.pid) {\n                    if (contiguous) {\n                        break; // End of section\n                    }\n                    else {\n                        continue; // Ignore this packet\n                    }\n                }\n                if (packet.payloadUnitStartIndicator === 1) {\n                    break;\n                }\n            }\n            const hasAdaptationField = !!(packet.adaptationFieldControl & 0b10);\n            const hasPayload = !!(packet.adaptationFieldControl & 0b01);\n            let adaptationFieldLength = 0;\n            if (hasAdaptationField) {\n                adaptationFieldLength = 1 + packet.body[0];\n                // Extract random_access_indicator from first packet's adaptation field\n                if (packet === firstPacket && adaptationFieldLength > 1) {\n                    randomAccessIndicator = (packet.body[1] >> 6) & 1;\n                }\n            }\n            if (hasPayload) {\n                if (adaptationFieldLength === 0) {\n                    chunks.push(packet.body);\n                    chunksByteLength += packet.body.byteLength;\n                }\n                else {\n                    chunks.push(packet.body.subarray(adaptationFieldLength));\n                    chunksByteLength += packet.body.byteLength - adaptationFieldLength;\n                }\n            }\n            endPos = currentPos;\n            // 64 is just \"a bit of data\", enough for the PES packet header\n            if (!full && chunksByteLength >= 64) {\n                mustAddSectionEnd = false; // Not the actual section end\n                break;\n            }\n            // Check if we already know this is a section end\n            const isKnownSectionEnd = binarySearchExact(this.sectionEndPositions, endPos, x => x) !== -1;\n            if (isKnownSectionEnd) {\n                mustAddSectionEnd = false;\n                break;\n            }\n        }\n        if (mustAddSectionEnd) {\n            const index = binarySearchLessOrEqual(this.sectionEndPositions, endPos, x => x);\n            this.sectionEndPositions.splice(index + 1, 0, endPos);\n        }\n        if (!firstPacket) {\n            return null;\n        }\n        let merged;\n        if (chunks.length === 1) {\n            merged = chunks[0];\n        }\n        else {\n            const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n            merged = new Uint8Array(totalLength);\n            let offset = 0;\n            for (const chunk of chunks) {\n                merged.set(chunk, offset);\n                offset += chunk.length;\n            }\n        }\n        return {\n            startPos,\n            endPos: full ? endPos : null,\n            pid: firstPacket.pid,\n            payload: merged,\n            randomAccessIndicator,\n        };\n    }\n    async readPacketHeader(pos) {\n        let slice = this.reader.requestSlice(pos, 4);\n        if (isThenable(slice))\n            slice = await slice;\n        if (!slice) {\n            return null;\n        }\n        const syncByte = readU8(slice);\n        if (syncByte !== 0x47) {\n            throw new Error('Invalid TS packet sync byte; the file is likely corrupted.');\n        }\n        const nextTwoBytes = readU16Be(slice);\n        // eslint-disable-next-line @typescript-eslint/no-unused-vars\n        const transportErrorIndicator = nextTwoBytes >> 15;\n        const payloadUnitStartIndicator = (nextTwoBytes >> 14) & 0x1;\n        // eslint-disable-next-line @typescript-eslint/no-unused-vars\n        const transportPriority = (nextTwoBytes >> 13) & 0x1;\n        const pid = nextTwoBytes & 0x1FFF;\n        const nextByte = readU8(slice);\n        // eslint-disable-next-line @typescript-eslint/no-unused-vars\n        const transportScramblingControl = nextByte >> 6;\n        const adaptationFieldControl = (nextByte >> 4) & 0x3;\n        // eslint-disable-next-line @typescript-eslint/no-unused-vars\n        const continuityCounter = nextByte & 0xF;\n        return {\n            payloadUnitStartIndicator,\n            pid,\n            adaptationFieldControl,\n        };\n    }\n    async readPacket(pos) {\n        // Code in here is duplicated from readPacketHeader for performance reasons\n        let slice = this.reader.requestSlice(pos, TS_PACKET_SIZE);\n        if (isThenable(slice))\n            slice = await slice;\n        if (!slice) {\n            return null;\n        }\n        const bytes = readBytes(slice, TS_PACKET_SIZE);\n        const syncByte = bytes[0];\n        if (syncByte !== 0x47) {\n            throw new Error('Invalid TS packet sync byte; the file is likely corrupted.');\n        }\n        const nextTwoBytes = (bytes[1] << 8) + bytes[2];\n        // eslint-disable-next-line @typescript-eslint/no-unused-vars\n        const transportErrorIndicator = nextTwoBytes >> 15;\n        const payloadUnitStartIndicator = (nextTwoBytes >> 14) & 0x1;\n        // eslint-disable-next-line @typescript-eslint/no-unused-vars\n        const transportPriority = (nextTwoBytes >> 13) & 0x1;\n        const pid = nextTwoBytes & 0x1FFF;\n        const nextByte = bytes[3];\n        // eslint-disable-next-line @typescript-eslint/no-unused-vars\n        const transportScramblingControl = nextByte >> 6;\n        const adaptationFieldControl = (nextByte >> 4) & 0x3;\n        // eslint-disable-next-line @typescript-eslint/no-unused-vars\n        const continuityCounter = nextByte & 0xF;\n        return {\n            payloadUnitStartIndicator,\n            pid,\n            adaptationFieldControl,\n            body: bytes.subarray(4),\n        };\n    }\n    normalizeTimestamp(timestamp) {\n        if (!this.timestampWrapInfo) {\n            // No info yet, let's initialize it anchored on this timestamp. Since we process packets sequentially when\n            // extracting metadata, this means we'll anchor to the first PTS in the file.\n            const tolerance = 60 * TIMESCALE;\n            this.timestampWrapInfo = {\n                reference: timestamp - tolerance,\n                offset: timestamp >= TIMESTAMP_MODULUS - tolerance\n                    ? -TIMESTAMP_MODULUS // Timestamps close to the modulus are treated as negative\n                    : TIMESTAMP_MODULUS,\n            };\n        }\n        const { reference, offset } = this.timestampWrapInfo;\n        if ((offset < 0 && timestamp >= reference)\n            || (offset > 0 && timestamp < reference)) {\n            return timestamp + offset;\n        }\n        return timestamp;\n    }\n}\nconst readPesPacketHeader = (demuxer, section, expectPts) => {\n    if (section.payload.byteLength < 3) {\n        return null;\n    }\n    const bitstream = new Bitstream(section.payload);\n    const startCodePrefix = bitstream.readBits(24);\n    if (startCodePrefix !== 0x000001) {\n        return null;\n    }\n    const streamId = bitstream.readBits(8);\n    bitstream.skipBits(16);\n    if (streamId === 0b10111100 // program_stream_map\n        || streamId === 0b10111110 // padding_stream\n        || streamId === 0b10111111 // private_stream_2\n        || streamId === 0b11110000 // ECM\n        || streamId === 0b11110001 // EMM\n        || streamId === 0b11111111 // program_stream_directory\n        || streamId === 0b11110010 // DSMCC_stream\n        || streamId === 0b11111000 // ITU-T Rec. H.222.1 type E stream\n    ) {\n        return null;\n    }\n    bitstream.skipBits(8);\n    const ptsDtsFlags = bitstream.readBits(2);\n    bitstream.skipBits(14);\n    let pts = null;\n    if (ptsDtsFlags === 0b10 || ptsDtsFlags === 0b11) {\n        pts = 0;\n        bitstream.skipBits(4);\n        pts += bitstream.readBits(3) * (1 << 30);\n        bitstream.skipBits(1);\n        pts += bitstream.readBits(15) * (1 << 15);\n        bitstream.skipBits(1);\n        pts += bitstream.readBits(15);\n        pts = demuxer.normalizeTimestamp(pts);\n    }\n    else {\n        if (expectPts) {\n            throw new Error(MISSING_PTS_ERROR_MESSAGE);\n        }\n    }\n    return {\n        sectionStartPos: section.startPos,\n        sectionEndPos: section.endPos,\n        pts,\n        randomAccessIndicator: section.randomAccessIndicator,\n    };\n};\nconst readPesPacket = (demuxer, section, expectPts) => {\n    assert(section.endPos !== null); // Can only read full PES packets from fully read sections\n    const header = readPesPacketHeader(demuxer, section, expectPts);\n    if (!header) {\n        return null;\n    }\n    const bitstream = new Bitstream(section.payload);\n    bitstream.skipBits(32);\n    const pesPacketLength = bitstream.readBits(16);\n    const BYTES_UNTIL_END_OF_PES_PACKET_LENGTH = 6;\n    bitstream.skipBits(16);\n    const pesHeaderDataLength = bitstream.readBits(8);\n    const pesHeaderEndPos = bitstream.pos + 8 * pesHeaderDataLength;\n    bitstream.pos = pesHeaderEndPos;\n    const bytePos = pesHeaderEndPos / 8;\n    assert(Number.isInteger(bytePos));\n    const data = section.payload.subarray(bytePos, \n    // \"A value of 0 indicates that the PES packet length is neither specified nor bounded and is allowed only in\n    // PES packets whose payload consists of bytes from a video elementary stream contained in\n    // transport stream packets.\"\n    pesPacketLength > 0\n        ? BYTES_UNTIL_END_OF_PES_PACKET_LENGTH + pesPacketLength\n        : section.payload.byteLength);\n    return {\n        ...header,\n        data,\n    };\n};\nclass MpegTsTrackBacking {\n    constructor(elementaryStream) {\n        this.elementaryStream = elementaryStream;\n        this.packetBuffers = new WeakMap();\n        /** Used for recreating PacketBuffers if necessary. */\n        this.packetSectionStarts = new WeakMap();\n    }\n    getId() {\n        return this.elementaryStream.pid;\n    }\n    getNumber() {\n        const demuxer = this.elementaryStream.demuxer;\n        const trackType = this.elementaryStream.info.type;\n        let number = 0;\n        for (const backing of demuxer.trackBackingEntries) {\n            if (backing.getType() === trackType) {\n                number++;\n            }\n            assert(backing instanceof MpegTsTrackBacking);\n            if (backing.elementaryStream === this.elementaryStream) {\n                break;\n            }\n        }\n        return number;\n    }\n    getCodec() {\n        throw new Error('Not implemented on base class.');\n    }\n    getInternalCodecId() {\n        return this.elementaryStream.streamType;\n    }\n    getName() {\n        return null;\n    }\n    getLanguageCode() {\n        return UNDETERMINED_LANGUAGE;\n    }\n    getDisposition() {\n        return {\n            ...DEFAULT_TRACK_DISPOSITION,\n            primary: false,\n        };\n    }\n    getTimeResolution() {\n        return TIMESCALE;\n    }\n    isRelativeToUnixEpoch() {\n        return false;\n    }\n    getUnixTimeForTimestamp() {\n        return null;\n    }\n    getPairingMask() {\n        return 1n;\n    }\n    getBitrate() {\n        return null;\n    }\n    getAverageBitrate() {\n        return null;\n    }\n    async getDurationFromMetadata() {\n        return null;\n    }\n    async getLiveRefreshInterval() {\n        return null;\n    }\n    createEncodedPacket(suppliedPacket, duration, options) {\n        let packetType;\n        if (this.allPacketsAreKeyPackets()) {\n            packetType = 'key';\n        }\n        else {\n            packetType = suppliedPacket.randomAccessIndicator === 1\n                ? 'key'\n                : 'delta';\n        }\n        return new EncodedPacket(options.metadataOnly ? PLACEHOLDER_DATA : suppliedPacket.data, packetType, suppliedPacket.pts / TIMESCALE, Math.max(duration / TIMESCALE, 0), suppliedPacket.sequenceNumber, suppliedPacket.data.byteLength);\n    }\n    async getFirstPacket(options) {\n        const section = this.elementaryStream.firstSection;\n        assert(section);\n        const pesPacket = readPesPacket(this.elementaryStream.demuxer, section, true);\n        assert(pesPacket);\n        const context = new PacketReadingContext(this.elementaryStream, pesPacket);\n        const buffer = new PacketBuffer(this, context);\n        const result = await buffer.readNext();\n        if (!result) {\n            return null;\n        }\n        const packet = this.createEncodedPacket(result.packet, result.duration, options);\n        this.packetBuffers.set(packet, buffer);\n        this.packetSectionStarts.set(packet, result.packet.sectionStartPos);\n        return packet;\n    }\n    async getNextPacket(packet, options) {\n        let buffer = this.packetBuffers.get(packet);\n        if (buffer) {\n            // Fast path\n            const result = await buffer.readNext();\n            if (!result) {\n                return null;\n            }\n            // Remove PacketBuffer access from the old packet, it belongs to the next packet now\n            this.packetBuffers.delete(packet);\n            const newPacket = this.createEncodedPacket(result.packet, result.duration, options);\n            this.packetBuffers.set(newPacket, buffer);\n            this.packetSectionStarts.set(newPacket, result.packet.sectionStartPos);\n            return newPacket;\n        }\n        // No buffer, we gotta do some rereading\n        const sectionStartPos = this.packetSectionStarts.get(packet);\n        if (sectionStartPos === undefined) {\n            throw new Error('Packet was not created from this track.');\n        }\n        const demuxer = this.elementaryStream.demuxer;\n        const section = await demuxer.readSection(sectionStartPos, true);\n        assert(section);\n        const pesPacket = readPesPacket(demuxer, section, true);\n        assert(pesPacket);\n        const context = new PacketReadingContext(this.elementaryStream, pesPacket);\n        buffer = new PacketBuffer(this, context);\n        // Advance until we pass the current packet's sequence number\n        const targetSequenceNumber = packet.sequenceNumber;\n        while (true) {\n            const result = await buffer.readNext();\n            if (!result) {\n                return null;\n            }\n            if (result.packet.sequenceNumber > targetSequenceNumber) {\n                // We found the next packet!\n                const newPacket = this.createEncodedPacket(result.packet, result.duration, options);\n                this.packetBuffers.set(newPacket, buffer);\n                this.packetSectionStarts.set(newPacket, result.packet.sectionStartPos);\n                return newPacket;\n            }\n        }\n    }\n    async getNextKeyPacket(packet, options) {\n        let currentPacket = packet;\n        // Just loop until we hit one\n        while (true) {\n            currentPacket = await this.getNextPacket(currentPacket, options);\n            if (!currentPacket) {\n                return null;\n            }\n            if (currentPacket.type === 'key') {\n                return currentPacket;\n            }\n        }\n    }\n    getPacket(timestamp, options) {\n        return this.doPacketLookup(timestamp, false, options);\n    }\n    getKeyPacket(timestamp, options) {\n        return this.doPacketLookup(timestamp, true, options);\n    }\n    /**\n     * Searches for the packet with the largest timestamp not larger than `timestamp` in the file, using a combination\n     * of chunk-based binary search and linear refinement. The reason the coarse search is done in large chunks is to\n     * make it more performant for small files and over high-latency readers such as the network.\n     */\n    async doPacketLookup(timestamp, keyframesOnly, options) {\n        const searchPts = roundIfAlmostInteger(timestamp * TIMESCALE);\n        const demuxer = this.elementaryStream.demuxer;\n        const { reader, seekChunkSize } = demuxer;\n        const pid = this.elementaryStream.pid;\n        const findFirstPesPacketHeaderInChunk = async (startPos, endPos, readSectionInFull) => {\n            let currentPos = startPos;\n            while (currentPos < endPos) {\n                const packetHeader = await demuxer.readPacketHeader(currentPos);\n                if (!packetHeader) {\n                    return null;\n                }\n                if (packetHeader.pid === pid && packetHeader.payloadUnitStartIndicator === 1) {\n                    const section = await demuxer.readSection(currentPos, readSectionInFull);\n                    if (!section) {\n                        return null;\n                    }\n                    const pesPacketHeader = readPesPacketHeader(demuxer, section, false);\n                    if (pesPacketHeader && pesPacketHeader.pts !== null) {\n                        return {\n                            pesPacketHeader: pesPacketHeader,\n                            section,\n                        };\n                    }\n                }\n                currentPos += demuxer.packetStride;\n            }\n            return null;\n        };\n        // Get the first PES packet of the track\n        const firstSection = this.elementaryStream.firstSection;\n        assert(firstSection);\n        const firstPesPacketHeader = readPesPacketHeader(demuxer, firstSection, true);\n        assert(firstPesPacketHeader);\n        if (searchPts < firstPesPacketHeader.pts) {\n            // We're before the first packet, definitely nothing here\n            return null;\n        }\n        let scanStartPos;\n        const referencePesPackets = this.elementaryStream.referencePesPackets;\n        const referencePointIndex = binarySearchLessOrEqual(referencePesPackets, searchPts, x => x.pts);\n        const referencePoint = referencePointIndex !== -1 ? referencePesPackets[referencePointIndex] : null;\n        if (referencePoint && searchPts - referencePoint.pts < TIMESCALE / 2) {\n            // Reference point ain't too far away, prefer it over the chunk search\n            scanStartPos = referencePoint.sectionStartPos;\n        }\n        else {\n            let startChunkIndex = 0;\n            if (reader.fileSize !== null) {\n                const numChunks = Math.ceil(reader.fileSize / seekChunkSize);\n                if (numChunks > 1) {\n                    // Binary search to find the chunk with highest index whose first PES has pts <= searchPts\n                    let low = 0;\n                    let high = numChunks - 1;\n                    startChunkIndex = low;\n                    while (low <= high) {\n                        const mid = Math.floor((low + high) / 2);\n                        const chunkStartPos = floorToMultiple(mid * seekChunkSize, demuxer.packetStride)\n                            + firstPesPacketHeader.sectionStartPos;\n                        const chunkEndPos = chunkStartPos + seekChunkSize;\n                        const result = await findFirstPesPacketHeaderInChunk(chunkStartPos, chunkEndPos, false);\n                        if (!result) {\n                            // No PES packet found in this chunk, search left\n                            high = mid - 1;\n                            continue;\n                        }\n                        if (result.pesPacketHeader.pts <= searchPts) {\n                            // This chunk's first PES is <= searchPts, it's a candidate\n                            startChunkIndex = mid;\n                            low = mid + 1; // Search right\n                        }\n                        else {\n                            // Search left\n                            high = mid - 1;\n                        }\n                    }\n                }\n            }\n            scanStartPos = floorToMultiple(startChunkIndex * seekChunkSize, demuxer.packetStride) + firstPesPacketHeader.sectionStartPos;\n        }\n        // Find the first PES packet at or after scanStartPos\n        const result = await findFirstPesPacketHeaderInChunk(scanStartPos, reader.fileSize ?? Infinity, false);\n        let currentPesHeader = result?.pesPacketHeader ?? null;\n        if (!currentPesHeader) {\n            // Fall back to first packet\n            currentPesHeader = firstPesPacketHeader;\n        }\n        const reorderSize = this.getReorderSize();\n        const retrieveEncodedPacket = async (sectionStartPos, predicate) => {\n            // Load the relevant section in full\n            const section = await demuxer.readSection(sectionStartPos, true);\n            assert(section);\n            const pesPacket = readPesPacket(demuxer, section, true);\n            assert(pesPacket);\n            const context = new PacketReadingContext(this.elementaryStream, pesPacket);\n            const buffer = new PacketBuffer(this, context);\n            // Advance until the top-most presentation timestamp crosses or equals searchPts\n            while (true) {\n                const topPts = last(buffer.presentationOrderPackets)?.pts ?? -Infinity;\n                if (topPts >= searchPts) {\n                    break;\n                }\n                const didRead = await buffer.readNextPacket();\n                if (!didRead) {\n                    break;\n                }\n            }\n            const targetIndex = findLastIndex(buffer.presentationOrderPackets, predicate);\n            if (targetIndex === -1) {\n                return null;\n            }\n            const targetPacket = buffer.presentationOrderPackets[targetIndex];\n            const lastDuration = targetIndex === 0\n                ? 0\n                : targetPacket.pts - buffer.presentationOrderPackets[targetIndex - 1].pts;\n            // Pop packets in decode order until we hit the target packet\n            buffer.decodeOrderPackets.splice(0, buffer.decodeOrderPackets.indexOf(targetPacket));\n            buffer.lastDuration = lastDuration; // Kinda ugly but necessary fix\n            const result = await buffer.readNext();\n            assert(result);\n            const packet = this.createEncodedPacket(result.packet, result.duration, options);\n            this.packetBuffers.set(packet, buffer);\n            this.packetSectionStarts.set(packet, result.packet.sectionStartPos);\n            return packet;\n        };\n        if (!keyframesOnly || this.allPacketsAreKeyPackets()) {\n            // Normat packet lookup case. Slightly easier since we just need to search (mostly) forward to find the\n            // packet.\n            // Linear scan to find the PES packet with largest pts <= searchPts. This will be used as the \"midpoint\"\n            // of the next refinement step (which is needed because of B-frames).\n            outer: while (true) {\n                let currentPos = currentPesHeader.sectionStartPos + demuxer.packetStride;\n                while (true) {\n                    const packetHeader = await demuxer.readPacketHeader(currentPos);\n                    if (!packetHeader) {\n                        break outer; // End of file\n                    }\n                    if (packetHeader.pid === pid && packetHeader.payloadUnitStartIndicator === 1) {\n                        const section = await demuxer.readSection(currentPos, false);\n                        if (section) {\n                            const nextPesHeader = readPesPacketHeader(demuxer, section, false);\n                            if (nextPesHeader && nextPesHeader.pts !== null) {\n                                if (nextPesHeader.pts > searchPts) {\n                                    break outer;\n                                }\n                                currentPesHeader = nextPesHeader;\n                                maybeInsertReferencePacket(this.elementaryStream, currentPesHeader);\n                                break;\n                            }\n                        }\n                    }\n                    currentPos += demuxer.packetStride;\n                }\n            }\n            // Rewind by reorderSize + 1 PES packets (even for audio! To ensure proper durations)\n            outer: for (let i = 0; i < reorderSize + 1; i++) {\n                let pos = currentPesHeader.sectionStartPos - demuxer.packetStride;\n                while (pos >= demuxer.packetOffset) {\n                    const packetHeader = await demuxer.readPacketHeader(pos);\n                    if (!packetHeader) {\n                        break outer;\n                    }\n                    if (packetHeader.pid === pid && packetHeader.payloadUnitStartIndicator === 1) {\n                        const section = await demuxer.readSection(pos, false);\n                        if (section) {\n                            const header = readPesPacketHeader(demuxer, section, false);\n                            if (header && header.pts !== null) {\n                                currentPesHeader = header;\n                                break;\n                            }\n                        }\n                    }\n                    pos -= demuxer.packetStride;\n                }\n                if (pos < demuxer.packetOffset) {\n                    break; // We've hit the start of the file, there's nothing more to rewind\n                }\n            }\n            return retrieveEncodedPacket(currentPesHeader.sectionStartPos, p => p.pts <= searchPts);\n        }\n        else {\n            // Key packet lookup case. Slightly harder since the starting chunk may not have a key packet at all, which\n            // means we might need to search the previous chunks until we find something.\n            let currentChunkStartPos = scanStartPos;\n            let nextChunkStartPos = null; // \"next\" as in later in the file, even tho we scan backwards\n            const readSectionsInFull = !this.elementaryStream.canBeTrustedWithKeyPackets;\n            while (true) {\n                let bestKeyPesHeader = null;\n                const isFirstChunk = currentChunkStartPos <= firstPesPacketHeader.sectionStartPos;\n                let pesHeader;\n                let pesHeaderSection = null;\n                if (isFirstChunk) {\n                    pesHeader = firstPesPacketHeader;\n                    pesHeaderSection = firstSection;\n                }\n                else {\n                    const result = await findFirstPesPacketHeaderInChunk(currentChunkStartPos, nextChunkStartPos ?? reader.fileSize ?? Infinity, readSectionsInFull);\n                    pesHeader = result?.pesPacketHeader ?? null;\n                    pesHeaderSection = result?.section ?? null;\n                }\n                let passedSearchPts = false;\n                let lookaheadCount = 0;\n                let context = null; // Walks the chunk's packets in order\n                outer: while (pesHeader) {\n                    if (nextChunkStartPos !== null && pesHeader.sectionStartPos >= nextChunkStartPos) {\n                        // Stop at the next chunk boundary\n                        break;\n                    }\n                    if (pesHeader.pts <= searchPts) {\n                        let isKeyPacket;\n                        if (this.elementaryStream.canBeTrustedWithKeyPackets) {\n                            isKeyPacket = pesHeader.randomAccessIndicator === 1;\n                        }\n                        else {\n                            if (!context) {\n                                assert(pesHeaderSection);\n                                const pesPacket = readPesPacket(demuxer, pesHeaderSection, true);\n                                assert(pesPacket);\n                                context = new PacketReadingContext(this.elementaryStream, pesPacket);\n                            }\n                            // Advance to the first packet that starts in this PES packet\n                            while (!context.suppliedPacket\n                                || context.suppliedPacket.sectionStartPos < pesHeader.sectionStartPos) {\n                                context.suppliedPacket = null;\n                                await context.markNextPacket();\n                                if (!context.suppliedPacket) {\n                                    break;\n                                }\n                            }\n                            isKeyPacket = context.suppliedPacket?.sectionStartPos === pesHeader.sectionStartPos\n                                && context.suppliedPacket.randomAccessIndicator === 1;\n                        }\n                        if (isKeyPacket) {\n                            bestKeyPesHeader = pesHeader;\n                        }\n                    }\n                    if (pesHeader.pts > searchPts) {\n                        passedSearchPts = true;\n                    }\n                    // If we've passed searchPts, do lookahead for reorderSize more packets just to be sure\n                    if (passedSearchPts) {\n                        lookaheadCount++;\n                        if (lookaheadCount > reorderSize) {\n                            break;\n                        }\n                    }\n                    // Find next PES packet\n                    let currentPos = pesHeader.sectionStartPos + demuxer.packetStride;\n                    while (true) {\n                        const packetHeader = await demuxer.readPacketHeader(currentPos);\n                        if (!packetHeader) {\n                            break outer; // End of file\n                        }\n                        if (packetHeader.pid === pid && packetHeader.payloadUnitStartIndicator === 1) {\n                            const section = await demuxer.readSection(currentPos, readSectionsInFull);\n                            if (section) {\n                                const nextPesHeader = readPesPacketHeader(demuxer, section, false);\n                                if (nextPesHeader && nextPesHeader.pts !== null) {\n                                    pesHeader = nextPesHeader;\n                                    pesHeaderSection = section;\n                                    maybeInsertReferencePacket(this.elementaryStream, pesHeader);\n                                    break;\n                                }\n                            }\n                        }\n                        currentPos += demuxer.packetStride;\n                    }\n                }\n                if (bestKeyPesHeader) {\n                    let startPesHeader = bestKeyPesHeader;\n                    if (lookaheadCount === 0) {\n                        // Packet is at the end of stream, let's rewind a little to obtain the correct packet duration\n                        outer: for (let i = 0; i < reorderSize; i++) {\n                            let pos = startPesHeader.sectionStartPos - demuxer.packetStride;\n                            while (pos >= demuxer.packetOffset) {\n                                const packetHeader = await demuxer.readPacketHeader(pos);\n                                if (!packetHeader) {\n                                    break outer;\n                                }\n                                if (packetHeader.pid === pid && packetHeader.payloadUnitStartIndicator === 1) {\n                                    const section = await demuxer.readSection(pos, readSectionsInFull);\n                                    if (section) {\n                                        const header = readPesPacketHeader(demuxer, section, false);\n                                        if (header && header.pts !== null) {\n                                            startPesHeader = header;\n                                            break;\n                                        }\n                                    }\n                                }\n                                pos -= demuxer.packetStride;\n                            }\n                            if (pos < demuxer.packetOffset) {\n                                break; // We've hit the start of the file, there's nothing more to rewind\n                            }\n                        }\n                    }\n                    const encodedPacket = await retrieveEncodedPacket(startPesHeader.sectionStartPos, p => p.pts <= searchPts && p.randomAccessIndicator === 1);\n                    if (encodedPacket) {\n                        return encodedPacket;\n                    }\n                    else {\n                        // The key packet didn't materialize (can happen with odd packetization where packets take their\n                        // timestamp from a later PES packet), so let's keep looking further back\n                    }\n                }\n                if (isFirstChunk) {\n                    return null;\n                }\n                // No key frame found in this chunk, move one chunk to the left\n                nextChunkStartPos = currentChunkStartPos;\n                currentChunkStartPos = Math.max(floorToMultiple(currentChunkStartPos - firstPesPacketHeader.sectionStartPos - seekChunkSize, demuxer.packetStride) + firstPesPacketHeader.sectionStartPos, firstPesPacketHeader.sectionStartPos);\n            }\n        }\n    }\n}\nclass MpegTsVideoTrackBacking extends MpegTsTrackBacking {\n    getType() {\n        return 'video';\n    }\n    getCodec() {\n        return this.elementaryStream.info.codec;\n    }\n    getCodedWidth() {\n        return this.elementaryStream.info.width;\n    }\n    getCodedHeight() {\n        return this.elementaryStream.info.height;\n    }\n    getSquarePixelWidth() {\n        return this.elementaryStream.info.squarePixelWidth;\n    }\n    getSquarePixelHeight() {\n        return this.elementaryStream.info.squarePixelHeight;\n    }\n    getTransformationMatrix() {\n        return [...IDENTITY_MATRIX];\n    }\n    async getColorSpace() {\n        return this.elementaryStream.info.colorSpace;\n    }\n    async canBeTransparent() {\n        return false;\n    }\n    async getDecoderConfig() {\n        assert(this.elementaryStream.info.decoderConfig);\n        return this.elementaryStream.info.decoderConfig;\n    }\n    allPacketsAreKeyPackets() {\n        return false;\n    }\n    getReorderSize() {\n        return this.elementaryStream.info.reorderSize;\n    }\n}\nclass MpegTsAudioTrackBacking extends MpegTsTrackBacking {\n    getType() {\n        return 'audio';\n    }\n    getCodec() {\n        return this.elementaryStream.info.codec;\n    }\n    getNumberOfChannels() {\n        return this.elementaryStream.info.numberOfChannels;\n    }\n    getSampleRate() {\n        return this.elementaryStream.info.sampleRate;\n    }\n    async getDecoderConfig() {\n        assert(this.elementaryStream.info.decoderConfig);\n        return this.elementaryStream.info.decoderConfig;\n    }\n    allPacketsAreKeyPackets() {\n        return true;\n    }\n    getReorderSize() {\n        return 0; // No reordering, since no B-frames because goated\n    }\n}\nconst maybeInsertReferencePacket = (elementaryStream, pesPacketHeader) => {\n    const referencePesPackets = elementaryStream.referencePesPackets;\n    const index = binarySearchLessOrEqual(referencePesPackets, pesPacketHeader.sectionStartPos, x => x.sectionStartPos);\n    if (index >= 0) {\n        // Since pts and file position don't necessarily have a monotonic relationship (since pts can go crazy),\n        // let's see if inserting at the given index would violate the pts order. If so, return.\n        const entry = referencePesPackets[index];\n        if (pesPacketHeader.pts <= entry.pts) {\n            return false;\n        }\n        const minByteDistance = elementaryStream.demuxer.minReferencePointByteDistance;\n        if (pesPacketHeader.sectionStartPos - entry.sectionStartPos < minByteDistance) {\n            // Too close\n            return false;\n        }\n        if (index < referencePesPackets.length - 1) {\n            const nextEntry = referencePesPackets[index + 1];\n            if (nextEntry.pts < pesPacketHeader.pts) {\n                // Out of order\n                return false;\n            }\n            if (nextEntry.sectionStartPos - pesPacketHeader.sectionStartPos < minByteDistance) {\n                // Too close\n                return false;\n            }\n        }\n    }\n    referencePesPackets.splice(index + 1, 0, pesPacketHeader);\n    return true;\n};\n/** Stateful context used to extract exact encoded packets from the underlying data stream. */\nclass PacketReadingContext {\n    constructor(elementaryStream, startingPesPacket) {\n        this.currentPos = 0; // Relative to the data in startingPesPacket\n        this.pesPackets = [];\n        this.currentPesPacketIndex = 0;\n        this.currentPesPacketPos = 0;\n        this.endPos = 0;\n        this.lastSuppliedPesPacket = null;\n        this.nextPts = null;\n        this.suppliedPacket = null;\n        this.elementaryStream = elementaryStream;\n        this.pid = elementaryStream.pid;\n        this.demuxer = elementaryStream.demuxer;\n        this.startingPesPacket = startingPesPacket;\n    }\n    ensureBuffered(length) {\n        const remaining = this.endPos - this.currentPos;\n        if (remaining >= length) {\n            return length;\n        }\n        return this.bufferData(length - remaining)\n            .then(() => Math.min(this.endPos - this.currentPos, length));\n    }\n    getCurrentPesPacket() {\n        const packet = this.pesPackets[this.currentPesPacketIndex];\n        assert(packet);\n        return packet;\n    }\n    async bufferData(length) {\n        const targetEndPos = this.endPos + length;\n        while (this.endPos < targetEndPos) {\n            let pesPacket;\n            if (this.pesPackets.length === 0) {\n                pesPacket = this.startingPesPacket;\n            }\n            else {\n                // Find the next PES packet\n                let currentPos = last(this.pesPackets).sectionEndPos;\n                assert(currentPos !== null);\n                while (true) {\n                    const packetHeader = await this.demuxer.readPacketHeader(currentPos);\n                    if (!packetHeader) {\n                        return;\n                    }\n                    if (packetHeader.pid === this.pid) {\n                        const nextSection = await this.demuxer.readSection(currentPos, true);\n                        if (!nextSection) {\n                            return;\n                        }\n                        const nextPesPacket = readPesPacket(this.demuxer, nextSection, false);\n                        if (nextPesPacket) {\n                            pesPacket = nextPesPacket;\n                            break;\n                        }\n                    }\n                    currentPos += this.demuxer.packetStride;\n                }\n            }\n            this.pesPackets.push(pesPacket);\n            this.endPos += pesPacket.data.byteLength;\n        }\n    }\n    readBytes(length) {\n        const currentPesPacket = this.getCurrentPesPacket();\n        const relativeStartOffset = this.currentPos - this.currentPesPacketPos;\n        const relativeEndOffset = relativeStartOffset + length;\n        this.currentPos += length;\n        if (relativeEndOffset <= currentPesPacket.data.byteLength) {\n            // Request can be satisfied with one PES packet\n            return currentPesPacket.data.subarray(relativeStartOffset, relativeEndOffset);\n        }\n        // Data spans multiple PES packets, we must do some merging\n        const result = new Uint8Array(length);\n        result.set(currentPesPacket.data.subarray(relativeStartOffset));\n        let offset = currentPesPacket.data.byteLength - relativeStartOffset;\n        while (true) {\n            this.advanceCurrentPacket();\n            const currentPesPacket = this.getCurrentPesPacket();\n            const relativeEndOffset = length - offset;\n            if (relativeEndOffset <= currentPesPacket.data.byteLength) {\n                result.set(currentPesPacket.data.subarray(0, relativeEndOffset), offset);\n                break;\n            }\n            result.set(currentPesPacket.data, offset);\n            offset += currentPesPacket.data.byteLength;\n        }\n        return result;\n    }\n    readU8() {\n        let currentPesPacket = this.getCurrentPesPacket();\n        const relativeOffset = this.currentPos - this.currentPesPacketPos;\n        this.currentPos++;\n        if (relativeOffset < currentPesPacket.data.byteLength) {\n            return currentPesPacket.data[relativeOffset];\n        }\n        // Skip over PES packets without any data\n        do {\n            this.advanceCurrentPacket();\n            currentPesPacket = this.getCurrentPesPacket();\n        } while (currentPesPacket.data.byteLength === 0);\n        return currentPesPacket.data[0];\n    }\n    seekTo(pos) {\n        if (pos === this.currentPos) {\n            return;\n        }\n        if (pos < this.currentPos) {\n            while (pos < this.currentPesPacketPos) {\n                // Move to the previous PES packet\n                this.currentPesPacketIndex--;\n                const currentPacket = this.getCurrentPesPacket();\n                this.currentPesPacketPos -= currentPacket.data.byteLength;\n            }\n        }\n        else {\n            while (true) {\n                // Move to the next PES packet\n                const currentPesPacket = this.getCurrentPesPacket();\n                const currentEndPos = this.currentPesPacketPos + currentPesPacket.data.byteLength;\n                if (pos < currentEndPos) {\n                    break;\n                }\n                this.currentPesPacketPos += currentPesPacket.data.byteLength;\n                this.currentPesPacketIndex++;\n            }\n        }\n        this.currentPos = pos;\n    }\n    skip(n) {\n        this.seekTo(this.currentPos + n);\n    }\n    advanceCurrentPacket() {\n        this.currentPesPacketPos += this.getCurrentPesPacket().data.byteLength;\n        this.currentPesPacketIndex++;\n    }\n    async markNextPacket() {\n        assert(!this.suppliedPacket);\n        const elementaryStream = this.elementaryStream;\n        if (elementaryStream.info.type === 'video') {\n            // Our job here is to separate the video stream into access units. Sometimes this is easy (like when AUDs\n            // are present), sometimes it's a little harder.\n            const codec = elementaryStream.info.codec;\n            const CHUNK_SIZE = 1024;\n            if (codec !== 'avc' && codec !== 'hevc') {\n                throw new Error('Unhandled.');\n            }\n            const nalHeaderSize = codec === 'avc' ? 1 : 2;\n            let packetStartPos = null;\n            let frameStartFound = false;\n            let lastFirstMacroblockInSlice = 0;\n            while (true) {\n                let remaining = this.ensureBuffered(CHUNK_SIZE);\n                if (isThenable(remaining))\n                    remaining = await remaining;\n                if (remaining === 0) {\n                    break;\n                }\n                const chunkStartPos = this.currentPos;\n                const chunk = this.readBytes(remaining);\n                const length = chunk.byteLength;\n                let i = 0;\n                while (i < length) {\n                    const zeroIndex = chunk.indexOf(0, i);\n                    if (zeroIndex === -1 || zeroIndex >= length) {\n                        break;\n                    }\n                    i = zeroIndex;\n                    const posBeforeZero = chunkStartPos + i;\n                    // Need 3 more bytes after the 0x00 to recognize a start code prefix\n                    if (i + 3 >= length) {\n                        // Not enough data in current chunk, seek back and let the next iteration handle it\n                        this.seekTo(posBeforeZero);\n                        break;\n                    }\n                    const b1 = chunk[i + 1];\n                    const b2 = chunk[i + 2];\n                    const b3 = chunk[i + 3];\n                    let startCodeLength = 0;\n                    // Check for 4-byte start code (0x00000001)\n                    if (b1 === 0x00 && b2 === 0x00 && b3 === 0x01) {\n                        startCodeLength = 4;\n                    }\n                    else if (b1 === 0x00 && b2 === 0x01) {\n                        // 3-byte start code (0x000001)\n                        startCodeLength = 3;\n                    }\n                    if (startCodeLength === 0) {\n                        // Not a start code, continue\n                        i++;\n                        continue;\n                    }\n                    const startCodePos = posBeforeZero;\n                    // The packet only really begins at the first NAL unit; anything before it isn't usable\n                    packetStartPos ??= startCodePos;\n                    const nalHeaderStart = i + startCodeLength;\n                    const payloadStart = nalHeaderStart + nalHeaderSize;\n                    // Bytes peeked from the start of a slice header to decode first_mb_in_slice. Six bytes (48 bits)\n                    // comfortably covers the exp-Golomb code for any realistic macroblock count\n                    const AVC_SLICE_HEADER_PEEK_SIZE = 6;\n                    // We read the NAL header plus, for slices, the start of the slice header to decode the\n                    // first_mb_in_slice / first_slice_segment_in_pic_flag. Make sure all of it is buffered.\n                    const bytesNeeded = payloadStart + (codec === 'avc' ? AVC_SLICE_HEADER_PEEK_SIZE : 1);\n                    if (bytesNeeded > length) {\n                        this.seekTo(posBeforeZero);\n                        break;\n                    }\n                    const headerByte0 = chunk[nalHeaderStart];\n                    let nalUnitType;\n                    let isSlice;\n                    let isAccessUnitStart;\n                    let isAccessUnitDelimiter;\n                    if (codec === 'avc') {\n                        nalUnitType = extractNalUnitTypeForAvc(headerByte0);\n                        isSlice = nalUnitType === AvcNalUnitType.NON_IDR_SLICE\n                            || nalUnitType === AvcNalUnitType.SLICE_DPA\n                            || nalUnitType === AvcNalUnitType.IDR;\n                        isAccessUnitStart = nalUnitType === AvcNalUnitType.SEI\n                            || nalUnitType === AvcNalUnitType.SPS\n                            || nalUnitType === AvcNalUnitType.PPS\n                            || nalUnitType === AvcNalUnitType.AUD;\n                        isAccessUnitDelimiter = nalUnitType === AvcNalUnitType.AUD;\n                    }\n                    else {\n                        nalUnitType = extractNalUnitTypeForHevc(headerByte0);\n                        const layerId = ((headerByte0 & 1) << 5) | (chunk[nalHeaderStart + 1] >> 3);\n                        if (layerId > 0) {\n                            // Higher layers don't delimit the base-layer frames we care about\n                            i += startCodeLength;\n                            continue;\n                        }\n                        // VCL slices: 0..RASL_R, plus the IRAP range BLA_W_LP..CRA_NUT\n                        isSlice = nalUnitType <= HevcNalUnitType.RASL_R\n                            || (nalUnitType >= HevcNalUnitType.BLA_W_LP && nalUnitType <= 21);\n                        // VPS..FD, prefix SEI, and the reserved/unspecified non-VCL ranges\n                        isAccessUnitStart = (nalUnitType >= HevcNalUnitType.VPS_NUT && nalUnitType <= 37)\n                            || nalUnitType === HevcNalUnitType.PREFIX_SEI_NUT\n                            || (nalUnitType >= 41 && nalUnitType <= 44)\n                            || (nalUnitType >= 48 && nalUnitType <= 55);\n                        isAccessUnitDelimiter = nalUnitType === HevcNalUnitType.AUD_NUT;\n                    }\n                    let isFrameBoundary = false;\n                    if (isSlice) {\n                        let startsNewPicture;\n                        if (codec === 'avc') {\n                            const headerBytes = chunk.subarray(payloadStart, payloadStart + AVC_SLICE_HEADER_PEEK_SIZE);\n                            const firstMacroblockInSlice = readExpGolomb(new Bitstream(headerBytes));\n                            startsNewPicture = !frameStartFound || firstMacroblockInSlice <= lastFirstMacroblockInSlice;\n                            lastFirstMacroblockInSlice = firstMacroblockInSlice;\n                        }\n                        else {\n                            startsNewPicture = (chunk[payloadStart] >> 7) === 1;\n                        }\n                        if (startsNewPicture) {\n                            if (frameStartFound) {\n                                isFrameBoundary = true;\n                            }\n                            else {\n                                frameStartFound = true;\n                            }\n                        }\n                    }\n                    else if (isAccessUnitStart && frameStartFound) {\n                        isFrameBoundary = true;\n                    }\n                    else if (isAccessUnitDelimiter) {\n                        // An AUD always begins a new access unit. We haven't seen a slice yet, so whatever came before\n                        // it holds no picture; let's drop it\n                        packetStartPos = startCodePos;\n                    }\n                    if (isFrameBoundary) {\n                        // End the packet at this start code (the next frame begins here)\n                        const packetLength = startCodePos - packetStartPos;\n                        this.seekTo(packetStartPos);\n                        return this.supplyPacket(packetLength, 0);\n                    }\n                    i += startCodeLength;\n                }\n                if (remaining < CHUNK_SIZE) {\n                    // End of stream\n                    break;\n                }\n            }\n            // End of stream - emit whatever's left as the final packet, unless it holds no picture\n            if (frameStartFound) {\n                assert(packetStartPos !== null);\n                const packetLength = this.endPos - packetStartPos;\n                this.seekTo(packetStartPos);\n                return this.supplyPacket(packetLength, 0);\n            }\n        }\n        else {\n            const codec = elementaryStream.info.codec;\n            const CHUNK_SIZE = 128;\n            while (true) {\n                let remaining = this.ensureBuffered(CHUNK_SIZE);\n                if (isThenable(remaining))\n                    remaining = await remaining;\n                const startPos = this.currentPos;\n                while (this.currentPos - startPos < remaining) {\n                    const byte = this.readU8();\n                    if (codec === 'aac') {\n                        if (byte !== 0xff) {\n                            continue;\n                        }\n                        this.skip(-1);\n                        const possibleHeaderStartPos = this.currentPos;\n                        let remaining = this.ensureBuffered(MAX_ADTS_FRAME_HEADER_SIZE);\n                        if (isThenable(remaining))\n                            remaining = await remaining;\n                        if (remaining < MAX_ADTS_FRAME_HEADER_SIZE) {\n                            return;\n                        }\n                        const headerBytes = this.readBytes(MAX_ADTS_FRAME_HEADER_SIZE);\n                        const header = readAdtsFrameHeader(FileSlice.tempFromBytes(headerBytes));\n                        if (header) {\n                            this.seekTo(possibleHeaderStartPos);\n                            let remaining = this.ensureBuffered(header.frameLength);\n                            if (isThenable(remaining))\n                                remaining = await remaining;\n                            return this.supplyPacket(remaining, Math.round(SAMPLES_PER_AAC_FRAME * TIMESCALE / elementaryStream.info.sampleRate));\n                        }\n                        else {\n                            this.seekTo(possibleHeaderStartPos + 1);\n                        }\n                    }\n                    else if (codec === 'mp3') {\n                        if (byte !== 0xff) {\n                            continue;\n                        }\n                        this.skip(-1);\n                        const possibleHeaderStartPos = this.currentPos;\n                        let remaining = this.ensureBuffered(MP3_FRAME_HEADER_SIZE);\n                        if (isThenable(remaining))\n                            remaining = await remaining;\n                        if (remaining < MP3_FRAME_HEADER_SIZE) {\n                            return;\n                        }\n                        const headerBytes = this.readBytes(MP3_FRAME_HEADER_SIZE);\n                        const word = toDataView(headerBytes).getUint32(0);\n                        const result = readMp3FrameHeader(word, null);\n                        if (result.header) {\n                            this.seekTo(possibleHeaderStartPos);\n                            let remaining = this.ensureBuffered(result.header.totalSize);\n                            if (isThenable(remaining))\n                                remaining = await remaining;\n                            const duration = result.header.audioSamplesInFrame * TIMESCALE\n                                / elementaryStream.info.sampleRate;\n                            return this.supplyPacket(remaining, Math.round(duration));\n                        }\n                        else {\n                            this.seekTo(possibleHeaderStartPos + 1);\n                        }\n                    }\n                    else if (codec === 'ac3') {\n                        if (byte !== 0x0b) {\n                            continue;\n                        }\n                        this.skip(-1);\n                        const possibleSyncPos = this.currentPos;\n                        // Need at least 5 bytes for sync word + CRC + fscod/frmsizecod\n                        let remaining = this.ensureBuffered(5);\n                        if (isThenable(remaining))\n                            remaining = await remaining;\n                        if (remaining < 5) {\n                            return;\n                        }\n                        const headerBytes = this.readBytes(5);\n                        // Verify sync word (0x0B77)\n                        if (headerBytes[0] !== 0x0b || headerBytes[1] !== 0x77) {\n                            this.seekTo(possibleSyncPos + 1);\n                            continue;\n                        }\n                        const fscod = headerBytes[4] >> 6;\n                        const frmsizecod = headerBytes[4] & 0x3f;\n                        if (fscod === 3 || frmsizecod > 37) {\n                            // Invalid\n                            this.seekTo(possibleSyncPos + 1);\n                            continue;\n                        }\n                        const frameSize = AC3_FRAME_SIZES[3 * frmsizecod + fscod];\n                        assert(frameSize !== undefined);\n                        this.seekTo(possibleSyncPos);\n                        remaining = this.ensureBuffered(frameSize);\n                        if (isThenable(remaining))\n                            remaining = await remaining;\n                        const duration = Math.round(AC3_SAMPLES_PER_FRAME * TIMESCALE / elementaryStream.info.sampleRate);\n                        return this.supplyPacket(remaining, duration);\n                    }\n                    else if (codec === 'eac3') {\n                        if (byte !== 0x0b) {\n                            continue;\n                        }\n                        this.skip(-1);\n                        const possibleSyncPos = this.currentPos;\n                        // Need at least 5 bytes for E-AC-3 header parsing (sync word + frmsiz + fscod/numblkscod)\n                        let remaining = this.ensureBuffered(5);\n                        if (isThenable(remaining))\n                            remaining = await remaining;\n                        if (remaining < 5) {\n                            return;\n                        }\n                        const headerBytes = this.readBytes(5);\n                        if (headerBytes[0] !== 0x0b || headerBytes[1] !== 0x77) {\n                            this.seekTo(possibleSyncPos + 1);\n                            continue;\n                        }\n                        const frmsiz = ((headerBytes[2] & 0x07) << 8) | headerBytes[3];\n                        const frameSize = (frmsiz + 1) * 2;\n                        const fscod = headerBytes[4] >> 6;\n                        const numblkscod = fscod === 3 ? 3 : (headerBytes[4] >> 4) & 0x03;\n                        const numblks = EAC3_NUMBLKS_TABLE[numblkscod];\n                        this.seekTo(possibleSyncPos);\n                        remaining = this.ensureBuffered(frameSize);\n                        if (isThenable(remaining))\n                            remaining = await remaining;\n                        // Duration = numblks * 256 samples per block\n                        const samplesPerFrame = numblks * 256;\n                        const duration = Math.round(samplesPerFrame * TIMESCALE / elementaryStream.info.sampleRate);\n                        return this.supplyPacket(remaining, duration);\n                    }\n                    else if (codec === 'dts') {\n                        if (byte !== 0x7f && byte !== 0x64) {\n                            continue;\n                        }\n                        this.skip(-1);\n                        const possibleSyncPos = this.currentPos;\n                        let remaining = this.ensureBuffered(DTS_CORE_FRAME_HEADER_SIZE);\n                        if (isThenable(remaining))\n                            remaining = await remaining;\n                        if (remaining < DTS_CORE_FRAME_HEADER_SIZE) {\n                            return;\n                        }\n                        const headerBytes = this.readBytes(DTS_CORE_FRAME_HEADER_SIZE);\n                        const core = parseDtsCoreFrameHeader(headerBytes);\n                        let leadingExss = core ? null : parseDtsExssHeader(headerBytes);\n                        if (!core && !leadingExss) {\n                            this.seekTo(possibleSyncPos + 1);\n                            continue;\n                        }\n                        if (leadingExss && !leadingExss.asset) {\n                            // The static fields and the asset descriptor reach past the bytes we read for the\n                            // core header, so take another look with the substream's whole header available\n                            this.seekTo(possibleSyncPos);\n                            const headerBound = Math.min(leadingExss.frameSize, DTS_EXSS_MAX_HEADER_SIZE);\n                            let remaining = this.ensureBuffered(headerBound);\n                            if (isThenable(remaining))\n                                remaining = await remaining;\n                            leadingExss = parseDtsExssHeader(this.readBytes(remaining)) ?? leadingExss;\n                        }\n                        let frameSize = core ? core.frameSize : leadingExss.frameSize;\n                        // Extension-only streams put exactly one substream in each frame, so it's only a core\n                        // frame that needs us to go looking for the extensions riding along with it. The core is\n                        // padded out to a 4-byte boundary before the first of them starts.\n                        if (core) {\n                            let nextSubstreamPos = Math.ceil(core.frameSize / 4) * 4;\n                            while (true) {\n                                this.seekTo(possibleSyncPos);\n                                const neededBytes = nextSubstreamPos + DTS_EXSS_HEADER_PREFIX_SIZE;\n                                let remaining = this.ensureBuffered(neededBytes);\n                                if (isThenable(remaining))\n                                    remaining = await remaining;\n                                if (remaining < neededBytes) {\n                                    break;\n                                }\n                                this.seekTo(possibleSyncPos + nextSubstreamPos);\n                                const exss = parseDtsExssHeader(this.readBytes(DTS_EXSS_HEADER_PREFIX_SIZE));\n                                if (!exss) {\n                                    break;\n                                }\n                                nextSubstreamPos += exss.frameSize;\n                                frameSize = nextSubstreamPos;\n                            }\n                        }\n                        // Only the substream leading the frame declares how many samples the frame holds\n                        const sampleCount = core?.sampleCount ?? leadingExss.asset?.sampleCount;\n                        if (sampleCount === undefined) {\n                            this.seekTo(possibleSyncPos + 1);\n                            continue;\n                        }\n                        this.seekTo(possibleSyncPos);\n                        remaining = this.ensureBuffered(frameSize);\n                        if (isThenable(remaining))\n                            remaining = await remaining;\n                        const duration = Math.round(sampleCount * TIMESCALE / elementaryStream.info.sampleRate);\n                        return this.supplyPacket(remaining, duration);\n                    }\n                    else {\n                        throw new Error('Unhandled.');\n                    }\n                }\n                if (remaining < CHUNK_SIZE) {\n                    break;\n                }\n            }\n        }\n    }\n    /** Supplies the context with a new encoded packet, beginning at the current position. */\n    supplyPacket(packetLength, intrinsicDuration) {\n        const currentPesPacket = this.getCurrentPesPacket();\n        let pts;\n        if (this.lastSuppliedPesPacket === currentPesPacket) {\n            assert(this.nextPts !== null);\n            pts = this.nextPts;\n        }\n        else {\n            if (currentPesPacket.pts === null) {\n                throw new Error(MISSING_PTS_ERROR_MESSAGE);\n            }\n            pts = currentPesPacket.pts;\n            maybeInsertReferencePacket(this.elementaryStream, currentPesPacket);\n        }\n        this.lastSuppliedPesPacket = currentPesPacket;\n        this.nextPts = pts + intrinsicDuration;\n        const sectionStartPos = currentPesPacket.sectionStartPos;\n        // The sequence number is the starting position of the section the PES packet is in, PLUS the offset within the\n        // PES packet where the packet starts.\n        const sequenceNumber = sectionStartPos + (this.currentPos - this.currentPesPacketPos);\n        const data = this.readBytes(packetLength);\n        let randomAccessIndicator = currentPesPacket.randomAccessIndicator;\n        if (randomAccessIndicator === 0 && !this.elementaryStream.canBeTrustedWithKeyPackets) {\n            if (this.elementaryStream.info.type === 'audio') {\n                randomAccessIndicator = 1;\n            }\n            else {\n                if (this.elementaryStream.info.decoderConfig) {\n                    const isKey = determineVideoPacketType(this.elementaryStream.info.codec, this.elementaryStream.info.decoderConfig, data) === 'key';\n                    randomAccessIndicator = Number(isKey);\n                }\n                else {\n                    // We're reading packets before the decoder config is determined\n                }\n            }\n        }\n        this.suppliedPacket = {\n            pts,\n            data,\n            sequenceNumber,\n            sectionStartPos,\n            randomAccessIndicator,\n        };\n        this.pesPackets.splice(0, this.currentPesPacketIndex);\n        this.currentPesPacketIndex = 0;\n    }\n}\n/**\n * A buffer that simulates decoder frame reordering to compute packet durations. Packets arrive in decode order but\n * durations are based on presentation order.\n */\nclass PacketBuffer {\n    constructor(backing, context) {\n        this.decodeOrderPackets = [];\n        this.reorderBuffer = [];\n        this.presentationOrderPackets = [];\n        this.reachedEnd = false;\n        this.lastDuration = 0;\n        this.backing = backing;\n        this.context = context;\n        this.reorderSize = backing.getReorderSize();\n        assert(this.reorderSize >= 0);\n    }\n    async readNext() {\n        if (this.decodeOrderPackets.length === 0) {\n            // We need the next packet\n            const didRead = await this.readNextPacket();\n            if (!didRead) {\n                return null;\n            }\n        }\n        // Ensure we know the next packet in presentation order so we can compute the current packet's duration\n        await this.ensureCurrentPacketHasNext();\n        const packet = this.decodeOrderPackets[0];\n        // Let's compute the duration\n        const presentationIndex = this.presentationOrderPackets.indexOf(packet);\n        let duration;\n        if (presentationIndex === -1 || presentationIndex === this.presentationOrderPackets.length - 1) {\n            // The packet has no known successor (or isn't even placed yet when timestamps are messed up)\n            duration = this.lastDuration; // Reasonable heuristic\n        }\n        else {\n            const nextPacket = this.presentationOrderPackets[presentationIndex + 1];\n            duration = nextPacket.pts - packet.pts;\n            this.lastDuration = duration;\n        }\n        this.decodeOrderPackets.shift();\n        // Shrink the presentation array as much as possible\n        while (this.presentationOrderPackets.length > 0) {\n            const first = this.presentationOrderPackets[0];\n            if (this.decodeOrderPackets.includes(first)) {\n                break;\n            }\n            this.presentationOrderPackets.shift();\n        }\n        return { packet, duration };\n    }\n    async readNextPacket() {\n        if (this.reachedEnd) {\n            return false;\n        }\n        let suppliedPacket;\n        if (this.context.suppliedPacket) {\n            // Small optimization: there was already a supplied packet in the context, so let's first use that one\n            suppliedPacket = this.context.suppliedPacket;\n        }\n        else {\n            await this.context.markNextPacket();\n            suppliedPacket = this.context.suppliedPacket;\n        }\n        this.context.suppliedPacket = null;\n        if (!suppliedPacket) {\n            this.reachedEnd = true;\n            this.flushReorderBuffer();\n            return false;\n        }\n        this.decodeOrderPackets.push(suppliedPacket);\n        this.processPacketThroughReorderBuffer(suppliedPacket);\n        return true;\n    }\n    async ensureCurrentPacketHasNext() {\n        const current = this.decodeOrderPackets[0];\n        assert(current);\n        while (true) {\n            const presentationIndex = this.presentationOrderPackets.indexOf(current);\n            // Check if current packet has a next packet\n            if (presentationIndex !== -1 && presentationIndex <= this.presentationOrderPackets.length - 2) {\n                break;\n            }\n            // Cap it so that nonsensical timestamps don't scan the entire file\n            if (this.decodeOrderPackets.length > 4 * (this.reorderSize + 1)) {\n                break;\n            }\n            const didRead = await this.readNextPacket();\n            if (!didRead) {\n                break;\n            }\n        }\n    }\n    processPacketThroughReorderBuffer(packet) {\n        this.reorderBuffer.push(packet);\n        // If buffer is now overfull, output the packet with smallest PTS\n        if (this.reorderBuffer.length > this.reorderSize) {\n            let minIndex = 0;\n            for (let i = 1; i < this.reorderBuffer.length; i++) {\n                if (this.reorderBuffer[i].pts < this.reorderBuffer[minIndex].pts) {\n                    minIndex = i;\n                }\n            }\n            const packet = this.reorderBuffer[minIndex];\n            this.presentationOrderPackets.push(packet);\n            this.reorderBuffer.splice(minIndex, 1);\n        }\n    }\n    flushReorderBuffer() {\n        this.reorderBuffer.sort((a, b) => a.pts - b.pts);\n        this.presentationOrderPackets.push(...this.reorderBuffer);\n        this.reorderBuffer.length = 0;\n    }\n}\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { assert, binarySearchLessOrEqual, clamp, closedIntervalsOverlap, isNumber, isThenable, isWebKit, mergeRequestInit, normalizeHeaders, polyfillSymbolDispose, promiseWithResolvers, retriedFetch, toDataView, toUint8Array, wait, EventEmitter, } from './misc.js';\nimport * as nodeAlias from './node.js';\nimport { InputDisposedError } from './input.js';\nimport { Logging } from './logging.js';\npolyfillSymbolDispose();\nconst node = typeof nodeAlias !== 'undefined'\n    ? nodeAlias // Aliasing it prevents some bundler warnings\n    : undefined;\nexport const DEFAULT_MIN_READ_POSITION = 0;\nexport const DEFAULT_MAX_READ_POSITION = Infinity;\nlet sourceFinalizationRegistry = null;\nif (typeof FinalizationRegistry !== 'undefined') {\n    sourceFinalizationRegistry = new FinalizationRegistry((cleanup) => {\n        cleanup();\n    });\n}\n/**\n * The source base class, representing a resource from which bytes can be read.\n * @group Input sources\n * @public\n */\nexport class Source extends EventEmitter {\n    constructor() {\n        super();\n        /** @internal */\n        this._disposed = false;\n        /** @internal */\n        this._refCount = 0;\n        /**\n         * Used internally to mark if a source stems from an HLS reading operation. Used to suppress certain warnings.\n         * @internal\n         */\n        this._usedForHls = false;\n        /**\n         * FinalizationRegistry for rogue refs to this source that didn't get freed. It lives on the Source itself so that\n         * in case the Source transitively points back to itself and forms a cycle (for example through a custom\n         * CustomSource callback) that we're not leaking memory.\n         * @internal\n         */\n        this._refFinalizationRegistry = null;\n        /** @internal */\n        this._sizePromise = null;\n        /**\n         * Called each time data is retrieved from the source. Will be called with the retrieved range (end exclusive).\n         *\n         * @deprecated Use `source.on('read', ({ start, end }) => ...)` instead.\n         */\n        this.onread = null;\n        if (typeof FinalizationRegistry !== 'undefined') {\n            this._refFinalizationRegistry = new FinalizationRegistry((source) => {\n                source._decrementRefCount();\n            });\n        }\n    }\n    /**\n     * Resolves with the total size of the file in bytes. This function is memoized, meaning only the first call\n     * will retrieve the size.\n     *\n     * Returns null if the source is unsized.\n     */\n    async getSizeOrNull() {\n        if (this._disposed) {\n            throw new InputDisposedError();\n        }\n        return this._sizePromise ??= (async () => {\n            let size = this._getFileSize();\n            if (size !== undefined) {\n                return size;\n            }\n            await this._read(0, 1, DEFAULT_MIN_READ_POSITION, DEFAULT_MAX_READ_POSITION);\n            size = this._getFileSize();\n            assert(size !== undefined);\n            return size;\n        })();\n    }\n    /**\n     * Resolves with the total size of the file in bytes. This function is memoized, meaning only the first call\n     * will retrieve the size.\n     *\n     * Throws an error if the source is unsized.\n     */\n    async getSize() {\n        if (this._disposed) {\n            throw new InputDisposedError();\n        }\n        const result = await this.getSizeOrNull();\n        if (result === null) {\n            throw new Error('Cannot determine the size of an unsized source.');\n        }\n        return result;\n    }\n    /**\n     * Returns a new {@link RangedSource} that maps data onto this source using the given offset and length. If a length\n     * is not provided, the ranged source spans until the end of this source's data.\n     *\n     * Useful for reading files that are embedded within larger files.\n     */\n    slice(offset, length) {\n        if (!Number.isInteger(offset) || offset < 0) {\n            throw new TypeError('offset must be a non-negative integer.');\n        }\n        if (length !== undefined && (!Number.isInteger(length) || length < 0)) {\n            throw new TypeError('length, when provided, must be a non-negative integer.');\n        }\n        return new RangedSource(this, offset, length);\n    }\n    /** @internal */\n    _dispatchRead(start, end) {\n        // eslint-disable-next-line @typescript-eslint/no-deprecated\n        this.onread?.(start, end);\n        this._emit('read', { start, end });\n    }\n    /**\n     * Creates a new `SourceRef` pointing to this source. You are expected to call `.free()` on said `SourceRef` when\n     * you're done with it.\n     */\n    ref() {\n        return new SourceRef(this);\n    }\n    /** @internal */\n    _incrementRefCount() {\n        this._refCount++;\n    }\n    /** @internal */\n    _decrementRefCount() {\n        this._refCount--;\n        if (this._refCount === 0) {\n            this._dispose();\n            this._disposed = true;\n        }\n    }\n}\n/**\n * A reference to a {@link Source}, used to manage a source's lifecycle. Creating a `SourceRef` via {@link Source.ref}\n * increases that source's internal reference count. As long as a source has a non-zero reference count, it is assumed\n * to still be in use. Once all references are freed via {@link SourceRef.free}, the source gets disposed.\n *\n * @group Input sources\n * @public\n */\nexport class SourceRef {\n    /** @internal */\n    constructor(source) {\n        /** @internal */\n        this._freed = false;\n        if (source._disposed) {\n            throw new Error('Cannot ref a disposed source.');\n        }\n        source._incrementRefCount();\n        source._refFinalizationRegistry?.register(this, source, this);\n        this._source = source;\n    }\n    /** The {@link Source} this ref references. Accessing this field throws an error after having freed the ref. */\n    get source() {\n        if (!this._source) {\n            throw new Error('Can\\'t get source; ref has already been freed.');\n        }\n        return this._source;\n    }\n    /** Whether or not this reference has been freed via {@link SourceRef.free}. */\n    get freed() {\n        return this._freed;\n    }\n    /**\n     * Frees the ref, decrementing the source's internal reference count. If the source's internal reference count\n     * reaches zero, it gets disposed. To catch bugs, this method throws if the ref is already freed.\n     */\n    free() {\n        if (this._freed) {\n            throw new Error('Illegal operation: double free on SourceRef.');\n        }\n        const source = this.source;\n        assert(source._refCount > 0);\n        source._decrementRefCount();\n        source._refFinalizationRegistry?.unregister(this);\n        this._freed = true;\n        this._source = null;\n    }\n    /**\n     * Calls {@link SourceRef.free}.\n     */\n    [Symbol.dispose]() {\n        if (!this.freed) {\n            this.free();\n        }\n    }\n}\n/**\n * A source which can create new sources from file paths. Required for multi-file inputs such as HLS playlists.\n * @public\n * @group Input sources\n */\nexport class PathedSource extends Source {\n    constructor(\n    /**\n     * The path that points to the root file; the entry file of the media.\n     *\n     * This path may be modified by the source to indicate a redirect: an updated path to perform new requests\n     * relative to.\n     */\n    rootPath, \n    /** The callback that is called for each requested file; must return a {@link Source} or {@link SourceRef}. */\n    requestHandler) {\n        if (typeof rootPath !== 'string') {\n            throw new TypeError('rootPath must be a string.');\n        }\n        if (typeof requestHandler !== 'function') {\n            throw new TypeError('requestHandler must be a function.');\n        }\n        super();\n        this.rootPath = rootPath;\n        this.requestHandler = requestHandler;\n    }\n    /** @internal */\n    _resolveRequest(request) {\n        const result = this.requestHandler(request);\n        const handle = (result) => {\n            if (!(result instanceof Source || result instanceof SourceRef)) {\n                throw new TypeError('requestHandler must return or resolve to a Source or SourceRef.');\n            }\n            const ref = result instanceof Source\n                ? result.ref()\n                : result;\n            ref.source._usedForHls ||= this._usedForHls;\n            return ref;\n        };\n        if (isThenable(result)) {\n            return result.then(handle);\n        }\n        else {\n            return handle(result);\n        }\n    }\n}\nexport const sourceRequestsAreEqual = (a, b) => {\n    return a.path === b.path;\n};\n/**\n * A custom multi-file source where each file is uniquely identified by a {@link FilePath} and can be resolved to\n * an arbitrary {@link Source}.\n *\n * @public\n * @group Input sources\n */\nexport class CustomPathedSource extends PathedSource {\n    constructor() {\n        super(...arguments);\n        /** @internal */\n        this._root = null;\n        /** @internal */\n        this._rootRequest = null;\n    }\n    /** @internal */\n    _read(start, end, minReadPosition, maxReadPosition) {\n        if (!this._root) {\n            if (!this._rootRequest) {\n                const result = this._resolveRequest({ path: this.rootPath, isRoot: true });\n                const handle = (result) => {\n                    const ref = result instanceof Source\n                        ? result.ref()\n                        : result;\n                    this._root = ref;\n                    this._rootRequest = null;\n                    return ref;\n                };\n                if (isThenable(result)) {\n                    this._rootRequest = result.then(handle);\n                }\n                else {\n                    handle(result);\n                    assert(this._root);\n                }\n            }\n            if (this._rootRequest) {\n                return this._rootRequest.then(ref => ref.source._read(start, end, minReadPosition, maxReadPosition));\n            }\n        }\n        return this._root.source._read(start, end, minReadPosition, maxReadPosition);\n    }\n    /** @internal */\n    _getFileSize() {\n        if (this._root) {\n            return this._root.source._getFileSize();\n        }\n        return undefined;\n    }\n    /** @internal */\n    _dispose() {\n        if (this._root) {\n            this._root.free();\n        }\n        else if (this._rootRequest) {\n            void this._rootRequest\n                .then(ref => ref.free())\n                .catch(() => { });\n        }\n    }\n}\n/**\n * A source backed by an ArrayBuffer or ArrayBufferView, with the entire file held in memory.\n * @group Input sources\n * @public\n */\nexport class BufferSource extends Source {\n    /**\n     * Creates a new {@link BufferSource} backed by the specified `ArrayBuffer`, `SharedArrayBuffer`,\n     * or `ArrayBufferView`.\n     */\n    constructor(buffer) {\n        if (!(buffer instanceof ArrayBuffer)\n            && !(typeof SharedArrayBuffer !== 'undefined' && buffer instanceof SharedArrayBuffer)\n            && !ArrayBuffer.isView(buffer)) {\n            throw new TypeError('buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.');\n        }\n        super();\n        /** @internal */\n        this._onreadCalled = false;\n        this._bytes = toUint8Array(buffer);\n        this._view = toDataView(buffer);\n    }\n    /** @internal */\n    _getFileSize() {\n        return this._bytes.byteLength;\n    }\n    /** @internal */\n    _read() {\n        if (!this._onreadCalled) {\n            // We just say the first read retrieves all bytes from the source (which, I mean, it does)\n            this._dispatchRead(0, this._bytes.byteLength);\n            this._onreadCalled = true;\n        }\n        return {\n            bytes: this._bytes,\n            view: this._view,\n            offset: 0,\n        };\n    }\n    /** @internal */\n    _dispose() { }\n}\nconst blobReaderRegistry = typeof FinalizationRegistry !== 'undefined'\n    ? new FinalizationRegistry((reader) => {\n        // Browsers don't GC readers that aren't \"done\", which creates indefinite memory leaks,\n        // see https://github.com/Vanilagy/mediabunny/issues/144#issuecomment-5465467062. So, we need to do it instead.\n        void reader.cancel().catch(() => { });\n    })\n    : null;\n/**\n * A source backed by a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob). Since a\n * [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) is also a `Blob`, this is the source to use when\n * reading files off the disk.\n * @group Input sources\n * @public\n */\nexport class BlobSource extends Source {\n    /**\n     * Creates a new {@link BlobSource} backed by the specified\n     * [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).\n     */\n    constructor(blob, options = {}) {\n        if (!(blob instanceof Blob)) {\n            throw new TypeError('blob must be a Blob.');\n        }\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.maxCacheSize !== undefined\n            && (!isNumber(options.maxCacheSize) || options.maxCacheSize < 0)) {\n            throw new TypeError('options.maxCacheSize, when provided, must be a non-negative number.');\n        }\n        if (options.useStreamReader !== undefined && typeof options.useStreamReader !== 'boolean') {\n            throw new TypeError('options.useStreamReader, when provided, must be a boolean.');\n        }\n        if (options.handleUnhandledError !== undefined && typeof options.handleUnhandledError !== 'function') {\n            throw new TypeError('options.handleUnhandledError, when provided, must be a function.');\n        }\n        super();\n        /** @internal */\n        this._readers = new WeakMap();\n        this._blob = blob;\n        this._options = options;\n        this._orchestrator = new ReadOrchestrator({\n            maxCacheSize: options.maxCacheSize ?? (8 * 2 ** 20 /* 8 MiB */),\n            maxWorkerCount: 4,\n            runWorker: this._runWorker.bind(this),\n            onIdleWorkerRemoved: (worker) => {\n                const reader = this._readers.get(worker);\n                if (reader) {\n                    this._readers.delete(worker);\n                    blobReaderRegistry?.unregister(worker);\n                    // If we don't do this, memory leaks indefinitely\n                    void reader.cancel().catch(() => { });\n                }\n            },\n            prefetchProfile: PREFETCH_PROFILES.fileSystem,\n            handleUnhandledError: options.handleUnhandledError,\n        });\n        this._orchestrator.fileSize = blob.size;\n    }\n    /** @internal */\n    _getFileSize() {\n        return this._orchestrator.fileSize; // Faster than blob.size\n    }\n    /** @internal */\n    _read(start, end, minReadPosition, maxReadPosition) {\n        return this._orchestrator.read(start, end, minReadPosition, maxReadPosition);\n    }\n    /** @internal */\n    async _runWorker(worker) {\n        assert(worker.strictTarget);\n        let reader = this._readers.get(worker);\n        if (reader === undefined) {\n            // https://github.com/Vanilagy/mediabunny/issues/184\n            // WebKit has critical bugs with blob.stream():\n            // - WebKitBlobResource error 1 when streaming large files\n            // - Memory buildup and reload loops on iOS (network process crashes)\n            // - ReadableStream stalls under backpressure (especially video)\n            // Affects Safari and all iOS browsers (Chrome, Firefox, etc.).\n            // Use arrayBuffer() fallback for WebKit browsers.\n            if ('stream' in this._blob && !isWebKit()\n                && this._options.useStreamReader !== false) {\n                // Get a reader of the blob starting at the required offset, and then keep it around\n                const slice = this._blob.slice(worker.currentPos);\n                reader = slice.stream().getReader();\n                blobReaderRegistry?.register(worker, reader, worker);\n            }\n            else {\n                // We'll need to use more primitive ways\n                reader = null;\n            }\n            this._readers.set(worker, reader);\n        }\n        while (worker.currentPos < worker.targetPos && !worker.aborted) {\n            if (reader) {\n                const { done, value } = await reader.read();\n                if (done) {\n                    this._orchestrator.onWorkerFinished(worker);\n                    throw new Error('Blob reader stopped unexpectedly before all requested data was read.');\n                }\n                if (worker.aborted) {\n                    break;\n                }\n                this._dispatchRead(worker.currentPos, worker.currentPos + value.length);\n                this._orchestrator.supplyWorkerData(worker, value);\n            }\n            else {\n                const data = await this._blob.slice(worker.currentPos, worker.targetPos).arrayBuffer();\n                if (worker.aborted) {\n                    break;\n                }\n                this._dispatchRead(worker.currentPos, worker.currentPos + data.byteLength);\n                this._orchestrator.supplyWorkerData(worker, new Uint8Array(data));\n            }\n        }\n        this._orchestrator.signalWorkerStoppedRunning(worker);\n        if (worker.aborted) {\n            // MDN: \"Calling this method signals a loss of interest in the stream by a consumer.\"\n            await reader?.cancel().catch(() => { });\n        }\n    }\n    /** @internal */\n    _dispose() {\n        this._orchestrator.dispose();\n    }\n}\nconst URL_SOURCE_MIN_LOAD_AMOUNT = 0.5 * 2 ** 20; // 0.5 MiB\nconst DEFAULT_RETRY_DELAY = ((previousAttempts, error, src) => {\n    // Check if this could be a CORS error. If so, we cannot recover from it and\n    // should not attempt to retry.\n    // CORS errors are intentionally not opaque, so we need to rely on heuristics.\n    const couldBeCorsError = error instanceof Error\n        && (error.message.includes('Failed to fetch') // Chrome\n            || error.message.includes('Load failed') // Safari\n            || error.message.includes('NetworkError when attempting to fetch resource') // Firefox\n        )\n        && typeof window !== 'undefined'; // CORS only happens in browser environments\n    if (couldBeCorsError) {\n        let originOfSrc = null;\n        // Checking if the origin is different, because only then a CORS error could originate\n        try {\n            if (typeof window !== 'undefined' && typeof window.location !== 'undefined') {\n                originOfSrc = new URL(src instanceof Request ? src.url : src, window.location.href).origin;\n            }\n        }\n        catch {\n            // URL parse failed\n        }\n        // If user is offline, it is probably not a CORS error.\n        const isOnline = typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean' ? navigator.onLine : true;\n        if (isOnline && originOfSrc !== null && originOfSrc !== window.location.origin) {\n            Logging._warn(`Request will not be retried because a CORS error was suspected due to different origins. You can`\n                + ` modify this behavior by providing your own function for the 'getRetryDelay' option.`);\n            return null;\n        }\n    }\n    return Math.min(2 ** (previousAttempts - 2), 16);\n});\nconst warnedOrigins = new Set();\n/**\n * A source backed by a URL. This is useful for reading data from the network. Requests will be made using an optimized\n * reading and prefetching pattern to minimize request count and latency. Works best with servers that support HTTP\n * range requests; otherwise, resources must be streamed and read sequentially.\n * @group Input sources\n * @public\n */\nexport class UrlSource extends PathedSource {\n    /**\n     * Creates a new {@link UrlSource} backed by the resource at the specified URL.\n     *\n     * When passing a `Request` instance, note that its `signal` will be overridden by Mediabunny; if you want to cancel\n     * ongoing requests, use {@link Input.dispose}.\n     */\n    constructor(url, options = {}) {\n        if (typeof url !== 'string'\n            && !(url instanceof URL)\n            && !(typeof Request !== 'undefined' && url instanceof Request)) {\n            throw new TypeError('url must be a string, URL or Request.');\n        }\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.requestInit !== undefined && (!options.requestInit || typeof options.requestInit !== 'object')) {\n            throw new TypeError('options.requestInit, when provided, must be an object.');\n        }\n        if (options.getRetryDelay !== undefined && typeof options.getRetryDelay !== 'function') {\n            throw new TypeError('options.getRetryDelay, when provided, must be a function.');\n        }\n        if (options.maxCacheSize !== undefined\n            && (!isNumber(options.maxCacheSize) || options.maxCacheSize < 0)) {\n            throw new TypeError('options.maxCacheSize, when provided, must be a non-negative number.');\n        }\n        if (options.parallelism !== undefined && (!Number.isInteger(options.parallelism) || options.parallelism < 1)) {\n            throw new TypeError('options.parallelism, when provided, must be a positive number.');\n        }\n        if (options.fetchFn !== undefined && typeof options.fetchFn !== 'function') {\n            throw new TypeError('options.fetchFn, when provided, must be a function.');\n            // Won't bother validating this function beyond this\n        }\n        if (options.handleUnhandledError !== undefined && typeof options.handleUnhandledError !== 'function') {\n            throw new TypeError('options.handleUnhandledError, when provided, must be a function.');\n        }\n        const urlString = url instanceof Request\n            ? url.url\n            : url instanceof URL\n                ? url.href\n                : url;\n        super(urlString, request => new UrlSource(request.path, this._options));\n        /** @internal */\n        this._offset = 0;\n        /** @internal */\n        this._length = null;\n        /**\n         * Note that this value being true does NOT mean the file size can't change anymore; it just signals that we have at\n         * least checked if we know the file size or not.\n         * @internal\n         */\n        this._fileSizeDetermined = false;\n        /**\n         * When the server doesn't support range requests, we abandon the orchestrator and instead defer to an internal\n         * ReadableStreamSource wrapping the response body, which pulls new data only when reads demand it.\n         * @internal\n         */\n        this._sequentialBacking = null;\n        /** @internal */\n        this._abortControllers = new Map();\n        /** @internal */\n        this._sequentialAbortController = null;\n        this._url = url;\n        this._options = options;\n        this._getRetryDelay = options.getRetryDelay ?? DEFAULT_RETRY_DELAY;\n        // A user-supplied Range header is interpreted as a byte offset (and optional length) into the resource. We\n        // pull it out of the request and remember it for subsequent requests.\n        this._requestInit = { ...options.requestInit };\n        let rangeHeaderValue = null;\n        if (options.requestInit?.headers) {\n            const headers = { ...normalizeHeaders(options.requestInit.headers) };\n            const rangeKey = Object.keys(headers).find(key => key.toLowerCase() === 'range');\n            if (rangeKey !== undefined) {\n                rangeHeaderValue = headers[rangeKey];\n                delete headers[rangeKey];\n                this._requestInit.headers = headers;\n            }\n        }\n        if (url instanceof Request) {\n            const requestRange = url.headers.get('Range');\n            if (requestRange !== null) {\n                rangeHeaderValue ??= requestRange;\n                // Clone the request so we don't mutate the user's object, then strip the Range header\n                const strippedRequest = new Request(url);\n                strippedRequest.headers.delete('Range');\n                this._url = strippedRequest;\n            }\n        }\n        if (rangeHeaderValue !== null) {\n            const parsed = parseByteRangeHeader(rangeHeaderValue);\n            if (parsed) {\n                this._offset = parsed.offset;\n                this._length = parsed.length;\n            }\n        }\n        // Most files in the real-world have a single sequential access pattern, but having two in parallel can\n        // also happen\n        const DEFAULT_PARALLELISM = 2;\n        this._orchestrator = new ReadOrchestrator({\n            maxCacheSize: options.maxCacheSize ?? (64 * 2 ** 20 /* 64 MiB */),\n            maxWorkerCount: options.parallelism ?? DEFAULT_PARALLELISM,\n            runWorker: this._runWorker.bind(this),\n            onIdleWorkerRemoved: worker => this._abortControllers.delete(worker),\n            prefetchProfile: PREFETCH_PROFILES.network,\n            handleUnhandledError: options.handleUnhandledError,\n        });\n    }\n    /** @internal */\n    _getFileSize() {\n        if (!this._fileSizeDetermined) {\n            return this._length !== null ? this._length : undefined;\n        }\n        const baseSize = this._sequentialBacking\n            ? this._sequentialBacking._endIndex\n            : this._orchestrator.fileSize;\n        if (baseSize === null) {\n            return this._length !== null ? this._length : null;\n        }\n        return clamp(baseSize - this._offset, 0, this._length ?? Infinity);\n    }\n    /** @internal */\n    _read(start, end, minReadPosition, maxReadPosition) {\n        if (this._length !== null && end > this._length) {\n            return null;\n        }\n        const offset = this._offset;\n        const result = this._sequentialBacking\n            ? this._sequentialBacking._read(offset + start, offset + end)\n            : this._orchestrator.read(offset + start, offset + end, Math.max(offset + minReadPosition, offset), offset + Math.min(maxReadPosition, this._length ?? Infinity));\n        const processResult = (result) => {\n            if (!result) {\n                return null;\n            }\n            result.offset -= this._offset;\n            return result;\n        };\n        if (isThenable(result)) {\n            return result.then(processResult);\n        }\n        else {\n            return processResult(result);\n        }\n    }\n    /** @internal */\n    async _runWorker(worker) {\n        // The outer loop is for resuming a request if it dies mid-response\n        while (true) {\n            if (worker.aborted) {\n                // Workers can still get started after disposal, or get aborted while waiting to resume\n                this._orchestrator.signalWorkerStoppedRunning(worker);\n                return;\n            }\n            const abortController = new AbortController();\n            this._abortControllers.set(worker, abortController);\n            const response = await retriedFetch(this._options.fetchFn ?? fetch, this._url, mergeRequestInit(this._requestInit, {\n                headers: {\n                    // Always sending a range request is a good way to probe if the server supports them\n                    Range: `bytes=${worker.currentPos}-`,\n                },\n                signal: abortController.signal,\n            }), this._getRetryDelay, () => abortController.signal.aborted);\n            if (!response.ok) {\n                // eslint-disable-next-line @typescript-eslint/no-base-to-string\n                throw new Error(`Error fetching ${String(this._url)}: ${response.status} ${response.statusText}`);\n            }\n            if (response.redirected) {\n                // Modify our own root path so that future subrequests get made relative to the redirected URL\n                this.rootPath = response.url;\n            }\n            outer: if (this._orchestrator.fileSize === null\n                // Content-Range/Length fields are meaningless if Content-Encoding is present: they count encoded\n                // bytes, while the reader addresses decoded ones. This holds for 206 responses too - some CDNs do\n                // answer range requests with a content coding, stating the compressed total (stupid!)\n                && !response.headers.has('Content-Encoding')\n                // CORS requests may have Content-Encoding but they hide it from us\n                && (response.status === 206 || response.type === 'basic')) {\n                // See if we can deduce the file size from the response\n                const contentRange = response.headers.get('Content-Range');\n                if (contentRange) {\n                    const match = /\\/(\\d+)/.exec(contentRange);\n                    if (match) {\n                        this._orchestrator.supplyFileSize(Number(match[1]));\n                        break outer;\n                    }\n                }\n                const contentLength = response.headers.get('Content-Length');\n                if (contentLength) {\n                    // Note: For range requests, this is _technically_ not correct, as the range response could contain\n                    // less data than was requested. In practice, it seems most servers don't do this though, and the\n                    // Content-Length header actually contains the length until the end of the file.\n                    // A non-206 response always spans the entire resource, no matter what range we asked for.\n                    const basePos = response.status === 206 ? worker.currentPos : 0;\n                    this._orchestrator.supplyFileSize(basePos + Number(contentLength));\n                }\n            }\n            this._fileSizeDetermined = true; // Yes, this is correct even if file size is still null\n            if (!response.body) {\n                throw new Error('Missing HTTP response body stream. The used fetch function must provide the response body as a'\n                    + ' ReadableStream.');\n            }\n            if (response.status !== 206) {\n                if (this._sequentialBacking) {\n                    // Another worker already discovered the missing range request support and initiated the\n                    // transition into sequential mode; this response is of no use anymore\n                    void response.body.cancel().catch(() => { });\n                    return;\n                }\n                if (!this._usedForHls) {\n                    const url = new URL(this._url instanceof Request ? this._url.url : this._url, typeof window !== 'undefined' ? window.location.href : undefined);\n                    if (url.origin !== 'null'\n                        // Don't show the warning for M3U8 playlist files, it's irrelevant for those\n                        && !(url.pathname.endsWith('.m3u8') || url.pathname.endsWith('.m3u'))) {\n                        if (!warnedOrigins.has(url.origin)) {\n                            Logging._warn(`HTTP server (origin ${url.origin}) did not respond to a range request with 206 Partial`\n                                + ' Content, meaning the resource will now be streamed sequentially, with old data'\n                                + ' being evicted from the cache. Reads into evicted regions will throw. To enable'\n                                + ' efficient media file streaming across a network, please make sure your server'\n                                + ' supports range requests. Alternatively, set maxCacheSize to Infinity in the'\n                                + ' UrlSource options to keep the entire resource in memory.');\n                            warnedOrigins.add(url.origin);\n                        }\n                    }\n                }\n                this._abortControllers.delete(worker);\n                this._transitionToSequentialMode(response.body, abortController);\n                return;\n            }\n            const reader = response.body.getReader();\n            while (true) {\n                if (worker.currentPos >= worker.targetPos || worker.aborted) {\n                    abortController.abort();\n                    this._orchestrator.signalWorkerStoppedRunning(worker);\n                    return;\n                }\n                let readResult;\n                try {\n                    readResult = await reader.read();\n                }\n                catch (error) {\n                    if (abortController.signal.aborted) {\n                        // No need to try to retry\n                        throw error;\n                    }\n                    const retryDelayInSeconds = this._getRetryDelay(1, error, this._url);\n                    if (retryDelayInSeconds !== null) {\n                        Logging._error('Error while reading response stream. Attempting to resume.', error);\n                        await wait(1000 * retryDelayInSeconds);\n                        break;\n                    }\n                    else {\n                        throw error;\n                    }\n                }\n                if (worker.aborted) {\n                    continue; // Cleanup happens in next iteration\n                }\n                const { done, value } = readResult;\n                if (done) {\n                    if (worker.currentPos >= worker.targetPos) {\n                        // All data was delivered, we're good\n                        this._orchestrator.onWorkerFinished(worker);\n                        return;\n                    }\n                    if (worker.strictTarget) {\n                        // The response stopped early, before the target. This can happen if server decides to cap range\n                        // requests arbitrarily, even if the request had an uncapped end. In this case, let's fetch the\n                        // rest of the data using a new request.\n                        break;\n                    }\n                    else {\n                        // Assume we have simply reached the end of the resource\n                        this._orchestrator.onWorkerFinished(worker);\n                        return;\n                    }\n                }\n                this._dispatchRead(worker.currentPos, worker.currentPos + value.length);\n                this._orchestrator.supplyWorkerData(worker, value);\n            }\n        }\n        // The previous UrlSource had logic for circumventing https://issues.chromium.org/issues/436025873; I haven't\n        // been able to observe this bug with the new UrlSource (maybe because we're using response streaming), so the\n        // logic for that has vanished for now. Leaving a comment here if this becomes relevant again.\n    }\n    /** @internal */\n    _transitionToSequentialMode(body, abortController) {\n        // The server ignored our range request and is sending the entire resource from byte 0. Instead of downloading\n        // and caching the whole thing, we hand the response over to an internal ReadableStreamSource, which pulls new\n        // data only when reads demand it and evicts old data as usual. The response body is wrapped in a stream that\n        // transparently resumes when the connection dies.\n        this._sequentialAbortController = abortController;\n        let currentReader = body.getReader();\n        let streamPosition = 0;\n        let skipRemaining = 0;\n        const wrappedStream = new ReadableStream({\n            pull: async (controller) => {\n                while (true) {\n                    let readResult;\n                    try {\n                        readResult = await currentReader.read();\n                    }\n                    catch (error) {\n                        if (this._disposed) {\n                            throw error;\n                        }\n                        const retryDelayInSeconds = this._getRetryDelay(1, error, this._url);\n                        if (retryDelayInSeconds === null) {\n                            throw error;\n                        }\n                        Logging._error('Error while reading response stream. Attempting to resume.', error);\n                        await wait(1000 * retryDelayInSeconds);\n                        this._sequentialAbortController = new AbortController();\n                        if (this._disposed) {\n                            this._sequentialAbortController.abort();\n                        }\n                        const newResponse = await retriedFetch(this._options.fetchFn ?? fetch, this._url, mergeRequestInit(this._requestInit, {\n                            headers: {\n                                // Who knows, maybe the server honors range requests this time\n                                Range: `bytes=${streamPosition}-`,\n                            },\n                            signal: this._sequentialAbortController.signal,\n                        }), this._getRetryDelay, () => this._disposed);\n                        if (!newResponse.ok) {\n                            throw new Error(\n                            // eslint-disable-next-line @typescript-eslint/no-base-to-string\n                            `Error fetching ${String(this._url)}:`\n                                + ` ${newResponse.status} ${newResponse.statusText}`);\n                        }\n                        if (!newResponse.body) {\n                            throw new Error('Missing HTTP response body stream. The used fetch function must provide the'\n                                + ' response body as a ReadableStream.');\n                        }\n                        currentReader = newResponse.body.getReader();\n                        // If the server still doesn't do ranges, the new response starts at byte 0 again and\n                        // we need to skip over everything we already delivered. Cursed!\n                        skipRemaining = newResponse.status === 206 ? 0 : streamPosition;\n                        continue;\n                    }\n                    if (readResult.done) {\n                        controller.close();\n                        return;\n                    }\n                    let chunk = readResult.value;\n                    if (skipRemaining > 0) {\n                        const skippedAmount = Math.min(skipRemaining, chunk.length);\n                        skipRemaining -= skippedAmount;\n                        chunk = chunk.subarray(skippedAmount);\n                    }\n                    if (chunk.length === 0) {\n                        continue;\n                    }\n                    streamPosition += chunk.length;\n                    controller.enqueue(chunk);\n                    return;\n                }\n            },\n            cancel: () => currentReader.cancel().catch(() => { }),\n        });\n        const backing = new ReadableStreamSource(wrappedStream, {\n            maxCacheSize: this._orchestrator.options.maxCacheSize,\n            handleUnhandledError: this._options.handleUnhandledError,\n        });\n        backing._endIndex = this._orchestrator.fileSize; // Might still be null\n        backing._cacheMissErrorMessage = 'Attempted to read data from an already-evicted part of the cache. Because the'\n            + ' HTTP server did not honor the range request, data can only be read sequentially, with old data being'\n            + ' evicted from the cache. To fix this issue, either ensure your server responds to range requests with'\n            + ' 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter'\n            + ' will store the entire file in the cache if needed, no matter how large.';\n        backing.on('read', ({ start, end }) => this._dispatchRead(start, end));\n        this._sequentialBacking = backing;\n        // Everything still pending in the orchestrator must now be served by the backing instead. Gather all\n        // pending slices, then retire the orchestrator's workers and queued reads for good; _read will only\n        // consult the backing from now on.\n        const uniqueSlices = new Set();\n        for (const otherWorker of this._orchestrator.workers) {\n            for (const slice of otherWorker.pendingSlices) {\n                uniqueSlices.add(slice);\n            }\n            otherWorker.aborted = true;\n            otherWorker.pendingSlices.length = 0;\n        }\n        for (const queuedRead of this._orchestrator.queuedReads) {\n            for (const slice of queuedRead.pendingSlices) {\n                uniqueSlices.add(slice);\n            }\n        }\n        this._orchestrator.workers.length = 0;\n        this._orchestrator.queuedReads.length = 0;\n        for (const [, otherAbortController] of this._abortControllers) {\n            otherAbortController.abort();\n        }\n        this._abortControllers.clear();\n        for (const slice of uniqueSlices) {\n            const result = backing._read(slice.start, slice.start + slice.bytes.length);\n            if (isThenable(result)) {\n                result.then((readResult) => {\n                    if (readResult) {\n                        // The backing's cache is empty at this point, so the read is guaranteed to produce\n                        // exactly the requested range\n                        assert(readResult.offset === slice.start);\n                        slice.resolve(readResult.bytes);\n                    }\n                    else {\n                        slice.resolve(null);\n                    }\n                }, (error) => slice.reject(error));\n            }\n            else {\n                // Can only happen synchronously when the slice lies beyond the known file size\n                assert(result === null);\n                slice.resolve(null);\n            }\n        }\n    }\n    /** @internal */\n    _dispose() {\n        this._orchestrator.dispose();\n        for (const [, abortController] of this._abortControllers) {\n            abortController.abort();\n        }\n        this._abortControllers.clear();\n        this._sequentialAbortController?.abort();\n        if (this._sequentialBacking) {\n            this._sequentialBacking._disposed = true;\n            this._sequentialBacking._dispose();\n        }\n    }\n}\nconst BYTE_RANGE_REGEX = /^bytes=(\\d+)-(\\d*)$/;\nconst parseByteRangeHeader = (value) => {\n    const match = BYTE_RANGE_REGEX.exec(value.trim());\n    if (!match) {\n        return null;\n    }\n    const offset = Number(match[1]);\n    const end = match[2] === '' ? null : Number(match[2]);\n    if (end !== null && end < offset) {\n        return null;\n    }\n    return {\n        offset,\n        length: end !== null ? end - offset + 1 : null,\n    };\n};\n/**\n * A source backed by a path to a file. Intended for server-side usage in Node, Bun, or Deno.\n *\n * Make sure to call `.dispose()` on the corresponding {@link Input} when done to explicitly free the internal file\n * handle acquired by this source.\n * @group Input sources\n * @public\n */\nexport class FilePathSource extends PathedSource {\n    /** Creates a new {@link FilePathSource} backed by the file at the specified file path. */\n    constructor(filePath, options = {}) {\n        if (typeof filePath !== 'string') {\n            throw new TypeError('filePath must be a string.');\n        }\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.maxCacheSize !== undefined\n            && (!isNumber(options.maxCacheSize) || options.maxCacheSize < 0)) {\n            throw new TypeError('options.maxCacheSize, when provided, must be a non-negative number.');\n        }\n        if (!node.fs) {\n            throw new Error('FilePathSource is only available in server-side environments (Node.js, Bun, Deno).');\n        }\n        super(filePath, request => new FilePathSource(request.path, options));\n        /** @internal */\n        this._fileHandle = null;\n        // Let's back this source with a CustomSource, makes the implementation very simple\n        this._customSource = new CustomSource({\n            getSize: async () => {\n                const fileHandle = await node.fs.open(filePath, 'r');\n                this._fileHandle = fileHandle;\n                sourceFinalizationRegistry?.register(this, () => {\n                    // If it's not closed, Node prints annoying warnings\n                    void fileHandle.close();\n                }, this);\n                const stats = await fileHandle.stat();\n                return stats.size;\n            },\n            read: async (start, end) => {\n                assert(this._fileHandle);\n                const buffer = new Uint8Array(end - start);\n                await this._fileHandle.read(buffer, 0, end - start, start);\n                return buffer;\n            },\n            maxCacheSize: options.maxCacheSize,\n            prefetchProfile: 'fileSystem',\n            handleUnhandledError: options.handleUnhandledError,\n        });\n    }\n    /** @internal */\n    _read(start, end, minReadPosition, maxReadPosition) {\n        return this._customSource._read(start, end, minReadPosition, maxReadPosition);\n    }\n    /** @internal */\n    _getFileSize() {\n        return this._customSource._getFileSize();\n    }\n    /** @internal */\n    _dispose() {\n        this._customSource._dispose();\n        if (this._fileHandle) {\n            void this._fileHandle.close();\n            this._fileHandle = null;\n            sourceFinalizationRegistry?.unregister(this);\n        }\n    }\n}\n/**\n * A general-purpose, callback-driven source that can get its data from anywhere. Use this source to implement your own\n * custom source if the other sources don't cover your case.\n * @group Input sources\n * @public\n */\nexport class CustomSource extends Source {\n    /** Creates a new {@link CustomSource} whose behavior is specified by `options`.  */\n    constructor(options) {\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (typeof options.getSize !== 'function') {\n            throw new TypeError('options.getSize must be a function.');\n        }\n        if (typeof options.read !== 'function') {\n            throw new TypeError('options.read must be a function.');\n        }\n        if (options.dispose !== undefined && typeof options.dispose !== 'function') {\n            throw new TypeError('options.dispose, when provided, must be a function.');\n        }\n        if (options.handleUnhandledError !== undefined && typeof options.handleUnhandledError !== 'function') {\n            throw new TypeError('options.handleUnhandledError, when provided, must be a function.');\n        }\n        if (options.maxCacheSize !== undefined\n            && (!isNumber(options.maxCacheSize) || options.maxCacheSize < 0)) {\n            throw new TypeError('options.maxCacheSize, when provided, must be a non-negative number.');\n        }\n        if (options.prefetchProfile && !['none', 'fileSystem', 'network'].includes(options.prefetchProfile)) {\n            throw new TypeError('options.prefetchProfile, when provided, must be one of \\'none\\', \\'fileSystem\\' or \\'network\\'.');\n        }\n        super();\n        /** @internal */\n        this._readers = new Set();\n        this._options = options;\n        this._orchestrator = new ReadOrchestrator({\n            maxCacheSize: options.maxCacheSize ?? (8 * 2 ** 20 /* 8 MiB */),\n            maxWorkerCount: 2, // Fixed for now, *should* be fine\n            prefetchProfile: PREFETCH_PROFILES[options.prefetchProfile ?? 'none'],\n            runWorker: this._runWorker.bind(this),\n            handleUnhandledError: options.handleUnhandledError,\n        });\n    }\n    /** @internal */\n    _getFileSize() {\n        return this._orchestrator.fileSize ?? undefined;\n    }\n    /** @internal */\n    _read(start, end, minReadPosition, maxReadPosition) {\n        if (this._orchestrator.fileSize !== null) {\n            return this._orchestrator.read(start, end, minReadPosition, maxReadPosition);\n        }\n        const result = this._options.getSize();\n        if (isThenable(result)) {\n            return result.then((size) => {\n                if (!Number.isInteger(size) || size < 0) {\n                    throw new TypeError('options.getSize must return or resolve to a non-negative integer.');\n                }\n                if (this._disposed) {\n                    throw new InputDisposedError();\n                }\n                this._orchestrator.fileSize = size;\n                if (end > size) {\n                    return null; // Now that we know the size, it turns out the read doesn't fit\n                }\n                return this._orchestrator.read(start, end, minReadPosition, maxReadPosition);\n            });\n        }\n        else {\n            if (!Number.isInteger(result) || result < 0) {\n                throw new TypeError('options.getSize must return or resolve to a non-negative integer.');\n            }\n            this._orchestrator.fileSize = result;\n            if (end > result) {\n                return null;\n            }\n            return this._orchestrator.read(start, end, minReadPosition, maxReadPosition);\n        }\n    }\n    /** @internal */\n    async _runWorker(worker) {\n        while (worker.currentPos < worker.targetPos && !worker.aborted) {\n            const originalCurrentPos = worker.currentPos;\n            const originalTargetPos = worker.targetPos;\n            let data = this._options.read(worker.currentPos, originalTargetPos);\n            if (isThenable(data))\n                data = await data;\n            if (worker.aborted) {\n                if (data instanceof ReadableStream) {\n                    await data.cancel().catch(() => { });\n                }\n                break;\n            }\n            if (data instanceof Uint8Array) {\n                data = toUint8Array(data); // Normalize things like Node.js Buffer to Uint8Array\n                if (data.length !== originalTargetPos - worker.currentPos) {\n                    // Yes, we're that strict\n                    throw new Error(`options.read returned a Uint8Array with unexpected length: Requested ${originalTargetPos - worker.currentPos} bytes, but got ${data.length}.`);\n                }\n                this._dispatchRead(worker.currentPos, worker.currentPos + data.length);\n                this._orchestrator.supplyWorkerData(worker, data);\n            }\n            else if (data instanceof ReadableStream) {\n                const reader = data.getReader();\n                this._readers.add(reader);\n                try {\n                    while (worker.currentPos < originalTargetPos && !worker.aborted) {\n                        const { done, value } = await reader.read();\n                        if (done) {\n                            if (worker.currentPos < originalTargetPos) {\n                                // Yes, we're *that* strict\n                                throw new Error(`ReadableStream returned by options.read ended before supplying enough data.`\n                                    + ` Requested ${originalTargetPos - originalCurrentPos} bytes, but got ${worker.currentPos - originalCurrentPos}`);\n                            }\n                            break;\n                        }\n                        if (!(value instanceof Uint8Array)) {\n                            throw new TypeError('ReadableStream returned by options.read must yield Uint8Array chunks.');\n                        }\n                        if (worker.aborted) {\n                            break;\n                        }\n                        const data = toUint8Array(value); // Normalize things like Node.js Buffer to Uint8Array\n                        this._dispatchRead(worker.currentPos, worker.currentPos + data.length);\n                        this._orchestrator.supplyWorkerData(worker, data);\n                    }\n                }\n                finally {\n                    this._readers.delete(reader);\n                    reader.releaseLock();\n                }\n            }\n            else {\n                throw new TypeError('options.read must return or resolve to a Uint8Array or a ReadableStream.');\n            }\n        }\n        this._orchestrator.signalWorkerStoppedRunning(worker);\n    }\n    /** @internal */\n    _dispose() {\n        this._orchestrator.dispose();\n        for (const reader of this._readers) {\n            // Pending consumers have already been rejected with InputDisposedError\n            void reader.cancel().catch(() => { });\n        }\n        this._readers.clear();\n        this._options.dispose?.();\n    }\n}\n/**\n * An alias for {@link CustomSource}.\n * @deprecated This name is misleading and will be removed in a future release. Please use {@link CustomSource} instead.\n *\n * @group Input sources\n * @public\n */\nexport const StreamSource = CustomSource;\n/**\n * A source backed by a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) of\n * `Uint8Array`, representing an append-only byte stream of unknown length. This is the source to use for incrementally\n * streaming in input files that are still being constructed and whose size we don't yet know, like for example the\n * output chunks of [MediaRecorder](https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder).\n *\n * This source is *unsized*, meaning calls to `.getSize()` will throw and readers are more limited due to the\n * lack of random file access. You should only use this source with sequential access patterns, such as reading all\n * packets from start to end. This source does not work well with random access patterns unless you increase its\n * max cache size.\n *\n * @group Input sources\n * @public\n */\nexport class ReadableStreamSource extends Source {\n    /** Creates a new {@link ReadableStreamSource} backed by the specified `ReadableStream<Uint8Array>`. */\n    constructor(stream, options = {}) {\n        if (!(stream instanceof ReadableStream)) {\n            throw new TypeError('stream must be a ReadableStream.');\n        }\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.handleUnhandledError !== undefined && typeof options.handleUnhandledError !== 'function') {\n            throw new TypeError('options.handleUnhandledError, when provided, must be a function.');\n        }\n        if (options.maxCacheSize !== undefined\n            && (!isNumber(options.maxCacheSize) || options.maxCacheSize < 0)) {\n            throw new TypeError('options.maxCacheSize, when provided, must be a non-negative number.');\n        }\n        super();\n        /** @internal */\n        this._reader = null;\n        /** @internal */\n        this._cache = [];\n        /** @internal */\n        this._pendingSlices = [];\n        /** @internal */\n        this._currentIndex = 0;\n        /** @internal */\n        this._targetIndex = 0;\n        /** @internal */\n        this._maxRequestedIndex = 0;\n        /** @internal */\n        this._endIndex = null;\n        /** @internal */\n        this._pulling = false;\n        /**\n         * Overridable for internal use.\n         * @internal\n         */\n        this._cacheMissErrorMessage = 'Attempted to read data from an already-evicted part of the cache. With'\n            + ' ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.';\n        this._stream = stream;\n        this._maxCacheSize = options.maxCacheSize ?? (32 * 2 ** 20 /* 32 MiB */);\n        this._handleUnhandledError = options.handleUnhandledError;\n    }\n    /** @internal */\n    _getFileSize() {\n        return this._endIndex; // Starts out as null, meaning this source is unsized\n    }\n    /** @internal */\n    _read(start, end) {\n        if (this._endIndex !== null && end > this._endIndex) {\n            return null;\n        }\n        this._maxRequestedIndex = Math.max(this._maxRequestedIndex, end);\n        const cacheStartIndex = binarySearchLessOrEqual(this._cache, start, x => x.start);\n        const cacheStartEntry = cacheStartIndex !== -1 ? this._cache[cacheStartIndex] : null;\n        if (cacheStartEntry && cacheStartEntry.start <= start && end <= cacheStartEntry.end) {\n            // The request can be satisfied with a single cache entry\n            return {\n                bytes: cacheStartEntry.bytes,\n                view: cacheStartEntry.view,\n                offset: cacheStartEntry.start,\n            };\n        }\n        let lastEnd = start;\n        const parts = [];\n        if (cacheStartIndex !== -1) {\n            // Walk over the cache to see if we can satisfy the request using multiple cache entries\n            for (let i = cacheStartIndex; i < this._cache.length; i++) {\n                const cacheEntry = this._cache[i];\n                if (cacheEntry.start >= end) {\n                    break;\n                }\n                const cappedStart = Math.max(start, cacheEntry.start);\n                if (cappedStart > lastEnd) {\n                    // We're too far behind\n                    this._throwDueToCacheMiss();\n                }\n                const cappedEnd = Math.min(end, cacheEntry.end);\n                if (cappedStart < cappedEnd) {\n                    parts.push({\n                        start: cappedStart,\n                        bytes: cacheEntry.bytes.subarray(cappedStart - cacheEntry.start, cappedEnd - cacheEntry.start),\n                    });\n                    lastEnd = cappedEnd;\n                }\n            }\n        }\n        if (lastEnd === end) {\n            return assembleSlice(start, end, parts);\n        }\n        // We need to pull more data\n        if (this._currentIndex > lastEnd) {\n            // We're too far behind\n            this._throwDueToCacheMiss();\n        }\n        const { promise, resolve, reject } = promiseWithResolvers();\n        this._pendingSlices.push({\n            start,\n            end,\n            parts,\n            resolve,\n            reject,\n        });\n        this._targetIndex = Math.max(this._targetIndex, end);\n        // Start pulling from the stream if we're not already doing it\n        if (!this._pulling) {\n            this._pulling = true;\n            void this._pull()\n                .catch((error) => {\n                this._pulling = false;\n                if (this._pendingSlices.length > 0) {\n                    this._pendingSlices.forEach(x => x.reject(error)); // Make sure to propagate any errors\n                    this._pendingSlices.length = 0;\n                }\n                else if (this._handleUnhandledError) {\n                    this._handleUnhandledError(error);\n                }\n                else {\n                    throw error; // So it doesn't get swallowed\n                }\n            });\n        }\n        return promise;\n    }\n    /** @internal */\n    _throwDueToCacheMiss() {\n        throw new Error(this._cacheMissErrorMessage);\n    }\n    /** @internal */\n    async _pull() {\n        this._reader ??= this._stream.getReader();\n        // This is the loop that keeps pulling data from the stream until a target index is reached, filling requests\n        // in the process\n        while (this._currentIndex < this._targetIndex && !this._disposed) {\n            const { done, value } = await this._reader.read();\n            if (done) {\n                for (const pendingSlice of this._pendingSlices) {\n                    pendingSlice.resolve(null);\n                }\n                this._pendingSlices.length = 0;\n                this._endIndex = this._currentIndex; // We know how long the file is now!\n                break;\n            }\n            const startIndex = this._currentIndex;\n            const endIndex = this._currentIndex + value.byteLength;\n            this._dispatchRead(startIndex, endIndex);\n            // Fill the pending slices with the data\n            for (let i = 0; i < this._pendingSlices.length; i++) {\n                const pendingSlice = this._pendingSlices[i];\n                const cappedStart = Math.max(startIndex, pendingSlice.start);\n                const cappedEnd = Math.min(endIndex, pendingSlice.end);\n                if (cappedStart < cappedEnd) {\n                    pendingSlice.parts.push({\n                        start: cappedStart,\n                        bytes: value.subarray(cappedStart - startIndex, cappedEnd - startIndex),\n                    });\n                    if (cappedEnd === pendingSlice.end) {\n                        // Pending slice fully filled. Assembling only at the end protects us from attacks where huge\n                        // data ranges are requested, despite those never being fulfillable.\n                        pendingSlice.resolve(assembleSlice(pendingSlice.start, pendingSlice.end, pendingSlice.parts));\n                        this._pendingSlices.splice(i, 1);\n                        i--;\n                    }\n                }\n            }\n            this._cache.push({\n                start: startIndex,\n                end: endIndex,\n                bytes: value,\n                view: toDataView(value),\n                age: 0, // Unused\n            });\n            // Do cache eviction, based on the distance from the last-requested index. It's important that we do it like\n            // this and not based on how far we've pulled the stream, because if the stream supplies data faster than it\n            // is being requested, we'd unnecessarily evict data that we still might need.\n            while (this._cache.length > 0) {\n                const firstEntry = this._cache[0];\n                const distance = this._maxRequestedIndex - firstEntry.end;\n                if (distance <= this._maxCacheSize) {\n                    break;\n                }\n                this._cache.shift();\n            }\n            this._currentIndex += value.byteLength;\n        }\n        this._pulling = false;\n    }\n    /** @internal */\n    _dispose() {\n        for (const pendingSlice of this._pendingSlices) {\n            pendingSlice.reject(new InputDisposedError());\n        }\n        this._pendingSlices.length = 0;\n        this._cache.length = 0;\n        void this._reader?.cancel().catch(() => { });\n    }\n}\nconst assembleSlice = (start, end, parts) => {\n    const bytes = new Uint8Array(end - start);\n    for (const part of parts) {\n        bytes.set(part.bytes, part.start - start);\n    }\n    return {\n        bytes,\n        view: toDataView(bytes),\n        offset: start,\n    };\n};\nconst PREFETCH_PROFILES = {\n    none: (start, end) => ({ start, end }),\n    fileSystem: (start, end) => {\n        const padding = 2 ** 16;\n        start = Math.floor((start - padding) / padding) * padding;\n        end = Math.ceil((end + padding) / padding) * padding;\n        return { start, end };\n    },\n    network: (start, end, workers) => {\n        // Add a slight bit of start padding because backwards reading is painful\n        const paddingStart = 2 ** 16;\n        start = Math.max(0, Math.floor((start - paddingStart) / paddingStart) * paddingStart);\n        // Remote resources have extreme latency (relatively speaking), so the benefit from intelligent\n        // prefetching is great. The network prefetch strategy is as follows: When we notice\n        // successive reads to a worker's read region, we prefetch more data at the end of that region,\n        // growing exponentially (up to a cap). This performs well for real-world use cases: Either we read a\n        // small part of the file once and then never need it again, in which case the requested about of data\n        // is small. Or, we're repeatedly doing a sequential access pattern (common in media files), in which\n        // case we can become more and more confident to prefetch more and more data.\n        for (const worker of workers) {\n            const maxExtensionAmount = 8 * 2 ** 20; // 8 MiB\n            // When the read region cross the threshold point, we trigger a prefetch. This point is typically\n            // in the middle of the worker's read region, or a fixed offset from the end if the region has grown\n            // really large.\n            const thresholdPoint = Math.max((worker.startPos + worker.targetPos) / 2, worker.targetPos - maxExtensionAmount);\n            if (closedIntervalsOverlap(start, end, thresholdPoint, worker.targetPos)) {\n                const size = worker.targetPos - worker.startPos;\n                // If we extend by maxExtensionAmount\n                const a = Math.ceil((size + 1) / maxExtensionAmount) * maxExtensionAmount;\n                // If we extend to the next power of 2\n                const b = 2 ** Math.ceil(Math.log2(size + 1));\n                const extent = Math.min(b, a);\n                end = Math.max(end, worker.startPos + extent);\n            }\n        }\n        end = Math.max(end, start + URL_SOURCE_MIN_LOAD_AMOUNT);\n        return {\n            start,\n            end,\n        };\n    },\n};\n/**\n * Godclass for orchestrating complex, cached read operations. The reading model is as follows: Any reading task is\n * delegated to a *worker*, which is a sequential reader positioned somewhere along the file. All workers run in\n * parallel and can be stopped and resumed in their forward movement. When read requests come in, this orchestrator will\n * first try to satisfy the request with only the cached data. If this isn't possible, workers are spun up for all\n * missing parts (or existing workers are repurposed), and these workers will then fill the holes in the data as they\n * march along the file.\n */\nclass ReadOrchestrator {\n    constructor(options) {\n        this.options = options;\n        this.fileSize = null;\n        this.nextAge = 0; // Used for multiple things\n        this.workers = [];\n        this.cache = [];\n        this.currentCacheSize = 0;\n        this.disposed = false;\n        this.queuedReads = [];\n    }\n    read(innerStart, innerEnd, minReadPosition, maxReadPosition) {\n        assert(!this.disposed);\n        const prefetchRange = this.options.prefetchProfile(innerStart, innerEnd, this.workers);\n        const outerStart = Math.max(prefetchRange.start, minReadPosition);\n        const outerEnd = Math.min(prefetchRange.end, this.fileSize ?? Infinity, maxReadPosition);\n        assert(outerStart <= innerStart && innerEnd <= outerEnd);\n        let result = null;\n        const innerCacheStartIndex = binarySearchLessOrEqual(this.cache, innerStart, x => x.start);\n        const innerStartEntry = innerCacheStartIndex !== -1 ? this.cache[innerCacheStartIndex] : null;\n        // See if the read request can be satisfied by a single cache entry\n        if (innerStartEntry && innerStartEntry.start <= innerStart && innerEnd <= innerStartEntry.end) {\n            innerStartEntry.age = this.nextAge++;\n            result = {\n                bytes: innerStartEntry.bytes,\n                view: innerStartEntry.view,\n                offset: innerStartEntry.start,\n            };\n            // Can't return yet though, still need to check if the prefetch range might lie outside the cached area\n        }\n        const outerCacheStartIndex = binarySearchLessOrEqual(this.cache, outerStart, x => x.start);\n        const bytes = result ? null : new Uint8Array(innerEnd - innerStart);\n        let contiguousBytesWriteEnd = 0; // Used to track if the cache is able to completely cover the bytes\n        let lastEnd = outerStart;\n        // The \"holes\" in the cache (the parts we need to load)\n        const outerHoles = [];\n        // Loop over the cache and build up the list of holes\n        if (outerCacheStartIndex !== -1) {\n            for (let i = outerCacheStartIndex; i < this.cache.length; i++) {\n                const entry = this.cache[i];\n                if (entry.start >= outerEnd) {\n                    break;\n                }\n                if (entry.end <= outerStart) {\n                    continue;\n                }\n                const cappedOuterStart = Math.max(outerStart, entry.start);\n                const cappedOuterEnd = Math.min(outerEnd, entry.end);\n                assert(cappedOuterStart <= cappedOuterEnd);\n                if (lastEnd < cappedOuterStart) {\n                    outerHoles.push({ start: lastEnd, end: cappedOuterStart });\n                }\n                lastEnd = cappedOuterEnd;\n                if (bytes) {\n                    const cappedInnerStart = Math.max(innerStart, entry.start);\n                    const cappedInnerEnd = Math.min(innerEnd, entry.end);\n                    if (cappedInnerStart < cappedInnerEnd) {\n                        const relativeOffset = cappedInnerStart - innerStart;\n                        // Fill the relevant section of the bytes with the cached data\n                        bytes.set(entry.bytes.subarray(cappedInnerStart - entry.start, cappedInnerEnd - entry.start), relativeOffset);\n                        if (relativeOffset === contiguousBytesWriteEnd) {\n                            contiguousBytesWriteEnd = cappedInnerEnd - innerStart;\n                        }\n                    }\n                }\n                entry.age = this.nextAge++;\n            }\n            if (lastEnd < outerEnd) {\n                outerHoles.push({ start: lastEnd, end: outerEnd });\n            }\n        }\n        else {\n            outerHoles.push({ start: outerStart, end: outerEnd });\n        }\n        if (bytes && contiguousBytesWriteEnd >= bytes.length) {\n            // Multiple cache entries were able to completely cover the requested bytes!\n            result = {\n                bytes,\n                view: toDataView(bytes),\n                offset: innerStart,\n            };\n        }\n        if (outerHoles.length === 0) {\n            assert(result);\n            return result;\n        }\n        // We need to read more data, so now we're in async land\n        const { promise, resolve, reject } = promiseWithResolvers();\n        const innerHoles = [];\n        for (const outerHole of outerHoles) {\n            const cappedStart = Math.max(innerStart, outerHole.start);\n            const cappedEnd = Math.min(innerEnd, outerHole.end);\n            if (cappedStart === outerHole.start && cappedEnd === outerHole.end) {\n                innerHoles.push(outerHole); // Can reuse without allocating a new object\n            }\n            else if (cappedStart < cappedEnd) {\n                innerHoles.push({ start: cappedStart, end: cappedEnd });\n            }\n        }\n        const pendingSlice = bytes && {\n            start: innerStart,\n            bytes,\n            holes: innerHoles,\n            resolve,\n            reject,\n        };\n        // Fire off workers to take care of patching the holes\n        outer: for (const outerHole of outerHoles) {\n            for (const worker of this.workers) {\n                const addedToWorker = this.checkHoleAgainstWorker(worker, outerHole, pendingSlice ? [pendingSlice] : []);\n                if (addedToWorker) {\n                    this.checkQueuedReadsAgainstWorker(worker);\n                    continue outer;\n                }\n            }\n            // We need to spawn a new worker\n            const strictTarget = outerHole.end < outerEnd || this.fileSize !== null;\n            const newWorker = this.createWorker(outerHole.start, outerHole.end, strictTarget);\n            if (newWorker) {\n                if (pendingSlice) {\n                    newWorker.pendingSlices = [pendingSlice];\n                }\n                this.runWorker(newWorker);\n            }\n            else {\n                // Max worker count has been reached, let's queue a read for later\n                let index = binarySearchLessOrEqual(this.queuedReads, outerHole.start, x => x.hole.start);\n                let entry = index !== -1\n                    ? this.queuedReads[index]\n                    : null;\n                if (entry && outerHole.start <= entry.hole.end) {\n                    entry.hole.end = Math.max(entry.hole.end, outerHole.end);\n                    entry.strictTarget &&= strictTarget;\n                    if (pendingSlice) {\n                        entry.pendingSlices.push(pendingSlice);\n                    }\n                }\n                else {\n                    index++;\n                    entry = {\n                        hole: {\n                            // Clone the hole because it might be mutated later\n                            start: outerHole.start,\n                            end: outerHole.end,\n                        },\n                        strictTarget,\n                        pendingSlices: pendingSlice ? [pendingSlice] : [],\n                        age: this.nextAge++,\n                    };\n                    this.queuedReads.splice(index, 0, entry);\n                }\n                // Merge with any subsequent entries that overlap\n                while (index + 1 < this.queuedReads.length) {\n                    const nextEntry = this.queuedReads[index + 1];\n                    if (nextEntry.hole.start > entry.hole.end) {\n                        break;\n                    }\n                    entry.hole.end = Math.max(entry.hole.end, nextEntry.hole.end);\n                    entry.pendingSlices.push(...nextEntry.pendingSlices);\n                    entry.strictTarget &&= nextEntry.strictTarget;\n                    entry.age = Math.min(entry.age, nextEntry.age);\n                    this.queuedReads.splice(index + 1, 1);\n                }\n            }\n        }\n        if (!result) {\n            assert(bytes);\n            result = promise.then(bytes => bytes && {\n                bytes,\n                view: toDataView(bytes),\n                offset: innerStart,\n            });\n        }\n        else {\n            // The requested region was satisfied by the cache, but the entire prefetch region was not\n            promise.catch((error) => {\n                if (this.disposed) {\n                    return; // Swallow the error\n                }\n                // Nobody's awaiting this result but an errored read is still notable\n                if (this.options.handleUnhandledError) {\n                    this.options.handleUnhandledError(error);\n                }\n                else {\n                    throw error;\n                }\n            });\n        }\n        return result;\n    }\n    checkHoleAgainstWorker(worker, hole, pendingSlices) {\n        // A small tolerance in the case that the requested region is *just* after the target position of an\n        // existing worker. In that case, it's probably more efficient to repurpose that worker than to spawn\n        // another one so close to it\n        const gapTolerance = 2 ** 17;\n        // This check also implies worker.currentPos <= hole.start, a critical condition\n        if (closedIntervalsOverlap(hole.start - gapTolerance, hole.start, worker.currentPos, worker.targetPos)) {\n            worker.targetPos = Math.max(worker.targetPos, hole.end); // Update the worker's target position\n            for (let i = 0; i < pendingSlices.length; i++) {\n                const pendingSlice = pendingSlices[i];\n                if (!worker.pendingSlices.includes(pendingSlice)) {\n                    worker.pendingSlices.push(pendingSlice);\n                }\n            }\n            if (!worker.running) {\n                // Kick it off if it's idle\n                this.runWorker(worker);\n            }\n            return true;\n        }\n        return false;\n    }\n    checkQueuedReadsAgainstWorker(worker) {\n        let wasTrueOnce = false;\n        for (let i = 0; i < this.queuedReads.length; i++) {\n            const queuedRead = this.queuedReads[i];\n            const result = this.checkHoleAgainstWorker(worker, queuedRead.hole, queuedRead.pendingSlices);\n            if (result) {\n                this.queuedReads.splice(i, 1);\n                i--;\n                wasTrueOnce = true;\n            }\n            else if (wasTrueOnce) {\n                // We can stop since the holes are sorted\n                break;\n            }\n        }\n    }\n    createWorker(startPos, targetPos, strictTarget) {\n        if (this.workers.length >= this.options.maxWorkerCount) {\n            let oldestWorker = null;\n            let oldestIndex = null;\n            for (let i = 0; i < this.workers.length; i++) {\n                const worker = this.workers[i];\n                if (!worker.running\n                    && worker.pendingSlices.length === 0\n                    && (!oldestWorker || worker.age < oldestWorker.age)) {\n                    oldestIndex = i;\n                    oldestWorker = worker;\n                }\n            }\n            if (oldestWorker) {\n                // LRU eviction\n                assert(oldestIndex !== null);\n                assert(oldestWorker.pendingSlices.length === 0);\n                this.workers.splice(oldestIndex, 1);\n                this.options.onIdleWorkerRemoved?.(oldestWorker);\n            }\n            else {\n                return null; // All workers are still running, we can't create a new one\n            }\n        }\n        const worker = {\n            startPos,\n            currentPos: startPos,\n            targetPos,\n            strictTarget,\n            running: false,\n            // Due to async shenanigans, it can happen that workers are started after disposal. In this case, instead of\n            // simply not creating the worker, we allow it to run but immediately label it as aborted, so it can then\n            // shut itself down.\n            aborted: this.disposed,\n            pendingSlices: [],\n            age: this.nextAge++,\n        };\n        this.workers.push(worker);\n        return worker;\n    }\n    runWorker(worker) {\n        assert(!worker.running);\n        assert(worker.currentPos < worker.targetPos);\n        worker.running = true;\n        worker.age = this.nextAge++;\n        void this.options.runWorker(worker)\n            .catch((error) => {\n            worker.running = false;\n            if (worker.pendingSlices.length > 0) {\n                worker.pendingSlices.forEach(x => x.reject(error)); // Make sure to propagate any errors\n                worker.pendingSlices.length = 0;\n            }\n            else if (!worker.aborted && !this.disposed) {\n                if (this.options.handleUnhandledError) {\n                    this.options.handleUnhandledError(error);\n                }\n                else {\n                    throw error; // So it doesn't get swallowed\n                }\n            }\n        })\n            .finally(() => {\n            if (worker.running) {\n                // Rare, but can happen with multiple concurrent reads. In this case, don't do anything.\n                return;\n            }\n            if (this.queuedReads.length > 0) {\n                let oldestIndex = 0;\n                for (let i = 1; i < this.queuedReads.length; i++) {\n                    const queuedRead = this.queuedReads[i];\n                    if (queuedRead.age < this.queuedReads[oldestIndex].age) {\n                        oldestIndex = i;\n                    }\n                }\n                const queuedRead = this.queuedReads[oldestIndex];\n                const newWorker = this.createWorker(queuedRead.hole.start, queuedRead.hole.end, queuedRead.strictTarget);\n                if (!newWorker) {\n                    // In high-contention cases, it could be that we've already reached max worker count, so in this\n                    // case we don't do anything.\n                    return;\n                }\n                this.queuedReads.splice(oldestIndex, 1);\n                newWorker.pendingSlices = queuedRead.pendingSlices;\n                this.runWorker(newWorker);\n            }\n        });\n    }\n    /** Called by a worker when it has read some data. */\n    supplyWorkerData(worker, bytes) {\n        assert(!worker.aborted);\n        const start = worker.currentPos;\n        const end = start + bytes.length;\n        this.insertIntoCache({\n            start,\n            end,\n            bytes,\n            view: toDataView(bytes),\n            age: this.nextAge++,\n        });\n        worker.currentPos += bytes.length;\n        if (worker.currentPos > worker.targetPos) {\n            // In case it overshoots\n            worker.targetPos = worker.currentPos;\n            this.checkQueuedReadsAgainstWorker(worker);\n        }\n        // Now, let's see if we can use the read bytes to fill any pending slice\n        for (let i = 0; i < worker.pendingSlices.length; i++) {\n            const pendingSlice = worker.pendingSlices[i];\n            const clampedStart = Math.max(start, pendingSlice.start);\n            const clampedEnd = Math.min(end, pendingSlice.start + pendingSlice.bytes.length);\n            if (clampedStart < clampedEnd) {\n                pendingSlice.bytes.set(bytes.subarray(clampedStart - start, clampedEnd - start), clampedStart - pendingSlice.start);\n            }\n            for (let j = 0; j < pendingSlice.holes.length; j++) {\n                // The hole is intentionally not modified here if the read section starts somewhere in the middle of\n                // the hole. We don't need to do \"hole splitting\", since the workers are spawned *by* the holes,\n                // meaning there's always a worker which will consume the hole left to right.\n                const hole = pendingSlice.holes[j];\n                if (start <= hole.start && end > hole.start) {\n                    hole.start = end;\n                }\n                if (hole.end <= hole.start) {\n                    pendingSlice.holes.splice(j, 1);\n                    j--;\n                }\n            }\n            if (pendingSlice.holes.length === 0) {\n                // The slice has been fulfilled, everything has been read. Let's resolve the promise\n                pendingSlice.resolve(pendingSlice.bytes);\n                worker.pendingSlices.splice(i, 1);\n                i--;\n            }\n        }\n        // Remove other idle workers if we \"ate\" into their territory\n        for (let i = 0; i < this.workers.length; i++) {\n            const otherWorker = this.workers[i];\n            if (worker === otherWorker || otherWorker.running) {\n                continue;\n            }\n            if (closedIntervalsOverlap(start, end, otherWorker.currentPos, otherWorker.targetPos)) {\n                this.workers.splice(i, 1);\n                this.options.onIdleWorkerRemoved?.(otherWorker);\n                i--;\n            }\n        }\n    }\n    supplyFileSize(size) {\n        assert(this.fileSize === null);\n        this.fileSize = size;\n        // Trim the workers with this new information\n        for (const worker of this.workers) {\n            worker.targetPos = Math.min(worker.targetPos, size);\n            worker.strictTarget = true;\n            for (let i = 0; i < worker.pendingSlices.length; i++) {\n                const pendingSlice = worker.pendingSlices[i];\n                for (const hole of pendingSlice.holes) {\n                    if (hole.end > size) {\n                        // Can't satisfy this slice anymore\n                        pendingSlice.resolve(null);\n                        worker.pendingSlices.splice(i, 1);\n                        i--;\n                        break;\n                    }\n                }\n            }\n        }\n        // Trim the queued reads as well\n        for (let i = 0; i < this.queuedReads.length; i++) {\n            const queuedRead = this.queuedReads[i];\n            if (queuedRead.hole.start >= size) {\n                // Entirely out of bounds\n                for (const slice of queuedRead.pendingSlices)\n                    slice.resolve(null);\n                this.queuedReads.splice(i, 1);\n                i--;\n            }\n            else if (queuedRead.hole.end > size) {\n                // Partially out of bounds\n                queuedRead.hole.end = size;\n                queuedRead.strictTarget = true;\n                for (let j = 0; j < queuedRead.pendingSlices.length; j++) {\n                    const slice = queuedRead.pendingSlices[j];\n                    // If the slice itself is out of bounds, resolve it\n                    if (slice.start >= size) {\n                        slice.resolve(null);\n                        queuedRead.pendingSlices.splice(j, 1);\n                        j--;\n                    }\n                }\n            }\n        }\n    }\n    signalWorkerStoppedRunning(worker) {\n        worker.running = false;\n        if (!worker.aborted) {\n            // When a worker stops running, that means it has hit its targetPos. It might still have pendingSlices\n            // assigned, but this is because those pending slices cover data that other workers are assigned to fill.\n            // Since targetPos has been reached, we can confidently say that this worker has completed its share of work\n            // on the pending slices and must no longer care about them.\n            worker.pendingSlices.length = 0;\n        }\n    }\n    /** Called when a worker reaches the end of the underlying data and must be cleaned up. */\n    onWorkerFinished(worker) {\n        const index = this.workers.indexOf(worker);\n        assert(index !== -1);\n        worker.running = false;\n        this.workers.splice(index, 1);\n        this.options.onIdleWorkerRemoved?.(worker);\n        if (this.fileSize === null) {\n            // We can now deduce the file size!\n            this.supplyFileSize(worker.currentPos);\n        }\n        for (const pendingSlice of worker.pendingSlices) {\n            pendingSlice.resolve(null);\n        }\n    }\n    insertIntoCache(entry) {\n        if (this.options.maxCacheSize === 0) {\n            return; // No caching\n        }\n        let insertionIndex = binarySearchLessOrEqual(this.cache, entry.start, x => x.start) + 1;\n        if (insertionIndex > 0) {\n            const previous = this.cache[insertionIndex - 1];\n            if (previous.end >= entry.end) {\n                // Previous entry swallows the one to be inserted; we don't need to do anything\n                return;\n            }\n            if (previous.end > entry.start) {\n                // Partial overlap with the previous entry, let's join\n                const joined = new Uint8Array(entry.end - previous.start);\n                joined.set(previous.bytes, 0);\n                joined.set(entry.bytes, entry.start - previous.start);\n                this.currentCacheSize += entry.end - previous.end;\n                previous.bytes = joined;\n                previous.view = toDataView(joined);\n                previous.end = entry.end;\n                // Do the rest of the logic with the previous entry instead\n                insertionIndex--;\n                entry = previous;\n            }\n            else {\n                this.cache.splice(insertionIndex, 0, entry);\n                this.currentCacheSize += entry.bytes.length;\n            }\n        }\n        else {\n            this.cache.splice(insertionIndex, 0, entry);\n            this.currentCacheSize += entry.bytes.length;\n        }\n        for (let i = insertionIndex + 1; i < this.cache.length; i++) {\n            const next = this.cache[i];\n            if (entry.end <= next.start) {\n                // Even if they touch, we don't wanna merge them, no need\n                break;\n            }\n            if (entry.end >= next.end) {\n                // The inserted entry completely swallows the next entry\n                this.cache.splice(i, 1);\n                this.currentCacheSize -= next.bytes.length;\n                i--;\n                continue;\n            }\n            // Partial overlap, let's join\n            const joined = new Uint8Array(next.end - entry.start);\n            joined.set(entry.bytes, 0);\n            joined.set(next.bytes, next.start - entry.start);\n            this.currentCacheSize -= entry.end - next.start; // Subtract the overlap\n            entry.bytes = joined;\n            entry.view = toDataView(joined);\n            entry.end = next.end;\n            this.cache.splice(i, 1);\n            break; // After the join case, we're done: the next entry cannot possibly overlap with the inserted one.\n        }\n        // LRU eviction of cache entries\n        while (this.currentCacheSize > this.options.maxCacheSize) {\n            let oldestIndex = 0;\n            let oldestEntry = this.cache[0];\n            for (let i = 1; i < this.cache.length; i++) {\n                const entry = this.cache[i];\n                if (entry.age < oldestEntry.age) {\n                    oldestIndex = i;\n                    oldestEntry = entry;\n                }\n            }\n            if (this.currentCacheSize - oldestEntry.bytes.length <= this.options.maxCacheSize) {\n                // Don't evict if it would shrink the cache below the max size\n                break;\n            }\n            this.cache.splice(oldestIndex, 1);\n            this.currentCacheSize -= oldestEntry.bytes.length;\n        }\n    }\n    dispose() {\n        for (const worker of this.workers) {\n            for (const slice of worker.pendingSlices) {\n                slice.reject(new InputDisposedError());\n            }\n            worker.pendingSlices.length = 0;\n            worker.aborted = true;\n            if (!worker.running) {\n                // Running workers clean up after themselves when they notice the abort\n                this.options.onIdleWorkerRemoved?.(worker);\n            }\n        }\n        for (const queuedRead of this.queuedReads) {\n            for (const slice of queuedRead.pendingSlices) {\n                slice.reject(new InputDisposedError());\n            }\n        }\n        this.workers.length = 0;\n        this.cache.length = 0;\n        this.queuedReads.length = 0;\n        this.disposed = true;\n    }\n}\n/**\n * A dummy source from which no data can be read. Can be used in conjunction with input formats that get their data\n * from another source.\n */\nexport class NullSource extends Source {\n    _getFileSize() {\n        return null;\n    }\n    _read() {\n        return null;\n    }\n    _dispose() {\n        // Do nothing\n    }\n}\n/**\n * A source that covers a range (offset + length) of another source. Useful for reading files that are embedded within\n * larger files.\n *\n * @group Input sources\n * @public\n */\nexport class RangedSource extends Source {\n    /** @internal */\n    constructor(baseSource, offset, length) {\n        super();\n        /** @internal */\n        this._ref = null;\n        if (baseSource._disposed) {\n            throw new Error('Cannot create a slice of a disposed source.');\n        }\n        this._baseSource = baseSource;\n        this._offset = offset;\n        this._length = length ?? null;\n    }\n    /** @internal */\n    _getFileSize() {\n        const baseSize = this._baseSource._getFileSize();\n        if (baseSize === undefined) {\n            return this._length !== null\n                ? this._length\n                : undefined;\n        }\n        if (baseSize === null) {\n            if (this._length !== null) {\n                return this._length;\n            }\n            else {\n                return null;\n            }\n        }\n        return clamp(baseSize - this._offset, 0, this._length ?? Infinity);\n    }\n    /** @internal */\n    _read(start, end, minReadPosition, maxReadPosition) {\n        if (this._length !== null && end > this._length) {\n            return null;\n        }\n        const result = this._baseSource._read(this._offset + start, this._offset + end, this._offset + minReadPosition, this._offset + maxReadPosition);\n        const processResult = (result) => {\n            if (!result) {\n                return null;\n            }\n            result.offset -= this._offset;\n            return result;\n        };\n        if (isThenable(result)) {\n            return result.then(processResult);\n        }\n        else {\n            return processResult(result);\n        }\n    }\n    /** @internal */\n    _dispose() {\n        this._ref?.free();\n    }\n    ref() {\n        this._ref ??= this._baseSource.ref();\n        return super.ref();\n    }\n}\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { IsobmffDemuxer } from './isobmff/isobmff-demuxer.js';\nimport { EBMLId, MAX_HEADER_SIZE, MIN_HEADER_SIZE, readAsciiString, readElementHeader, readElementSize, readUnsignedInt, readVarIntSize, } from './matroska/ebml.js';\nimport { MatroskaDemuxer } from './matroska/matroska-demuxer.js';\nimport { Mp3Demuxer } from './mp3/mp3-demuxer.js';\nimport { MP3_FRAME_HEADER_SIZE, getXingOffset, INFO, XING } from '../shared/mp3-misc.js';\nimport { ID3_V2_HEADER_SIZE, readId3V2Header } from './id3.js';\nimport { readNextMp3FrameHeader } from './mp3/mp3-reader.js';\nimport { OggDemuxer } from './ogg/ogg-demuxer.js';\nimport { WaveDemuxer } from './wave/wave-demuxer.js';\nimport { MAX_ADTS_FRAME_HEADER_SIZE, MIN_ADTS_FRAME_HEADER_SIZE, readAdtsFrameHeader } from './adts/adts-reader.js';\nimport { AdtsDemuxer } from './adts/adts-demuxer.js';\nimport { readAscii, readBytes, readU32Be, readU64Be } from './reader.js';\nimport { FlacDemuxer } from './flac/flac-demuxer.js';\nimport { MpegTsDemuxer } from './mpeg-ts/mpeg-ts-demuxer.js';\nimport { TS_PACKET_SIZE } from './mpeg-ts/mpeg-ts-misc.js';\nimport { HlsDemuxer } from './hls/hls-demuxer.js';\nimport { HLS_MIME_TYPE } from './hls/hls-misc.js';\nimport { PathedSource } from './source.js';\nimport { isThenable } from './misc.js';\n/**\n * Base class representing an input media file format.\n * @group Input formats\n * @public\n */\nexport class InputFormat {\n    constructor() {\n        /**\n         * Provided for tree-shakable checking.\n         * @internal\n         */\n        this._isIsobmff = false;\n    }\n}\n/**\n * Format representing files compatible with the ISO base media file format (ISOBMFF), like MP4 or MOV files.\n *\n * This format can make use of {@link InputOptions.initInput}. When the file contents are fragmented but no track\n * initialization info is provided (no `moov` atom), then it must be provided via `initInput`.\n *\n * @group Input formats\n * @public\n */\nexport class IsobmffInputFormat extends InputFormat {\n    constructor() {\n        super(...arguments);\n        /** @internal */\n        this._isIsobmff = true;\n    }\n    /** @internal */\n    async _getMajorBrand(input) {\n        let slice = input._reader.requestSlice(0, 12);\n        if (isThenable(slice))\n            slice = await slice;\n        if (!slice)\n            return null;\n        slice.skip(4);\n        const fourCc = readAscii(slice, 4);\n        if (fourCc !== 'ftyp'\n            && fourCc !== 'styp' // Segment\n        ) {\n            return null;\n        }\n        return readAscii(slice, 4);\n    }\n    /** @internal */\n    _createDemuxer(input) {\n        return new IsobmffDemuxer(input);\n    }\n    get supportsTimestampedMediaData() {\n        return true;\n    }\n}\n/**\n * MPEG-4 Part 14 (MP4) file format.\n *\n * Do not instantiate this class; use the {@link MP4} singleton instead.\n *\n * @group Input formats\n * @public\n */\nexport class Mp4InputFormat extends IsobmffInputFormat {\n    /** @internal */\n    async _canReadInput(input) {\n        const majorBrand = await this._getMajorBrand(input);\n        if (majorBrand !== null) {\n            return majorBrand !== 'qt  ';\n        }\n        let pos = 0;\n        for (let iter = 0; iter < 10; iter++) { // Bounded loop\n            let slice = input._reader.requestSlice(pos, 8);\n            if (isThenable(slice))\n                slice = await slice;\n            if (!slice)\n                return false;\n            let size = readU32Be(slice);\n            let headerSize = 8;\n            if (size === 1) {\n                let sizeExtensionSlice = input._reader.requestSlice(pos + 8, 8);\n                if (isThenable(sizeExtensionSlice))\n                    sizeExtensionSlice = await sizeExtensionSlice;\n                if (!sizeExtensionSlice)\n                    return false;\n                size = readU64Be(sizeExtensionSlice);\n                headerSize = 16;\n            }\n            if (size < headerSize) {\n                return false; // Hardly a box is it\n            }\n            const fourCc = readAscii(slice, 4);\n            if (fourCc === 'moof' || fourCc === 'sidx') { // Seen in HLS for example\n                return true;\n            }\n            else if (fourCc === 'emsg' || fourCc === 'prft' || fourCc === 'free') {\n                // These are boxes that can appear before the first moof in DASH Media Segments. They're a strong signal\n                // that this is indeed an fMP4 segment, but just to be sure, let's walk the box structure to make sure\n                // it stays sane.\n                pos += size;\n            }\n            else {\n                return false;\n            }\n        }\n        return false;\n    }\n    get name() {\n        return 'MP4';\n    }\n    get mimeType() {\n        return 'video/mp4';\n    }\n}\n/**\n * QuickTime File Format (QTFF), often called MOV.\n *\n * Do not instantiate this class; use the {@link QTFF} singleton instead.\n *\n * @group Input formats\n * @public\n */\nexport class QuickTimeInputFormat extends IsobmffInputFormat {\n    /** @internal */\n    async _canReadInput(input) {\n        const majorBrand = await this._getMajorBrand(input);\n        return majorBrand === 'qt  ';\n    }\n    get name() {\n        return 'QuickTime File Format';\n    }\n    get mimeType() {\n        return 'video/quicktime';\n    }\n}\n/**\n * Matroska file format.\n *\n * Do not instantiate this class; use the {@link MATROSKA} singleton instead.\n *\n * @group Input formats\n * @public\n */\nexport class MatroskaInputFormat extends InputFormat {\n    /** @internal */\n    async isSupportedEBMLOfDocType(input, desiredDocType) {\n        let headerSlice = input._reader.requestSlice(0, MAX_HEADER_SIZE);\n        if (isThenable(headerSlice))\n            headerSlice = await headerSlice;\n        if (!headerSlice)\n            return false;\n        const varIntSize = readVarIntSize(headerSlice);\n        if (varIntSize === null) {\n            return false;\n        }\n        if (varIntSize < 1 || varIntSize > 8) {\n            return false;\n        }\n        const id = readUnsignedInt(headerSlice, varIntSize);\n        if (id !== EBMLId.EBML) {\n            return false;\n        }\n        const dataSize = readElementSize(headerSlice);\n        if (typeof dataSize !== 'number') {\n            return false; // Miss me with that shit\n        }\n        let dataSlice = input._reader.requestSlice(headerSlice.filePos, dataSize);\n        if (isThenable(dataSlice))\n            dataSlice = await dataSlice;\n        if (!dataSlice)\n            return false;\n        const startPos = headerSlice.filePos;\n        while (dataSlice.filePos <= startPos + dataSize - MIN_HEADER_SIZE) {\n            const header = readElementHeader(dataSlice);\n            if (!header)\n                break;\n            const { id, size } = header;\n            const dataStartPos = dataSlice.filePos;\n            if (size === undefined)\n                return false;\n            if (dataStartPos + size > startPos + dataSize || (size > 8 && id !== EBMLId.DocType)) {\n                return false; // The element overruns the header or is an integer of impossible size\n            }\n            switch (id) {\n                case EBMLId.EBMLVersion:\n                    {\n                        const ebmlVersion = readUnsignedInt(dataSlice, size);\n                        if (ebmlVersion !== 1) {\n                            return false;\n                        }\n                    }\n                    ;\n                    break;\n                case EBMLId.EBMLReadVersion:\n                    {\n                        const ebmlReadVersion = readUnsignedInt(dataSlice, size);\n                        if (ebmlReadVersion !== 1) {\n                            return false;\n                        }\n                    }\n                    ;\n                    break;\n                case EBMLId.DocType:\n                    {\n                        const docType = readAsciiString(dataSlice, size);\n                        if (docType !== desiredDocType) {\n                            return false;\n                        }\n                    }\n                    ;\n                    break;\n                case EBMLId.DocTypeVersion:\n                    {\n                        const docTypeVersion = readUnsignedInt(dataSlice, size);\n                        if (docTypeVersion > 4) { // Support up to Matroska v4\n                            return false;\n                        }\n                    }\n                    ;\n                    break;\n            }\n            dataSlice.filePos = dataStartPos + size;\n        }\n        return true;\n    }\n    /** @internal */\n    _canReadInput(input) {\n        return this.isSupportedEBMLOfDocType(input, 'matroska');\n    }\n    /** @internal */\n    _createDemuxer(input) {\n        return new MatroskaDemuxer(input);\n    }\n    get name() {\n        return 'Matroska';\n    }\n    get mimeType() {\n        return 'video/x-matroska';\n    }\n    get supportsTimestampedMediaData() {\n        return true;\n    }\n}\n/**\n * WebM file format, based on Matroska.\n *\n * Do not instantiate this class; use the {@link WEBM} singleton instead.\n *\n * @group Input formats\n * @public\n */\nexport class WebMInputFormat extends MatroskaInputFormat {\n    /** @internal */\n    _canReadInput(input) {\n        return this.isSupportedEBMLOfDocType(input, 'webm');\n    }\n    get name() {\n        return 'WebM';\n    }\n    get mimeType() {\n        return 'video/webm';\n    }\n}\n/**\n * MP3 file format.\n *\n * Do not instantiate this class; use the {@link MP3} singleton instead.\n *\n * @group Input formats\n * @public\n */\nexport class Mp3InputFormat extends InputFormat {\n    /** @internal */\n    async _canReadInput(input) {\n        let currentPos = 0;\n        while (true) {\n            let slice = input._reader.requestSlice(currentPos, ID3_V2_HEADER_SIZE);\n            if (isThenable(slice))\n                slice = await slice;\n            if (!slice)\n                break;\n            const id3V2Header = readId3V2Header(slice);\n            if (!id3V2Header) {\n                break;\n            }\n            currentPos = slice.filePos + id3V2Header.size;\n        }\n        const firstResult = await readNextMp3FrameHeader(input._reader, currentPos, currentPos + 4096);\n        if (!firstResult) {\n            return false;\n        }\n        const firstHeader = firstResult.header;\n        const xingOffset = getXingOffset(firstHeader.mpegVersionId, firstHeader.channel);\n        let slice = input._reader.requestSlice(firstResult.startPos + xingOffset, 4);\n        if (isThenable(slice))\n            slice = await slice;\n        if (!slice)\n            return false;\n        const word = readU32Be(slice);\n        const isXing = word === XING || word === INFO;\n        if (isXing) {\n            // Gotta be MP3\n            return true;\n        }\n        currentPos = firstResult.startPos + firstResult.header.totalSize;\n        // Fine, we found one frame header, but we're still not entirely sure this is MP3. Let's check if we can find\n        // another header right after it:\n        const secondResult = await readNextMp3FrameHeader(input._reader, currentPos, currentPos + MP3_FRAME_HEADER_SIZE);\n        if (!secondResult) {\n            return false;\n        }\n        const secondHeader = secondResult.header;\n        // In a well-formed MP3 file, we'd expect these two frames to share some similarities:\n        if (firstHeader.channel !== secondHeader.channel || firstHeader.sampleRate !== secondHeader.sampleRate) {\n            return false;\n        }\n        // We have found two matching consecutive MP3 frames, a strong indicator that this is an MP3 file\n        return true;\n    }\n    /** @internal */\n    _createDemuxer(input) {\n        return new Mp3Demuxer(input);\n    }\n    get name() {\n        return 'MP3';\n    }\n    get mimeType() {\n        return 'audio/mpeg';\n    }\n    get supportsTimestampedMediaData() {\n        return false;\n    }\n}\n/**\n * WAVE file format, based on RIFF.\n *\n * Do not instantiate this class; use the {@link WAVE} singleton instead.\n *\n * @group Input formats\n * @public\n */\nexport class WaveInputFormat extends InputFormat {\n    /** @internal */\n    async _canReadInput(input) {\n        let slice = input._reader.requestSlice(0, 12);\n        if (isThenable(slice))\n            slice = await slice;\n        if (!slice)\n            return false;\n        const riffType = readAscii(slice, 4);\n        if (riffType !== 'RIFF' && riffType !== 'RIFX' && riffType !== 'RF64') {\n            return false;\n        }\n        slice.skip(4);\n        const format = readAscii(slice, 4);\n        return format === 'WAVE';\n    }\n    /** @internal */\n    _createDemuxer(input) {\n        return new WaveDemuxer(input);\n    }\n    get name() {\n        return 'WAVE';\n    }\n    get mimeType() {\n        return 'audio/wav';\n    }\n    get supportsTimestampedMediaData() {\n        return false;\n    }\n}\n/**\n * Ogg file format.\n *\n * Do not instantiate this class; use the {@link OGG} singleton instead.\n *\n * @group Input formats\n * @public\n */\nexport class OggInputFormat extends InputFormat {\n    /** @internal */\n    async _canReadInput(input) {\n        let slice = input._reader.requestSlice(0, 4);\n        if (isThenable(slice))\n            slice = await slice;\n        if (!slice)\n            return false;\n        return readAscii(slice, 4) === 'OggS';\n    }\n    /** @internal */\n    _createDemuxer(input) {\n        return new OggDemuxer(input);\n    }\n    get name() {\n        return 'Ogg';\n    }\n    get mimeType() {\n        return 'application/ogg';\n    }\n    get supportsTimestampedMediaData() {\n        return true;\n    }\n}\n/**\n * FLAC file format.\n *\n * Do not instantiate this class; use the {@link FLAC} singleton instead.\n *\n * @group Input formats\n * @public\n */\nexport class FlacInputFormat extends InputFormat {\n    /** @internal */\n    async _canReadInput(input) {\n        let currentPos = 0;\n        // There might be ID3v2 headers at the start, skip 'em\n        while (true) {\n            let slice = input._reader.requestSlice(currentPos, ID3_V2_HEADER_SIZE);\n            if (isThenable(slice))\n                slice = await slice;\n            if (!slice)\n                break;\n            const id3V2Header = readId3V2Header(slice);\n            if (!id3V2Header) {\n                break;\n            }\n            currentPos = slice.filePos + id3V2Header.size;\n        }\n        let slice = input._reader.requestSlice(currentPos, 4);\n        if (isThenable(slice))\n            slice = await slice;\n        if (!slice)\n            return false;\n        return readAscii(slice, 4) === 'fLaC';\n    }\n    get name() {\n        return 'FLAC';\n    }\n    get mimeType() {\n        return 'audio/flac';\n    }\n    get supportsTimestampedMediaData() {\n        return false;\n    }\n    /** @internal */\n    _createDemuxer(input) {\n        return new FlacDemuxer(input);\n    }\n}\n/**\n * ADTS file format.\n *\n * Do not instantiate this class; use the {@link ADTS} singleton instead.\n *\n * @group Input formats\n * @public\n */\nexport class AdtsInputFormat extends InputFormat {\n    /** @internal */\n    async _canReadInput(input) {\n        let currentPos = 0;\n        while (true) {\n            let slice = input._reader.requestSlice(currentPos, ID3_V2_HEADER_SIZE);\n            if (isThenable(slice))\n                slice = await slice;\n            if (!slice)\n                break;\n            const id3V2Header = readId3V2Header(slice);\n            if (!id3V2Header) {\n                break;\n            }\n            currentPos = slice.filePos + id3V2Header.size;\n        }\n        let slice = input._reader.requestSliceRange(currentPos, MIN_ADTS_FRAME_HEADER_SIZE, MAX_ADTS_FRAME_HEADER_SIZE);\n        if (isThenable(slice))\n            slice = await slice;\n        if (!slice)\n            return false;\n        const firstHeader = readAdtsFrameHeader(slice);\n        if (!firstHeader) {\n            return false;\n        }\n        currentPos += firstHeader.frameLength;\n        slice = input._reader.requestSliceRange(currentPos, MIN_ADTS_FRAME_HEADER_SIZE, MAX_ADTS_FRAME_HEADER_SIZE);\n        if (isThenable(slice))\n            slice = await slice;\n        if (!slice)\n            return false;\n        const secondHeader = readAdtsFrameHeader(slice);\n        if (!secondHeader) {\n            return false;\n        }\n        return firstHeader.objectType === secondHeader.objectType\n            && firstHeader.samplingFrequencyIndex === secondHeader.samplingFrequencyIndex\n            && firstHeader.channelConfiguration === secondHeader.channelConfiguration;\n    }\n    /** @internal */\n    _createDemuxer(input) {\n        return new AdtsDemuxer(input);\n    }\n    get name() {\n        return 'ADTS';\n    }\n    get mimeType() {\n        return 'audio/aac';\n    }\n    get supportsTimestampedMediaData() {\n        return false;\n    }\n}\n/**\n * MPEG Transport Stream (MPEG-TS) file format.\n *\n * This format can make use of {@link InputOptions.initInput} to initialize track information even when no\n * initialization information is provided for the track, for example because it has no key frames. In this case, tracks\n * are matched to each other based on their PID.\n *\n * Do not instantiate this class; use the {@link MPEG_TS} singleton instead.\n *\n * @group Input formats\n * @public\n */\nexport class MpegTsInputFormat extends InputFormat {\n    /** @internal */\n    async _canReadInput(input) {\n        const lengthToCheck = TS_PACKET_SIZE + 16 + 1;\n        let slice = input._reader.requestSlice(0, lengthToCheck);\n        if (isThenable(slice))\n            slice = await slice;\n        if (!slice)\n            return false;\n        const bytes = readBytes(slice, lengthToCheck);\n        if (bytes[0] === 0x47 && bytes[TS_PACKET_SIZE] === 0x47) {\n            // Regular MPEG-TS\n            return true;\n        }\n        else if (bytes[0] === 0x47 && bytes[TS_PACKET_SIZE + 16] === 0x47) {\n            // MPEG-TS with Forward Error Correction\n            return true;\n        }\n        else if (bytes[4] === 0x47 && bytes[4 + TS_PACKET_SIZE + 4] === 0x47) {\n            // MPEG-2-TS (DVHS)\n            return true;\n        }\n        return false;\n    }\n    /** @internal */\n    _createDemuxer(input) {\n        return new MpegTsDemuxer(input);\n    }\n    get name() {\n        return 'MPEG Transport Stream';\n    }\n    get mimeType() {\n        return 'video/MP2T';\n    }\n    get supportsTimestampedMediaData() {\n        return true;\n    }\n}\n/**\n * Media described using the HTTP Live Streaming (HLS) protocol, with playlists in the M3U8 format.\n *\n * Do not instantiate this class; use the {@link HLS} singleton instead.\n *\n * @group Input formats\n * @public\n */\nexport class HlsInputFormat extends InputFormat {\n    /** @internal */\n    async _canReadInput(input) {\n        let slice = input._reader.requestSlice(0, 7);\n        if (isThenable(slice))\n            slice = await slice;\n        if (!slice)\n            return false;\n        const isM3u8 = readAscii(slice, 7) === '#EXTM3U';\n        if (!isM3u8) {\n            return false;\n        }\n        if (!(input._rootSource instanceof PathedSource)) {\n            throw new TypeError('HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.');\n        }\n        input._rootSource._usedForHls = true;\n        return true;\n    }\n    /** @internal */\n    _createDemuxer(input) {\n        return new HlsDemuxer(input);\n    }\n    get name() {\n        return 'HTTP Live Streaming (HLS)';\n    }\n    get mimeType() {\n        return HLS_MIME_TYPE;\n    }\n    get supportsTimestampedMediaData() {\n        return true;\n    }\n}\n/**\n * MP4 input format singleton.\n * @group Input formats\n * @public\n */\nexport const MP4 = /* #__PURE__ */ new Mp4InputFormat();\n/**\n * QuickTime File Format input format singleton.\n * @group Input formats\n * @public\n */\nexport const QTFF = /* #__PURE__ */ new QuickTimeInputFormat();\n/**\n * Matroska input format singleton.\n * @group Input formats\n * @public\n */\nexport const MATROSKA = /* #__PURE__ */ new MatroskaInputFormat();\n/**\n * WebM input format singleton.\n * @group Input formats\n * @public\n */\nexport const WEBM = /* #__PURE__ */ new WebMInputFormat();\n/**\n * MP3 input format singleton.\n * @group Input formats\n * @public\n */\nexport const MP3 = /* #__PURE__ */ new Mp3InputFormat();\n/**\n * WAVE input format singleton.\n * @group Input formats\n * @public\n */\nexport const WAVE = /* #__PURE__ */ new WaveInputFormat();\n/**\n * Ogg input format singleton.\n * @group Input formats\n * @public\n */\nexport const OGG = /* #__PURE__ */ new OggInputFormat();\n/**\n * ADTS input format singleton.\n * @group Input formats\n * @public\n */\nexport const ADTS = /* #__PURE__ */ new AdtsInputFormat();\n/**\n * FLAC input format singleton.\n * @group Input formats\n * @public\n */\nexport const FLAC = /* #__PURE__ */ new FlacInputFormat();\n/**\n * MPEG-TS input format singleton.\n * @group Input formats\n * @public\n */\nexport const MPEG_TS = /* #__PURE__ */ new MpegTsInputFormat();\n/**\n * HLS input format singleton.\n * @group Input formats\n * @public\n */\nexport const HLS = /* #__PURE__ */ new HlsInputFormat();\n/**\n * List of all input format singletons. If you don't need to support all input formats, you should specify the\n * formats individually for better tree shaking.\n * @group Input formats\n * @public\n */\nexport const ALL_FORMATS = [HLS, MP4, QTFF, MATROSKA, WEBM, WAVE, OGG, FLAC, MP3, ADTS, MPEG_TS];\n/**\n * List of input formats required for playback of typical HLS manifests. Includes HLS itself as well as the typical\n * segment formats: MPEG Transport Stream (.ts), MP4 (CMAF), ADTS (.aac) and MP3.\n * @group Input formats\n * @public\n */\nexport const HLS_FORMATS = [HLS, MP4, QTFF, MP3, ADTS, MPEG_TS];\nexport const validateInputFormatOptions = (options, prefix) => {\n    if (!options || typeof options !== 'object') {\n        throw new TypeError(`${prefix}, when provided, must be an object.`);\n    }\n    if (options.isobmff !== undefined) {\n        if (!options.isobmff || typeof options.isobmff !== 'object') {\n            throw new TypeError(`${prefix}.isobmff, when provided, must be an object.`);\n        }\n        if (options.isobmff.resolveKeyId !== undefined && typeof options.isobmff.resolveKeyId !== 'function') {\n            throw new TypeError(`${prefix}.isobmff.resolveKeyId, when provided, must be a function.`);\n        }\n    }\n    if (options.hls !== undefined) {\n        if (!options.hls || typeof options.hls !== 'object') {\n            throw new TypeError(`${prefix}.hls, when provided, must be an object.`);\n        }\n        if (options.hls.offsetTimestampsByDateTime !== undefined\n            && typeof options.hls.offsetTimestampsByDateTime !== 'boolean') {\n            throw new TypeError(`${prefix}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`);\n        }\n    }\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nvar __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {\n    if (value !== null && value !== void 0) {\n        if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n        var dispose, inner;\n        if (async) {\n            if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n            dispose = value[Symbol.asyncDispose];\n        }\n        if (dispose === void 0) {\n            if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n            dispose = value[Symbol.dispose];\n            if (async) inner = dispose;\n        }\n        if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n        env.stack.push({ value: value, dispose: dispose, async: async });\n    }\n    else if (async) {\n        env.stack.push({ async: true });\n    }\n    return value;\n};\nvar __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {\n    return function (env) {\n        function fail(e) {\n            env.error = env.hasError ? new SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n            env.hasError = true;\n        }\n        var r, s = 0;\n        function next() {\n            while (r = env.stack.pop()) {\n                try {\n                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n                    if (r.dispose) {\n                        var result = r.dispose.call(r.value);\n                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n                    }\n                    else s |= 1;\n                }\n                catch (e) {\n                    fail(e);\n                }\n            }\n            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n            if (env.hasError) throw env.error;\n        }\n        return next();\n    };\n})(typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n    var e = new Error(message);\n    return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n});\nimport { assert, clamp, COLOR_PRIMARIES_MAP, isAllowSharedBufferSource, isThenable, MATRIX_COEFFICIENTS_MAP, SECOND_TO_MICROSECOND_FACTOR, toDataView, toUint8Array, TRANSFER_CHARACTERISTICS_MAP, isFirefox, polyfillSymbolDispose, assertNever, isWebKit, simplifyRational, validateRectangle, composeRotationAndFlip, roundToMultiple, arrayArgmin, } from './misc.js';\nimport { Logging } from './logging.js';\npolyfillSymbolDispose();\n// Let's manually handle logging the garbage collection errors that are typically logged by the browser. This way, they\n// also kick for audio samples (which is normally not the case), making sure any incorrect code is quickly caught.\nlet lastVideoGcErrorLog = -Infinity;\nlet lastAudioGcErrorLog = -Infinity;\nlet finalizationRegistry = null;\nif (typeof FinalizationRegistry !== 'undefined') {\n    finalizationRegistry = new FinalizationRegistry((value) => {\n        const now = performance.now();\n        if (value.type === 'video') {\n            if (now - lastVideoGcErrorLog >= 1000) {\n                // This error is annoying but oh so important\n                Logging._error(`A VideoSample was garbage collected without first being closed. For proper resource management,`\n                    + ` make sure to call close() on all your VideoSamples as soon as you're done using them.`);\n                lastVideoGcErrorLog = now;\n            }\n            if (typeof VideoFrame !== 'undefined' && value.data instanceof VideoFrame) {\n                value.data.close(); // Prevent the browser error since we're logging our own\n            }\n        }\n        else {\n            if (now - lastAudioGcErrorLog >= 1000) {\n                Logging._error(`An AudioSample was garbage collected without first being closed. For proper resource management,`\n                    + ` make sure to call close() on all your AudioSamples as soon as you're done using them.`);\n                lastAudioGcErrorLog = now;\n            }\n            if (typeof AudioData !== 'undefined' && value.data instanceof AudioData) {\n                value.data.close();\n            }\n        }\n    });\n}\n/**\n * Abstract base class for custom video sample resources. Implement this class to provide custom backing\n * for VideoSample instances.\n * @group Samples\n * @public\n */\nexport class VideoSampleResource {\n    constructor() {\n        /** @internal */\n        this._referenceCount = 0;\n        /** @internal */\n        this._lastAllocationBuffer = null;\n    }\n}\n/**\n * The list of {@link VideoSample} pixel formats.\n * @group Samples\n * @public\n */\nexport const VIDEO_SAMPLE_PIXEL_FORMATS = [\n    // 4:2:0 Y, U, V\n    'I420',\n    'I420P10',\n    'I420P12',\n    // 4:2:0 Y, U, V, A\n    'I420A',\n    'I420AP10',\n    'I420AP12',\n    // 4:2:2 Y, U, V\n    'I422',\n    'I422P10',\n    'I422P12',\n    // 4:2:2 Y, U, V, A\n    'I422A',\n    'I422AP10',\n    'I422AP12',\n    // 4:4:4 Y, U, V\n    'I444',\n    'I444P10',\n    'I444P12',\n    // 4:4:4 Y, U, V, A\n    'I444A',\n    'I444AP10',\n    'I444AP12',\n    // 4:2:0 Y, UV\n    'NV12',\n    // 4:4:4 RGBA\n    'RGBA',\n    // 4:4:4 RGBX (opaque)\n    'RGBX',\n    // 4:4:4 BGRA\n    'BGRA',\n    // 4:4:4 BGRX (opaque)\n    'BGRX',\n];\nconst VIDEO_SAMPLE_PIXEL_FORMATS_SET = new Set(VIDEO_SAMPLE_PIXEL_FORMATS);\n/**\n * Represents a raw, unencoded video sample (frame). Mainly used as an expressive wrapper around WebCodecs API's\n * [`VideoFrame`](https://developer.mozilla.org/en-US/docs/Web/API/VideoFrame), but can also be used standalone.\n * @group Samples\n * @public\n */\nexport class VideoSample {\n    /** The width of the frame in pixels. */\n    get codedWidth() {\n        // This is wrong, but the fix is a v2 thing\n        return this.visibleRect.width;\n    }\n    /** The height of the frame in pixels. */\n    get codedHeight() {\n        // Same here\n        return this.visibleRect.height;\n    }\n    /** The display width of the frame in pixels, after aspect ratio adjustment, rotation and flip. */\n    get displayWidth() {\n        return this.rotation % 180 === 0 ? this.squarePixelWidth : this.squarePixelHeight;\n    }\n    /** The display height of the frame in pixels, after aspect ratio adjustment, rotation and flip. */\n    get displayHeight() {\n        return this.rotation % 180 === 0 ? this.squarePixelHeight : this.squarePixelWidth;\n    }\n    /** The presentation timestamp of the frame in microseconds. */\n    get microsecondTimestamp() {\n        return Math.trunc(SECOND_TO_MICROSECOND_FACTOR * this.timestamp);\n    }\n    /** The duration of the frame in microseconds. */\n    get microsecondDuration() {\n        return Math.trunc(SECOND_TO_MICROSECOND_FACTOR * this.duration);\n    }\n    /**\n     * Whether this sample uses a pixel format that can hold transparency data. Note that this doesn't necessarily mean\n     * that the sample is transparent.\n     */\n    get hasAlpha() {\n        return this.format && this.format.includes('A');\n    }\n    constructor(data, init) {\n        /** @internal */\n        this._closed = false;\n        if (data instanceof ArrayBuffer\n            || (typeof SharedArrayBuffer !== 'undefined' && data instanceof SharedArrayBuffer)\n            || ArrayBuffer.isView(data)) {\n            if (!init || typeof init !== 'object') {\n                throw new TypeError('init must be an object.');\n            }\n            if (init.format === undefined || !VIDEO_SAMPLE_PIXEL_FORMATS_SET.has(init.format)) {\n                throw new TypeError('init.format must be one of: ' + VIDEO_SAMPLE_PIXEL_FORMATS.join(', '));\n            }\n            if (!Number.isInteger(init.codedWidth) || init.codedWidth <= 0) {\n                throw new TypeError('init.codedWidth must be a positive integer.');\n            }\n            if (!Number.isInteger(init.codedHeight) || init.codedHeight <= 0) {\n                throw new TypeError('init.codedHeight must be a positive integer.');\n            }\n            if (init.rotation !== undefined && ![0, 90, 180, 270].includes(init.rotation)) {\n                throw new TypeError('init.rotation, when provided, must be 0, 90, 180, or 270.');\n            }\n            if (init.flip !== undefined && typeof init.flip !== 'boolean') {\n                throw new TypeError('init.flip, when provided, must be a boolean.');\n            }\n            if (!Number.isFinite(init.timestamp)) {\n                throw new TypeError('init.timestamp must be a number.');\n            }\n            if (init.duration !== undefined && (!Number.isFinite(init.duration) || init.duration < 0)) {\n                throw new TypeError('init.duration, when provided, must be a non-negative number.');\n            }\n            if (init.layout !== undefined) {\n                if (!Array.isArray(init.layout)) {\n                    throw new TypeError('init.layout, when provided, must be an array.');\n                }\n                for (const plane of init.layout) {\n                    if (!plane || typeof plane !== 'object' || Array.isArray(plane)) {\n                        throw new TypeError('Each entry in init.layout must be an object.');\n                    }\n                    if (!Number.isInteger(plane.offset) || plane.offset < 0) {\n                        throw new TypeError('plane.offset must be a non-negative integer.');\n                    }\n                    if (!Number.isInteger(plane.stride) || plane.stride < 0) {\n                        throw new TypeError('plane.stride must be a non-negative integer.');\n                    }\n                }\n            }\n            if (init.visibleRect !== undefined) {\n                validateRectangle(init.visibleRect, 'init.visibleRect');\n            }\n            if (init.displayWidth !== undefined\n                && (!Number.isInteger(init.displayWidth) || init.displayWidth <= 0)) {\n                throw new TypeError('init.displayWidth, when provided, must be a positive integer.');\n            }\n            if (init.displayHeight !== undefined\n                && (!Number.isInteger(init.displayHeight) || init.displayHeight <= 0)) {\n                throw new TypeError('init.displayHeight, when provided, must be a positive integer.');\n            }\n            if ((init.displayWidth !== undefined) !== (init.displayHeight !== undefined)) {\n                throw new TypeError('init.displayWidth and init.displayHeight must be either both provided or both omitted.');\n            }\n            this.format = init.format;\n            this.rotation = init.rotation ?? 0;\n            this.flip = init.flip ?? false;\n            this.timestamp = init.timestamp;\n            this.duration = init.duration ?? 0;\n            const layout = init.layout ?? createDefaultPlaneLayout(init.format, init.codedWidth, init.codedHeight);\n            let colorSpaceInit = init.colorSpace ?? null;\n            if (colorSpaceInit === null) {\n                if (this.format === 'RGBA' || this.format === 'RGBX'\n                    || this.format === 'BGRA' || this.format === 'BGRX') {\n                    // sRGB Color Space\n                    colorSpaceInit = {\n                        primaries: 'bt709',\n                        transfer: 'iec61966-2-1',\n                        matrix: 'rgb',\n                        fullRange: true,\n                    };\n                }\n                else {\n                    // REC709 Color Space\n                    colorSpaceInit = {\n                        primaries: 'bt709',\n                        transfer: 'bt709',\n                        matrix: 'bt709',\n                        fullRange: false,\n                    };\n                }\n            }\n            this.visibleRect = {\n                left: init.visibleRect?.left ?? 0,\n                top: init.visibleRect?.top ?? 0,\n                width: init.visibleRect?.width ?? init.codedWidth,\n                height: init.visibleRect?.height ?? init.codedHeight,\n            };\n            if (init.displayWidth !== undefined) {\n                this.squarePixelWidth = this.rotation % 180 === 0 ? init.displayWidth : init.displayHeight;\n                this.squarePixelHeight = this.rotation % 180 === 0 ? init.displayHeight : init.displayWidth;\n            }\n            else {\n                this.squarePixelWidth = this.visibleRect.width;\n                this.squarePixelHeight = this.visibleRect.height;\n            }\n            // As an optimization, one could check if VideoFrame is defined and if it is, create a VideoFrame here from\n            // the data. Since VideoFrames are typically needed anyway, doing it this way would avoid an additional\n            // copy of the frame data. But due to https://issues.chromium.org/issues/529413114, this is currently\n            // not done.\n            this._data = init._doNotCopy\n                ? toUint8Array(data)\n                : toUint8Array(data).slice(); // Copy it\n            this._layout = layout;\n            this.colorSpace = new VideoSampleColorSpace(colorSpaceInit);\n        }\n        else if (typeof VideoFrame !== 'undefined' && data instanceof VideoFrame) {\n            if (init?.rotation !== undefined && ![0, 90, 180, 270].includes(init.rotation)) {\n                throw new TypeError('init.rotation, when provided, must be 0, 90, 180, or 270.');\n            }\n            if (init?.flip !== undefined && typeof init.flip !== 'boolean') {\n                throw new TypeError('init.flip, when provided, must be a boolean.');\n            }\n            if (init?.timestamp !== undefined && !Number.isFinite(init?.timestamp)) {\n                throw new TypeError('init.timestamp, when provided, must be a number.');\n            }\n            if (init?.duration !== undefined && (!Number.isFinite(init.duration) || init.duration < 0)) {\n                throw new TypeError('init.duration, when provided, must be a non-negative number.');\n            }\n            if (init?.visibleRect !== undefined) {\n                validateRectangle(init.visibleRect, 'init.visibleRect');\n            }\n            this._data = data;\n            this._layout = null;\n            this.format = data.format;\n            this.visibleRect = {\n                left: data.visibleRect?.x ?? 0,\n                top: data.visibleRect?.y ?? 0,\n                width: data.visibleRect?.width ?? data.codedWidth,\n                height: data.visibleRect?.height ?? data.codedHeight,\n            };\n            // The VideoFrame's rotation and flip are ignored here. They're still new fields, and I'm not sure of any\n            // application where the browser makes use of them. If a case gets found, I'll add it.\n            this.rotation = init?.rotation ?? 0;\n            this.flip = init?.flip ?? false;\n            // Assuming no innate VideoFrame rotation here\n            this.squarePixelWidth = data.displayWidth;\n            this.squarePixelHeight = data.displayHeight;\n            this.timestamp = init?.timestamp ?? data.timestamp / 1e6;\n            this.duration = init?.duration ?? (data.duration ?? 0) / 1e6;\n            // Sanitize the inputs we pass in so that out-of-spec values don't throw\n            // See https://github.com/Vanilagy/mediabunny/issues/555\n            const { primaries, transfer, matrix, fullRange } = data.colorSpace;\n            this.colorSpace = new VideoSampleColorSpace({\n                primaries: primaries !== null && primaries in COLOR_PRIMARIES_MAP ? primaries : null,\n                transfer: transfer !== null && transfer in TRANSFER_CHARACTERISTICS_MAP ? transfer : null,\n                matrix: matrix !== null && matrix in MATRIX_COEFFICIENTS_MAP ? matrix : null,\n                fullRange,\n            });\n        }\n        else if ((typeof HTMLImageElement !== 'undefined' && data instanceof HTMLImageElement)\n            || (typeof SVGImageElement !== 'undefined' && data instanceof SVGImageElement)\n            || (typeof ImageBitmap !== 'undefined' && data instanceof ImageBitmap)\n            || (typeof HTMLVideoElement !== 'undefined' && data instanceof HTMLVideoElement)\n            || (typeof HTMLCanvasElement !== 'undefined' && data instanceof HTMLCanvasElement)\n            || (typeof OffscreenCanvas !== 'undefined' && data instanceof OffscreenCanvas)) {\n            if (!init || typeof init !== 'object') {\n                throw new TypeError('init must be an object.');\n            }\n            if (init.rotation !== undefined && ![0, 90, 180, 270].includes(init.rotation)) {\n                throw new TypeError('init.rotation, when provided, must be 0, 90, 180, or 270.');\n            }\n            if (init.flip !== undefined && typeof init.flip !== 'boolean') {\n                throw new TypeError('init.flip, when provided, must be a boolean.');\n            }\n            if (!Number.isFinite(init.timestamp)) {\n                throw new TypeError('init.timestamp must be a number.');\n            }\n            if (init.duration !== undefined && (!Number.isFinite(init.duration) || init.duration < 0)) {\n                throw new TypeError('init.duration, when provided, must be a non-negative number.');\n            }\n            if (init.visibleRect !== undefined) {\n                validateRectangle(init.visibleRect, 'init.visibleRect');\n            }\n            if (typeof VideoFrame !== 'undefined') {\n                return new VideoSample(new VideoFrame(data, {\n                    timestamp: Math.trunc(init.timestamp * SECOND_TO_MICROSECOND_FACTOR),\n                    // Drag 0 to undefined\n                    duration: Math.trunc((init.duration ?? 0) * SECOND_TO_MICROSECOND_FACTOR) || undefined,\n                    // WebCodecs wants DOMRectInit\n                    visibleRect: init.visibleRect && {\n                        x: init.visibleRect.left,\n                        y: init.visibleRect.top,\n                        width: init.visibleRect.width,\n                        height: init.visibleRect.height,\n                    },\n                }), init);\n            }\n            let width = 0;\n            let height = 0;\n            // Determine the dimensions of the thing\n            if ('naturalWidth' in data) {\n                width = data.naturalWidth;\n                height = data.naturalHeight;\n            }\n            else if ('videoWidth' in data) {\n                width = data.videoWidth;\n                height = data.videoHeight;\n            }\n            else if ('width' in data) {\n                width = Number(data.width);\n                height = Number(data.height);\n            }\n            if (!width || !height) {\n                throw new TypeError('Could not determine dimensions.');\n            }\n            const visibleRect = init.visibleRect ?? { left: 0, top: 0, width, height };\n            const canvas = new OffscreenCanvas(visibleRect.width, visibleRect.height);\n            const context = canvas.getContext('2d', {\n                alpha: isFirefox(), // Firefox has VideoFrame glitches with opaque canvases\n                willReadFrequently: true,\n            });\n            if (!context) {\n                throw new Error('OffscreenCanvas must have support for the \\'2d\\' context in order to create a VideoSample from'\n                    + ' this data.');\n            }\n            // Draw it to a canvas, cropped to the visible rect\n            context.drawImage(data, -visibleRect.left, -visibleRect.top);\n            this._data = canvas;\n            this._layout = null;\n            this.format = 'RGBX';\n            this.visibleRect = { left: 0, top: 0, width: visibleRect.width, height: visibleRect.height };\n            this.squarePixelWidth = visibleRect.width;\n            this.squarePixelHeight = visibleRect.height;\n            this.rotation = init.rotation ?? 0;\n            this.flip = init.flip ?? false;\n            this.timestamp = init.timestamp;\n            this.duration = init.duration ?? 0;\n            this.colorSpace = new VideoSampleColorSpace({\n                matrix: 'rgb',\n                primaries: 'bt709',\n                transfer: 'iec61966-2-1',\n                fullRange: true,\n            });\n        }\n        else if (data instanceof VideoSampleResource) {\n            if (!init || typeof init !== 'object') {\n                throw new TypeError('init must be an object.');\n            }\n            if (init.rotation !== undefined && ![0, 90, 180, 270].includes(init.rotation)) {\n                throw new TypeError('init.rotation, when provided, must be 0, 90, 180, or 270.');\n            }\n            if (init.flip !== undefined && typeof init.flip !== 'boolean') {\n                throw new TypeError('init.flip, when provided, must be a boolean.');\n            }\n            if (!Number.isFinite(init.timestamp)) {\n                throw new TypeError('init.timestamp must be a number.');\n            }\n            if (init.duration !== undefined && (!Number.isFinite(init.duration) || init.duration < 0)) {\n                throw new TypeError('init.duration, when provided, must be a non-negative number.');\n            }\n            this._data = data;\n            data._referenceCount++;\n            this.format = data.getFormat();\n            if (this.format !== null && !VIDEO_SAMPLE_PIXEL_FORMATS.includes(this.format)) {\n                throw new TypeError('getFormat() must return a VideoSamplePixelFormat or null.');\n            }\n            this.visibleRect = {\n                left: 0,\n                top: 0,\n                width: data.getCodedWidth(),\n                height: data.getCodedHeight(),\n            };\n            if (!Number.isInteger(this.visibleRect.width) || this.visibleRect.width <= 0) {\n                throw new TypeError('getCodedWidth() must return a positive integer.');\n            }\n            if (!Number.isInteger(this.visibleRect.height) || this.visibleRect.height <= 0) {\n                throw new TypeError('getCodedHeight() must return a positive integer.');\n            }\n            this.squarePixelWidth = data.getSquarePixelWidth();\n            if (!Number.isInteger(this.squarePixelWidth) || this.squarePixelWidth <= 0) {\n                throw new TypeError('getSquarePixelWidth() must return a positive integer.');\n            }\n            this.squarePixelHeight = data.getSquarePixelHeight();\n            if (!Number.isInteger(this.squarePixelHeight) || this.squarePixelHeight <= 0) {\n                throw new TypeError('getSquarePixelHeight() must return a positive integer.');\n            }\n            this.rotation = init.rotation ?? 0;\n            this.flip = init.flip ?? false;\n            this.timestamp = init.timestamp;\n            this.duration = init.duration ?? 0;\n            this.colorSpace = data.getColorSpace();\n        }\n        else {\n            throw new TypeError('Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.');\n        }\n        this.encodeOptions = init?.encodeOptions ?? {};\n        this.pixelAspectRatio = simplifyRational({\n            num: this.squarePixelWidth * this.codedHeight,\n            den: this.squarePixelHeight * this.codedWidth,\n        });\n        finalizationRegistry?.register(this, { type: 'video', data: this._data }, this);\n    }\n    /** Clones this video sample. */\n    clone() {\n        if (this._closed) {\n            throw new Error('VideoSample is closed.');\n        }\n        assert(this._data !== null);\n        if (this._data instanceof VideoSampleResource) {\n            return new VideoSample(this._data, {\n                timestamp: this.timestamp,\n                duration: this.duration,\n                rotation: this.rotation,\n                flip: this.flip,\n                encodeOptions: this.encodeOptions,\n            });\n        }\n        else if (isVideoFrame(this._data)) {\n            return new VideoSample(this._data.clone(), {\n                timestamp: this.timestamp,\n                duration: this.duration,\n                rotation: this.rotation,\n                flip: this.flip,\n                encodeOptions: this.encodeOptions,\n            });\n        }\n        else if (this._data instanceof Uint8Array) {\n            assert(this._layout);\n            return new VideoSample(this._data, {\n                format: this.format,\n                layout: this._layout,\n                codedWidth: this.codedWidth,\n                codedHeight: this.codedHeight,\n                timestamp: this.timestamp,\n                duration: this.duration,\n                colorSpace: this.colorSpace,\n                rotation: this.rotation,\n                flip: this.flip,\n                visibleRect: this.visibleRect,\n                displayWidth: this.displayWidth,\n                displayHeight: this.displayHeight,\n                encodeOptions: this.encodeOptions,\n                // It's already been copied, if we copy it again we make the clone unnecessarily expensive\n                _doNotCopy: true,\n            });\n        }\n        else {\n            return new VideoSample(this._data, {\n                format: this.format,\n                codedWidth: this.codedWidth,\n                codedHeight: this.codedHeight,\n                timestamp: this.timestamp,\n                duration: this.duration,\n                colorSpace: this.colorSpace,\n                rotation: this.rotation,\n                flip: this.flip,\n                visibleRect: this.visibleRect,\n                displayWidth: this.displayWidth,\n                displayHeight: this.displayHeight,\n                encodeOptions: this.encodeOptions,\n            });\n        }\n    }\n    /**\n     * Closes this video sample, releasing held resources. Video samples should be closed as soon as they are not\n     * needed anymore.\n     */\n    close() {\n        if (this._closed) {\n            return;\n        }\n        finalizationRegistry?.unregister(this);\n        if (this._data instanceof VideoSampleResource) {\n            this._data._referenceCount--;\n            if (this._data._referenceCount === 0) {\n                this._data.close();\n            }\n        }\n        else if (isVideoFrame(this._data)) {\n            this._data.close();\n        }\n        else {\n            this._data = null; // GC that shit\n        }\n        this._closed = true;\n    }\n    /**\n     * Returns the number of bytes required to hold this video sample's pixel data.\n     */\n    allocationSize(options = {}) {\n        validateVideoFrameCopyToOptions(options);\n        if (this._closed) {\n            throw new Error('VideoSample is closed.');\n        }\n        if ((options.format ?? this.format) == null) {\n            // https://github.com/Vanilagy/mediabunny/issues/267\n            // https://github.com/w3c/webcodecs/issues/920\n            throw new Error('Cannot get allocation size when format is null.');\n        }\n        if (isVideoFrame(this._data)) {\n            // Call the native method purely for performance\n            return this._data.allocationSize(options);\n        }\n        const combinedLayout = ParseVideoFrameCopyToOptions(this, options);\n        return combinedLayout.allocationSize;\n    }\n    /**\n     * Copies this video sample's pixel data to an ArrayBuffer or ArrayBufferView.\n     * @returns The byte layout of the planes of the copied data.\n     */\n    async copyTo(destination, options = {}) {\n        if (!isAllowSharedBufferSource(destination)) {\n            throw new TypeError('destination must be an ArrayBuffer or an ArrayBuffer view.');\n        }\n        validateVideoFrameCopyToOptions(options);\n        if (this._closed) {\n            throw new Error('VideoSample is closed.');\n        }\n        if ((options.format ?? this.format) == null) {\n            throw new Error('Cannot copy video sample data when format is null.');\n        }\n        assert(this._data !== null);\n        if (isVideoFrame(this._data)) {\n            return this._data.copyTo(destination, options);\n        }\n        // Detect non-RGB to RGB conversion\n        if (options.format\n            && !['RGBA', 'RGBX', 'BGRA', 'BGRX'].includes(this.format)\n            && ['RGBA', 'RGBX', 'BGRA', 'BGRX'].includes(options.format)) {\n            // RGB conversion for custom VideoSampleResource\n            if (this._data instanceof VideoSampleResource) {\n                const env_1 = { stack: [], error: void 0, hasError: false };\n                try {\n                    const rgbSample = __addDisposableResource(env_1, await this._data.toRgbSample({\n                        timestamp: this.timestamp,\n                        duration: this.duration,\n                        rotation: this.rotation,\n                        flip: this.flip,\n                    }, options.colorSpace ?? 'srgb'), false);\n                    if (!(rgbSample instanceof VideoSample)) {\n                        throw new TypeError('toRgbSample() must return a VideoSample.');\n                    }\n                    if (!['RGBA', 'RGBX', 'BGRA', 'BGRX'].includes(rgbSample.format)) {\n                        throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got`\n                            + ` '${rgbSample.format}' instead.`);\n                    }\n                    // Note that we DON'T force the RGB format to be exactly what was requested; any RGB format will do\n                    return await rgbSample.copyTo(destination, options); // 'await' is intentional here cuz of using\n                }\n                catch (e_1) {\n                    env_1.error = e_1;\n                    env_1.hasError = true;\n                }\n                finally {\n                    __disposeResources(env_1);\n                }\n            }\n            else {\n                if (typeof VideoFrame === 'undefined') {\n                    throw new Error('For this sample, converting from a non-RGB to an RGB format requires VideoFrame to'\n                        + ' be defined.');\n                }\n                const tempFrame = this.toVideoFrame();\n                const result = await tempFrame.copyTo(destination, options);\n                tempFrame.close();\n                return result;\n            }\n        }\n        const combinedLayout = ParseVideoFrameCopyToOptions(this, options);\n        assert(this.format);\n        // 4. If destination.byteLength is less than combinedLayout’s allocationSize, return a promise rejected with\n        const destBytes = toUint8Array(destination);\n        if (destBytes.byteLength < combinedLayout.allocationSize) {\n            throw new TypeError(`Destination buffer too small. Required: ${combinedLayout.allocationSize},`\n                + ` Available: ${destBytes.byteLength}`);\n        }\n        const planeConfigs = getPlaneConfigs(this.format);\n        let dataPlanes;\n        if (this._data instanceof VideoSampleResource) {\n            let result = this._data.getDataPlanes();\n            if (isThenable(result))\n                result = await result;\n            if (!Array.isArray(result)\n                || result.some(x => !(x.data instanceof Uint8Array) || !Number.isInteger(x.stride) || x.stride < 0)) {\n                throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array \"data\" property and a'\n                    + ' non-negative integer \"stride\" property.');\n            }\n            dataPlanes = result;\n        }\n        else if (this._data instanceof Uint8Array) {\n            assert(this._layout);\n            assert(this._layout.length === planeConfigs.length);\n            dataPlanes = this._layout.map((planeLayout, i) => {\n                const height = Math.ceil(this.codedHeight / planeConfigs[i].heightDivisor);\n                return {\n                    data: this._data.subarray(planeLayout.offset, planeLayout.offset + planeLayout.stride * height),\n                    stride: planeLayout.stride,\n                };\n            });\n        }\n        else {\n            const canvas = this._data;\n            const context = canvas.getContext('2d');\n            assert(context); // We already got it earlier so it's definitely available\n            const imageData = context.getImageData(0, 0, this.codedWidth, this.codedHeight);\n            dataPlanes = [{\n                    data: toUint8Array(imageData.data),\n                    stride: 4 * this.codedWidth,\n                }];\n        }\n        // Algo taken from WebCodecs spec:\n        // 6. Let p be a new Promise. (Implicit)\n        // 7. Let copyStepsQueue be the result of starting a new parallel queue. (Implicit)\n        // 8. Let planeLayouts be a new list.\n        const planeLayouts = [];\n        // Enqueue the following steps to copyStepsQueue: (fuck the queuing part)\n        // Let resource be the media resource referenced by [[resource reference]].\n        // (this.data)\n        // Let numPlanes be the number of planes as defined by [[format]].\n        const numPlanes = planeConfigs.length;\n        // Let planeIndex be 0.\n        // While planeIndex is less than combinedLayout’s numPlanes:\n        for (let planeIndex = 0; planeIndex < numPlanes; planeIndex++) {\n            const computedLayout = combinedLayout.computedLayouts[planeIndex];\n            // Let sourceStride be the stride of the plane in resource as identified by planeIndex.\n            const sourceStride = dataPlanes[planeIndex].stride;\n            const sourceData = dataPlanes[planeIndex].data;\n            // Let sourceOffset be the product of multiplying computedLayout’s sourceTop by sourceStride\n            let sourceOffset = computedLayout.sourceTop * sourceStride;\n            // Add computedLayout’s sourceLeftBytes to sourceOffset.\n            sourceOffset += computedLayout.sourceLeftBytes;\n            // Let destinationOffset be computedLayout’s destinationOffset.\n            let destinationOffset = computedLayout.destinationOffset;\n            // Let rowBytes be computedLayout’s sourceWidthBytes.\n            const rowBytes = computedLayout.sourceWidthBytes;\n            // Let layout be a new PlaneLayout, with offset set to destinationOffset and stride set to rowBytes.\n            // This is a spec error actually (https://github.com/w3c/webcodecs/issues/918)\n            const layout = {\n                offset: destinationOffset,\n                stride: computedLayout.destinationStride,\n            };\n            // Let row be 0.\n            // While row is less than computedLayout’s sourceHeight:\n            for (let row = 0; row < computedLayout.sourceHeight; row++) {\n                // Copy rowBytes bytes from resource starting at sourceOffset to destination starting\n                // at destinationOffset.\n                if (sourceOffset + rowBytes > sourceData.byteLength) {\n                    throw new Error(`Source buffer OOB read.`);\n                }\n                if (destinationOffset + rowBytes > destBytes.byteLength) {\n                    throw new Error(`Destination buffer OOB write.`);\n                }\n                const srcSub = sourceData.subarray(sourceOffset, sourceOffset + rowBytes);\n                destBytes.set(srcSub, destinationOffset);\n                // Increment sourceOffset by sourceStride.\n                sourceOffset += sourceStride;\n                // Increment destinationOffset by computedLayout’s destinationStride.\n                destinationOffset += computedLayout.destinationStride;\n            }\n            // Append layout to planeLayouts.\n            planeLayouts.push(layout);\n        }\n        // Now, handle converting between different RGB formats\n        if (options.format !== undefined) {\n            const needsRgbConversion = this.format.startsWith('RGB') !== options.format.startsWith('RGB');\n            // Going X->A requires setting the alpha to 255, going the other way doesn't since the value of X is w/e\n            const needsAlphaConversion = this.format.includes('X') && options.format.includes('A');\n            if (needsRgbConversion || needsAlphaConversion) {\n                // Loop over the destination bytes\n                for (let i = 0; i < combinedLayout.allocationSize; i += 4) {\n                    if (needsRgbConversion) {\n                        // Swap R with B\n                        const r = destBytes[i];\n                        const b = destBytes[i + 2];\n                        destBytes[i] = b;\n                        destBytes[i + 2] = r;\n                    }\n                    if (needsAlphaConversion) {\n                        destBytes[i + 3] = 255;\n                    }\n                }\n            }\n        }\n        // Queue a task to resolve p with planeLayouts.\n        return planeLayouts;\n    }\n    /**\n     * Converts this video sample to a VideoFrame for use with the WebCodecs API. The VideoFrame returned by this\n     * method *must* be closed separately from this video sample.\n     */\n    toVideoFrame() {\n        if (this._closed) {\n            throw new Error('VideoSample is closed.');\n        }\n        assert(this._data !== null);\n        if (this._data instanceof VideoSampleResource) {\n            if (this.format === null) {\n                throw new Error('Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.');\n            }\n            const planes = this._data.getDataPlanes();\n            if (isThenable(planes)) {\n                throw new Error('Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns'\n                    + ' a promise.');\n            }\n            // We can't use allocationSize since that method assumes a tight packing\n            const size = planes.reduce((a, b) => a + b.data.byteLength, 0);\n            const buffer = new Uint8Array(size);\n            let offset = 0;\n            const offsets = [];\n            for (const plane of planes) {\n                buffer.set(plane.data, offset);\n                offsets.push(offset);\n                offset += plane.data.byteLength;\n            }\n            return new VideoFrame(buffer, {\n                format: this.format,\n                layout: planes.map((x, i) => ({\n                    offset: offsets[i],\n                    stride: x.stride,\n                })),\n                codedWidth: this.codedWidth,\n                codedHeight: this.codedHeight,\n                timestamp: this.microsecondTimestamp,\n                duration: this.microsecondDuration,\n                colorSpace: this.colorSpace,\n                visibleRect: this.visibleRect,\n                displayWidth: this.squarePixelWidth, // Not display* since we're not passing rotation\n                displayHeight: this.squarePixelHeight,\n            });\n        }\n        else if (isVideoFrame(this._data)) {\n            return new VideoFrame(this._data, {\n                timestamp: this.microsecondTimestamp,\n                duration: this.microsecondDuration || undefined, // Drag 0 duration to undefined, glitches some codecs\n            });\n        }\n        else if (this._data instanceof Uint8Array) {\n            assert(this._layout);\n            return new VideoFrame(this._data, {\n                format: this.format,\n                codedWidth: this.codedWidth, // This is technically wrong! codedWidth is a lie technically. But, since\n                codedHeight: this.codedHeight, // we pass the layout (which contains the true coded width), we're good.\n                layout: this._layout,\n                timestamp: this.microsecondTimestamp,\n                duration: this.microsecondDuration || undefined,\n                colorSpace: this.colorSpace,\n                visibleRect: this.visibleRect,\n                displayWidth: this.squarePixelWidth, // Not display* since we're not passing rotation\n                displayHeight: this.squarePixelHeight,\n            });\n        }\n        else {\n            return new VideoFrame(this._data, {\n                timestamp: this.microsecondTimestamp,\n                duration: this.microsecondDuration || undefined,\n            });\n        }\n    }\n    draw(context, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) {\n        let sx = 0;\n        let sy = 0;\n        let sWidth = this.displayWidth;\n        let sHeight = this.displayHeight;\n        let dx = 0;\n        let dy = 0;\n        let dWidth = this.displayWidth;\n        let dHeight = this.displayHeight;\n        if (arg5 !== undefined) {\n            sx = arg1;\n            sy = arg2;\n            sWidth = arg3;\n            sHeight = arg4;\n            dx = arg5;\n            dy = arg6;\n            if (arg7 !== undefined) {\n                dWidth = arg7;\n                dHeight = arg8;\n            }\n            else {\n                dWidth = sWidth;\n                dHeight = sHeight;\n            }\n        }\n        else {\n            dx = arg1;\n            dy = arg2;\n            if (arg3 !== undefined) {\n                dWidth = arg3;\n                dHeight = arg4;\n            }\n        }\n        if (!((typeof CanvasRenderingContext2D !== 'undefined' && context instanceof CanvasRenderingContext2D)\n            || (typeof OffscreenCanvasRenderingContext2D !== 'undefined'\n                && context instanceof OffscreenCanvasRenderingContext2D))) {\n            throw new TypeError('context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.');\n        }\n        if (!Number.isFinite(sx)) {\n            throw new TypeError('sx must be a number.');\n        }\n        if (!Number.isFinite(sy)) {\n            throw new TypeError('sy must be a number.');\n        }\n        if (!Number.isFinite(sWidth) || sWidth < 0) {\n            throw new TypeError('sWidth must be a non-negative number.');\n        }\n        if (!Number.isFinite(sHeight) || sHeight < 0) {\n            throw new TypeError('sHeight must be a non-negative number.');\n        }\n        if (!Number.isFinite(dx)) {\n            throw new TypeError('dx must be a number.');\n        }\n        if (!Number.isFinite(dy)) {\n            throw new TypeError('dy must be a number.');\n        }\n        if (!Number.isFinite(dWidth) || dWidth < 0) {\n            throw new TypeError('dWidth must be a non-negative number.');\n        }\n        if (!Number.isFinite(dHeight) || dHeight < 0) {\n            throw new TypeError('dHeight must be a non-negative number.');\n        }\n        if (this._closed) {\n            throw new Error('VideoSample is closed.');\n        }\n        ({ sx, sy, sWidth, sHeight } = this._unmapSourceRegion(sx, sy, sWidth, sHeight, this.rotation, this.flip));\n        const source = this.toCanvasImageSource();\n        context.save();\n        const centerX = dx + dWidth / 2;\n        const centerY = dy + dHeight / 2;\n        context.translate(centerX, centerY);\n        // Canvas transforms apply to the image in reverse call order, so to rotate first and then flip, the flip has\n        // to be set up before the rotation\n        if (this.flip) {\n            context.scale(-1, 1);\n        }\n        context.rotate(this.rotation * Math.PI / 180);\n        const aspectRatioChange = this.rotation % 180 === 0 ? 1 : dWidth / dHeight;\n        // Scale to compensate for aspect ratio changes when rotated\n        context.scale(1 / aspectRatioChange, aspectRatioChange);\n        context.drawImage(source, sx, sy, sWidth, sHeight, -dWidth / 2, -dHeight / 2, dWidth, dHeight);\n        context.restore();\n    }\n    /**\n     * Draws the sample in the middle of the canvas corresponding to the context with the specified fit behavior.\n     */\n    drawWithFit(context, options) {\n        if (!((typeof CanvasRenderingContext2D !== 'undefined' && context instanceof CanvasRenderingContext2D)\n            || (typeof OffscreenCanvasRenderingContext2D !== 'undefined'\n                && context instanceof OffscreenCanvasRenderingContext2D))) {\n            throw new TypeError('context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.');\n        }\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (!['fill', 'contain', 'cover'].includes(options.fit)) {\n            throw new TypeError('options.fit must be \\'fill\\', \\'contain\\', or \\'cover\\'.');\n        }\n        if (options.rotation !== undefined && ![0, 90, 180, 270].includes(options.rotation)) {\n            throw new TypeError('options.rotation, when provided, must be 0, 90, 180, or 270.');\n        }\n        if (options.flip !== undefined && typeof options.flip !== 'boolean') {\n            throw new TypeError('options.flip, when provided, must be a boolean.');\n        }\n        if (options.crop !== undefined) {\n            validateCropRectangle(options.crop, 'options.');\n        }\n        const canvasWidth = context.canvas.width;\n        const canvasHeight = context.canvas.height;\n        const rotation = options.rotation ?? this.rotation;\n        const flip = options.flip ?? this.flip;\n        const [rotatedWidth, rotatedHeight] = rotation % 180 === 0\n            ? [this.squarePixelWidth, this.squarePixelHeight]\n            : [this.squarePixelHeight, this.squarePixelWidth];\n        let finalCrop = options.crop;\n        if (finalCrop) {\n            finalCrop = clampCropRectangle(finalCrop, rotatedWidth, rotatedHeight);\n        }\n        // These variables specify where the final sample will be drawn on the canvas\n        let dx;\n        let dy;\n        let newWidth;\n        let newHeight;\n        const { sx, sy, sWidth, sHeight } = this._unmapSourceRegion(options.crop?.left ?? 0, options.crop?.top ?? 0, options.crop?.width ?? rotatedWidth, options.crop?.height ?? rotatedHeight, rotation, flip);\n        if (options.fit === 'fill') {\n            dx = 0;\n            dy = 0;\n            newWidth = canvasWidth;\n            newHeight = canvasHeight;\n        }\n        else {\n            const [sampleWidth, sampleHeight] = options.crop\n                ? [options.crop.width, options.crop.height]\n                : [rotatedWidth, rotatedHeight];\n            const scale = options.fit === 'contain'\n                ? Math.min(canvasWidth / sampleWidth, canvasHeight / sampleHeight)\n                : Math.max(canvasWidth / sampleWidth, canvasHeight / sampleHeight);\n            newWidth = sampleWidth * scale;\n            newHeight = sampleHeight * scale;\n            dx = (canvasWidth - newWidth) / 2;\n            dy = (canvasHeight - newHeight) / 2;\n        }\n        context.save();\n        const aspectRatioChange = rotation % 180 === 0 ? 1 : newWidth / newHeight;\n        context.translate(canvasWidth / 2, canvasHeight / 2);\n        // Canvas transforms apply to the image in reverse call order, so to rotate first and then flip, the flip has\n        // to be set up before the rotation\n        if (flip) {\n            context.scale(-1, 1);\n        }\n        context.rotate(rotation * Math.PI / 180);\n        // This aspect ratio compensation is done so that we can draw the sample with the intended dimensions and\n        // don't need to think about how those dimensions change after the rotation\n        context.scale(1 / aspectRatioChange, aspectRatioChange);\n        context.translate(-canvasWidth / 2, -canvasHeight / 2);\n        // Important that we don't use .draw() here since that would take rotation and flip into account, but we wanna\n        // handle them ourselves here\n        context.drawImage(this.toCanvasImageSource(), sx, sy, sWidth, sHeight, dx, dy, newWidth, newHeight);\n        context.restore();\n    }\n    /** @internal */\n    _unmapSourceRegion(sx, sy, sWidth, sHeight, rotation, flip) {\n        // The provided sx,sy,sWidth,sHeight refer to the final rotated and flipped image, but that's not actually how\n        // the image is stored. Therefore, we must map these back onto the original image. Since the flip is applied\n        // last, we undo it first, mirroring within the rotated width.\n        if (flip) {\n            const rotatedWidth = rotation % 180 === 0 ? this.squarePixelWidth : this.squarePixelHeight;\n            sx = rotatedWidth - sx - sWidth;\n        }\n        if (rotation === 90) {\n            [sx, sy, sWidth, sHeight] = [\n                sy,\n                this.squarePixelHeight - sx - sWidth,\n                sHeight,\n                sWidth,\n            ];\n        }\n        else if (rotation === 180) {\n            [sx, sy] = [\n                this.squarePixelWidth - sx - sWidth,\n                this.squarePixelHeight - sy - sHeight,\n            ];\n        }\n        else if (rotation === 270) {\n            [sx, sy, sWidth, sHeight] = [\n                this.squarePixelWidth - sy - sHeight,\n                sx,\n                sHeight,\n                sWidth,\n            ];\n        }\n        return { sx, sy, sWidth, sHeight };\n    }\n    /**\n     * Draws the sample onto the target canvas with fit behavior, manually mipmapping on strong downscales for quality.\n     * @internal\n     */\n    _drawWithFitAndMipmapping(targetCanvas, targetContext, options) {\n        const targetWidth = targetCanvas.width;\n        const targetHeight = targetCanvas.height;\n        const [rotatedWidth, rotatedHeight] = options.rotation % 180 === 0\n            ? [this.squarePixelWidth, this.squarePixelHeight]\n            : [this.squarePixelHeight, this.squarePixelWidth];\n        const sourceWidth = options.crop ? options.crop.width : rotatedWidth;\n        const sourceHeight = options.crop ? options.crop.height : rotatedHeight;\n        // Once we downscale by more than 2x, bilinear filtering starts skipping pixels and the result aliases. So in\n        // that case, we do manual mipmapping: draw at a larger size first, then iteratively halve the image until we\n        // arrive at the target size. Sucks that we have to do this honestly, but imageSmoothingQuality is very flaky -\n        // some resources are just not mipmapped in the browser and thus always fall back to bilinear downsampling.\n        let mipLevels = 0;\n        if (2 * targetWidth < sourceWidth && 2 * targetHeight < sourceHeight) {\n            mipLevels = Math.floor(Math.log2(Math.min(sourceWidth / targetWidth, sourceHeight / targetHeight)));\n        }\n        const drawWidth = targetWidth * 2 ** mipLevels;\n        const drawHeight = targetHeight * 2 ** mipLevels;\n        const { canvas, context, isNew } = mipLevels > 0\n            ? getTransformationCanvas(drawWidth, drawHeight)\n            : { canvas: targetCanvas, context: targetContext, isNew: options.targetIsFresh };\n        context.imageSmoothingQuality = 'high';\n        if (options.fillBlack) {\n            context.fillStyle = 'black';\n            context.fillRect(0, 0, drawWidth, drawHeight);\n        }\n        else if (!isNew) {\n            // Reused canvases carry stale pixels from a prior draw\n            context.clearRect(0, 0, drawWidth, drawHeight);\n        }\n        this.drawWithFit(context, {\n            fit: options.fit,\n            rotation: options.rotation,\n            flip: options.flip,\n            crop: options.crop,\n        });\n        // Walk down the mip chain by repeatedly drawing the canvas onto itself at half size. The 'copy' composite\n        // operation makes sure pixels get replaced instead of blended with what's already there.\n        context.globalCompositeOperation = 'copy';\n        for (let i = mipLevels; i > 1; i--) {\n            const levelWidth = targetWidth * 2 ** i;\n            const levelHeight = targetHeight * 2 ** i;\n            context.drawImage(canvas, 0, 0, levelWidth, levelHeight, 0, 0, levelWidth / 2, levelHeight / 2);\n        }\n        context.globalCompositeOperation = 'source-over';\n        if (mipLevels > 0) {\n            // We'd love to skip this step and hand over the oversized mip canvas cropped with visibleRect, but sadly,\n            // all browsers ignore a frame's visibleRect when encoding it and consume the full coded frame instead\n            // (violating the WebCodecs spec, I think? See https://issues.chromium.org/issues/543284189). So, the result\n            // must live on a canvas of exactly the target size, which is why the last halving step draws onto the\n            // target canvas directly. 'copy' also conveniently disposes of any stale pixels there.\n            targetContext.imageSmoothingQuality = 'high';\n            targetContext.globalCompositeOperation = 'copy';\n            targetContext.drawImage(canvas, 0, 0, 2 * targetWidth, 2 * targetHeight, 0, 0, targetWidth, targetHeight);\n            targetContext.globalCompositeOperation = 'source-over';\n        }\n    }\n    /**\n     * Converts this video sample to a\n     * [`CanvasImageSource`](https://udn.realityripple.com/docs/Web/API/CanvasImageSource) for drawing to a canvas.\n     *\n     * You must use the value returned by this method immediately, as any VideoFrame created internally may\n     * automatically be closed in the next microtask.\n     */\n    toCanvasImageSource() {\n        if (this._closed) {\n            throw new Error('VideoSample is closed.');\n        }\n        assert(this._data !== null);\n        if (this._data instanceof VideoSampleResource || this._data instanceof Uint8Array) {\n            // Requires VideoFrame to be defined\n            const videoFrame = this.toVideoFrame();\n            queueMicrotask(() => videoFrame.close()); // Let's automatically close the frame in the next microtask\n            return videoFrame;\n        }\n        else {\n            return this._data;\n        }\n    }\n    /**\n     * Transform this video sample to a new video sample given the options. Can be used to resize, rotate, flip, and\n     * crop the sample.\n     *\n     * In non-browser environments, this method will not work by default. To make it work, register a custom\n     * transformer function via {@link registerVideoSampleTransformer}.\n     */\n    async transform(options) {\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.width !== undefined && (!Number.isInteger(options.width) || options.width <= 0)) {\n            throw new TypeError('options.width, when provided, must be a positive integer.');\n        }\n        if (options.height !== undefined && (!Number.isInteger(options.height) || options.height <= 0)) {\n            throw new TypeError('options.height, when provided, must be a positive integer.');\n        }\n        if (options.roundDimensionsTo !== undefined\n            && (!Number.isInteger(options.roundDimensionsTo) || options.roundDimensionsTo <= 0)) {\n            throw new TypeError('options.roundDimensionsTo, when provided, must be a positive integer.');\n        }\n        if (options.fit !== undefined && !['fill', 'contain', 'cover'].includes(options.fit)) {\n            throw new TypeError('options.fit, when provided, must be one of \"fill\", \"contain\", or \"cover\".');\n        }\n        if (options.width !== undefined\n            && options.height !== undefined\n            && options.fit === undefined) {\n            throw new TypeError('When both options.width and options.height are provided, options.fit must also be provided.');\n        }\n        if (options.rotate !== undefined && ![0, 90, 180, 270].includes(options.rotate)) {\n            throw new TypeError('options.rotate, when provided, must be 0, 90, 180 or 270.');\n        }\n        if (options.flip !== undefined && typeof options.flip !== 'boolean') {\n            throw new TypeError('options.flip, when provided, must be a boolean.');\n        }\n        if (options.crop !== undefined) {\n            validateCropRectangle(options.crop, 'options.');\n        }\n        if (options.alpha !== undefined && !['keep', 'discard'].includes(options.alpha)) {\n            throw new TypeError('options.alpha, when provided, must be \\'keep\\' or \\'discard\\'.');\n        }\n        const { rotation, flip } = composeRotationAndFlip(this.rotation, this.flip, options.rotate ?? 0, options.flip ?? false);\n        const [rotatedWidth, rotatedHeight] = rotation % 180 === 0\n            ? [this.squarePixelWidth, this.squarePixelHeight]\n            : [this.squarePixelHeight, this.squarePixelWidth];\n        // Clamp crop rectangle to the rotated video dimensions\n        let finalCrop = options.crop;\n        if (finalCrop) {\n            finalCrop = clampCropRectangle(finalCrop, rotatedWidth, rotatedHeight);\n        }\n        const cropWidth = finalCrop ? finalCrop.width : rotatedWidth;\n        const cropHeight = finalCrop ? finalCrop.height : rotatedHeight;\n        const originalAspectRatio = cropWidth / cropHeight;\n        let targetWidth;\n        let targetHeight;\n        if (options.width !== undefined && options.height === undefined) {\n            targetWidth = options.width;\n            targetHeight = targetWidth / originalAspectRatio;\n        }\n        else if (options.width === undefined && options.height !== undefined) {\n            targetHeight = options.height;\n            targetWidth = targetHeight * originalAspectRatio;\n        }\n        else if (options.width !== undefined && options.height !== undefined) {\n            targetWidth = options.width;\n            targetHeight = options.height;\n        }\n        else {\n            targetWidth = cropWidth;\n            targetHeight = cropHeight;\n        }\n        targetWidth = roundToMultiple(targetWidth, options.roundDimensionsTo ?? 1);\n        targetHeight = roundToMultiple(targetHeight, options.roundDimensionsTo ?? 1);\n        const description = {\n            width: targetWidth,\n            height: targetHeight,\n            fit: options.fit ?? 'fill',\n            rotation,\n            flip,\n            crop: finalCrop ?? {\n                left: 0,\n                top: 0,\n                width: rotatedWidth,\n                height: rotatedHeight,\n            },\n            alpha: options.alpha ?? 'keep',\n        };\n        // Description's finalized; let's see if a registered transformer wants to handle it\n        for (const transformer of registeredVideoSampleTransformers) {\n            let result = transformer(this, description);\n            if (isThenable(result))\n                result = await result;\n            if (result !== null) {\n                return result;\n            }\n        }\n        // We need to handle it ourselves, and we use canvases to do it\n        const { canvas, context, isNew } = getTransformationCanvas(description.width, description.height);\n        this._drawWithFitAndMipmapping(canvas, context, {\n            fit: description.fit,\n            rotation: description.rotation,\n            flip: description.flip,\n            crop: description.crop,\n            targetIsFresh: isNew,\n            fillBlack: description.alpha === 'discard',\n        });\n        return new VideoSample(canvas, {\n            timestamp: this.timestamp,\n            duration: this.duration,\n            // Any previous rotation and flip are now baked in\n            rotation: 0,\n            flip: false,\n        });\n    }\n    /** Sets the rotation metadata of this video sample. */\n    setRotation(newRotation) {\n        if (![0, 90, 180, 270].includes(newRotation)) {\n            throw new TypeError('newRotation must be 0, 90, 180, or 270.');\n        }\n        // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n        this.rotation = newRotation;\n    }\n    /** Sets the flip metadata of this video sample. */\n    setFlip(newFlip) {\n        if (typeof newFlip !== 'boolean') {\n            throw new TypeError('newFlip must be a boolean.');\n        }\n        // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n        this.flip = newFlip;\n    }\n    /** Sets the presentation timestamp of this video sample, in seconds. */\n    setTimestamp(newTimestamp) {\n        if (!Number.isFinite(newTimestamp)) {\n            throw new TypeError('newTimestamp must be a number.');\n        }\n        // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n        this.timestamp = newTimestamp;\n    }\n    /** Sets the duration of this video sample, in seconds. */\n    setDuration(newDuration) {\n        if (!Number.isFinite(newDuration) || newDuration < 0) {\n            throw new TypeError('newDuration must be a non-negative number.');\n        }\n        // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n        this.duration = newDuration;\n    }\n    /** Sets the encode options used when this sample is passed to an encoder. */\n    setEncodeOptions(newEncodeOptions) {\n        if (!newEncodeOptions || typeof newEncodeOptions !== 'object') {\n            throw new TypeError('newEncodeOptions must be an object.');\n        }\n        // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n        this.encodeOptions = newEncodeOptions;\n    }\n    /** Calls `.close()`. */\n    [Symbol.dispose]() {\n        this.close();\n    }\n}\nconst registeredVideoSampleTransformers = [];\n/**\n * Registers a callback to handle the transformation of {@link VideoSample} instances. The callback can either return\n * the transformed sample, or `null` to indicate that it doesn't want to handle the given transformation task.\n * @group Samples\n * @public\n */\nexport const registerVideoSampleTransformer = (transformer) => {\n    if (registeredVideoSampleTransformers.includes(transformer)) {\n        return; // Already in there\n    }\n    registeredVideoSampleTransformers.push(transformer);\n};\nconst TRANSFORMATION_CANVAS_CACHE_MAX_SIZE = 3;\nconst transformationCanvasCache = [];\nlet transformationCanvasCacheNextAge = 0;\nconst getTransformationCanvas = (width, height) => {\n    for (const entry of transformationCanvasCache) {\n        if (entry.canvas.width === width && entry.canvas.height === height) {\n            entry.age = transformationCanvasCacheNextAge++;\n            return { canvas: entry.canvas, context: entry.context, isNew: false };\n        }\n    }\n    let canvas;\n    if (typeof OffscreenCanvas !== 'undefined') {\n        canvas = new OffscreenCanvas(width, height);\n    }\n    else {\n        if (typeof window === 'undefined' || typeof document === 'undefined') {\n            throw new Error('Cannot transform VideoSamples in this environment. Either run in an environment with'\n                + ' OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using'\n                + ' registerVideoSampleTransformer().');\n        }\n        canvas = document.createElement('canvas');\n        canvas.width = width;\n        canvas.height = height;\n    }\n    const context = canvas.getContext('2d', {\n        alpha: true,\n        willReadFrequently: false,\n    });\n    if (!context) {\n        throw new Error('The \\'2d\\' canvas context is required to transform VideoSamples. Register a custom transformer using'\n            + ' registerVideoSampleTransformer to work around this limitation.');\n    }\n    if (transformationCanvasCache.length >= TRANSFORMATION_CANVAS_CACHE_MAX_SIZE) {\n        transformationCanvasCache.splice(arrayArgmin(transformationCanvasCache, x => x.age), 1);\n    }\n    transformationCanvasCache.push({\n        canvas,\n        context,\n        age: transformationCanvasCacheNextAge++,\n    });\n    return { canvas, context, isNew: true };\n};\n/**\n * Describes the color space of a {@link VideoSample}. Corresponds to the WebCodecs API's VideoColorSpace.\n * @group Samples\n * @public\n */\nexport class VideoSampleColorSpace {\n    /** Creates a new VideoSampleColorSpace. */\n    constructor(init) {\n        if (init !== undefined) {\n            if (!init || typeof init !== 'object') {\n                throw new TypeError('init.colorSpace, when provided, must be an object.');\n            }\n            const primariesValues = Object.keys(COLOR_PRIMARIES_MAP);\n            if (init.primaries != null && !primariesValues.includes(init.primaries)) {\n                throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${primariesValues.join(', ')}.`);\n            }\n            const transferValues = Object.keys(TRANSFER_CHARACTERISTICS_MAP);\n            if (init.transfer != null && !transferValues.includes(init.transfer)) {\n                throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${transferValues.join(', ')}.`);\n            }\n            const matrixValues = Object.keys(MATRIX_COEFFICIENTS_MAP);\n            if (init.matrix != null && !matrixValues.includes(init.matrix)) {\n                throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${matrixValues.join(', ')}.`);\n            }\n            if (init.fullRange != null && typeof init.fullRange !== 'boolean') {\n                throw new TypeError('init.colorSpace.fullRange, when provided, must be a boolean.');\n            }\n        }\n        this.primaries = init?.primaries ?? null;\n        this.transfer = init?.transfer ?? null;\n        this.matrix = init?.matrix ?? null;\n        this.fullRange = init?.fullRange ?? null;\n    }\n    /** Serializes the color space to a JSON object. */\n    toJSON() {\n        return {\n            primaries: this.primaries,\n            transfer: this.transfer,\n            matrix: this.matrix,\n            fullRange: this.fullRange,\n        };\n    }\n}\nconst isVideoFrame = (x) => {\n    return typeof VideoFrame !== 'undefined' && x instanceof VideoFrame;\n};\nexport const clampCropRectangle = (crop, outerWidth, outerHeight) => {\n    const left = Math.min(crop.left, outerWidth);\n    const top = Math.min(crop.top, outerHeight);\n    const width = Math.min(crop.width, outerWidth - left);\n    const height = Math.min(crop.height, outerHeight - top);\n    assert(width >= 0);\n    assert(height >= 0);\n    return { left, top, width, height };\n};\nexport const validateCropRectangle = (crop, prefix) => {\n    if (!crop || typeof crop !== 'object') {\n        throw new TypeError(prefix + 'crop, when provided, must be an object.');\n    }\n    if (!Number.isInteger(crop.left) || crop.left < 0) {\n        throw new TypeError(prefix + 'crop.left must be a non-negative integer.');\n    }\n    if (!Number.isInteger(crop.top) || crop.top < 0) {\n        throw new TypeError(prefix + 'crop.top must be a non-negative integer.');\n    }\n    if (!Number.isInteger(crop.width) || crop.width < 0) {\n        throw new TypeError(prefix + 'crop.width must be a non-negative integer.');\n    }\n    if (!Number.isInteger(crop.height) || crop.height < 0) {\n        throw new TypeError(prefix + 'crop.height must be a non-negative integer.');\n    }\n};\nconst validateVideoFrameCopyToOptions = (options) => {\n    if (!options || typeof options !== 'object') {\n        throw new TypeError('options must be an object.');\n    }\n    if (options.colorSpace !== undefined && !['display-p3', 'srgb'].includes(options.colorSpace)) {\n        throw new TypeError('options.colorSpace, when provided, must be \\'display-p3\\' or \\'srgb\\'.');\n    }\n    if (options.format !== undefined && typeof options.format !== 'string') {\n        throw new TypeError('options.format, when provided, must be a string.');\n    }\n    if (options.layout !== undefined) {\n        if (!Array.isArray(options.layout)) {\n            throw new TypeError('options.layout, when provided, must be an array.');\n        }\n        for (const plane of options.layout) {\n            if (!plane || typeof plane !== 'object') {\n                throw new TypeError('Each entry in options.layout must be an object.');\n            }\n            if (!Number.isInteger(plane.offset) || plane.offset < 0) {\n                throw new TypeError('plane.offset must be a non-negative integer.');\n            }\n            if (!Number.isInteger(plane.stride) || plane.stride < 0) {\n                throw new TypeError('plane.stride must be a non-negative integer.');\n            }\n        }\n    }\n    if (options.rect !== undefined) {\n        if (!options.rect || typeof options.rect !== 'object') {\n            throw new TypeError('options.rect, when provided, must be an object.');\n        }\n        if (options.rect.x !== undefined && (!Number.isInteger(options.rect.x) || options.rect.x < 0)) {\n            throw new TypeError('options.rect.x, when provided, must be a non-negative integer.');\n        }\n        if (options.rect.y !== undefined && (!Number.isInteger(options.rect.y) || options.rect.y < 0)) {\n            throw new TypeError('options.rect.y, when provided, must be a non-negative integer.');\n        }\n        if (options.rect.width !== undefined && (!Number.isInteger(options.rect.width) || options.rect.width < 0)) {\n            throw new TypeError('options.rect.width, when provided, must be a non-negative integer.');\n        }\n        if (options.rect.height !== undefined && (!Number.isInteger(options.rect.height) || options.rect.height < 0)) {\n            throw new TypeError('options.rect.height, when provided, must be a non-negative integer.');\n        }\n    }\n};\n/** Implements logic from WebCodecs § 9.4.6 \"Compute Layout and Allocation Size\" */\nconst createDefaultPlaneLayout = (format, codedWidth, codedHeight) => {\n    const planes = getPlaneConfigs(format);\n    const layouts = [];\n    let currentOffset = 0;\n    for (const plane of planes) {\n        // Per § 9.8, dimensions are usually \"rounded up to the nearest integer\".\n        const planeWidth = Math.ceil(codedWidth / plane.widthDivisor);\n        const planeHeight = Math.ceil(codedHeight / plane.heightDivisor);\n        const stride = planeWidth * plane.sampleBytes;\n        // Tight packing\n        const planeSize = stride * planeHeight;\n        layouts.push({\n            offset: currentOffset,\n            stride: stride,\n        });\n        currentOffset += planeSize;\n    }\n    return layouts;\n};\n/** Helper to retrieve plane configurations based on WebCodecs § 9.8 Pixel Format definitions. */\nexport const getPlaneConfigs = (format) => {\n    // Helper for standard YUV planes\n    const yuv = (yBytes, uvBytes, subX, subY, hasAlpha) => {\n        const configs = [\n            { sampleBytes: yBytes, widthDivisor: 1, heightDivisor: 1 },\n            { sampleBytes: uvBytes, widthDivisor: subX, heightDivisor: subY },\n            { sampleBytes: uvBytes, widthDivisor: subX, heightDivisor: subY },\n        ];\n        if (hasAlpha) {\n            // Match luma dimensions\n            configs.push({ sampleBytes: yBytes, widthDivisor: 1, heightDivisor: 1 });\n        }\n        return configs;\n    };\n    switch (format) {\n        case 'I420':\n            return yuv(1, 1, 2, 2, false);\n        case 'I420P10':\n        case 'I420P12':\n            return yuv(2, 2, 2, 2, false);\n        case 'I420A':\n            return yuv(1, 1, 2, 2, true);\n        case 'I420AP10':\n        case 'I420AP12':\n            return yuv(2, 2, 2, 2, true);\n        case 'I422':\n            return yuv(1, 1, 2, 1, false);\n        case 'I422P10':\n        case 'I422P12':\n            return yuv(2, 2, 2, 1, false);\n        case 'I422A':\n            return yuv(1, 1, 2, 1, true);\n        case 'I422AP10':\n        case 'I422AP12':\n            return yuv(2, 2, 2, 1, true);\n        case 'I444':\n            return yuv(1, 1, 1, 1, false);\n        case 'I444P10':\n        case 'I444P12':\n            return yuv(2, 2, 1, 1, false);\n        case 'I444A':\n            return yuv(1, 1, 1, 1, true);\n        case 'I444AP10':\n        case 'I444AP12':\n            return yuv(2, 2, 1, 1, true);\n        case 'NV12':\n            return [\n                { sampleBytes: 1, widthDivisor: 1, heightDivisor: 1 },\n                { sampleBytes: 2, widthDivisor: 2, heightDivisor: 2 }, // Interleaved U and V\n            ];\n        case 'RGBA':\n        case 'RGBX':\n        case 'BGRA':\n        case 'BGRX':\n            return [\n                { sampleBytes: 4, widthDivisor: 1, heightDivisor: 1 },\n            ];\n        default:\n            assertNever(format);\n            assert(false);\n    }\n};\n/** Taken from the WebCodecs spec. */\nconst ParseVideoFrameCopyToOptions = (sample, options) => {\n    // 1. Let defaultRect be the result of performing the getter steps for visibleRect.\n    const defaultRect = {\n        left: 0,\n        top: 0,\n        width: sample.codedWidth,\n        height: sample.codedHeight,\n    };\n    // 2. Let overrideRect be undefined.\n    // 3. If options.rect exists, assign the value of options.rect to overrideRect.\n    const overrideRect = options.rect;\n    // 4. Let parsedRect be the result of running the Parse Visible Rect algorithm...\n    const parsedRect = ParseVisibleRect(defaultRect, overrideRect, sample.codedWidth, sample.codedHeight, sample.format);\n    // 5. If parsedRect is an exception, return parsedRect. (Handled by throw)\n    // 6. Let optLayout be undefined.\n    // 7. If options.layout exists, assign its value to optLayout.\n    const optLayout = options.layout;\n    // 8. Let format be undefined.\n    let format;\n    // 9. If options.format does not exist, assign [[format]] to format.\n    if (!options.format || options.format === sample.format) {\n        format = sample.format;\n    }\n    else if (['RGBA', 'RGBX', 'BGRA', 'BGRX'].includes(options.format)) {\n        // 10. Otherwise, if options.format is equal to one of RGBA, RGBX, BGRA, BGRX, then assign options.format\n        //  to format...\n        format = options.format;\n    }\n    else {\n        throw new Error('NotSupportedError: Invalid destination format.');\n    }\n    // 11. Let combinedLayout be the result of running the Compute Layout and Allocation Size algorithm...\n    return ComputeLayoutAndAllocationSize(parsedRect, format, optLayout);\n};\n/** Taken from the WebCodecs spec. */\nconst ParseVisibleRect = (defaultRect, overrideRect, codedWidth, codedHeight, format) => {\n    // 1. Let sourceRect be defaultRect\n    const sourceRect = { ...defaultRect };\n    // 2. If overrideRect is not undefined:\n    if (overrideRect !== undefined) {\n        // If either of overrideRect.width or height is 0, return a TypeError.\n        if (overrideRect.width === 0 || overrideRect.height === 0) {\n            throw new TypeError('visibleRect dimensions cannot be zero.');\n        }\n        // If the sum of overrideRect.x and overrideRect.width is greater than codedWidth, return a TypeError.\n        if ((overrideRect.x || 0) + (overrideRect.width || 0) > codedWidth) {\n            throw new TypeError('visibleRect exceeds codedWidth.');\n        }\n        // If the sum of overrideRect.y and overrideRect.height is greater than codedHeight, return a TypeError.\n        if ((overrideRect.y || 0) + (overrideRect.height || 0) > codedHeight) {\n            throw new TypeError('visibleRect exceeds codedHeight.');\n        }\n        // Assign overrideRect to sourceRect.\n        sourceRect.x = overrideRect.x || 0;\n        sourceRect.y = overrideRect.y || 0;\n        sourceRect.width = overrideRect.width || 0;\n        sourceRect.height = overrideRect.height || 0;\n    }\n    // 3. Let validAlignment be the result of running the Verify Rect Offset Alignment algorithm.\n    const validAlignment = VerifyRectOffsetAlignment(format, sourceRect);\n    // 4. If validAlignment is false, throw a TypeError.\n    if (!validAlignment) {\n        throw new TypeError('visibleRect alignment is invalid for the format.');\n    }\n    // 5. Return sourceRect.\n    return sourceRect;\n};\n/** Taken from the WebCodecs spec. */\nconst VerifyRectOffsetAlignment = (format, rect) => {\n    // 1. If format is null, return true.\n    if (format === null)\n        return true;\n    const planes = getPlaneConfigs(format);\n    // 2. Let planeIndex be 0.\n    // 3. Let numPlanes be the number of planes as defined by format.\n    // 4. While planeIndex is less than numPlanes:\n    for (let planeIndex = 0; planeIndex < planes.length; planeIndex++) {\n        const plane = planes[planeIndex];\n        const sampleWidth = plane.widthDivisor;\n        const sampleHeight = plane.heightDivisor;\n        // If rect.x is not a multiple of sampleWidth, return false.\n        if ((rect.x || 0) % sampleWidth !== 0)\n            return false;\n        // If rect.y is not a multiple of sampleHeight, return false.\n        if ((rect.y || 0) % sampleHeight !== 0)\n            return false;\n    }\n    return true;\n};\n/** Taken from the WebCodecs spec. */\nconst ComputeLayoutAndAllocationSize = (parsedRect, format, layout) => {\n    const planes = getPlaneConfigs(format);\n    // 1. Let numPlanes be the number of planes as defined by format.\n    const numPlanes = planes.length;\n    // 2. If layout is not undefined and its length does not equal numPlanes, throw a TypeError.\n    if (layout !== undefined && layout.length !== numPlanes) {\n        throw new TypeError(`Layout must have ${numPlanes} planes.`);\n    }\n    // 3. Let minAllocationSize be 0.\n    let minAllocationSize = 0;\n    // 4. Let computedLayouts be a new list.\n    const computedLayouts = [];\n    // 5. Let endOffsets be a new list.\n    const endOffsets = [];\n    // 6. Let planeIndex be 0.\n    // 7. While planeIndex < numPlanes:\n    for (let planeIndex = 0; planeIndex < numPlanes; planeIndex++) {\n        const plane = planes[planeIndex];\n        const sampleBytes = plane.sampleBytes;\n        const sampleWidth = plane.widthDivisor;\n        const sampleHeight = plane.heightDivisor;\n        // Let computedLayout be a new computed plane layout.\n        const computedLayout = {\n            destinationOffset: 0,\n            destinationStride: 0,\n            sourceTop: 0,\n            sourceHeight: 0,\n            sourceLeftBytes: 0,\n            sourceWidthBytes: 0,\n        };\n        // Set computedLayout’s sourceTop...\n        computedLayout.sourceTop = Math.ceil(Math.trunc(parsedRect.y || 0) / sampleHeight);\n        // Set computedLayout’s sourceHeight...\n        computedLayout.sourceHeight = Math.ceil(Math.trunc(parsedRect.height || 0) / sampleHeight);\n        // Set computedLayout’s sourceLeftBytes...\n        computedLayout.sourceLeftBytes = Math.floor(Math.trunc(parsedRect.x || 0) / sampleWidth) * sampleBytes;\n        // Set computedLayout’s sourceWidthBytes...\n        computedLayout.sourceWidthBytes = Math.floor(Math.trunc(parsedRect.width || 0) / sampleWidth) * sampleBytes;\n        // If layout is not undefined:\n        if (layout !== undefined) {\n            const planeLayout = layout[planeIndex];\n            // If planeLayout.stride is less than computedLayout’s sourceWidthBytes, return a TypeError.\n            if (planeLayout.stride < computedLayout.sourceWidthBytes) {\n                throw new TypeError(`Stride for plane ${planeIndex} is too small.`);\n            }\n            // Assign planeLayout.offset to computedLayout’s destinationOffset.\n            computedLayout.destinationOffset = planeLayout.offset;\n            // Assign planeLayout.stride to computedLayout’s destinationStride.\n            computedLayout.destinationStride = planeLayout.stride;\n        }\n        else {\n            // Otherwise:\n            // Assign minAllocationSize to computedLayout’s destinationOffset.\n            computedLayout.destinationOffset = minAllocationSize;\n            // Assign computedLayout’s sourceWidthBytes to computedLayout’s destinationStride.\n            computedLayout.destinationStride = computedLayout.sourceWidthBytes;\n        }\n        // Let planeSize be the product of multiplying computedLayout’s destinationStride and sourceHeight.\n        const planeSize = computedLayout.destinationStride * computedLayout.sourceHeight;\n        // Let planeEnd be the sum of planeSize and computedLayout’s destinationOffset.\n        const planeEnd = planeSize + computedLayout.destinationOffset;\n        // If planeSize or planeEnd is greater than maximum range of unsigned long, return a TypeError.\n        if (planeEnd > 4294967295) {\n            throw new TypeError('Allocation size exceeds limit.');\n        }\n        // Append planeEnd to endOffsets.\n        endOffsets.push(planeEnd);\n        // Assign the maximum of minAllocationSize and planeEnd to minAllocationSize.\n        minAllocationSize = Math.max(minAllocationSize, planeEnd);\n        // Check for overlap\n        for (let earlierPlaneIndex = 0; earlierPlaneIndex < planeIndex; earlierPlaneIndex++) {\n            const earlierLayout = computedLayouts[earlierPlaneIndex];\n            // If plane A ends before plane B starts, they do not overlap.\n            if (endOffsets[planeIndex] <= earlierLayout.destinationOffset\n                || endOffsets[earlierPlaneIndex] <= computedLayout.destinationOffset) {\n                continue;\n            }\n            throw new TypeError('Planes overlap.');\n        }\n        computedLayouts.push(computedLayout);\n    }\n    // 12. Return combinedLayout.\n    return {\n        allocationSize: minAllocationSize,\n        computedLayouts: computedLayouts,\n    };\n};\nconst AUDIO_SAMPLE_FORMATS = new Set(['f32', 'f32-planar', 's16', 's16-planar', 's32', 's32-planar', 'u8', 'u8-planar']);\n/**\n * Abstract base class for custom audio sample resources. Implement this class to provide custom backing\n * for AudioSample instances.\n * @group Samples\n * @public\n */\nexport class AudioSampleResource {\n    constructor() {\n        /** @internal */\n        this._referenceCount = 0;\n    }\n}\n/**\n * Represents a raw, unencoded audio sample. Mainly used as an expressive wrapper around WebCodecs API's\n * [`AudioData`](https://developer.mozilla.org/en-US/docs/Web/API/AudioData), but can also be used standalone.\n * @group Samples\n * @public\n */\nexport class AudioSample {\n    /** The presentation timestamp of the sample in microseconds. */\n    get microsecondTimestamp() {\n        return Math.trunc(SECOND_TO_MICROSECOND_FACTOR * this.timestamp);\n    }\n    /** The duration of the sample in microseconds. */\n    get microsecondDuration() {\n        return Math.trunc(SECOND_TO_MICROSECOND_FACTOR * this.duration);\n    }\n    constructor(init) {\n        /** @internal */\n        this._closed = false;\n        if (isAudioData(init)) {\n            if (init.format === null) {\n                throw new TypeError('AudioData with null format is not supported.');\n            }\n            this._data = init;\n            this.format = init.format;\n            this.sampleRate = init.sampleRate;\n            this.numberOfFrames = init.numberOfFrames;\n            this.numberOfChannels = init.numberOfChannels;\n            this.timestamp = init.timestamp / 1e6;\n            this.duration = init.numberOfFrames / init.sampleRate;\n        }\n        else if (init instanceof AudioSampleResource) {\n            this._data = init;\n            init._referenceCount++;\n            this.format = init.getFormat();\n            if (!AUDIO_SAMPLE_FORMATS.has(this.format)) {\n                throw new TypeError('getFormat() must return an AudioSampleFormat.');\n            }\n            this.sampleRate = init.getSampleRate();\n            if (!Number.isInteger(this.sampleRate) || this.sampleRate <= 0) {\n                throw new TypeError('getSampleRate() must return a positive integer.');\n            }\n            this.numberOfFrames = init.getNumberOfFrames();\n            if (!Number.isInteger(this.numberOfFrames) || this.numberOfFrames < 0) {\n                throw new TypeError('getNumberOfFrames() must return a non-negative integer.');\n            }\n            this.numberOfChannels = init.getNumberOfChannels();\n            if (!Number.isInteger(this.numberOfChannels) || this.numberOfChannels <= 0) {\n                throw new TypeError('getNumberOfChannels() must return a positive integer.');\n            }\n            this.timestamp = init.getTimestamp();\n            if (!Number.isFinite(this.timestamp)) {\n                throw new TypeError('getTimestamp() must return a finite number.');\n            }\n            this.duration = this.numberOfFrames / this.sampleRate;\n        }\n        else {\n            if (!init || typeof init !== 'object') {\n                throw new TypeError('Invalid AudioDataInit: must be an object.');\n            }\n            if (!AUDIO_SAMPLE_FORMATS.has(init.format)) {\n                throw new TypeError('Invalid AudioDataInit: invalid format.');\n            }\n            if (!Number.isFinite(init.sampleRate) || init.sampleRate <= 0) {\n                throw new TypeError('Invalid AudioDataInit: sampleRate must be > 0.');\n            }\n            if (!Number.isInteger(init.numberOfChannels) || init.numberOfChannels === 0) {\n                throw new TypeError('Invalid AudioDataInit: numberOfChannels must be an integer > 0.');\n            }\n            if (!Number.isFinite(init?.timestamp)) {\n                throw new TypeError('init.timestamp must be a number.');\n            }\n            const numberOfFrames = init.data.byteLength / (getBytesPerSample(init.format) * init.numberOfChannels);\n            if (!Number.isInteger(numberOfFrames)) {\n                throw new TypeError('Invalid AudioDataInit: data size is not a multiple of frame size.');\n            }\n            this.format = init.format;\n            this.sampleRate = init.sampleRate;\n            this.numberOfFrames = numberOfFrames;\n            this.numberOfChannels = init.numberOfChannels;\n            this.timestamp = init.timestamp;\n            this.duration = numberOfFrames / init.sampleRate;\n            let dataBuffer;\n            if (init.data instanceof ArrayBuffer) {\n                dataBuffer = new Uint8Array(init.data);\n            }\n            else if (ArrayBuffer.isView(init.data)) {\n                dataBuffer = new Uint8Array(init.data.buffer, init.data.byteOffset, init.data.byteLength);\n            }\n            else {\n                throw new TypeError('Invalid AudioDataInit: data is not a BufferSource.');\n            }\n            const expectedSize = this.numberOfFrames * this.numberOfChannels * getBytesPerSample(this.format);\n            if (dataBuffer.byteLength < expectedSize) {\n                throw new TypeError('Invalid AudioDataInit: insufficient data size.');\n            }\n            this._data = dataBuffer;\n        }\n        finalizationRegistry?.register(this, { type: 'audio', data: this._data }, this);\n    }\n    /** Returns the number of bytes required to hold the audio sample's data as specified by the given options. */\n    allocationSize(options) {\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (!Number.isInteger(options.planeIndex) || options.planeIndex < 0) {\n            throw new TypeError('planeIndex must be a non-negative integer.');\n        }\n        if (options.format !== undefined && !AUDIO_SAMPLE_FORMATS.has(options.format)) {\n            throw new TypeError('Invalid format.');\n        }\n        if (options.frameOffset !== undefined && (!Number.isInteger(options.frameOffset) || options.frameOffset < 0)) {\n            throw new TypeError('frameOffset must be a non-negative integer.');\n        }\n        if (options.frameCount !== undefined && (!Number.isInteger(options.frameCount) || options.frameCount < 0)) {\n            throw new TypeError('frameCount must be a non-negative integer.');\n        }\n        if (this._closed) {\n            throw new Error('AudioSample is closed.');\n        }\n        const destFormat = options.format ?? this.format;\n        const frameOffset = options.frameOffset ?? 0;\n        if (frameOffset >= this.numberOfFrames) {\n            throw new RangeError('frameOffset out of range');\n        }\n        const copyFrameCount = options.frameCount !== undefined ? options.frameCount : (this.numberOfFrames - frameOffset);\n        if (copyFrameCount > (this.numberOfFrames - frameOffset)) {\n            throw new RangeError('frameCount out of range');\n        }\n        const bytesPerSample = getBytesPerSample(destFormat);\n        const isPlanar = formatIsPlanar(destFormat);\n        if (isPlanar && options.planeIndex >= this.numberOfChannels) {\n            throw new RangeError('planeIndex out of range');\n        }\n        if (!isPlanar && options.planeIndex !== 0) {\n            throw new RangeError('planeIndex out of range');\n        }\n        const elementCount = isPlanar ? copyFrameCount : copyFrameCount * this.numberOfChannels;\n        return elementCount * bytesPerSample;\n    }\n    /** Copies the audio sample's data to an ArrayBuffer or ArrayBufferView as specified by the given options. */\n    copyTo(destination, options) {\n        if (!isAllowSharedBufferSource(destination)) {\n            throw new TypeError('destination must be an ArrayBuffer or an ArrayBuffer view.');\n        }\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (!Number.isInteger(options.planeIndex) || options.planeIndex < 0) {\n            throw new TypeError('planeIndex must be a non-negative integer.');\n        }\n        if (options.format !== undefined && !AUDIO_SAMPLE_FORMATS.has(options.format)) {\n            throw new TypeError('Invalid format.');\n        }\n        if (options.frameOffset !== undefined && (!Number.isInteger(options.frameOffset) || options.frameOffset < 0)) {\n            throw new TypeError('frameOffset must be a non-negative integer.');\n        }\n        if (options.frameCount !== undefined && (!Number.isInteger(options.frameCount) || options.frameCount < 0)) {\n            throw new TypeError('frameCount must be a non-negative integer.');\n        }\n        if (this._closed) {\n            throw new Error('AudioSample is closed.');\n        }\n        const { format, frameCount: optFrameCount, frameOffset: optFrameOffset } = options;\n        let { planeIndex } = options;\n        let srcFormat = this.format;\n        const destFormat = format ?? this.format;\n        if (!destFormat)\n            throw new Error('Destination format not determined');\n        const numFrames = this.numberOfFrames;\n        const numChannels = this.numberOfChannels;\n        const frameOffset = optFrameOffset ?? 0;\n        if (frameOffset >= numFrames) {\n            throw new RangeError('frameOffset out of range');\n        }\n        const copyFrameCount = optFrameCount !== undefined ? optFrameCount : (numFrames - frameOffset);\n        if (copyFrameCount > (numFrames - frameOffset)) {\n            throw new RangeError('frameCount out of range');\n        }\n        const destBytesPerSample = getBytesPerSample(destFormat);\n        const destIsPlanar = formatIsPlanar(destFormat);\n        if (destIsPlanar && planeIndex >= numChannels) {\n            throw new RangeError('planeIndex out of range');\n        }\n        if (!destIsPlanar && planeIndex !== 0) {\n            throw new RangeError('planeIndex out of range');\n        }\n        const destElementCount = destIsPlanar ? copyFrameCount : copyFrameCount * numChannels;\n        const requiredSize = destElementCount * destBytesPerSample;\n        if (destination.byteLength < requiredSize) {\n            throw new RangeError('Destination buffer is too small');\n        }\n        const destView = toDataView(destination);\n        const writeFn = getWriteFunction(destFormat);\n        if (isAudioData(this._data)) {\n            if (isWebKit() && numChannels > 2 && destFormat !== srcFormat) {\n                // WebKit bug workaround\n                doAudioDataCopyToWebKitWorkaround(this._data, destView, srcFormat, destFormat, numChannels, planeIndex, frameOffset, copyFrameCount);\n                return;\n            }\n            else {\n                try {\n                    // The spec only requires f32-planar to work here, but most of the time, all formats work. Sometimes\n                    // they don't, and that's why we try-catch it.\n                    this._data.copyTo(destination, {\n                        planeIndex,\n                        frameOffset,\n                        frameCount: copyFrameCount,\n                        format: destFormat,\n                    });\n                    return;\n                }\n                catch (error) {\n                    if (destFormat === 'f32-planar') {\n                        throw error;\n                    }\n                    // Format conversion likely wasn't supported, so let's fall back to the manual conversion path\n                    srcFormat = 'f32-planar';\n                }\n            }\n        }\n        const readFn = getReadFunction(srcFormat);\n        const srcBytesPerSample = getBytesPerSample(srcFormat);\n        const srcIsPlanar = formatIsPlanar(srcFormat);\n        let uint8Data;\n        if (this._data instanceof AudioSampleResource) {\n            const getDataPlaneValidated = (index) => {\n                const result = this._data.getDataPlane(index);\n                if (!(result instanceof Uint8Array)) {\n                    throw new TypeError('getDataPlane() must return a Uint8Array.');\n                }\n                const expectedSize = numFrames * srcBytesPerSample * (srcIsPlanar ? 1 : numChannels);\n                if (result.byteLength !== expectedSize) {\n                    throw new TypeError(`Data plane ${index} has invalid size. Expected exactly ${expectedSize} bytes, got`\n                        + ` ${result.byteLength} bytes.`);\n                }\n                return result;\n            };\n            if (srcIsPlanar) {\n                if (destIsPlanar) {\n                    // Only one source plane will be extracted, so let's fetch only that one\n                    uint8Data = getDataPlaneValidated(planeIndex);\n                    planeIndex = 0; // To fix the subsequent access\n                }\n                else {\n                    // Pack all planes tightly together\n                    uint8Data = new Uint8Array(numFrames * srcBytesPerSample * numChannels);\n                    for (let ch = 0; ch < numChannels; ch++) {\n                        const planeData = getDataPlaneValidated(ch);\n                        uint8Data.set(planeData, ch * numFrames * srcBytesPerSample);\n                    }\n                }\n            }\n            else {\n                uint8Data = getDataPlaneValidated(0); // That's the only plane there is\n            }\n        }\n        else if (this._data instanceof Uint8Array) {\n            uint8Data = this._data;\n        }\n        else {\n            assert(srcFormat === 'f32-planar');\n            if (destIsPlanar) {\n                // Only one source plane will be read, so let's copy only that one\n                uint8Data = new Uint8Array(this._data.allocationSize({\n                    format: 'f32-planar',\n                    planeIndex,\n                }));\n                this._data.copyTo(uint8Data, {\n                    format: 'f32-planar',\n                    planeIndex,\n                });\n                planeIndex = 0; // To fix the subsequent access\n            }\n            else {\n                // All planes will be read, so fetch 'em all\n                uint8Data = new Uint8Array(this._data.allocationSize({\n                    format: 'f32-planar',\n                    planeIndex: 0,\n                }) * numChannels);\n                for (let ch = 0; ch < numChannels; ch++) {\n                    this._data.copyTo(uint8Data.subarray(ch * numFrames * srcBytesPerSample, (ch + 1) * numFrames * srcBytesPerSample), {\n                        format: 'f32-planar',\n                        planeIndex: ch,\n                    });\n                }\n            }\n        }\n        const srcView = toDataView(uint8Data);\n        for (let i = 0; i < copyFrameCount; i++) {\n            if (destIsPlanar) {\n                const destOffset = i * destBytesPerSample;\n                let srcOffset;\n                if (srcIsPlanar) {\n                    srcOffset = (planeIndex * numFrames + (i + frameOffset)) * srcBytesPerSample;\n                }\n                else {\n                    srcOffset = (((i + frameOffset) * numChannels) + planeIndex) * srcBytesPerSample;\n                }\n                const normalized = readFn(srcView, srcOffset);\n                writeFn(destView, destOffset, normalized);\n            }\n            else {\n                for (let ch = 0; ch < numChannels; ch++) {\n                    const destIndex = i * numChannels + ch;\n                    const destOffset = destIndex * destBytesPerSample;\n                    let srcOffset;\n                    if (srcIsPlanar) {\n                        srcOffset = (ch * numFrames + (i + frameOffset)) * srcBytesPerSample;\n                    }\n                    else {\n                        srcOffset = (((i + frameOffset) * numChannels) + ch) * srcBytesPerSample;\n                    }\n                    const normalized = readFn(srcView, srcOffset);\n                    writeFn(destView, destOffset, normalized);\n                }\n            }\n        }\n    }\n    /** Clones this audio sample. */\n    clone() {\n        if (this._closed) {\n            throw new Error('AudioSample is closed.');\n        }\n        if (this._data instanceof AudioSampleResource) {\n            const sample = new AudioSample(this._data);\n            sample.setTimestamp(this.timestamp); // Make sure the timestamp is correct\n            return sample;\n        }\n        else if (isAudioData(this._data)) {\n            const sample = new AudioSample(this._data.clone());\n            sample.setTimestamp(this.timestamp);\n            return sample;\n        }\n        else {\n            return new AudioSample({\n                format: this.format,\n                sampleRate: this.sampleRate,\n                numberOfFrames: this.numberOfFrames,\n                numberOfChannels: this.numberOfChannels,\n                timestamp: this.timestamp,\n                data: this._data,\n            });\n        }\n    }\n    /**\n     * Returns a new {@link AudioSample} containing only the frames in the range [startFrame, endFrame). Both bounds\n     * must lie within this sample's range of frames. The returned sample's timestamp is shifted to match the start of\n     * the trimmed section.\n     */\n    trim(startFrame, endFrame = this.numberOfFrames) {\n        if (!Number.isInteger(startFrame) || startFrame < 0) {\n            throw new TypeError('startFrame must be a non-negative integer.');\n        }\n        if (!Number.isInteger(endFrame) || endFrame < 0) {\n            throw new TypeError('endFrame must be a non-negative integer.');\n        }\n        if (startFrame > this.numberOfFrames) {\n            throw new RangeError('startFrame out of range.');\n        }\n        if (endFrame > this.numberOfFrames) {\n            throw new RangeError('endFrame out of range.');\n        }\n        if (endFrame < startFrame) {\n            throw new RangeError('endFrame must not be less than startFrame.');\n        }\n        if (this._closed) {\n            throw new Error('AudioSample is closed.');\n        }\n        const frameCount = endFrame - startFrame;\n        const bytesPerSample = getBytesPerSample(this.format);\n        let data;\n        if (formatIsPlanar(this.format)) {\n            const planeSize = frameCount * bytesPerSample;\n            data = new Uint8Array(planeSize * this.numberOfChannels);\n            if (frameCount > 0) {\n                // Copy plane-by-plane\n                for (let i = 0; i < this.numberOfChannels; i++) {\n                    this.copyTo(data.subarray(i * planeSize, (i + 1) * planeSize), {\n                        planeIndex: i,\n                        format: this.format,\n                        frameOffset: startFrame,\n                        frameCount,\n                    });\n                }\n            }\n        }\n        else {\n            // Trivial\n            data = new Uint8Array(frameCount * this.numberOfChannels * bytesPerSample);\n            if (frameCount > 0) {\n                this.copyTo(data, {\n                    planeIndex: 0,\n                    format: this.format,\n                    frameOffset: startFrame,\n                    frameCount,\n                });\n            }\n        }\n        return new AudioSample({\n            data,\n            format: this.format,\n            sampleRate: this.sampleRate,\n            numberOfChannels: this.numberOfChannels,\n            timestamp: this.timestamp + startFrame / this.sampleRate,\n        });\n    }\n    /**\n     * Closes this audio sample, releasing held resources. Audio samples should be closed as soon as they are not\n     * needed anymore.\n     */\n    close() {\n        if (this._closed) {\n            return;\n        }\n        finalizationRegistry?.unregister(this);\n        if (this._data instanceof AudioSampleResource) {\n            this._data._referenceCount--;\n            if (this._data._referenceCount === 0) {\n                this._data.close();\n            }\n        }\n        else if (isAudioData(this._data)) {\n            this._data.close();\n        }\n        else {\n            this._data = new Uint8Array(0);\n        }\n        this._closed = true;\n    }\n    /**\n     * Converts this audio sample to an AudioData for use with the WebCodecs API. The AudioData returned by this\n     * method *must* be closed separately from this audio sample.\n     */\n    toAudioData() {\n        if (this._closed) {\n            throw new Error('AudioSample is closed.');\n        }\n        if (this._data instanceof AudioSampleResource) {\n            return this._createAudioDataFromData();\n        }\n        else if (isAudioData(this._data)) {\n            if (this._data.timestamp === this.microsecondTimestamp) {\n                // Timestamp matches, let's just return the data (but cloned)\n                return this._data.clone();\n            }\n            else {\n                // It's impossible to simply change an AudioData's timestamp, so we'll need to create a new one\n                return this._createAudioDataFromData();\n            }\n        }\n        else {\n            return new AudioData({\n                format: this.format,\n                sampleRate: this.sampleRate,\n                numberOfFrames: this.numberOfFrames,\n                numberOfChannels: this.numberOfChannels,\n                timestamp: this.microsecondTimestamp,\n                data: this._data.buffer instanceof ArrayBuffer\n                    ? this._data.buffer\n                    : this._data.slice(), // In the case of SharedArrayBuffer, convert to ArrayBuffer\n            });\n        }\n    }\n    /** @internal */\n    _createAudioDataFromData() {\n        if (formatIsPlanar(this.format)) {\n            const size = this.allocationSize({ planeIndex: 0, format: this.format });\n            const data = new ArrayBuffer(size * this.numberOfChannels);\n            // We gotta read out each plane individually\n            for (let i = 0; i < this.numberOfChannels; i++) {\n                this.copyTo(new Uint8Array(data, i * size, size), { planeIndex: i, format: this.format });\n            }\n            return new AudioData({\n                format: this.format,\n                sampleRate: this.sampleRate,\n                numberOfFrames: this.numberOfFrames,\n                numberOfChannels: this.numberOfChannels,\n                timestamp: this.microsecondTimestamp,\n                data,\n            });\n        }\n        else {\n            const data = new ArrayBuffer(this.allocationSize({ planeIndex: 0, format: this.format }));\n            this.copyTo(data, { planeIndex: 0, format: this.format });\n            return new AudioData({\n                format: this.format,\n                sampleRate: this.sampleRate,\n                numberOfFrames: this.numberOfFrames,\n                numberOfChannels: this.numberOfChannels,\n                timestamp: this.microsecondTimestamp,\n                data,\n            });\n        }\n    }\n    /** Convert this audio sample to an AudioBuffer for use with the Web Audio API. */\n    toAudioBuffer() {\n        if (this._closed) {\n            throw new Error('AudioSample is closed.');\n        }\n        const audioBuffer = new AudioBuffer({\n            numberOfChannels: this.numberOfChannels,\n            length: this.numberOfFrames,\n            sampleRate: this.sampleRate,\n        });\n        const dataBytes = new Float32Array(this.allocationSize({ planeIndex: 0, format: 'f32-planar' }) / 4);\n        for (let i = 0; i < this.numberOfChannels; i++) {\n            this.copyTo(dataBytes, { planeIndex: i, format: 'f32-planar' });\n            audioBuffer.copyToChannel(dataBytes, i);\n        }\n        return audioBuffer;\n    }\n    /** Sets the presentation timestamp of this audio sample, in seconds. */\n    setTimestamp(newTimestamp) {\n        if (!Number.isFinite(newTimestamp)) {\n            throw new TypeError('newTimestamp must be a number.');\n        }\n        // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n        this.timestamp = newTimestamp;\n    }\n    /** Calls `.close()`. */\n    [Symbol.dispose]() {\n        this.close();\n    }\n    /** @internal */\n    static *_fromAudioBuffer(audioBuffer, timestamp) {\n        if (!(audioBuffer instanceof AudioBuffer)) {\n            throw new TypeError('audioBuffer must be an AudioBuffer.');\n        }\n        const MAX_FLOAT_COUNT = 48000 * 5; // 5 seconds of mono 48 kHz audio per sample\n        const numberOfChannels = audioBuffer.numberOfChannels;\n        const sampleRate = audioBuffer.sampleRate;\n        const totalFrames = audioBuffer.length;\n        const maxFramesPerChunk = Math.floor(MAX_FLOAT_COUNT / numberOfChannels);\n        let currentRelativeFrame = 0;\n        let remainingFrames = totalFrames;\n        // Create AudioSamples in a chunked fashion so we don't create huge Float32Arrays\n        while (remainingFrames > 0) {\n            const framesToCopy = Math.min(maxFramesPerChunk, remainingFrames);\n            const chunkData = new Float32Array(numberOfChannels * framesToCopy);\n            for (let channel = 0; channel < numberOfChannels; channel++) {\n                audioBuffer.copyFromChannel(chunkData.subarray(channel * framesToCopy, (channel + 1) * framesToCopy), channel, currentRelativeFrame);\n            }\n            yield new AudioSample({\n                format: 'f32-planar',\n                sampleRate,\n                numberOfFrames: framesToCopy,\n                numberOfChannels,\n                timestamp: timestamp + currentRelativeFrame / sampleRate,\n                data: chunkData,\n            });\n            currentRelativeFrame += framesToCopy;\n            remainingFrames -= framesToCopy;\n        }\n    }\n    /**\n     * Creates AudioSamples from an AudioBuffer, starting at the given timestamp in seconds. Typically creates exactly\n     * one sample, but may create multiple if the AudioBuffer is exceedingly large.\n     */\n    static fromAudioBuffer(audioBuffer, timestamp) {\n        if (!(audioBuffer instanceof AudioBuffer)) {\n            throw new TypeError('audioBuffer must be an AudioBuffer.');\n        }\n        const MAX_FLOAT_COUNT = 48000 * 5; // 5 seconds of mono 48 kHz audio per sample\n        const numberOfChannels = audioBuffer.numberOfChannels;\n        const sampleRate = audioBuffer.sampleRate;\n        const totalFrames = audioBuffer.length;\n        const maxFramesPerChunk = Math.floor(MAX_FLOAT_COUNT / numberOfChannels);\n        let currentRelativeFrame = 0;\n        let remainingFrames = totalFrames;\n        const result = [];\n        // Create AudioSamples in a chunked fashion so we don't create huge Float32Arrays\n        while (remainingFrames > 0) {\n            const framesToCopy = Math.min(maxFramesPerChunk, remainingFrames);\n            const chunkData = new Float32Array(numberOfChannels * framesToCopy);\n            for (let channel = 0; channel < numberOfChannels; channel++) {\n                audioBuffer.copyFromChannel(chunkData.subarray(channel * framesToCopy, (channel + 1) * framesToCopy), channel, currentRelativeFrame);\n            }\n            const audioSample = new AudioSample({\n                format: 'f32-planar',\n                sampleRate,\n                numberOfFrames: framesToCopy,\n                numberOfChannels,\n                timestamp: timestamp + currentRelativeFrame / sampleRate,\n                data: chunkData,\n            });\n            result.push(audioSample);\n            currentRelativeFrame += framesToCopy;\n            remainingFrames -= framesToCopy;\n        }\n        return result;\n    }\n}\nexport const getBytesPerSample = (format) => {\n    switch (format) {\n        case 'u8':\n        case 'u8-planar':\n            return 1;\n        case 's16':\n        case 's16-planar':\n            return 2;\n        case 's32':\n        case 's32-planar':\n            return 4;\n        case 'f32':\n        case 'f32-planar':\n            return 4;\n        default:\n            throw new Error('Unknown AudioSampleFormat');\n    }\n};\nconst formatIsPlanar = (format) => {\n    switch (format) {\n        case 'u8-planar':\n        case 's16-planar':\n        case 's32-planar':\n        case 'f32-planar':\n            return true;\n        default:\n            return false;\n    }\n};\nconst getReadFunction = (format) => {\n    switch (format) {\n        case 'u8':\n        case 'u8-planar':\n            return (view, offset) => (view.getUint8(offset) - 128) / 128;\n        case 's16':\n        case 's16-planar':\n            return (view, offset) => view.getInt16(offset, true) / 32768;\n        case 's32':\n        case 's32-planar':\n            return (view, offset) => view.getInt32(offset, true) / 2147483648;\n        case 'f32':\n        case 'f32-planar':\n            return (view, offset) => view.getFloat32(offset, true);\n    }\n};\nconst getWriteFunction = (format) => {\n    switch (format) {\n        case 'u8':\n        case 'u8-planar':\n            return (view, offset, value) => view.setUint8(offset, clamp(Math.round(value * 128) + 128, 0, 255));\n        case 's16':\n        case 's16-planar':\n            return (view, offset, value) => view.setInt16(offset, clamp(Math.round(value * 32768), -32768, 32767), true);\n        case 's32':\n        case 's32-planar':\n            return (view, offset, value) => view.setInt32(offset, clamp(Math.round(value * 2147483648), -2147483648, 2147483647), true);\n        case 'f32':\n        case 'f32-planar':\n            return (view, offset, value) => view.setFloat32(offset, value, true);\n    }\n};\nconst isAudioData = (x) => {\n    return typeof AudioData !== 'undefined' && x instanceof AudioData;\n};\nexport const toInterleavedAudioFormat = (format) => {\n    switch (format) {\n        case 'u8-planar':\n            return 'u8';\n        case 's16-planar':\n            return 's16';\n        case 's32-planar':\n            return 's32';\n        case 'f32-planar':\n            return 'f32';\n        default:\n            return format;\n    }\n};\n/**\n * WebKit has a bug where calling AudioData.copyTo with a format different from the source format crashes the tab when\n * there are more than 2 channels. This function works around that by always copying with the source format and then\n * manually converting to the destination format.\n *\n * See https://bugs.webkit.org/show_bug.cgi?id=302521.\n */\nconst doAudioDataCopyToWebKitWorkaround = (audioData, destView, srcFormat, destFormat, numChannels, planeIndex, frameOffset, copyFrameCount) => {\n    const readFn = getReadFunction(srcFormat);\n    const writeFn = getWriteFunction(destFormat);\n    const srcBytesPerSample = getBytesPerSample(srcFormat);\n    const destBytesPerSample = getBytesPerSample(destFormat);\n    const srcIsPlanar = formatIsPlanar(srcFormat);\n    const destIsPlanar = formatIsPlanar(destFormat);\n    if (destIsPlanar) {\n        if (srcIsPlanar) {\n            // src planar -> dest planar: copy single plane and convert\n            const data = new ArrayBuffer(copyFrameCount * srcBytesPerSample);\n            const dataView = toDataView(data);\n            audioData.copyTo(data, {\n                planeIndex,\n                frameOffset,\n                frameCount: copyFrameCount,\n                format: srcFormat,\n            });\n            for (let i = 0; i < copyFrameCount; i++) {\n                const srcOffset = i * srcBytesPerSample;\n                const destOffset = i * destBytesPerSample;\n                const sample = readFn(dataView, srcOffset);\n                writeFn(destView, destOffset, sample);\n            }\n        }\n        else {\n            // src interleaved -> dest planar: copy all interleaved data, extract one channel\n            const data = new ArrayBuffer(copyFrameCount * numChannels * srcBytesPerSample);\n            const dataView = toDataView(data);\n            audioData.copyTo(data, {\n                planeIndex: 0,\n                frameOffset,\n                frameCount: copyFrameCount,\n                format: srcFormat,\n            });\n            for (let i = 0; i < copyFrameCount; i++) {\n                const srcOffset = (i * numChannels + planeIndex) * srcBytesPerSample;\n                const destOffset = i * destBytesPerSample;\n                const sample = readFn(dataView, srcOffset);\n                writeFn(destView, destOffset, sample);\n            }\n        }\n    }\n    else {\n        if (srcIsPlanar) {\n            // src planar -> dest interleaved: copy each plane and interleave\n            const planeSize = copyFrameCount * srcBytesPerSample;\n            const data = new ArrayBuffer(planeSize);\n            const dataView = toDataView(data);\n            for (let ch = 0; ch < numChannels; ch++) {\n                audioData.copyTo(data, {\n                    planeIndex: ch,\n                    frameOffset,\n                    frameCount: copyFrameCount,\n                    format: srcFormat,\n                });\n                for (let i = 0; i < copyFrameCount; i++) {\n                    const srcOffset = i * srcBytesPerSample;\n                    const destOffset = (i * numChannels + ch) * destBytesPerSample;\n                    const sample = readFn(dataView, srcOffset);\n                    writeFn(destView, destOffset, sample);\n                }\n            }\n        }\n        else {\n            // src interleaved -> dest interleaved: copy all and convert\n            const data = new ArrayBuffer(copyFrameCount * numChannels * srcBytesPerSample);\n            const dataView = toDataView(data);\n            audioData.copyTo(data, {\n                planeIndex: 0,\n                frameOffset,\n                frameCount: copyFrameCount,\n                format: srcFormat,\n            });\n            for (let i = 0; i < copyFrameCount; i++) {\n                for (let ch = 0; ch < numChannels; ch++) {\n                    const idx = i * numChannels + ch;\n                    const srcOffset = idx * srcBytesPerSample;\n                    const destOffset = idx * destBytesPerSample;\n                    const sample = readFn(dataView, srcOffset);\n                    writeFn(destView, destOffset, sample);\n                }\n            }\n        }\n    }\n};\nexport const audioSampleToInterleavedFormat = (sample, format) => {\n    const size = sample.allocationSize({ format, planeIndex: 0 });\n    const buffer = new ArrayBuffer(size);\n    sample.copyTo(buffer, { format, planeIndex: 0 });\n    return new AudioSample({\n        data: buffer,\n        format,\n        numberOfChannels: sample.numberOfChannels,\n        sampleRate: sample.sampleRate,\n        timestamp: sample.timestamp,\n        duration: sample.duration,\n    });\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { AUDIO_CODECS, buildAudioCodecString, buildVideoCodecString, getAudioEncoderConfigExtension, getVideoEncoderConfigExtension, inferCodecFromCodecString, PCM_AUDIO_CODECS, SUBTITLE_CODECS, VIDEO_CODECS, } from './codec.js';\nimport { customAudioEncoders, customVideoEncoders } from './custom-coder.js';\nimport { assert, clamp, getChromiumVersion, isFirefox, lerp } from './misc.js';\nimport { validateCropRectangle } from './sample.js';\nexport const canEncodeVideoMemo = new Map();\nexport const canEncodeAudioMemo = new Map();\nexport const validateVideoEncodingConfig = (config) => {\n    if (!config || typeof config !== 'object') {\n        throw new TypeError('Encoding config must be an object.');\n    }\n    if (!VIDEO_CODECS.includes(config.codec)) {\n        throw new TypeError(`Invalid video codec '${config.codec}'. Must be one of: ${VIDEO_CODECS.join(', ')}.`);\n    }\n    // eslint-disable-next-line @typescript-eslint/no-deprecated\n    const bitrate = config.bitrate;\n    if (config.quality === undefined && bitrate === undefined) {\n        throw new TypeError('config.quality must be provided.');\n    }\n    if (config.quality !== undefined && bitrate !== undefined) {\n        throw new TypeError('config.quality and config.bitrate cannot both be provided.');\n    }\n    if (config.quality !== undefined && !(config.quality instanceof Quality)) {\n        throw new TypeError('config.quality, when provided, must be a Quality.');\n    }\n    if (bitrate !== undefined && !(bitrate instanceof Quality) && (!Number.isInteger(bitrate) || bitrate <= 0)) {\n        throw new TypeError('config.bitrate, when provided, must be a positive integer or a quality.');\n    }\n    if (config.keyFrameInterval !== undefined\n        && (!Number.isFinite(config.keyFrameInterval) || config.keyFrameInterval < 0)) {\n        throw new TypeError('config.keyFrameInterval, when provided, must be a non-negative number.');\n    }\n    if (config.sizeChangeBehavior !== undefined\n        && !['deny', 'passThrough', 'fill', 'contain', 'cover'].includes(config.sizeChangeBehavior)) {\n        throw new TypeError('config.sizeChangeBehavior, when provided, must be \\'deny\\', \\'passThrough\\', \\'fill\\', \\'contain\\''\n            + ' or \\'cover\\'.');\n    }\n    if (config.transform !== undefined) {\n        if (typeof config.transform !== 'object' || !config.transform) {\n            throw new TypeError('config.transform, when provided, must be an object.');\n        }\n        if (config.transform.width !== undefined\n            && (!Number.isInteger(config.transform.width) || config.transform.width <= 0)) {\n            throw new TypeError('config.transform.width, when provided, must be a positive integer.');\n        }\n        if (config.transform.height !== undefined\n            && (!Number.isInteger(config.transform.height) || config.transform.height <= 0)) {\n            throw new TypeError('config.transform.height, when provided, must be a positive integer.');\n        }\n        if (config.transform.fit !== undefined && !['fill', 'contain', 'cover'].includes(config.transform.fit)) {\n            throw new TypeError('config.transform.fit, when provided, must be one of \"fill\", \"contain\", or \"cover\".');\n        }\n        if (config.transform.width !== undefined\n            && config.transform.height !== undefined\n            && config.transform.fit === undefined\n            && !['fill', 'contain', 'cover'].includes(config.sizeChangeBehavior)) {\n            throw new TypeError('When both config.transform.width and config.transform.height are provided, config.transform.fit'\n                + ' must also be provided.');\n        }\n        if (config.transform.fit !== undefined\n            && ['fill', 'contain', 'cover'].includes(config.sizeChangeBehavior)\n            && config.transform.fit !== config.sizeChangeBehavior) {\n            throw new TypeError('config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when'\n                + ' config.sizeChangeBehavior is \\'fill\\', \\'contain\\' or \\'cover\\', as sizeChangeBehavior already'\n                + ' determines the fitting algorithm.');\n        }\n        if (config.transform.rotate !== undefined && ![0, 90, 180, 270].includes(config.transform.rotate)) {\n            throw new TypeError('config.transform.rotate, when provided, must be 0, 90, 180 or 270.');\n        }\n        if (config.transform.flip !== undefined && typeof config.transform.flip !== 'boolean') {\n            throw new TypeError('config.transform.flip, when provided, must be a boolean.');\n        }\n        if (config.transform.crop !== undefined) {\n            validateCropRectangle(config.transform.crop, 'config.transform.');\n        }\n        if (config.transform.process !== undefined && typeof config.transform.process !== 'function') {\n            throw new TypeError('config.transform.process, when provided, must be a function.');\n        }\n        if (config.transform.frameRate !== undefined\n            && (!Number.isFinite(config.transform.frameRate) || config.transform.frameRate <= 0)) {\n            throw new TypeError('config.transform.frameRate, when provided, must be a finite positive number.');\n        }\n        if (config.transform.force !== undefined && typeof config.transform.force !== 'boolean') {\n            throw new TypeError('config.transform.force, when provided, must be a boolean.');\n        }\n    }\n    if (config.onEncodedPacket !== undefined && typeof config.onEncodedPacket !== 'function') {\n        throw new TypeError('config.onEncodedPacket, when provided, must be a function.');\n    }\n    if (config.onEncoderConfig !== undefined && typeof config.onEncoderConfig !== 'function') {\n        throw new TypeError('config.onEncoderConfig, when provided, must be a function.');\n    }\n    if (config.onEncodedSample !== undefined && typeof config.onEncodedSample !== 'function') {\n        throw new TypeError('config.onEncodedSample, when provided, must be a function.');\n    }\n    validateVideoEncodingAdditionalOptions(config.codec, config);\n};\nexport const validateVideoEncodingAdditionalOptions = (codec, options) => {\n    if (!options || typeof options !== 'object') {\n        throw new TypeError('Encoding options must be an object.');\n    }\n    if (options.alpha !== undefined && !['discard', 'keep'].includes(options.alpha)) {\n        throw new TypeError('options.alpha, when provided, must be \\'discard\\' or \\'keep\\'.');\n    }\n    // eslint-disable-next-line @typescript-eslint/no-deprecated\n    const bitrateMode = options.bitrateMode;\n    if (bitrateMode !== undefined && !['constant', 'variable'].includes(bitrateMode)) {\n        throw new TypeError('bitrateMode, when provided, must be \\'constant\\' or \\'variable\\'.');\n    }\n    if (options.latencyMode !== undefined && !['quality', 'realtime'].includes(options.latencyMode)) {\n        throw new TypeError('latencyMode, when provided, must be \\'quality\\' or \\'realtime\\'.');\n    }\n    if (options.fullCodecString !== undefined && typeof options.fullCodecString !== 'string') {\n        throw new TypeError('fullCodecString, when provided, must be a string.');\n    }\n    if (options.fullCodecString !== undefined && inferCodecFromCodecString(options.fullCodecString) !== codec) {\n        throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${codec}).`);\n    }\n    if (options.hardwareAcceleration !== undefined\n        && !['no-preference', 'prefer-hardware', 'prefer-software'].includes(options.hardwareAcceleration)) {\n        throw new TypeError('hardwareAcceleration, when provided, must be \\'no-preference\\', \\'prefer-hardware\\' or'\n            + ' \\'prefer-software\\'.');\n    }\n    if (options.scalabilityMode !== undefined && typeof options.scalabilityMode !== 'string') {\n        throw new TypeError('scalabilityMode, when provided, must be a string.');\n    }\n    if (options.contentHint !== undefined && typeof options.contentHint !== 'string') {\n        throw new TypeError('contentHint, when provided, must be a string.');\n    }\n};\n/**\n * Builds the encoder configs to attempt, in order of preference. Multiple configs are returned when a Quality can be\n * satisfied by multiple rate control methods (quantizer-based encoding with a bitrate-based fallback).\n */\nexport const buildVideoEncoderConfigs = (options) => {\n    // eslint-disable-next-line @typescript-eslint/no-deprecated\n    const fallbackBitrateMode = options.bitrateMode;\n    const rateControl = options.quality._toVideoRateControl(options.codec, options.width, options.height, fallbackBitrateMode);\n    const buildConfig = (bitrate, bitrateMode, bitrateEstimate) => ({\n        codec: options.fullCodecString ?? buildVideoCodecString(options.codec, options.width, options.height, bitrateEstimate, options.alpha === 'keep'),\n        width: options.width,\n        height: options.height,\n        displayWidth: options.squarePixelWidth,\n        displayHeight: options.squarePixelHeight,\n        bitrate,\n        bitrateMode,\n        alpha: options.alpha ?? 'discard',\n        framerate: options.framerate,\n        latencyMode: options.latencyMode,\n        hardwareAcceleration: options.hardwareAcceleration,\n        scalabilityMode: options.scalabilityMode,\n        contentHint: options.contentHint,\n        ...getVideoEncoderConfigExtension(options.codec),\n    });\n    const candidates = [];\n    if (rateControl.quantizer !== null) {\n        candidates.push({\n            config: buildConfig(undefined, 'quantizer', rateControl.bitrate),\n            quantizer: rateControl.quantizer,\n        });\n    }\n    if (rateControl.bitrateMode !== 'quantizer') {\n        candidates.push({\n            config: buildConfig(rateControl.bitrate, rateControl.bitrateMode, rateControl.bitrate),\n            quantizer: null,\n        });\n    }\n    assert(candidates.length > 0);\n    return candidates;\n};\nexport const validateAudioEncodingConfig = (config) => {\n    if (!config || typeof config !== 'object') {\n        throw new TypeError('Encoding config must be an object.');\n    }\n    if (!AUDIO_CODECS.includes(config.codec)) {\n        throw new TypeError(`Invalid audio codec '${config.codec}'. Must be one of: ${AUDIO_CODECS.join(', ')}.`);\n    }\n    // eslint-disable-next-line @typescript-eslint/no-deprecated\n    const bitrate = config.bitrate;\n    if (config.quality === undefined\n        && bitrate === undefined\n        && !(PCM_AUDIO_CODECS.includes(config.codec) || config.codec === 'flac')) {\n        throw new TypeError('config.quality must be provided for compressed audio codecs.');\n    }\n    if (config.quality !== undefined && bitrate !== undefined) {\n        throw new TypeError('config.quality and config.bitrate cannot both be provided.');\n    }\n    if (config.quality !== undefined && !(config.quality instanceof Quality)) {\n        throw new TypeError('config.quality, when provided, must be a Quality.');\n    }\n    if (bitrate !== undefined && !(bitrate instanceof Quality) && (!Number.isInteger(bitrate) || bitrate <= 0)) {\n        throw new TypeError('config.bitrate, when provided, must be a positive integer or a quality.');\n    }\n    if (config.transform !== undefined) {\n        if (typeof config.transform !== 'object' || !config.transform) {\n            throw new TypeError('config.transform, when provided, must be an object.');\n        }\n        if (config.transform.numberOfChannels !== undefined\n            && (!Number.isInteger(config.transform.numberOfChannels) || config.transform.numberOfChannels <= 0)) {\n            throw new TypeError('config.transform.numberOfChannels, when provided, must be a positive integer.');\n        }\n        if (config.transform.sampleRate !== undefined\n            && (!Number.isInteger(config.transform.sampleRate) || config.transform.sampleRate <= 0)) {\n            throw new TypeError('config.transform.sampleRate, when provided, must be a positive integer.');\n        }\n        if (config.transform.sampleFormat !== undefined\n            && !['u8', 's16', 's32', 'f32'].includes(config.transform.sampleFormat)) {\n            throw new TypeError('config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.');\n        }\n        if (config.transform.process !== undefined && typeof config.transform.process !== 'function') {\n            throw new TypeError('config.transform.process, when provided, must be a function.');\n        }\n    }\n    if (config.onEncodedPacket !== undefined && typeof config.onEncodedPacket !== 'function') {\n        throw new TypeError('config.onEncodedPacket, when provided, must be a function.');\n    }\n    if (config.onEncoderConfig !== undefined && typeof config.onEncoderConfig !== 'function') {\n        throw new TypeError('config.onEncoderConfig, when provided, must be a function.');\n    }\n    if (config.onEncodedSample !== undefined && typeof config.onEncodedSample !== 'function') {\n        throw new TypeError('config.onEncodedSample, when provided, must be a function.');\n    }\n    validateAudioEncodingAdditionalOptions(config.codec, config);\n};\nexport const validateAudioEncodingAdditionalOptions = (codec, options) => {\n    if (!options || typeof options !== 'object') {\n        throw new TypeError('Encoding options must be an object.');\n    }\n    // eslint-disable-next-line @typescript-eslint/no-deprecated\n    const bitrateMode = options.bitrateMode;\n    if (bitrateMode !== undefined && !['constant', 'variable'].includes(bitrateMode)) {\n        throw new TypeError('bitrateMode, when provided, must be \\'constant\\' or \\'variable\\'.');\n    }\n    if (options.fullCodecString !== undefined && typeof options.fullCodecString !== 'string') {\n        throw new TypeError('fullCodecString, when provided, must be a string.');\n    }\n    if (options.fullCodecString !== undefined && inferCodecFromCodecString(options.fullCodecString) !== codec) {\n        throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${codec}).`);\n    }\n};\nexport const buildAudioEncoderConfig = (options) => {\n    // eslint-disable-next-line @typescript-eslint/no-deprecated\n    const fallbackBitrateMode = options.bitrateMode;\n    return {\n        codec: options.fullCodecString ?? buildAudioCodecString(options.codec, options.numberOfChannels, options.sampleRate),\n        numberOfChannels: options.numberOfChannels,\n        sampleRate: options.sampleRate,\n        bitrate: options.quality?._toAudioBitrate(options.codec),\n        bitrateMode: options.quality?._bitrateMode ?? fallbackBitrateMode,\n        ...getAudioEncoderConfigExtension(options.codec),\n    };\n};\n/**\n * Represents a desired encoding quality. Can express a qualitative quality level, an explicit bitrate, an explicit\n * quantizer value, or a combination thereof.\n * @group Encoding\n * @public\n */\nexport class Quality {\n    constructor(options) {\n        if (typeof options === 'number' || typeof options === 'string') {\n            // Shorthand for directly specifying a qualitative quality level\n            options = { quality: options };\n        }\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.bitrateMode !== undefined && !['constant', 'variable'].includes(options.bitrateMode)) {\n            throw new TypeError('options.bitrateMode, when provided, must be \\'constant\\' or \\'variable\\'.');\n        }\n        if ('quality' in options) {\n            if (typeof options.quality === 'string'\n                ? !(options.quality in QUALITY_LEVELS)\n                : (typeof options.quality !== 'number' || Number.isNaN(options.quality))) {\n                throw new TypeError('options.quality must be a number, or one of \\'very-low\\', \\'low\\', \\'medium\\', \\'high\\''\n                    + ' or \\'very-high\\'.');\n            }\n            if (options.preferBitrate !== undefined && typeof options.preferBitrate !== 'boolean') {\n                throw new TypeError('options.preferBitrate, when provided, must be a boolean.');\n            }\n            if ('bitrate' in options || 'quantizer' in options) {\n                throw new TypeError('options.quality cannot be combined with options.bitrate or options.quantizer.');\n            }\n            this._quality = typeof options.quality === 'string'\n                ? QUALITY_LEVELS[options.quality]\n                : options.quality;\n            this._preferBitrate = options.preferBitrate ?? false;\n            this._bitrate = undefined;\n            this._quantizer = undefined;\n        }\n        else {\n            if (options.bitrate !== undefined && (!Number.isInteger(options.bitrate) || options.bitrate <= 0)) {\n                throw new TypeError('options.bitrate, when provided, must be a positive integer.');\n            }\n            if (options.quantizer !== undefined && (!Number.isInteger(options.quantizer) || options.quantizer < 0)) {\n                throw new TypeError('options.quantizer, when provided, must be a non-negative integer.');\n            }\n            if (options.bitrate === undefined && options.quantizer === undefined) {\n                throw new TypeError('At least one of options.bitrate or options.quantizer must be set.');\n            }\n            if ('preferBitrate' in options) {\n                throw new TypeError('options.preferBitrate can only be combined with options.quality.');\n            }\n            this._quality = undefined;\n            this._preferBitrate = false;\n            this._bitrate = options.bitrate;\n            this._quantizer = options.quantizer;\n        }\n        this._bitrateMode = options.bitrateMode;\n    }\n    /**\n     * Determines the rate control methods usable for the given codec.\n     * @internal\n     */\n    _toVideoRateControl(codec, width, height, fallbackBitrateMode) {\n        const quantizerSupport = VIDEO_CODEC_QUANTIZER_SUPPORT[codec];\n        let quantizer = null;\n        let bitrateMode = this._bitrateMode ?? fallbackBitrateMode ?? 'variable';\n        if (this._quantizer !== undefined) {\n            // An explicit quantizer demands quantizer-based encoding, with an explicit bitrate (if any) being the\n            // only permitted fallback\n            if (!quantizerSupport) {\n                if (this._bitrate === undefined) {\n                    throw new Error(`Codec '${codec}' does not support quantizer-based encoding. Provide a bitrate in the Quality`\n                        + ` to define a fallback.`);\n                }\n            }\n            else if (this._quantizer < quantizerSupport.min || this._quantizer > quantizerSupport.max) {\n                if (this._bitrate === undefined) {\n                    throw new Error(`Quantizer ${this._quantizer} is out of range for codec '${codec}'; must be between`\n                        + ` ${quantizerSupport.min} and ${quantizerSupport.max}.`);\n                }\n            }\n            else {\n                quantizer = this._quantizer;\n                if (this._bitrate === undefined) {\n                    bitrateMode = 'quantizer';\n                }\n            }\n        }\n        else if (this._bitrate === undefined && quantizerSupport && !this._preferBitrate) {\n            // A qualitative quality level is set; offer quantizer-based encoding since the codec supports it. Since\n            // the quality may lie outside the 0-1 range, we clamp the result to the codec's legal quantizer range.\n            assert(this._quality !== undefined);\n            quantizer = clamp(Math.round(lerp(quantizerSupport.worst, quantizerSupport.best, this._quality)), quantizerSupport.min, quantizerSupport.max);\n        }\n        let bitrate;\n        if (this._bitrate !== undefined) {\n            bitrate = this._bitrate;\n        }\n        else {\n            let quality = this._quality;\n            if (quality === undefined) {\n                // Map the quantizer back onto the quality scale to derive a fitting bitrate estimate\n                assert(quantizer !== null && quantizerSupport);\n                quality = clamp((quantizer - quantizerSupport.worst) / (quantizerSupport.best - quantizerSupport.worst), 0, 1);\n            }\n            bitrate = computeVideoBitrate(codec, width, height, qualityToBitrateFactor(quality));\n        }\n        return { quantizer, bitrate, bitrateMode };\n    }\n    /** @internal */\n    _toVideoBitrate(codec, width, height) {\n        if (this._bitrate !== undefined) {\n            return this._bitrate;\n        }\n        assert(this._quality !== undefined);\n        return computeVideoBitrate(codec, width, height, qualityToBitrateFactor(this._quality));\n    }\n    /** @internal */\n    _toAudioBitrate(codec) {\n        if (PCM_AUDIO_CODECS.includes(codec) || codec === 'flac') {\n            return undefined;\n        }\n        if (this._bitrate !== undefined) {\n            return this._bitrate;\n        }\n        if (this._quality === undefined) {\n            throw new Error('This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio'\n                + ' encoding.');\n        }\n        const factor = qualityToBitrateFactor(this._quality);\n        const baseRates = {\n            aac: 128000, // 128kbps base for AAC\n            opus: 64000, // 64kbps base for Opus\n            mp3: 160000, // 160kbps base for MP3\n            vorbis: 64000, // 64kbps base for Vorbis\n            ac3: 384000, // 384kbps base for AC-3\n            eac3: 192000, // 192kbps base for E-AC-3\n            dts: 768000, // 768kbps base for DTS\n        };\n        const baseBitrate = baseRates[codec];\n        if (!baseBitrate) {\n            throw new Error(`Unhandled codec: ${codec}`);\n        }\n        let finalBitrate = baseBitrate * factor;\n        if (codec === 'aac') {\n            // AAC only works with specific bitrates, let's find the closest\n            const validRates = [96000, 128000, 160000, 192000];\n            finalBitrate = validRates.reduce((prev, curr) => Math.abs(curr - finalBitrate) < Math.abs(prev - finalBitrate) ? curr : prev);\n        }\n        else if (codec === 'opus' || codec === 'vorbis') {\n            finalBitrate = Math.max(6000, finalBitrate);\n        }\n        else if (codec === 'mp3') {\n            const validRates = [\n                8000, 16000, 24000, 32000, 40000, 48000, 64000, 80000,\n                96000, 112000, 128000, 160000, 192000, 224000, 256000, 320000,\n            ];\n            finalBitrate = validRates.reduce((prev, curr) => Math.abs(curr - finalBitrate) < Math.abs(prev - finalBitrate) ? curr : prev);\n        }\n        return Math.round(finalBitrate / 1000) * 1000;\n    }\n}\nconst QUALITY_LEVELS = {\n    'very-low': 0,\n    'low': 0.25,\n    'medium': 0.5,\n    'high': 0.75,\n    'very-high': 1,\n};\n// best and worse define the reasonable range\nconst VIDEO_CODEC_QUANTIZER_SUPPORT = {\n    avc: { min: 0, max: 51, worst: 41, best: 16 },\n    hevc: { min: 0, max: 51, worst: 41, best: 16 },\n    // Chromium used the 0-63 scale before v145, see https://github.com/Vanilagy/mediabunny/issues/566\n    vp9: (getChromiumVersion() ?? Infinity) < 145\n        ? { min: 0, max: 63, worst: 52, best: 20 }\n        : { min: 0, max: 255, worst: 208, best: 80 },\n    av1: { min: 0, max: 255, worst: 208, best: 80 },\n};\n/**\n * Maps the qualitative 0-1 quality scale to a bitrate multiplier. The curve is a least-squares exponential fit through\n * the multipliers historically used by the predefined quality levels (0.3, 0.6, 1, 2, 4).\n */\nconst qualityToBitrateFactor = (quality) => 0.3 * Math.exp(2.5538 * quality);\nconst computeVideoBitrate = (codec, width, height, factor) => {\n    const pixels = width * height;\n    const referencePixels = 1920 * 1080;\n    const referenceBitrate = 3_000_000;\n    const scaleFactor = Math.pow(pixels / referencePixels, 0.95); // Slight non-linear scaling\n    const baseBitrate = referenceBitrate * scaleFactor;\n    const codecEfficiencyFactors = {\n        avc: 1.0, // H.264/AVC (baseline)\n        hevc: 0.6, // H.265/HEVC (~40% more efficient than AVC)\n        vp9: 0.6, // Similar to HEVC\n        av1: 0.4, // ~60% more efficient than AVC\n        vp8: 1.2, // Slightly less efficient than AVC\n        prores: 220_000_000 / referenceBitrate, // Apple ProRes white paper claims 220 Mbps for 1080p 422 HQ @30Hz\n    };\n    const codecAdjustedBitrate = baseBitrate * codecEfficiencyFactors[codec];\n    const finalBitrate = codecAdjustedBitrate * factor;\n    return Math.ceil(finalBitrate / 1000) * 1000;\n};\n/** Builds the per-frame encode options that carry the quantizer value for the given codec. */\nexport const buildQuantizerEncodeOptions = (codec, quantizer) => {\n    if (codec === 'avc') {\n        return { avc: { quantizer } };\n    }\n    else if (codec === 'hevc') {\n        return { hevc: { quantizer } };\n    }\n    else if (codec === 'vp9') {\n        return { vp9: { quantizer } };\n    }\n    else if (codec === 'av1') {\n        return { av1: { quantizer } };\n    }\n    assert(false);\n};\n/**\n * Represents a very low media quality.\n * @deprecated Use `new Quality('very-low')` instead.\n * @group Encoding\n * @public\n */\nexport const QUALITY_VERY_LOW = /* #__PURE__ */ new Quality('very-low');\n/**\n * Represents a low media quality.\n * @deprecated Use `new Quality('low')` instead.\n * @group Encoding\n * @public\n */\nexport const QUALITY_LOW = /* #__PURE__ */ new Quality('low');\n/**\n * Represents a medium media quality.\n * @deprecated Use `new Quality('medium')` instead.\n * @group Encoding\n * @public\n */\nexport const QUALITY_MEDIUM = /* #__PURE__ */ new Quality('medium');\n/**\n * Represents a high media quality.\n * @deprecated Use `new Quality('high')` instead.\n * @group Encoding\n * @public\n */\nexport const QUALITY_HIGH = /* #__PURE__ */ new Quality('high');\n/**\n * Represents a very high media quality.\n * @deprecated Use `new Quality('very-high')` instead.\n * @group Encoding\n * @public\n */\nexport const QUALITY_VERY_HIGH = /* #__PURE__ */ new Quality('very-high');\n/**\n * Checks if the browser is able to encode the given codec.\n * @group Encoding\n * @public\n */\nexport const canEncode = (codec) => {\n    if (VIDEO_CODECS.includes(codec)) {\n        return canEncodeVideo(codec);\n    }\n    else if (AUDIO_CODECS.includes(codec)) {\n        return canEncodeAudio(codec);\n    }\n    else if (SUBTITLE_CODECS.includes(codec)) {\n        return canEncodeSubtitles(codec);\n    }\n    throw new TypeError(`Unknown codec '${codec}'.`);\n};\n/**\n * Checks if the browser is able to encode the given video codec with the given parameters.\n * @group Encoding\n * @public\n */\nexport const canEncodeVideo = async (codec, options = {}) => {\n    const { width = 1280, height = 720, quality, \n    // eslint-disable-next-line @typescript-eslint/no-deprecated\n    bitrate, frameRate, ...restOptions } = options;\n    if (!VIDEO_CODECS.includes(codec)) {\n        return false;\n    }\n    if (!Number.isInteger(width) || width <= 0) {\n        throw new TypeError('width must be a positive integer.');\n    }\n    if (!Number.isInteger(height) || height <= 0) {\n        throw new TypeError('height must be a positive integer.');\n    }\n    if (quality !== undefined && !(quality instanceof Quality)) {\n        throw new TypeError('quality, when provided, must be a Quality.');\n    }\n    if (quality !== undefined && bitrate !== undefined) {\n        throw new TypeError('quality and bitrate cannot both be provided.');\n    }\n    if (bitrate !== undefined && !(bitrate instanceof Quality) && (!Number.isInteger(bitrate) || bitrate <= 0)) {\n        throw new TypeError('bitrate must be a positive integer or a quality.');\n    }\n    if (frameRate !== undefined && (!Number.isFinite(frameRate) || frameRate <= 0)) {\n        throw new TypeError('frameRate, when provided, must be a finite positive number.');\n    }\n    validateVideoEncodingAdditionalOptions(codec, restOptions);\n    const resolvedQuality = resolveQuality(quality, bitrate) ?? new Quality('medium');\n    let candidates;\n    try {\n        candidates = buildVideoEncoderConfigs({\n            codec,\n            width,\n            height,\n            quality: resolvedQuality,\n            framerate: frameRate,\n            ...restOptions,\n            alpha: 'discard', // Since we handle alpha ourselves\n        });\n    }\n    catch {\n        // The requested rate control cannot be used with this codec (e.g. a quantizer with no fallback bitrate on a\n        // codec without quantizer support)\n        return false;\n    }\n    const key = JSON.stringify(candidates);\n    const memoized = canEncodeVideoMemo.get(key);\n    if (memoized) {\n        return memoized;\n    }\n    const promise = (async () => {\n        for (const { config } of candidates) {\n            if (customVideoEncoders.some(x => x.supports(codec, config))) {\n                // There's a custom encoder\n                return true;\n            }\n        }\n        if (typeof VideoEncoder === 'undefined') {\n            return false;\n        }\n        const hasOddDimension = width % 2 === 1 || height % 2 === 1;\n        if (hasOddDimension\n            && (codec === 'avc' || codec === 'hevc')) {\n            // Disallow odd dimensions for certain codecs\n            return false;\n        }\n        for (const { config, quantizer } of candidates) {\n            try {\n                const support = await VideoEncoder.isConfigSupported(config);\n                if (!support.supported) {\n                    continue;\n                }\n            }\n            catch {\n                // Can type-error when unknown config features are used\n                continue;\n            }\n            if (!isFirefox()) {\n                return true;\n            }\n            // isConfigSupported on Firefox appears to unreliably indicate if encoding will actually succeed. Therefore,\n            // we just try encoding a frame to see if it actually works.\n            // https://github.com/Vanilagy/mediabunny/issues/222\n            // eslint-disable-next-line @typescript-eslint/no-misused-promises, no-async-promise-executor\n            const success = await new Promise(async (resolve) => {\n                try {\n                    const encoder = new VideoEncoder({\n                        output: () => { },\n                        error: () => resolve(false),\n                    });\n                    encoder.configure(config);\n                    const frameData = new Uint8Array(width * height * 4);\n                    const frame = new VideoFrame(frameData, {\n                        format: 'RGBA',\n                        codedWidth: width,\n                        codedHeight: height,\n                        timestamp: 0,\n                    });\n                    encoder.encode(frame, quantizer !== null ? buildQuantizerEncodeOptions(codec, quantizer) : undefined);\n                    frame.close();\n                    await encoder.flush();\n                    resolve(true);\n                }\n                catch {\n                    resolve(false);\n                }\n            });\n            if (success) {\n                return true;\n            }\n        }\n        return false;\n    })();\n    canEncodeVideoMemo.set(key, promise);\n    return promise;\n};\n/**\n * Checks if the browser is able to encode the given audio codec with the given parameters.\n * @group Encoding\n * @public\n */\nexport const canEncodeAudio = async (codec, options = {}) => {\n    const { numberOfChannels = 2, sampleRate = 48000, quality, \n    // eslint-disable-next-line @typescript-eslint/no-deprecated\n    bitrate, ...restOptions } = options;\n    if (!AUDIO_CODECS.includes(codec)) {\n        return false;\n    }\n    if (!Number.isInteger(numberOfChannels) || numberOfChannels <= 0) {\n        throw new TypeError('numberOfChannels must be a positive integer.');\n    }\n    if (!Number.isInteger(sampleRate) || sampleRate <= 0) {\n        throw new TypeError('sampleRate must be a positive integer.');\n    }\n    if (quality !== undefined && !(quality instanceof Quality)) {\n        throw new TypeError('quality, when provided, must be a Quality.');\n    }\n    if (quality !== undefined && bitrate !== undefined) {\n        throw new TypeError('quality and bitrate cannot both be provided.');\n    }\n    if (bitrate !== undefined && !(bitrate instanceof Quality) && (!Number.isInteger(bitrate) || bitrate <= 0)) {\n        throw new TypeError('bitrate must be a positive integer.');\n    }\n    validateAudioEncodingAdditionalOptions(codec, restOptions);\n    const resolvedQuality = resolveQuality(quality, bitrate) ?? new Quality('medium');\n    const encoderConfig = buildAudioEncoderConfig({\n        codec,\n        numberOfChannels,\n        sampleRate,\n        quality: resolvedQuality,\n        ...restOptions,\n    });\n    const key = JSON.stringify(encoderConfig);\n    const memoized = canEncodeAudioMemo.get(key);\n    if (memoized) {\n        return memoized;\n    }\n    const promise = (async () => {\n        if (customAudioEncoders.some(x => x.supports(codec, encoderConfig))) {\n            // There's a custom encoder\n            return true;\n        }\n        if (PCM_AUDIO_CODECS.includes(codec)) {\n            return true; // Because we encode these ourselves\n        }\n        if (typeof AudioEncoder === 'undefined') {\n            return false;\n        }\n        try {\n            const support = await AudioEncoder.isConfigSupported(encoderConfig);\n            return support.supported === true;\n        }\n        catch {\n            // Can type-error when unknown config features are used\n            return false;\n        }\n    })();\n    canEncodeAudioMemo.set(key, promise);\n    return promise;\n};\n/**\n * Resolves the `quality` and deprecated `bitrate` fields from the public API into a {@link Quality}, the norm used\n * internally.\n */\nexport const resolveQuality = (quality, bitrate) => {\n    if (quality !== undefined) {\n        return quality;\n    }\n    if (bitrate === undefined) {\n        return undefined;\n    }\n    return bitrate instanceof Quality ? bitrate : new Quality({ bitrate });\n};\n/**\n * Checks if the browser is able to encode the given subtitle codec.\n * @group Encoding\n * @public\n */\nexport const canEncodeSubtitles = async (codec) => {\n    if (!SUBTITLE_CODECS.includes(codec)) {\n        return false;\n    }\n    return true;\n};\n/**\n * Returns the list of all media codecs that can be encoded by the browser.\n * @group Encoding\n * @public\n */\nexport const getEncodableCodecs = async () => {\n    const [videoCodecs, audioCodecs, subtitleCodecs] = await Promise.all([\n        getEncodableVideoCodecs(),\n        getEncodableAudioCodecs(),\n        getEncodableSubtitleCodecs(),\n    ]);\n    return [...videoCodecs, ...audioCodecs, ...subtitleCodecs];\n};\n/**\n * Returns the list of all video codecs that can be encoded by the browser.\n * @group Encoding\n * @public\n */\nexport const getEncodableVideoCodecs = async (checkedCodecs = VIDEO_CODECS, options) => {\n    const bools = await Promise.all(checkedCodecs.map(codec => canEncodeVideo(codec, options)));\n    return checkedCodecs.filter((_, i) => bools[i]);\n};\n/**\n * Returns the list of all audio codecs that can be encoded by the browser.\n * @group Encoding\n * @public\n */\nexport const getEncodableAudioCodecs = async (checkedCodecs = AUDIO_CODECS, options) => {\n    const bools = await Promise.all(checkedCodecs.map(codec => canEncodeAudio(codec, options)));\n    return checkedCodecs.filter((_, i) => bools[i]);\n};\n/**\n * Returns the list of all subtitle codecs that can be encoded by the browser.\n * @group Encoding\n * @public\n */\nexport const getEncodableSubtitleCodecs = async (checkedCodecs = SUBTITLE_CODECS) => {\n    const bools = await Promise.all(checkedCodecs.map(canEncodeSubtitles));\n    return checkedCodecs.filter((_, i) => bools[i]);\n};\n/**\n * Returns the first video codec from the given list that can be encoded by the browser.\n * @group Encoding\n * @public\n */\nexport const getFirstEncodableVideoCodec = async (checkedCodecs, options) => {\n    for (const codec of checkedCodecs) {\n        if (await canEncodeVideo(codec, options)) {\n            return codec;\n        }\n    }\n    return null;\n};\n/**\n * Returns the first audio codec from the given list that can be encoded by the browser.\n * @group Encoding\n * @public\n */\nexport const getFirstEncodableAudioCodec = async (checkedCodecs, options) => {\n    for (const codec of checkedCodecs) {\n        if (await canEncodeAudio(codec, options)) {\n            return codec;\n        }\n    }\n    return null;\n};\n/**\n * Returns the first subtitle codec from the given list that can be encoded by the browser.\n * @group Encoding\n * @public\n */\nexport const getFirstEncodableSubtitleCodec = async (checkedCodecs) => {\n    for (const codec of checkedCodecs) {\n        if (await canEncodeSubtitles(codec)) {\n            return codec;\n        }\n    }\n    return null;\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { canDecodeAudioMemo, canDecodeVideoMemo } from './decode.js';\nimport { canEncodeAudioMemo, canEncodeVideoMemo } from './encode.js';\nimport { Logging } from './logging.js';\n/**\n * Base class for custom video decoders. To add your own custom video decoder, extend this class, implement the\n * abstract methods and static `supports` method, and register the decoder using {@link registerDecoder}.\n * @group Custom coders\n * @public\n */\nexport class CustomVideoDecoder {\n    /** Returns true if and only if the decoder can decode the given codec configuration. */\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    static supports(codec, config) {\n        return false;\n    }\n}\n/**\n * Base class for custom audio decoders. To add your own custom audio decoder, extend this class, implement the\n * abstract methods and static `supports` method, and register the decoder using {@link registerDecoder}.\n * @group Custom coders\n * @public\n */\nexport class CustomAudioDecoder {\n    /** Returns true if and only if the decoder can decode the given codec configuration. */\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    static supports(codec, config) {\n        return false;\n    }\n}\n/**\n * Base class for custom video encoders. To add your own custom video encoder, extend this class, implement the\n * abstract methods and static `supports` method, and register the encoder using {@link registerEncoder}.\n * @group Custom coders\n * @public\n */\nexport class CustomVideoEncoder {\n    /** Returns true if and only if the encoder can encode the given codec configuration. */\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    static supports(codec, config) {\n        return false;\n    }\n}\n/**\n * Base class for custom audio encoders. To add your own custom audio encoder, extend this class, implement the\n * abstract methods and static `supports` method, and register the encoder using {@link registerEncoder}.\n * @group Custom coders\n * @public\n */\nexport class CustomAudioEncoder {\n    /** Returns true if and only if the encoder can encode the given codec configuration. */\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    static supports(codec, config) {\n        return false;\n    }\n}\nexport const customVideoDecoders = [];\nexport const customAudioDecoders = [];\nexport const customVideoEncoders = [];\nexport const customAudioEncoders = [];\n/**\n * Registers a custom video or audio decoder. Registered decoders will automatically be used for decoding whenever\n * possible.\n * @group Custom coders\n * @public\n */\nexport const registerDecoder = (decoder) => {\n    if (decoder.prototype instanceof CustomVideoDecoder) {\n        const casted = decoder;\n        if (customVideoDecoders.includes(casted)) {\n            Logging._warn('Video decoder already registered.');\n            return;\n        }\n        customVideoDecoders.push(casted);\n        canDecodeVideoMemo.clear();\n    }\n    else if (decoder.prototype instanceof CustomAudioDecoder) {\n        const casted = decoder;\n        if (customAudioDecoders.includes(casted)) {\n            Logging._warn('Audio decoder already registered.');\n            return;\n        }\n        customAudioDecoders.push(casted);\n        canDecodeAudioMemo.clear();\n    }\n    else {\n        throw new TypeError('Decoder must be a CustomVideoDecoder or CustomAudioDecoder.');\n    }\n};\n/**\n * Registers a custom video or audio encoder. Registered encoders will automatically be used for encoding whenever\n * possible.\n * @group Custom coders\n * @public\n */\nexport const registerEncoder = (encoder) => {\n    if (encoder.prototype instanceof CustomVideoEncoder) {\n        const casted = encoder;\n        if (customVideoEncoders.includes(casted)) {\n            Logging._warn('Video encoder already registered.');\n            return;\n        }\n        customVideoEncoders.push(casted);\n        canEncodeVideoMemo.clear();\n    }\n    else if (encoder.prototype instanceof CustomAudioEncoder) {\n        const casted = encoder;\n        if (customAudioEncoders.includes(casted)) {\n            Logging._warn('Audio encoder already registered.');\n            return;\n        }\n        customAudioEncoders.push(casted);\n        canEncodeAudioMemo.clear();\n    }\n    else {\n        throw new TypeError('Encoder must be a CustomVideoEncoder or CustomAudioEncoder.');\n    }\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\n// Original source:\n// https://github.com/dystopiancode/pcm-g711/blob/master/pcm-g711/g711.c\nexport const toUlaw = (s16) => {\n    const MULAW_MAX = 0x1FFF;\n    const MULAW_BIAS = 33;\n    let number = s16 >> 2;\n    let mask = 0x1000;\n    let sign = 0;\n    let position = 12;\n    let lsb = 0;\n    if (number < 0) {\n        number = -number;\n        sign = 0x80;\n    }\n    number += MULAW_BIAS;\n    if (number > MULAW_MAX) {\n        number = MULAW_MAX;\n    }\n    while ((number & mask) !== mask && position >= 5) {\n        mask >>= 1;\n        position--;\n    }\n    lsb = (number >> (position - 4)) & 0x0f;\n    return ~(sign | ((position - 5) << 4) | lsb) & 0xFF;\n};\nexport const fromUlaw = (u8) => {\n    const MULAW_BIAS = 33;\n    let sign = 0;\n    let position = 0;\n    let number = ~u8;\n    if (number & 0x80) {\n        number &= ~(1 << 7);\n        sign = -1;\n    }\n    position = ((number & 0xF0) >> 4) + 5;\n    const decoded = ((1 << position) | ((number & 0x0F) << (position - 4))\n        | (1 << (position - 5))) - MULAW_BIAS;\n    return ((sign === 0) ? decoded : -decoded) << 2;\n};\nexport const toAlaw = (s16) => {\n    const ALAW_MAX = 0xFFF;\n    let mask = 0x800;\n    let sign = 0;\n    let position = 11;\n    let lsb = 0;\n    let number = s16 >> 3;\n    if (number < 0) {\n        number = -number - 1;\n    }\n    else {\n        sign = 0x80;\n    }\n    if (number > ALAW_MAX) {\n        number = ALAW_MAX;\n    }\n    while ((number & mask) !== mask && position >= 5) {\n        mask >>= 1;\n        position--;\n    }\n    lsb = (number >> ((position === 4) ? 1 : (position - 4))) & 0x0f;\n    return (sign | ((position - 4) << 4) | lsb) ^ 0x55;\n};\nexport const fromAlaw = (u8) => {\n    let sign = 0x00;\n    let position = 0;\n    let number = u8 ^ 0x55;\n    if (number & 0x80) {\n        number &= ~(1 << 7);\n        sign = -1;\n    }\n    position = ((number & 0xF0) >> 4) + 4;\n    let decoded = 0;\n    if (position !== 4) {\n        decoded = ((1 << position) | ((number & 0x0F) << (position - 4))\n            | (1 << (position - 5)));\n    }\n    else {\n        decoded = (number << 1) | 1;\n    }\n    return ((sign === 0) ? -decoded : decoded) << 3;\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { parsePcmCodec, PCM_AUDIO_CODECS } from './codec.js';\nimport { addAvcBitstreamRestriction, AvcNalUnitType, concatAvcNalUnits, deserializeAvcDecoderConfigurationRecord, determineVideoPacketType, extractNalUnitTypeForAvc, extractNalUnitTypeForHevc, HevcNalUnitType, iterateAvcNalUnits, iterateHevcNalUnits, parseAvcSps, sanitizeHevcPacketForChromium, serializeAvcDecoderConfigurationRecord, } from './codec-data.js';\nimport { customVideoDecoders, customAudioDecoders } from './custom-coder.js';\nimport { InputDisposedError } from './input.js';\nimport { InputAudioTrack, InputTrack, InputVideoTrack } from './input-track.js';\nimport { assert, assertNever, CallSerializer, clamp, colorSpaceIsComplete, getInt24, getUint24, insertSorted, isChromium, isFirefox, isNumber, isWebKit, last, mapAsyncGenerator, missingWebCodecsClassMessage, promiseWithResolvers, removeItem, toAsyncIterator, toDataView, toUint8Array, validateAnyIterable, } from './misc.js';\nimport { EncodedPacket } from './packet.js';\nimport { fromAlaw, fromUlaw } from './pcm.js';\nimport { AudioSample, clampCropRectangle, validateCropRectangle, VideoSample, } from './sample.js';\nconst validatePacketRetrievalOptions = (options) => {\n    if (!options || typeof options !== 'object') {\n        throw new TypeError('options must be an object.');\n    }\n    if (options.metadataOnly !== undefined && typeof options.metadataOnly !== 'boolean') {\n        throw new TypeError('options.metadataOnly, when defined, must be a boolean.');\n    }\n    if (options.verifyKeyPackets !== undefined && typeof options.verifyKeyPackets !== 'boolean') {\n        throw new TypeError('options.verifyKeyPackets, when defined, must be a boolean.');\n    }\n    if (options.verifyKeyPackets && options.metadataOnly) {\n        throw new TypeError('options.verifyKeyPackets and options.metadataOnly cannot be enabled together.');\n    }\n    if (options.skipLiveWait !== undefined && typeof options.skipLiveWait !== 'boolean') {\n        throw new TypeError('options.skipLiveWait, when defined, must be a boolean.');\n    }\n};\nconst validateTimestamp = (timestamp) => {\n    if (!isNumber(timestamp)) {\n        throw new TypeError('timestamp must be a number.'); // It can be non-finite, that's fine\n    }\n};\nconst maybeFixPacketType = (track, promise, options) => {\n    if (options.verifyKeyPackets) {\n        return promise.then(async (packet) => {\n            if (!packet || packet.type === 'delta') {\n                return packet;\n            }\n            const determinedType = await track.determinePacketType(packet);\n            if (determinedType) {\n                // @ts-expect-error Technically readonly\n                packet.type = determinedType;\n            }\n            return packet;\n        });\n    }\n    else {\n        return promise;\n    }\n};\n/**\n * Sink for retrieving encoded packets from an input track.\n * @group Media sinks\n * @public\n */\nexport class EncodedPacketSink {\n    /** Creates a new {@link EncodedPacketSink} for the given {@link InputTrack}. */\n    constructor(track) {\n        if (!(track instanceof InputTrack)) {\n            throw new TypeError('track must be an InputTrack.');\n        }\n        this._track = track;\n    }\n    /**\n     * Retrieves the track's first packet (in decode order), or null if it has no packets. The first packet is very\n     * likely to be a key packet, but it doesn't have to be.\n     */\n    async getFirstPacket(options = {}) {\n        validatePacketRetrievalOptions(options);\n        if (this._track.input._disposed) {\n            throw new InputDisposedError();\n        }\n        return maybeFixPacketType(this._track, this._track._backing.getFirstPacket(options), options);\n    }\n    /** Retrieves the track's first key packet (in decode order), or null if it has no key packets. */\n    async getFirstKeyPacket(options = {}) {\n        validatePacketRetrievalOptions(options);\n        const firstPacket = await this.getFirstPacket(options);\n        if (!firstPacket) {\n            return null;\n        }\n        if (firstPacket.type === 'key') {\n            // Great\n            return firstPacket;\n        }\n        return this.getNextKeyPacket(firstPacket, options);\n    }\n    /**\n     * Retrieves the packet corresponding to the given timestamp, in seconds. More specifically, returns the last packet\n     * (in presentation order) with a start timestamp less than or equal to the given timestamp. This method can be\n     * used to retrieve a track's last packet using `getPacket(Infinity)`. The method returns null if the timestamp\n     * is before the first packet in the track.\n     *\n     * @param timestamp - The timestamp used for retrieval, in seconds.\n     */\n    async getPacket(timestamp, options = {}) {\n        validateTimestamp(timestamp);\n        validatePacketRetrievalOptions(options);\n        if (this._track.input._disposed) {\n            throw new InputDisposedError();\n        }\n        return maybeFixPacketType(this._track, this._track._backing.getPacket(timestamp, options), options);\n    }\n    /**\n     * Retrieves the packet following the given packet (in decode order), or null if the given packet is the\n     * last packet.\n     */\n    async getNextPacket(packet, options = {}) {\n        if (!(packet instanceof EncodedPacket)) {\n            throw new TypeError('packet must be an EncodedPacket.');\n        }\n        validatePacketRetrievalOptions(options);\n        if (this._track.input._disposed) {\n            throw new InputDisposedError();\n        }\n        return maybeFixPacketType(this._track, this._track._backing.getNextPacket(packet, options), options);\n    }\n    /**\n     * Retrieves the key packet corresponding to the given timestamp, in seconds. More specifically, returns the last\n     * key packet (in presentation order) with a start timestamp less than or equal to the given timestamp. A key packet\n     * is a packet that doesn't require previous packets to be decoded. This method can be used to retrieve a track's\n     * last key packet using `getKeyPacket(Infinity)`. The method returns null if the timestamp is before the first\n     * key packet in the track.\n     *\n     * To ensure that the returned packet is guaranteed to be a real key frame, enable `options.verifyKeyPackets`.\n     *\n     * @param timestamp - The timestamp used for retrieval, in seconds.\n     */\n    async getKeyPacket(timestamp, options = {}) {\n        validateTimestamp(timestamp);\n        validatePacketRetrievalOptions(options);\n        if (this._track.input._disposed) {\n            throw new InputDisposedError();\n        }\n        if (!options.verifyKeyPackets) {\n            return this._track._backing.getKeyPacket(timestamp, options);\n        }\n        let packet = await this._track._backing.getKeyPacket(timestamp, options);\n        while (packet) {\n            assert(packet.type === 'key');\n            const determinedType = await this._track.determinePacketType(packet);\n            if (determinedType !== 'delta') {\n                return packet;\n            }\n            // Try the previous key packet instead (in hopes that it's actually a key packet)\n            let step = 1 / await this._track.getTimeResolution();\n            let previousPacket;\n            while (true) {\n                previousPacket = await this._track._backing.getKeyPacket(packet.timestamp - step, options);\n                if (!previousPacket || previousPacket.timestamp < packet.timestamp) {\n                    break;\n                }\n                // Huge timestamps, the step wasn't enough to move us, try again\n                step *= 2;\n            }\n            packet = previousPacket;\n        }\n        return null;\n    }\n    /**\n     * Retrieves the key packet following the given packet (in decode order), or null if the given packet is the last\n     * key packet.\n     *\n     * To ensure that the returned packet is guaranteed to be a real key frame, enable `options.verifyKeyPackets`.\n     */\n    async getNextKeyPacket(packet, options = {}) {\n        if (!(packet instanceof EncodedPacket)) {\n            throw new TypeError('packet must be an EncodedPacket.');\n        }\n        validatePacketRetrievalOptions(options);\n        if (this._track.input._disposed) {\n            throw new InputDisposedError();\n        }\n        if (!options.verifyKeyPackets) {\n            return this._track._backing.getNextKeyPacket(packet, options);\n        }\n        let nextPacket = await this._track._backing.getNextKeyPacket(packet, options);\n        while (nextPacket) {\n            assert(nextPacket.type === 'key');\n            const determinedType = await this._track.determinePacketType(nextPacket);\n            if (determinedType !== 'delta') {\n                return nextPacket;\n            }\n            // Try the next key packet instead (in hopes that it's actually a key packet)\n            nextPacket = await this._track._backing.getNextKeyPacket(nextPacket, options);\n        }\n        return null;\n    }\n    /**\n     * Creates an async iterator that yields the packets in this track in decode order. To enable fast iteration, this\n     * method will intelligently preload packets based on the speed of the consumer.\n     *\n     * @param startPacket - (optional) The packet from which iteration should begin. This packet will also be yielded.\n     * @param endPacket - (optional) The packet at which iteration should end. This packet will _not_ be yielded.\n     */\n    packets(startPacket, endPacket, options = {}) {\n        if (startPacket !== undefined && !(startPacket instanceof EncodedPacket)) {\n            throw new TypeError('startPacket must be an EncodedPacket.');\n        }\n        if (startPacket !== undefined && startPacket.isMetadataOnly && !options?.metadataOnly) {\n            throw new TypeError('startPacket can only be metadata-only if options.metadataOnly is enabled.');\n        }\n        if (endPacket !== undefined && !(endPacket instanceof EncodedPacket)) {\n            throw new TypeError('endPacket must be an EncodedPacket.');\n        }\n        validatePacketRetrievalOptions(options);\n        if (this._track.input._disposed) {\n            throw new InputDisposedError();\n        }\n        const packetQueue = [];\n        let { promise: queueNotEmpty, resolve: onQueueNotEmpty } = promiseWithResolvers();\n        let { promise: queueDequeue, resolve: onQueueDequeue } = promiseWithResolvers();\n        let ended = false;\n        let terminated = false;\n        // This stores errors that are \"out of band\" in the sense that they didn't occur in the normal flow of this\n        // method but instead in a different context. This error should not go unnoticed and must be bubbled up to\n        // the consumer.\n        let outOfBandError = null;\n        let hasOutOfBandError = false;\n        const timestamps = [];\n        // The queue should always be big enough to hold 1 second worth of packets\n        const maxQueueSize = () => Math.max(2, timestamps.length);\n        // The following is the \"pump\" process that keeps pumping packets into the queue\n        (async () => {\n            let packet = startPacket ?? await this.getFirstPacket(options);\n            while (packet && !terminated && !this._track.input._disposed) {\n                if (endPacket && packet.sequenceNumber >= endPacket?.sequenceNumber) {\n                    break;\n                }\n                if (packetQueue.length > maxQueueSize()) {\n                    ({ promise: queueDequeue, resolve: onQueueDequeue } = promiseWithResolvers());\n                    await queueDequeue;\n                    continue;\n                }\n                packetQueue.push(packet);\n                onQueueNotEmpty();\n                ({ promise: queueNotEmpty, resolve: onQueueNotEmpty } = promiseWithResolvers());\n                packet = await this.getNextPacket(packet, options);\n            }\n            ended = true;\n            onQueueNotEmpty();\n        })().catch((error) => {\n            if (!hasOutOfBandError) {\n                outOfBandError = error;\n                hasOutOfBandError = true;\n                onQueueNotEmpty();\n            }\n        });\n        const track = this._track;\n        return {\n            async next() {\n                while (true) {\n                    if (track.input._disposed) {\n                        throw new InputDisposedError();\n                    }\n                    else if (terminated) {\n                        return { value: undefined, done: true };\n                    }\n                    else if (hasOutOfBandError) {\n                        throw outOfBandError;\n                    }\n                    else if (packetQueue.length > 0) {\n                        const value = packetQueue.shift();\n                        const now = performance.now();\n                        timestamps.push(now);\n                        while (timestamps.length > 0 && now - timestamps[0] >= 1000) {\n                            timestamps.shift();\n                        }\n                        onQueueDequeue();\n                        return { value, done: false };\n                    }\n                    else if (ended) {\n                        return { value: undefined, done: true };\n                    }\n                    else {\n                        await queueNotEmpty;\n                    }\n                }\n            },\n            async return() {\n                terminated = true;\n                onQueueDequeue();\n                onQueueNotEmpty();\n                return { value: undefined, done: true };\n            },\n            async throw(error) {\n                throw error;\n            },\n            [Symbol.asyncIterator]() {\n                return this;\n            },\n        };\n    }\n}\nconst MAX_QUEUE_SIZE = 4;\nclass DecoderWrapper {\n    constructor(onSample, onError) {\n        this.onSample = onSample;\n        this.onError = onError;\n        this.onDequeue = null;\n    }\n}\n/**\n * Base class for decoded media sample sinks.\n * @group Media sinks\n * @public\n */\nexport class BaseMediaSampleSink {\n    /** @internal */\n    mediaSamplesInRange(startTimestamp = -Infinity, endTimestamp = Infinity, options) {\n        validateTimestamp(startTimestamp);\n        validateTimestamp(endTimestamp);\n        const sampleQueue = [];\n        let firstSampleQueued = false;\n        let lastSample = null;\n        let { promise: queueNotEmpty, resolve: onQueueNotEmpty } = promiseWithResolvers();\n        let { promise: queueDequeue, resolve: onQueueDequeue } = promiseWithResolvers();\n        let decoderIsFlushed = false;\n        let ended = false;\n        let terminated = false;\n        let decoder = null;\n        // This stores errors that are \"out of band\" in the sense that they didn't occur in the normal flow of this\n        // method but instead in a different context. This error should not go unnoticed and must be bubbled up to\n        // the consumer.\n        let outOfBandError = null;\n        let hasOutOfBandError = false;\n        const packetRetrievalOptions = {\n            ...options,\n            verifyKeyPackets: true,\n            metadataOnly: false,\n        };\n        // The following is the \"pump\" process that keeps pumping packets into the decoder\n        (async () => {\n            decoder = await this._createDecoder((sample) => {\n                onQueueDequeue();\n                if (sample.timestamp >= endTimestamp) {\n                    ended = true;\n                }\n                if (ended) {\n                    sample.close();\n                    return;\n                }\n                if (lastSample) {\n                    if (sample.timestamp > startTimestamp) {\n                        // We don't know ahead of time what the first first is. This is because the first first is the\n                        // last first whose timestamp is less than or equal to the start timestamp. Therefore we need to\n                        // wait for the first first after the start timestamp, and then we'll know that the previous\n                        // first was the first first.\n                        sampleQueue.push(lastSample);\n                        firstSampleQueued = true;\n                    }\n                    else {\n                        lastSample.close();\n                    }\n                }\n                if (sample.timestamp >= startTimestamp) {\n                    sampleQueue.push(sample);\n                    firstSampleQueued = true;\n                }\n                lastSample = firstSampleQueued ? null : sample;\n                if (sampleQueue.length > 0) {\n                    onQueueNotEmpty();\n                    ({ promise: queueNotEmpty, resolve: onQueueNotEmpty } = promiseWithResolvers());\n                }\n            }, (error) => {\n                if (!hasOutOfBandError) {\n                    outOfBandError = error;\n                    hasOutOfBandError = true;\n                    onQueueNotEmpty();\n                }\n            });\n            decoder.onDequeue = () => onQueueDequeue();\n            const packetSink = this._createPacketSink();\n            const keyPacket = await packetSink.getKeyPacket(startTimestamp, packetRetrievalOptions)\n                ?? await packetSink.getFirstKeyPacket(packetRetrievalOptions);\n            let currentPacket = keyPacket;\n            // B-frames make it exceedingly difficult to properly define an upper bound for packet iteration if an end\n            // timestamp is set, so we just don't do it. The case that makes it especially tricky is when the frames\n            // following a key frame have a lower timestamp than the keyframe; something that quite frequently happens\n            // in HEVC streams. The price to pay for not upper-bounding the packet iterator is a slight increase in\n            // decoder work at the end of the range, but the added correctness and reliability makes this tradeoff worth\n            // it.\n            const endPacket = undefined;\n            const packets = packetSink.packets(keyPacket ?? undefined, endPacket, packetRetrievalOptions);\n            await packets.next(); // Skip the start packet as we already have it\n            while (currentPacket && !ended && !this._track.input._disposed) {\n                if (sampleQueue.length + decoder.getDecodeQueueSize() >= MAX_QUEUE_SIZE) {\n                    ({ promise: queueDequeue, resolve: onQueueDequeue } = promiseWithResolvers());\n                    await queueDequeue;\n                    continue;\n                }\n                decoder.decode(currentPacket);\n                const packetResult = await packets.next();\n                if (packetResult.done) {\n                    break;\n                }\n                currentPacket = packetResult.value;\n            }\n            await packets.return();\n            if (!terminated && !this._track.input._disposed) {\n                await decoder.flush();\n            }\n            if (!firstSampleQueued && lastSample) {\n                sampleQueue.push(lastSample);\n                lastSample = null;\n            }\n            decoderIsFlushed = true;\n            onQueueNotEmpty(); // To unstuck (unstick?) the generator\n        })().catch((error) => {\n            if (!hasOutOfBandError) {\n                outOfBandError = error;\n                hasOutOfBandError = true;\n                onQueueNotEmpty();\n            }\n        }).finally(() => {\n            decoder?.close();\n        });\n        const track = this._track;\n        const closeSamples = () => {\n            lastSample?.close();\n            for (const sample of sampleQueue) {\n                sample.close();\n            }\n        };\n        return {\n            async next() {\n                while (true) {\n                    if (track.input._disposed) {\n                        // Once next() throws, the consumer will never call return(), so terminate the\n                        // iteration here - otherwise, the pump keeps queueing decoded samples that\n                        // nothing can ever close.\n                        terminated = true;\n                        ended = true;\n                        closeSamples();\n                        throw new InputDisposedError();\n                    }\n                    else if (terminated) {\n                        return { value: undefined, done: true };\n                    }\n                    else if (hasOutOfBandError) {\n                        terminated = true;\n                        ended = true;\n                        closeSamples();\n                        throw outOfBandError;\n                    }\n                    else if (sampleQueue.length > 0) {\n                        const value = sampleQueue.shift();\n                        onQueueDequeue();\n                        return { value, done: false };\n                    }\n                    else if (!decoderIsFlushed) {\n                        await queueNotEmpty;\n                    }\n                    else {\n                        return { value: undefined, done: true };\n                    }\n                }\n            },\n            async return() {\n                terminated = true;\n                ended = true;\n                onQueueDequeue();\n                onQueueNotEmpty();\n                closeSamples();\n                return { value: undefined, done: true };\n            },\n            async throw(error) {\n                throw error;\n            },\n            [Symbol.asyncIterator]() {\n                return this;\n            },\n        };\n    }\n    /** @internal */\n    mediaSamplesAtTimestamps(timestamps, options) {\n        validateAnyIterable(timestamps);\n        const timestampIterator = toAsyncIterator(timestamps);\n        const timestampsOfInterest = [];\n        const sampleQueue = [];\n        let { promise: queueNotEmpty, resolve: onQueueNotEmpty } = promiseWithResolvers();\n        let { promise: queueDequeue, resolve: onQueueDequeue } = promiseWithResolvers();\n        let decoderIsFlushed = false;\n        let terminated = false;\n        let decoder = null;\n        // This stores errors that are \"out of band\" in the sense that they didn't occur in the normal flow of this\n        // method but instead in a different context. This error should not go unnoticed and must be bubbled up to\n        // the consumer.\n        let outOfBandError = null;\n        let hasOutOfBandError = false;\n        const pushToQueue = (sample) => {\n            sampleQueue.push(sample);\n            onQueueNotEmpty();\n            ({ promise: queueNotEmpty, resolve: onQueueNotEmpty } = promiseWithResolvers());\n        };\n        const retrievalOptions = {\n            ...options,\n            verifyKeyPackets: true,\n            metadataOnly: false,\n        };\n        // The following is the \"pump\" process that keeps pumping packets into the decoder\n        (async () => {\n            decoder = await this._createDecoder((sample) => {\n                onQueueDequeue();\n                if (terminated) {\n                    sample.close();\n                    return;\n                }\n                let sampleUses = 0;\n                while (timestampsOfInterest.length > 0\n                    && sample.timestamp - timestampsOfInterest[0] > -1e-10 // Give it a little epsilon\n                ) {\n                    sampleUses++;\n                    timestampsOfInterest.shift();\n                }\n                if (sampleUses > 0) {\n                    for (let i = 0; i < sampleUses; i++) {\n                        // Clone the sample if we need to emit it multiple times\n                        pushToQueue((i < sampleUses - 1 ? sample.clone() : sample));\n                    }\n                }\n                else {\n                    sample.close();\n                }\n            }, (error) => {\n                if (!hasOutOfBandError) {\n                    outOfBandError = error;\n                    hasOutOfBandError = true;\n                    onQueueNotEmpty();\n                }\n            });\n            decoder.onDequeue = () => onQueueDequeue();\n            const packetSink = this._createPacketSink();\n            let lastPacket = null;\n            let lastKeyPacket = null;\n            // The end sequence number (inclusive) in the next batch of packets that will be decoded. The batch starts\n            // at the last key frame and goes until this sequence number.\n            let maxSequenceNumber = -1;\n            const decodePackets = async () => {\n                assert(lastKeyPacket);\n                assert(decoder);\n                // Start at the current key packet\n                let currentPacket = lastKeyPacket;\n                decoder.decode(currentPacket);\n                while (currentPacket.sequenceNumber < maxSequenceNumber) {\n                    while (sampleQueue.length + decoder.getDecodeQueueSize() >= MAX_QUEUE_SIZE && !terminated) {\n                        ({ promise: queueDequeue, resolve: onQueueDequeue } = promiseWithResolvers());\n                        await queueDequeue;\n                    }\n                    if (terminated) {\n                        break;\n                    }\n                    const nextPacket = await packetSink.getNextPacket(currentPacket, retrievalOptions);\n                    if (!nextPacket) {\n                        throw new Error('Internal error: couldn\\'t get next packet when one was expected.');\n                    }\n                    decoder.decode(nextPacket);\n                    currentPacket = nextPacket;\n                }\n                maxSequenceNumber = -1;\n            };\n            const flushDecoder = async () => {\n                assert(decoder);\n                await decoder.flush();\n                // We don't expect this list to have any elements in it anymore, but in case it does, let's emit\n                // nulls for every remaining element, then clear it.\n                for (let i = 0; i < timestampsOfInterest.length; i++) {\n                    pushToQueue(null);\n                }\n                timestampsOfInterest.length = 0;\n            };\n            for await (const timestamp of timestampIterator) {\n                validateTimestamp(timestamp);\n                if (terminated || this._track.input._disposed) {\n                    break;\n                }\n                const targetPacket = await packetSink.getPacket(timestamp, retrievalOptions);\n                const keyPacket = targetPacket && await packetSink.getKeyPacket(timestamp, retrievalOptions);\n                if (!keyPacket) {\n                    if (maxSequenceNumber !== -1) {\n                        await decodePackets();\n                        await flushDecoder();\n                    }\n                    pushToQueue(null);\n                    lastPacket = null;\n                    continue;\n                }\n                // Check if the key packet has changed or if we're going back in time\n                if (lastPacket\n                    && (keyPacket.sequenceNumber !== lastKeyPacket.sequenceNumber\n                        || targetPacket.timestamp < lastPacket.timestamp)) {\n                    await decodePackets();\n                    await flushDecoder(); // Always flush here, improves decoder compatibility\n                }\n                timestampsOfInterest.push(targetPacket.timestamp);\n                maxSequenceNumber = Math.max(targetPacket.sequenceNumber, maxSequenceNumber);\n                lastPacket = targetPacket;\n                lastKeyPacket = keyPacket;\n            }\n            if (!terminated && !this._track.input._disposed) {\n                if (maxSequenceNumber !== -1) {\n                    // We still need to decode packets\n                    await decodePackets();\n                }\n                await flushDecoder();\n            }\n            decoderIsFlushed = true;\n            onQueueNotEmpty(); // To unstuck the generator\n        })().catch((error) => {\n            if (!hasOutOfBandError) {\n                outOfBandError = error;\n                hasOutOfBandError = true;\n                onQueueNotEmpty();\n            }\n        }).finally(() => {\n            decoder?.close();\n        });\n        const track = this._track;\n        const closeSamples = () => {\n            for (const sample of sampleQueue) {\n                sample?.close();\n            }\n        };\n        return {\n            async next() {\n                while (true) {\n                    if (track.input._disposed) {\n                        // Once next() throws, the consumer will never call return(), so terminate the\n                        // iteration here - otherwise, the pump keeps queueing decoded samples that\n                        // nothing can ever close.\n                        terminated = true;\n                        closeSamples();\n                        throw new InputDisposedError();\n                    }\n                    else if (terminated) {\n                        return { value: undefined, done: true };\n                    }\n                    else if (hasOutOfBandError) {\n                        terminated = true;\n                        closeSamples();\n                        throw outOfBandError;\n                    }\n                    else if (sampleQueue.length > 0) {\n                        const value = sampleQueue.shift();\n                        assert(value !== undefined);\n                        onQueueDequeue();\n                        return { value, done: false };\n                    }\n                    else if (!decoderIsFlushed) {\n                        await queueNotEmpty;\n                    }\n                    else {\n                        return { value: undefined, done: true };\n                    }\n                }\n            },\n            async return() {\n                terminated = true;\n                onQueueDequeue();\n                onQueueNotEmpty();\n                closeSamples();\n                return { value: undefined, done: true };\n            },\n            async throw(error) {\n                throw error;\n            },\n            [Symbol.asyncIterator]() {\n                return this;\n            },\n        };\n    }\n}\nclass VideoDecoderWrapper extends DecoderWrapper {\n    constructor(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution) {\n        super(onSample, onError);\n        this.codec = codec;\n        this.decoderConfig = decoderConfig;\n        this.rotation = rotation;\n        this.flip = flip;\n        this.timeResolution = timeResolution;\n        this.decoder = null;\n        this.customDecoder = null;\n        this.customDecoderCallSerializer = new CallSerializer();\n        this.customDecoderQueueSize = 0;\n        this.inputTimestamps = []; // Timestamps input into the decoder, sorted.\n        this.sampleQueue = []; // Safari-specific thing, check usage.\n        this.currentPacketIndex = 0;\n        this.raslSkipped = false; // For HEVC stuff\n        // Alpha stuff\n        this.alphaDecoder = null;\n        this.alphaHadKeyframe = false;\n        this.colorQueue = [];\n        this.alphaQueue = [];\n        this.merger = null;\n        this.decodedAlphaChunkCount = 0;\n        this.alphaDecoderQueueSize = 0;\n        /** Each value is the number of decoded alpha chunks at which a null alpha frame should be added. */\n        this.nullAlphaFrameQueue = [];\n        this.currentAlphaPacketIndex = 0;\n        this.alphaRaslSkipped = false; // For HEVC stuff\n        this.finalSamples = [];\n        this.mergeAlphaPromises = [];\n        const MatchingCustomDecoder = customVideoDecoders.find(x => x.supports(codec, decoderConfig));\n        if (MatchingCustomDecoder) {\n            // @ts-expect-error \"Can't create instance of abstract class 🤓\"\n            this.customDecoder = new MatchingCustomDecoder();\n            // @ts-expect-error It's technically readonly\n            this.customDecoder.codec = codec;\n            // @ts-expect-error It's technically readonly\n            this.customDecoder.config = decoderConfig;\n            // @ts-expect-error It's technically readonly\n            this.customDecoder.onSample = (sample) => {\n                if (!(sample instanceof VideoSample)) {\n                    throw new TypeError('The argument passed to onSample must be a VideoSample.');\n                }\n                this.finalizeAndEmitSample(sample);\n            };\n            // @ts-expect-error It's technically readonly\n            this.customDecoder.onError = (error) => {\n                onError(error);\n            };\n            void this.customDecoderCallSerializer\n                .call(() => this.customDecoder.init())\n                .catch(error => onError(error));\n        }\n        else {\n            const colorHandler = (frame) => {\n                if (this.alphaQueue.length > 0) {\n                    // Even when no alpha data is present (most of the time), there will be nulls in this queue\n                    const alphaFrame = this.alphaQueue.shift();\n                    assert(alphaFrame !== undefined);\n                    void this.mergeAlpha(frame, alphaFrame);\n                }\n                else {\n                    this.colorQueue.push(frame);\n                }\n            };\n            if (isChromium()) {\n                if (codec === 'avc' && this.decoderConfig.description) {\n                    const record = deserializeAvcDecoderConfigurationRecord(toUint8Array(this.decoderConfig.description));\n                    if (record && record.sequenceParameterSets.length > 0) {\n                        const sps = parseAvcSps(record.sequenceParameterSets[0]);\n                        if (sps) {\n                            if (sps.frameMbsOnlyFlag === 0) {\n                                // Chromium has/had a bug with playing interlaced AVC\n                                // (https://issues.chromium.org/issues/456919096) which can be worked around by\n                                // requesting that software decoding be used. So, here we peek into the AVC description,\n                                // if present, and switch to software decoding if we find interlaced content.\n                                this.decoderConfig = {\n                                    ...this.decoderConfig,\n                                    hardwareAcceleration: 'prefer-software',\n                                };\n                            }\n                            if (sps.maxDecFrameBuffering !== 0 && sps.bitstreamRestrictionFlag !== 1) {\n                                // Modify the SPS to fix potential loss of B frames\n                                record.sequenceParameterSets[0] = addAvcBitstreamRestriction(sps);\n                                this.decoderConfig = {\n                                    ...this.decoderConfig,\n                                    description: serializeAvcDecoderConfigurationRecord(record),\n                                };\n                            }\n                        }\n                    }\n                }\n                if (!colorSpaceIsComplete(this.decoderConfig.colorSpace)) {\n                    // Found via https://github.com/remotion-dev/remotion/issues/10841.\n                    // If the color space is incomplete (which is often that it's just partially filled), Chromium has\n                    // some nasty logic where it doesn't pass that information along to the GPU at all. The result is\n                    // that information is genuinely lost, like the color matrix for example. Chromium has other code\n                    // paths where it just fills the missing values with a hardcoded default, so we do the exact same\n                    // thing here, with the same hardcoded defaults:\n                    this.decoderConfig = {\n                        ...this.decoderConfig,\n                        colorSpace: {\n                            primaries: this.decoderConfig.colorSpace?.primaries ?? 'bt709',\n                            matrix: this.decoderConfig.colorSpace?.matrix ?? 'bt709',\n                            transfer: this.decoderConfig.colorSpace?.transfer ?? 'bt709',\n                            fullRange: this.decoderConfig.colorSpace?.fullRange ?? false,\n                        },\n                    };\n                }\n            }\n            const stack = new Error('Decoding error').stack;\n            this.decoder = new VideoDecoder({\n                output: (frame) => {\n                    try {\n                        colorHandler(frame);\n                    }\n                    catch (error) {\n                        this.onError(error);\n                    }\n                },\n                error: (error) => {\n                    error.stack = stack; // Provide a more useful stack trace, the default one sucks\n                    this.onError(error);\n                },\n            });\n            this.decoder.addEventListener('dequeue', () => {\n                this.onDequeue?.();\n            });\n            this.decoder.configure(this.decoderConfig);\n        }\n    }\n    getDecodeQueueSize() {\n        if (this.customDecoder) {\n            return this.customDecoderQueueSize;\n        }\n        else {\n            assert(this.decoder);\n            return Math.max(this.decoder.decodeQueueSize, this.alphaDecoder?.decodeQueueSize ?? 0);\n        }\n    }\n    decode(packet) {\n        if (this.codec === 'hevc' && this.currentPacketIndex > 0 && !this.raslSkipped) {\n            if (this.hasHevcRaslPicture(packet.data)) {\n                return; // Drop\n            }\n            this.raslSkipped = true;\n        }\n        if (this.customDecoder) {\n            this.customDecoderQueueSize++;\n            void this.customDecoderCallSerializer\n                .call(() => this.customDecoder.decode(packet))\n                .catch(error => this.onError(error))\n                .finally(() => {\n                this.customDecoderQueueSize--;\n                this.onDequeue?.();\n            });\n        }\n        else {\n            assert(this.decoder);\n            if (!isWebKit()) {\n                insertSorted(this.inputTimestamps, packet.timestamp, x => x);\n            }\n            if (isChromium() && this.currentPacketIndex === 0) {\n                if (this.codec === 'avc') {\n                    // Workaround for https://issues.chromium.org/issues/470109459\n                    const filteredNalUnits = [];\n                    let hasFrameData = false;\n                    for (const loc of iterateAvcNalUnits(packet.data, this.decoderConfig)) {\n                        const type = extractNalUnitTypeForAvc(packet.data[loc.offset]);\n                        hasFrameData ||= type >= 1 && type <= 5;\n                        if (type === AvcNalUnitType.AUD) {\n                            if (hasFrameData) {\n                                // Already has actual frame data, so treat an AUD as simply the end of the packet\n                                break;\n                            }\n                            else {\n                                // If packets contain an AUD and have NALUs before it, this trips up Chromium's key\n                                // frame detector. Clear the NALUs if an AUD is encountered.\n                                // https://github.com/Vanilagy/mediabunny/issues/396\n                                filteredNalUnits.length = 0;\n                            }\n                        }\n                        // These trip up Chromium's key frame detection, so let's strip them\n                        if (!(type >= 20 && type <= 31)) {\n                            filteredNalUnits.push(packet.data.subarray(loc.offset, loc.offset + loc.length));\n                        }\n                    }\n                    if (!this.decoderConfig.description) {\n                        // Do SPS fixups if necessary\n                        for (let i = 0; i < filteredNalUnits.length; i++) {\n                            const nalUnit = filteredNalUnits[i];\n                            if (extractNalUnitTypeForAvc(nalUnit[0]) !== AvcNalUnitType.SPS) {\n                                continue;\n                            }\n                            const sps = parseAvcSps(nalUnit);\n                            if (sps && sps.maxDecFrameBuffering !== 0 && sps.bitstreamRestrictionFlag !== 1) {\n                                filteredNalUnits[i] = addAvcBitstreamRestriction(sps);\n                            }\n                            break;\n                        }\n                    }\n                    const newData = concatAvcNalUnits(filteredNalUnits, this.decoderConfig);\n                    packet = new EncodedPacket(newData, packet.type, packet.timestamp, packet.duration);\n                }\n                else if (this.codec === 'hevc') {\n                    // Workaround for https://issues.chromium.org/issues/507611247\n                    const sanitizedData = sanitizeHevcPacketForChromium(packet.data, this.decoderConfig);\n                    if (sanitizedData) {\n                        packet = new EncodedPacket(sanitizedData, packet.type, packet.timestamp, packet.duration);\n                    }\n                }\n            }\n            this.decoder.decode(packet.toEncodedVideoChunk());\n            this.decodeAlphaData(packet);\n        }\n        this.currentPacketIndex++;\n    }\n    decodeAlphaData(packet) {\n        if (!packet.sideData.alpha) {\n            // No alpha side data in the packet, most common case\n            this.pushNullAlphaFrame();\n            return;\n        }\n        if (!this.merger) {\n            this.merger = new ColorAlphaMerger();\n        }\n        // Check if we need to set up the alpha decoder\n        if (!this.alphaDecoder) {\n            const alphaHandler = (frame) => {\n                if (this.colorQueue.length > 0) {\n                    const colorFrame = this.colorQueue.shift();\n                    assert(colorFrame !== undefined);\n                    void this.mergeAlpha(colorFrame, frame);\n                }\n                else {\n                    this.alphaQueue.push(frame);\n                }\n                // Check if any null frames have been queued for this point\n                this.decodedAlphaChunkCount++;\n                while (this.nullAlphaFrameQueue.length > 0\n                    && this.nullAlphaFrameQueue[0] === this.decodedAlphaChunkCount) {\n                    this.nullAlphaFrameQueue.shift();\n                    if (this.colorQueue.length > 0) {\n                        const colorFrame = this.colorQueue.shift();\n                        assert(colorFrame !== undefined);\n                        void this.mergeAlpha(colorFrame, null);\n                    }\n                    else {\n                        this.alphaQueue.push(null);\n                    }\n                }\n                this.alphaDecoderQueueSize--;\n            };\n            const stack = new Error('Decoding error').stack;\n            this.alphaDecoder = new VideoDecoder({\n                output: (frame) => {\n                    try {\n                        alphaHandler(frame);\n                    }\n                    catch (error) {\n                        this.onError(error);\n                    }\n                },\n                error: (error) => {\n                    error.stack = stack; // Provide a more useful stack trace, the default one sucks\n                    this.onError(error);\n                },\n            });\n            this.alphaDecoder.addEventListener('dequeue', () => {\n                this.onDequeue?.();\n            });\n            this.alphaDecoder.configure({\n                ...this.decoderConfig,\n                // Alpha is always full range, regardless of what the color track says. The decoder only honors the\n                // override if all fields are set tho.\n                colorSpace: {\n                    fullRange: true,\n                    // These fields are irrelevant:\n                    matrix: 'bt709',\n                    primaries: 'bt709',\n                    transfer: 'bt709',\n                },\n            });\n        }\n        const type = determineVideoPacketType(this.codec, this.decoderConfig, packet.sideData.alpha);\n        // Alpha packets might follow a different key frame rhythm than the main packets. Therefore, before we start\n        // decoding, we must first find a packet that's actually a key frame. Until then, we treat the image as opaque.\n        if (!this.alphaHadKeyframe) {\n            this.alphaHadKeyframe = type === 'key';\n        }\n        if (this.alphaHadKeyframe) {\n            // Same RASL skipping logic as for color, unlikely to be hit (since who uses HEVC with separate alpha??) but\n            // here for symmetry.\n            if (this.codec === 'hevc' && this.currentAlphaPacketIndex > 0 && !this.alphaRaslSkipped) {\n                if (this.hasHevcRaslPicture(packet.sideData.alpha)) {\n                    this.pushNullAlphaFrame();\n                    return;\n                }\n                this.alphaRaslSkipped = true;\n            }\n            this.currentAlphaPacketIndex++;\n            this.alphaDecoder.decode(packet.alphaToEncodedVideoChunk(type ?? packet.type));\n            this.alphaDecoderQueueSize++;\n        }\n        else {\n            this.pushNullAlphaFrame();\n        }\n    }\n    pushNullAlphaFrame() {\n        if (this.alphaDecoderQueueSize === 0) {\n            // Easy\n            this.alphaQueue.push(null);\n        }\n        else {\n            // There are still alpha chunks being decoded, so pushing `null` immediately would result in out-of-order\n            // data and be incorrect. Instead, we need to enqueue a \"null frame\" for when the current decoder workload\n            // has finished.\n            this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount + this.alphaDecoderQueueSize);\n        }\n    }\n    /**\n     * If we're using HEVC, we need to make sure to skip any RASL slices that follow a non-IDR key frame such as\n     * CRA_NUT. This is because RASL slices cannot be decoded without data before the CRA_NUT. Browsers behave\n     * differently here: Chromium drops the packets, Safari throws a decoder error. Either way, it's not good\n     * and causes bugs upstream. So, let's take the dropping into our own hands.\n     */\n    hasHevcRaslPicture(packetData) {\n        for (const loc of iterateHevcNalUnits(packetData, this.decoderConfig)) {\n            const type = extractNalUnitTypeForHevc(packetData[loc.offset]);\n            if (type === HevcNalUnitType.RASL_N || type === HevcNalUnitType.RASL_R) {\n                return true;\n            }\n        }\n        return false;\n    }\n    /** Handler for the WebCodecs VideoDecoder for ironing out browser differences. */\n    sampleHandler(sample) {\n        if (isWebKit()) {\n            // For correct B-frame handling, we don't just hand over the frames directly but instead add them to\n            // a queue, because we want to ensure frames are emitted in presentation order. We flush the queue\n            // each time we receive a frame with a timestamp larger than the highest we've seen so far, as we\n            // can sure that is not a B-frame. Typically, WebCodecs automatically guarantees that frames are\n            // emitted in presentation order, but Safari doesn't always follow this rule.\n            if (this.sampleQueue.length > 0 && (sample.timestamp >= last(this.sampleQueue).timestamp)) {\n                for (const sample of this.sampleQueue) {\n                    this.finalizeAndEmitSample(sample);\n                }\n                this.sampleQueue.length = 0;\n            }\n            insertSorted(this.sampleQueue, sample, x => x.timestamp);\n        }\n        else {\n            // Assign it the next earliest timestamp from the input. We do this because browsers, by spec, are\n            // required to emit decoded frames in presentation order *while* retaining the timestamp of their\n            // originating EncodedVideoChunk. For files with B-frames but no out-of-order timestamps (like a\n            // missing ctts box, for example), this causes a mismatch. We therefore fix the timestamps and\n            // ensure they are sorted by doing this.\n            const timestamp = this.inputTimestamps.shift();\n            // There's no way we'd have more decoded frames than encoded packets we passed in. Actually, the\n            // correspondence should be 1:1.\n            assert(timestamp !== undefined);\n            sample.setTimestamp(timestamp);\n            this.finalizeAndEmitSample(sample);\n        }\n    }\n    finalizeAndEmitSample(sample) {\n        // Round the timestamps to the time resolution\n        sample.setTimestamp(Math.round(sample.timestamp * this.timeResolution) / this.timeResolution);\n        sample.setDuration(Math.round(sample.duration * this.timeResolution) / this.timeResolution);\n        sample.setRotation(this.rotation);\n        sample.setFlip(this.flip);\n        this.onSample(sample);\n    }\n    async mergeAlpha(color, alpha) {\n        const resolver = promiseWithResolvers();\n        this.mergeAlphaPromises.push(resolver.promise);\n        // Alpha merging is concurrent but the samples must still be emitted in the same order in which the merging\n        // began. Therefore, serialize the results in an array.\n        const result = { sample: null };\n        this.finalSamples.push(result);\n        try {\n            if (!alpha) {\n                // Nothing needs to be merged\n                result.sample = new VideoSample(color);\n            }\n            else {\n                assert(this.merger);\n                // The merger takes ownership of the frames, so no need to close them ourselves\n                const finalFrame = await this.merger.merge(color, alpha);\n                result.sample = new VideoSample(finalFrame);\n            }\n            // Emit any leading samples that are ready, preserving input order\n            while (this.finalSamples.length > 0 && this.finalSamples[0].sample !== null) {\n                const next = this.finalSamples.shift();\n                this.sampleHandler(next.sample);\n            }\n        }\n        catch (error) {\n            removeItem(this.finalSamples, result);\n            this.onError(error);\n        }\n        finally {\n            removeItem(this.mergeAlphaPromises, resolver.promise);\n            resolver.resolve();\n        }\n    }\n    async flush() {\n        if (this.customDecoder) {\n            await this.customDecoderCallSerializer.call(() => this.customDecoder.flush());\n        }\n        else {\n            assert(this.decoder);\n            await Promise.all([\n                this.decoder.flush(),\n                this.alphaDecoder?.flush(),\n            ]);\n            await Promise.all(this.mergeAlphaPromises);\n            this.colorQueue.forEach(x => x.close());\n            this.colorQueue.length = 0;\n            this.alphaQueue.forEach(x => x?.close());\n            this.alphaQueue.length = 0;\n            this.alphaHadKeyframe = false;\n            this.decodedAlphaChunkCount = 0;\n            this.alphaDecoderQueueSize = 0;\n            this.nullAlphaFrameQueue.length = 0;\n            this.currentAlphaPacketIndex = 0;\n            this.alphaRaslSkipped = false;\n        }\n        if (isWebKit()) {\n            for (const sample of this.sampleQueue) {\n                this.finalizeAndEmitSample(sample);\n            }\n            this.sampleQueue.length = 0;\n        }\n        this.currentPacketIndex = 0;\n        this.raslSkipped = false;\n    }\n    close() {\n        if (this.customDecoder) {\n            void this.customDecoderCallSerializer.call(() => this.customDecoder.close());\n        }\n        else {\n            assert(this.decoder);\n            if (this.decoder.state !== 'closed') {\n                this.decoder.close();\n            }\n            if (this.alphaDecoder && this.alphaDecoder.state !== 'closed') {\n                this.alphaDecoder.close();\n            }\n            this.colorQueue.forEach(x => x.close());\n            this.colorQueue.length = 0;\n            this.alphaQueue.forEach(x => x?.close());\n            this.alphaQueue.length = 0;\n            this.merger?.close();\n        }\n        for (const sample of this.sampleQueue) {\n            sample.close();\n        }\n        this.sampleQueue.length = 0;\n    }\n}\nlet mergerWorkerUrl = null;\n/** Utility class that merges together color and alpha information on the CPU in a pool of workers. */\nexport class ColorAlphaMerger {\n    constructor() {\n        this.workers = [];\n        this.nextWorkerIndex = 0;\n        this.pendingRequests = new Map();\n        this.nextRequestId = 0;\n    }\n    merge(color, alpha) {\n        if (this.workers.length === 0) {\n            if (!mergerWorkerUrl) {\n                const blob = new Blob([`(${colorAlphaMergerWorkerCode.toString()})()`], { type: 'application/javascript' });\n                mergerWorkerUrl = URL.createObjectURL(blob);\n            }\n            const poolSize = clamp(navigator.hardwareConcurrency, 1, 4);\n            for (let i = 0; i < poolSize; i++) {\n                const worker = new Worker(mergerWorkerUrl);\n                worker.addEventListener('message', (event) => {\n                    const data = event.data;\n                    const pending = this.pendingRequests.get(data.id);\n                    if (!pending) {\n                        return;\n                    }\n                    this.pendingRequests.delete(data.id);\n                    if ('error' in data) {\n                        pending.reject(new Error(data.error));\n                    }\n                    else {\n                        pending.resolve(data.frame);\n                    }\n                });\n                worker.addEventListener('error', (event) => {\n                    const error = new Error(event.message || 'Color/alpha merge worker error.');\n                    for (const pending of this.pendingRequests.values()) {\n                        pending.reject(error);\n                    }\n                    this.pendingRequests.clear();\n                });\n                this.workers.push(worker);\n            }\n        }\n        const id = this.nextRequestId++;\n        const pending = promiseWithResolvers();\n        this.pendingRequests.set(id, pending);\n        // Hand the job to the next worker in round-robin fashion\n        const worker = this.workers[this.nextWorkerIndex];\n        this.nextWorkerIndex = (this.nextWorkerIndex + 1) % this.workers.length;\n        worker.postMessage({ id, color, alpha }, { transfer: [color, alpha] });\n        return pending.promise;\n    }\n    close() {\n        for (const worker of this.workers) {\n            worker.terminate();\n        }\n        this.workers.length = 0;\n        const error = new Error('Color/alpha merger closed.');\n        for (const pending of this.pendingRequests.values()) {\n            pending.reject(error);\n        }\n        this.pendingRequests.clear();\n    }\n}\nconst colorAlphaMergerWorkerCode = () => {\n    // These buffers are reused across frames as long as the size matches, since consecutive frames usually share\n    // dimensions\n    let cpuAlphaBuffer = null;\n    let cpuColorBuffer = null;\n    // Serialize execution internally so concurrent requests don't race on the shared cpu*Buffer state.\n    let chain = Promise.resolve();\n    self.addEventListener('message', (event) => {\n        const { id, color, alpha } = event.data;\n        chain = chain.then(async () => {\n            try {\n                const frame = await merge(color, alpha);\n                self.postMessage({ id, frame }, { transfer: [frame] });\n            }\n            catch (error) {\n                self.postMessage({ id, error: error.message });\n            }\n            finally {\n                // We took ownership of the inputs via transfer; close them now that the merge (or its error) is done.\n                color.close();\n                alpha.close();\n            }\n        });\n    });\n    const merge = async (color, alpha) => {\n        const format = color.format;\n        const alphaFormat = alpha.format;\n        if (!format || !alphaFormat) {\n            throw new Error('CPU color/alpha merging requires a known VideoFrame format.');\n        }\n        // The alpha frame must have the same bit depth as the color frame\n        const colorIs10 = format.includes('P10');\n        const colorIs12 = format.includes('P12');\n        const alphaIs10 = alphaFormat.includes('P10');\n        const alphaIs12 = alphaFormat.includes('P12');\n        if (alphaIs10 !== colorIs10 || alphaIs12 !== colorIs12) {\n            throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame`\n                + ` (color: '${format}', alpha: '${alphaFormat}').`);\n        }\n        if (format === 'RGBX' || format === 'RGBA' || format === 'BGRX' || format === 'BGRA') {\n            return await mergeInterleavedRgba(color, alpha, format);\n        }\n        else if (format === 'I420' || format === 'I420P10' || format === 'I420P12'\n            || format === 'I422' || format === 'I422P10' || format === 'I422P12'\n            || format === 'I444' || format === 'I444P10' || format === 'I444P12') {\n            return await mergePlanarYuv(color, alpha, format);\n        }\n        else if (format === 'NV12') {\n            return await mergeNv12(color, alpha);\n        }\n        throw new Error(`CPU color/alpha merging does not support format '${format}'.`);\n    };\n    const mergeInterleavedRgba = async (color, alpha, format) => {\n        const width = color.visibleRect?.width ?? color.codedWidth;\n        const height = color.visibleRect?.height ?? color.codedHeight;\n        const pixelCount = width * height;\n        const output = new Uint8Array(pixelCount * 4);\n        // Color goes straight into the output buffer via copyTo, no intermediate copy needed\n        await color.copyTo(output);\n        // And now add the alpha data\n        const alphaY = await readAlpha(alpha, width, height, 1);\n        for (let i = 0, j = 3; i < pixelCount; i++, j += 4) {\n            output[j] = alphaY[i];\n        }\n        const outputFormat = (format === 'RGBX' || format === 'RGBA') ? 'RGBA' : 'BGRA';\n        const init = {\n            format: outputFormat,\n            codedWidth: width,\n            codedHeight: height,\n            timestamp: color.timestamp,\n            duration: color.duration ?? undefined,\n            transfer: [output.buffer],\n        };\n        return new VideoFrame(output, init);\n    };\n    const mergePlanarYuv = async (color, alpha, format) => {\n        const width = color.visibleRect?.width ?? color.codedWidth;\n        const height = color.visibleRect?.height ?? color.codedHeight;\n        const is10 = format.includes('P10');\n        const is12 = format.includes('P12');\n        const bytesPerSample = (is10 || is12) ? 2 : 1;\n        let chromaW;\n        let chromaH;\n        if (format.startsWith('I420')) {\n            chromaW = Math.ceil(width / 2);\n            chromaH = Math.ceil(height / 2);\n        }\n        else if (format.startsWith('I422')) {\n            chromaW = Math.ceil(width / 2);\n            chromaH = height;\n        }\n        else {\n            chromaW = width;\n            chromaH = height;\n        }\n        const ySamples = width * height;\n        const uvSamples = chromaW * chromaH;\n        const yBytes = ySamples * bytesPerSample;\n        const uvBytes = uvSamples * bytesPerSample;\n        const aBytes = ySamples * bytesPerSample;\n        const outputBytes = yBytes + 2 * uvBytes + aBytes;\n        const output = new Uint8Array(outputBytes);\n        // Write color planes directly into the output buffer via copyTo, no intermediate copy\n        await color.copyTo(output);\n        const alphaY = await readAlpha(alpha, width, height, bytesPerSample);\n        const aOffset = yBytes + 2 * uvBytes;\n        output.set(alphaY, aOffset);\n        const outputFormat = (format.slice(0, 4) + 'A' + format.slice(4));\n        const init = {\n            format: outputFormat,\n            codedWidth: width,\n            codedHeight: height,\n            timestamp: color.timestamp,\n            duration: color.duration ?? undefined,\n            transfer: [output.buffer],\n        };\n        return new VideoFrame(output, init);\n    };\n    const mergeNv12 = async (color, alpha) => {\n        const width = color.visibleRect?.width ?? color.codedWidth;\n        const height = color.visibleRect?.height ?? color.codedHeight;\n        const ySize = width * height;\n        const chromaW = Math.ceil(width / 2);\n        const chromaH = Math.ceil(height / 2);\n        const uvSize = chromaW * chromaH;\n        const sourceSize = color.allocationSize();\n        if (!cpuColorBuffer || cpuColorBuffer.byteLength !== sourceSize) {\n            cpuColorBuffer = new Uint8Array(sourceSize);\n        }\n        await color.copyTo(cpuColorBuffer);\n        const output = new Uint8Array(ySize + 2 * uvSize + ySize);\n        // Y plane copies straight over\n        output.set(cpuColorBuffer.subarray(0, ySize), 0);\n        // Deinterleave the UV plane into separate U and V planes\n        const uOffset = ySize;\n        const vOffset = ySize + uvSize;\n        const uvStart = ySize;\n        for (let i = 0; i < uvSize; i++) {\n            output[uOffset + i] = cpuColorBuffer[uvStart + i * 2];\n            output[vOffset + i] = cpuColorBuffer[uvStart + i * 2 + 1];\n        }\n        const alphaY = await readAlpha(alpha, width, height, 1);\n        output.set(alphaY, ySize + 2 * uvSize);\n        const init = {\n            format: 'I420A',\n            codedWidth: width,\n            codedHeight: height,\n            timestamp: color.timestamp,\n            duration: color.duration ?? undefined,\n            transfer: [output.buffer],\n        };\n        return new VideoFrame(output, init);\n    };\n    const readAlpha = async (alpha, width, height, bytesPerSample) => {\n        const size = alpha.allocationSize();\n        if (!cpuAlphaBuffer || cpuAlphaBuffer.byteLength !== size) {\n            cpuAlphaBuffer = new Uint8Array(size);\n        }\n        await alpha.copyTo(cpuAlphaBuffer);\n        const format = alpha.format;\n        if (format === 'RGBA' || format === 'BGRA' || format === 'RGBX' || format === 'BGRX') {\n            // Pack alpha data tightly. Assume alpha is stored in RGB, so sample just from R for simplicity.\n            const rOffset = (format === 'RGBA' || format === 'RGBX') ? 0 : 2;\n            const pixelCount = width * height;\n            for (let i = 0; i < pixelCount; i++) {\n                cpuAlphaBuffer[i] = cpuAlphaBuffer[i * 4 + rOffset];\n            }\n            return cpuAlphaBuffer.subarray(0, pixelCount);\n        }\n        else {\n            // For Y-plane-first formats (I*** and NV12), the leading width*height samples are the Y plane\n            const yPlane = cpuAlphaBuffer.subarray(0, width * height * bytesPerSample);\n            if (alpha.colorSpace.fullRange === false) {\n                // Some decoders hand us limited-range alpha, so stretch it back out to full range\n                const bitDepth = format.includes('P12') ? 12 : format.includes('P10') ? 10 : 8;\n                const low = 16 << (bitDepth - 8);\n                const high = 235 << (bitDepth - 8);\n                const max = (1 << bitDepth) - 1;\n                const samples = bytesPerSample === 2\n                    ? new Uint16Array(yPlane.buffer, 0, width * height)\n                    : yPlane;\n                for (let i = 0; i < samples.length; i++) {\n                    const value = Math.round((samples[i] - low) * max / (high - low));\n                    samples[i] = Math.min(Math.max(value, 0), max);\n                }\n            }\n            return yPlane;\n        }\n    };\n};\nconst validateVideoSinkDecoderOptions = (decoderOptions) => {\n    if (!decoderOptions || typeof decoderOptions !== 'object') {\n        throw new TypeError('decoderOptions must be an object.');\n    }\n    if (decoderOptions.hardwareAcceleration !== undefined\n        && !['no-preference', 'prefer-hardware', 'prefer-software'].includes(decoderOptions.hardwareAcceleration)) {\n        throw new TypeError('decoderOptions.hardwareAcceleration, when provided, must be \\'no-preference\\', \\'prefer-hardware\\' or'\n            + ' \\'prefer-software\\'.');\n    }\n    if (decoderOptions.optimizeForLatency !== undefined && typeof decoderOptions.optimizeForLatency !== 'boolean') {\n        throw new TypeError('decoderOptions.optimizeForLatency, when provided, must be a boolean.');\n    }\n};\n/**\n * A sink that retrieves decoded video samples (video frames) from a video track.\n * @group Media sinks\n * @public\n */\nexport class VideoSampleSink extends BaseMediaSampleSink {\n    /** Creates a new {@link VideoSampleSink} for the given {@link InputVideoTrack}. */\n    constructor(videoTrack, decoderOptions = {}) {\n        if (!(videoTrack instanceof InputVideoTrack)) {\n            throw new TypeError('videoTrack must be an InputVideoTrack.');\n        }\n        validateVideoSinkDecoderOptions(decoderOptions);\n        super();\n        this._track = videoTrack;\n        this._decoderOptions = decoderOptions;\n    }\n    /** @internal */\n    async _createDecoder(onSample, onError) {\n        if (!(await this._track.canDecode())) {\n            if (typeof VideoDecoder === 'undefined') {\n                throw new Error(missingWebCodecsClassMessage('VideoDecoder'));\n            }\n            throw new Error('This video track cannot be decoded in this environment. Make sure to check decodability before using'\n                + ' a track.');\n        }\n        const codec = await this._track.getCodec();\n        const rotation = await this._track.getRotation();\n        const flip = await this._track.getFlip();\n        let decoderConfig = await this._track.getDecoderConfig();\n        const timeResolution = await this._track.getTimeResolution();\n        assert(codec && decoderConfig);\n        decoderConfig = {\n            ...decoderConfig,\n            hardwareAcceleration: this._decoderOptions.hardwareAcceleration,\n            optimizeForLatency: this._decoderOptions.optimizeForLatency,\n        };\n        return new VideoDecoderWrapper(onSample, onError, codec, decoderConfig, rotation, flip, timeResolution);\n    }\n    /** @internal */\n    _createPacketSink() {\n        return new EncodedPacketSink(this._track);\n    }\n    /**\n     * Retrieves the video sample (frame) corresponding to the given timestamp, in seconds. More specifically, returns\n     * the last video sample (in presentation order) with a start timestamp less than or equal to the given timestamp.\n     * Returns null if the timestamp is before the track's first timestamp.\n     *\n     * @param timestamp - The timestamp used for retrieval, in seconds.\n     * @param options - Options used for the underlying packet retrieval.\n     */\n    async getSample(timestamp, options = {}) {\n        validateTimestamp(timestamp);\n        for await (const sample of this.mediaSamplesAtTimestamps([timestamp], options)) {\n            return sample;\n        }\n        throw new Error('Internal error: Iterator returned nothing.');\n    }\n    /**\n     * Creates an async iterator that yields the video samples (frames) of this track in presentation order. This method\n     * will intelligently pre-decode a few frames ahead to enable fast iteration.\n     *\n     * @param startTimestamp - The timestamp in seconds at which to start yielding samples (inclusive).\n     * @param endTimestamp - The timestamp in seconds at which to stop yielding samples (exclusive).\n     * @param options - Options used for the underlying packet retrieval.\n     */\n    samples(startTimestamp, endTimestamp, options = {}) {\n        return this.mediaSamplesInRange(startTimestamp, endTimestamp, options);\n    }\n    /**\n     * Creates an async iterator that yields a video sample (frame) for each timestamp in the argument. This method\n     * uses an optimized decoding pipeline if these timestamps are monotonically sorted, decoding each packet at most\n     * once, and is therefore more efficient than manually getting the sample for every timestamp. The iterator may\n     * yield null if no frame is available for a given timestamp.\n     *\n     * This method is good for sparse access of media data. If you want primarily sequential media access, prefer\n     * {@link VideoSampleSink.samples} instead.\n     *\n     * @param timestamps - An iterable or async iterable of timestamps in seconds.\n     * @param options - Options used for the underlying packet retrieval.\n     */\n    samplesAtTimestamps(timestamps, options = {}) {\n        return this.mediaSamplesAtTimestamps(timestamps, options);\n    }\n}\n/**\n * A sink that renders video samples (frames) of the given video track to canvases. This is often more useful than\n * directly retrieving frames, as it comes with common preprocessing steps such as resizing or applying rotation and\n * flip metadata.\n *\n * This sink will yield `HTMLCanvasElement`s when in a DOM context, and `OffscreenCanvas`es otherwise.\n *\n * @group Media sinks\n * @public\n */\nexport class CanvasSink {\n    /** Creates a new {@link CanvasSink} for the given {@link InputVideoTrack}. */\n    constructor(videoTrack, options = {}) {\n        /** @internal */\n        this._rotation = 0;\n        /** @internal */\n        this._flip = false;\n        /** @internal */\n        this._initPromise = null;\n        /** @internal */\n        this._nextCanvasIndex = 0;\n        if (!(videoTrack instanceof InputVideoTrack)) {\n            throw new TypeError('videoTrack must be an InputVideoTrack.');\n        }\n        if (options && typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.alpha !== undefined && typeof options.alpha !== 'boolean') {\n            throw new TypeError('options.alpha, when provided, must be a boolean.');\n        }\n        if (options.width !== undefined && (!Number.isInteger(options.width) || options.width <= 0)) {\n            throw new TypeError('options.width, when defined, must be a positive integer.');\n        }\n        if (options.height !== undefined && (!Number.isInteger(options.height) || options.height <= 0)) {\n            throw new TypeError('options.height, when defined, must be a positive integer.');\n        }\n        if (options.fit !== undefined && !['fill', 'contain', 'cover'].includes(options.fit)) {\n            throw new TypeError('options.fit, when provided, must be one of \"fill\", \"contain\", or \"cover\".');\n        }\n        if (options.width !== undefined\n            && options.height !== undefined\n            && options.fit === undefined) {\n            throw new TypeError('When both options.width and options.height are provided, options.fit must also be provided.');\n        }\n        if (options.rotation !== undefined && ![0, 90, 180, 270].includes(options.rotation)) {\n            throw new TypeError('options.rotation, when provided, must be 0, 90, 180 or 270.');\n        }\n        if (options.flip !== undefined && typeof options.flip !== 'boolean') {\n            throw new TypeError('options.flip, when provided, must be a boolean.');\n        }\n        if (options.crop !== undefined) {\n            validateCropRectangle(options.crop, 'options.');\n        }\n        if (options.poolSize !== undefined\n            && (typeof options.poolSize !== 'number' || !Number.isInteger(options.poolSize) || options.poolSize < 0)) {\n            throw new TypeError('poolSize must be a non-negative integer.');\n        }\n        if (options.decoderOptions !== undefined) {\n            validateVideoSinkDecoderOptions(options.decoderOptions);\n        }\n        this._videoTrack = videoTrack;\n        this._alpha = options.alpha ?? false;\n        this._options = options;\n        this._fit = options.fit ?? 'fill';\n        this._videoSampleSink = new VideoSampleSink(videoTrack, options.decoderOptions);\n        this._canvasPool = Array.from({ length: options.poolSize ?? 0 }, () => null);\n    }\n    /** @internal */\n    _ensureInit() {\n        return this._initPromise ??= (async () => {\n            const options = this._options;\n            const videoTrack = this._videoTrack;\n            const rotation = options.rotation ?? await videoTrack.getRotation();\n            const flip = options.flip ?? await videoTrack.getFlip();\n            const squarePixelWidth = await videoTrack.getSquarePixelWidth();\n            const squarePixelHeight = await videoTrack.getSquarePixelHeight();\n            const [rotatedWidth, rotatedHeight] = rotation % 180 === 0\n                ? [squarePixelWidth, squarePixelHeight]\n                : [squarePixelHeight, squarePixelWidth];\n            let crop = options.crop;\n            if (crop) {\n                crop = clampCropRectangle(crop, rotatedWidth, rotatedHeight);\n            }\n            let [width, height] = crop\n                ? [crop.width, crop.height]\n                : [rotatedWidth, rotatedHeight];\n            const originalAspectRatio = width / height;\n            // If width and height aren't defined together, deduce the missing value using the aspect ratio\n            if (options.width !== undefined && options.height === undefined) {\n                width = options.width;\n                height = Math.round(width / originalAspectRatio);\n            }\n            else if (options.width === undefined && options.height !== undefined) {\n                height = options.height;\n                width = Math.round(height * originalAspectRatio);\n            }\n            else if (options.width !== undefined && options.height !== undefined) {\n                width = options.width;\n                height = options.height;\n            }\n            this._width = width;\n            this._height = height;\n            this._rotation = rotation;\n            this._flip = flip;\n            this._crop = crop;\n        })();\n    }\n    /** @internal */\n    _videoSampleToWrappedCanvas(sample) {\n        const width = this._width;\n        const height = this._height;\n        let canvas = this._canvasPool[this._nextCanvasIndex];\n        let canvasIsNew = false;\n        if (!canvas) {\n            if (typeof document !== 'undefined') {\n                // Prefer an HTMLCanvasElement\n                canvas = document.createElement('canvas');\n                canvas.width = width;\n                canvas.height = height;\n            }\n            else {\n                canvas = new OffscreenCanvas(width, height);\n            }\n            if (this._canvasPool.length > 0) {\n                this._canvasPool[this._nextCanvasIndex] = canvas;\n            }\n            canvasIsNew = true;\n        }\n        if (this._canvasPool.length > 0) {\n            this._nextCanvasIndex = (this._nextCanvasIndex + 1) % this._canvasPool.length;\n        }\n        const context = canvas.getContext('2d', {\n            alpha: this._alpha || isFirefox(), // Firefox has VideoFrame glitches with opaque canvases\n        });\n        assert(context);\n        sample._drawWithFitAndMipmapping(canvas, context, {\n            fit: this._fit,\n            rotation: this._rotation,\n            flip: this._flip,\n            crop: this._crop,\n            targetIsFresh: canvasIsNew,\n            fillBlack: !this._alpha && isFirefox(),\n        });\n        const result = {\n            canvas,\n            timestamp: sample.timestamp,\n            duration: sample.duration,\n        };\n        sample.close();\n        return result;\n    }\n    /**\n     * Retrieves a canvas with the video frame corresponding to the given timestamp, in seconds. More specifically,\n     * returns the last video frame (in presentation order) with a start timestamp less than or equal to the given\n     * timestamp. Returns null if the timestamp is before the track's first timestamp.\n     *\n     * @param timestamp - The timestamp used for retrieval, in seconds.\n     * @param options - Options used for the underlying packet retrieval.\n     */\n    async getCanvas(timestamp, options) {\n        validateTimestamp(timestamp);\n        await this._ensureInit();\n        const sample = await this._videoSampleSink.getSample(timestamp, options);\n        return sample && this._videoSampleToWrappedCanvas(sample);\n    }\n    /**\n     * Creates an async iterator that yields canvases with the video frames of this track in presentation order. This\n     * method will intelligently pre-decode a few frames ahead to enable fast iteration.\n     *\n     * @param startTimestamp - The timestamp in seconds at which to start yielding canvases (inclusive).\n     * @param endTimestamp - The timestamp in seconds at which to stop yielding canvases (exclusive).\n     * @param options - Options used for the underlying packet retrieval.\n     */\n    async *canvases(startTimestamp, endTimestamp, options) {\n        await this._ensureInit();\n        yield* mapAsyncGenerator(this._videoSampleSink.samples(startTimestamp, endTimestamp, options), sample => this._videoSampleToWrappedCanvas(sample));\n    }\n    /**\n     * Creates an async iterator that yields a canvas for each timestamp in the argument. This method uses an optimized\n     * decoding pipeline if these timestamps are monotonically sorted, decoding each packet at most once, and is\n     * therefore more efficient than manually getting the canvas for every timestamp. The iterator may yield null if\n     * no frame is available for a given timestamp.\n     *\n     * This method is good for sparse access of media data. If you want primarily sequential media access, prefer\n     * {@link CanvasSink.canvases} instead.\n     *\n     * @param timestamps - An iterable or async iterable of timestamps in seconds.\n     * @param options - Options used for the underlying packet retrieval.\n     */\n    async *canvasesAtTimestamps(timestamps, options) {\n        await this._ensureInit();\n        yield* mapAsyncGenerator(this._videoSampleSink.samplesAtTimestamps(timestamps, options), sample => sample && this._videoSampleToWrappedCanvas(sample));\n    }\n}\nclass AudioDecoderWrapper extends DecoderWrapper {\n    constructor(onSample, onError, codec, decoderConfig) {\n        super(onSample, onError);\n        this.decoder = null;\n        this.customDecoder = null;\n        this.customDecoderCallSerializer = new CallSerializer();\n        this.customDecoderQueueSize = 0;\n        // Internal state to accumulate a precise current timestamp based on audio durations, not the (potentially\n        // inaccurate) packet timestamps.\n        this.currentTimestamp = null;\n        // Chromium does not respect negative packet timestamps, so we must do the fixin' ourselves\n        this.expectedFirstTimestamp = null;\n        this.timestampOffset = 0;\n        const sampleHandler = (sample) => {\n            let sampleTimestamp = sample.timestamp;\n            if (this.expectedFirstTimestamp !== null && this.currentTimestamp === null) {\n                this.timestampOffset = this.expectedFirstTimestamp - sampleTimestamp;\n                ;\n            }\n            sampleTimestamp += this.timestampOffset;\n            if (this.currentTimestamp === null\n                || Math.abs(sampleTimestamp - this.currentTimestamp) >= sample.duration) {\n                // We need to sync with the sample timestamp again\n                this.currentTimestamp = sampleTimestamp;\n            }\n            const preciseTimestamp = this.currentTimestamp;\n            this.currentTimestamp += sample.duration;\n            if (sample.numberOfFrames === 0) {\n                // We skip zero-data (empty) AudioSamples. These are sometimes emitted, for example, by Firefox when it\n                // decodes Vorbis (at the start).\n                sample.close();\n                return;\n            }\n            // Round the timestamp to the sample rate\n            const sampleRate = decoderConfig.sampleRate;\n            sample.setTimestamp(Math.round(preciseTimestamp * sampleRate) / sampleRate);\n            onSample(sample);\n        };\n        const MatchingCustomDecoder = customAudioDecoders.find(x => x.supports(codec, decoderConfig));\n        if (MatchingCustomDecoder) {\n            // @ts-expect-error \"Can't create instance of abstract class 🤓\"\n            this.customDecoder = new MatchingCustomDecoder();\n            // @ts-expect-error It's technically readonly\n            this.customDecoder.codec = codec;\n            // @ts-expect-error It's technically readonly\n            this.customDecoder.config = decoderConfig;\n            // @ts-expect-error It's technically readonly\n            this.customDecoder.onSample = (sample) => {\n                if (!(sample instanceof AudioSample)) {\n                    throw new TypeError('The argument passed to onSample must be an AudioSample.');\n                }\n                sampleHandler(sample);\n            };\n            // @ts-expect-error It's technically readonly\n            this.customDecoder.onError = (error) => {\n                onError(error);\n            };\n            void this.customDecoderCallSerializer\n                .call(() => this.customDecoder.init())\n                .catch(error => onError(error));\n        }\n        else {\n            const stack = new Error('Decoding error').stack;\n            this.decoder = new AudioDecoder({\n                output: (data) => {\n                    try {\n                        sampleHandler(new AudioSample(data));\n                    }\n                    catch (error) {\n                        this.onError(error);\n                    }\n                },\n                error: (error) => {\n                    error.stack = stack; // Provide a more useful stack trace, the default one sucks\n                    this.onError(error);\n                },\n            });\n            this.decoder.addEventListener('dequeue', () => {\n                this.onDequeue?.();\n            });\n            this.decoder.configure(decoderConfig);\n        }\n    }\n    getDecodeQueueSize() {\n        if (this.customDecoder) {\n            return this.customDecoderQueueSize;\n        }\n        else {\n            assert(this.decoder);\n            return this.decoder.decodeQueueSize;\n        }\n    }\n    decode(packet) {\n        if (this.customDecoder) {\n            this.customDecoderQueueSize++;\n            void this.customDecoderCallSerializer\n                .call(() => this.customDecoder.decode(packet))\n                .catch(error => this.onError(error))\n                .finally(() => {\n                this.customDecoderQueueSize--;\n                this.onDequeue?.();\n            });\n        }\n        else {\n            assert(this.decoder);\n            this.expectedFirstTimestamp ??= packet.timestamp;\n            this.decoder.decode(packet.toEncodedAudioChunk());\n        }\n    }\n    async flush() {\n        if (this.customDecoder) {\n            await this.customDecoderCallSerializer.call(() => this.customDecoder.flush());\n        }\n        else {\n            assert(this.decoder);\n            await this.decoder.flush();\n        }\n        this.currentTimestamp = null;\n        this.expectedFirstTimestamp = null;\n        this.timestampOffset = 0;\n    }\n    close() {\n        if (this.customDecoder) {\n            void this.customDecoderCallSerializer.call(() => this.customDecoder.close());\n        }\n        else {\n            assert(this.decoder);\n            if (this.decoder.state !== 'closed') {\n                this.decoder.close();\n            }\n        }\n    }\n}\n// There are a lot of PCM variants not natively supported by the browser and by AudioData. Therefore we need a simple\n// decoder that maps any input PCM format into a PCM format supported by the browser.\nclass PcmAudioDecoderWrapper extends DecoderWrapper {\n    constructor(onSample, onError, decoderConfig) {\n        super(onSample, onError);\n        this.decoderConfig = decoderConfig;\n        // Internal state to accumulate a precise current timestamp based on audio durations, not the (potentially\n        // inaccurate) packet timestamps.\n        this.currentTimestamp = null;\n        assert(PCM_AUDIO_CODECS.includes(decoderConfig.codec));\n        this.codec = decoderConfig.codec;\n        const { dataType, sampleSize, littleEndian } = parsePcmCodec(this.codec);\n        this.inputSampleSize = sampleSize;\n        switch (sampleSize) {\n            case 1:\n                {\n                    if (dataType === 'unsigned') {\n                        this.readInputValue = (view, byteOffset) => view.getUint8(byteOffset) - 2 ** 7;\n                    }\n                    else if (dataType === 'signed') {\n                        this.readInputValue = (view, byteOffset) => view.getInt8(byteOffset);\n                    }\n                    else if (dataType === 'ulaw') {\n                        this.readInputValue = (view, byteOffset) => fromUlaw(view.getUint8(byteOffset));\n                    }\n                    else if (dataType === 'alaw') {\n                        this.readInputValue = (view, byteOffset) => fromAlaw(view.getUint8(byteOffset));\n                    }\n                    else {\n                        assert(false);\n                    }\n                }\n                ;\n                break;\n            case 2:\n                {\n                    if (dataType === 'unsigned') {\n                        this.readInputValue = (view, byteOffset) => view.getUint16(byteOffset, littleEndian) - 2 ** 15;\n                    }\n                    else if (dataType === 'signed') {\n                        this.readInputValue = (view, byteOffset) => view.getInt16(byteOffset, littleEndian);\n                    }\n                    else {\n                        assert(false);\n                    }\n                }\n                ;\n                break;\n            case 3:\n                {\n                    if (dataType === 'unsigned') {\n                        this.readInputValue = (view, byteOffset) => getUint24(view, byteOffset, littleEndian) - 2 ** 23;\n                    }\n                    else if (dataType === 'signed') {\n                        this.readInputValue = (view, byteOffset) => getInt24(view, byteOffset, littleEndian);\n                    }\n                    else {\n                        assert(false);\n                    }\n                }\n                ;\n                break;\n            case 4:\n                {\n                    if (dataType === 'unsigned') {\n                        this.readInputValue = (view, byteOffset) => view.getUint32(byteOffset, littleEndian) - 2 ** 31;\n                    }\n                    else if (dataType === 'signed') {\n                        this.readInputValue = (view, byteOffset) => view.getInt32(byteOffset, littleEndian);\n                    }\n                    else if (dataType === 'float') {\n                        this.readInputValue = (view, byteOffset) => view.getFloat32(byteOffset, littleEndian);\n                    }\n                    else {\n                        assert(false);\n                    }\n                }\n                ;\n                break;\n            case 8:\n                {\n                    if (dataType === 'float') {\n                        this.readInputValue = (view, byteOffset) => view.getFloat64(byteOffset, littleEndian);\n                    }\n                    else {\n                        assert(false);\n                    }\n                }\n                ;\n                break;\n            default:\n                {\n                    assertNever(sampleSize);\n                    assert(false);\n                }\n                ;\n        }\n        switch (sampleSize) {\n            case 1:\n                {\n                    if (dataType === 'ulaw' || dataType === 'alaw') {\n                        this.outputSampleSize = 2;\n                        this.outputFormat = 's16';\n                        this.writeOutputValue = (view, byteOffset, value) => view.setInt16(byteOffset, value, true);\n                    }\n                    else {\n                        this.outputSampleSize = 1;\n                        this.outputFormat = 'u8';\n                        this.writeOutputValue = (view, byteOffset, value) => view.setUint8(byteOffset, value + 2 ** 7);\n                    }\n                }\n                ;\n                break;\n            case 2:\n                {\n                    this.outputSampleSize = 2;\n                    this.outputFormat = 's16';\n                    this.writeOutputValue = (view, byteOffset, value) => view.setInt16(byteOffset, value, true);\n                }\n                ;\n                break;\n            case 3:\n                {\n                    this.outputSampleSize = 4;\n                    this.outputFormat = 's32';\n                    // From https://www.w3.org/TR/webcodecs:\n                    // AudioData containing 24-bit samples SHOULD store those samples in s32 or f32. When samples are\n                    // stored in s32, each sample MUST be left-shifted by 8 bits.\n                    this.writeOutputValue = (view, byteOffset, value) => view.setInt32(byteOffset, value << 8, true);\n                }\n                ;\n                break;\n            case 4:\n                {\n                    this.outputSampleSize = 4;\n                    if (dataType === 'float') {\n                        this.outputFormat = 'f32';\n                        this.writeOutputValue = (view, byteOffset, value) => view.setFloat32(byteOffset, value, true);\n                    }\n                    else {\n                        this.outputFormat = 's32';\n                        this.writeOutputValue = (view, byteOffset, value) => view.setInt32(byteOffset, value, true);\n                    }\n                }\n                ;\n                break;\n            case 8:\n                {\n                    this.outputSampleSize = 4;\n                    this.outputFormat = 'f32';\n                    this.writeOutputValue = (view, byteOffset, value) => view.setFloat32(byteOffset, value, true);\n                }\n                ;\n                break;\n            default:\n                {\n                    assertNever(sampleSize);\n                    assert(false);\n                }\n                ;\n        }\n        ;\n    }\n    getDecodeQueueSize() {\n        return 0;\n    }\n    decode(packet) {\n        const inputView = toDataView(packet.data);\n        // A trailing partial frame (only in malformed files) gets dropped\n        const numberOfFrames = Math.floor(packet.byteLength / this.decoderConfig.numberOfChannels / this.inputSampleSize);\n        const outputBufferSize = numberOfFrames * this.decoderConfig.numberOfChannels * this.outputSampleSize;\n        const outputBuffer = new ArrayBuffer(outputBufferSize);\n        const outputView = new DataView(outputBuffer);\n        for (let i = 0; i < numberOfFrames * this.decoderConfig.numberOfChannels; i++) {\n            const inputIndex = i * this.inputSampleSize;\n            const outputIndex = i * this.outputSampleSize;\n            const value = this.readInputValue(inputView, inputIndex);\n            this.writeOutputValue(outputView, outputIndex, value);\n        }\n        const preciseDuration = numberOfFrames / this.decoderConfig.sampleRate;\n        if (this.currentTimestamp === null || Math.abs(packet.timestamp - this.currentTimestamp) >= preciseDuration) {\n            // We need to sync with the packet timestamp again\n            this.currentTimestamp = packet.timestamp;\n        }\n        const preciseTimestamp = this.currentTimestamp;\n        this.currentTimestamp += preciseDuration;\n        const audioSample = new AudioSample({\n            format: this.outputFormat,\n            data: outputBuffer,\n            numberOfChannels: this.decoderConfig.numberOfChannels,\n            sampleRate: this.decoderConfig.sampleRate,\n            numberOfFrames,\n            timestamp: preciseTimestamp,\n        });\n        this.onSample(audioSample);\n    }\n    async flush() {\n        // Do nothing\n    }\n    close() {\n        // Do nothing\n    }\n}\n/**\n * Sink for retrieving decoded audio samples from an audio track.\n * @group Media sinks\n * @public\n */\nexport class AudioSampleSink extends BaseMediaSampleSink {\n    /** Creates a new {@link AudioSampleSink} for the given {@link InputAudioTrack}. */\n    constructor(audioTrack) {\n        if (!(audioTrack instanceof InputAudioTrack)) {\n            throw new TypeError('audioTrack must be an InputAudioTrack.');\n        }\n        super();\n        this._track = audioTrack;\n    }\n    /** @internal */\n    async _createDecoder(onSample, onError) {\n        if (!(await this._track.canDecode())) {\n            if (typeof AudioDecoder === 'undefined') {\n                throw new Error(missingWebCodecsClassMessage('AudioDecoder'));\n            }\n            throw new Error('This audio track cannot be decoded in this environment. Make sure to check decodability before using'\n                + ' a track.');\n        }\n        const codec = await this._track.getCodec();\n        const decoderConfig = await this._track.getDecoderConfig();\n        assert(codec && decoderConfig);\n        if (PCM_AUDIO_CODECS.includes(decoderConfig.codec)) {\n            return new PcmAudioDecoderWrapper(onSample, onError, decoderConfig);\n        }\n        else {\n            return new AudioDecoderWrapper(onSample, onError, codec, decoderConfig);\n        }\n    }\n    /** @internal */\n    _createPacketSink() {\n        return new EncodedPacketSink(this._track);\n    }\n    /**\n     * Retrieves the audio sample corresponding to the given timestamp, in seconds. More specifically, returns\n     * the last audio sample (in presentation order) with a start timestamp less than or equal to the given timestamp.\n     * Returns null if the timestamp is before the track's first timestamp.\n     *\n     * @param timestamp - The timestamp used for retrieval, in seconds.\n     * @param options - Options used for the underlying packet retrieval.\n     */\n    async getSample(timestamp, options = {}) {\n        validateTimestamp(timestamp);\n        for await (const sample of this.mediaSamplesAtTimestamps([timestamp], options)) {\n            return sample;\n        }\n        throw new Error('Internal error: Iterator returned nothing.');\n    }\n    /**\n     * Creates an async iterator that yields the audio samples of this track in presentation order. This method\n     * will intelligently pre-decode a few samples ahead to enable fast iteration.\n     *\n     * @param startTimestamp - The timestamp in seconds at which to start yielding samples (inclusive).\n     * @param endTimestamp - The timestamp in seconds at which to stop yielding samples (exclusive).\n     * @param options - Options used for the underlying packet retrieval.\n     */\n    samples(startTimestamp, endTimestamp, options = {}) {\n        return this.mediaSamplesInRange(startTimestamp, endTimestamp, options);\n    }\n    /**\n     * Creates an async iterator that yields an audio sample for each timestamp in the argument. This method\n     * uses an optimized decoding pipeline if these timestamps are monotonically sorted, decoding each packet at most\n     * once, and is therefore more efficient than manually getting the sample for every timestamp. The iterator may\n     * yield null if no sample is available for a given timestamp.\n     *\n     * This method is good for sparse access of media data. If you want primarily sequential media access, prefer\n     * {@link AudioSampleSink.samples} instead.\n     *\n     * @param timestamps - An iterable or async iterable of timestamps in seconds.\n     * @param options - Options used for the underlying packet retrieval.\n     */\n    samplesAtTimestamps(timestamps, options = {}) {\n        return this.mediaSamplesAtTimestamps(timestamps, options);\n    }\n}\n/**\n * A sink that retrieves decoded audio samples from an audio track and converts them to `AudioBuffer` instances. This is\n * often more useful than directly retrieving audio samples, as audio buffers can be directly used with the\n * Web Audio API.\n * @group Media sinks\n * @public\n */\nexport class AudioBufferSink {\n    /** Creates a new {@link AudioBufferSink} for the given {@link InputAudioTrack}. */\n    constructor(audioTrack) {\n        if (!(audioTrack instanceof InputAudioTrack)) {\n            throw new TypeError('audioTrack must be an InputAudioTrack.');\n        }\n        this._audioSampleSink = new AudioSampleSink(audioTrack);\n    }\n    /** @internal */\n    _audioSampleToWrappedArrayBuffer(sample) {\n        const result = {\n            buffer: sample.toAudioBuffer(),\n            timestamp: sample.timestamp,\n            duration: sample.duration,\n        };\n        sample.close();\n        return result;\n    }\n    /**\n     * Retrieves the audio buffer corresponding to the given timestamp, in seconds. More specifically, returns\n     * the last audio buffer (in presentation order) with a start timestamp less than or equal to the given timestamp.\n     * Returns null if the timestamp is before the track's first timestamp.\n     *\n     * @param timestamp - The timestamp used for retrieval, in seconds.\n     * @param options - Options used for the underlying packet retrieval.\n     */\n    async getBuffer(timestamp, options) {\n        validateTimestamp(timestamp);\n        const data = await this._audioSampleSink.getSample(timestamp, options);\n        return data && this._audioSampleToWrappedArrayBuffer(data);\n    }\n    /**\n     * Creates an async iterator that yields audio buffers of this track in presentation order. This method\n     * will intelligently pre-decode a few buffers ahead to enable fast iteration.\n     *\n     * @param startTimestamp - The timestamp in seconds at which to start yielding buffers (inclusive).\n     * @param endTimestamp - The timestamp in seconds at which to stop yielding buffers (exclusive).\n     * @param options - Options used for the underlying packet retrieval.\n     */\n    buffers(startTimestamp, endTimestamp, options) {\n        return mapAsyncGenerator(this._audioSampleSink.samples(startTimestamp, endTimestamp, options), data => this._audioSampleToWrappedArrayBuffer(data));\n    }\n    /**\n     * Creates an async iterator that yields an audio buffer for each timestamp in the argument. This method\n     * uses an optimized decoding pipeline if these timestamps are monotonically sorted, decoding each packet at most\n     * once, and is therefore more efficient than manually getting the buffer for every timestamp. The iterator may\n     * yield null if no buffer is available for a given timestamp.\n     *\n     * @param timestamps - An iterable or async iterable of timestamps in seconds.\n     * @param options - Options used for the underlying packet retrieval.\n     */\n    buffersAtTimestamps(timestamps, options) {\n        return mapAsyncGenerator(this._audioSampleSink.samplesAtTimestamps(timestamps, options), data => data && this._audioSampleToWrappedArrayBuffer(data));\n    }\n}\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { PCM_AUDIO_CODECS } from './codec.js';\nimport { determineVideoPacketType } from './codec-data.js';\nimport { customAudioDecoders, customVideoDecoders } from './custom-coder.js';\nimport { Logging } from './logging.js';\nimport { EncodedPacketSink } from './media-sink.js';\nimport { assert, extractRotationFromMatrix, isNumber, isThenable, matrixIsFlipped, roundToDivisor, simplifyRational, } from './misc.js';\nimport { EncodedPacket } from './packet.js';\n/**\n * Represents a media track in an input file.\n * @group Input files & tracks\n * @public\n */\nexport class InputTrack {\n    /** @internal */\n    constructor(input, backing) {\n        this.input = input;\n        this._backing = backing;\n    }\n    /** Returns true if and only if this track is a video track. */\n    isVideoTrack() {\n        return this instanceof InputVideoTrack;\n    }\n    /** Returns true if and only if this track is an audio track. */\n    isAudioTrack() {\n        return this instanceof InputAudioTrack;\n    }\n    /** The unique ID of this track in the input file. */\n    get id() {\n        return this._backing.getId();\n    }\n    /**\n     * The 1-based index of this track among all tracks of the same type in the input file. For example, the first\n     * video track has number 1, the second video track has number 2, and so on. The index refers to the order in\n     * which the tracks are returned by {@link Input.getTracks}.\n     */\n    get number() {\n        return this._backing.getNumber();\n    }\n    /**\n     * Returns the identifier of the codec used internally by the container. It is not homogenized by Mediabunny\n     * and depends entirely on the container format.\n     *\n     * This method can be used to determine the codec of a track in case Mediabunny doesn't know that codec.\n     *\n     * - For ISOBMFF files, this resolves to the name of the Sample Description Box (e.g. `'avc1'`).\n     * - For Matroska files, this resolves to the value of the `CodecID` element.\n     * - For WAVE files, this resolves to the value of the format tag in the `'fmt '` chunk.\n     * - For ADTS files, this resolves to the `MPEG-4 Audio Object Type`.\n     * - For MPEG-TS files, this resolves to the `streamType` value from the Program Map Table.\n     * - In all other cases, this resolves to `null`.\n     */\n    async getInternalCodecId() {\n        return this._backing.getInternalCodecId();\n    }\n    /**\n     * See {@link InputTrack.getInternalCodecId}.\n     * @deprecated Use {@link InputTrack.getInternalCodecId} instead.\n     */\n    get internalCodecId() {\n        return requireSync(this._backing.getInternalCodecId(), 'internalCodecId', 'getInternalCodecId');\n    }\n    /**\n     * Returns the ISO 639-2/T language code for this track. If the language is unknown, this resolves to `'und'`\n     * (undetermined).\n     */\n    async getLanguageCode() {\n        return this._backing.getLanguageCode();\n    }\n    /**\n     * The ISO 639-2/T language code for this track. If the language is unknown, this field is `'und'` (undetermined).\n     * @deprecated Use {@link InputTrack.getLanguageCode} instead.\n     */\n    get languageCode() {\n        return requireSync(this._backing.getLanguageCode(), 'languageCode', 'getLanguageCode');\n    }\n    /** Returns the user-defined name for this track. */\n    async getName() {\n        return this._backing.getName();\n    }\n    /**\n     * A user-defined name for this track.\n     * @deprecated Use {@link InputTrack.getName} instead.\n     */\n    get name() {\n        return requireSync(this._backing.getName(), 'name', 'getName');\n    }\n    /**\n     * Returns a positive number x such that all timestamps and durations of all packets of this track are\n     * integer multiples of 1/x.\n     */\n    async getTimeResolution() {\n        return this._backing.getTimeResolution();\n    }\n    /**\n     * A positive number x such that all timestamps and durations of all packets of this track are\n     * integer multiples of 1/x.\n     * @deprecated Use {@link InputTrack.getTimeResolution} instead.\n     */\n    get timeResolution() {\n        return requireSync(this._backing.getTimeResolution(), 'timeResolution', 'getTimeResolution');\n    }\n    /**\n     * Returns whether the timestamps of this track are relative to the Unix epoch (January 1, 1970 00:00:00 UTC).\n     * When `true`, each timestamp maps to a definitive point in time.\n     */\n    async isRelativeToUnixEpoch() {\n        return this._backing.isRelativeToUnixEpoch();\n    }\n    /**\n     * Returns the Unix time (in seconds since January 1, 1970 00:00:00 UTC) that the given track timestamp (in seconds)\n     * maps to, or `null` if there is no such mapping. This provides a piecewise-continuous mapping from this track's\n     * timestamp space into wall-clock time. Such mapping exists, for example, for HLS playlists with\n     * `#EXT-X-PROGRAM-DATE-TIME` tags present.\n     *\n     * This mapping can be available even when {@link InputTrack.isRelativeToUnixEpoch} is `false`, for example for HLS\n     * streams with program date time information but with {@link HlsInputFormatOptions.offsetTimestampsByDateTime}\n     * set to `false`.\n     */\n    async getUnixTimeForTimestamp(timestamp) {\n        return this._backing.getUnixTimeForTimestamp(timestamp);\n    }\n    /**\n     * Whether the track's timestamps can be mapped to Unix wall clock time via\n     * {@link InputTrack.getUnixTimeForTimestamp}.\n     */\n    async hasUnixTimeMapping() {\n        return (await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())) !== null;\n    }\n    /** Returns the track's disposition, i.e. information about its intended usage. */\n    async getDisposition() {\n        return this._backing.getDisposition();\n    }\n    /**\n     * The track's disposition, i.e. information about its intended usage.\n     * @deprecated Use {@link InputTrack.getDisposition} instead.\n     */\n    get disposition() {\n        return requireSync(this._backing.getDisposition(), 'disposition', 'getDisposition');\n    }\n    /**\n     * Returns the peak bitrate of the track in bits per second, as specified in the track's metadata. This might not\n     * match the actual media data's bitrate.\n     */\n    async getBitrate() {\n        return this._backing.getBitrate();\n    }\n    /**\n     * Returns the average bitrate of the track in bits per second, as specified in the track's metadata. This might\n     * not match the actual media data's bitrate.\n     */\n    async getAverageBitrate() {\n        return this._backing.getAverageBitrate();\n    }\n    /**\n     * Returns the start timestamp of the first packet of this track, in seconds. While often near zero, this value\n     * may be positive or even negative. A negative starting timestamp means the track's timing has been offset. Samples\n     * with a negative timestamp should not be presented.\n     */\n    async getFirstTimestamp() {\n        const firstPacket = await this._backing.getFirstPacket({ metadataOnly: true });\n        return firstPacket?.timestamp ?? 0;\n    }\n    /**\n     * Returns the end timestamp of the last packet of this track, in seconds.\n     *\n     * By default, when the underlying media is live, this method will only resolve once the live stream ends. If you\n     * want to query the current end timestamp of the stream, set {@link PacketRetrievalOptions.skipLiveWait} to `true`\n     * in the options.\n     */\n    async computeDuration(options) {\n        const lastPacket = await this._backing.getPacket(Infinity, { metadataOnly: true, ...options });\n        const result = (lastPacket?.timestamp ?? 0) + (lastPacket?.duration ?? 0);\n        return roundToDivisor(result, await this.getTimeResolution());\n    }\n    /**\n     * Gets the duration (end timestamp) in seconds of this track from metadata stored in the file. This value may be\n     * approximate or diverge from the actual, precise duration returned by `.computeDuration()`, but compared to that\n     * method, this method is cheaper. When the duration cannot be determined from the file metadata, `null`\n     * is returned.\n     *\n     * By default, when the underlying media is live, this method will only resolve once the live stream\n     * ends. If you want to query the current duration of the media, set\n     * {@link DurationMetadataRequestOptions.skipLiveWait} to `true` in the options.\n     */\n    async getDurationFromMetadata(options = {}) {\n        return this._backing.getDurationFromMetadata(options);\n    }\n    /**\n     * Computes aggregate packet statistics for this track, such as average packet rate or bitrate.\n     *\n     * @param targetPacketCount - This optional parameter sets a target for how many packets this method must have\n     * looked at before it can return early; this means, you can use it to aggregate only a subset (prefix) of all\n     * packets. This is very useful for getting a great estimate of video frame rate without having to scan through the\n     * entire file.\n     *\n     * By default, when the underlying media is live and `targetPacketCount` is not set, this method will only resolve\n     * once the live stream ends. If you want to query the current packet statistics of the stream, set\n     * {@link PacketRetrievalOptions.skipLiveWait} to `true` in the options.\n     */\n    async computePacketStats(targetPacketCount = Infinity, options) {\n        const sink = new EncodedPacketSink(this);\n        let startTimestamp = Infinity;\n        let endTimestamp = -Infinity;\n        let packetCount = 0;\n        let totalPacketBytes = 0;\n        for await (const packet of sink.packets(undefined, undefined, { metadataOnly: true, ...options })) {\n            if (packetCount >= targetPacketCount\n                // This additional condition is needed to produce correct results with out-of-presentation-order packets\n                && packet.timestamp >= endTimestamp) {\n                break;\n            }\n            startTimestamp = Math.min(startTimestamp, packet.timestamp);\n            endTimestamp = Math.max(endTimestamp, packet.timestamp + packet.duration);\n            packetCount++;\n            totalPacketBytes += packet.byteLength;\n        }\n        return {\n            packetCount,\n            averagePacketRate: packetCount\n                ? Number((packetCount / (endTimestamp - startTimestamp)).toPrecision(16))\n                : 0,\n            averageBitrate: packetCount\n                ? Number((8 * totalPacketBytes / (endTimestamp - startTimestamp)).toPrecision(16))\n                : 0,\n        };\n    }\n    /**\n     * Whether or not this track is currently live, meaning the media's end is still unknown.\n     *\n     * The value returned by this method may change over time as the track stops being live. To keep track of the\n     * track's live status, poll this method at the track's refresh interval\n     * via {@link InputTrack.getLiveRefreshInterval}.\n     */\n    async isLive() {\n        return (await this._backing.getLiveRefreshInterval()) !== null;\n    }\n    /**\n     * Returns the track's live refresh interval in seconds, or `null` if the track is not live. This interval describes\n     * the time it takes, on average, for new live media data to become available.\n     */\n    async getLiveRefreshInterval() {\n        return this._backing.getLiveRefreshInterval();\n    }\n    /**\n     * Returns `true` if this track can be paired with the given track. Two tracks being pairable means they can be\n     * presented (displayed) together.\n     *\n     * Returns `false` if `other` equals `this`.\n     */\n    canBePairedWith(other) {\n        if (!(other instanceof InputTrack)) {\n            throw new TypeError('other must be an InputTrack.');\n        }\n        if (this.input !== other.input || this === other) {\n            return false;\n        }\n        return (this._backing.getPairingMask() & other._backing.getPairingMask()) !== 0n;\n    }\n    /**\n     * Gets the list of other tracks that can be paired with this track. An optional query can be provided to narrow\n     * down the results.\n     */\n    async getPairableTracks(query) {\n        return this.input.getTracks(mergeInputTrackQueries({\n            filter: t => t.canBePairedWith(this),\n        }, query));\n    }\n    /**\n     * Gets the list of other video tracks that can be paired with this track. An optional query can be provided to\n     * narrow down the results.\n     */\n    async getPairableVideoTracks(query) {\n        return this.input.getVideoTracks(mergeInputTrackQueries({\n            filter: t => t.canBePairedWith(this),\n        }, query));\n    }\n    /**\n     * Gets the list of other audio tracks that can be paired with this track. An optional query can be provided to\n     * narrow down the results.\n     */\n    async getPairableAudioTracks(query) {\n        return this.input.getAudioTracks(mergeInputTrackQueries({\n            filter: t => t.canBePairedWith(this),\n        }, query));\n    }\n    /** Returns the primary track that can be paired with this track, optionally steered by the provided query. */\n    async getPrimaryPairableVideoTrack(query) {\n        return this.input.getPrimaryVideoTrack(mergeInputTrackQueries({\n            filter: t => t.canBePairedWith(this),\n        }, query));\n    }\n    /** Returns the primary track that can be paired with this track, optionally steered by the provided query. */\n    async getPrimaryPairableAudioTrack(query) {\n        return this.input.getPrimaryAudioTrack(mergeInputTrackQueries({\n            filter: t => t.canBePairedWith(this),\n        }, query));\n    }\n    /** Returns `true` if there is another track that can be paired with this track. */\n    async hasPairableTrack(predicate) {\n        predicate &&= toValidatedPredicate(predicate);\n        const tracks = await this.input.getTracks();\n        for (const track of tracks) {\n            if (!this.canBePairedWith(track)) {\n                continue;\n            }\n            if (!predicate || await predicate(track)) {\n                return true;\n            }\n        }\n        return false;\n    }\n    /** Returns `true` if there is a video track that can be paired with this track. */\n    hasPairableVideoTrack(predicate) {\n        predicate &&= toValidatedPredicate(predicate);\n        return this.hasPairableTrack(async (x) => x.isVideoTrack() && (!predicate || await predicate(x)));\n    }\n    /** Returns `true` if there is an audio track that can be paired with this track. */\n    hasPairableAudioTrack(predicate) {\n        predicate &&= toValidatedPredicate(predicate);\n        return this.hasPairableTrack(async (x) => x.isAudioTrack() && (!predicate || await predicate(x)));\n    }\n}\nconst requireSync = (value, getterName, asyncName) => {\n    if (isThenable(value)) {\n        throw new Error(`'${getterName}' is deprecated and not available synchronously for this track. Use the preferred`\n            + ` '${asyncName}()' instead.`);\n    }\n    return value;\n};\nconst toValidatedPredicate = (predicate) => {\n    if (predicate !== undefined && typeof predicate !== 'function') {\n        throw new TypeError('predicate, when provided, must be a function.');\n    }\n    return predicate\n        ? (track) => {\n            const handle = (result) => {\n                if (typeof result !== 'boolean') {\n                    throw new TypeError('predicate must return or resolve to a boolean value.');\n                }\n                return result;\n            };\n            const result = predicate(track);\n            if (isThenable(result)) {\n                return result.then(handle);\n            }\n            return handle(result);\n        }\n        : undefined;\n};\n/**\n * Represents a video track in an input file.\n * @group Input files & tracks\n * @public\n */\nexport class InputVideoTrack extends InputTrack {\n    /** @internal */\n    constructor(input, backing) {\n        super(input, backing);\n        /** @internal */\n        this._pixelAspectRatioCache = null;\n    }\n    get type() {\n        return 'video';\n    }\n    /** The codec of the track's packets. */\n    async getCodec() {\n        return this._backing.getCodec();\n    }\n    /**\n     * The codec of the track's packets.\n     * @deprecated Use {@link InputVideoTrack.getCodec} instead.\n     */\n    get codec() {\n        return requireSync(this._backing.getCodec(), 'codec', 'getCodec');\n    }\n    async hasOnlyKeyPackets() {\n        return (await this._backing.getHasOnlyKeyPackets?.())\n            ?? (await this._backing.getCodec() === 'prores'); // Only ProRes is fully intra-frame\n    }\n    /** Returns the width in pixels of the track's coded samples, before any transformations or rotations. */\n    async getCodedWidth() {\n        return this._backing.getCodedWidth();\n    }\n    /**\n     * The width in pixels of the track's coded samples, before any transformations or rotations.\n     * @deprecated Use {@link InputVideoTrack.getCodedWidth} instead.\n     */\n    get codedWidth() {\n        return requireSync(this._backing.getCodedWidth(), 'codedWidth', 'getCodedWidth');\n    }\n    /** Returns the height in pixels of the track's coded samples, before any transformations or rotations. */\n    async getCodedHeight() {\n        return this._backing.getCodedHeight();\n    }\n    /**\n     * The height in pixels of the track's coded samples, before any transformations or rotations.\n     * @deprecated Use {@link InputVideoTrack.getCodedHeight} instead.\n     */\n    get codedHeight() {\n        return requireSync(this._backing.getCodedHeight(), 'codedHeight', 'getCodedHeight');\n    }\n    /**\n     * Returns the row-major 3x3 affine transformation matrix that is used to transform the raw video frames before they\n     * are displayed. The raw frames are assumed to be placed with their top-left corner at the origin (0,0).\n     *\n     * Usually, this matrix models a rotation and a flip. Depending on the file, it may also contain a translation\n     * component. When displaying video, you should typically ignore the translation component and display the center of\n     * the transformed frame in the center of the viewport.\n     */\n    async getTransformationMatrix() {\n        return this._backing.getTransformationMatrix();\n    }\n    /**\n     * Returns the angle in degrees by which the track's frames should be rotated (clockwise). The rotation is\n     * applied before flipping.\n     */\n    async getRotation() {\n        return extractRotationFromMatrix(await this._backing.getTransformationMatrix());\n    }\n    /**\n     * The angle in degrees by which the track's frames should be rotated (clockwise).\n     * @deprecated Use {@link InputVideoTrack.getRotation} instead.\n     */\n    get rotation() {\n        return extractRotationFromMatrix(requireSync(this._backing.getTransformationMatrix(), 'rotation', 'getRotation'));\n    }\n    /**\n     * Returns whether the track's frames should be flipped horizontally (about the vertical axis), after rotation.\n     */\n    async getFlip() {\n        return matrixIsFlipped(await this._backing.getTransformationMatrix());\n    }\n    /**\n     * Returns the width of the track's frames in square pixels, adjusted for pixel aspect ratio but before rotation.\n     */\n    async getSquarePixelWidth() {\n        return this._backing.getSquarePixelWidth();\n    }\n    /**\n     * The width of the track's frames in square pixels, adjusted for pixel aspect ratio but before rotation.\n     * @deprecated Use {@link InputVideoTrack.getSquarePixelWidth} instead.\n     */\n    get squarePixelWidth() {\n        return requireSync(this._backing.getSquarePixelWidth(), 'squarePixelWidth', 'getSquarePixelWidth');\n    }\n    /**\n     * Returns the height of the track's frames in square pixels, adjusted for pixel aspect ratio but before rotation.\n     */\n    async getSquarePixelHeight() {\n        return this._backing.getSquarePixelHeight();\n    }\n    /**\n     * The height of the track's frames in square pixels, adjusted for pixel aspect ratio but before rotation.\n     * @deprecated Use {@link InputVideoTrack.getSquarePixelHeight} instead.\n     */\n    get squarePixelHeight() {\n        return requireSync(this._backing.getSquarePixelHeight(), 'squarePixelHeight', 'getSquarePixelHeight');\n    }\n    /**\n     * Returns the pixel aspect ratio of the track's frames as a rational number in its reduced form. Most videos use\n     * square pixels (1:1).\n     */\n    async getPixelAspectRatio() {\n        // Potential minor async race condition here if called twice, but doesn't matter since the computation is\n        // so cheap\n        return this._pixelAspectRatioCache ??= toPixelAspectRatio((await this.getSquarePixelWidth()) * (await this.getCodedHeight()), (await this.getSquarePixelHeight()) * (await this.getCodedWidth()));\n    }\n    /**\n     * The pixel aspect ratio of the track's frames, as a rational number in its reduced form. Most videos use\n     * square pixels (1:1).\n     * @deprecated Use {@link InputVideoTrack.getPixelAspectRatio} instead.\n     */\n    get pixelAspectRatio() {\n        return this._pixelAspectRatioCache ??= toPixelAspectRatio(requireSync(this._backing.getSquarePixelWidth(), 'pixelAspectRatio', 'getPixelAspectRatio')\n            * requireSync(this._backing.getCodedHeight(), 'pixelAspectRatio', 'getPixelAspectRatio'), requireSync(this._backing.getSquarePixelHeight(), 'pixelAspectRatio', 'getPixelAspectRatio')\n            * requireSync(this._backing.getCodedWidth(), 'pixelAspectRatio', 'getPixelAspectRatio'));\n    }\n    /** Returns the display width of the track's frames in pixels, after aspect ratio adjustment and rotation. */\n    async getDisplayWidth() {\n        const metadata = await this._backing.getMetadataDisplayWidth?.();\n        if (metadata != null) {\n            return metadata;\n        }\n        const rotation = await this.getRotation();\n        return rotation % 180 === 0 ? this.getSquarePixelWidth() : this.getSquarePixelHeight();\n    }\n    /**\n     * The display width of the track's frames in pixels, after aspect ratio adjustment and rotation.\n     * @deprecated Use {@link InputVideoTrack.getDisplayWidth} instead.\n     */\n    get displayWidth() {\n        const metadataRaw = this._backing.getMetadataDisplayWidth?.();\n        if (metadataRaw !== undefined) {\n            const metadata = requireSync(metadataRaw, 'displayWidth', 'getDisplayWidth');\n            if (metadata !== null) {\n                return metadata;\n            }\n        }\n        const rotation = extractRotationFromMatrix(requireSync(this._backing.getTransformationMatrix(), 'displayWidth', 'getDisplayWidth'));\n        const value = rotation % 180 === 0\n            ? this._backing.getSquarePixelWidth()\n            : this._backing.getSquarePixelHeight();\n        return requireSync(value, 'displayWidth', 'getDisplayWidth');\n    }\n    /** Returns the display height of the track's frames in pixels, after aspect ratio adjustment and rotation. */\n    async getDisplayHeight() {\n        const metadata = await this._backing.getMetadataDisplayHeight?.();\n        if (metadata != null) {\n            return metadata;\n        }\n        const rotation = await this.getRotation();\n        return rotation % 180 === 0 ? this.getSquarePixelHeight() : this.getSquarePixelWidth();\n    }\n    /**\n     * The display height of the track's frames in pixels, after aspect ratio adjustment and rotation.\n     * @deprecated Use {@link InputVideoTrack.getDisplayHeight} instead.\n     */\n    get displayHeight() {\n        const metadataRaw = this._backing.getMetadataDisplayHeight?.();\n        if (metadataRaw !== undefined) {\n            const metadata = requireSync(metadataRaw, 'displayHeight', 'getDisplayHeight');\n            if (metadata !== null) {\n                return metadata;\n            }\n        }\n        const rotation = extractRotationFromMatrix(requireSync(this._backing.getTransformationMatrix(), 'displayHeight', 'getDisplayHeight'));\n        const value = rotation % 180 === 0\n            ? this._backing.getSquarePixelHeight()\n            : this._backing.getSquarePixelWidth();\n        return requireSync(value, 'displayHeight', 'getDisplayHeight');\n    }\n    /** Returns the color space of the track's samples. */\n    async getColorSpace() {\n        return this._backing.getColorSpace();\n    }\n    /** If this method returns true, the track's samples use a high dynamic range (HDR). */\n    async hasHighDynamicRange() {\n        const colorSpace = await this._backing.getColorSpace();\n        return colorSpace.primaries === 'bt2020' || colorSpace.primaries === 'smpte432'\n            || colorSpace.transfer === 'pq' || colorSpace.transfer === 'hlg'\n            || colorSpace.matrix === 'bt2020-ncl';\n    }\n    /** Checks if this track may contain transparent samples with alpha data. */\n    async canBeTransparent() {\n        return this._backing.canBeTransparent();\n    }\n    /**\n     * Returns the [decoder configuration](https://www.w3.org/TR/webcodecs/#video-decoder-config) for decoding the\n     * track's packets using a [`VideoDecoder`](https://developer.mozilla.org/en-US/docs/Web/API/VideoDecoder). Returns\n     * null if the track's codec is unknown.\n     */\n    async getDecoderConfig() {\n        return this._backing.getDecoderConfig();\n    }\n    async getCodecParameterString() {\n        const fromMetadata = await this._backing.getMetadataCodecParameterString?.();\n        if (fromMetadata != null) {\n            return fromMetadata;\n        }\n        const decoderConfig = await this._backing.getDecoderConfig();\n        return decoderConfig?.codec ?? null;\n    }\n    async canDecode() {\n        try {\n            const decoderConfig = await this._backing.getDecoderConfig();\n            if (!decoderConfig) {\n                return false;\n            }\n            const codec = await this._backing.getCodec();\n            assert(codec !== null);\n            if (customVideoDecoders.some(x => x.supports(codec, decoderConfig))) {\n                return true;\n            }\n            if (typeof VideoDecoder === 'undefined') {\n                return false;\n            }\n            const support = await VideoDecoder.isConfigSupported(decoderConfig);\n            return support.supported === true;\n        }\n        catch (error) {\n            Logging._error('Error during decodability check:', error);\n            return false;\n        }\n    }\n    async determinePacketType(packet) {\n        if (!(packet instanceof EncodedPacket)) {\n            throw new TypeError('packet must be an EncodedPacket.');\n        }\n        if (packet.isMetadataOnly) {\n            throw new TypeError('packet must not be metadata-only to determine its type.');\n        }\n        const codec = await this.getCodec();\n        if (codec === null) {\n            return null;\n        }\n        const decoderConfig = await this.getDecoderConfig();\n        assert(decoderConfig);\n        return determineVideoPacketType(codec, decoderConfig, packet.data);\n    }\n    /**\n     * Computes frame rate metrics for this video track, i.e. estimates the video's frame rate. Frame rate is never\n     * determined from file metadata (which is unreliable) but is always deduced directly from the actual frame\n     * timestamps.\n     */\n    async computeFrameRateMetrics(options = {}) {\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.targetPacketCount !== undefined\n            && (!isNumber(options.targetPacketCount) || options.targetPacketCount < 0)) {\n            throw new TypeError('options.targetPacketCount must be a non-negative number.');\n        }\n        const timeResolution = await this.getTimeResolution();\n        const targetPacketCount = options.targetPacketCount ?? 256;\n        const sink = new EncodedPacketSink(this);\n        const timestamps = [];\n        let maxTimestamp = -Infinity;\n        let probedPacketCount = 0;\n        for await (const packet of sink.packets(undefined, undefined, { metadataOnly: true })) {\n            if (timestamps.length >= targetPacketCount\n                // Needed for out-of-presentation-order packets.\n                && packet.timestamp >= maxTimestamp) {\n                break;\n            }\n            timestamps.push(packet.timestamp);\n            maxTimestamp = Math.max(maxTimestamp, packet.timestamp);\n            probedPacketCount++;\n        }\n        const ticks = new Float64Array(timestamps.length);\n        for (let i = 0; i < timestamps.length; i++) {\n            ticks[i] = Math.round(timestamps[i] * timeResolution);\n        }\n        ticks.sort();\n        // Deduplicate in-place; only ticks[0..n) remains active.\n        let n = 1;\n        for (let i = 1; i < ticks.length; i++) {\n            if (ticks[i] !== ticks[n - 1]) {\n                ticks[n++] = ticks[i];\n            }\n        }\n        if (n < 2) {\n            return {\n                underlyingFrameRate: null,\n                bestGuessFrameRate: timeResolution,\n                minFrameRate: timeResolution,\n                maxFrameRate: timeResolution,\n                averageFrameRate: timeResolution,\n                medianFrameRate: timeResolution,\n                frameRateIsConstant: true,\n                probedPacketCount,\n            };\n        }\n        const activeTicks = ticks.subarray(0, n);\n        const underlyingFrameRate = findUnderlyingFrameRate(activeTicks, timeResolution);\n        // If an underlying frame rate exists, differences are expressed in inferred frame intervals. Otherwise they\n        // remain raw timestamp ticks.\n        const unitRate = underlyingFrameRate ?? timeResolution;\n        const ticksPerFrame = underlyingFrameRate !== null\n            ? timeResolution / underlyingFrameRate\n            : null;\n        const histogram = new Map();\n        let minDifference = Infinity;\n        let maxDifference = -Infinity;\n        let totalDifference = 0;\n        for (let i = 1; i < n; i++) {\n            const tickDifference = activeTicks[i] - activeTicks[i - 1];\n            const difference = ticksPerFrame !== null\n                ? Math.max(1, Math.round(tickDifference / ticksPerFrame))\n                : tickDifference;\n            histogram.set(difference, (histogram.get(difference) ?? 0) + 1);\n            minDifference = Math.min(minDifference, difference);\n            maxDifference = Math.max(maxDifference, difference);\n            totalDifference += difference;\n        }\n        const differenceCount = n - 1;\n        // Get the two middle differences so the even-sized case has a true median.\n        const sortedDifferences = [...histogram.keys()].sort((a, b) => a - b);\n        const middleA = (differenceCount - 1) >> 1;\n        const middleB = differenceCount >> 1;\n        let medianDifferenceA = 0;\n        let medianDifferenceB = 0;\n        let cumulativeCount = 0;\n        for (const difference of sortedDifferences) {\n            cumulativeCount += histogram.get(difference);\n            if (medianDifferenceA === 0 && cumulativeCount > middleA) {\n                medianDifferenceA = difference;\n            }\n            if (cumulativeCount > middleB) {\n                medianDifferenceB = difference;\n                break;\n            }\n        }\n        // Median is defined over instantaneous frame rates, not durations.\n        const medianFrameRate = (unitRate / medianDifferenceA\n            + unitRate / medianDifferenceB) / 2;\n        return {\n            underlyingFrameRate,\n            bestGuessFrameRate: underlyingFrameRate !== null\n                ? underlyingFrameRate\n                : getBestGuessFrameRate(medianFrameRate),\n            minFrameRate: unitRate / maxDifference,\n            maxFrameRate: unitRate / minDifference,\n            averageFrameRate: unitRate * differenceCount / totalDifference,\n            medianFrameRate,\n            frameRateIsConstant: underlyingFrameRate !== null\n                && minDifference === 1\n                && maxDifference === 1,\n            probedPacketCount,\n        };\n    }\n}\nconst toPixelAspectRatio = (num, den) => {\n    if (num === 0 || den === 0) {\n        // Can kick if dimensions are zero, so just return square pixels\n        return { num: 1, den: 1 };\n    }\n    return simplifyRational({ num, den });\n};\n/**\n * Represents an audio track in an input file.\n * @group Input files & tracks\n * @public\n */\nexport class InputAudioTrack extends InputTrack {\n    /** @internal */\n    constructor(input, backing) {\n        super(input, backing);\n    }\n    get type() {\n        return 'audio';\n    }\n    /** The codec of the track's packets. */\n    async getCodec() {\n        return this._backing.getCodec();\n    }\n    /**\n     * The codec of the track's packets.\n     * @deprecated Use {@link InputAudioTrack.getCodec} instead.\n     */\n    get codec() {\n        return requireSync(this._backing.getCodec(), 'codec', 'getCodec');\n    }\n    async hasOnlyKeyPackets() {\n        return (await this._backing.getHasOnlyKeyPackets?.()) ?? true;\n    }\n    /** Returns the number of audio channels in the track. */\n    async getNumberOfChannels() {\n        return this._backing.getNumberOfChannels();\n    }\n    /**\n     * The number of audio channels in the track.\n     * @deprecated Use {@link InputAudioTrack.getNumberOfChannels} instead.\n     */\n    get numberOfChannels() {\n        return requireSync(this._backing.getNumberOfChannels(), 'numberOfChannels', 'getNumberOfChannels');\n    }\n    /** Returns the track's audio sample rate in hertz. */\n    async getSampleRate() {\n        return this._backing.getSampleRate();\n    }\n    /**\n     * The track's audio sample rate in hertz.\n     * @deprecated Use {@link InputAudioTrack.getSampleRate} instead.\n     */\n    get sampleRate() {\n        return requireSync(this._backing.getSampleRate(), 'sampleRate', 'getSampleRate');\n    }\n    /**\n     * Returns the [decoder configuration](https://www.w3.org/TR/webcodecs/#audio-decoder-config) for decoding the\n     * track's packets using an [`AudioDecoder`](https://developer.mozilla.org/en-US/docs/Web/API/AudioDecoder). Returns\n     * null if the track's codec is unknown.\n     */\n    async getDecoderConfig() {\n        return this._backing.getDecoderConfig();\n    }\n    async getCodecParameterString() {\n        const fromMetadata = await this._backing.getMetadataCodecParameterString?.();\n        if (fromMetadata != null) {\n            return fromMetadata;\n        }\n        const decoderConfig = await this._backing.getDecoderConfig();\n        return decoderConfig?.codec ?? null;\n    }\n    async canDecode() {\n        try {\n            const decoderConfig = await this._backing.getDecoderConfig();\n            if (!decoderConfig) {\n                return false;\n            }\n            const codec = await this._backing.getCodec();\n            assert(codec !== null);\n            if (customAudioDecoders.some(x => x.supports(codec, decoderConfig))) {\n                return true;\n            }\n            if (PCM_AUDIO_CODECS.includes(decoderConfig.codec)) {\n                return true; // Since we decode it ourselves\n            }\n            else {\n                if (typeof AudioDecoder === 'undefined') {\n                    return false;\n                }\n                const support = await AudioDecoder.isConfigSupported(decoderConfig);\n                return support.supported === true;\n            }\n        }\n        catch (error) {\n            Logging._error('Error during decodability check:', error);\n            return false;\n        }\n    }\n    async determinePacketType(packet) {\n        if (!(packet instanceof EncodedPacket)) {\n            throw new TypeError('packet must be an EncodedPacket.');\n        }\n        if ((await this.getCodec()) === null) {\n            return null;\n        }\n        return 'key'; // No audio codec with delta packets\n    }\n}\n/**\n * Helper function for use in {@link InputTrackQuery.sortBy}, used to describe sorting tracks by a numeric property in\n * ascending order. `null` and `undefined` are accepted too and are last in the order (sorted to the end).\n *\n * @group Input files & tracks\n * @public\n */\nexport const asc = (value) => {\n    return value ?? Infinity; // nulls and undefined last\n};\n/**\n * Helper function for use in {@link InputTrackQuery.sortBy}, used to describe sorting tracks by a numeric property in\n * descending order. `null` and `undefined` are accepted too and are last in the order (sorted to the end).\n *\n * @group Input files & tracks\n * @public\n */\nexport const desc = (value) => {\n    return -(value ?? -Infinity); // nulls and undefined last\n};\n/**\n * Helper function for use in {@link InputTrackQuery.sortBy}, used to sort tracks by boolean properties. `true` is\n * sorted to the start, `false` to the end. Useful for expressing soft preferences (e.g., \"I'd prefer 1080p, but other\n * resolutions are fine too\") as opposed to {@link InputTrackQuery.filter} which expresses hard requirements for\n * tracks.\n *\n * @group Input files & tracks\n * @public\n */\nexport const prefer = (value) => {\n    return -value;\n};\nexport const toValidatedInputTrackQuery = (query) => {\n    if (typeof query !== 'object' || !query) {\n        throw new TypeError('query must be an object.');\n    }\n    if (query.filter !== undefined && typeof query.filter !== 'function') {\n        throw new TypeError('query.filter, when provided, must be a function.');\n    }\n    if (query.sortBy !== undefined && typeof query.sortBy !== 'function') {\n        throw new TypeError('query.sortBy, when provided, must be a function.');\n    }\n    // Instead of validating the return types of the functions everywhere the query is used, simply return a new query\n    // which wraps the old one while validating it.\n    return {\n        filter: query.filter\n            ? (track) => {\n                const handle = (bool) => {\n                    if (typeof bool !== 'boolean') {\n                        throw new TypeError('query.filter must return or resolve to a boolean.');\n                    }\n                    return bool;\n                };\n                const result = query.filter(track);\n                if (isThenable(result)) {\n                    return result.then(handle);\n                }\n                else {\n                    return handle(result);\n                }\n            }\n            : undefined,\n        sortBy: query.sortBy\n            ? (track) => {\n                const handle = (value) => {\n                    if (typeof value !== 'number'\n                        && (!Array.isArray(value) || !value.every(x => typeof x === 'number'))) {\n                        throw new TypeError('query.sortBy must return or resolve to a number or an array of numbers.');\n                    }\n                    return value;\n                };\n                const result = query.sortBy(track);\n                if (isThenable(result)) {\n                    return result.then(handle);\n                }\n                else {\n                    return handle(result);\n                }\n            }\n            : undefined,\n    };\n};\nexport const mergeInputTrackQueries = (queryA, queryB) => {\n    return {\n        filter: queryA?.filter || queryB?.filter\n            ? (track) => {\n                const resultA = queryA?.filter?.(track) ?? true;\n                const handleResultA = (resultA) => {\n                    if (resultA === false) {\n                        return false;\n                    }\n                    return queryB?.filter?.(track) ?? true;\n                };\n                if (isThenable(resultA)) {\n                    return resultA.then(handleResultA);\n                }\n                else {\n                    return handleResultA(resultA);\n                }\n            }\n            : undefined,\n        sortBy: queryA?.sortBy || queryB?.sortBy\n            ? (track) => {\n                const resultA = queryA?.sortBy?.(track) ?? [];\n                const resultB = queryB?.sortBy?.(track) ?? [];\n                const join = (resultA, resultB) => {\n                    return [\n                        ...(Array.isArray(resultA) ? resultA : [resultA]),\n                        ...(Array.isArray(resultB) ? resultB : [resultB]),\n                    ];\n                };\n                if (isThenable(resultA) || isThenable(resultB)) {\n                    return Promise.all([resultA, resultB]).then(([resultA, resultB]) => {\n                        return join(resultA, resultB);\n                    });\n                }\n                else {\n                    return join(resultA, resultB);\n                }\n            }\n            : undefined,\n    };\n};\nexport const queryInputTracks = async (tracks, query) => {\n    let matched = tracks;\n    if (query?.filter) {\n        const filterMatches = tracks.map(t => query.filter(t));\n        const hasAsyncFilter = filterMatches.some(x => isThenable(x));\n        if (hasAsyncFilter) {\n            // eslint-disable-next-line @typescript-eslint/await-thenable\n            const resolvedFilterMatches = await Promise.all(filterMatches);\n            matched = tracks.filter((_, i) => resolvedFilterMatches[i]);\n        }\n        else {\n            matched = tracks.filter((_, i) => filterMatches[i]);\n        }\n    }\n    if (!query?.sortBy) {\n        return matched;\n    }\n    const sortValues = matched.map(t => query.sortBy(t));\n    const hasAsyncSort = sortValues.some(x => isThenable(x));\n    const resolvedSortValues = hasAsyncSort\n        // eslint-disable-next-line @typescript-eslint/await-thenable\n        ? await Promise.all(sortValues)\n        : sortValues;\n    return matched\n        .map((track, i) => ({ track, sortValue: resolvedSortValues[i] }))\n        .sort((a, b) => {\n        const aValues = Array.isArray(a.sortValue) ? a.sortValue : [a.sortValue];\n        const bValues = Array.isArray(b.sortValue) ? b.sortValue : [b.sortValue];\n        const maxLength = Math.max(aValues.length, bValues.length);\n        for (let i = 0; i < maxLength; i++) {\n            const aValue = aValues[i] ?? 0;\n            const bValue = bValues[i] ?? 0;\n            if (aValue === bValue) {\n                continue;\n            }\n            return aValue - bValue;\n        }\n        return 0;\n    })\n        .map(x => x.track);\n};\n/**\n * Estimates the underlying CFR-like frame rate from timestamp deltas.\n *\n * Each delta is modeled as an integer multiple of one frame period, allowing dropped frames and a small number of\n * malformed timestamps.\n */\nexport const findUnderlyingFrameRate = (ticks, resolution) => {\n    const MAX_DENOMINATOR = 1_000_000;\n    const MIN_INLIER_RATIO = 0.98;\n    const DELTA_TOLERANCE = 1 + 1e-9;\n    const MAX_EFFECTIVE_FRAME_SPAN = 1000;\n    const KNOWN_FRAME_RATES = [\n        12,\n        15,\n        20,\n        24000 / 1001,\n        24,\n        25,\n        30000 / 1001,\n        30,\n        48,\n        50,\n        60000 / 1001,\n        60,\n        100,\n        120000 / 1001,\n        120,\n        144,\n        240,\n    ];\n    if (ticks.length < 2) {\n        return null;\n    }\n    const gaps = new Float64Array(ticks.length - 1);\n    for (let i = 1; i < ticks.length; i++) {\n        const gap = ticks[i] - ticks[i - 1];\n        if (!(gap > 0)) {\n            return null;\n        }\n        gaps[i - 1] = gap;\n    }\n    // Start near the low end so dropped frames don't inflate the estimate, without letting one anomalously short gap\n    // determine it.\n    const sortedGaps = gaps.slice();\n    sortedGaps.sort();\n    let period = sortedGaps[Math.floor(sortedGaps.length * 0.05)];\n    // Repeatedly infer how many frame periods each gap spans and refine the underlying period from the locally\n    // consistent gaps.\n    for (let iteration = 0; iteration < 6; iteration++) {\n        let totalTicks = 0;\n        let totalFrames = 0;\n        for (const gap of gaps) {\n            const multiple = Math.max(1, Math.round(gap / period));\n            if (Math.abs(gap - multiple * period) >= DELTA_TOLERANCE) {\n                continue;\n            }\n            totalTicks += gap;\n            totalFrames += multiple;\n        }\n        if (totalFrames === 0) {\n            return null;\n        }\n        const refinedPeriod = totalTicks / totalFrames;\n        if (Math.abs(refinedPeriod - period)\n            <= 1e-12 * Math.max(1, period)) {\n            period = refinedPeriod;\n            break;\n        }\n        period = refinedPeriod;\n    }\n    let inlierCount = 0;\n    let totalTicks = 0;\n    let totalFrames = 0;\n    for (const gap of gaps) {\n        const multiple = Math.max(1, Math.round(gap / period));\n        if (Math.abs(gap - multiple * period) >= DELTA_TOLERANCE) {\n            continue;\n        }\n        inlierCount++;\n        totalTicks += gap;\n        totalFrames += multiple;\n    }\n    if (inlierCount / gaps.length < MIN_INLIER_RATIO) {\n        return null;\n    }\n    period = totalTicks / totalFrames;\n    // Don't let arbitrarily long files force arbitrarily precise rational reconstruction from microscopic clock drift.\n    const uncertainty = 1 / Math.min(totalFrames, MAX_EFFECTIVE_FRAME_SPAN);\n    const periodLo = Math.max(Number.EPSILON, period - uncertainty);\n    const periodHi = period + uncertainty;\n    const fpsLo = resolution / periodHi;\n    const fpsHi = resolution / periodLo;\n    const fittedFps = resolution / period;\n    // Prefer established frame rates when they're supported by the measured interval. If several fit, use the one\n    // closest to the measured cadence.\n    let fps = null;\n    let bestKnownError = Infinity;\n    for (const candidate of KNOWN_FRAME_RATES) {\n        if (candidate < fpsLo || candidate > fpsHi) {\n            continue;\n        }\n        const error = Math.abs(candidate / fittedFps - 1);\n        if (error < bestKnownError) {\n            fps = candidate;\n            bestKnownError = error;\n        }\n    }\n    if (fps === null) {\n        // Otherwise, the natural fraction may be simpler either as FPS or as ticks/frame.\n        const periodFraction = simplestFractionBetween(periodLo, periodHi, MAX_DENOMINATOR);\n        const fpsFraction = simplestFractionBetween(fpsLo, fpsHi, MAX_DENOMINATOR);\n        if (fpsFraction\n            && (!periodFraction\n                || fpsFraction.den < periodFraction.den\n                || (fpsFraction.den === periodFraction.den\n                    && fpsFraction.num <= periodFraction.num))) {\n            fps = fpsFraction.num / fpsFraction.den;\n        }\n        else if (periodFraction) {\n            fps = resolution * periodFraction.den / periodFraction.num;\n        }\n        else {\n            return null;\n        }\n    }\n    // Make sure the chosen rate still explains the deltas.\n    const finalPeriod = resolution / fps;\n    let finalInlierCount = 0;\n    for (const gap of gaps) {\n        const multiple = Math.max(1, Math.round(gap / finalPeriod));\n        if (Math.abs(gap - multiple * finalPeriod)\n            < DELTA_TOLERANCE) {\n            finalInlierCount++;\n        }\n    }\n    if (finalInlierCount / gaps.length < MIN_INLIER_RATIO) {\n        return null;\n    }\n    return fps;\n};\nconst simplestFractionBetween = (lo, hi, maxDenominator) => {\n    for (let den = 1; den <= maxDenominator; den++) {\n        const num = Math.floor(lo * den) + 1;\n        if (num / den < hi) {\n            return simplifyRational({ num, den });\n        }\n    }\n    return null;\n};\nconst getBestGuessFrameRate = (frameRate) => {\n    const SPECIAL_FRAME_RATES = [\n        24 / 1.001,\n        30 / 1.001,\n        60 / 1.001,\n        120 / 1.001,\n    ];\n    const COMMON_FRAME_RATES = [\n        12,\n        15,\n        20,\n        24,\n        25,\n        30,\n        48,\n        50,\n        60,\n        100,\n        120,\n        144,\n        240,\n    ];\n    const SPECIAL_TOLERANCE = 0.0005;\n    const COMMON_TOLERANCE = 0.025;\n    for (const candidate of SPECIAL_FRAME_RATES) {\n        if (Math.abs(candidate / frameRate - 1) <= SPECIAL_TOLERANCE) {\n            return candidate;\n        }\n    }\n    let best = frameRate;\n    let bestError = Infinity;\n    for (const candidate of COMMON_FRAME_RATES) {\n        const error = Math.abs(candidate / frameRate - 1);\n        if (error <= COMMON_TOLERANCE && error < bestError) {\n            best = candidate;\n            bestError = error;\n        }\n    }\n    return best;\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { InputFormat, validateInputFormatOptions } from './input-format.js';\nimport { InputAudioTrack, InputVideoTrack, mergeInputTrackQueries, queryInputTracks, toValidatedInputTrackQuery, prefer, desc, } from './input-track.js';\nimport { arrayArgmin, arrayCount, assert, EventEmitter, polyfillSymbolDispose, removeItem, } from './misc.js';\nimport { Reader } from './reader.js';\nimport { PathedSource, Source, SourceRef, sourceRequestsAreEqual, } from './source.js';\npolyfillSymbolDispose();\nexport const DEFAULT_SOURCE_CACHE_GROUP = 1;\nexport const ENCRYPTION_KEY_CACHE_GROUP = 2;\n/**\n * Represents input media, backed by a single file or multiple files depending on the format.\n *\n * This is the root object from which all media read operations start.\n * @group Input files & tracks\n * @public\n */\nexport class Input extends EventEmitter {\n    /** True if the input has been disposed. */\n    get disposed() {\n        return this._disposed;\n    }\n    /**\n     * Creates a new input file from the specified options. No reading operations will be performed until methods are\n     * called on this instance.\n     */\n    constructor(options) {\n        super();\n        /** @internal */\n        this._demuxerPromise = null;\n        /** @internal */\n        this._format = null;\n        /** @internal */\n        this._trackBackingsCache = null;\n        /** @internal */\n        this._backingToTrack = new Map();\n        /** @internal */\n        this._disposed = false;\n        /** @internal */\n        this._nextSourceCacheAge = 0;\n        /** @internal */\n        this._sourceRefs = [];\n        /** @internal */\n        this._sourceCache = [];\n        /** @internal */\n        this._sourceCachePromises = [];\n        /** @internal */\n        this._onFormatDetermined = null;\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (!Array.isArray(options.formats) || options.formats.some(x => !(x instanceof InputFormat))) {\n            throw new TypeError('options.formats must be an array of InputFormat.');\n        }\n        if (!(options.source instanceof Source || options.source instanceof SourceRef)) {\n            throw new TypeError('options.source must be a Source or SourceRef.');\n        }\n        if (options.source instanceof Source && options.source._disposed) {\n            throw new TypeError('options.source must not be a disposed Source.');\n        }\n        if (options.initInput !== undefined && !(options.initInput instanceof Input)) {\n            throw new TypeError('options.initInput, when provided, must be an Input.');\n        }\n        if (options.formatOptions !== undefined) {\n            validateInputFormatOptions(options.formatOptions, 'formatOptions');\n        }\n        this._formats = options.formats;\n        this._initInput = options.initInput ?? null;\n        this._formatOptions = options.formatOptions ?? {};\n        if (options.source instanceof Source) {\n            this._rootRef = options.source.ref();\n        }\n        else {\n            this._rootRef = options.source;\n        }\n        this._sourceRefs.push(this._rootRef);\n    }\n    /** @internal */\n    get _rootSource() {\n        return this._rootRef.source;\n    }\n    /** @internal */\n    async _getSourceUncached(request) {\n        assert(this._rootSource instanceof PathedSource);\n        const ref = await this._rootSource._resolveRequest(request);\n        this._emit('source', { source: ref.source, request, isRoot: request.isRoot });\n        return ref;\n    }\n    /** @internal */\n    _getSourceCached(request, cacheGroup = DEFAULT_SOURCE_CACHE_GROUP) {\n        const cachedEntry = this._sourceCache.find(x => x.cacheGroup === cacheGroup && sourceRequestsAreEqual(x.request, request));\n        if (cachedEntry) {\n            cachedEntry.age++;\n            return Promise.resolve(cachedEntry.sourceRef.source.ref());\n        }\n        const cachedPromiseEntry = this._sourceCachePromises.find(x => x.cacheGroup === cacheGroup && sourceRequestsAreEqual(x.request, request));\n        if (cachedPromiseEntry) {\n            return cachedPromiseEntry.promise.then(x => x.sourceRef.source.ref());\n        }\n        const promise = (async () => {\n            const sourceRef = await this._getSourceUncached(request);\n            if (this._disposed) {\n                sourceRef.free();\n                throw new InputDisposedError();\n            }\n            const MAX_SOURCE_CACHE_SIZE = 4;\n            const count = arrayCount(this._sourceCache, x => x.cacheGroup === cacheGroup && x.sourceRef.source._refCount === 1);\n            if (count >= MAX_SOURCE_CACHE_SIZE) {\n                const minAgeIndex = arrayArgmin(this._sourceCache, x => x.cacheGroup === cacheGroup && x.sourceRef.source._refCount === 1 ? x.age : Infinity);\n                assert(minAgeIndex !== -1);\n                const entry = this._sourceCache[minAgeIndex];\n                this._sourceCache.splice(minAgeIndex, 1);\n                entry.sourceRef.free();\n                removeItem(this._sourceRefs, entry.sourceRef);\n            }\n            this._sourceRefs.push(sourceRef);\n            const promiseIndex = this._sourceCachePromises.findIndex(x => x.request === request);\n            assert(promiseIndex !== -1);\n            this._sourceCachePromises.splice(promiseIndex, 1);\n            const cacheEntry = {\n                request,\n                sourceRef,\n                age: this._nextSourceCacheAge++,\n                cacheGroup,\n            };\n            return cacheEntry;\n        })();\n        this._sourceCachePromises.push({\n            request,\n            cacheGroup,\n            promise,\n        });\n        return promise.then((entry) => {\n            const ref = entry.sourceRef.source.ref();\n            // We need to add it to the cache this late to avoid the ref being freed prematurely due to race conditions\n            this._sourceCache.push(entry);\n            return ref;\n        });\n    }\n    /** @internal */\n    _getDemuxer() {\n        return this._demuxerPromise ??= (async () => {\n            this._reader = new Reader(this._rootSource);\n            this._emit('source', { source: this._rootSource, request: null, isRoot: true });\n            for (const format of this._formats) {\n                const canRead = await format._canReadInput(this);\n                if (canRead) {\n                    this._format = format;\n                    this._onFormatDetermined?.(format);\n                    return format._createDemuxer(this);\n                }\n            }\n            throw new UnsupportedInputFormatError();\n        })();\n    }\n    /**\n     * Returns the source from which this input file reads data for the root path.\n     */\n    get source() {\n        return this._rootSource;\n    }\n    /**\n     * Returns the format of the input file. You can compare this result directly to the {@link InputFormat} singletons\n     * or use `instanceof` checks for subset-aware logic (for example, `format instanceof MatroskaInputFormat` is true\n     * for both MKV and WebM).\n     */\n    async getFormat() {\n        await this._getDemuxer();\n        assert(this._format);\n        return this._format;\n    }\n    /** Returns `true` if the format of the input file is known and the file can be read, `false` otherwise. */\n    async canRead() {\n        try {\n            await this._getDemuxer();\n            return true;\n        }\n        catch (error) {\n            if (error instanceof UnsupportedInputFormatError) {\n                return false;\n            }\n            throw error;\n        }\n    }\n    /**\n     * Returns the timestamp at which the input file starts. More precisely, returns the smallest starting timestamp\n     * among all tracks.\n     *\n     * Optionally, you can pass in the list of tracks for which you want to compute the starting timestamp.\n     *\n     * Note that this method is potentially expensive for inputs with many tracks (such as HLS manifests), since it\n     * probes every track.\n     */\n    async getFirstTimestamp(tracks) {\n        tracks ??= await this.getTracks();\n        const filtered = tracks.filter(x => x !== null);\n        if (filtered.length === 0) {\n            return 0;\n        }\n        // Only count the timestamps of tracks that have at least one packet\n        const firstPackets = await Promise.all(filtered.map(x => x._backing.getFirstPacket({ metadataOnly: true })));\n        const result = Math.min(...firstPackets.map(x => x?.timestamp ?? Infinity));\n        return result === Infinity ? 0 : result;\n    }\n    /**\n     * Computes the duration of the input file, in seconds. More precisely, returns the largest end timestamp among\n     * all tracks.\n     *\n     * Optionally, you can pass in the list of tracks for which you want to compute the duration.\n     *\n     * This method can be potentially expensive depending on the underlying file format, because it returns the most\n     * accurate duration possible and must check all tracks. Use {@link Input.getDurationFromMetadata} for a faster but\n     * less accurate estimate of duration.\n     *\n     * By default, when any track in the underlying media is live, this method will only resolve once the live stream\n     * ends. If you want to query the current duration of the media, set {@link PacketRetrievalOptions.skipLiveWait}\n     * to `true` in the options.\n     */\n    async computeDuration(tracks, options) {\n        tracks ??= await this.getTracks();\n        const filtered = tracks.filter(x => x !== null);\n        if (filtered.length === 0) {\n            return 0;\n        }\n        const tracksDurations = await Promise.all(filtered.map(x => x.computeDuration(options)));\n        return Math.max(...tracksDurations);\n    }\n    /**\n     * Gets the duration (end timestamp) in seconds of the input file from metadata stored in the file. This value may\n     * be approximate or diverge from the actual, precise duration returned by `.computeDuration()`, but compared to\n     * that method, this method is cheaper. When the duration cannot be determined from the file metadata, `null`\n     * is returned.\n     *\n     * Optionally, you can pass in the list of tracks for which you want to get the duration from metadata.\n     *\n     * By default, when the underlying media is live, this method will only resolve once the live stream\n     * ends. If you want to query the current duration of the media, set\n     * {@link DurationMetadataRequestOptions.skipLiveWait} to `true` in the options.\n     */\n    async getDurationFromMetadata(tracks, options) {\n        tracks ??= await this.getTracks();\n        const filtered = tracks.filter(x => x !== null);\n        const tracksDurations = await Promise.all(filtered.map(x => x.getDurationFromMetadata(options)));\n        const nonNullDurations = tracksDurations.filter(x => x !== null);\n        if (nonNullDurations.length === 0) {\n            return null;\n        }\n        return Math.max(...nonNullDurations);\n    }\n    /**\n     * Returns the list of all tracks of this input file in the order in which they appear in the file. An optional\n     * query can be provided.\n     */\n    async getTracks(query) {\n        query &&= toValidatedInputTrackQuery(query);\n        const backings = await this._getTrackBackings();\n        const tracks = backings.map(backing => this._wrapBackingAsTrack(backing));\n        return queryInputTracks(tracks, query);\n    }\n    /** Returns the list of all video tracks of this input file. An optional query can be provided. */\n    async getVideoTracks(query) {\n        query &&= toValidatedInputTrackQuery(query);\n        const tracks = await this.getTracks();\n        const videoTracks = tracks.filter((x) => x.isVideoTrack());\n        return queryInputTracks(videoTracks, query);\n    }\n    /** Returns the list of all audio tracks of this input file. An optional query can be provided. */\n    async getAudioTracks(query) {\n        query &&= toValidatedInputTrackQuery(query);\n        const tracks = await this.getTracks();\n        const audioTracks = tracks.filter((x) => x.isAudioTrack());\n        return queryInputTracks(audioTracks, query);\n    }\n    /**\n     * Returns the primary video track of this input file, or null if there are no video tracks.\n     *\n     * Multiple factors determine which track is considered primary, including its position in the file, disposition,\n     * bitrate (higher bitrate is preferred), and if it can be paired with an audio track.\n     */\n    async getPrimaryVideoTrack(query) {\n        query &&= toValidatedInputTrackQuery(query);\n        const merged = mergeInputTrackQueries(query, {\n            sortBy: async (t) => [\n                prefer((await t.getDisposition()).default),\n                prefer(await t.hasPairableAudioTrack()),\n                prefer(!(await t.hasOnlyKeyPackets())),\n                desc(await t.getBitrate()),\n            ],\n        });\n        const sorted = await this.getVideoTracks(merged);\n        return sorted[0] ?? null;\n    }\n    /**\n     * Returns the primary audio track of this input file, or null if there are no audio tracks.\n     *\n     * Multiple factors determine which track is considered primary, including its position in the file, disposition,\n     * bitrate (higher bitrate is preferred), and if it can be paired with the primary video track.\n     */\n    async getPrimaryAudioTrack(query) {\n        query &&= toValidatedInputTrackQuery(query);\n        const primaryVideoTrack = await this.getPrimaryVideoTrack();\n        const merged = mergeInputTrackQueries(query, {\n            sortBy: async (t) => [\n                prefer(!primaryVideoTrack || t.canBePairedWith(primaryVideoTrack)),\n                prefer((await t.getDisposition()).default),\n                desc(await t.getBitrate()),\n            ],\n        });\n        const sorted = await this.getAudioTracks(merged);\n        return sorted[0] ?? null;\n    }\n    /** @internal */\n    async _getTrackBackings() {\n        const demuxer = await this._getDemuxer();\n        return this._trackBackingsCache ??= await demuxer.getTrackBackings();\n    }\n    /** @internal */\n    _wrapBackingAsTrack(backing) {\n        const existing = this._backingToTrack.get(backing);\n        if (existing) {\n            return existing;\n        }\n        const type = backing.getType();\n        const track = type === 'video'\n            ? new InputVideoTrack(this, backing)\n            : new InputAudioTrack(this, backing);\n        this._backingToTrack.set(backing, track);\n        return track;\n    }\n    /** Returns the full MIME type of this input file, including track codecs. */\n    async getMimeType() {\n        const demuxer = await this._getDemuxer();\n        return demuxer.getMimeType();\n    }\n    /**\n     * Returns descriptive metadata tags about the media file, such as title, author, date, cover art, or other\n     * attached files.\n     */\n    async getMetadataTags() {\n        const demuxer = await this._getDemuxer();\n        return demuxer.getMetadataTags();\n    }\n    /**\n     * Disposes this input and frees connected resources. When an input is disposed, ongoing read operations will be\n     * canceled, all future read operations will fail, any open decoders will be closed, and all ongoing media sink\n     * operations will be canceled. Disallowed and canceled operations will throw an {@link InputDisposedError}.\n     *\n     * You are expected not to use an input after disposing it. While some operations may still work, it is not\n     * specified and may change in any future update.\n     */\n    dispose() {\n        if (this._disposed) {\n            return;\n        }\n        this._disposed = true;\n        for (const ref of this._sourceRefs) {\n            ref.free();\n        }\n        this._sourceRefs.length = 0;\n        if (this._demuxerPromise) {\n            // The demuxer promise may already be rejected after failed format detection.\n            void this._demuxerPromise\n                .then(demuxer => demuxer.dispose())\n                .catch(() => { });\n        }\n    }\n    /**\n     * Calls `.dispose()` on the input, implementing the `Disposable` interface for use with\n     * JavaScript Explicit Resource Management features.\n     */\n    [Symbol.dispose]() {\n        this.dispose();\n    }\n}\n/**\n * Thrown when trying to operate on an input that has an unsupported or unrecognizable format.\n * @group Input files & tracks\n * @public\n */\nexport class UnsupportedInputFormatError extends Error {\n    /** Creates a new {@link UnsupportedInputFormatError}. */\n    constructor(message = 'Input has an unsupported or unrecognizable format.') {\n        super(message);\n        this.name = 'UnsupportedInputFormatError';\n    }\n}\n/**\n * Thrown when an operation was prevented because the corresponding {@link Input} has been disposed.\n * @group Input files & tracks\n * @public\n */\nexport class InputDisposedError extends Error {\n    /** Creates a new {@link InputDisposedError}. */\n    constructor(message = 'Input has been disposed.') {\n        super(message);\n        this.name = 'InputDisposedError';\n    }\n}\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { InputDisposedError } from './input.js';\nimport { assert, clamp, getUint24, isThenable, textDecoder, toDataView } from './misc.js';\nimport { DEFAULT_MAX_READ_POSITION, DEFAULT_MIN_READ_POSITION } from './source.js';\nexport class Reader {\n    constructor(source) {\n        this.source = source;\n    }\n    get fileSize() {\n        const size = this.source._getFileSize();\n        if (size === undefined) {\n            throw new Error('Reading file size too early; read required first.');\n        }\n        return size;\n    }\n    get fileSizeNonStrict() {\n        return this.source._getFileSize() ?? null;\n    }\n    requestSlice(start, length) {\n        if (this.source._disposed) {\n            throw new InputDisposedError();\n        }\n        if (start < 0) {\n            return null;\n        }\n        if (this.fileSizeNonStrict !== null && start + length > this.fileSizeNonStrict) {\n            return null;\n        }\n        if (length === 0) {\n            const buffer = new Uint8Array(0);\n            return new FileSlice(buffer, toDataView(buffer), 0, start, start);\n        }\n        const end = start + length;\n        const result = this.source._read(start, end, DEFAULT_MIN_READ_POSITION, DEFAULT_MAX_READ_POSITION);\n        if (isThenable(result)) {\n            return result.then((x) => {\n                if (!x) {\n                    return null;\n                }\n                return new FileSlice(x.bytes, x.view, x.offset, start, end);\n            });\n        }\n        else {\n            if (!result) {\n                return null;\n            }\n            return new FileSlice(result.bytes, result.view, result.offset, start, end);\n        }\n    }\n    requestSliceRange(start, minLength, maxLength) {\n        if (this.source._disposed) {\n            throw new InputDisposedError();\n        }\n        if (start < 0) {\n            return null;\n        }\n        if (this.fileSizeNonStrict !== null) {\n            return this.requestSlice(start, clamp(this.fileSizeNonStrict - start, minLength, maxLength));\n        }\n        else {\n            const promisedAttempt = this.requestSlice(start, maxLength);\n            const handleAttempt = (attempt) => {\n                if (attempt) {\n                    return attempt;\n                }\n                // The slice couldn't fit, meaning we must know the file size now\n                assert(this.fileSizeNonStrict !== null);\n                return this.requestSlice(start, clamp(this.fileSizeNonStrict - start, minLength, maxLength));\n            };\n            if (isThenable(promisedAttempt)) {\n                return promisedAttempt.then(handleAttempt);\n            }\n            else {\n                return handleAttempt(promisedAttempt);\n            }\n        }\n    }\n    requestEntireFile() {\n        if (this.fileSizeNonStrict !== null) {\n            return this.requestSlice(0, this.fileSizeNonStrict);\n        }\n        const CHUNK_SIZE = 1024;\n        return (async () => {\n            const chunks = [];\n            let currentSize = 0;\n            while (true) {\n                if (chunks.length === 1 && this.fileSizeNonStrict !== null) {\n                    // It only took one read to get to know the whole file size\n                    return this.requestSlice(0, this.fileSizeNonStrict);\n                }\n                let slice = this.requestSliceRange(currentSize, 0, CHUNK_SIZE);\n                if (isThenable(slice))\n                    slice = await slice;\n                if (!slice || slice.length === 0) {\n                    break;\n                }\n                const chunk = readBytes(slice, slice.length);\n                chunks.push(chunk);\n                currentSize += slice.length;\n            }\n            const joined = new Uint8Array(currentSize);\n            let offset = 0;\n            for (const chunk of chunks) {\n                joined.set(chunk, offset);\n                offset += chunk.length;\n            }\n            return new FileSlice(joined, toDataView(joined), 0, 0, currentSize);\n        })();\n    }\n}\nexport class FileSlice {\n    constructor(\n    /** The underlying bytes backing this slice. Avoid using this directly and prefer reader functions instead. */\n    bytes, \n    /** A view into the bytes backing this slice. Avoid using this directly and prefer reader functions instead. */\n    view, \n    /** The offset in \"file bytes\" at which `bytes` begins in the file. */\n    offset, \n    /** The offset in \"file bytes\" where this slice begins. */\n    start, \n    /** The offset in \"file bytes\" where this slice ends (exclusive). */\n    end) {\n        this.bytes = bytes;\n        this.view = view;\n        this.offset = offset;\n        this.start = start;\n        this.end = end;\n        this.bufferPos = start - offset;\n    }\n    static tempFromBytes(bytes) {\n        return new FileSlice(bytes, toDataView(bytes), 0, 0, bytes.length);\n    }\n    get length() {\n        return this.end - this.start;\n    }\n    get filePos() {\n        return this.offset + this.bufferPos;\n    }\n    set filePos(value) {\n        this.bufferPos = value - this.offset;\n    }\n    /** The number of bytes left from the current pos to the end of the slice. */\n    get remainingLength() {\n        return Math.max(this.end - this.filePos, 0);\n    }\n    skip(byteCount) {\n        this.bufferPos += byteCount;\n    }\n    /** Creates a new subslice of this slice whose byte range must be contained within this slice. */\n    slice(filePos, length = this.end - filePos) {\n        if (filePos < this.start || filePos + length > this.end) {\n            throw new RangeError('Slicing outside of original slice.');\n        }\n        return new FileSlice(this.bytes, this.view, this.offset, filePos, filePos + length);\n    }\n}\nconst checkIsInRange = (slice, bytesToRead) => {\n    if (bytesToRead < 0 || slice.filePos < slice.start || slice.filePos + bytesToRead > slice.end) {\n        throw new RangeError(`Tried reading [${slice.filePos}, ${slice.filePos + bytesToRead}), but slice is`\n            + ` [${slice.start}, ${slice.end}). This is likely an internal error, please report it alongside the file`\n            + ` that caused it.`);\n    }\n};\nexport const readBytes = (slice, length) => {\n    checkIsInRange(slice, length);\n    const bytes = slice.bytes.subarray(slice.bufferPos, slice.bufferPos + length);\n    slice.bufferPos += length;\n    return bytes;\n};\nexport const readU8 = (slice) => {\n    checkIsInRange(slice, 1);\n    return slice.view.getUint8(slice.bufferPos++);\n};\nexport const readU16 = (slice, littleEndian) => {\n    checkIsInRange(slice, 2);\n    const value = slice.view.getUint16(slice.bufferPos, littleEndian);\n    slice.bufferPos += 2;\n    return value;\n};\nexport const readU16Be = (slice) => {\n    checkIsInRange(slice, 2);\n    const value = slice.view.getUint16(slice.bufferPos, false);\n    slice.bufferPos += 2;\n    return value;\n};\nexport const readU24Be = (slice) => {\n    checkIsInRange(slice, 3);\n    const value = getUint24(slice.view, slice.bufferPos, false);\n    slice.bufferPos += 3;\n    return value;\n};\nexport const readI16Be = (slice) => {\n    checkIsInRange(slice, 2);\n    const value = slice.view.getInt16(slice.bufferPos, false);\n    slice.bufferPos += 2;\n    return value;\n};\nexport const readU32 = (slice, littleEndian) => {\n    checkIsInRange(slice, 4);\n    const value = slice.view.getUint32(slice.bufferPos, littleEndian);\n    slice.bufferPos += 4;\n    return value;\n};\nexport const readU32Be = (slice) => {\n    checkIsInRange(slice, 4);\n    const value = slice.view.getUint32(slice.bufferPos, false);\n    slice.bufferPos += 4;\n    return value;\n};\nexport const readU32Le = (slice) => {\n    checkIsInRange(slice, 4);\n    const value = slice.view.getUint32(slice.bufferPos, true);\n    slice.bufferPos += 4;\n    return value;\n};\nexport const readI32Be = (slice) => {\n    checkIsInRange(slice, 4);\n    const value = slice.view.getInt32(slice.bufferPos, false);\n    slice.bufferPos += 4;\n    return value;\n};\nexport const readI32Le = (slice) => {\n    checkIsInRange(slice, 4);\n    const value = slice.view.getInt32(slice.bufferPos, true);\n    slice.bufferPos += 4;\n    return value;\n};\nexport const readU64 = (slice, littleEndian) => {\n    let low;\n    let high;\n    if (littleEndian) {\n        low = readU32(slice, true);\n        high = readU32(slice, true);\n    }\n    else {\n        high = readU32(slice, false);\n        low = readU32(slice, false);\n    }\n    return high * 0x100000000 + low;\n};\nexport const readU64Be = (slice) => {\n    const high = readU32Be(slice);\n    const low = readU32Be(slice);\n    return high * 0x100000000 + low;\n};\nexport const readI64Be = (slice) => {\n    const high = readI32Be(slice);\n    const low = readU32Be(slice);\n    return high * 0x100000000 + low;\n};\nexport const readI64Le = (slice) => {\n    const low = readU32Le(slice);\n    const high = readI32Le(slice);\n    return high * 0x100000000 + low;\n};\nexport const readF32Be = (slice) => {\n    checkIsInRange(slice, 4);\n    const value = slice.view.getFloat32(slice.bufferPos, false);\n    slice.bufferPos += 4;\n    return value;\n};\nexport const readF64Be = (slice) => {\n    checkIsInRange(slice, 8);\n    const value = slice.view.getFloat64(slice.bufferPos, false);\n    slice.bufferPos += 8;\n    return value;\n};\nexport const readAscii = (slice, length) => {\n    checkIsInRange(slice, length);\n    let str = '';\n    for (let i = 0; i < length; i++) {\n        str += String.fromCharCode(slice.bytes[slice.bufferPos++]);\n    }\n    return str;\n};\nexport const readAllLines = (slice, length, options) => {\n    const text = textDecoder.decode(readBytes(slice, length));\n    const lines = text.split('\\n')\n        .map(x => x.trim())\n        .filter(x => x.length > 0 && !options?.ignore?.(x));\n    return lines;\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { AsyncMutex } from './misc.js';\nexport class Muxer {\n    constructor(output) {\n        this.mutex = new AsyncMutex();\n        this.trackTimestampInfo = new WeakMap();\n        this.output = output;\n    }\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    onTrackClose(track) { }\n    validateTimestamp(track, timestampInSeconds, isKeyPacket) {\n        let timestampInfo = this.trackTimestampInfo.get(track);\n        if (!timestampInfo) {\n            if (!isKeyPacket) {\n                throw new Error('First packet must be a key packet.');\n            }\n            timestampInfo = {\n                maxTimestamp: timestampInSeconds,\n                maxTimestampBeforeLastKeyPacket: null,\n            };\n            this.trackTimestampInfo.set(track, timestampInfo);\n        }\n        else {\n            if (isKeyPacket) {\n                timestampInfo.maxTimestampBeforeLastKeyPacket = timestampInfo.maxTimestamp;\n            }\n            if (timestampInfo.maxTimestampBeforeLastKeyPacket !== null\n                && timestampInSeconds < timestampInfo.maxTimestampBeforeLastKeyPacket) {\n                throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a`\n                    + ` key packet and ends right before the next key packet). Got ${timestampInSeconds}s, but largest`\n                    + ` timestamp is ${timestampInfo.maxTimestampBeforeLastKeyPacket}s.`);\n            }\n            timestampInfo.maxTimestamp = Math.max(timestampInfo.maxTimestamp, timestampInSeconds);\n        }\n    }\n}\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nconst cueBlockHeaderRegex = /(?:(.+?)\\n)?((?:\\d{2}:)?\\d{2}:\\d{2}.\\d{3})\\s+-->\\s+((?:\\d{2}:)?\\d{2}:\\d{2}.\\d{3})/g;\nconst preambleStartRegex = /^WEBVTT(.|\\n)*?\\n{2}/;\nexport const inlineTimestampRegex = /<(?:(\\d{2}):)?(\\d{2}):(\\d{2}).(\\d{3})>/g;\nexport class SubtitleParser {\n    constructor(options) {\n        this.preambleText = null;\n        this.preambleEmitted = false;\n        this.options = options;\n    }\n    parse(text) {\n        text = text.replaceAll('\\r\\n', '\\n').replaceAll('\\r', '\\n');\n        cueBlockHeaderRegex.lastIndex = 0;\n        let match;\n        if (!this.preambleText) {\n            if (!preambleStartRegex.test(text)) {\n                throw new Error('WebVTT preamble incorrect.');\n            }\n            match = cueBlockHeaderRegex.exec(text);\n            const preamble = text.slice(0, match?.index ?? text.length).trimEnd();\n            if (!preamble) {\n                throw new Error('No WebVTT preamble provided.');\n            }\n            this.preambleText = preamble;\n            if (match) {\n                text = text.slice(match.index);\n                cueBlockHeaderRegex.lastIndex = 0;\n            }\n        }\n        while ((match = cueBlockHeaderRegex.exec(text))) {\n            const notes = text.slice(0, match.index);\n            const cueIdentifier = match[1];\n            const matchEnd = match.index + match[0].length;\n            const bodyStart = text.indexOf('\\n', matchEnd) + 1;\n            const cueSettings = text.slice(matchEnd, bodyStart).trim();\n            let bodyEnd = text.indexOf('\\n\\n', matchEnd);\n            if (bodyEnd === -1)\n                bodyEnd = text.length;\n            const startTime = parseSubtitleTimestamp(match[2]);\n            const endTime = parseSubtitleTimestamp(match[3]);\n            const duration = endTime - startTime;\n            const body = text.slice(bodyStart, bodyEnd).trim();\n            text = text.slice(bodyEnd).trimStart();\n            cueBlockHeaderRegex.lastIndex = 0;\n            const cue = {\n                timestamp: startTime / 1000,\n                duration: duration / 1000,\n                text: body,\n                identifier: cueIdentifier,\n                settings: cueSettings,\n                notes,\n            };\n            const meta = {};\n            if (!this.preambleEmitted) {\n                meta.config = {\n                    description: this.preambleText,\n                };\n                this.preambleEmitted = true;\n            }\n            this.options.output(cue, meta);\n        }\n    }\n}\nconst timestampRegex = /(?:(\\d{2}):)?(\\d{2}):(\\d{2}).(\\d{3})/;\nexport const parseSubtitleTimestamp = (string) => {\n    const match = timestampRegex.exec(string);\n    if (!match)\n        throw new Error('Expected match.');\n    return 60 * 60 * 1000 * Number(match[1] || '0')\n        + 60 * 1000 * Number(match[2])\n        + 1000 * Number(match[3])\n        + Number(match[4]);\n};\nexport const formatSubtitleTimestamp = (timestamp) => {\n    const hours = Math.floor(timestamp / (60 * 60 * 1000));\n    const minutes = Math.floor((timestamp % (60 * 60 * 1000)) / (60 * 1000));\n    const seconds = Math.floor((timestamp % (60 * 1000)) / 1000);\n    const milliseconds = timestamp % 1000;\n    return hours.toString().padStart(2, '0') + ':'\n        + minutes.toString().padStart(2, '0') + ':'\n        + seconds.toString().padStart(2, '0') + '.'\n        + milliseconds.toString().padStart(3, '0');\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { toUint8Array, assert, isI32, isU32, last, IDENTITY_MATRIX, centeredTransformationMatrix, multiplyMatrices, rotationMatrix, scaleMatrix, textEncoder, COLOR_PRIMARIES_MAP, TRANSFER_CHARACTERISTICS_MAP, MATRIX_COEFFICIENTS_MAP, colorSpaceIsEmpty, UNDETERMINED_LANGUAGE, assertNever, keyValueIterator, } from '../misc.js';\nimport { generateAv1CodecConfigurationFromCodecString, parsePcmCodec, PCM_AUDIO_CODECS, } from '../codec.js';\nimport { formatSubtitleTimestamp } from '../subtitles.js';\nimport { getTrackMetadata, GLOBAL_TIMESCALE, intoTimescale, presentationSpan, } from './isobmff-muxer.js';\nimport { buildDtsSpecificBox, parseAc3SyncFrame, parseDtsFrame, parseEac3SyncFrame, parseOpusIdentificationHeader, } from '../codec-data.js';\nimport { RichImageData } from '../metadata.js';\nimport { Bitstream } from '../../shared/bitstream.js';\nimport { VERSIONED_NAME } from '../version.js';\nexport class IsobmffBoxWriter {\n    constructor(writer) {\n        this.writer = writer;\n        this.helper = new Uint8Array(8);\n        this.helperView = new DataView(this.helper.buffer);\n        /**\n         * Stores the position from the start of the file to where boxes elements have been written. This is used to\n         * rewrite/edit elements that were already added before, and to measure sizes of things.\n         */\n        this.offsets = new WeakMap();\n    }\n    writeU32(value) {\n        this.helperView.setUint32(0, value, false);\n        this.writer.write(this.helper.subarray(0, 4));\n    }\n    writeU64(value) {\n        this.helperView.setUint32(0, Math.floor(value / 2 ** 32), false);\n        this.helperView.setUint32(4, value, false);\n        this.writer.write(this.helper.subarray(0, 8));\n    }\n    writeAscii(text) {\n        for (let i = 0; i < text.length; i++) {\n            this.helperView.setUint8(i % 8, text.charCodeAt(i));\n            if (i % 8 === 7)\n                this.writer.write(this.helper);\n        }\n        if (text.length % 8 !== 0) {\n            this.writer.write(this.helper.subarray(0, text.length % 8));\n        }\n    }\n    writeBox(box) {\n        this.offsets.set(box, this.writer.getPos());\n        if (box.contents && !box.children) {\n            this.writeBoxHeader(box, box.size ?? box.contents.byteLength + 8);\n            this.writer.write(box.contents);\n        }\n        else {\n            const startPos = this.writer.getPos();\n            this.writeBoxHeader(box, 0);\n            if (box.contents)\n                this.writer.write(box.contents);\n            if (box.children)\n                for (const child of box.children)\n                    if (child)\n                        this.writeBox(child);\n            const endPos = this.writer.getPos();\n            const size = box.size ?? endPos - startPos;\n            this.writer.seek(startPos);\n            this.writeBoxHeader(box, size);\n            this.writer.seek(endPos);\n        }\n    }\n    writeBoxHeader(box, size) {\n        this.writeU32(box.largeSize ? 1 : size);\n        this.writeAscii(box.type);\n        if (box.largeSize)\n            this.writeU64(size);\n    }\n    measureBoxHeader(box) {\n        return 8 + (box.largeSize ? 8 : 0);\n    }\n    patchBox(box) {\n        const boxOffset = this.offsets.get(box);\n        assert(boxOffset !== undefined);\n        const endPos = this.writer.getPos();\n        this.writer.seek(boxOffset);\n        this.writeBox(box);\n        this.writer.seek(endPos);\n    }\n    measureBox(box) {\n        if (box.contents && !box.children) {\n            const headerSize = this.measureBoxHeader(box);\n            return headerSize + box.contents.byteLength;\n        }\n        else {\n            let result = this.measureBoxHeader(box);\n            if (box.contents)\n                result += box.contents.byteLength;\n            if (box.children)\n                for (const child of box.children)\n                    if (child)\n                        result += this.measureBox(child);\n            return result;\n        }\n    }\n}\nconst bytes = /* #__PURE__ */ new Uint8Array(8);\nconst view = /* #__PURE__ */ new DataView(bytes.buffer);\nconst u8 = (value) => {\n    return [(value % 0x100 + 0x100) % 0x100];\n};\nconst u16 = (value) => {\n    view.setUint16(0, value, false);\n    return [bytes[0], bytes[1]];\n};\nconst i16 = (value) => {\n    view.setInt16(0, value, false);\n    return [bytes[0], bytes[1]];\n};\nconst u24 = (value) => {\n    view.setUint32(0, value, false);\n    return [bytes[1], bytes[2], bytes[3]];\n};\nconst u32 = (value) => {\n    view.setUint32(0, value, false);\n    return [bytes[0], bytes[1], bytes[2], bytes[3]];\n};\nconst i32 = (value) => {\n    view.setInt32(0, value, false);\n    return [bytes[0], bytes[1], bytes[2], bytes[3]];\n};\nconst u64 = (value) => {\n    view.setUint32(0, Math.floor(value / 2 ** 32), false);\n    view.setUint32(4, value, false);\n    return [bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]];\n};\nconst i64 = (value) => {\n    view.setInt32(0, Math.floor(value / 2 ** 32), false);\n    view.setUint32(4, value, false);\n    return [bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]];\n};\nconst fixed_8_8 = (value) => {\n    view.setInt16(0, 2 ** 8 * value, false);\n    return [bytes[0], bytes[1]];\n};\nconst fixed_16_16 = (value) => {\n    view.setInt32(0, 2 ** 16 * value, false);\n    return [bytes[0], bytes[1], bytes[2], bytes[3]];\n};\nconst fixed_2_30 = (value) => {\n    view.setInt32(0, 2 ** 30 * value, false);\n    return [bytes[0], bytes[1], bytes[2], bytes[3]];\n};\nconst variableUnsignedInt = (value, byteLength) => {\n    const bytes = [];\n    let remaining = value;\n    do {\n        let byte = remaining & 0x7f;\n        remaining >>= 7;\n        // If this isn't the first byte we're adding (meaning there will be more bytes after it\n        // when we reverse the array), set the continuation bit\n        if (bytes.length > 0) {\n            byte |= 0x80;\n        }\n        bytes.push(byte);\n        if (byteLength !== undefined) {\n            byteLength--;\n        }\n    } while (remaining > 0 || byteLength);\n    // Reverse the array since we built it backwards\n    return bytes.reverse();\n};\nconst ascii = (text, nullTerminated = false) => {\n    const bytes = Array(text.length).fill(null).map((_, i) => text.charCodeAt(i));\n    if (nullTerminated)\n        bytes.push(0x00);\n    return bytes;\n};\nconst matrixToBytes = (matrix) => {\n    return [\n        fixed_16_16(matrix[0]), fixed_16_16(matrix[1]), fixed_2_30(matrix[2]),\n        fixed_16_16(matrix[3]), fixed_16_16(matrix[4]), fixed_2_30(matrix[5]),\n        fixed_16_16(matrix[6]), fixed_16_16(matrix[7]), fixed_2_30(matrix[8]),\n    ];\n};\nexport const box = (type, contents, children) => ({\n    type,\n    contents: contents && new Uint8Array(contents.flat(10)),\n    children,\n});\n/** A FullBox always starts with a version byte, followed by three flag bytes. */\nexport const fullBox = (type, version, flags, contents, children) => box(type, [u8(version), u24(flags), contents ?? []], children);\n/**\n * File Type Compatibility Box: Allows the reader to determine whether this is a type of file that the\n * reader understands.\n */\nexport const ftyp = (details) => {\n    // You can find the full logic for this at\n    // https://github.com/FFmpeg/FFmpeg/blob/de2fb43e785773738c660cdafb9309b1ef1bc80d/libavformat/movenc.c#L5518\n    // Obviously, this lib only needs a small subset of that logic.\n    const minorVersion = 0x200;\n    if (details.isQuickTime) {\n        return box('ftyp', [\n            ascii('qt  '), // Major brand\n            u32(minorVersion), // Minor version\n            // Compatible brands\n            ascii('qt  '),\n        ]);\n    }\n    if (details.fragmented) {\n        if (details.cmaf) {\n            return box('ftyp', [\n                ascii('iso5'), // Major brand\n                u32(minorVersion), // Minor version\n                // Compatible brands\n                ascii('iso5'),\n                ascii('iso6'),\n                ascii('mp41'),\n                ascii('cmfc'),\n                ascii('dash'),\n            ]);\n        }\n        else {\n            return box('ftyp', [\n                ascii('iso5'), // Major brand\n                u32(minorVersion), // Minor version\n                // Compatible brands\n                ascii('iso5'),\n                ascii('iso6'),\n                ascii('mp41'),\n            ]);\n        }\n    }\n    return box('ftyp', [\n        ascii('isom'), // Major brand\n        u32(minorVersion), // Minor version\n        // Compatible brands\n        ascii('isom'),\n        details.holdsAvc ? ascii('avc1') : [],\n        ascii('mp41'),\n    ]);\n};\n/** Segment Type Box */\nexport const styp = () => box('styp', [\n    ascii('iso5'), // Major brand\n    u32(0), // Minor version\n    // Compatible brands\n    ascii('iso5'),\n    ascii('iso6'),\n    ascii('mp41'),\n    ascii('cmfc'),\n    ascii('dash'),\n]);\n/** Segment Index Box */\nexport const sidx = (muxer, referencedSize) => {\n    const earliestPresentationTime = Math.max(0, muxer.minWrittenTimestamp);\n    let duration = Math.max(0, muxer.maxWrittenEndTimestamp - earliestPresentationTime);\n    if (!Number.isFinite(duration)) {\n        duration = 0;\n    }\n    return fullBox('sidx', 1, 0, [\n        u32(1), // Reference ID\n        u32(GLOBAL_TIMESCALE), // Timescale\n        u64(intoTimescale(earliestPresentationTime, GLOBAL_TIMESCALE)), // Earliest presentation time\n        u64(0), // First offset\n        u16(0), // Reserved\n        u16(1), // Reference count\n        u32(referencedSize & 0x7fffffff), // Reference type (0) + referenced size\n        u32(intoTimescale(duration, GLOBAL_TIMESCALE)), // Subsegment duration\n        u32(0), // Starts with SAP + SAP type + SAP delta time (no information provided)\n    ]);\n};\n/** Movie Sample Data Box. Contains the actual frames/samples of the media. */\nexport const mdat = (reserveLargeSize) => ({ type: 'mdat', largeSize: reserveLargeSize });\n/** Free Space Box: A box that designates unused space in the movie data file. */\nexport const free = (size) => ({ type: 'free', size });\n/**\n * Movie Box: Used to specify the information that defines a movie - that is, the information that allows\n * an application to interpret the sample data that is stored elsewhere.\n */\nexport const moov = (muxer) => {\n    return box('moov', undefined, [\n        mvhd(muxer.creationTime, muxer.trackDatas),\n        ...muxer.trackDatas.map(x => trak(x, muxer.creationTime)),\n        muxer.isFragmented ? mvex(muxer.trackDatas) : null,\n        udta(muxer),\n    ]);\n};\n/** Movie Header Box: Used to specify the characteristics of the entire movie, such as timescale and duration. */\nexport const mvhd = (creationTime, trackDatas) => {\n    const duration = Math.max(0, ...trackDatas\n        .map(trackData => (\n    // Round separately to match the edit list\n    Math.max(0, intoTimescale(presentationSpan(trackData), GLOBAL_TIMESCALE)\n        + intoTimescale(trackData.startTimestampOffset ?? 0, GLOBAL_TIMESCALE)))));\n    const nextTrackId = Math.max(0, ...trackDatas.map(x => x.track.id)) + 1;\n    // Conditionally use u64 if u32 isn't enough\n    const needsU64 = !isU32(creationTime) || !isU32(duration);\n    const u32OrU64 = needsU64 ? u64 : u32;\n    return fullBox('mvhd', +needsU64, 0, [\n        u32OrU64(creationTime), // Creation time\n        u32OrU64(creationTime), // Modification time\n        u32(GLOBAL_TIMESCALE), // Timescale\n        u32OrU64(duration), // Duration\n        fixed_16_16(1), // Preferred rate\n        fixed_8_8(1), // Preferred volume\n        Array(10).fill(0), // Reserved\n        matrixToBytes(IDENTITY_MATRIX), // Matrix\n        Array(24).fill(0), // Pre-defined\n        u32(nextTrackId), // Next track ID\n    ]);\n};\n/**\n * Track Box: Defines a single track of a movie. A movie may consist of one or more tracks. Each track is\n * independent of the other tracks in the movie and carries its own temporal and spatial information. Each Track Box\n * contains its associated Media Box.\n */\nexport const trak = (trackData, creationTime) => {\n    const trackMetadata = getTrackMetadata(trackData);\n    const needsEditList = trackData.startTimestampOffset !== null && trackData.startTimestampOffset !== 0;\n    return box('trak', undefined, [\n        tkhd(trackData, creationTime),\n        needsEditList ? edts(trackData) : null,\n        mdia(trackData, creationTime),\n        trackMetadata.name !== undefined\n            ? box('udta', undefined, [\n                box('name', [\n                    ...textEncoder.encode(trackMetadata.name),\n                ]),\n            ])\n            : null,\n    ]);\n};\n/** Track Header Box: Specifies the characteristics of a single track within a movie. */\nexport const tkhd = (trackData, creationTime) => {\n    // Round separately to match the edit list\n    const durationInGlobalTimescale = Math.max(0, intoTimescale(presentationSpan(trackData), GLOBAL_TIMESCALE)\n        + intoTimescale(trackData.startTimestampOffset ?? 0, GLOBAL_TIMESCALE));\n    const needsU64 = !isU32(creationTime) || !isU32(durationInGlobalTimescale);\n    const u32OrU64 = needsU64 ? u64 : u32;\n    let matrix;\n    if (trackData.type === 'video' && trackData.track.metadata.transformationMatrix) {\n        matrix = trackData.track.metadata.transformationMatrix;\n    }\n    else if (trackData.type === 'video') {\n        const { rotation, flip } = trackData.track.metadata;\n        // Rotation is applied before flipping\n        const linear = multiplyMatrices(rotationMatrix(rotation ?? 0), scaleMatrix(flip ? -1 : 1, 1));\n        matrix = centeredTransformationMatrix(linear, trackData.info.width, trackData.info.height);\n    }\n    else {\n        matrix = IDENTITY_MATRIX;\n    }\n    let flags = 0x2; // Track in movie\n    if (trackData.track.metadata.disposition?.default !== false) {\n        flags |= 0x1; // Track enabled\n    }\n    // Set the alternate group based on the track type; this mirror's how FFmpeg does it. A more advanced version would\n    // determine the alternate groups based on the actual track pairability graph. Note that it appears important that\n    // video get assigned to group 0, see https://github.com/Vanilagy/mediabunny/issues/454.\n    const alternateGroup = trackData.type === 'video'\n        ? 0\n        : trackData.type === 'audio'\n            ? 1\n            : trackData.type === 'subtitle'\n                ? 2\n                : assertNever(trackData);\n    return fullBox('tkhd', +needsU64, flags, [\n        u32OrU64(creationTime), // Creation time\n        u32OrU64(creationTime), // Modification time\n        u32(trackData.track.id), // Track ID\n        u32(0), // Reserved\n        u32OrU64(durationInGlobalTimescale), // Duration\n        Array(8).fill(0), // Reserved\n        u16(0), // Layer\n        u16(alternateGroup), // Alternate group\n        fixed_8_8(trackData.type === 'audio' ? 1 : 0), // Volume\n        u16(0), // Reserved\n        matrixToBytes(matrix), // Matrix\n        fixed_16_16(trackData.type === 'video' ? trackData.info.width : 0), // Track width\n        fixed_16_16(trackData.type === 'video' ? trackData.info.height : 0), // Track height\n    ]);\n};\n/** Edit Box: Specifies edits to the track's media. */\nexport const edts = (trackData) => {\n    const offset = trackData.startTimestampOffset;\n    assert(offset !== null);\n    if (offset > 0) {\n        // Positive offset: empty segment at the start, then the full media afterwards\n        const startOffset = intoTimescale(offset, GLOBAL_TIMESCALE);\n        const mediaDuration = intoTimescale(presentationSpan(trackData), GLOBAL_TIMESCALE);\n        const needs64Bits = !isU32(startOffset) || !isU32(mediaDuration);\n        const u32OrU64 = needs64Bits ? u64 : u32;\n        const i32OrI64 = needs64Bits ? i64 : i32;\n        return box('edts', undefined, [\n            fullBox('elst', needs64Bits ? 1 : 0, 0, [\n                u32(2), // Entry count\n                // #1\n                u32OrU64(startOffset), // Segment duration\n                i32OrI64(-1), // Media time\n                fixed_16_16(1), // Media rate\n                // #2\n                u32OrU64(mediaDuration), // Segment duration\n                i32OrI64(0), // Media time\n                fixed_16_16(1), // Media rate\n            ]),\n        ]);\n    }\n    else {\n        // Negative offset: the negative section of the media is trimmed off\n        const mediaTime = intoTimescale(-offset, trackData.timescale);\n        // Not the entire media is visible.\n        // For fragmented files, this value is zero, which simply means \"unknown duration\" in this case. Spec:\n        // \"the segment_duration of this edit may be zero\"\n        const mediaDuration = Math.max(0, intoTimescale(presentationSpan(trackData), GLOBAL_TIMESCALE)\n            + intoTimescale(offset, GLOBAL_TIMESCALE));\n        const needs64Bits = !isI32(mediaTime) || !isU32(mediaDuration);\n        const u32OrU64 = needs64Bits ? u64 : u32;\n        const i32OrI64 = needs64Bits ? i64 : i32;\n        return box('edts', undefined, [\n            fullBox('elst', needs64Bits ? 1 : 0, 0, [\n                u32(1), // Entry count\n                // #1\n                u32OrU64(mediaDuration), // Segment duration\n                i32OrI64(mediaTime), // Media time\n                fixed_16_16(1), // Media rate\n            ]),\n        ]);\n    }\n};\n/** Media Box: Describes and define a track's media type and sample data. */\nexport const mdia = (trackData, creationTime) => box('mdia', undefined, [\n    mdhd(trackData, creationTime),\n    hdlr(true, TRACK_TYPE_TO_COMPONENT_SUBTYPE[trackData.type], TRACK_TYPE_TO_HANDLER_NAME[trackData.type]),\n    minf(trackData),\n]);\n/** Media Header Box: Specifies the characteristics of a media, including timescale and duration. */\nexport const mdhd = (trackData, creationTime) => {\n    // Since _this_ duration represents the raw media duration, edit list offsets are not taken into account here\n    const localDuration = intoTimescale(presentationSpan(trackData), trackData.timescale);\n    const needsU64 = !isU32(creationTime) || !isU32(localDuration);\n    const u32OrU64 = needsU64 ? u64 : u32;\n    return fullBox('mdhd', +needsU64, 0, [\n        u32OrU64(creationTime), // Creation time\n        u32OrU64(creationTime), // Modification time\n        u32(trackData.timescale), // Timescale\n        u32OrU64(localDuration), // Duration\n        u16(getLanguageCodeInt(trackData.track.metadata.languageCode ?? UNDETERMINED_LANGUAGE)), // Language\n        u16(0), // Quality\n    ]);\n};\nconst TRACK_TYPE_TO_COMPONENT_SUBTYPE = {\n    video: 'vide',\n    audio: 'soun',\n    subtitle: 'text',\n};\nconst TRACK_TYPE_TO_HANDLER_NAME = {\n    video: 'MediabunnyVideoHandler',\n    audio: 'MediabunnySoundHandler',\n    subtitle: 'MediabunnyTextHandler',\n};\n/** Handler Reference Box. */\nexport const hdlr = (hasComponentType, handlerType, name, manufacturer = '\\0\\0\\0\\0') => fullBox('hdlr', 0, 0, [\n    hasComponentType ? ascii('mhlr') : u32(0), // Component type\n    ascii(handlerType), // Component subtype\n    ascii(manufacturer), // Component manufacturer\n    u32(0), // Component flags\n    u32(0), // Component flags mask\n    ascii(name, true), // Component name\n]);\n/**\n * Media Information Box: Stores handler-specific information for a track's media data. The media handler uses this\n * information to map from media time to media data and to process the media data.\n */\nexport const minf = (trackData) => box('minf', undefined, [\n    TRACK_TYPE_TO_HEADER_BOX[trackData.type](),\n    dinf(),\n    stbl(trackData),\n]);\n/** Video Media Information Header Box: Defines specific color and graphics mode information. */\nexport const vmhd = () => fullBox('vmhd', 0, 1, [\n    u16(0), // Graphics mode\n    u16(0), // Opcolor R\n    u16(0), // Opcolor G\n    u16(0), // Opcolor B\n]);\n/** Sound Media Information Header Box: Stores the sound media's control information, such as balance. */\nexport const smhd = () => fullBox('smhd', 0, 0, [\n    u16(0), // Balance\n    u16(0), // Reserved\n]);\n/** Null Media Header Box. */\nexport const nmhd = () => fullBox('nmhd', 0, 0);\nconst TRACK_TYPE_TO_HEADER_BOX = {\n    video: vmhd,\n    audio: smhd,\n    subtitle: nmhd,\n};\n/**\n * Data Information Box: Contains information specifying the data handler component that provides access to the\n * media data. The data handler component uses the Data Information Box to interpret the media's data.\n */\nexport const dinf = () => box('dinf', undefined, [\n    dref(),\n]);\n/**\n * Data Reference Box: Contains tabular data that instructs the data handler component how to access the media's data.\n */\nexport const dref = () => fullBox('dref', 0, 0, [\n    u32(1), // Entry count\n], [\n    url(),\n]);\nexport const url = () => fullBox('url ', 0, 1); // Self-reference flag enabled\n/**\n * Sample Table Box: Contains information for converting from media time to sample number to sample location. This box\n * also indicates how to interpret the sample (for example, whether to decompress the video data and, if so, how).\n */\nexport const stbl = (trackData) => {\n    const needsCtts = trackData.compositionTimeOffsetTable.length > 1\n        || trackData.compositionTimeOffsetTable.some(x => x.sampleCompositionTimeOffset !== 0);\n    return box('stbl', undefined, [\n        stsd(trackData),\n        stts(trackData),\n        needsCtts ? ctts(trackData) : null,\n        needsCtts ? cslg(trackData) : null,\n        stsc(trackData),\n        stsz(trackData),\n        stco(trackData),\n        stss(trackData),\n    ]);\n};\n/**\n * Sample Description Box: Stores information that allows you to decode samples in the media. The data stored in the\n * sample description varies, depending on the media type.\n */\nexport const stsd = (trackData) => {\n    let sampleDescription;\n    if (trackData.type === 'video') {\n        sampleDescription = videoSampleDescription(videoCodecToBoxName(trackData.track.source._codec, trackData.info.decoderConfig.codec), trackData);\n    }\n    else if (trackData.type === 'audio') {\n        const boxName = audioCodecToBoxName(trackData.track.source._codec, trackData.info.decoderConfig.codec, trackData.muxer.isQuickTime);\n        assert(boxName);\n        sampleDescription = soundSampleDescription(boxName, trackData);\n    }\n    else if (trackData.type === 'subtitle') {\n        sampleDescription = subtitleSampleDescription(SUBTITLE_CODEC_TO_BOX_NAME[trackData.track.source._codec], trackData);\n    }\n    assert(sampleDescription);\n    return fullBox('stsd', 0, 0, [\n        u32(1), // Entry count\n    ], [\n        sampleDescription,\n    ]);\n};\n/** Video Sample Description Box: Contains information that defines how to interpret video media data. */\nexport const videoSampleDescription = (compressionType, trackData) => box(compressionType, [\n    Array(6).fill(0), // Reserved\n    u16(1), // Data reference index\n    u16(0), // Pre-defined\n    u16(0), // Reserved\n    Array(12).fill(0), // Pre-defined\n    u16(trackData.info.width), // Width\n    u16(trackData.info.height), // Height\n    u32(0x00480000), // Horizontal resolution\n    u32(0x00480000), // Vertical resolution\n    u32(0), // Reserved\n    u16(1), // Frame count\n    // Compressor name\n    u8(VERSIONED_NAME.length), // Weird Pascal-style string\n    ascii(VERSIONED_NAME),\n    Array(31 - VERSIONED_NAME.length).fill(0),\n    u16(trackData.info.hasAlphaChannel ? 32 : 24), // Depth\n    i16(0xffff), // Pre-defined\n], [\n    VIDEO_CODEC_TO_CONFIGURATION_BOX[trackData.track.source._codec]?.(trackData) ?? null,\n    pasp(trackData),\n    colorSpaceIsEmpty(trackData.info.decoderConfig.colorSpace)\n        ? null\n        : colr(trackData),\n    btrt(trackData),\n]);\n/** Bit Rate Box: Signals the average and peak bitrate of the track. */\nexport const btrt = (trackData) => {\n    if (trackData.avgBitrate === 0 && trackData.maxBitrate === 0) {\n        return null;\n    }\n    return box('btrt', [\n        u32(0), // Decoding buffer size (unknown)\n        u32(trackData.maxBitrate), // Max bitrate\n        u32(trackData.avgBitrate), // Average bitrate\n    ]);\n};\n/** Pixel Aspect Ratio Box: Specifies pixel width:height spacing for non-square pixels. */\nexport const pasp = (trackData) => {\n    if (trackData.info.pixelAspectRatio.num === trackData.info.pixelAspectRatio.den) {\n        return null;\n    }\n    return box('pasp', [\n        u32(trackData.info.pixelAspectRatio.num),\n        u32(trackData.info.pixelAspectRatio.den),\n    ]);\n};\n/** Colour Information Box: Specifies the color space of the video. */\nexport const colr = (trackData) => {\n    const colorSpace = trackData.info.decoderConfig.colorSpace;\n    return box('colr', [\n        // Colour type\n        ascii(trackData.muxer.isQuickTime ? 'nclc' : 'nclx'),\n        // Colour primaries\n        u16(colorSpace?.primaries != null ? COLOR_PRIMARIES_MAP[colorSpace.primaries] : 2),\n        // Transfer characteristics\n        u16(colorSpace?.transfer != null ? TRANSFER_CHARACTERISTICS_MAP[colorSpace.transfer] : 2),\n        // Matrix coefficients\n        u16(colorSpace?.matrix != null ? MATRIX_COEFFICIENTS_MAP[colorSpace.matrix] : 2),\n        // Full range flag\n        trackData.muxer.isQuickTime\n            ? [] // Doesn't have it\n            : u8((colorSpace?.fullRange ? 1 : 0) << 7),\n    ]);\n};\n/** AVC Configuration Box: Provides additional information to the decoder. */\nexport const avcC = (trackData) => trackData.info.decoderConfig && box('avcC', [\n    // For AVC, description is an AVCDecoderConfigurationRecord, so nothing else to do here\n    ...toUint8Array(trackData.info.decoderConfig.description),\n]);\n/** HEVC Configuration Box: Provides additional information to the decoder. */\nexport const hvcC = (trackData) => trackData.info.decoderConfig && box('hvcC', [\n    // For HEVC, description is an HEVCDecoderConfigurationRecord, so nothing else to do here\n    ...toUint8Array(trackData.info.decoderConfig.description),\n]);\n/** VP Configuration Box: Provides additional information to the decoder. */\nexport const vpcC = (trackData) => {\n    // Reference: https://www.webmproject.org/vp9/mp4/\n    if (!trackData.info.decoderConfig) {\n        return null;\n    }\n    const decoderConfig = trackData.info.decoderConfig;\n    const parts = decoderConfig.codec.split('.'); // We can derive the required values from the codec string\n    const profile = Number(parts[1]);\n    const level = Number(parts[2]);\n    const bitDepth = Number(parts[3]);\n    const chromaSubsampling = parts[4] ? Number(parts[4]) : 1; // 4:2:0 colocated with luma (0,0)\n    const videoFullRangeFlag = parts[8] ? Number(parts[8]) : Number(decoderConfig.colorSpace?.fullRange ?? 0);\n    const thirdByte = (bitDepth << 4) + (chromaSubsampling << 1) + videoFullRangeFlag;\n    const colourPrimaries = parts[5]\n        ? Number(parts[5])\n        : decoderConfig.colorSpace?.primaries\n            ? COLOR_PRIMARIES_MAP[decoderConfig.colorSpace.primaries]\n            : 1;\n    const transferCharacteristics = parts[6]\n        ? Number(parts[6])\n        : decoderConfig.colorSpace?.transfer\n            ? TRANSFER_CHARACTERISTICS_MAP[decoderConfig.colorSpace.transfer]\n            : 1;\n    const matrixCoefficients = parts[7]\n        ? Number(parts[7])\n        : decoderConfig.colorSpace?.matrix\n            ? MATRIX_COEFFICIENTS_MAP[decoderConfig.colorSpace.matrix]\n            : 1;\n    return fullBox('vpcC', 1, 0, [\n        u8(profile), // Profile\n        u8(level), // Level\n        u8(thirdByte), // Bit depth, chroma subsampling, full range\n        u8(colourPrimaries), // Colour primaries\n        u8(transferCharacteristics), // Transfer characteristics\n        u8(matrixCoefficients), // Matrix coefficients\n        u16(0), // Codec initialization data size\n    ]);\n};\n/** AV1 Configuration Box: Provides additional information to the decoder. */\nexport const av1C = (trackData) => {\n    return box('av1C', generateAv1CodecConfigurationFromCodecString(trackData.info.decoderConfig.codec));\n};\n/** Sound Sample Description Box: Contains information that defines how to interpret sound media data. */\nexport const soundSampleDescription = (compressionType, trackData) => {\n    let version = 0;\n    let contents;\n    let sampleSizeInBits = 16;\n    const isPcmCodec = PCM_AUDIO_CODECS.includes(trackData.track.source._codec);\n    if (isPcmCodec) {\n        const codec = trackData.track.source._codec;\n        const { sampleSize } = parsePcmCodec(codec);\n        sampleSizeInBits = 8 * sampleSize;\n        if (sampleSizeInBits > 16) {\n            version = 1;\n        }\n    }\n    if (trackData.muxer.isQuickTime) {\n        version = 1;\n    }\n    if (version === 0) {\n        contents = [\n            Array(6).fill(0), // Reserved\n            u16(1), // Data reference index\n            u16(version), // Version\n            u16(0), // Revision level\n            u32(0), // Vendor\n            u16(trackData.info.numberOfChannels), // Number of channels\n            u16(sampleSizeInBits), // Sample size (bits)\n            u16(0), // Compression ID\n            u16(0), // Packet size\n            u16(trackData.info.sampleRate < 2 ** 16 ? trackData.info.sampleRate : 0), // Sample rate (upper)\n            u16(0), // Sample rate (lower)\n        ];\n    }\n    else {\n        const compressionId = isPcmCodec ? 0 : -2;\n        contents = [\n            Array(6).fill(0), // Reserved\n            u16(1), // Data reference index\n            u16(version), // Version\n            u16(0), // Revision level\n            u32(0), // Vendor\n            u16(trackData.info.numberOfChannels), // Number of channels\n            u16(Math.min(sampleSizeInBits, 16)), // Sample size (bits)\n            i16(compressionId), // Compression ID\n            u16(0), // Packet size\n            u16(trackData.info.sampleRate < 2 ** 16 ? trackData.info.sampleRate : 0), // Sample rate (upper)\n            u16(0), // Sample rate (lower)\n            isPcmCodec\n                ? [\n                    u32(1), // Samples per packet (must be 1 for uncompressed formats)\n                    u32(sampleSizeInBits / 8), // Bytes per packet\n                    u32(trackData.info.numberOfChannels * sampleSizeInBits / 8), // Bytes per frame\n                ]\n                : [\n                    u32(0), // Samples per packet (don't bother, still works with 0)\n                    u32(0), // Bytes per packet (variable)\n                    u32(0), // Bytes per frame (variable)\n                ],\n            u32(2), // Bytes per sample (constant in FFmpeg)\n        ];\n    }\n    return box(compressionType, contents, [\n        audioCodecToConfigurationBox(trackData.track.source._codec, trackData.muxer.isQuickTime)?.(trackData) ?? null,\n        btrt(trackData),\n    ]);\n};\n/** MPEG-4 Elementary Stream Descriptor Box. */\nexport const esds = (trackData) => {\n    // We build up the bytes in a layered way which reflects the nested structure\n    let objectTypeIndication;\n    switch (trackData.track.source._codec) {\n        case 'aac':\n            {\n                objectTypeIndication = 0x40;\n            }\n            ;\n            break;\n        case 'mp3':\n            {\n                objectTypeIndication = 0x6b;\n            }\n            ;\n            break;\n        case 'vorbis':\n            {\n                objectTypeIndication = 0xdd;\n            }\n            ;\n            break;\n        default: throw new Error(`Unhandled audio codec: ${trackData.track.source._codec}`);\n    }\n    let bytes = [\n        ...u8(objectTypeIndication), // Object type indication\n        ...u8(0x15), // stream type(6bits)=5 audio, flags(2bits)=1\n        ...u24(0), // 24bit buffer size\n        ...u32(trackData.maxBitrate), // max bitrate\n        ...u32(trackData.avgBitrate), // avg bitrate\n    ];\n    if (trackData.info.decoderConfig.description) {\n        const description = toUint8Array(trackData.info.decoderConfig.description);\n        // Add the decoder description to the end\n        bytes = [\n            ...bytes,\n            ...u8(0x05), // TAG(5) = DecoderSpecificInfo\n            ...variableUnsignedInt(description.byteLength),\n            ...description,\n        ];\n    }\n    bytes = [\n        ...u16(1), // ES_ID = 1\n        ...u8(0x00), // flags etc = 0\n        ...u8(0x04), // TAG(4) = ES Descriptor\n        ...variableUnsignedInt(bytes.length),\n        ...bytes,\n        ...u8(0x06), // TAG(6)\n        ...u8(0x01), // length\n        ...u8(0x02), // data\n    ];\n    bytes = [\n        ...u8(0x03), // TAG(3) = Object Descriptor\n        ...variableUnsignedInt(bytes.length),\n        ...bytes,\n    ];\n    return fullBox('esds', 0, 0, bytes);\n};\nexport const wave = (trackData) => {\n    return box('wave', undefined, [\n        frma(trackData),\n        enda(trackData),\n        box('\\x00\\x00\\x00\\x00'), // NULL tag at the end\n    ]);\n};\nexport const frma = (trackData) => {\n    return box('frma', [\n        ascii(audioCodecToBoxName(trackData.track.source._codec, trackData.info.decoderConfig.codec, trackData.muxer.isQuickTime)),\n    ]);\n};\n// This box specifies PCM endianness\nexport const enda = (trackData) => {\n    const { littleEndian } = parsePcmCodec(trackData.track.source._codec);\n    return box('enda', [\n        u16(+littleEndian),\n    ]);\n};\n/** Opus Specific Box. */\nexport const dOps = (trackData) => {\n    let outputChannelCount = trackData.info.numberOfChannels;\n    // Default PreSkip, should be at least 80 milliseconds worth of playback, measured in 48000 Hz samples\n    let preSkip = 3840;\n    let inputSampleRate = trackData.info.sampleRate;\n    let outputGain = 0;\n    let channelMappingFamily = 0;\n    let channelMappingTable = new Uint8Array(0);\n    // Read preskip and from codec private data from the encoder\n    // https://www.rfc-editor.org/rfc/rfc7845#section-5\n    const description = trackData.info.decoderConfig?.description;\n    if (description) {\n        assert(description.byteLength >= 18);\n        const bytes = toUint8Array(description);\n        const header = parseOpusIdentificationHeader(bytes);\n        outputChannelCount = header.outputChannelCount;\n        preSkip = header.preSkip;\n        inputSampleRate = header.inputSampleRate;\n        outputGain = header.outputGain;\n        channelMappingFamily = header.channelMappingFamily;\n        if (header.channelMappingTable) {\n            channelMappingTable = header.channelMappingTable;\n        }\n    }\n    // https://www.opus-codec.org/docs/opus_in_isobmff.html\n    return box('dOps', [\n        u8(0), // Version\n        u8(outputChannelCount), // OutputChannelCount\n        u16(preSkip), // PreSkip\n        u32(inputSampleRate), // InputSampleRate\n        i16(outputGain), // OutputGain\n        u8(channelMappingFamily), // ChannelMappingFamily\n        ...channelMappingTable,\n    ]);\n};\n/** FLAC specific box. */\nexport const dfLa = (trackData) => {\n    const description = trackData.info.decoderConfig?.description;\n    assert(description);\n    const bytes = toUint8Array(description);\n    return fullBox('dfLa', 0, 0, [\n        ...bytes.subarray(4),\n    ]);\n};\n/** PCM Configuration Box, ISO/IEC 23003-5. */\nconst pcmC = (trackData) => {\n    const { littleEndian, sampleSize } = parsePcmCodec(trackData.track.source._codec);\n    const formatFlags = +littleEndian;\n    return fullBox('pcmC', 0, 0, [\n        u8(formatFlags),\n        u8(8 * sampleSize),\n    ]);\n};\n/** AC3SpecificBox */\nconst dac3 = (trackData) => {\n    assert(trackData.info.primingPacket);\n    const frameInfo = parseAc3SyncFrame(trackData.info.primingPacket.data);\n    if (!frameInfo) {\n        throw new Error('Couldn\\'t extract AC-3 frame info from the audio packet. '\n            + 'Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).');\n    }\n    const bytes = new Uint8Array(3);\n    const bitstream = new Bitstream(bytes);\n    bitstream.writeBits(2, frameInfo.fscod);\n    bitstream.writeBits(5, frameInfo.bsid);\n    bitstream.writeBits(3, frameInfo.bsmod);\n    bitstream.writeBits(3, frameInfo.acmod);\n    bitstream.writeBits(1, frameInfo.lfeon);\n    bitstream.writeBits(5, frameInfo.bitRateCode);\n    bitstream.writeBits(5, 0); // reserved\n    return box('dac3', [...bytes]);\n};\n/** EC3SpecificBox */\nconst dec3 = (trackData) => {\n    assert(trackData.info.primingPacket);\n    const frameInfo = parseEac3SyncFrame(trackData.info.primingPacket.data);\n    if (!frameInfo) {\n        throw new Error('Couldn\\'t extract E-AC-3 frame info from the audio packet. '\n            + 'Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).');\n    }\n    // Calculate size\n    let totalBits = 16; // header: data_rate (13) + num_ind_sub (3)\n    for (const sub of frameInfo.substreams) {\n        totalBits += 23; // fixed fields per substream\n        if (sub.numDepSub > 0) {\n            totalBits += 9; // chan_loc\n        }\n        else {\n            totalBits += 1; // reserved\n        }\n    }\n    const size = Math.ceil(totalBits / 8);\n    const bytes = new Uint8Array(size);\n    const bitstream = new Bitstream(bytes);\n    bitstream.writeBits(13, frameInfo.dataRate);\n    bitstream.writeBits(3, frameInfo.substreams.length - 1); // num_ind_sub\n    for (const sub of frameInfo.substreams) {\n        bitstream.writeBits(2, sub.fscod);\n        bitstream.writeBits(5, sub.bsid);\n        bitstream.writeBits(1, 0); // reserved\n        bitstream.writeBits(1, 0); // asvc = 0\n        bitstream.writeBits(3, sub.bsmod);\n        bitstream.writeBits(3, sub.acmod);\n        bitstream.writeBits(1, sub.lfeon);\n        bitstream.writeBits(3, 0); // reserved\n        bitstream.writeBits(4, sub.numDepSub);\n        if (sub.numDepSub > 0) {\n            bitstream.writeBits(9, sub.chanLoc);\n        }\n        else {\n            bitstream.writeBits(1, 0); // reserved\n        }\n    }\n    return box('dec3', [...bytes]);\n};\n/** DTSSpecificBox */\nconst ddts = (trackData) => {\n    assert(trackData.info.primingPacket);\n    const frameInfo = parseDtsFrame(trackData.info.primingPacket.data);\n    if (!frameInfo) {\n        throw new Error('Couldn\\'t extract DTS frame info from the audio packet. '\n            + 'Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.');\n    }\n    return box('ddts', [...buildDtsSpecificBox(frameInfo)]);\n};\nexport const subtitleSampleDescription = (compressionType, trackData) => box(compressionType, [\n    Array(6).fill(0), // Reserved\n    u16(1), // Data reference index\n], [\n    SUBTITLE_CODEC_TO_CONFIGURATION_BOX[trackData.track.source._codec](trackData),\n    btrt(trackData),\n]);\nexport const vttC = (trackData) => box('vttC', [\n    ...textEncoder.encode(trackData.info.config.description),\n]);\nexport const txtC = (textConfig) => fullBox('txtC', 0, 0, [\n    ...textConfig, 0, // Text config (null-terminated)\n]);\n/**\n * Time-To-Sample Box: Stores duration information for a media's samples, providing a mapping from a time in a media\n * to the corresponding data sample. The table is compact, meaning that consecutive samples with the same time delta\n * will be grouped.\n */\nexport const stts = (trackData) => {\n    return fullBox('stts', 0, 0, [\n        u32(trackData.timeToSampleTable.length), // Number of entries\n        trackData.timeToSampleTable.map(x => [\n            u32(x.sampleCount), // Sample count\n            u32(x.sampleDelta), // Sample duration\n        ]),\n    ]);\n};\n/** Sync Sample Box: Identifies the key frames in the media, marking the random access points within a stream. */\nexport const stss = (trackData) => {\n    if (trackData.samples.every(x => x.type === 'key'))\n        return null; // No stss box -> every frame is a key frame\n    const keySamples = [...trackData.samples.entries()].filter(([, sample]) => sample.type === 'key');\n    return fullBox('stss', 0, 0, [\n        u32(keySamples.length), // Number of entries\n        keySamples.map(([index]) => u32(index + 1)), // Sync sample table\n    ]);\n};\n/**\n * Sample-To-Chunk Box: As samples are added to a media, they are collected into chunks that allow optimized data\n * access. A chunk contains one or more samples. Chunks in a media may have different sizes, and the samples within a\n * chunk may have different sizes. The Sample-To-Chunk Box stores chunk information for the samples in a media, stored\n * in a compactly-coded fashion.\n */\nexport const stsc = (trackData) => {\n    return fullBox('stsc', 0, 0, [\n        u32(trackData.compactlyCodedChunkTable.length), // Number of entries\n        trackData.compactlyCodedChunkTable.map(x => [\n            u32(x.firstChunk), // First chunk\n            u32(x.samplesPerChunk), // Samples per chunk\n            u32(1), // Sample description index\n        ]),\n    ]);\n};\n/** Sample Size Box: Specifies the byte size of each sample in the media. */\nexport const stsz = (trackData) => {\n    if (trackData.type === 'audio' && trackData.info.requiresPcmTransformation) {\n        const { sampleSize } = parsePcmCodec(trackData.track.source._codec);\n        // With PCM, every sample has the same size\n        return fullBox('stsz', 0, 0, [\n            u32(sampleSize * trackData.info.numberOfChannels), // Sample size\n            u32(trackData.samples.reduce((acc, x) => acc + intoTimescale(x.duration, trackData.timescale), 0)),\n        ]);\n    }\n    return fullBox('stsz', 0, 0, [\n        u32(0), // Sample size (0 means non-constant size)\n        u32(trackData.samples.length), // Number of entries\n        trackData.samples.map(x => u32(x.size)), // Sample size table\n    ]);\n};\n/** Chunk Offset Box: Identifies the location of each chunk of data in the media's data stream, relative to the file. */\nexport const stco = (trackData) => {\n    if (trackData.finalizedChunks.length > 0 && last(trackData.finalizedChunks).offset >= 2 ** 32) {\n        // If the file is large, use the co64 box\n        return fullBox('co64', 0, 0, [\n            u32(trackData.finalizedChunks.length), // Number of entries\n            trackData.finalizedChunks.map(x => u64(x.offset)), // Chunk offset table\n        ]);\n    }\n    return fullBox('stco', 0, 0, [\n        u32(trackData.finalizedChunks.length), // Number of entries\n        trackData.finalizedChunks.map(x => u32(x.offset)), // Chunk offset table\n    ]);\n};\n/**\n * Composition Time to Sample Box: Stores composition time offset information (PTS-DTS) for a\n * media's samples. The table is compact, meaning that consecutive samples with the same time\n * composition time offset will be grouped.\n */\nexport const ctts = (trackData) => {\n    return fullBox('ctts', 1, 0, [\n        u32(trackData.compositionTimeOffsetTable.length), // Number of entries\n        trackData.compositionTimeOffsetTable.map(x => [\n            u32(x.sampleCount), // Sample count\n            i32(x.sampleCompositionTimeOffset), // Sample offset\n        ]),\n    ]);\n};\n/**\n * Composition to Decode Box: Stores information about the composition and display times of the media samples.\n */\nexport const cslg = (trackData) => {\n    let leastDecodeToDisplayDelta = Infinity;\n    let greatestDecodeToDisplayDelta = -Infinity;\n    let compositionStartTime = Infinity;\n    let compositionEndTime = -Infinity;\n    assert(trackData.compositionTimeOffsetTable.length > 0);\n    assert(trackData.samples.length > 0);\n    for (let i = 0; i < trackData.compositionTimeOffsetTable.length; i++) {\n        const entry = trackData.compositionTimeOffsetTable[i];\n        leastDecodeToDisplayDelta = Math.min(leastDecodeToDisplayDelta, entry.sampleCompositionTimeOffset);\n        greatestDecodeToDisplayDelta = Math.max(greatestDecodeToDisplayDelta, entry.sampleCompositionTimeOffset);\n    }\n    for (let i = 0; i < trackData.samples.length; i++) {\n        const sample = trackData.samples[i];\n        compositionStartTime = Math.min(compositionStartTime, intoTimescale(sample.timestamp, trackData.timescale));\n        compositionEndTime = Math.max(compositionEndTime, intoTimescale(sample.timestamp + sample.duration, trackData.timescale));\n    }\n    const compositionToDtsShift = Math.max(-leastDecodeToDisplayDelta, 0);\n    if (compositionEndTime >= 2 ** 31) {\n        // For very large files, the composition end time can't be represented in i32, so let's just scrap the box in\n        // that case. QuickTime fails to read the file if there's a cslg box with version 1, so that's sadly not an\n        // option.\n        return null;\n    }\n    return fullBox('cslg', 0, 0, [\n        i32(compositionToDtsShift), // Composition to DTS shift\n        i32(leastDecodeToDisplayDelta), // Least decode to display delta\n        i32(greatestDecodeToDisplayDelta), // Greatest decode to display delta\n        i32(compositionStartTime), // Composition start time\n        i32(compositionEndTime), // Composition end time\n    ]);\n};\n/**\n * Movie Extends Box: This box signals to readers that the file is fragmented. Contains a single Track Extends Box\n * for each track in the movie.\n */\nexport const mvex = (trackDatas) => {\n    return box('mvex', undefined, trackDatas.map(trex));\n};\n/** Track Extends Box: Contains the default values used by the movie fragments. */\nexport const trex = (trackData) => {\n    return fullBox('trex', 0, 0, [\n        u32(trackData.track.id), // Track ID\n        u32(1), // Default sample description index\n        u32(0), // Default sample duration\n        u32(0), // Default sample size\n        u32(0), // Default sample flags\n    ]);\n};\n/**\n * Movie Fragment Box: The movie fragments extend the presentation in time. They provide the information that would\n * previously have been\tin the Movie Box.\n */\nexport const moof = (sequenceNumber, trackDatas) => {\n    return box('moof', undefined, [\n        mfhd(sequenceNumber),\n        ...trackDatas.map(traf),\n    ]);\n};\n/** Movie Fragment Header Box: Contains a sequence number as a safety check. */\nexport const mfhd = (sequenceNumber) => {\n    return fullBox('mfhd', 0, 0, [\n        u32(sequenceNumber), // Sequence number\n    ]);\n};\nconst fragmentSampleFlags = (sample) => {\n    let byte1 = 0;\n    let byte2 = 0;\n    const byte3 = 0;\n    const byte4 = 0;\n    const sampleIsDifferenceSample = sample.type === 'delta';\n    byte2 |= +sampleIsDifferenceSample;\n    if (sampleIsDifferenceSample) {\n        byte1 |= 1; // There is redundant coding in this sample\n    }\n    else {\n        byte1 |= 2; // There is no redundant coding in this sample\n    }\n    // Note that there are a lot of other flags to potentially set here, but most are irrelevant / non-necessary\n    return byte1 << 24 | byte2 << 16 | byte3 << 8 | byte4;\n};\n/** Track Fragment Box */\nexport const traf = (trackData) => {\n    return box('traf', undefined, [\n        tfhd(trackData),\n        tfdt(trackData),\n        trun(trackData),\n    ]);\n};\n/** Track Fragment Header Box: Provides a reference to the extended track, and flags. */\nexport const tfhd = (trackData) => {\n    assert(trackData.currentChunk);\n    let tfFlags = 0;\n    tfFlags |= 0x00008; // Default sample duration present\n    tfFlags |= 0x00010; // Default sample size present\n    tfFlags |= 0x00020; // Default sample flags present\n    tfFlags |= 0x20000; // Default base is moof\n    // Prefer the second sample over the first one, as the first one is a sync sample and therefore the \"odd one out\"\n    const referenceSample = trackData.currentChunk.samples[1] ?? trackData.currentChunk.samples[0];\n    const referenceSampleInfo = {\n        duration: referenceSample.timescaleUnitsToNextSample,\n        size: referenceSample.size,\n        flags: fragmentSampleFlags(referenceSample),\n    };\n    return fullBox('tfhd', 0, tfFlags, [\n        u32(trackData.track.id), // Track ID\n        u32(referenceSampleInfo.duration), // Default sample duration\n        u32(referenceSampleInfo.size), // Default sample size\n        u32(referenceSampleInfo.flags), // Default sample flags\n    ]);\n};\n/**\n * Track Fragment Decode Time Box: Provides the absolute decode time of the first sample of the fragment. This is\n * useful for performing random access on the media file.\n */\nexport const tfdt = (trackData) => {\n    assert(trackData.currentChunk);\n    return fullBox('tfdt', 1, 0, [\n        u64(intoTimescale(trackData.currentChunk.startTimestamp, trackData.timescale)), // Base Media Decode Time\n    ]);\n};\n/** Track Run Box: Specifies a run of contiguous samples for a given track. */\nexport const trun = (trackData) => {\n    assert(trackData.currentChunk);\n    const allSampleDurations = trackData.currentChunk.samples.map(x => x.timescaleUnitsToNextSample);\n    const allSampleSizes = trackData.currentChunk.samples.map(x => x.size);\n    const allSampleFlags = trackData.currentChunk.samples.map(fragmentSampleFlags);\n    const allSampleCompositionTimeOffsets = trackData.currentChunk.samples\n        .map(x => intoTimescale(x.timestamp - x.decodeTimestamp, trackData.timescale));\n    const uniqueSampleDurations = new Set(allSampleDurations);\n    const uniqueSampleSizes = new Set(allSampleSizes);\n    const uniqueSampleFlags = new Set(allSampleFlags);\n    const uniqueSampleCompositionTimeOffsets = new Set(allSampleCompositionTimeOffsets);\n    const firstSampleFlagsPresent = uniqueSampleFlags.size === 2 && allSampleFlags[0] !== allSampleFlags[1];\n    const sampleDurationPresent = uniqueSampleDurations.size > 1;\n    const sampleSizePresent = uniqueSampleSizes.size > 1;\n    const sampleFlagsPresent = !firstSampleFlagsPresent && uniqueSampleFlags.size > 1;\n    const sampleCompositionTimeOffsetsPresent = uniqueSampleCompositionTimeOffsets.size > 1 || [...uniqueSampleCompositionTimeOffsets].some(x => x !== 0);\n    let flags = 0;\n    flags |= 0x0001; // Data offset present\n    flags |= 0x0004 * +firstSampleFlagsPresent; // First sample flags present\n    flags |= 0x0100 * +sampleDurationPresent; // Sample duration present\n    flags |= 0x0200 * +sampleSizePresent; // Sample size present\n    flags |= 0x0400 * +sampleFlagsPresent; // Sample flags present\n    flags |= 0x0800 * +sampleCompositionTimeOffsetsPresent; // Sample composition time offsets present\n    return fullBox('trun', 1, flags, [\n        u32(trackData.currentChunk.samples.length), // Sample count\n        u32(trackData.currentChunk.offset - trackData.currentChunk.moofOffset || 0), // Data offset\n        firstSampleFlagsPresent ? u32(allSampleFlags[0]) : [],\n        trackData.currentChunk.samples.map((_, i) => [\n            sampleDurationPresent ? u32(allSampleDurations[i]) : [], // Sample duration\n            sampleSizePresent ? u32(allSampleSizes[i]) : [], // Sample size\n            sampleFlagsPresent ? u32(allSampleFlags[i]) : [], // Sample flags\n            // Sample composition time offsets\n            sampleCompositionTimeOffsetsPresent ? i32(allSampleCompositionTimeOffsets[i]) : [],\n        ]),\n    ]);\n};\n/**\n * Movie Fragment Random Access Box: For each track, provides pointers to sync samples within the file\n * for random access.\n */\nexport const mfra = (trackDatas) => {\n    return box('mfra', undefined, [\n        ...trackDatas.map(tfra),\n        mfro(),\n    ]);\n};\n/** Track Fragment Random Access Box: Provides pointers to sync samples within the file for random access. */\nexport const tfra = (trackData) => {\n    const version = 1; // Using this version allows us to use 64-bit time and offset values\n    const entries = [];\n    for (const chunk of trackData.finalizedChunks) {\n        const sampleIndex = chunk.samples.findIndex(sample => sample.type === 'key');\n        if (sampleIndex === -1) {\n            // tfra must point to sync samples, so continue here. This should never happen in practice since all\n            // fragments begin with a sync sample for every track anyways.\n            continue;\n        }\n        const sample = chunk.samples[sampleIndex];\n        entries.push([\n            u64(intoTimescale(sample.timestamp, trackData.timescale)), // Time (in presentation time)\n            u64(chunk.moofOffset), // moof offset\n            u32(chunk.trafIndex + 1), // traf number\n            u32(1), // trun number\n            u32(sampleIndex + 1), // Sample number\n        ]);\n    }\n    return fullBox('tfra', version, 0, [\n        u32(trackData.track.id), // Track ID\n        u32(0b111111), // This specifies that traf number, trun number and sample number are 32-bit ints\n        u32(entries.length), // Number of entries\n        entries,\n    ]);\n};\n/**\n * Movie Fragment Random Access Offset Box: Provides the size of the enclosing mfra box. This box can be used by readers\n * to quickly locate the mfra box by searching from the end of the file.\n */\nexport const mfro = () => {\n    return fullBox('mfro', 0, 0, [\n        // This value needs to be overwritten manually from the outside, where the actual size of the enclosing mfra box\n        // is known\n        u32(0), // Size\n    ]);\n};\n/** VTT Empty Cue Box */\nexport const vtte = () => box('vtte');\n/** VTT Cue Box */\nexport const vttc = (payload, timestamp, identifier, settings, sourceId) => box('vttc', undefined, [\n    sourceId !== null ? box('vsid', [i32(sourceId)]) : null,\n    identifier !== null ? box('iden', [...textEncoder.encode(identifier)]) : null,\n    timestamp !== null ? box('ctim', [...textEncoder.encode(formatSubtitleTimestamp(timestamp))]) : null,\n    settings !== null ? box('sttg', [...textEncoder.encode(settings)]) : null,\n    box('payl', [...textEncoder.encode(payload)]),\n]);\n/** VTT Additional Text Box */\nexport const vtta = (notes) => box('vtta', [...textEncoder.encode(notes)]);\n/** User Data Box */\nconst udta = (muxer) => {\n    const boxes = [];\n    const metadataFormat = muxer.format._options.metadataFormat ?? 'auto';\n    const metadataTags = muxer.output._metadataTags;\n    // Depending on the format, metadata tags are written differently\n    if (metadataFormat === 'mdir' || (metadataFormat === 'auto' && !muxer.isQuickTime)) {\n        const metaBox = metaMdir(metadataTags);\n        if (metaBox)\n            boxes.push(metaBox);\n    }\n    else if (metadataFormat === 'mdta') {\n        const metaBox = metaMdta(metadataTags);\n        if (metaBox)\n            boxes.push(metaBox);\n    }\n    else if (metadataFormat === 'udta' || (metadataFormat === 'auto' && muxer.isQuickTime)) {\n        addQuickTimeMetadataTagBoxes(boxes, muxer.output._metadataTags);\n    }\n    if (boxes.length === 0) {\n        return null;\n    }\n    return box('udta', undefined, boxes);\n};\nconst addQuickTimeMetadataTagBoxes = (boxes, tags) => {\n    // https://exiftool.org/TagNames/QuickTime.html (QuickTime UserData Tags)\n    // For QuickTime files, metadata tags are dumped into the udta box\n    for (const { key, value } of keyValueIterator(tags)) {\n        switch (key) {\n            case 'title':\n                {\n                    boxes.push(metadataTagStringBoxShort('©nam', value));\n                }\n                ;\n                break;\n            case 'description':\n                {\n                    boxes.push(metadataTagStringBoxShort('©des', value));\n                }\n                ;\n                break;\n            case 'artist':\n                {\n                    boxes.push(metadataTagStringBoxShort('©ART', value));\n                }\n                ;\n                break;\n            case 'album':\n                {\n                    boxes.push(metadataTagStringBoxShort('©alb', value));\n                }\n                ;\n                break;\n            case 'albumArtist':\n                {\n                    boxes.push(metadataTagStringBoxShort('albr', value));\n                }\n                ;\n                break;\n            case 'genre':\n                {\n                    boxes.push(metadataTagStringBoxShort('©gen', value));\n                }\n                ;\n                break;\n            case 'date':\n                {\n                    boxes.push(metadataTagStringBoxShort('©day', value.toISOString().slice(0, 10)));\n                }\n                ;\n                break;\n            case 'comment':\n                {\n                    boxes.push(metadataTagStringBoxShort('©cmt', value));\n                }\n                ;\n                break;\n            case 'lyrics':\n                {\n                    boxes.push(metadataTagStringBoxShort('©lyr', value));\n                }\n                ;\n                break;\n            case 'raw':\n                {\n                    // Handled later\n                }\n                ;\n                break;\n            case 'discNumber':\n            case 'discsTotal':\n            case 'trackNumber':\n            case 'tracksTotal':\n            case 'beatsPerMinute':\n            case 'images':\n                {\n                    // Not written for QuickTime (common Apple L)\n                }\n                ;\n                break;\n            default: assertNever(key);\n        }\n    }\n    if (tags.raw) {\n        for (const key in tags.raw) {\n            const value = tags.raw[key];\n            if (value == null || key.length !== 4 || boxes.some(x => x.type === key)) {\n                continue;\n            }\n            if (typeof value === 'string') {\n                boxes.push(metadataTagStringBoxShort(key, value));\n            }\n            else if (value instanceof Uint8Array) {\n                boxes.push(box(key, Array.from(value)));\n            }\n        }\n    }\n};\nconst metadataTagStringBoxShort = (name, value) => {\n    const encoded = textEncoder.encode(value);\n    return box(name, [\n        u16(encoded.length),\n        u16(getLanguageCodeInt('und')),\n        Array.from(encoded),\n    ]);\n};\nconst DATA_BOX_MIME_TYPE_MAP = {\n    'image/jpeg': 13,\n    'image/png': 14,\n    'image/bmp': 27,\n};\n/**\n * Generates key-value metadata for inclusion in the \"meta\" box.\n */\nconst generateMetadataPairs = (tags, isMdta) => {\n    const pairs = [];\n    // https://exiftool.org/TagNames/QuickTime.html (QuickTime ItemList Tags)\n    // This is the metadata format used for MP4 files\n    for (const { key, value } of keyValueIterator(tags)) {\n        switch (key) {\n            case 'title':\n                {\n                    pairs.push({ key: isMdta ? 'title' : '©nam', value: dataStringBoxLong(value) });\n                }\n                ;\n                break;\n            case 'description':\n                {\n                    pairs.push({ key: isMdta ? 'description' : '©des', value: dataStringBoxLong(value) });\n                }\n                ;\n                break;\n            case 'artist':\n                {\n                    pairs.push({ key: isMdta ? 'artist' : '©ART', value: dataStringBoxLong(value) });\n                }\n                ;\n                break;\n            case 'album':\n                {\n                    pairs.push({ key: isMdta ? 'album' : '©alb', value: dataStringBoxLong(value) });\n                }\n                ;\n                break;\n            case 'albumArtist':\n                {\n                    pairs.push({ key: isMdta ? 'album_artist' : 'aART', value: dataStringBoxLong(value) });\n                }\n                ;\n                break;\n            case 'comment':\n                {\n                    pairs.push({ key: isMdta ? 'comment' : '©cmt', value: dataStringBoxLong(value) });\n                }\n                ;\n                break;\n            case 'genre':\n                {\n                    pairs.push({ key: isMdta ? 'genre' : '©gen', value: dataStringBoxLong(value) });\n                }\n                ;\n                break;\n            case 'beatsPerMinute':\n                {\n                    if (!isMdta) {\n                        pairs.push({ key: 'tmpo', value: box('data', [\n                                u32(21), // Type indicator\n                                u32(0), // Locale indicator\n                                u16(value),\n                            ]) });\n                    }\n                }\n                ;\n                break;\n            case 'lyrics':\n                {\n                    pairs.push({ key: isMdta ? 'lyrics' : '©lyr', value: dataStringBoxLong(value) });\n                }\n                ;\n                break;\n            case 'date':\n                {\n                    pairs.push({\n                        key: isMdta ? 'date' : '©day',\n                        value: dataStringBoxLong(value.toISOString().slice(0, 10)),\n                    });\n                }\n                ;\n                break;\n            case 'images':\n                {\n                    for (const image of value) {\n                        if (image.kind !== 'coverFront') {\n                            continue;\n                        }\n                        pairs.push({ key: 'covr', value: box('data', [\n                                u32(DATA_BOX_MIME_TYPE_MAP[image.mimeType] ?? 0), // Type indicator\n                                u32(0), // Locale indicator\n                                Array.from(image.data), // Kinda slow, hopefully temp\n                            ]) });\n                    }\n                }\n                ;\n                break;\n            case 'trackNumber':\n                {\n                    if (isMdta) {\n                        const string = tags.tracksTotal !== undefined\n                            ? `${value}/${tags.tracksTotal}`\n                            : value.toString();\n                        pairs.push({ key: 'track', value: dataStringBoxLong(string) });\n                    }\n                    else {\n                        pairs.push({ key: 'trkn', value: box('data', [\n                                u32(0), // 8 bytes empty\n                                u32(0),\n                                u16(0), // Empty\n                                u16(value),\n                                u16(tags.tracksTotal ?? 0),\n                                u16(0), // Empty\n                            ]) });\n                    }\n                }\n                ;\n                break;\n            case 'discNumber':\n                {\n                    if (!isMdta) {\n                        // Only written for mdir\n                        pairs.push({ key: 'disc', value: box('data', [\n                                u32(0), // 8 bytes empty\n                                u32(0),\n                                u16(0), // Empty\n                                u16(value),\n                                u16(tags.discsTotal ?? 0),\n                                u16(0), // Empty\n                            ]) });\n                    }\n                }\n                ;\n                break;\n            case 'tracksTotal':\n            case 'discsTotal':\n                {\n                    // These are included with 'trackNumber' and 'discNumber' respectively\n                }\n                ;\n                break;\n            case 'raw':\n                {\n                    // Handled later\n                }\n                ;\n                break;\n            default: assertNever(key);\n        }\n    }\n    if (tags.raw) {\n        for (const key in tags.raw) {\n            const value = tags.raw[key];\n            if (value == null || (!isMdta && key.length !== 4) || pairs.some(x => x.key === key)) {\n                continue;\n            }\n            if (typeof value === 'string') {\n                pairs.push({ key, value: dataStringBoxLong(value) });\n            }\n            else if (value instanceof Uint8Array) {\n                pairs.push({ key, value: box('data', [\n                        u32(0), // Type indicator\n                        u32(0), // Locale indicator\n                        Array.from(value),\n                    ]) });\n            }\n            else if (value instanceof RichImageData) {\n                pairs.push({ key, value: box('data', [\n                        u32(DATA_BOX_MIME_TYPE_MAP[value.mimeType] ?? 0), // Type indicator\n                        u32(0), // Locale indicator\n                        Array.from(value.data), // Kinda slow, hopefully temp\n                    ]) });\n            }\n        }\n    }\n    return pairs;\n};\n/** Metadata Box (mdir format) */\nconst metaMdir = (tags) => {\n    const pairs = generateMetadataPairs(tags, false);\n    if (pairs.length === 0) {\n        return null;\n    }\n    // fullBox format\n    return fullBox('meta', 0, 0, undefined, [\n        hdlr(false, 'mdir', '', 'appl'), // mdir handler\n        box('ilst', undefined, pairs.map(pair => box(pair.key, undefined, [pair.value]))), // Item list without keys box\n    ]);\n};\n/** Metadata Box (mdta format with keys box) */\nconst metaMdta = (tags) => {\n    const pairs = generateMetadataPairs(tags, true);\n    if (pairs.length === 0) {\n        return null;\n    }\n    // box without version and flags\n    return box('meta', undefined, [\n        hdlr(false, 'mdta', ''), // mdta handler\n        fullBox('keys', 0, 0, [\n            u32(pairs.length),\n        ], pairs.map(pair => box('mdta', [\n            ...textEncoder.encode(pair.key),\n        ]))),\n        box('ilst', undefined, pairs.map((pair, i) => {\n            const boxName = String.fromCharCode(...u32(i + 1));\n            return box(boxName, undefined, [pair.value]);\n        })),\n    ]);\n};\nconst dataStringBoxLong = (value) => {\n    return box('data', [\n        u32(1), // Type indicator (UTF-8)\n        u32(0), // Locale indicator\n        ...textEncoder.encode(value),\n    ]);\n};\nconst videoCodecToBoxName = (codec, fullCodecString) => {\n    switch (codec) {\n        case 'avc': return fullCodecString.startsWith('avc3') ? 'avc3' : 'avc1';\n        case 'hevc': return 'hvc1';\n        case 'vp8': return 'vp08';\n        case 'vp9': return 'vp09';\n        case 'av1': return 'av01';\n        case 'prores': return fullCodecString;\n    }\n};\nconst VIDEO_CODEC_TO_CONFIGURATION_BOX = {\n    avc: avcC,\n    hevc: hvcC,\n    vp8: vpcC,\n    vp9: vpcC,\n    av1: av1C,\n    prores: null,\n};\nconst audioCodecToBoxName = (codec, fullCodecString, isQuickTime) => {\n    switch (codec) {\n        case 'aac': return 'mp4a';\n        case 'mp3': return 'mp4a';\n        case 'opus': return 'Opus';\n        case 'vorbis': return 'mp4a';\n        case 'flac': return 'fLaC';\n        case 'ulaw': return 'ulaw';\n        case 'alaw': return 'alaw';\n        case 'pcm-u8': return 'raw ';\n        case 'pcm-s8': return 'sowt';\n        case 'ac3': return 'ac-3';\n        case 'eac3': return 'ec-3';\n        case 'dts': return fullCodecString;\n    }\n    // Logic diverges here\n    if (isQuickTime) {\n        switch (codec) {\n            case 'pcm-s16': return 'sowt';\n            case 'pcm-s16be': return 'twos';\n            case 'pcm-s24': return 'in24';\n            case 'pcm-s24be': return 'in24';\n            case 'pcm-s32': return 'in32';\n            case 'pcm-s32be': return 'in32';\n            case 'pcm-f32': return 'fl32';\n            case 'pcm-f32be': return 'fl32';\n            case 'pcm-f64': return 'fl64';\n            case 'pcm-f64be': return 'fl64';\n        }\n    }\n    else {\n        switch (codec) {\n            case 'pcm-s16': return 'ipcm';\n            case 'pcm-s16be': return 'ipcm';\n            case 'pcm-s24': return 'ipcm';\n            case 'pcm-s24be': return 'ipcm';\n            case 'pcm-s32': return 'ipcm';\n            case 'pcm-s32be': return 'ipcm';\n            case 'pcm-f32': return 'fpcm';\n            case 'pcm-f32be': return 'fpcm';\n            case 'pcm-f64': return 'fpcm';\n            case 'pcm-f64be': return 'fpcm';\n        }\n    }\n};\nconst audioCodecToConfigurationBox = (codec, isQuickTime) => {\n    switch (codec) {\n        case 'aac': return esds;\n        case 'mp3': return esds;\n        case 'opus': return dOps;\n        case 'vorbis': return esds;\n        case 'flac': return dfLa;\n        case 'ac3': return dac3;\n        case 'eac3': return dec3;\n        case 'dts': return ddts;\n    }\n    // Logic diverges here\n    if (isQuickTime) {\n        switch (codec) {\n            case 'pcm-s24': return wave;\n            case 'pcm-s24be': return wave;\n            case 'pcm-s32': return wave;\n            case 'pcm-s32be': return wave;\n            case 'pcm-f32': return wave;\n            case 'pcm-f32be': return wave;\n            case 'pcm-f64': return wave;\n            case 'pcm-f64be': return wave;\n        }\n    }\n    else {\n        switch (codec) {\n            case 'pcm-s16': return pcmC;\n            case 'pcm-s16be': return pcmC;\n            case 'pcm-s24': return pcmC;\n            case 'pcm-s24be': return pcmC;\n            case 'pcm-s32': return pcmC;\n            case 'pcm-s32be': return pcmC;\n            case 'pcm-f32': return pcmC;\n            case 'pcm-f32be': return pcmC;\n            case 'pcm-f64': return pcmC;\n            case 'pcm-f64be': return pcmC;\n        }\n    }\n    return null;\n};\nconst SUBTITLE_CODEC_TO_BOX_NAME = {\n    webvtt: 'wvtt',\n};\nconst SUBTITLE_CODEC_TO_CONFIGURATION_BOX = {\n    webvtt: vttC,\n};\nconst getLanguageCodeInt = (code) => {\n    assert(code.length === 3);\n    ;\n    let language = 0;\n    for (let i = 0; i < 3; i++) {\n        language <<= 5;\n        language += code.charCodeAt(i) - 0x60;\n    }\n    return language;\n};\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { assert } from './misc.js';\nexport class Writer {\n    constructor(target, isMonotonic) {\n        this.finalized = false;\n        this.started = false;\n        this.pos = 0;\n        this.trackedWrites = null;\n        this.trackedStart = -1;\n        this.trackedEnd = -1;\n        if (target._writerAcquired) {\n            throw new Error('Can\\'t have multiple Writers for the same Target.');\n        }\n        this.target = target;\n        target._setMonotonicity(isMonotonic);\n        target._writerAcquired = true;\n    }\n    start() {\n        assert(!this.started);\n        this.target._start();\n        this.started = true;\n    }\n    /** Writes the given data to the target, at the current position. */\n    write(data) {\n        assert(this.started && !this.finalized);\n        this.maybeTrackWrites(data);\n        this.target._write(data, this.pos);\n        this.pos += data.byteLength;\n    }\n    /** Sets the current position for future writes to a new one. */\n    seek(newPos) {\n        this.pos = newPos;\n    }\n    /** Returns the current position. */\n    getPos() {\n        return this.pos;\n    }\n    /** Signals to the writer that it may be time to flush. */\n    async flush() {\n        assert(this.started && !this.finalized);\n        return this.target._flush();\n    }\n    /** Called after muxing has finished. */\n    async finalize() {\n        assert(this.started && !this.finalized);\n        await this.target._finalize();\n        this.finalized = true;\n    }\n    maybeTrackWrites(data) {\n        if (!this.trackedWrites) {\n            return;\n        }\n        // Handle negative relative write positions\n        let pos = this.getPos();\n        if (pos < this.trackedStart) {\n            if (pos + data.byteLength <= this.trackedStart) {\n                return;\n            }\n            data = data.subarray(this.trackedStart - pos);\n            pos = 0;\n        }\n        const neededSize = pos + data.byteLength - this.trackedStart;\n        let newLength = this.trackedWrites.byteLength;\n        while (newLength < neededSize) {\n            newLength *= 2;\n        }\n        // Check if we need to resize the buffer\n        if (newLength !== this.trackedWrites.byteLength) {\n            const copy = new Uint8Array(newLength);\n            copy.set(this.trackedWrites, 0);\n            this.trackedWrites = copy;\n        }\n        this.trackedWrites.set(data, pos - this.trackedStart);\n        this.trackedEnd = Math.max(this.trackedEnd, pos + data.byteLength);\n    }\n    startTrackingWrites() {\n        this.trackedWrites = new Uint8Array(2 ** 10);\n        this.trackedStart = this.getPos();\n        this.trackedEnd = this.trackedStart;\n    }\n    stopTrackingWrites() {\n        if (!this.trackedWrites) {\n            throw new Error('Internal error: Can\\'t get tracked writes since nothing was tracked.');\n        }\n        const slice = this.trackedWrites.subarray(0, this.trackedEnd - this.trackedStart);\n        const result = {\n            data: slice,\n            start: this.trackedStart,\n            end: this.trackedEnd,\n        };\n        this.trackedWrites = null;\n        return result;\n    }\n}\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport * as nodeAlias from './node.js';\nimport { assert, EventEmitter, isWebKit } from './misc.js';\nconst node = typeof nodeAlias !== 'undefined'\n    ? nodeAlias // Aliasing it prevents some bundler warnings\n    : undefined;\n/**\n * Base class for targets, specifying where output files are written.\n * @group Output targets\n * @public\n */\nexport class Target extends EventEmitter {\n    constructor() {\n        super(...arguments);\n        /** @internal */\n        this._writerAcquired = false;\n        /** @internal */\n        this._monotonicity = null; // null = unknown\n        /**\n         * Called each time data is written to the target. Will be called with the byte range into which data was written.\n         *\n         * Use this callback to track the size of the output file as it grows. But be warned, this function is chatty and\n         * gets called *extremely* often.\n         *\n         * @deprecated Use `target.on('write', ({ start, end }) => ...)` instead.\n         */\n        this.onwrite = null;\n    }\n    /** @internal */\n    _setMonotonicity(monotonicity) {\n        if (this._monotonicity !== false) {\n            this._monotonicity = monotonicity;\n        }\n        else {\n            // Once false, it's locked\n        }\n    }\n    /** @internal */\n    _dispatchWrite(start, end) {\n        // eslint-disable-next-line @typescript-eslint/no-deprecated\n        this.onwrite?.(start, end);\n        this._emit('write', { start, end });\n    }\n    /**\n     * Returns a new {@link RangedTarget} that writes data to this target using the given offset.\n     *\n     * Useful for writing a file into a section of a larger file.\n     */\n    slice(offset) {\n        if (!Number.isInteger(offset) || offset < 0) {\n            throw new TypeError('offset must be a non-negative integer.');\n        }\n        return new RangedTarget(this, offset);\n    }\n}\nconst ARRAY_BUFFER_INITIAL_SIZE = 2 ** 16;\nconst ARRAY_BUFFER_MAX_SIZE = 2 ** 32;\n/**\n * A target that writes data directly into an ArrayBuffer in memory. Great for performance, but not suitable for very\n * large files. The buffer will be available once the output has been finalized.\n * @group Output targets\n * @public\n */\nexport class BufferTarget extends Target {\n    /** Creates a new {@link BufferTarget}. The buffer holding the data will be created and managed internally. */\n    constructor(options = {}) {\n        super();\n        /** Stores the final output buffer. Until the output is finalized, this will be `null`. */\n        this.buffer = null;\n        /** @internal */\n        this._maxPos = 0;\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('BufferTarget options, when provided, must be an object.');\n        }\n        if (options.onFinalize !== undefined && typeof options.onFinalize !== 'function') {\n            throw new TypeError('options.onFinalize, when provided, must be a function.');\n        }\n        this._options = options;\n        this._supportsResize = 'resize' in new ArrayBuffer(0);\n        if (this._supportsResize) {\n            try {\n                // @ts-expect-error Don't want to bump \"lib\" in tsconfig\n                this._buffer = new ArrayBuffer(ARRAY_BUFFER_INITIAL_SIZE, { maxByteLength: ARRAY_BUFFER_MAX_SIZE });\n            }\n            catch {\n                this._buffer = new ArrayBuffer(ARRAY_BUFFER_INITIAL_SIZE);\n                this._supportsResize = false;\n            }\n        }\n        else {\n            this._buffer = new ArrayBuffer(ARRAY_BUFFER_INITIAL_SIZE);\n        }\n        this._bytes = new Uint8Array(this._buffer);\n    }\n    /** @internal */\n    _ensureSize(size) {\n        let newLength = this._buffer.byteLength;\n        while (newLength < size)\n            newLength *= 2;\n        if (newLength === this._buffer.byteLength)\n            return;\n        if (newLength > ARRAY_BUFFER_MAX_SIZE) {\n            throw new Error(`ArrayBuffer exceeded maximum size of ${ARRAY_BUFFER_MAX_SIZE} bytes. Please consider using another`\n                + ` target.`);\n        }\n        if (this._supportsResize) {\n            // Use resize if it exists\n            // @ts-expect-error Don't want to bump \"lib\" in tsconfig\n            // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n            this._buffer.resize(newLength);\n            // The Uint8Array scales automatically\n        }\n        else {\n            const newBuffer = new ArrayBuffer(newLength);\n            const newBytes = new Uint8Array(newBuffer);\n            newBytes.set(this._bytes, 0);\n            this._buffer = newBuffer;\n            this._bytes = newBytes;\n        }\n    }\n    /** @internal */\n    _start() { }\n    /** @internal */\n    _write(data, pos) {\n        this._ensureSize(pos + data.byteLength);\n        this._bytes.set(data, pos);\n        this._maxPos = Math.max(this._maxPos, pos + data.byteLength);\n        this._dispatchWrite(pos, pos + data.byteLength);\n    }\n    /** @internal */\n    async _flush() { }\n    /** @internal */\n    async _finalize() {\n        this.buffer = this._buffer.slice(0, this._maxPos);\n        if (this._options.onFinalize) {\n            await this._options.onFinalize(this.buffer);\n        }\n        this._emit('finalized');\n    }\n    /** @internal */\n    async _close() { }\n    /** @internal */\n    _getSlice(start, end) {\n        return this._bytes.slice(start, end);\n    }\n}\nconst DEFAULT_CHUNK_SIZE = 2 ** 24;\nconst MAX_CHUNKS_AT_ONCE = 2;\n/**\n * This target writes data to a [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream),\n * making it a general-purpose target for writing data anywhere. It is also compatible with\n * [`FileSystemWritableFileStream`](https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream) for\n * use with the [File System Access API](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API). The\n * `WritableStream` can also apply backpressure, which will propagate to the output and throttle the encoders.\n * @group Output targets\n * @public\n */\nexport class StreamTarget extends Target {\n    /** Creates a new {@link StreamTarget} which writes to the specified `writable`. */\n    constructor(writable, options = {}) {\n        super();\n        /** @internal */\n        this._sections = [];\n        /** @internal */\n        this._lastWriteEnd = 0;\n        /** @internal */\n        this._lastFlushEnd = 0;\n        /** @internal */\n        this._streamWriter = null;\n        /** @internal */\n        this._writeError = null;\n        /**\n         * The data is divided up into fixed-size chunks, whose contents are first filled in RAM and then flushed out.\n         * A chunk is flushed if all of its contents have been written.\n         */\n        /** @internal */\n        this._chunks = [];\n        if (!(writable instanceof WritableStream)) {\n            throw new TypeError('StreamTarget requires a WritableStream instance.');\n        }\n        if (options != null && typeof options !== 'object') {\n            throw new TypeError('StreamTarget options, when provided, must be an object.');\n        }\n        if (options.chunked !== undefined && typeof options.chunked !== 'boolean') {\n            throw new TypeError('options.chunked, when provided, must be a boolean.');\n        }\n        if (options.chunkSize !== undefined && (!Number.isInteger(options.chunkSize) || options.chunkSize < 1024)) {\n            throw new TypeError('options.chunkSize, when provided, must be an integer and not smaller than 1024.');\n        }\n        this._writable = writable;\n        this._options = options;\n        this._chunked = options.chunked ?? false;\n        this._chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE;\n    }\n    /** @internal */\n    _start() {\n        this._streamWriter = this._writable.getWriter();\n    }\n    /** @internal */\n    _write(data, pos) {\n        if (pos > this._lastWriteEnd) {\n            const paddingBytesNeeded = pos - this._lastWriteEnd;\n            this._write(new Uint8Array(paddingBytesNeeded), this._lastWriteEnd);\n        }\n        this._sections.push({\n            data: data.slice(),\n            start: pos,\n        });\n        this._lastWriteEnd = Math.max(this._lastWriteEnd, pos + data.byteLength);\n        this._dispatchWrite(pos, pos + data.byteLength);\n    }\n    /** @internal */\n    async _flush() {\n        if (this._writeError !== null) {\n            // eslint-disable-next-line @typescript-eslint/only-throw-error\n            throw this._writeError;\n        }\n        assert(this._streamWriter);\n        if (this._sections.length === 0) {\n            return;\n        }\n        const chunks = [];\n        const sorted = [...this._sections].sort((a, b) => a.start - b.start);\n        chunks.push({\n            start: sorted[0].start,\n            size: sorted[0].data.byteLength,\n        });\n        // Figure out how many contiguous chunks we have\n        for (let i = 1; i < sorted.length; i++) {\n            const lastChunk = chunks[chunks.length - 1];\n            const section = sorted[i];\n            if (section.start <= lastChunk.start + lastChunk.size) {\n                lastChunk.size = Math.max(lastChunk.size, section.start + section.data.byteLength - lastChunk.start);\n            }\n            else {\n                chunks.push({\n                    start: section.start,\n                    size: section.data.byteLength,\n                });\n            }\n        }\n        for (const chunk of chunks) {\n            chunk.data = new Uint8Array(chunk.size);\n            // Make sure to write the data in the correct order for correct overwriting\n            for (const section of this._sections) {\n                // Check if the section is in the chunk\n                if (chunk.start <= section.start && section.start < chunk.start + chunk.size) {\n                    chunk.data.set(section.data, section.start - chunk.start);\n                }\n            }\n            if (this._streamWriter.desiredSize !== null && this._streamWriter.desiredSize <= 0) {\n                await this._streamWriter.ready; // Allow the writer to apply backpressure\n            }\n            if (this._chunked) {\n                // Let's first gather the data into bigger chunks before writing it\n                this._writeDataIntoChunks(chunk.data, chunk.start);\n                this._tryToFlushChunks();\n            }\n            else {\n                if (this._monotonicity === true && chunk.start !== this._lastFlushEnd) {\n                    throw new Error('Internal error: Monotonicity violation.');\n                }\n                void this._streamWriter.write({\n                    type: 'write',\n                    data: chunk.data,\n                    position: chunk.start,\n                }).catch((error) => {\n                    this._writeError ??= error;\n                });\n                this._lastFlushEnd = chunk.start + chunk.data.byteLength;\n            }\n        }\n        this._sections.length = 0;\n    }\n    /** @internal */\n    _writeDataIntoChunks(data, position) {\n        // First, find the chunk to write the data into, or create one if none exists\n        let chunkIndex = this._chunks.findIndex(x => x.start <= position && position < x.start + this._chunkSize);\n        if (chunkIndex === -1)\n            chunkIndex = this._createChunk(position);\n        const chunk = this._chunks[chunkIndex];\n        // Figure out how much to write to the chunk, and then write to the chunk\n        const relativePosition = position - chunk.start;\n        const toWrite = data.subarray(0, Math.min(this._chunkSize - relativePosition, data.byteLength));\n        chunk.data.set(toWrite, relativePosition);\n        // Create a section describing the region of data that was just written to\n        const section = {\n            start: relativePosition,\n            end: relativePosition + toWrite.byteLength,\n        };\n        this._insertSectionIntoChunk(chunk, section);\n        // Queue chunk for flushing to target if it has been fully written to\n        if (chunk.written[0].start === 0 && chunk.written[0].end === this._chunkSize) {\n            chunk.shouldFlush = true;\n        }\n        // Make sure we don't hold too many chunks in memory at once to keep memory usage down\n        if (this._chunks.length > MAX_CHUNKS_AT_ONCE) {\n            // Flush all but the last chunk\n            for (let i = 0; i < this._chunks.length - 1; i++) {\n                this._chunks[i].shouldFlush = true;\n            }\n            this._tryToFlushChunks();\n        }\n        // If the data didn't fit in one chunk, recurse with the remaining data\n        if (toWrite.byteLength < data.byteLength) {\n            this._writeDataIntoChunks(data.subarray(toWrite.byteLength), position + toWrite.byteLength);\n        }\n    }\n    /** @internal */\n    _insertSectionIntoChunk(chunk, section) {\n        let low = 0;\n        let high = chunk.written.length - 1;\n        let index = -1;\n        // Do a binary search to find the last section with a start not larger than `section`'s start\n        while (low <= high) {\n            const mid = Math.floor(low + (high - low + 1) / 2);\n            if (chunk.written[mid].start <= section.start) {\n                low = mid + 1;\n                index = mid;\n            }\n            else {\n                high = mid - 1;\n            }\n        }\n        // Insert the new section\n        chunk.written.splice(index + 1, 0, section);\n        if (index === -1 || chunk.written[index].end < section.start)\n            index++;\n        // Merge overlapping sections\n        while (index < chunk.written.length - 1 && chunk.written[index].end >= chunk.written[index + 1].start) {\n            chunk.written[index].end = Math.max(chunk.written[index].end, chunk.written[index + 1].end);\n            chunk.written.splice(index + 1, 1);\n        }\n    }\n    /** @internal */\n    _createChunk(includesPosition) {\n        const start = Math.floor(includesPosition / this._chunkSize) * this._chunkSize;\n        const chunk = {\n            start,\n            data: new Uint8Array(this._chunkSize),\n            written: [],\n            shouldFlush: false,\n        };\n        this._chunks.push(chunk);\n        this._chunks.sort((a, b) => a.start - b.start);\n        return this._chunks.indexOf(chunk);\n    }\n    /** @internal */\n    _tryToFlushChunks(force = false) {\n        assert(this._streamWriter);\n        for (let i = 0; i < this._chunks.length; i++) {\n            const chunk = this._chunks[i];\n            if (!chunk.shouldFlush && !force)\n                continue;\n            for (const section of chunk.written) {\n                const position = chunk.start + section.start;\n                if (this._monotonicity === true && position !== this._lastFlushEnd) {\n                    throw new Error('Internal error: Monotonicity violation.');\n                }\n                const isPartialView = section.start !== 0 || section.end !== chunk.data.byteLength;\n                let data;\n                if (isPartialView && isWebKit()) {\n                    // https://bugs.webkit.org/show_bug.cgi?id=302733\n                    data = chunk.data.slice(section.start, section.end);\n                }\n                else {\n                    data = chunk.data.subarray(section.start, section.end);\n                }\n                void this._streamWriter.write({\n                    type: 'write',\n                    data,\n                    position,\n                }).catch((error) => {\n                    this._writeError ??= error;\n                });\n                this._lastFlushEnd = chunk.start + section.end;\n            }\n            this._chunks.splice(i--, 1);\n        }\n    }\n    /** @internal */\n    async _finalize() {\n        if (this._chunked) {\n            this._tryToFlushChunks(true);\n        }\n        if (this._writeError !== null) {\n            // eslint-disable-next-line @typescript-eslint/only-throw-error\n            throw this._writeError;\n        }\n        assert(this._streamWriter);\n        await this._streamWriter.ready;\n        await this._streamWriter.close();\n        this._emit('finalized');\n    }\n    /** @internal */\n    async _close() {\n        return this._streamWriter?.close();\n    }\n}\n/**\n * This target writes to a `WritableStream<Uint8Array>`, meaning all writes are necessarily append-only and involve no\n * seeking. Great for streaming data to a source that can only accept sequential data, like an HTTP server processing\n * an incoming upload.\n *\n * Note that using this target *requires* that the underlying format write data sequentially. Not all formats do this,\n * and this target will throw for the formats that don't. Check the guide for more.\n *\n * @group Output targets\n * @public\n */\nexport class AppendOnlyStreamTarget extends Target {\n    constructor(writable) {\n        super();\n        /** @internal */\n        this._writer = null;\n        /** @internal */\n        this._nextWritePos = 0;\n        this._writable = writable;\n        this._streamTarget = new StreamTarget(new WritableStream({\n            start: () => {\n                this._writer = this._writable.getWriter();\n            },\n            write: (chunk) => {\n                if (this._monotonicity !== true) {\n                    throw new Error('AppendOnlyStreamTarget requires that data be written monotonically (always appended to the'\n                        + ' end). You must use a format that guarantees this behavior.');\n                }\n                assert(chunk.position === this._nextWritePos);\n                this._nextWritePos += chunk.data.byteLength;\n                assert(this._writer);\n                return this._writer.write(chunk.data);\n            },\n            close: () => {\n                return this._writer?.close();\n            },\n        }));\n    }\n    /** @internal */\n    _start() {\n        this._streamTarget._start();\n    }\n    /** @internal */\n    _write(data, pos) {\n        this._streamTarget._write(data, pos);\n        this._dispatchWrite(pos, pos + data.byteLength);\n    }\n    /** @internal */\n    _flush() {\n        return this._streamTarget._flush();\n    }\n    /** @internal */\n    _finalize() {\n        return this._streamTarget._finalize();\n    }\n    /** @internal */\n    _close() {\n        return this._streamTarget._close();\n    }\n    /** @internal */\n    _setMonotonicity(monotonicity) {\n        super._setMonotonicity(monotonicity);\n        this._streamTarget._setMonotonicity(monotonicity);\n    }\n}\n/**\n * A target that writes to a file at the specified path. Intended for server-side usage in Node, Bun, or Deno.\n *\n * Writing is chunked by default. The internally held file handle will be closed when `.finalize()` or `.cancel()` are\n * called on the corresponding {@link Output}.\n * @group Output targets\n * @public\n */\nexport class FilePathTarget extends Target {\n    /** Creates a new {@link FilePathTarget} that writes to the file at the specified file path. */\n    constructor(filePath, options = {}) {\n        if (typeof filePath !== 'string') {\n            throw new TypeError('filePath must be a string.');\n        }\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (!node.fs) {\n            throw new Error('FilePathTarget is only available in server-side environments (Node.js, Bun, Deno).');\n        }\n        super();\n        /** @internal */\n        this._fileHandle = null;\n        // Let's back this target with a StreamTarget, makes the implementation very simple\n        const writable = new WritableStream({\n            start: async () => {\n                this._fileHandle = await node.fs.open(filePath, 'w');\n            },\n            write: async (chunk) => {\n                assert(this._fileHandle);\n                await this._fileHandle.write(chunk.data, 0, chunk.data.byteLength, chunk.position);\n            },\n            close: async () => {\n                if (this._fileHandle) {\n                    await this._fileHandle.close();\n                    this._fileHandle = null;\n                }\n            },\n        });\n        this._streamTarget = new StreamTarget(writable, {\n            chunked: true,\n            ...options,\n        });\n    }\n    /** @internal */\n    _start() {\n        this._streamTarget._start();\n    }\n    /** @internal */\n    _write(data, pos) {\n        this._streamTarget._write(data, pos);\n        this._dispatchWrite(pos, pos + data.byteLength);\n    }\n    /** @internal */\n    async _flush() {\n        return this._streamTarget._flush();\n    }\n    /** @internal */\n    async _finalize() {\n        await this._streamTarget._finalize();\n        this._emit('finalized');\n    }\n    /** @internal */\n    async _close() {\n        return this._streamTarget._close();\n    }\n    /** @internal */\n    _setMonotonicity(monotonicity) {\n        super._setMonotonicity(monotonicity);\n        this._streamTarget._setMonotonicity(monotonicity);\n    }\n}\n/**\n * This target just discards all incoming data. It is useful for when you need an {@link Output} but extract data from\n * it differently, for example through format-specific callbacks (`onMoof`, `onMdat`, ...) or encoder events.\n * @group Output targets\n * @public\n */\nexport class NullTarget extends Target {\n    /** @internal */\n    _start() { }\n    /** @internal */\n    _write(data, pos) {\n        this._dispatchWrite(pos, pos + data.byteLength);\n    }\n    /** @internal */\n    async _flush() { }\n    /** @internal */\n    async _finalize() {\n        this._emit('finalized');\n    }\n    /** @internal */\n    async _close() { }\n}\n/**\n * A target that writes to a subrange (defined by an offset) of another, underlying target. Useful for writing a file\n * into a section of a larger file.\n * @group Output targets\n * @public\n */\nexport class RangedTarget extends Target {\n    /** @internal */\n    constructor(baseTarget, offset) {\n        super();\n        this._baseTarget = baseTarget;\n        this._offset = offset;\n    }\n    /** @internal */\n    _start() { }\n    /** @internal */\n    _write(data, pos) {\n        this._baseTarget._write(data, this._offset + pos);\n        this._dispatchWrite(pos, pos + data.byteLength);\n    }\n    /** @internal */\n    _flush() {\n        return this._baseTarget._flush();\n    }\n    /** @internal */\n    async _finalize() {\n        this._emit('finalized');\n    }\n    /** @internal */\n    async _close() { }\n    /** @internal */\n    _setMonotonicity(monotonicity) {\n        super._setMonotonicity(monotonicity);\n        this._baseTarget._setMonotonicity(monotonicity);\n    }\n}\n/**\n * A special target for writing multi-file media where each file is uniquely identified by a path.\n * @group Output targets\n * @public\n */\nexport class PathedTarget {\n    /** Creates a new {@link PathedTarget} from a root path and a callback. */\n    constructor(\n    /** The path that points to the root file; the entry file of the media. */\n    rootPath, \n    /** The callback that is called for each file that needs to be written; must return a {@link Target}. */\n    getTarget) {\n        this.rootPath = rootPath;\n        this.getTarget = getTarget;\n        if (typeof rootPath !== 'string') {\n            throw new TypeError('rootPath must be a string.');\n        }\n        if (typeof getTarget !== 'function') {\n            throw new TypeError('getTarget must be a function.');\n        }\n    }\n}\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { free, ftyp, IsobmffBoxWriter, mdat, mfra, moof, moov, sidx, styp, vtta, vttc, vtte, } from './isobmff-boxes.js';\nimport { Muxer } from '../muxer.js';\nimport { Writer } from '../writer.js';\nimport { BufferTarget } from '../target.js';\nimport { assert, computeRationalApproximation, last, promiseWithResolvers, simplifyRational } from '../misc.js';\nimport { MovOutputFormat, CmafOutputFormat } from '../output-format.js';\nimport { inlineTimestampRegex } from '../subtitles.js';\nimport { aacChannelMap, aacFrequencyTable, buildAacAudioSpecificConfig } from '../../shared/aac-misc.js';\nimport { parsePcmCodec, PCM_AUDIO_CODECS, validateAudioChunkMetadata, validateSubtitleMetadata, validateVideoChunkMetadata, } from '../codec.js';\nimport { MAX_ADTS_FRAME_HEADER_SIZE, MIN_ADTS_FRAME_HEADER_SIZE, readAdtsFrameHeader } from '../adts/adts-reader.js';\nimport { FileSlice } from '../reader.js';\nimport { concatNalUnitsInLengthPrefixed, extractAvcDecoderConfigurationRecord, extractHevcDecoderConfigurationRecord, iterateNalUnitsInAnnexB, serializeAvcDecoderConfigurationRecord, serializeHevcDecoderConfigurationRecord, } from '../codec-data.js';\nimport { buildIsobmffMimeType } from './isobmff-misc.js';\nimport { MAX_BOX_HEADER_SIZE, MIN_BOX_HEADER_SIZE } from './isobmff-reader.js';\nexport const GLOBAL_TIMESCALE = 57600; // LCM of a bunch of common frame rates (24, 25, 30, 60, 144, ...)\nconst TIMESTAMP_OFFSET = 2_082_844_800; // Seconds between Jan 1 1904 and Jan 1 1970\nexport const getTrackMetadata = (trackData) => {\n    const metadata = {};\n    const track = trackData.track;\n    if (track.metadata.name !== undefined) {\n        metadata.name = track.metadata.name;\n    }\n    return metadata;\n};\nexport const intoTimescale = (timeInSeconds, timescale, round = true) => {\n    const value = timeInSeconds * timescale;\n    return round ? Math.round(value) : value;\n};\nexport const presentationSpan = (trackData) => {\n    if (trackData.samples.length === 0) {\n        return 0;\n    }\n    let minTimestamp = Infinity;\n    let maxEndTimestamp = -Infinity;\n    for (let i = 0; i < trackData.samples.length; i++) {\n        const sample = trackData.samples[i];\n        if (sample.timestamp < minTimestamp) {\n            minTimestamp = sample.timestamp;\n        }\n        if (sample.timestamp + sample.duration > maxEndTimestamp) {\n            maxEndTimestamp = sample.timestamp + sample.duration;\n        }\n    }\n    if (minTimestamp === Infinity) {\n        return 0;\n    }\n    return maxEndTimestamp - minTimestamp;\n};\nexport class IsobmffMuxer extends Muxer {\n    constructor(output, format) {\n        super(output);\n        this.writer = null;\n        this.boxWriter = null;\n        this.initWriter = null;\n        this.initBoxWriter = null;\n        this.auxTarget = new BufferTarget();\n        this.auxWriter = new Writer(this.auxTarget, false);\n        this.auxBoxWriter = new IsobmffBoxWriter(this.auxWriter);\n        this.mdat = null;\n        this.ftypSize = null;\n        this.trackDatas = [];\n        this.allTracksKnown = promiseWithResolvers();\n        this.creationTime = Math.floor(Date.now() / 1000) + TIMESTAMP_OFFSET;\n        this.finalizedChunks = [];\n        this.wroteFragmentedHeader = false;\n        this.nextFragmentNumber = 1;\n        // Only relevant for fragmented files, to make sure new fragments start with the highest timestamp seen so far\n        this.maxWrittenTimestamp = -Infinity;\n        this.minWrittenTimestamp = Infinity;\n        this.maxWrittenEndTimestamp = -Infinity;\n        this.segmentHeaderSize = null;\n        this.format = format;\n        this.formatOptions = { ...format._options };\n        this.isQuickTime = format instanceof MovOutputFormat;\n        this.isCmaf = format instanceof CmafOutputFormat;\n        this.minimumFragmentDuration = this.formatOptions.minimumFragmentDuration\n            ?? (format instanceof CmafOutputFormat ? Infinity : 1);\n        this.auxWriter.start();\n    }\n    async start() {\n        const release = await this.mutex.acquire();\n        if (!this.isCmaf) {\n            this.writer = await this.output._getRootWriter(target => (this.formatOptions.fastStart !== undefined\n                ? this.formatOptions.fastStart === 'fragmented'\n                : target instanceof BufferTarget // Since if this is the case we'll use 'in-memory'\n            ));\n            this.boxWriter = new IsobmffBoxWriter(this.writer);\n            // If the fastStart option isn't defined, enable in-memory fast start if the target is an ArrayBuffer, as\n            // the memory usage remains identical\n            this.fastStart = this.formatOptions.fastStart\n                ?? (this.writer.target instanceof BufferTarget ? 'in-memory' : false);\n            this.isFragmented = this.fastStart === 'fragmented';\n        }\n        else {\n            this.fastStart = 'fragmented';\n            this.isFragmented = true;\n        }\n        if (this.isCmaf) {\n            if (!this.output._hasInitTarget()) {\n                throw new Error(`CMAF outputs require the initTarget field in OutputOptions to be set; the init segment`\n                    + ` will be written to it.`);\n            }\n            // Set up the init writer to which we'll write the init segment\n            const initTarget = await this.output._getInitTarget();\n            const initWriter = new Writer(initTarget, true);\n            initWriter.start();\n            this.initWriter = initWriter;\n            this.initBoxWriter = new IsobmffBoxWriter(initWriter);\n        }\n        const holdsAvc = this.output.tracks.some(x => x.isVideoTrack() && x.source._codec === 'avc');\n        // Write the header\n        {\n            const boxWriter = this.initBoxWriter ?? this.boxWriter;\n            assert(boxWriter);\n            if (this.formatOptions.onFtyp) {\n                boxWriter.writer.startTrackingWrites();\n            }\n            boxWriter.writeBox(ftyp({\n                isQuickTime: this.isQuickTime,\n                holdsAvc: holdsAvc,\n                fragmented: this.isFragmented,\n                cmaf: this.isCmaf,\n            }));\n            if (this.formatOptions.onFtyp) {\n                const { data, start } = boxWriter.writer.stopTrackingWrites();\n                this.formatOptions.onFtyp(data, start);\n            }\n            this.ftypSize = boxWriter.writer.getPos();\n            if (this.isCmaf) {\n                await this.initWriter.flush();\n            }\n        }\n        if (this.fastStart === 'in-memory') {\n            // We're write at finalization\n        }\n        else if (this.fastStart === 'reserve') {\n            // Validate that all tracks have set maximumPacketCount\n            for (const track of this.output.tracks) {\n                if (track.metadata.maximumPacketCount === undefined) {\n                    throw new Error('All tracks must specify maximumPacketCount in their metadata when using'\n                        + ' fastStart: \\'reserve\\'.');\n                }\n            }\n            // We'll start writing once we know all tracks\n        }\n        else if (this.isFragmented) {\n            // We write the moov box once we write out the first fragment to make sure we get the decoder configs\n        }\n        else {\n            assert(this.writer);\n            assert(this.boxWriter);\n            if (this.formatOptions.onMdat) {\n                this.writer.startTrackingWrites();\n            }\n            this.mdat = mdat(true); // Reserve large size by default, can refine this when finalizing.\n            this.boxWriter.writeBox(this.mdat);\n        }\n        await this.writer?.flush();\n        for (const track of this.output.tracks) {\n            if (track.isVideoTrack() && track.metadata.decoderConfig) {\n                this.getVideoTrackData(track, track.metadata.primingPacket ?? null, { decoderConfig: track.metadata.decoderConfig });\n            }\n            else if (track.isAudioTrack() && track.metadata.decoderConfig) {\n                this.getAudioTrackData(track, track.metadata.primingPacket ?? null, { decoderConfig: track.metadata.decoderConfig });\n            }\n        }\n        release();\n    }\n    allTracksAreKnown() {\n        for (const track of this.output.tracks) {\n            if (!track.source._closed && !this.trackDatas.some(x => x.track === track)) {\n                return false; // We haven't seen a sample from this open track yet\n            }\n        }\n        return true;\n    }\n    async getMimeType() {\n        await this.allTracksKnown.promise;\n        const codecStrings = this.trackDatas.map((trackData) => {\n            if (trackData.type === 'video') {\n                return trackData.info.decoderConfig.codec;\n            }\n            else if (trackData.type === 'audio') {\n                return trackData.info.decoderConfig.codec;\n            }\n            else {\n                const map = {\n                    webvtt: 'wvtt',\n                };\n                return map[trackData.track.source._codec];\n            }\n        });\n        return buildIsobmffMimeType({\n            isQuickTime: this.isQuickTime,\n            hasVideo: this.trackDatas.some(x => x.type === 'video'),\n            hasAudio: this.trackDatas.some(x => x.type === 'audio'),\n            codecStrings,\n        });\n    }\n    getVideoTrackData(track, packet, meta) {\n        const existingTrackData = this.trackDatas.find(x => x.track === track);\n        if (existingTrackData) {\n            return existingTrackData;\n        }\n        validateVideoChunkMetadata(meta, track.source._codec);\n        assert(meta);\n        assert(meta.decoderConfig);\n        const decoderConfig = { ...meta.decoderConfig };\n        assert(decoderConfig.codedWidth !== undefined);\n        assert(decoderConfig.codedHeight !== undefined);\n        let requiresAnnexBTransformation = false;\n        if (track.source._codec === 'avc' && !decoderConfig.description) {\n            // ISOBMFF can only hold AVC in the AVCC format, not in Annex B, but the missing description indicates\n            // Annex B. This means we'll need to do some converterino.\n            if (!packet) {\n                throw new Error('No AVC description provided; you must therefore provide a priming packet.');\n            }\n            const decoderConfigurationRecord = extractAvcDecoderConfigurationRecord(packet.data);\n            if (!decoderConfigurationRecord) {\n                throw new Error('Couldn\\'t extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are'\n                    + ' in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or'\n                    + ' provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15)'\n                    + ' and ensure the packets are in AVCC format.');\n            }\n            decoderConfig.description = serializeAvcDecoderConfigurationRecord(decoderConfigurationRecord);\n            requiresAnnexBTransformation = true;\n        }\n        else if (track.source._codec === 'hevc' && !decoderConfig.description) {\n            // ISOBMFF can only hold HEVC in the HEVC format, not in Annex B, but the missing description indicates\n            // Annex B. This means we'll need to do some converterino.\n            if (!packet) {\n                throw new Error('No HEVC description provided; you must therefore provide a priming packet.');\n            }\n            const decoderConfigurationRecord = extractHevcDecoderConfigurationRecord(packet.data);\n            if (!decoderConfigurationRecord) {\n                throw new Error('Couldn\\'t extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets'\n                    + ' are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or'\n                    + ' provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15)'\n                    + ' and ensure the packets are in HEVC format.');\n            }\n            decoderConfig.description = serializeHevcDecoderConfigurationRecord(decoderConfigurationRecord);\n            requiresAnnexBTransformation = true;\n        }\n        // The frame rate set by the user may not be an integer. Since timescale is an integer, we'll approximate the\n        // frame time (inverse of frame rate) with a rational number, then use that approximation's denominator\n        // as the timescale.\n        const timescale = computeRationalApproximation(1 / (track.metadata.frameRate ?? GLOBAL_TIMESCALE), 1e6).den;\n        const displayAspectWidth = decoderConfig.displayAspectWidth;\n        const displayAspectHeight = decoderConfig.displayAspectHeight;\n        const pixelAspectRatio = displayAspectWidth === undefined || displayAspectHeight === undefined\n            ? { num: 1, den: 1 }\n            : simplifyRational({\n                num: displayAspectWidth * decoderConfig.codedHeight,\n                den: displayAspectHeight * decoderConfig.codedWidth,\n            });\n        // Kicks for ProRes 4444.\n        const hasAlphaChannel = decoderConfig.codec === 'ap4h' || decoderConfig.codec === 'ap4x';\n        const newTrackData = {\n            muxer: this,\n            track,\n            type: 'video',\n            info: {\n                width: decoderConfig.codedWidth,\n                height: decoderConfig.codedHeight,\n                pixelAspectRatio,\n                decoderConfig: decoderConfig,\n                requiresAnnexBTransformation,\n                hasAlphaChannel,\n            },\n            timescale,\n            samples: [],\n            sampleQueue: [],\n            timestampProcessingQueue: [],\n            timeToSampleTable: [],\n            compositionTimeOffsetTable: [],\n            lastTimescaleUnits: null,\n            lastSample: null,\n            startTimestampOffset: null,\n            finalizedChunks: [],\n            currentChunk: null,\n            compactlyCodedChunkTable: [],\n            closed: false,\n            avgBitrate: track.source._nominalBitrate ?? track.metadata.averageBitrate ?? 0,\n            maxBitrate: track.source._nominalBitrate ?? track.metadata.bitrate ?? 0,\n        };\n        this.trackDatas.push(newTrackData);\n        this.trackDatas.sort((a, b) => a.track.id - b.track.id);\n        if (this.allTracksAreKnown()) {\n            this.allTracksKnown.resolve();\n        }\n        return newTrackData;\n    }\n    getAudioTrackData(track, packet, meta) {\n        const existingTrackData = this.trackDatas.find(x => x.track === track);\n        if (existingTrackData) {\n            return existingTrackData;\n        }\n        validateAudioChunkMetadata(meta, track.source._codec);\n        assert(meta);\n        assert(meta.decoderConfig);\n        const decoderConfig = { ...meta.decoderConfig };\n        let requiresAdtsStripping = false;\n        if (track.source._codec === 'aac' && !decoderConfig.description) {\n            // ISOBMFF can only hold AAC in raw format, not ADTS, but the missing description indicates ADTS.\n            // Parse the first packet to extract the AudioSpecificConfig.\n            if (!packet) {\n                throw new Error('No AAC description provided; you must therefore provide a priming packet.');\n            }\n            const adtsFrame = readAdtsFrameHeader(FileSlice.tempFromBytes(packet.data));\n            if (!adtsFrame) {\n                throw new Error('Couldn\\'t parse ADTS header from the AAC packet. Make sure the packets are in ADTS format'\n                    + ' (as specified in ISO 13818-7) when not providing a description, or provide a description'\n                    + ' (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets'\n                    + ' are raw AAC data.');\n            }\n            const sampleRate = aacFrequencyTable[adtsFrame.samplingFrequencyIndex];\n            const numberOfChannels = aacChannelMap[adtsFrame.channelConfiguration];\n            if (sampleRate === undefined || numberOfChannels === undefined) {\n                throw new Error('Invalid ADTS frame header.');\n            }\n            decoderConfig.description = buildAacAudioSpecificConfig({\n                objectType: adtsFrame.objectType,\n                outputSampleRate: sampleRate,\n                outputNumberOfChannels: numberOfChannels,\n            });\n            requiresAdtsStripping = true;\n        }\n        if (!packet) {\n            if (track.source._codec === 'ac3' || track.source._codec === 'eac3') {\n                throw new Error('AC-3/E-AC-3 require a priming packet.');\n            }\n            if (track.source._codec === 'dts') {\n                throw new Error('DTS requires a priming packet.');\n            }\n        }\n        const newTrackData = {\n            muxer: this,\n            track,\n            type: 'audio',\n            info: {\n                numberOfChannels: meta.decoderConfig.numberOfChannels,\n                sampleRate: meta.decoderConfig.sampleRate,\n                decoderConfig,\n                requiresPcmTransformation: !this.isFragmented\n                    && PCM_AUDIO_CODECS.includes(track.source._codec),\n                expectedNextPcmPacketTimestamp: null,\n                requiresAdtsStripping,\n                primingPacket: packet,\n            },\n            timescale: decoderConfig.sampleRate,\n            samples: [],\n            sampleQueue: [],\n            timestampProcessingQueue: [],\n            timeToSampleTable: [],\n            compositionTimeOffsetTable: [],\n            lastTimescaleUnits: null,\n            lastSample: null,\n            startTimestampOffset: null,\n            finalizedChunks: [],\n            currentChunk: null,\n            compactlyCodedChunkTable: [],\n            closed: false,\n            avgBitrate: track.source._nominalBitrate ?? track.metadata.averageBitrate ?? 0,\n            maxBitrate: track.source._nominalBitrate ?? track.metadata.bitrate ?? 0,\n        };\n        this.trackDatas.push(newTrackData);\n        this.trackDatas.sort((a, b) => a.track.id - b.track.id);\n        if (this.allTracksAreKnown()) {\n            this.allTracksKnown.resolve();\n        }\n        return newTrackData;\n    }\n    getSubtitleTrackData(track, meta) {\n        const existingTrackData = this.trackDatas.find(x => x.track === track);\n        if (existingTrackData) {\n            return existingTrackData;\n        }\n        validateSubtitleMetadata(meta);\n        assert(meta);\n        assert(meta.config);\n        const newTrackData = {\n            muxer: this,\n            track,\n            type: 'subtitle',\n            info: {\n                config: meta.config,\n            },\n            timescale: 1000, // Reasonable\n            samples: [],\n            sampleQueue: [],\n            timestampProcessingQueue: [],\n            timeToSampleTable: [],\n            compositionTimeOffsetTable: [],\n            lastTimescaleUnits: null,\n            lastSample: null,\n            startTimestampOffset: null,\n            finalizedChunks: [],\n            currentChunk: null,\n            compactlyCodedChunkTable: [],\n            closed: false,\n            avgBitrate: track.source._nominalBitrate ?? track.metadata.averageBitrate ?? 0,\n            maxBitrate: track.source._nominalBitrate ?? track.metadata.bitrate ?? 0,\n            lastCueEndTimestamp: null,\n            cueQueue: [],\n            nextSourceId: 0,\n            cueToSourceId: new WeakMap(),\n        };\n        this.trackDatas.push(newTrackData);\n        this.trackDatas.sort((a, b) => a.track.id - b.track.id);\n        if (this.allTracksAreKnown()) {\n            this.allTracksKnown.resolve();\n        }\n        return newTrackData;\n    }\n    async addEncodedVideoPacket(track, packet, meta) {\n        const release = await this.mutex.acquire();\n        try {\n            const trackData = this.getVideoTrackData(track, packet, meta);\n            let packetData = packet.data;\n            if (trackData.info.requiresAnnexBTransformation) {\n                const nalUnits = [...iterateNalUnitsInAnnexB(packetData)]\n                    .map(loc => packetData.subarray(loc.offset, loc.offset + loc.length));\n                if (nalUnits.length === 0) {\n                    // It's not valid Annex B data\n                    throw new Error('Failed to transform packet data. Make sure all packets are provided in Annex B format, as'\n                        + ' specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.');\n                }\n                // We don't strip things like SPS or PPS NALUs here, mainly because they can also appear in the middle\n                // of a stream and potentially modify the parameters of it. So, let's just leave them in to be sure.\n                packetData = concatNalUnitsInLengthPrefixed(nalUnits, 4);\n            }\n            this.validateTimestamp(trackData.track, packet.timestamp, packet.type === 'key');\n            const internalSample = this.createSampleForTrack(trackData, packetData, packet.timestamp, packet.duration, packet.type);\n            await this.registerSample(trackData, internalSample);\n        }\n        finally {\n            release();\n        }\n    }\n    async addEncodedAudioPacket(track, packet, meta) {\n        const release = await this.mutex.acquire();\n        try {\n            const trackData = this.getAudioTrackData(track, packet, meta);\n            let packetData = packet.data;\n            if (trackData.info.requiresAdtsStripping) {\n                const adtsFrame = readAdtsFrameHeader(FileSlice.tempFromBytes(packetData));\n                if (!adtsFrame) {\n                    throw new Error('Expected ADTS frame, didn\\'t get one.');\n                }\n                const headerLength = adtsFrame.crcCheck === null\n                    ? MIN_ADTS_FRAME_HEADER_SIZE\n                    : MAX_ADTS_FRAME_HEADER_SIZE;\n                packetData = packetData.subarray(headerLength);\n            }\n            this.validateTimestamp(trackData.track, packet.timestamp, packet.type === 'key');\n            let timestamp = packet.timestamp;\n            let duration = packet.duration;\n            if (trackData.info.requiresPcmTransformation) {\n                // Packets may have only approximate timestamp/duration information, but for our PCM logic, we need it\n                // to be precise. So here, we refine the values.\n                const pcmInfo = parsePcmCodec(trackData.info.decoderConfig.codec);\n                const frameSize = pcmInfo.sampleSize * trackData.info.numberOfChannels;\n                // Compute the precise duration\n                duration = packetData.byteLength / frameSize / trackData.info.sampleRate;\n                if (trackData.info.expectedNextPcmPacketTimestamp !== null) {\n                    const diff = timestamp - trackData.info.expectedNextPcmPacketTimestamp;\n                    if (diff < 0.01) {\n                        timestamp = trackData.info.expectedNextPcmPacketTimestamp;\n                    }\n                    else {\n                        const paddedDuration = await this.padWithSilence(trackData, trackData.info.expectedNextPcmPacketTimestamp, diff);\n                        timestamp = trackData.info.expectedNextPcmPacketTimestamp + paddedDuration;\n                    }\n                }\n                trackData.info.expectedNextPcmPacketTimestamp = timestamp + duration;\n            }\n            const internalSample = this.createSampleForTrack(trackData, packetData, timestamp, duration, packet.type);\n            await this.registerSample(trackData, internalSample);\n        }\n        finally {\n            release();\n        }\n    }\n    async padWithSilence(trackData, timestamp, duration) {\n        const deltaInTimescale = intoTimescale(duration, trackData.timescale);\n        duration = deltaInTimescale / trackData.timescale;\n        if (deltaInTimescale > 0) {\n            const { sampleSize, silentValue } = parsePcmCodec(trackData.info.decoderConfig.codec);\n            const samplesNeeded = deltaInTimescale * trackData.info.numberOfChannels;\n            const data = new Uint8Array(sampleSize * samplesNeeded).fill(silentValue);\n            const paddingSample = this.createSampleForTrack(trackData, new Uint8Array(data.buffer), timestamp, duration, 'key');\n            await this.registerSample(trackData, paddingSample);\n        }\n        return duration;\n    }\n    async addSubtitleCue(track, cue, meta) {\n        const release = await this.mutex.acquire();\n        try {\n            const trackData = this.getSubtitleTrackData(track, meta);\n            this.validateTimestamp(trackData.track, cue.timestamp, true);\n            if (track.source._codec === 'webvtt') {\n                trackData.cueQueue.push(cue);\n                await this.processWebVTTCues(trackData, cue.timestamp);\n            }\n            else {\n                // TODO\n            }\n        }\n        finally {\n            release();\n        }\n    }\n    async processWebVTTCues(trackData, until) {\n        // WebVTT cues need to undergo special processing as empty sections need to be padded out with samples, and\n        // overlapping samples require special logic. The algorithm produces the format specified in ISO 14496-30.\n        while (trackData.cueQueue.length > 0) {\n            trackData.lastCueEndTimestamp ??= Math.min(0, trackData.cueQueue[0].timestamp);\n            const timestamps = new Set([]);\n            for (const cue of trackData.cueQueue) {\n                assert(cue.timestamp <= until);\n                assert(trackData.lastCueEndTimestamp <= cue.timestamp + cue.duration);\n                timestamps.add(Math.max(cue.timestamp, trackData.lastCueEndTimestamp)); // Start timestamp\n                timestamps.add(cue.timestamp + cue.duration); // End timestamp\n            }\n            const sortedTimestamps = [...timestamps].sort((a, b) => a - b);\n            // These are the timestamps of the next sample we'll create:\n            const sampleStart = sortedTimestamps[0];\n            const sampleEnd = sortedTimestamps[1] ?? sampleStart;\n            if (until < sampleEnd) {\n                break;\n            }\n            // We may need to pad out empty space with an vtte box\n            if (trackData.lastCueEndTimestamp < sampleStart) {\n                this.auxWriter.seek(0);\n                const box = vtte();\n                this.auxBoxWriter.writeBox(box);\n                const body = this.auxTarget._getSlice(0, this.auxWriter.getPos());\n                const sample = this.createSampleForTrack(trackData, body, trackData.lastCueEndTimestamp, sampleStart - trackData.lastCueEndTimestamp, 'key');\n                await this.registerSample(trackData, sample);\n                trackData.lastCueEndTimestamp = sampleStart;\n            }\n            this.auxWriter.seek(0);\n            for (let i = 0; i < trackData.cueQueue.length; i++) {\n                const cue = trackData.cueQueue[i];\n                if (cue.timestamp >= sampleEnd) {\n                    break;\n                }\n                inlineTimestampRegex.lastIndex = 0;\n                const containsTimestamp = inlineTimestampRegex.test(cue.text);\n                const endTimestamp = cue.timestamp + cue.duration;\n                let sourceId = trackData.cueToSourceId.get(cue);\n                if (sourceId === undefined && sampleEnd < endTimestamp) {\n                    // We know this cue will appear in more than one sample, therefore we need to mark it with a\n                    // unique ID\n                    sourceId = trackData.nextSourceId++;\n                    trackData.cueToSourceId.set(cue, sourceId);\n                }\n                if (cue.notes) {\n                    // Any notes/comments are included in a special vtta box\n                    const box = vtta(cue.notes);\n                    this.auxBoxWriter.writeBox(box);\n                }\n                const box = vttc(cue.text, containsTimestamp ? sampleStart : null, cue.identifier ?? null, cue.settings ?? null, sourceId ?? null);\n                this.auxBoxWriter.writeBox(box);\n                if (endTimestamp === sampleEnd) {\n                    // The cue won't appear in any future sample, so we're done with it\n                    trackData.cueQueue.splice(i--, 1);\n                }\n            }\n            const body = this.auxTarget._getSlice(0, this.auxWriter.getPos());\n            const sample = this.createSampleForTrack(trackData, body, sampleStart, sampleEnd - sampleStart, 'key');\n            await this.registerSample(trackData, sample);\n            trackData.lastCueEndTimestamp = sampleEnd;\n        }\n    }\n    createSampleForTrack(trackData, data, timestamp, duration, type) {\n        const sample = {\n            timestamp,\n            decodeTimestamp: timestamp, // This may be refined later\n            duration,\n            data,\n            size: data.byteLength,\n            type,\n            timescaleUnitsToNextSample: intoTimescale(duration, trackData.timescale), // Will be refined\n        };\n        return sample;\n    }\n    processTimestamps(trackData, nextSample) {\n        if (trackData.timestampProcessingQueue.length === 0) {\n            return;\n        }\n        if (trackData.type === 'audio' && trackData.info.requiresPcmTransformation) {\n            assert(!this.isFragmented);\n            // The first timestamp is the lowest\n            trackData.startTimestampOffset ??= trackData.timestampProcessingQueue[0].timestamp;\n            let totalDuration = 0;\n            // Compute the total duration in the track timescale (which is equal to the amount of PCM audio samples)\n            // and simply say that's how many new samples there are.\n            for (let i = 0; i < trackData.timestampProcessingQueue.length; i++) {\n                const sample = trackData.timestampProcessingQueue[i];\n                const duration = intoTimescale(sample.duration, trackData.timescale);\n                totalDuration += duration;\n            }\n            if (trackData.timeToSampleTable.length === 0) {\n                trackData.timeToSampleTable.push({\n                    sampleCount: totalDuration,\n                    sampleDelta: 1,\n                });\n            }\n            else {\n                const lastEntry = last(trackData.timeToSampleTable);\n                lastEntry.sampleCount += totalDuration;\n            }\n            trackData.timestampProcessingQueue.length = 0;\n            return;\n        }\n        const sortedTimestamps = trackData.timestampProcessingQueue.map(x => x.timestamp).sort((a, b) => a - b);\n        if (this.isFragmented) {\n            trackData.startTimestampOffset ??= Math.min(sortedTimestamps[0], 0);\n        }\n        else {\n            trackData.startTimestampOffset ??= sortedTimestamps[0];\n        }\n        for (let i = 0; i < trackData.timestampProcessingQueue.length; i++) {\n            const sample = trackData.timestampProcessingQueue[i];\n            // Since the user only supplies presentation time, but these may be out of order, we reverse-engineer from\n            // that a sensible decode timestamp. The notion of a decode timestamp doesn't really make sense\n            // (presentation timestamp & decode order are all you need), but it is a concept in ISOBMFF so we need to\n            // model it.\n            sample.decodeTimestamp = sortedTimestamps[i];\n            const sampleCompositionTimeOffset = intoTimescale(sample.timestamp - sample.decodeTimestamp, trackData.timescale);\n            const durationInTimescale = intoTimescale(sample.duration, trackData.timescale);\n            if (trackData.lastTimescaleUnits !== null) {\n                assert(trackData.lastSample);\n                const timescaleUnits = intoTimescale(sample.decodeTimestamp, trackData.timescale, false);\n                const delta = Math.round(timescaleUnits - trackData.lastTimescaleUnits);\n                assert(delta >= 0);\n                trackData.lastTimescaleUnits += delta;\n                trackData.lastSample.timescaleUnitsToNextSample = delta;\n                if (!this.isFragmented) {\n                    let lastTableEntry = last(trackData.timeToSampleTable);\n                    assert(lastTableEntry);\n                    if (lastTableEntry.sampleCount === 1) {\n                        lastTableEntry.sampleDelta = delta;\n                        const entryBefore = trackData.timeToSampleTable[trackData.timeToSampleTable.length - 2];\n                        if (entryBefore && entryBefore.sampleDelta === delta) {\n                            // If the delta is the same as the previous one, merge the two entries\n                            entryBefore.sampleCount++;\n                            trackData.timeToSampleTable.pop();\n                            lastTableEntry = entryBefore;\n                        }\n                    }\n                    else if (lastTableEntry.sampleDelta !== delta) {\n                        // The delta has changed, so we need a new entry to reach the current sample\n                        lastTableEntry.sampleCount--;\n                        trackData.timeToSampleTable.push(lastTableEntry = {\n                            sampleCount: 1,\n                            sampleDelta: delta,\n                        });\n                    }\n                    if (lastTableEntry.sampleDelta === durationInTimescale) {\n                        // The sample's duration matches the delta, so we can increment the count\n                        lastTableEntry.sampleCount++;\n                    }\n                    else {\n                        // Add a new entry in order to maintain the last sample's true duration\n                        trackData.timeToSampleTable.push({\n                            sampleCount: 1,\n                            sampleDelta: durationInTimescale,\n                        });\n                    }\n                    const lastCompositionTimeOffsetTableEntry = last(trackData.compositionTimeOffsetTable);\n                    assert(lastCompositionTimeOffsetTableEntry);\n                    if (lastCompositionTimeOffsetTableEntry.sampleCompositionTimeOffset === sampleCompositionTimeOffset) {\n                        // Simply increment the count\n                        lastCompositionTimeOffsetTableEntry.sampleCount++;\n                    }\n                    else {\n                        // The composition time offset has changed, so create a new entry with the new composition time\n                        // offset\n                        trackData.compositionTimeOffsetTable.push({\n                            sampleCount: 1,\n                            sampleCompositionTimeOffset: sampleCompositionTimeOffset,\n                        });\n                    }\n                }\n            }\n            else {\n                // Decode timestamp of the first sample\n                trackData.lastTimescaleUnits = intoTimescale(sample.decodeTimestamp, trackData.timescale, false);\n                if (!this.isFragmented) {\n                    trackData.timeToSampleTable.push({\n                        sampleCount: 1,\n                        sampleDelta: durationInTimescale,\n                    });\n                    trackData.compositionTimeOffsetTable.push({\n                        sampleCount: 1,\n                        sampleCompositionTimeOffset: sampleCompositionTimeOffset,\n                    });\n                }\n            }\n            trackData.lastSample = sample;\n        }\n        trackData.timestampProcessingQueue.length = 0;\n        assert(trackData.lastSample);\n        assert(trackData.lastTimescaleUnits !== null);\n        if (nextSample !== undefined && trackData.lastSample.timescaleUnitsToNextSample === 0) {\n            assert(nextSample.type === 'key');\n            // Given the next sample, we can make a guess about the duration of the last sample. This avoids having\n            // the last sample's duration in each fragment be \"0\" for fragmented files. The guess we make here is\n            // actually correct most of the time, since typically, no delta frame with a lower timestamp follows the key\n            // frame (although it can happen).\n            const timescaleUnits = intoTimescale(nextSample.timestamp, trackData.timescale, false);\n            const delta = Math.round(timescaleUnits - trackData.lastTimescaleUnits);\n            trackData.lastSample.timescaleUnitsToNextSample = delta;\n        }\n    }\n    async registerSample(trackData, sample) {\n        if (sample.type === 'key') {\n            this.processTimestamps(trackData, sample);\n        }\n        trackData.timestampProcessingQueue.push(sample);\n        if (this.isFragmented) {\n            trackData.sampleQueue.push(sample);\n            await this.interleaveSamples();\n        }\n        else if (this.fastStart === 'reserve') {\n            await this.registerSampleFastStartReserve(trackData, sample);\n        }\n        else {\n            await this.addSampleToTrack(trackData, sample);\n        }\n    }\n    async addSampleToTrack(trackData, sample) {\n        if (!this.isFragmented) {\n            trackData.samples.push(sample);\n            if (this.fastStart === 'reserve') {\n                const maximumPacketCount = trackData.track.metadata.maximumPacketCount;\n                assert(maximumPacketCount !== undefined);\n                if (trackData.samples.length > maximumPacketCount) {\n                    throw new Error(`Track #${trackData.track.id} has already reached the maximum packet count`\n                        + ` (${maximumPacketCount}). Either add less packets or increase the maximum packet count.`);\n                }\n            }\n        }\n        let beginNewChunk = false;\n        if (!trackData.currentChunk) {\n            beginNewChunk = true;\n        }\n        else {\n            // Timestamp don't need to be monotonic (think B-frames), so we may need to update the start timestamp of\n            // the chunk\n            trackData.currentChunk.startTimestamp = Math.min(trackData.currentChunk.startTimestamp, sample.timestamp);\n            const currentChunkDuration = sample.timestamp - trackData.currentChunk.startTimestamp;\n            if (this.isFragmented) {\n                // We can only finalize this fragment (and begin a new one) if we know that each track will be able to\n                // start the new one with a key frame.\n                const keyFrameQueuedEverywhere = this.trackDatas.every((otherTrackData) => {\n                    if (trackData === otherTrackData) {\n                        return sample.type === 'key';\n                    }\n                    const firstQueuedSample = otherTrackData.sampleQueue[0];\n                    if (firstQueuedSample) {\n                        return firstQueuedSample.type === 'key';\n                    }\n                    return otherTrackData.closed;\n                });\n                if (currentChunkDuration >= this.minimumFragmentDuration\n                    && keyFrameQueuedEverywhere\n                    && sample.timestamp > this.maxWrittenTimestamp) {\n                    beginNewChunk = true;\n                    await this.finalizeFragment();\n                }\n            }\n            else {\n                beginNewChunk = currentChunkDuration >= 0.5; // Chunk is long enough, we need a new one\n            }\n        }\n        if (beginNewChunk) {\n            if (trackData.currentChunk) {\n                await this.finalizeCurrentChunk(trackData);\n            }\n            trackData.currentChunk = {\n                startTimestamp: sample.timestamp,\n                samples: [],\n                offset: null,\n                moofOffset: null,\n                trafIndex: null,\n            };\n        }\n        assert(trackData.currentChunk);\n        trackData.currentChunk.samples.push(sample);\n        if (this.isFragmented) {\n            this.maxWrittenTimestamp = Math.max(this.maxWrittenTimestamp, sample.timestamp);\n            this.maxWrittenEndTimestamp = Math.max(this.maxWrittenEndTimestamp, sample.timestamp + sample.duration);\n            this.minWrittenTimestamp = Math.min(this.minWrittenTimestamp, sample.timestamp);\n        }\n    }\n    async finalizeCurrentChunk(trackData) {\n        assert(!this.isFragmented);\n        assert(this.writer);\n        if (!trackData.currentChunk)\n            return;\n        trackData.finalizedChunks.push(trackData.currentChunk);\n        this.finalizedChunks.push(trackData.currentChunk);\n        let sampleCount = trackData.currentChunk.samples.length;\n        if (trackData.type === 'audio' && trackData.info.requiresPcmTransformation) {\n            sampleCount = trackData.currentChunk.samples\n                .reduce((acc, sample) => acc + intoTimescale(sample.duration, trackData.timescale), 0);\n        }\n        if (trackData.compactlyCodedChunkTable.length === 0\n            || last(trackData.compactlyCodedChunkTable).samplesPerChunk !== sampleCount) {\n            trackData.compactlyCodedChunkTable.push({\n                firstChunk: trackData.finalizedChunks.length, // 1-indexed\n                samplesPerChunk: sampleCount,\n            });\n        }\n        if (this.fastStart === 'in-memory') {\n            trackData.currentChunk.offset = 0; // We'll compute the proper offset when finalizing\n            return;\n        }\n        // Write out the data\n        trackData.currentChunk.offset = this.writer.getPos();\n        for (const sample of trackData.currentChunk.samples) {\n            assert(sample.data);\n            this.writer.write(sample.data);\n            sample.data = null; // Can be GC'd\n        }\n        await this.writer.flush();\n    }\n    async interleaveSamples(isFinalCall = false) {\n        assert(this.isFragmented);\n        if (!isFinalCall && !this.allTracksAreKnown()) {\n            return; // We can't interleave yet as we don't yet know how many tracks we'll truly have\n        }\n        outer: while (true) {\n            let trackWithMinTimestamp = null;\n            let minTimestamp = Infinity;\n            for (const trackData of this.trackDatas) {\n                if (!isFinalCall && trackData.sampleQueue.length === 0 && !trackData.closed) {\n                    break outer;\n                }\n                if (trackData.sampleQueue.length > 0 && trackData.sampleQueue[0].timestamp < minTimestamp) {\n                    trackWithMinTimestamp = trackData;\n                    minTimestamp = trackData.sampleQueue[0].timestamp;\n                }\n            }\n            if (!trackWithMinTimestamp) {\n                break;\n            }\n            const sample = trackWithMinTimestamp.sampleQueue.shift();\n            await this.addSampleToTrack(trackWithMinTimestamp, sample);\n        }\n    }\n    async finalizeFragment(flushWriter = !this.isCmaf) {\n        assert(this.isFragmented);\n        if (!this.wroteFragmentedHeader) {\n            this.wroteFragmentedHeader = true;\n            const boxWriter = this.initBoxWriter ?? this.boxWriter;\n            assert(boxWriter);\n            if (this.formatOptions.onMoov) {\n                boxWriter.writer.startTrackingWrites();\n            }\n            this.ensureOneEnabledTrack();\n            // Write the moov box now that we have all decoder configs\n            const movieBox = moov(this);\n            boxWriter.writeBox(movieBox);\n            if (this.formatOptions.onMoov) {\n                const { data, start } = boxWriter.writer.stopTrackingWrites();\n                this.formatOptions.onMoov(data, start);\n            }\n            if (this.isCmaf) {\n                assert(this.initWriter);\n                await this.initWriter.flush();\n                await this.initWriter.finalize(); // Init segment is done\n                // Only now, init the main writer; this way the init writer is fully done before the main writer is\n                // even acquired\n                this.writer = await this.output._getRootWriter(true);\n                this.boxWriter = new IsobmffBoxWriter(this.writer);\n                const stypSize = this.boxWriter.measureBox(styp());\n                const sidxSize = this.boxWriter.measureBox(sidx(this, 0));\n                this.segmentHeaderSize = stypSize + sidxSize;\n                this.writer.seek(this.segmentHeaderSize); // Make room for the header to be written later\n            }\n        }\n        assert(this.writer);\n        assert(this.boxWriter);\n        // Not all tracks need to be present in every fragment\n        const tracksInFragment = this.trackDatas.filter(x => x.currentChunk);\n        if (tracksInFragment.length === 0) {\n            // Zero tracks in this fragment and thus no fragment data\n            if (flushWriter) {\n                await this.writer.flush();\n            }\n            return;\n        }\n        const fragmentNumber = this.nextFragmentNumber++;\n        // Create an initial moof box and measure it; we need this to know where the following mdat box will begin\n        const moofBox = moof(fragmentNumber, tracksInFragment);\n        const moofOffset = this.writer.getPos();\n        const mdatStartPos = moofOffset + this.boxWriter.measureBox(moofBox);\n        let currentPos = mdatStartPos + MIN_BOX_HEADER_SIZE;\n        let fragmentStartTimestamp = Infinity;\n        for (let i = 0; i < tracksInFragment.length; i++) {\n            const trackData = tracksInFragment[i];\n            assert(trackData.currentChunk);\n            assert(trackData.startTimestampOffset !== null);\n            trackData.currentChunk.offset = currentPos;\n            trackData.currentChunk.moofOffset = moofOffset;\n            trackData.currentChunk.trafIndex = i;\n            trackData.currentChunk.startTimestamp -= trackData.startTimestampOffset;\n            for (const sample of trackData.currentChunk.samples) {\n                currentPos += sample.size;\n                sample.timestamp -= trackData.startTimestampOffset;\n                sample.decodeTimestamp -= trackData.startTimestampOffset;\n            }\n            fragmentStartTimestamp = Math.min(fragmentStartTimestamp, trackData.currentChunk.startTimestamp);\n        }\n        const mdatSize = currentPos - mdatStartPos;\n        const needsLargeMdatSize = mdatSize >= 2 ** 32;\n        if (needsLargeMdatSize) {\n            // Shift all offsets by 8. Previously, all chunks were shifted assuming the large box size, but due to what\n            // I suspect is a bug in WebKit, it failed in Safari (when livestreaming with MSE, not for static playback).\n            for (const trackData of tracksInFragment) {\n                trackData.currentChunk.offset += MAX_BOX_HEADER_SIZE - MIN_BOX_HEADER_SIZE;\n            }\n        }\n        if (this.formatOptions.onMoof) {\n            this.writer.startTrackingWrites();\n        }\n        const newMoofBox = moof(fragmentNumber, tracksInFragment);\n        this.boxWriter.writeBox(newMoofBox);\n        if (this.formatOptions.onMoof) {\n            const { data, start } = this.writer.stopTrackingWrites();\n            this.formatOptions.onMoof(data, start, fragmentStartTimestamp);\n        }\n        assert(this.writer.getPos() === mdatStartPos);\n        if (this.formatOptions.onMdat) {\n            this.writer.startTrackingWrites();\n        }\n        const mdatBox = mdat(needsLargeMdatSize);\n        mdatBox.size = mdatSize;\n        this.boxWriter.writeBox(mdatBox);\n        this.writer.seek(mdatStartPos + (needsLargeMdatSize ? MAX_BOX_HEADER_SIZE : MIN_BOX_HEADER_SIZE));\n        // Write sample data\n        for (const trackData of tracksInFragment) {\n            for (const sample of trackData.currentChunk.samples) {\n                this.writer.write(sample.data);\n                sample.data = null; // Can be GC'd\n            }\n        }\n        if (this.formatOptions.onMdat) {\n            const { data, start } = this.writer.stopTrackingWrites();\n            this.formatOptions.onMdat(data, start);\n        }\n        for (const trackData of tracksInFragment) {\n            trackData.finalizedChunks.push(trackData.currentChunk);\n            this.finalizedChunks.push(trackData.currentChunk);\n            trackData.currentChunk = null;\n        }\n        if (flushWriter) {\n            await this.writer.flush();\n        }\n    }\n    async registerSampleFastStartReserve(trackData, sample) {\n        if (this.allTracksAreKnown()) {\n            if (!this.mdat) {\n                await this.createFastStartReserveMdat();\n            }\n            await this.addSampleToTrack(trackData, sample);\n        }\n        else {\n            // Queue it for when we know all tracks\n            trackData.sampleQueue.push(sample);\n        }\n    }\n    async createFastStartReserveMdat() {\n        assert(this.writer);\n        assert(this.boxWriter);\n        this.ensureOneEnabledTrack();\n        // We finally know all tracks, let's reserve space for the moov box\n        const moovBox = moov(this);\n        const moovSize = this.boxWriter.measureBox(moovBox);\n        const reservedSize = moovSize\n            + this.computeSampleTableSizeUpperBound()\n            + 4096; // Just a little extra headroom\n        assert(this.ftypSize !== null);\n        this.writer.seek(this.ftypSize + reservedSize);\n        if (this.formatOptions.onMdat) {\n            this.writer.startTrackingWrites();\n        }\n        this.mdat = mdat(true);\n        this.boxWriter.writeBox(this.mdat);\n        // Now write everything that was queued\n        for (const trackData of this.trackDatas) {\n            for (const sample of trackData.sampleQueue) {\n                await this.addSampleToTrack(trackData, sample);\n            }\n            trackData.sampleQueue.length = 0;\n        }\n    }\n    computeSampleTableSizeUpperBound() {\n        assert(this.fastStart === 'reserve');\n        let upperBound = 0;\n        for (const trackData of this.trackDatas) {\n            const n = trackData.track.metadata.maximumPacketCount;\n            assert(n !== undefined); // We validated this earlier\n            // Given the max allowed packet count, compute the space they'll take up in the Sample Table Box, assuming\n            // the worst case for each individual box:\n            // stts box - since it is compactly coded, the maximum length of this table will be 2/3n\n            upperBound += (4 + 4) * Math.ceil(2 / 3 * n);\n            // stss box - 1 entry per sample\n            upperBound += 4 * n;\n            // ctts box - since it is compactly coded, the maximum length of this table will be 2/3n\n            upperBound += (4 + 4) * Math.ceil(2 / 3 * n);\n            // stsc box - since it is compactly coded, the maximum length of this table will be 2/3n\n            upperBound += (4 + 4 + 4) * Math.ceil(2 / 3 * n);\n            // stsz box - 1 entry per sample\n            upperBound += 4 * n;\n            // co64 box - we assume 1 sample per chunk and 64-bit chunk offsets (co64 instead of stco)\n            upperBound += 8 * n;\n        }\n        return upperBound;\n    }\n    // eslint-disable-next-line @typescript-eslint/no-misused-promises\n    async onTrackClose(track) {\n        const release = await this.mutex.acquire();\n        const trackData = this.trackDatas.find(x => x.track === track);\n        if (trackData) {\n            trackData.closed = true;\n            if (trackData.type === 'subtitle' && track.source._codec === 'webvtt') {\n                await this.processWebVTTCues(trackData, Infinity);\n            }\n            this.processTimestamps(trackData);\n        }\n        if (this.allTracksAreKnown()) {\n            this.allTracksKnown.resolve();\n        }\n        if (this.isFragmented) {\n            // Since a track is now closed, we may be able to write out chunks that were previously waiting\n            await this.interleaveSamples();\n        }\n        release();\n    }\n    ensureOneEnabledTrack() {\n        // If no track of a given type is enabled, force the first one to be enabled. Otherwise the video won't play in\n        // players like QuickTime.\n        // https://github.com/Vanilagy/mediabunny/pull/391\n        for (const type of ['video', 'audio', 'subtitle']) {\n            const tracks = this.trackDatas.filter(t => t.type === type);\n            if (tracks.length === 0) {\n                continue;\n            }\n            const hasEnabled = tracks.some(t => t.track.metadata.disposition?.default !== false);\n            if (!hasEnabled) {\n                const firstTrack = tracks[0];\n                firstTrack.track.metadata.disposition = {\n                    ...firstTrack.track.metadata.disposition,\n                    default: true,\n                };\n            }\n        }\n    }\n    /** Internal function for external callers who want to full control fragment boundaries. */\n    async forceFragmentFinalization() {\n        assert(this.isFragmented);\n        const release = await this.mutex.acquire();\n        try {\n            for (const trackData of this.trackDatas) {\n                if (trackData.type === 'subtitle' && trackData.track.source._codec === 'webvtt') {\n                    await this.processWebVTTCues(trackData, Infinity);\n                }\n                this.processTimestamps(trackData);\n            }\n            await this.interleaveSamples(true);\n            await this.finalizeFragment();\n        }\n        finally {\n            release();\n        }\n    }\n    /** Finalizes the file, making it ready for use. Must be called after all video and audio chunks have been added. */\n    async finalize() {\n        const release = await this.mutex.acquire();\n        this.allTracksKnown.resolve();\n        this.ensureOneEnabledTrack();\n        if (!this.mdat && this.fastStart === 'reserve') {\n            await this.createFastStartReserveMdat();\n        }\n        for (const trackData of this.trackDatas) {\n            trackData.closed = true;\n            if (trackData.type === 'subtitle' && trackData.track.source._codec === 'webvtt') {\n                await this.processWebVTTCues(trackData, Infinity);\n            }\n            this.processTimestamps(trackData);\n        }\n        if (this.isFragmented) {\n            await this.interleaveSamples(true);\n            await this.finalizeFragment(false); // Don't flush the last fragment as we will flush it with the mfra box\n        }\n        else {\n            for (const trackData of this.trackDatas) {\n                await this.finalizeCurrentChunk(trackData);\n                // Now that we have all samples, we can replace the nominal bitrates with measured ones\n                const span = presentationSpan(trackData);\n                if (span > 0) {\n                    let totalBytes = 0;\n                    for (const sample of trackData.samples) {\n                        totalBytes += sample.size;\n                    }\n                    trackData.avgBitrate = Math.round(8 * totalBytes / span);\n                }\n                else {\n                    trackData.avgBitrate = 0;\n                }\n                // Sliding one-second window over the samples in decode order\n                let windowStart = 0;\n                let windowBytes = 0;\n                let maxWindowBytes = 0;\n                for (let i = 0; i < trackData.samples.length; i++) {\n                    const sample = trackData.samples[i];\n                    windowBytes += sample.size;\n                    while (sample.decodeTimestamp - trackData.samples[windowStart].decodeTimestamp >= 1) {\n                        windowBytes -= trackData.samples[windowStart].size;\n                        windowStart++;\n                    }\n                    maxWindowBytes = Math.max(maxWindowBytes, windowBytes);\n                }\n                trackData.maxBitrate = 8 * maxWindowBytes;\n                if (trackData.startTimestampOffset !== null) {\n                    // Shift all of the samples by the start offset. We'll then write out an edit list that will shift\n                    // them back to their proper spot in the composition.\n                    for (let i = 0; i < trackData.samples.length; i++) {\n                        const sample = trackData.samples[i];\n                        sample.timestamp -= trackData.startTimestampOffset;\n                        sample.decodeTimestamp -= trackData.startTimestampOffset;\n                    }\n                }\n            }\n        }\n        assert(this.writer);\n        assert(this.boxWriter);\n        if (this.fastStart === 'in-memory') {\n            this.mdat = mdat(false);\n            let mdatSize;\n            // We know how many chunks there are, but computing the chunk positions requires an iterative approach:\n            // In order to know where the first chunk should go, we first need to know the size of the moov box. But we\n            // cannot write a proper moov box without first knowing all chunk positions. So, we generate a tentative\n            // moov box with placeholder values (0) for the chunk offsets to be able to compute its size. If it then\n            // turns out that appending all chunks exceeds 4 GiB, we need to repeat this process, now with the co64 box\n            // being used in the moov box instead, which will make it larger. After that, we definitely know the final\n            // size of the moov box and can compute the proper chunk positions.\n            for (let i = 0; i < 2; i++) {\n                const movieBox = moov(this);\n                const movieBoxSize = this.boxWriter.measureBox(movieBox);\n                mdatSize = this.boxWriter.measureBox(this.mdat);\n                let currentChunkPos = this.writer.getPos() + movieBoxSize + mdatSize;\n                for (const chunk of this.finalizedChunks) {\n                    chunk.offset = currentChunkPos;\n                    for (const { data } of chunk.samples) {\n                        assert(data);\n                        currentChunkPos += data.byteLength;\n                        mdatSize += data.byteLength;\n                    }\n                }\n                if (currentChunkPos < 2 ** 32)\n                    break;\n                if (mdatSize >= 2 ** 32)\n                    this.mdat.largeSize = true;\n            }\n            if (this.formatOptions.onMoov) {\n                this.writer.startTrackingWrites();\n            }\n            const movieBox = moov(this);\n            this.boxWriter.writeBox(movieBox);\n            if (this.formatOptions.onMoov) {\n                const { data, start } = this.writer.stopTrackingWrites();\n                this.formatOptions.onMoov(data, start);\n            }\n            if (this.formatOptions.onMdat) {\n                this.writer.startTrackingWrites();\n            }\n            this.mdat.size = mdatSize;\n            this.boxWriter.writeBox(this.mdat);\n            for (const chunk of this.finalizedChunks) {\n                for (const sample of chunk.samples) {\n                    assert(sample.data);\n                    this.writer.write(sample.data);\n                    sample.data = null;\n                }\n            }\n            if (this.formatOptions.onMdat) {\n                const { data, start } = this.writer.stopTrackingWrites();\n                this.formatOptions.onMdat(data, start);\n            }\n        }\n        else if (this.isFragmented) {\n            if (this.isCmaf) {\n                const contentSize = this.segmentHeaderSize !== null\n                    ? this.writer.getPos() - this.segmentHeaderSize\n                    : 0;\n                this.writer.seek(0);\n                // Write styp and sidx to the start; we recently made space for these\n                this.boxWriter.writeBox(styp());\n                this.boxWriter.writeBox(sidx(this, contentSize));\n            }\n            else {\n                // Append the mfra box to the end of the file for better random access\n                const startPos = this.writer.getPos();\n                const mfraBox = mfra(this.trackDatas);\n                this.boxWriter.writeBox(mfraBox);\n                // Patch the 'size' field of the mfro box at the end of the mfra box now that we know its actual size\n                const mfraBoxSize = this.writer.getPos() - startPos;\n                this.writer.seek(this.writer.getPos() - 4);\n                this.boxWriter.writeU32(mfraBoxSize);\n            }\n        }\n        else {\n            assert(this.mdat);\n            const mdatPos = this.boxWriter.offsets.get(this.mdat);\n            assert(mdatPos !== undefined);\n            const mdatSize = this.writer.getPos() - mdatPos;\n            this.mdat.size = mdatSize;\n            this.mdat.largeSize = mdatSize >= 2 ** 32; // Only use the large size if we need it\n            this.boxWriter.patchBox(this.mdat);\n            if (this.formatOptions.onMdat) {\n                const { data, start } = this.writer.stopTrackingWrites();\n                this.formatOptions.onMdat(data, start);\n            }\n            const movieBox = moov(this);\n            if (this.fastStart === 'reserve') {\n                assert(this.ftypSize !== null);\n                this.writer.seek(this.ftypSize);\n                if (this.formatOptions.onMoov) {\n                    this.writer.startTrackingWrites();\n                }\n                this.boxWriter.writeBox(movieBox);\n                // Fill the remaining space with a free box. If there are less than 8 bytes left, sucks I guess\n                const remainingSpace = this.boxWriter.offsets.get(this.mdat) - this.writer.getPos();\n                this.boxWriter.writeBox(free(remainingSpace));\n            }\n            else {\n                if (this.formatOptions.onMoov) {\n                    this.writer.startTrackingWrites();\n                }\n                this.boxWriter.writeBox(movieBox);\n            }\n            if (this.formatOptions.onMoov) {\n                const { data, start } = this.writer.stopTrackingWrites();\n                this.formatOptions.onMoov(data, start);\n            }\n        }\n        release();\n    }\n}\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { assert } from './misc.js';\nimport { AudioSample } from './sample.js';\n/**\n * Utility class to handle audio resampling, handling both sample rate resampling as well as channel up/downmixing.\n * The advantage over doing this manually rather than using OfflineAudioContext to do it for us is the artifact-free\n * handling of putting multiple resampled audio samples back to back, which produces flaky results using\n * OfflineAudioContext.\n */\nexport class AudioResampler {\n    constructor(options) {\n        this.sourceSampleRate = null;\n        this.sourceNumberOfChannels = null;\n        this.startTime = null;\n        /** Start frame of current buffer */\n        this.bufferStartFrame = 0;\n        /** The highest index written to in the current buffer */\n        this.maxWrittenFrame = null;\n        this.targetSampleRate = options.targetSampleRate;\n        this.targetNumberOfChannels = options.targetNumberOfChannels;\n        this.onSample = options.onSample;\n        this.bufferSizeInFrames = Math.floor(this.targetSampleRate * 5.0); // 5 seconds\n        this.bufferSizeInSamples = this.bufferSizeInFrames * this.targetNumberOfChannels;\n    }\n    /**\n     * Sets up the channel mixer to handle up/downmixing in the case where input and output channel counts don't match.\n     */\n    doChannelMixerSetup() {\n        assert(this.sourceNumberOfChannels !== null);\n        const sourceNum = this.sourceNumberOfChannels;\n        const targetNum = this.targetNumberOfChannels;\n        // Logic taken from\n        // https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API\n        // Most of the mapping functions are branchless.\n        if (sourceNum === 1 && targetNum === 2) {\n            // Mono to Stereo: M -> L, M -> R\n            this.channelMixer = (sourceData, sourceFrameIndex) => {\n                return sourceData[sourceFrameIndex * sourceNum];\n            };\n        }\n        else if (sourceNum === 1 && targetNum === 4) {\n            // Mono to Quad: M -> L, M -> R, 0 -> SL, 0 -> SR\n            this.channelMixer = (sourceData, sourceFrameIndex, targetChannelIndex) => {\n                return sourceData[sourceFrameIndex * sourceNum] * +(targetChannelIndex < 2);\n            };\n        }\n        else if (sourceNum === 1 && targetNum === 6) {\n            // Mono to 5.1: 0 -> L, 0 -> R, M -> C, 0 -> LFE, 0 -> SL, 0 -> SR\n            this.channelMixer = (sourceData, sourceFrameIndex, targetChannelIndex) => {\n                return sourceData[sourceFrameIndex * sourceNum] * +(targetChannelIndex === 2);\n            };\n        }\n        else if (sourceNum === 2 && targetNum === 1) {\n            // Stereo to Mono: 0.5 * (L + R)\n            this.channelMixer = (sourceData, sourceFrameIndex) => {\n                const baseIdx = sourceFrameIndex * sourceNum;\n                return 0.5 * (sourceData[baseIdx] + sourceData[baseIdx + 1]);\n            };\n        }\n        else if (sourceNum === 2 && targetNum === 4) {\n            // Stereo to Quad: L -> L, R -> R, 0 -> SL, 0 -> SR\n            this.channelMixer = (sourceData, sourceFrameIndex, targetChannelIndex) => {\n                return targetChannelIndex < 2\n                    ? sourceData[sourceFrameIndex * sourceNum + targetChannelIndex]\n                    : 0;\n            };\n        }\n        else if (sourceNum === 2 && targetNum === 6) {\n            // Stereo to 5.1: L -> L, R -> R, 0 -> C, 0 -> LFE, 0 -> SL, 0 -> SR\n            this.channelMixer = (sourceData, sourceFrameIndex, targetChannelIndex) => {\n                return targetChannelIndex < 2\n                    ? sourceData[sourceFrameIndex * sourceNum + targetChannelIndex]\n                    : 0;\n            };\n        }\n        else if (sourceNum === 4 && targetNum === 1) {\n            // Quad to Mono: 0.25 * (L + R + SL + SR)\n            this.channelMixer = (sourceData, sourceFrameIndex) => {\n                const baseIdx = sourceFrameIndex * sourceNum;\n                return 0.25 * (sourceData[baseIdx] + sourceData[baseIdx + 1]\n                    + sourceData[baseIdx + 2] + sourceData[baseIdx + 3]);\n            };\n        }\n        else if (sourceNum === 4 && targetNum === 2) {\n            // Quad to Stereo: 0.5 * (L + SL), 0.5 * (R + SR)\n            this.channelMixer = (sourceData, sourceFrameIndex, targetChannelIndex) => {\n                const baseIdx = sourceFrameIndex * sourceNum;\n                return 0.5 * (sourceData[baseIdx + targetChannelIndex]\n                    + sourceData[baseIdx + targetChannelIndex + 2]);\n            };\n        }\n        else if (sourceNum === 4 && targetNum === 6) {\n            // Quad to 5.1: L -> L, R -> R, 0 -> C, 0 -> LFE, SL -> SL, SR -> SR\n            this.channelMixer = (sourceData, sourceFrameIndex, targetChannelIndex) => {\n                const baseIdx = sourceFrameIndex * sourceNum;\n                // It's a bit harder to do this one branchlessly\n                if (targetChannelIndex < 2)\n                    return sourceData[baseIdx + targetChannelIndex]; // L, R\n                if (targetChannelIndex === 2 || targetChannelIndex === 3)\n                    return 0; // C, LFE\n                return sourceData[baseIdx + targetChannelIndex - 2]; // SL, SR\n            };\n        }\n        else if (sourceNum === 6 && targetNum === 1) {\n            // 5.1 to Mono: sqrt(1/2) * (L + R) + C + 0.5 * (SL + SR)\n            this.channelMixer = (sourceData, sourceFrameIndex) => {\n                const baseIdx = sourceFrameIndex * sourceNum;\n                return Math.SQRT1_2 * (sourceData[baseIdx] + sourceData[baseIdx + 1])\n                    + sourceData[baseIdx + 2]\n                    + 0.5 * (sourceData[baseIdx + 4] + sourceData[baseIdx + 5]);\n            };\n        }\n        else if (sourceNum === 6 && targetNum === 2) {\n            // 5.1 to Stereo: L + sqrt(1/2) * (C + SL), R + sqrt(1/2) * (C + SR)\n            this.channelMixer = (sourceData, sourceFrameIndex, targetChannelIndex) => {\n                const baseIdx = sourceFrameIndex * sourceNum;\n                return sourceData[baseIdx + targetChannelIndex]\n                    + Math.SQRT1_2 * (sourceData[baseIdx + 2] + sourceData[baseIdx + targetChannelIndex + 4]);\n            };\n        }\n        else if (sourceNum === 6 && targetNum === 4) {\n            // 5.1 to Quad: L + sqrt(1/2) * C, R + sqrt(1/2) * C, SL, SR\n            this.channelMixer = (sourceData, sourceFrameIndex, targetChannelIndex) => {\n                const baseIdx = sourceFrameIndex * sourceNum;\n                // It's a bit harder to do this one branchlessly\n                if (targetChannelIndex < 2) {\n                    return sourceData[baseIdx + targetChannelIndex] + Math.SQRT1_2 * sourceData[baseIdx + 2];\n                }\n                return sourceData[baseIdx + targetChannelIndex + 2]; // SL, SR\n            };\n        }\n        else {\n            // Discrete fallback: direct mapping with zero-fill or drop\n            this.channelMixer = (sourceData, sourceFrameIndex, targetChannelIndex) => {\n                return targetChannelIndex < sourceNum\n                    ? sourceData[sourceFrameIndex * sourceNum + targetChannelIndex]\n                    : 0;\n            };\n        }\n    }\n    ensureTempBufferSize(requiredSamples) {\n        let length = this.tempSourceBuffer.length;\n        while (length < requiredSamples) {\n            length *= 2;\n        }\n        if (length !== this.tempSourceBuffer.length) {\n            const newBuffer = new Float32Array(length);\n            newBuffer.set(this.tempSourceBuffer);\n            this.tempSourceBuffer = newBuffer;\n        }\n    }\n    async add(audioSample) {\n        if (this.sourceSampleRate === null) {\n            // This is the first sample, so let's init the missing data. Initing the sample rate from the decoded\n            // sample is more reliable than using the file's metadata, because decoders are free to emit any sample rate\n            // they see fit.\n            this.sourceSampleRate = audioSample.sampleRate;\n            this.sourceNumberOfChannels = audioSample.numberOfChannels;\n            this.startTime = audioSample.timestamp;\n            // An input sample may map to more than one output sample, which is why we need padding in the buffer to not\n            // lose any data\n            const overflowFrames = Math.ceil(this.targetSampleRate / this.sourceSampleRate);\n            this.bufferCapacityInFrames = this.bufferSizeInFrames + overflowFrames;\n            this.outputBuffer = new Float32Array(this.bufferCapacityInFrames * this.targetNumberOfChannels);\n            // Pre-allocate temporary buffer for source data\n            this.tempSourceBuffer = new Float32Array(this.sourceSampleRate * this.sourceNumberOfChannels);\n            this.doChannelMixerSetup();\n        }\n        assert(this.startTime !== null);\n        const requiredSamples = audioSample.numberOfFrames * audioSample.numberOfChannels;\n        this.ensureTempBufferSize(requiredSamples);\n        // Copy the audio data to the temp buffer\n        const sourceDataSize = audioSample.allocationSize({ planeIndex: 0, format: 'f32' });\n        const sourceView = new Float32Array(this.tempSourceBuffer.buffer, 0, sourceDataSize / 4);\n        audioSample.copyTo(sourceView, { planeIndex: 0, format: 'f32' });\n        const inputStartTime = audioSample.timestamp - this.startTime;\n        const inputEndTime = inputStartTime + audioSample.duration;\n        // Compute which output frames are affected by this sample\n        const outputStartFrame = Math.floor((inputStartTime - 1 / this.sourceSampleRate) * this.targetSampleRate) + 1;\n        const outputEndFrame = Math.ceil(inputEndTime * this.targetSampleRate);\n        for (let outputFrame = outputStartFrame; outputFrame < outputEndFrame; outputFrame++) {\n            if (outputFrame < this.bufferStartFrame) {\n                continue; // Skip writes to the past\n            }\n            while (outputFrame >= this.bufferStartFrame + this.bufferCapacityInFrames) {\n                // The write is wholly after the current buffer, so finalize it\n                await this.finalizeCurrentBuffer();\n                this.bufferStartFrame += this.bufferSizeInFrames;\n            }\n            const bufferFrameIndex = outputFrame - this.bufferStartFrame;\n            assert(bufferFrameIndex < this.bufferCapacityInFrames);\n            const outputTime = outputFrame / this.targetSampleRate;\n            const inputTime = outputTime - inputStartTime;\n            const sourcePosition = inputTime * this.sourceSampleRate;\n            const sourceLowerFrame = Math.floor(sourcePosition);\n            const sourceUpperFrame = Math.ceil(sourcePosition);\n            const fraction = sourcePosition - sourceLowerFrame;\n            // Process each output channel\n            for (let targetChannel = 0; targetChannel < this.targetNumberOfChannels; targetChannel++) {\n                let lowerSample = 0;\n                let upperSample = 0;\n                if (sourceLowerFrame >= 0 && sourceLowerFrame < audioSample.numberOfFrames) {\n                    lowerSample = this.channelMixer(sourceView, sourceLowerFrame, targetChannel);\n                }\n                if (sourceUpperFrame >= 0 && sourceUpperFrame < audioSample.numberOfFrames) {\n                    upperSample = this.channelMixer(sourceView, sourceUpperFrame, targetChannel);\n                }\n                // For resampling, we do naive linear interpolation to find the in-between sample. This produces\n                // suboptimal results especially for downsampling (for which a low-pass filter would first need to be\n                // applied), but AudioContext doesn't do this either, so, whatever, for now.\n                const outputSample = lowerSample + fraction * (upperSample - lowerSample);\n                // Write to output buffer (interleaved)\n                const outputIndex = bufferFrameIndex * this.targetNumberOfChannels + targetChannel;\n                this.outputBuffer[outputIndex] += outputSample; // Add in case of overlapping samples\n            }\n            if (this.maxWrittenFrame === null) {\n                this.maxWrittenFrame = bufferFrameIndex;\n            }\n            else {\n                this.maxWrittenFrame = Math.max(this.maxWrittenFrame, bufferFrameIndex);\n            }\n        }\n    }\n    async finalizeCurrentBuffer() {\n        if (this.maxWrittenFrame === null) {\n            return; // Nothing to finalize\n        }\n        assert(this.startTime !== null);\n        const samplesWritten = Math.min(this.maxWrittenFrame + 1, this.bufferSizeInFrames)\n            * this.targetNumberOfChannels;\n        const outputData = new Float32Array(samplesWritten);\n        outputData.set(this.outputBuffer.subarray(0, samplesWritten));\n        const audioSample = new AudioSample({\n            format: 'f32',\n            sampleRate: this.targetSampleRate,\n            numberOfChannels: this.targetNumberOfChannels,\n            timestamp: this.startTime + this.bufferStartFrame / this.targetSampleRate,\n            data: outputData,\n        });\n        await this.onSample(audioSample);\n        this.outputBuffer.copyWithin(0, this.bufferSizeInSamples);\n        this.outputBuffer.fill(0, this.outputBuffer.length - this.bufferSizeInSamples);\n        this.maxWrittenFrame = this.maxWrittenFrame >= this.bufferSizeInFrames\n            ? this.maxWrittenFrame - this.bufferSizeInFrames\n            : null;\n    }\n    async finalize() {\n        while (this.maxWrittenFrame !== null) {\n            await this.finalizeCurrentBuffer();\n            this.bufferStartFrame += this.bufferSizeInFrames;\n        }\n    }\n}\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nvar __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {\n    if (value !== null && value !== void 0) {\n        if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n        var dispose, inner;\n        if (async) {\n            if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n            dispose = value[Symbol.asyncDispose];\n        }\n        if (dispose === void 0) {\n            if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n            dispose = value[Symbol.dispose];\n            if (async) inner = dispose;\n        }\n        if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n        env.stack.push({ value: value, dispose: dispose, async: async });\n    }\n    else if (async) {\n        env.stack.push({ async: true });\n    }\n    return value;\n};\nvar __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {\n    return function (env) {\n        function fail(e) {\n            env.error = env.hasError ? new SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n            env.hasError = true;\n        }\n        var r, s = 0;\n        function next() {\n            while (r = env.stack.pop()) {\n                try {\n                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n                    if (r.dispose) {\n                        var result = r.dispose.call(r.value);\n                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n                    }\n                    else s |= 1;\n                }\n                catch (e) {\n                    fail(e);\n                }\n            }\n            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n            if (env.hasError) throw env.error;\n        }\n        return next();\n    };\n})(typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n    var e = new Error(message);\n    return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n});\nimport { buildAacAudioSpecificConfig, parseAacAudioSpecificConfig } from '../shared/aac-misc.js';\nimport { AUDIO_CODECS, extractVideoCodecString, parsePcmCodec, PCM_AUDIO_CODECS, SUBTITLE_CODECS, VIDEO_CODECS, } from './codec.js';\nimport { assert, assertNever, binarySearchLessOrEqual, CallSerializer, clamp, clearIntervalUnthrottled, floorToDivisor, isCodecReclaimedError, isFirefox, isThenable, last, missingWebCodecsClassMessage, promiseWithResolvers, roundToDivisor, setInt24, setIntervalUnthrottled, setUint24, toUint8Array, wait, } from './misc.js';\nimport { SubtitleParser } from './subtitles.js';\nimport { toAlaw, toUlaw } from './pcm.js';\nimport { customVideoEncoders, customAudioEncoders, } from './custom-coder.js';\nimport { EncodedPacket } from './packet.js';\nimport { AudioSample, audioSampleToInterleavedFormat, toInterleavedAudioFormat, VideoSample, } from './sample.js';\nimport { buildAudioEncoderConfig, buildQuantizerEncodeOptions, buildVideoEncoderConfigs, resolveQuality, validateAudioEncodingConfig, validateVideoEncodingConfig, } from './encode.js';\nimport { AudioResampler } from './resample.js';\nimport { deserializeAvcDecoderConfigurationRecord, determineVideoPacketType, extractAv1CodecInfoFromPacket, extractAvcDecoderConfigurationRecord, extractHevcDecoderConfigurationRecord, extractVp9CodecInfoFromPacket, serializeAvcDecoderConfigurationRecord, } from './codec-data.js';\nimport { Logging } from './logging.js';\nimport { readEsDescriptor } from './isobmff/isobmff-reader.js';\nimport { FileSlice } from './reader.js';\n/**\n * Base class for media sources. Media sources are used to add media samples to an output file.\n * @group Media sources\n * @public\n */\nexport class MediaSource {\n    constructor() {\n        /** @internal */\n        this._connectedTrack = null;\n        /** @internal */\n        this._closingPromise = null;\n        /** @internal */\n        this._closed = false;\n        /**\n         * Set when the encoder is configured with a bitrate.\n         * @internal\n         */\n        this._nominalBitrate = null;\n    }\n    /** @internal */\n    _ensureValidAdd() {\n        if (!this._connectedTrack) {\n            throw new Error('Source is not connected to an output track.');\n        }\n        if (this._connectedTrack.output.state === 'canceled') {\n            throw new Error('Output has been canceled.');\n        }\n        if (this._connectedTrack.output.state === 'finalizing' || this._connectedTrack.output.state === 'finalized') {\n            throw new Error('Output has been finalized.');\n        }\n        if (this._connectedTrack.output.state === 'pending') {\n            throw new Error('Output has not started.');\n        }\n        if (this._closed) {\n            throw new Error('Source is closed.');\n        }\n    }\n    /** @internal */\n    async _start() { }\n    /** @internal */\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    async _flushAndClose(forceClose) { }\n    /**\n     * Closes this source. This prevents future samples from being added and signals to the output file that no further\n     * samples will come in for this track. Calling `.close()` is optional but recommended after adding the\n     * last sample - for improved performance and reduced memory usage.\n     */\n    close() {\n        if (this._closingPromise) {\n            return;\n        }\n        const connectedTrack = this._connectedTrack;\n        if (!connectedTrack) {\n            throw new Error('Cannot call close without connecting the source to an output track.');\n        }\n        if (connectedTrack.output.state === 'pending') {\n            throw new Error('Cannot call close before output has been started.');\n        }\n        this._closingPromise = (async () => {\n            await this._flushAndClose(false);\n            this._closed = true;\n            if (connectedTrack.output.state === 'finalizing' || connectedTrack.output.state === 'finalized') {\n                return;\n            }\n            connectedTrack.output._muxer.onTrackClose(connectedTrack);\n        })();\n    }\n    /** @internal */\n    async _flushOrWaitForOngoingClose(forceClose) {\n        return this._closingPromise ??= (async () => {\n            await this._flushAndClose(forceClose);\n            this._closed = true;\n        })();\n    }\n}\n/**\n * Base class for video sources - sources for video tracks.\n * @group Media sources\n * @public\n */\nexport class VideoSource extends MediaSource {\n    /** Internal constructor. */\n    constructor(codec) {\n        super();\n        if (!VIDEO_CODECS.includes(codec)) {\n            throw new TypeError(`Invalid video codec '${codec}'. Must be one of: ${VIDEO_CODECS.join(', ')}.`);\n        }\n        this._codec = codec;\n    }\n}\nconst maybeEnsureIsKeyPacket = (track, packet) => {\n    if (track.metadata.hasOnlyKeyPackets && packet.type !== 'key') {\n        throw new Error('Cannot add non-key packets to a hasOnlyKeyPackets video track.');\n    }\n};\n/**\n * The most basic video source; can be used to directly pipe encoded packets into the output file.\n * @group Media sources\n * @public\n */\nexport class EncodedVideoPacketSource extends VideoSource {\n    /** Creates a new {@link EncodedVideoPacketSource} whose packets are encoded using `codec`. */\n    constructor(codec) {\n        super(codec);\n    }\n    /**\n     * Adds an encoded packet to the output video track. Packets must be added in *decode order*, while a packet's\n     * timestamp must be its *presentation timestamp*. B-frames are handled automatically.\n     *\n     * @param meta - Additional metadata from the encoder. You should pass this for the first call, including a valid\n     * decoder config.\n     *\n     * @returns A Promise that resolves once the output is ready to receive more samples. You should await this Promise\n     * to respect writer and encoder backpressure.\n     */\n    add(packet, meta) {\n        if (!(packet instanceof EncodedPacket)) {\n            throw new TypeError('packet must be an EncodedPacket.');\n        }\n        if (packet.isMetadataOnly) {\n            throw new TypeError('Metadata-only packets cannot be added.');\n        }\n        if (meta !== undefined && (!meta || typeof meta !== 'object')) {\n            throw new TypeError('meta, when provided, must be an object.');\n        }\n        this._ensureValidAdd();\n        maybeEnsureIsKeyPacket(this._connectedTrack, packet);\n        return this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack, packet, meta);\n    }\n}\nclass VideoEncoderWrapper {\n    setError(error) {\n        if (!this.errorSet) {\n            this.error = error;\n            this.errorSet = true;\n        }\n    }\n    constructor(source, encodingConfig) {\n        this.source = source;\n        this.encodingConfig = encodingConfig;\n        this.ensureEncoderPromise = null;\n        this.encoderInitialized = false;\n        this.encoder = null;\n        this.encoderConfig = null;\n        // Set when the browser closed our encoders due to inactivity; they'll be recreated on the next encode\n        this.encodersReclaimed = false;\n        this.muxer = null;\n        this.lastMultipleOfKeyFrameInterval = -1;\n        this.emittedEncoderPackets = 0;\n        this.chunkTimestampsAreShiftedByDuration = false; // See detectAvcChunkTimestampShift\n        // Tracks the input dimensions of the first frame\n        this.codedWidth = null;\n        this.codedHeight = null;\n        // Tracks the output dimensions of the first frame (used to lock dimensions for fill/contain/cover)\n        this.outputWidth = null;\n        this.outputHeight = null;\n        // Frame rate normalization state\n        this.frameRateLastSample = null;\n        this.frameRateLastTimestamp = null;\n        this.frameRateLastEndTimestamp = null;\n        // VideoEncoder converts everything to microseconds, so we need to do some bookkeeping to restore the original\n        // timing information\n        this.preciseTimings = [];\n        this.customEncoder = null;\n        this.customEncoderCallSerializer = new CallSerializer();\n        this.customEncoderQueueSize = 0;\n        // Set when the encoder uses quantizer-based rate control; carries the quantizer value applied to each frame\n        this.defaultEncodeOptions = {};\n        // Alpha stuff\n        this.alphaEncoder = null;\n        this.splitter = null;\n        this.splitterCreationFailed = false;\n        this.alphaFrameQueue = [];\n        /**\n         * Encoders typically throw their errors \"out of band\", meaning asynchronously in some other execution context.\n         * However, we want to surface these errors to the user within the normal control flow, so they don't go uncaught.\n         * So, we keep track of the encoder error and throw it as soon as we get the chance.\n         */\n        this.error = null;\n        this.errorSet = false;\n        this.lastMuxerPromise = Promise.resolve();\n        this.closed = false;\n    }\n    async add(videoSample, shouldClose, encodeOptions) {\n        const originalSample = videoSample;\n        try {\n            this.checkForEncoderError();\n            this.source._ensureValidAdd();\n            const config = this.encodingConfig;\n            const sizeChangeBehavior = config.sizeChangeBehavior ?? 'deny';\n            let isSizeChange = false;\n            // Ensure video sample size remains constant or handle the change\n            if (this.codedWidth !== null && this.codedHeight !== null) {\n                if (videoSample.codedWidth !== this.codedWidth || videoSample.codedHeight !== this.codedHeight) {\n                    isSizeChange = true;\n                    if (sizeChangeBehavior === 'deny') {\n                        throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight},`\n                            + ` got ${videoSample.codedWidth}x${videoSample.codedHeight}. To allow the sample size to`\n                            + ` change over time, set \\`sizeChangeBehavior\\` to a value other than 'deny' in the`\n                            + ` encoding options.`);\n                    }\n                }\n            }\n            else {\n                this.codedWidth = videoSample.codedWidth;\n                this.codedHeight = videoSample.codedHeight;\n            }\n            // Determine if we need to apply transformations via canvas\n            const hasTransformConfig = config.transform?.width !== undefined\n                || config.transform?.height !== undefined\n                || config.transform?.rotate !== undefined\n                || config.transform?.flip !== undefined\n                || config.transform?.crop !== undefined\n                || config.transform?.force === true;\n            const needsTransform = hasTransformConfig || (isSizeChange && sizeChangeBehavior !== 'passThrough');\n            if (needsTransform) {\n                let targetWidth = config.transform?.width;\n                let targetHeight = config.transform?.height;\n                let appliedFit = config.transform?.fit ?? 'fill';\n                // If the size changed and behavior is fill/contain/cover, lock to the original output dimensions\n                if (isSizeChange && sizeChangeBehavior !== 'passThrough') {\n                    assert(this.outputWidth);\n                    assert(this.outputHeight);\n                    assert(sizeChangeBehavior !== 'deny');\n                    targetWidth = this.outputWidth;\n                    targetHeight = this.outputHeight;\n                    appliedFit = sizeChangeBehavior;\n                }\n                const transformed = await videoSample.transform({\n                    width: targetWidth,\n                    height: targetHeight,\n                    roundDimensionsTo: 2,\n                    crop: config.transform?.crop,\n                    rotate: config.transform?.rotate,\n                    flip: config.transform?.flip,\n                    fit: appliedFit,\n                    alpha: config.alpha,\n                });\n                // Save the output dimensions of the first frame\n                if (this.outputWidth === null || this.outputHeight === null) {\n                    this.outputWidth = transformed.displayWidth;\n                    this.outputHeight = transformed.displayHeight;\n                }\n                if (shouldClose) {\n                    videoSample.close();\n                }\n                videoSample = transformed;\n                shouldClose = true;\n            }\n            else {\n                // If no canvas is needed, we still need to record the output dimensions for the first frame\n                if (this.outputWidth === null || this.outputHeight === null) {\n                    this.outputWidth = videoSample.codedWidth;\n                    this.outputHeight = videoSample.codedHeight;\n                }\n            }\n            const frameRate = config.transform?.frameRate;\n            if (frameRate !== undefined) {\n                // Apply frame rate normalization\n                const originalEndTimestamp = videoSample.timestamp + videoSample.duration;\n                const alignedTimestamp = floorToDivisor(videoSample.timestamp, frameRate);\n                if (this.frameRateLastSample !== null) {\n                    if (alignedTimestamp <= this.frameRateLastTimestamp) {\n                        // Same frame rate slot, replace stored sample with the newer one\n                        this.frameRateLastSample.close();\n                        this.frameRateLastSample = videoSample.clone();\n                        this.frameRateLastEndTimestamp = originalEndTimestamp;\n                        return;\n                    }\n                    else {\n                        // Pad the gap by repeating the previous frame\n                        await this.padFrameRate(alignedTimestamp, encodeOptions);\n                    }\n                }\n                // Clone if the sample is still the user's, to avoid mutating externally-owned data\n                if (videoSample === originalSample) {\n                    videoSample = videoSample.clone();\n                    shouldClose = true;\n                }\n                videoSample.setTimestamp(alignedTimestamp);\n                videoSample.setDuration(1 / frameRate);\n                this.frameRateLastSample?.close();\n                this.frameRateLastSample = videoSample.clone();\n                this.frameRateLastTimestamp = alignedTimestamp;\n                this.frameRateLastEndTimestamp = originalEndTimestamp;\n            }\n            await this.processAndEncode(videoSample, encodeOptions);\n        }\n        finally {\n            if (shouldClose) {\n                videoSample.close();\n            }\n        }\n    }\n    /**\n     * Runs the process function (if any) and encodes the resulting samples.\n     */\n    async processAndEncode(videoSample, encodeOptions) {\n        const config = this.encodingConfig;\n        let samplesToEncode;\n        // Apply the user-defined process function, if any\n        if (config.transform?.process) {\n            let processed = config.transform.process(videoSample);\n            if (isThenable(processed)) {\n                processed = await processed;\n            }\n            if (processed === null) {\n                return;\n            }\n            if (!Array.isArray(processed)) {\n                processed = [processed];\n            }\n            const mappedSamples = [];\n            try {\n                for (const x of processed) {\n                    if (x instanceof VideoSample) {\n                        mappedSamples.push(x);\n                    }\n                    else if (typeof VideoFrame !== 'undefined' && x instanceof VideoFrame) {\n                        mappedSamples.push(new VideoSample(x));\n                    }\n                    else {\n                        // Calling the VideoSample constructor here will automatically handle input validation for us\n                        // (it throws for any non-legal argument).\n                        mappedSamples.push(new VideoSample(x, {\n                            timestamp: videoSample.timestamp,\n                            duration: videoSample.duration,\n                        }));\n                    }\n                }\n            }\n            catch (error) {\n                // One of the returned elements was invalid; close everything closable so no resource is leaked\n                for (const sample of mappedSamples) {\n                    if (sample !== videoSample) {\n                        sample.close();\n                    }\n                }\n                for (const x of processed) {\n                    if (x instanceof VideoSample && x !== videoSample) {\n                        x.close();\n                    }\n                    else if (typeof VideoFrame !== 'undefined' && x instanceof VideoFrame) {\n                        x.close();\n                    }\n                }\n                throw error;\n            }\n            samplesToEncode = mappedSamples;\n        }\n        else {\n            samplesToEncode = [videoSample];\n        }\n        try {\n            for (const sampleToEncode of samplesToEncode) {\n                if (!this.encoderInitialized) {\n                    if (!this.ensureEncoderPromise) {\n                        this.ensureEncoder(sampleToEncode);\n                    }\n                    // No, this \"if\" statement is not useless. Sometimes, the above call to\n                    // `ensureEncoder` might have synchronously completed and the encoder is\n                    // already initialized. In this case, we don't need to await the promise\n                    // anymore. This also fixes nasty async race condition bugs when multiple\n                    // code paths are calling this method: It's important that the call that\n                    // initialized the encoder go through this code first.\n                    if (!this.encoderInitialized) {\n                        await this.ensureEncoderPromise;\n                    }\n                }\n                assert(this.encoderInitialized);\n                if (this.closed) {\n                    break;\n                }\n                if (this.encodersReclaimed) {\n                    this.recreateWebCodecsEncoders();\n                }\n                const keyFrameInterval = this.encodingConfig.keyFrameInterval ?? 2;\n                const multipleOfKeyFrameInterval = Math.floor(sampleToEncode.timestamp / keyFrameInterval);\n                const mergedEncodeOptions = {\n                    ...this.defaultEncodeOptions,\n                    ...sampleToEncode.encodeOptions,\n                    ...encodeOptions,\n                };\n                const finalEncodeOptions = {\n                    ...mergedEncodeOptions,\n                    keyFrame: mergedEncodeOptions.keyFrame !== undefined\n                        ? mergedEncodeOptions.keyFrame\n                        // Ensure a key frame every keyFrameInterval seconds. It is important that all video tracks\n                        // follow the same \"key frame\" rhythm, because aligned key frames are required to start new\n                        // fragments in ISOBMFF or clusters in Matroska (or at least desirable).\n                        : keyFrameInterval === 0\n                            || multipleOfKeyFrameInterval !== this.lastMultipleOfKeyFrameInterval,\n                };\n                this.lastMultipleOfKeyFrameInterval = multipleOfKeyFrameInterval;\n                this.encodingConfig.onEncodedSample?.(sampleToEncode);\n                if (this.customEncoder) {\n                    this.customEncoderQueueSize++;\n                    // We clone the sample so it cannot be closed on us from the outside before it reaches the encoder\n                    const clonedSample = sampleToEncode.clone();\n                    const promise = this.customEncoderCallSerializer\n                        .call(() => this.customEncoder.encode(clonedSample, finalEncodeOptions))\n                        .catch((error) => this.setError(error))\n                        .finally(() => {\n                        this.customEncoderQueueSize--;\n                        clonedSample.close();\n                    });\n                    if (this.customEncoderQueueSize >= 4) {\n                        await promise;\n                    }\n                }\n                else {\n                    assert(this.encoder);\n                    const videoFrame = sampleToEncode.toVideoFrame();\n                    const preciseTimingIndex = binarySearchLessOrEqual(this.preciseTimings, videoFrame.timestamp, x => x.microsecondTimestamp);\n                    const existingEntry = preciseTimingIndex !== -1\n                        ? this.preciseTimings[preciseTimingIndex]\n                        : null;\n                    if (existingEntry && existingEntry.microsecondTimestamp === videoFrame.timestamp) {\n                        if (existingEntry.timestamp !== sampleToEncode.timestamp) {\n                            // Mapping isn't unique, can't use the timestamp\n                            existingEntry.timestampIsValid = false;\n                        }\n                        if (existingEntry.duration !== sampleToEncode.duration) {\n                            // Mapping isn't unique, can't use the duration\n                            existingEntry.durationIsValid = false;\n                        }\n                    }\n                    else {\n                        this.preciseTimings.splice(preciseTimingIndex + 1, 0, {\n                            microsecondTimestamp: videoFrame.timestamp,\n                            timestamp: sampleToEncode.timestamp,\n                            duration: sampleToEncode.duration,\n                            timestampIsValid: true,\n                            durationIsValid: true,\n                        });\n                        // Make sure it doesn't grow indefinitely\n                        if (this.preciseTimings.length > 128) {\n                            this.preciseTimings.shift();\n                        }\n                    }\n                    if (!this.alphaEncoder) {\n                        // No alpha encoder, simple case\n                        try {\n                            this.encoder.encode(videoFrame, finalEncodeOptions);\n                        }\n                        finally {\n                            videoFrame.close();\n                        }\n                    }\n                    else {\n                        // We're expected to encode alpha as well\n                        const frameDefinitelyHasNoAlpha = !!videoFrame.format && !videoFrame.format.includes('A');\n                        if (frameDefinitelyHasNoAlpha || this.splitterCreationFailed) {\n                            this.alphaFrameQueue.push(null);\n                            try {\n                                this.encoder.encode(videoFrame, finalEncodeOptions);\n                            }\n                            finally {\n                                videoFrame.close();\n                            }\n                        }\n                        else {\n                            if (!this.splitter) {\n                                this.splitter = new ColorAlphaSplitter();\n                            }\n                            // The splitter takes ownership, so no need to close the frames ourselves\n                            const { colorFrame, alphaFrame } = await this.splitter.split(videoFrame);\n                            this.alphaFrameQueue.push(alphaFrame);\n                            try {\n                                this.encoder.encode(colorFrame, finalEncodeOptions);\n                            }\n                            finally {\n                                colorFrame.close();\n                            }\n                        }\n                    }\n                    // We need to do this after sending the frame to the encoder as the frame otherwise might be closed\n                    if (this.encoder.encodeQueueSize >= 4) {\n                        await new Promise(resolve => this.encoder.addEventListener('dequeue', resolve, { once: true }));\n                    }\n                }\n                await this.lastMuxerPromise; // Allow the writer to apply backpressure\n            }\n        }\n        finally {\n            for (const sample of samplesToEncode) {\n                if (sample !== videoSample) {\n                    sample.close();\n                }\n            }\n        }\n    }\n    /** Repeats the last frame rate sample to fill the gap up to the given timestamp. */\n    async padFrameRate(until, encodeOptions) {\n        const frameRate = this.encodingConfig.transform.frameRate;\n        assert(this.frameRateLastSample);\n        const frameDifference = Math.round((until - this.frameRateLastTimestamp) * frameRate);\n        for (let i = 1; i < frameDifference; i++) {\n            const env_1 = { stack: [], error: void 0, hasError: false };\n            try {\n                const sample = __addDisposableResource(env_1, this.frameRateLastSample.clone(), false);\n                sample.setTimestamp(this.frameRateLastTimestamp + i / frameRate);\n                sample.setDuration(1 / frameRate);\n                await this.processAndEncode(sample, encodeOptions);\n            }\n            catch (e_1) {\n                env_1.error = e_1;\n                env_1.hasError = true;\n            }\n            finally {\n                __disposeResources(env_1);\n            }\n        }\n    }\n    ensureEncoder(videoSample) {\n        this.ensureEncoderPromise = (async () => {\n            // eslint-disable-next-line @typescript-eslint/no-deprecated\n            const quality = resolveQuality(this.encodingConfig.quality, this.encodingConfig.bitrate);\n            assert(quality !== undefined);\n            const candidates = buildVideoEncoderConfigs({\n                ...this.encodingConfig,\n                quality,\n                width: videoSample.codedWidth,\n                height: videoSample.codedHeight,\n                squarePixelWidth: videoSample.squarePixelWidth,\n                squarePixelHeight: videoSample.squarePixelHeight,\n                framerate: this.source._connectedTrack?.metadata.frameRate,\n            });\n            // Try the candidate configs in order of preference until we find one that is supported\n            let selected = null;\n            let MatchingCustomEncoder;\n            for (const candidate of candidates) {\n                const candidateConfig = candidate.config;\n                this.encodingConfig.onEncoderConfig?.(candidateConfig);\n                MatchingCustomEncoder = customVideoEncoders.find(x => x.supports(this.encodingConfig.codec, candidateConfig));\n                if (MatchingCustomEncoder) {\n                    selected = candidate;\n                    break;\n                }\n                if (typeof VideoEncoder === 'undefined') {\n                    continue;\n                }\n                candidateConfig.alpha = 'discard'; // Since we handle alpha ourselves\n                if (this.encodingConfig.alpha === 'keep') {\n                    // Encoding alpha requires using two parallel encoders, so we need to make sure they stay in sync\n                    // and that neither of them drops frames. Setting latencyMode to 'quality' achieves this, because\n                    // \"User Agents MUST not drop frames to achieve the target bitrate and/or framerate.\"\n                    candidateConfig.latencyMode = 'quality';\n                }\n                const hasOddDimension = candidateConfig.width % 2 === 1 || candidateConfig.height % 2 === 1;\n                if (hasOddDimension\n                    && (this.encodingConfig.codec === 'avc' || this.encodingConfig.codec === 'hevc')) {\n                    // Throw a special error for this case as it gets hit often\n                    throw new Error(`The dimensions ${candidateConfig.width}x${candidateConfig.height} are not supported for codec`\n                        + ` '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to`\n                        + ` round your dimensions to the nearest even number.`);\n                }\n                try {\n                    const support = await VideoEncoder.isConfigSupported(candidateConfig);\n                    if (support.supported) {\n                        selected = candidate;\n                        break;\n                    }\n                }\n                catch {\n                    // Not supported\n                }\n            }\n            if (!selected) {\n                if (typeof VideoEncoder === 'undefined') {\n                    throw new Error(missingWebCodecsClassMessage('VideoEncoder'));\n                }\n                // The candidates only differ in their rate control, so we describe them as one config with a\n                // slash-separated list of the attempted rate control methods\n                const firstConfig = candidates[0].config;\n                const rateControls = candidates.map(({ config, quantizer }) => quantizer !== null ? `quantizer ${quantizer}` : `${config.bitrate} bps`);\n                throw new Error(`This specific encoder configuration (${firstConfig.codec}, ${rateControls.join(' / ')},`\n                    + ` ${firstConfig.width}x${firstConfig.height}, hardware acceleration:`\n                    + ` ${firstConfig.hardwareAcceleration ?? 'no-preference'}) is not supported in this environment.`\n                    + ` Consider using another codec or changing your video parameters.`);\n            }\n            const encoderConfig = selected.config;\n            if (selected.quantizer !== null) {\n                // The chosen config uses quantizer-based rate control, so each frame must carry the quantizer value\n                this.defaultEncodeOptions = buildQuantizerEncodeOptions(this.encodingConfig.codec, selected.quantizer);\n            }\n            else {\n                this.source._nominalBitrate = encoderConfig.bitrate ?? null;\n            }\n            if (MatchingCustomEncoder) {\n                // @ts-expect-error \"Can't create instance of abstract class 🤓\"\n                this.customEncoder = new MatchingCustomEncoder();\n                // @ts-expect-error It's technically readonly\n                this.customEncoder.codec = this.encodingConfig.codec;\n                // @ts-expect-error It's technically readonly\n                this.customEncoder.config = encoderConfig;\n                // @ts-expect-error It's technically readonly\n                this.customEncoder.onPacket = (packet, meta) => {\n                    if (!(packet instanceof EncodedPacket)) {\n                        throw new TypeError('The first argument passed to onPacket must be an EncodedPacket.');\n                    }\n                    if (meta !== undefined && (!meta || typeof meta !== 'object')) {\n                        throw new TypeError('The second argument passed to onPacket must be an object or undefined.');\n                    }\n                    maybeEnsureIsKeyPacket(this.source._connectedTrack, packet);\n                    this.encodingConfig.onEncodedPacket?.(packet, meta);\n                    this.lastMuxerPromise\n                        = this.muxer.addEncodedVideoPacket(this.source._connectedTrack, packet, meta)\n                            .catch((error) => {\n                            this.setError(error);\n                        });\n                };\n                // @ts-expect-error It's technically readonly\n                this.customEncoder.onError = (error) => {\n                    this.setError(error);\n                };\n                await this.customEncoder.init();\n            }\n            else {\n                this.encoderConfig = encoderConfig;\n                if (this.encodingConfig.codec === 'avc' && isFirefox()) {\n                    this.chunkTimestampsAreShiftedByDuration = await detectAvcChunkTimestampShift();\n                }\n                this.createWebCodecsEncoders();\n            }\n            assert(this.source._connectedTrack);\n            this.muxer = this.source._connectedTrack.output._muxer;\n            this.encoderInitialized = true;\n        })();\n    }\n    createWebCodecsEncoders() {\n        const encoderConfig = this.encoderConfig;\n        assert(encoderConfig);\n        /** Queue of color chunks waiting for their alpha counterpart. */\n        const colorChunkQueue = [];\n        /** Each value is the number of encoded alpha chunks at which a null alpha chunk should be added. */\n        const nullAlphaChunkQueue = [];\n        let encodedAlphaChunkCount = 0;\n        let alphaEncoderQueue = 0;\n        const handleError = (error, stack) => {\n            if (isCodecReclaimedError(error)) {\n                this.encodersReclaimed = true;\n                return;\n            }\n            error.stack = stack; // Provide a more useful stack trace, the default one sucks\n            this.setError(error);\n        };\n        const stack = new Error('Encoding error').stack;\n        this.encoder = new VideoEncoder({\n            output: (chunk, meta) => {\n                if (!this.alphaEncoder) {\n                    // We're done\n                    this.addPacket(chunk, null, meta);\n                    return;\n                }\n                const alphaFrame = this.alphaFrameQueue.shift();\n                assert(alphaFrame !== undefined);\n                if (alphaFrame) {\n                    this.alphaEncoder.encode(alphaFrame, {\n                        ...this.defaultEncodeOptions,\n                        // Crucial: The alpha frame is forced to be a key frame whenever the color frame\n                        // also is. Without this, playback can glitch and even crash in some browsers.\n                        // This is the reason why the two encoders are wired in series and not in parallel.\n                        keyFrame: chunk.type === 'key',\n                    });\n                    alphaEncoderQueue++;\n                    alphaFrame.close();\n                    colorChunkQueue.push({ chunk, meta });\n                }\n                else {\n                    // There was no alpha component for this frame\n                    if (alphaEncoderQueue === 0) {\n                        // No pending alpha encodes either, so we're done\n                        this.addPacket(chunk, null, meta);\n                    }\n                    else {\n                        // There are still alpha encodes pending, so we can't add the packet immediately since\n                        // we'd end up with out-of-order packets. Instead, let's queue a null alpha chunk to be\n                        // added in the future, after the current encoder workload has completed:\n                        nullAlphaChunkQueue.push(encodedAlphaChunkCount + alphaEncoderQueue);\n                        colorChunkQueue.push({ chunk, meta });\n                    }\n                }\n            },\n            error: error => handleError(error, stack),\n        });\n        this.encoder.configure(encoderConfig);\n        if (this.encodingConfig.alpha === 'keep') {\n            const stack = new Error('Encoding error').stack;\n            // We need to encode alpha as well, which we do with a separate encoder\n            this.alphaEncoder = new VideoEncoder({\n                // We ignore the alpha chunk's metadata\n                // eslint-disable-next-line @typescript-eslint/no-unused-vars\n                output: (chunk, meta) => {\n                    alphaEncoderQueue--;\n                    // There has to be a color chunk because the encoders are wired in series\n                    const colorChunk = colorChunkQueue.shift();\n                    assert(colorChunk !== undefined);\n                    this.addPacket(colorChunk.chunk, chunk, colorChunk.meta);\n                    // See if there are any null alpha chunks queued up\n                    encodedAlphaChunkCount++;\n                    while (nullAlphaChunkQueue.length > 0\n                        && nullAlphaChunkQueue[0] === encodedAlphaChunkCount) {\n                        nullAlphaChunkQueue.shift();\n                        const colorChunk = colorChunkQueue.shift();\n                        assert(colorChunk !== undefined);\n                        this.addPacket(colorChunk.chunk, null, colorChunk.meta);\n                    }\n                },\n                error: error => handleError(error, stack),\n            });\n            this.alphaEncoder.configure(encoderConfig);\n        }\n    }\n    addPacket(colorChunk, alphaChunk, meta) {\n        const sideData = {};\n        if (alphaChunk) {\n            const alphaData = new Uint8Array(alphaChunk.byteLength);\n            alphaChunk.copyTo(alphaData);\n            sideData.alpha = alphaData;\n        }\n        let packet = EncodedPacket.fromEncodedChunk(colorChunk, sideData);\n        const encoderConfig = this.encoderConfig;\n        assert(encoderConfig);\n        if (meta?.decoderConfig) {\n            // Let's correct the codec string based on the actual bitstream data, rather than leaving it on the default\n            // value (which is just what was in the encoder config). This provides better consistency.\n            meta.decoderConfig.codec = extractVideoCodecString({\n                width: encoderConfig.width,\n                height: encoderConfig.height,\n                codec: this.encodingConfig.codec,\n                codecDescription: meta.decoderConfig.description\n                    ? toUint8Array(meta.decoderConfig.description)\n                    : null,\n                colorSpace: meta.decoderConfig.colorSpace ?? null,\n                avcType: encoderConfig.codec.includes('avc1.')\n                    ? 1\n                    : encoderConfig.codec.includes('avc3.')\n                        ? 3\n                        : null,\n                avcCodecInfo: this.encodingConfig.codec === 'avc' && !meta.decoderConfig.description\n                    ? extractAvcDecoderConfigurationRecord(packet.data)\n                    : null,\n                hevcCodecInfo: this.encodingConfig.codec === 'hevc' && !meta.decoderConfig.description\n                    ? extractHevcDecoderConfigurationRecord(packet.data)\n                    : null,\n                vp9CodecInfo: this.encodingConfig.codec === 'vp9'\n                    ? extractVp9CodecInfoFromPacket(packet.data)\n                    : null,\n                av1CodecInfo: this.encodingConfig.codec === 'av1'\n                    ? extractAv1CodecInfoFromPacket(packet.data)\n                    : null,\n                proresFormat: null, // Can't be encoded by WebCodecs\n            });\n            if (this.encodingConfig.codec === 'avc' && meta.decoderConfig.description && isFirefox()) {\n                // This works around https://bugzilla.mozilla.org/show_bug.cgi?id=2082867\n                // Also see https://github.com/Vanilagy/mediabunny/issues/559\n                const parsed = deserializeAvcDecoderConfigurationRecord(toUint8Array(meta.decoderConfig.description));\n                let sps = parsed?.sequenceParameterSets[0];\n                if (sps && sps[0] === sps[1]) { // The first two bytes of the SPS being the same is a reliable signal\n                    assert(parsed);\n                    sps = sps.subarray(1);\n                    let pps = parsed.pictureParameterSets[0];\n                    if (pps) {\n                        pps = pps.subarray(1);\n                    }\n                    const record = serializeAvcDecoderConfigurationRecord({\n                        ...parsed,\n                        sequenceParameterSets: [sps],\n                        pictureParameterSets: pps ? [pps] : [],\n                    });\n                    meta.decoderConfig.description = record;\n                }\n            }\n        }\n        let microsecondTimestamp = colorChunk.timestamp;\n        if (this.chunkTimestampsAreShiftedByDuration) {\n            // The encoder added the frame's duration to its timestamp, so undo that\n            microsecondTimestamp -= colorChunk.duration ?? 0;\n            packet = packet.clone({ timestamp: microsecondTimestamp / 1e6 });\n        }\n        // See if there's a relevant timing entry to refine the packet's timing data\n        const preciseTimingIndex = binarySearchLessOrEqual(this.preciseTimings, microsecondTimestamp, x => x.microsecondTimestamp);\n        const entry = preciseTimingIndex !== -1\n            ? this.preciseTimings[preciseTimingIndex]\n            : null;\n        let actualType = null;\n        if (this.emittedEncoderPackets === 0 && packet.type === 'delta' && meta?.decoderConfig) {\n            // https://github.com/Vanilagy/mediabunny/issues/365\n            // We expect the first packet to be a key packet. If it's not, let's actually verify that it's\n            // not by getting the actual type.\n            actualType = determineVideoPacketType(this.encodingConfig.codec, meta.decoderConfig, packet.data);\n        }\n        // Define the packet\n        if ((entry && entry.microsecondTimestamp === microsecondTimestamp) || actualType !== null) {\n            packet = packet.clone({\n                timestamp: entry?.timestampIsValid ? entry.timestamp : undefined,\n                duration: entry?.durationIsValid ? entry.duration : undefined,\n                type: actualType ?? undefined,\n            });\n        }\n        maybeEnsureIsKeyPacket(this.source._connectedTrack, packet);\n        this.encodingConfig.onEncodedPacket?.(packet, meta);\n        this.lastMuxerPromise\n            = this.muxer.addEncodedVideoPacket(this.source._connectedTrack, packet, meta)\n                .catch((error) => {\n                this.setError(error);\n            });\n        this.emittedEncoderPackets++;\n    }\n    // Browsers may reclaim codecs that have been inactive for a while (see\n    // https://github.com/Vanilagy/mediabunny/issues/531), closing them and reporting a QuotaExceededError. Since a\n    // reclaimed encoder was idle, no frames are lost, so we transparently replace the encoders with fresh ones.\n    recreateWebCodecsEncoders() {\n        assert(this.encoder);\n        if (this.encoder.state !== 'closed') {\n            this.encoder.close();\n        }\n        if (this.alphaEncoder && this.alphaEncoder.state !== 'closed') {\n            this.alphaEncoder.close();\n        }\n        this.alphaFrameQueue.forEach(x => x?.close());\n        this.alphaFrameQueue.length = 0;\n        this.encodersReclaimed = false;\n        this.lastMultipleOfKeyFrameInterval = -1; // The fresh encoder must start with a key frame\n        this.createWebCodecsEncoders();\n    }\n    async flushAndClose(forceClose) {\n        try {\n            if (!forceClose) {\n                this.checkForEncoderError();\n                // Final frame rate padding: fill remaining frames up to the last sample's original end timestamp\n                if (this.frameRateLastSample) {\n                    const frameRate = this.encodingConfig.transform.frameRate;\n                    const alignedEnd = floorToDivisor(this.frameRateLastEndTimestamp, frameRate);\n                    await this.padFrameRate(alignedEnd);\n                }\n            }\n            this.closed = true;\n            if (!forceClose) {\n                if (this.customEncoder) {\n                    void this.customEncoderCallSerializer.call(() => this.customEncoder.flush());\n                }\n                else if (this.encoder && !this.encodersReclaimed) {\n                    // These are wired in series, therefore they must also be flushed in series\n                    await this.encoder.flush();\n                    await this.alphaEncoder?.flush();\n                    // Workaround for https://issues.chromium.org/issues/529852980 to give it time for errors to\n                    // surface\n                    await wait(25);\n                }\n            }\n        }\n        finally {\n            // This cleanup must also run when padding or flushing threw (e.g. due to an encoder error), otherwise\n            // samples, frames and encoders would be left dangling\n            this.closed = true;\n            this.frameRateLastSample?.close();\n            this.frameRateLastSample = null;\n            if (this.customEncoder) {\n                await this.customEncoderCallSerializer.call(() => this.customEncoder.close())\n                    .catch((error) => this.setError(error));\n            }\n            else if (this.encoder) {\n                if (this.encoder.state !== 'closed') {\n                    this.encoder.close();\n                }\n                if (this.alphaEncoder && this.alphaEncoder.state !== 'closed') {\n                    this.alphaEncoder.close();\n                }\n                this.alphaFrameQueue.forEach(x => x?.close());\n                this.alphaFrameQueue.length = 0;\n                this.splitter?.close();\n            }\n        }\n        if (!forceClose) {\n            this.checkForEncoderError();\n        }\n    }\n    getQueueSize() {\n        if (this.customEncoder) {\n            return this.customEncoderQueueSize;\n        }\n        else {\n            // Because the color and alpha encoders are wired in series, there's no need to also include the alpha\n            // encoder's queue size here\n            return this.encoder?.encodeQueueSize ?? 0;\n        }\n    }\n    checkForEncoderError() {\n        if (this.errorSet) {\n            throw this.error;\n        }\n    }\n}\nlet avcChunkTimestampShiftPromise = null;\n// Detects https://bugzilla.mozilla.org/show_bug.cgi?id=2082890 so we can work around it\nconst detectAvcChunkTimestampShift = () => {\n    return avcChunkTimestampShiftPromise ??= (async () => {\n        let chunkTimestamp = null;\n        const encoder = new VideoEncoder({\n            output: (chunk) => {\n                chunkTimestamp ??= chunk.timestamp;\n            },\n            error: () => { },\n        });\n        try {\n            encoder.configure({\n                codec: 'avc1.64001f',\n                width: 1280,\n                height: 720,\n            });\n            const frame = new VideoFrame(new Uint8Array(1280 * 720 * 1.5), {\n                format: 'I420',\n                codedWidth: 1280,\n                codedHeight: 720,\n                timestamp: 0,\n                duration: 500,\n            });\n            encoder.encode(frame, { keyFrame: true });\n            frame.close();\n            await encoder.flush();\n        }\n        catch {\n            return false;\n        }\n        finally {\n            if (encoder.state !== 'closed') {\n                encoder.close();\n            }\n        }\n        return chunkTimestamp === 500;\n    })();\n};\nlet splitterWorkerUrl = null;\n/** Utility class for splitting a composite frame into separate color and alpha parts on the CPU in a worker. */\nexport class ColorAlphaSplitter {\n    constructor() {\n        this.worker = null;\n        this.pendingRequests = new Map();\n        this.nextRequestId = 0;\n    }\n    split(sourceFrame) {\n        if (!this.worker) {\n            if (!splitterWorkerUrl) {\n                const blob = new Blob([`(${colorAlphaSplitterWorkerCode.toString()})()`], { type: 'application/javascript' });\n                splitterWorkerUrl = URL.createObjectURL(blob);\n            }\n            this.worker = new Worker(splitterWorkerUrl);\n            this.worker.addEventListener('message', (event) => {\n                const data = event.data;\n                const pending = this.pendingRequests.get(data.id);\n                if (!pending) {\n                    return;\n                }\n                this.pendingRequests.delete(data.id);\n                if ('error' in data) {\n                    pending.reject(new Error(data.error));\n                }\n                else {\n                    pending.resolve({ colorFrame: data.colorFrame, alphaFrame: data.alphaFrame });\n                }\n            });\n            this.worker.addEventListener('error', (event) => {\n                const error = new Error(event.message || 'Color/alpha splitter worker error.');\n                for (const pending of this.pendingRequests.values()) {\n                    pending.reject(error);\n                }\n                this.pendingRequests.clear();\n            });\n        }\n        const id = this.nextRequestId++;\n        const pending = promiseWithResolvers();\n        this.pendingRequests.set(id, pending);\n        this.worker.postMessage({ id, sourceFrame }, { transfer: [sourceFrame] });\n        return pending.promise;\n    }\n    close() {\n        this.worker?.terminate();\n        this.worker = null;\n        const error = new Error('Color/alpha splitter closed.');\n        for (const pending of this.pendingRequests.values()) {\n            pending.reject(error);\n        }\n        this.pendingRequests.clear();\n    }\n}\nconst colorAlphaSplitterWorkerCode = () => {\n    // Reused across frames as long as the size matches, since consecutive frames usually share dimensions.\n    let cpuSourceBuffer = null;\n    // Serialize execution internally so concurrent requests don't race on the shared cpuSourceBuffer.\n    let chain = Promise.resolve();\n    self.addEventListener('message', (event) => {\n        const { id, sourceFrame } = event.data;\n        chain = chain.then(async () => {\n            try {\n                const { colorFrame, alphaFrame } = await split(sourceFrame);\n                self.postMessage({ id, colorFrame, alphaFrame }, { transfer: [colorFrame, alphaFrame] });\n            }\n            catch (error) {\n                self.postMessage({ id, error: error.message });\n            }\n            finally {\n                sourceFrame.close();\n            }\n        });\n    });\n    const split = async (sourceFrame) => {\n        const format = sourceFrame.format;\n        if (!format) {\n            throw new Error('CPU color/alpha splitting requires a known VideoFrame format.');\n        }\n        const sourceSize = sourceFrame.allocationSize();\n        if (!cpuSourceBuffer || cpuSourceBuffer.byteLength !== sourceSize) {\n            cpuSourceBuffer = new Uint8Array(sourceSize);\n        }\n        await sourceFrame.copyTo(cpuSourceBuffer);\n        if (format === 'RGBA' || format === 'BGRA') {\n            return splitInterleavedRgba(cpuSourceBuffer, format, sourceFrame);\n        }\n        else if (format === 'I420A' || format === 'I420AP10' || format === 'I420AP12'\n            || format === 'I422A' || format === 'I422AP10' || format === 'I422AP12'\n            || format === 'I444A' || format === 'I444AP10' || format === 'I444AP12') {\n            return splitPlanarYuvA(cpuSourceBuffer, format, sourceFrame);\n        }\n        throw new Error(`CPU color/alpha splitting does not support format '${format}'.`);\n    };\n    const splitInterleavedRgba = (source, format, sourceFrame) => {\n        const width = sourceFrame.visibleRect?.width ?? sourceFrame.codedWidth;\n        const height = sourceFrame.visibleRect?.height ?? sourceFrame.codedHeight;\n        const pixelCount = width * height;\n        const chromaW = Math.ceil(width / 2);\n        const chromaH = Math.ceil(height / 2);\n        const alphaSize = pixelCount + chromaW * chromaH * 2;\n        // Encode alpha as I420: Y = source A bytes, UV = 128\n        const alphaBuffer = new Uint8Array(alphaSize);\n        for (let i = 0, j = 3; i < pixelCount; i++, j += 4) {\n            alphaBuffer[i] = source[j];\n        }\n        alphaBuffer.fill(128, pixelCount);\n        // Hand the source buffer straight to VideoFrame as RGBX/BGRX so the A bytes are ignored\n        const colorFrame = new VideoFrame(source, {\n            format: format === 'RGBA' ? 'RGBX' : 'BGRX',\n            codedWidth: width,\n            codedHeight: height,\n            timestamp: sourceFrame.timestamp,\n            duration: sourceFrame.duration ?? undefined,\n            // No transfer!\n        });\n        const alphaInit = {\n            format: 'I420',\n            codedWidth: width,\n            codedHeight: height,\n            timestamp: sourceFrame.timestamp,\n            duration: sourceFrame.duration ?? undefined,\n            colorSpace: {\n                fullRange: true,\n                matrix: 'bt709',\n                primaries: 'bt709',\n                transfer: 'bt709',\n            },\n            transfer: [alphaBuffer.buffer],\n        };\n        const alphaFrame = new VideoFrame(alphaBuffer, alphaInit);\n        return { colorFrame, alphaFrame };\n    };\n    const splitPlanarYuvA = (source, format, sourceFrame) => {\n        const width = sourceFrame.visibleRect?.width ?? sourceFrame.codedWidth;\n        const height = sourceFrame.visibleRect?.height ?? sourceFrame.codedHeight;\n        const is10 = format.includes('P10');\n        const is12 = format.includes('P12');\n        const bytesPerSample = (is10 || is12) ? 2 : 1;\n        let chromaW;\n        let chromaH;\n        if (format.startsWith('I420')) {\n            chromaW = Math.ceil(width / 2);\n            chromaH = Math.ceil(height / 2);\n        }\n        else if (format.startsWith('I422')) {\n            chromaW = Math.ceil(width / 2);\n            chromaH = height;\n        }\n        else {\n            chromaW = width;\n            chromaH = height;\n        }\n        const ySamples = width * height;\n        const uvSamples = chromaW * chromaH;\n        const yBytes = ySamples * bytesPerSample;\n        const uvBytes = uvSamples * bytesPerSample;\n        const aBytes = ySamples * bytesPerSample;\n        const colorBytes = yBytes + uvBytes * 2;\n        const colorFormat = format.replace('A', '');\n        const alphaChromaW = Math.ceil(width / 2);\n        const alphaChromaH = Math.ceil(height / 2);\n        const alphaUvSamples = alphaChromaW * alphaChromaH;\n        const alphaUvBytes = alphaUvSamples * bytesPerSample;\n        const alphaSize = aBytes + 2 * alphaUvBytes;\n        const alphaBuffer = new Uint8Array(alphaSize);\n        const aPlaneStart = colorBytes;\n        alphaBuffer.set(source.subarray(aPlaneStart, aPlaneStart + aBytes), 0);\n        // Fill UV planes with the neutral chroma value\n        const uvOffset = aBytes;\n        const neutralChroma = is10 ? 512 : (is12 ? 2048 : 128);\n        if (bytesPerSample === 1) {\n            alphaBuffer.fill(neutralChroma, uvOffset);\n        }\n        else {\n            const uvView = new Uint16Array(alphaBuffer.buffer, uvOffset, 2 * alphaUvSamples);\n            uvView.fill(neutralChroma);\n        }\n        const alphaFormat = (is10 ? 'I420P10' : (is12 ? 'I420P12' : 'I420'));\n        // Color frame is simply a prefix of the combined bytes\n        const colorFrame = new VideoFrame(source.subarray(0, colorBytes), {\n            format: colorFormat,\n            codedWidth: width,\n            codedHeight: height,\n            timestamp: sourceFrame.timestamp,\n            duration: sourceFrame.duration ?? undefined,\n        });\n        const alphaInit = {\n            format: alphaFormat,\n            codedWidth: width,\n            codedHeight: height,\n            timestamp: sourceFrame.timestamp,\n            duration: sourceFrame.duration ?? undefined,\n            colorSpace: {\n                fullRange: true,\n                matrix: 'bt709',\n                primaries: 'bt709',\n                transfer: 'bt709',\n            },\n            transfer: [alphaBuffer.buffer],\n        };\n        const alphaFrame = new VideoFrame(alphaBuffer, alphaInit);\n        return { colorFrame, alphaFrame };\n    };\n};\n/**\n * This source can be used to add raw, unencoded video samples (frames) to an output video track. These frames will\n * automatically be encoded and then piped into the output.\n * @group Media sources\n * @public\n */\nexport class VideoSampleSource extends VideoSource {\n    /**\n     * Creates a new {@link VideoSampleSource} whose samples are encoded according to the specified\n     * {@link VideoEncodingConfig}.\n     */\n    constructor(encodingConfig) {\n        validateVideoEncodingConfig(encodingConfig);\n        super(encodingConfig.codec);\n        this._encoder = new VideoEncoderWrapper(this, encodingConfig);\n    }\n    /**\n     * Encodes a video sample (frame) and then adds it to the output.\n     *\n     * @returns A Promise that resolves once the output is ready to receive more samples. You should await this Promise\n     * to respect writer and encoder backpressure.\n     */\n    add(videoSample, encodeOptions) {\n        if (!(videoSample instanceof VideoSample)) {\n            throw new TypeError('videoSample must be a VideoSample.');\n        }\n        return this._encoder.add(videoSample, false, encodeOptions);\n    }\n    /** @internal */\n    _flushAndClose(forceClose) {\n        return this._encoder.flushAndClose(forceClose);\n    }\n}\n/**\n * This source can be used to add video frames to the output track from a fixed canvas element. Since canvases are often\n * used for rendering, this source provides a convenient wrapper around {@link VideoSampleSource}.\n * @group Media sources\n * @public\n */\nexport class CanvasSource extends VideoSource {\n    /**\n     * Creates a new {@link CanvasSource} from a canvas element or `OffscreenCanvas` whose samples are encoded\n     * according to the specified {@link VideoEncodingConfig}.\n     */\n    constructor(canvas, encodingConfig) {\n        if (!(typeof HTMLCanvasElement !== 'undefined' && canvas instanceof HTMLCanvasElement)\n            && !(typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas)) {\n            throw new TypeError('canvas must be an HTMLCanvasElement or OffscreenCanvas.');\n        }\n        validateVideoEncodingConfig(encodingConfig);\n        super(encodingConfig.codec);\n        this._encoder = new VideoEncoderWrapper(this, encodingConfig);\n        this._canvas = canvas;\n    }\n    /**\n     * Captures the current canvas state as a video sample (frame), encodes it and adds it to the output.\n     *\n     * @param timestamp - The timestamp of the sample, in seconds.\n     * @param duration - The duration of the sample, in seconds.\n     *\n     * @returns A Promise that resolves once the output is ready to receive more samples. You should await this Promise\n     * to respect writer and encoder backpressure.\n     */\n    add(timestamp, duration = 0, encodeOptions) {\n        if (!Number.isFinite(timestamp)) {\n            throw new TypeError('timestamp must be a finite number.');\n        }\n        if (!Number.isFinite(duration) || duration < 0) {\n            throw new TypeError('duration must be a non-negative number.');\n        }\n        const sample = new VideoSample(this._canvas, { timestamp, duration });\n        return this._encoder.add(sample, true, encodeOptions);\n    }\n    /** @internal */\n    _flushAndClose(forceClose) {\n        return this._encoder.flushAndClose(forceClose);\n    }\n}\n/**\n * Video source that encodes the frames of a\n * [`MediaStreamVideoTrack`](https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack) and pipes them into the\n * output. This is useful for capturing live or real-time data such as webcams or screen captures. Frames will\n * automatically start being captured once the connected {@link Output} is started, and will keep being captured until\n * the {@link Output} is finalized or this source is closed.\n * @group Media sources\n * @public\n */\nexport class MediaStreamVideoTrackSource extends VideoSource {\n    /** A promise that rejects upon any error within this source. This promise never resolves. */\n    get errorPromise() {\n        this._errorPromiseAccessed = true;\n        return this._promiseWithResolvers.promise;\n    }\n    /** Whether this source is currently paused as a result of calling `.pause()`. */\n    get paused() {\n        return this._paused;\n    }\n    /**\n     * Creates a new {@link MediaStreamVideoTrackSource} from a\n     * [`MediaStreamVideoTrack`](https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack), which will pull\n     * video samples from the stream in real time and encode them according to {@link VideoEncodingConfig}.\n     */\n    constructor(track, encodingConfig, options = {}) {\n        if (!(track instanceof MediaStreamTrack) || track.kind !== 'video') {\n            throw new TypeError('track must be a video MediaStreamTrack.');\n        }\n        validateVideoEncodingConfig(encodingConfig);\n        if (typeof options !== 'object' || !options) {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.frameRate != null && (typeof options.frameRate !== 'number' || options.frameRate <= 0)) {\n            throw new TypeError('options.frameRate, when provided, must be either a positive number or null.');\n        }\n        if (options.timestampBase !== undefined\n            && options.timestampBase !== 'synced-zero'\n            && options.timestampBase !== 'zero'\n            && options.timestampBase !== 'unix') {\n            throw new TypeError('options.timestampBase, when provided, must be one of \\'synced-zero\\', \\'zero\\', or \\'unix\\'.');\n        }\n        encodingConfig = {\n            ...encodingConfig,\n            latencyMode: 'realtime',\n        };\n        super(encodingConfig.codec);\n        /** @internal */\n        this._abortController = null;\n        /** @internal */\n        this._workerTrackId = null;\n        /** @internal */\n        this._workerListener = null;\n        /** @internal */\n        this._promiseWithResolvers = promiseWithResolvers();\n        /** @internal */\n        this._errorPromiseAccessed = false;\n        /** @internal */\n        this._paused = false;\n        /** @internal */\n        this._lastVideoFrame = null;\n        /** @internal */\n        this._timerHandle = null;\n        /** @internal */\n        this._videoElement = null;\n        this._options = options;\n        this._encoder = new VideoEncoderWrapper(this, encodingConfig);\n        this._track = track;\n    }\n    /** @internal */\n    async _start() {\n        if (!this._errorPromiseAccessed) {\n            Logging._warn('Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal'\n                + ' errors get bubbled up properly.');\n        }\n        const frameRate = this._options.frameRate !== undefined\n            ? this._options.frameRate\n            : (this._track.getSettings().frameRate ?? null);\n        this._abortController = new AbortController();\n        let firstVideoFrameTimestamp = null;\n        let lastFrameTime = null;\n        let frameCount = 0;\n        let errored = false;\n        let lastSampleTimestamp = null;\n        let timestampOffset = 0;\n        const tick = () => {\n            assert(frameRate !== null);\n            if (!this._lastVideoFrame) {\n                return;\n            }\n            assert(lastFrameTime !== null);\n            assert(firstVideoFrameTimestamp !== null);\n            const now = performance.now();\n            // Add as many frames as warranted by the elapsed time.\n            // > instead of >= intentionally because tick() is called before the _lastVideoFrame is changed\n            while (now - lastFrameTime > 1000 / frameRate) {\n                lastFrameTime += 1000 / frameRate;\n                const timestamp = firstVideoFrameTimestamp + frameCount / frameRate;\n                const frame = new VideoFrame(this._videoElement ?? this._lastVideoFrame, {\n                    timestamp: 1e6 * timestamp,\n                    duration: 1e6 / frameRate,\n                });\n                addVideoFrame(frame, now);\n            }\n        };\n        if (frameRate !== null) {\n            this._timerHandle = setIntervalUnthrottled(tick, 4); // Run it at 250 Hz\n        }\n        const onVideoFrame = (videoFrame) => {\n            if (frameRate === null) {\n                addVideoFrame(videoFrame);\n            }\n            else {\n                const now = performance.now();\n                if (!this._lastVideoFrame) {\n                    addVideoFrame(videoFrame.clone(), now);\n                    lastFrameTime = now;\n                    this._lastVideoFrame = videoFrame;\n                }\n                else {\n                    tick();\n                    this._lastVideoFrame?.close();\n                    this._lastVideoFrame = videoFrame;\n                }\n            }\n        };\n        const addVideoFrame = (videoFrame, now = performance.now()) => {\n            if (errored) {\n                videoFrame.close();\n                return;\n            }\n            frameCount++;\n            const currentTimestamp = videoFrame.timestamp / 1e6;\n            if (this._paused) {\n                const frameSeen = firstVideoFrameTimestamp !== null;\n                if (frameSeen) {\n                    if (lastSampleTimestamp !== null && this._options.timestampBase !== 'unix') {\n                        // In addition to dropping this frame, let's also keep track of the time we have lost due to the\n                        // pause. Doing it like this instead of simply keeping track of the paused time is better since\n                        // it retains the frame rate of the underlying source.\n                        const timeDelta = currentTimestamp - lastSampleTimestamp;\n                        timestampOffset -= timeDelta;\n                    }\n                    lastSampleTimestamp = currentTimestamp;\n                }\n                videoFrame.close();\n                return;\n            }\n            if (firstVideoFrameTimestamp === null) {\n                firstVideoFrameTimestamp = currentTimestamp;\n                let target;\n                const timestampBase = this._options.timestampBase ?? 'synced-zero';\n                if (timestampBase === 'unix') {\n                    target = Date.now() / 1000;\n                }\n                else if (timestampBase === 'zero') {\n                    target = 0;\n                }\n                else {\n                    const output = this._connectedTrack.output;\n                    if (output._firstMediaStreamTimestamp === null) {\n                        output._firstMediaStreamTimestamp = now / 1000;\n                        target = 0;\n                    }\n                    else {\n                        target = now / 1000 - output._firstMediaStreamTimestamp;\n                    }\n                }\n                timestampOffset = target - firstVideoFrameTimestamp;\n            }\n            lastSampleTimestamp = currentTimestamp;\n            if (this._encoder.getQueueSize() >= 8) {\n                // Drop frames if the encoder is overloaded\n                videoFrame.close();\n                return;\n            }\n            const sample = new VideoSample(videoFrame, {\n                timestamp: currentTimestamp + timestampOffset,\n            });\n            void this._encoder.add(sample, true)\n                .catch((error) => {\n                errored = true;\n                this._abortController?.abort();\n                this._promiseWithResolvers.reject(error);\n                if (this._workerTrackId !== null) {\n                    // Tell the worker to stop the track\n                    sendMessageToMediaStreamTrackProcessorWorker({\n                        type: 'stopTrack',\n                        trackId: this._workerTrackId,\n                    });\n                }\n            });\n        };\n        if (typeof MediaStreamTrackProcessor !== 'undefined') {\n            // We can do it here directly, perfect\n            const processor = new MediaStreamTrackProcessor({ track: this._track });\n            const consumer = new WritableStream({ write: onVideoFrame });\n            processor.readable.pipeTo(consumer, {\n                signal: this._abortController.signal,\n            }).catch((error) => {\n                // Handle AbortError silently\n                if (error instanceof DOMException && error.name === 'AbortError')\n                    return;\n                this._promiseWithResolvers.reject(error);\n            });\n        }\n        else {\n            // It might still be supported in a worker, so let's check that\n            const supportedInWorker = await mediaStreamTrackProcessorIsSupportedInWorker();\n            if (supportedInWorker) {\n                this._workerTrackId = nextMediaStreamTrackProcessorWorkerId++;\n                sendMessageToMediaStreamTrackProcessorWorker({\n                    type: 'videoTrack',\n                    trackId: this._workerTrackId,\n                    track: this._track,\n                });\n                this._workerListener = (event) => {\n                    const message = event.data;\n                    if (message.type === 'videoFrame' && message.trackId === this._workerTrackId) {\n                        onVideoFrame(message.videoFrame);\n                    }\n                    else if (message.type === 'error' && message.trackId === this._workerTrackId) {\n                        this._promiseWithResolvers.reject(message.error);\n                    }\n                };\n                mediaStreamTrackProcessorWorker.addEventListener('message', this._workerListener);\n            }\n            else if (frameRate !== null) {\n                // No MediaStreamTrackProcessor support at all (e.g. Firefox), but we have a frame rate, so we can\n                // manually sample from a hidden <video> element instead.\n                const video = document.createElement('video');\n                video.style.position = 'fixed';\n                video.style.left = '-10000px';\n                video.style.top = '-10000px';\n                video.style.width = '1px';\n                video.style.height = '1px';\n                video.style.opacity = '0';\n                video.style.pointerEvents = 'none';\n                video.muted = true;\n                video.srcObject = new MediaStream([this._track]);\n                document.body.appendChild(video);\n                this._videoElement = video;\n                video.addEventListener('loadeddata', () => {\n                    if (errored || !this._videoElement) {\n                        return;\n                    }\n                    // This will be the first frame\n                    const frame = new VideoFrame(video, {\n                        timestamp: 1000 * performance.now(),\n                    });\n                    onVideoFrame(frame);\n                    frame.close();\n                }, { once: true });\n                void video.play().catch((error) => {\n                    errored = true;\n                    this._promiseWithResolvers.reject(error);\n                });\n            }\n            else {\n                throw new Error('When no explicit frame rate is set, MediaStreamTrackProcessor is required; but it\\'s not available'\n                    + ' in this environment.');\n            }\n        }\n    }\n    /**\n     * Pauses the capture of video frames - any video frames emitted by the underlying media stream will be ignored\n     * while paused. This does *not* close the underlying `MediaStreamVideoTrack`, it just ignores its output.\n     */\n    pause() {\n        this._paused = true;\n    }\n    /** Resumes the capture of video frames after being paused. */\n    resume() {\n        this._paused = false;\n    }\n    /** @internal */\n    async _flushAndClose(forceClose) {\n        try {\n            if (this._abortController) {\n                this._abortController.abort();\n                this._abortController = null;\n            }\n            if (this._timerHandle) {\n                clearIntervalUnthrottled(this._timerHandle);\n            }\n            this._lastVideoFrame?.close();\n            if (this._videoElement) {\n                this._videoElement.srcObject = null;\n                this._videoElement.remove();\n                this._videoElement = null;\n            }\n            if (this._workerTrackId !== null) {\n                assert(this._workerListener);\n                sendMessageToMediaStreamTrackProcessorWorker({\n                    type: 'stopTrack',\n                    trackId: this._workerTrackId,\n                });\n                // Wait for the worker to stop the track\n                await new Promise((resolve) => {\n                    const listener = (event) => {\n                        const message = event.data;\n                        if (message.type === 'trackStopped' && message.trackId === this._workerTrackId) {\n                            assert(this._workerListener);\n                            mediaStreamTrackProcessorWorker.removeEventListener('message', this._workerListener);\n                            mediaStreamTrackProcessorWorker.removeEventListener('message', listener);\n                            resolve();\n                        }\n                    };\n                    mediaStreamTrackProcessorWorker.addEventListener('message', listener);\n                });\n            }\n        }\n        finally {\n            // The encoder must be closed even if the track teardown above threw\n            await this._encoder.flushAndClose(forceClose);\n        }\n    }\n}\n/**\n * Base class for audio sources - sources for audio tracks.\n * @group Media sources\n * @public\n */\nexport class AudioSource extends MediaSource {\n    /** Internal constructor. */\n    constructor(codec) {\n        super();\n        if (!AUDIO_CODECS.includes(codec)) {\n            throw new TypeError(`Invalid audio codec '${codec}'. Must be one of: ${AUDIO_CODECS.join(', ')}.`);\n        }\n        this._codec = codec;\n    }\n}\n/**\n * The most basic audio source; can be used to directly pipe encoded packets into the output file.\n * @group Media sources\n * @public\n */\nexport class EncodedAudioPacketSource extends AudioSource {\n    /** Creates a new {@link EncodedAudioPacketSource} whose packets are encoded using `codec`. */\n    constructor(codec) {\n        super(codec);\n    }\n    /**\n     * Adds an encoded packet to the output audio track. Packets must be added in *decode order*.\n     *\n     * @param meta - Additional metadata from the encoder. You should pass this for the first call, including a valid\n     * decoder config.\n     *\n     * @returns A Promise that resolves once the output is ready to receive more samples. You should await this Promise\n     * to respect writer and encoder backpressure.\n     */\n    add(packet, meta) {\n        if (!(packet instanceof EncodedPacket)) {\n            throw new TypeError('packet must be an EncodedPacket.');\n        }\n        if (packet.isMetadataOnly) {\n            throw new TypeError('Metadata-only packets cannot be added.');\n        }\n        if (meta !== undefined && (!meta || typeof meta !== 'object')) {\n            throw new TypeError('meta, when provided, must be an object.');\n        }\n        this._ensureValidAdd();\n        return this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack, packet, meta);\n    }\n}\nclass AudioEncoderWrapper {\n    setError(error) {\n        if (!this.errorSet) {\n            this.error = error;\n            this.errorSet = true;\n        }\n    }\n    constructor(source, encodingConfig) {\n        this.source = source;\n        this.encodingConfig = encodingConfig;\n        this.ensureEncoderPromise = null;\n        this.encoderInitialized = false;\n        this.encoder = null;\n        this.muxer = null;\n        this.lastNumberOfChannels = null;\n        this.lastSampleRate = null;\n        this.isPcmEncoder = false;\n        this.outputSampleSize = null;\n        this.writeOutputValue = null;\n        this.customEncoder = null;\n        this.customEncoderCallSerializer = new CallSerializer();\n        this.customEncoderQueueSize = 0;\n        this.lastEndSampleIndex = null;\n        this.resampler = null;\n        /**\n         * Encoders typically throw their errors \"out of band\", meaning asynchronously in some other execution context.\n         * However, we want to surface these errors to the user within the normal control flow, so they don't go uncaught.\n         * So, we keep track of the encoder error and throw it as soon as we get the chance.\n         */\n        this.error = null;\n        this.errorSet = false;\n        this.lastMuxerPromise = Promise.resolve();\n        this.closed = false;\n    }\n    async add(audioSample, shouldClose) {\n        try {\n            this.checkForEncoderError();\n            this.source._ensureValidAdd();\n            // Ensure audio parameters remain constant\n            if (this.lastNumberOfChannels !== null && this.lastSampleRate !== null) {\n                if (audioSample.numberOfChannels !== this.lastNumberOfChannels\n                    || audioSample.sampleRate !== this.lastSampleRate) {\n                    throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at`\n                        + ` ${this.lastSampleRate} Hz, got ${audioSample.numberOfChannels} channels at`\n                        + ` ${audioSample.sampleRate} Hz.`);\n                }\n            }\n            else {\n                this.lastNumberOfChannels = audioSample.numberOfChannels;\n                this.lastSampleRate = audioSample.sampleRate;\n            }\n            const config = this.encodingConfig;\n            const needsResample = config.transform?.numberOfChannels !== undefined\n                || config.transform?.sampleRate !== undefined;\n            if (needsResample) {\n                if (!this.resampler) {\n                    // Initialize the resampler on first sample\n                    this.resampler = new AudioResampler({\n                        targetNumberOfChannels: config.transform.numberOfChannels\n                            ?? audioSample.numberOfChannels,\n                        targetSampleRate: config.transform.sampleRate\n                            ?? audioSample.sampleRate,\n                        onSample: async (sample) => {\n                            await this.processAndEncode(sample, true);\n                        },\n                    });\n                }\n                await this.resampler.add(audioSample);\n            }\n            else {\n                await this.processAndEncode(audioSample, shouldClose);\n            }\n        }\n        finally {\n            if (shouldClose) {\n                audioSample.close();\n            }\n        }\n    }\n    /**\n     * Runs the process function (if any) and encodes the resulting samples.\n     */\n    async processAndEncode(audioSample, shouldClose) {\n        const config = this.encodingConfig;\n        if (config.transform?.sampleFormat !== undefined\n            && toInterleavedAudioFormat(audioSample.format) !== config.transform.sampleFormat) {\n            // Do a sample format conversion\n            const newSample = audioSampleToInterleavedFormat(audioSample, config.transform.sampleFormat);\n            if (shouldClose) {\n                audioSample.close();\n            }\n            audioSample = newSample;\n            shouldClose = true;\n        }\n        if (config.transform?.process) {\n            try {\n                let processed = config.transform.process(audioSample);\n                if (isThenable(processed)) {\n                    processed = await processed;\n                }\n                if (processed === null) {\n                    return;\n                }\n                if (!Array.isArray(processed)) {\n                    processed = [processed];\n                }\n                try {\n                    for (const sample of processed) {\n                        if (!(sample instanceof AudioSample)) {\n                            throw new TypeError('The audio process function must return an AudioSample, null, or an array of'\n                                + ' AudioSamples.');\n                        }\n                    }\n                    for (const sample of processed) {\n                        await this.encodeSample(sample, true);\n                    }\n                }\n                finally {\n                    // encodeSample closes the samples it was passed; this additionally covers the samples never\n                    // reached because an earlier one threw (closing is idempotent)\n                    for (const sample of processed) {\n                        if (sample instanceof AudioSample) {\n                            sample.close();\n                        }\n                    }\n                }\n            }\n            finally {\n                if (shouldClose) {\n                    audioSample.close();\n                }\n            }\n        }\n        else {\n            await this.encodeSample(audioSample, shouldClose);\n        }\n    }\n    /**\n     * Encodes a single audio sample, handling encoder init, gap padding, and backpressure.\n     */\n    async encodeSample(audioSample, shouldClose) {\n        try {\n            if (!this.encoderInitialized) {\n                if (!this.ensureEncoderPromise) {\n                    this.ensureEncoder(audioSample);\n                }\n                // No, this \"if\" statement is not useless. Sometimes, the above call to `ensureEncoder` might have\n                // synchronously completed and the encoder is already initialized. In this case, we don't need to await\n                // the promise anymore. This also fixes nasty async race condition bugs when multiple code paths are\n                // calling this method: It's important that the call that initialized the encoder go through this\n                // code first.\n                if (!this.encoderInitialized) {\n                    await this.ensureEncoderPromise;\n                }\n            }\n            assert(this.encoderInitialized);\n            if (this.closed) {\n                return;\n            }\n            // Handle padding of gaps with silence to avoid audio drift over time, like in\n            // https://github.com/Vanilagy/mediabunny/issues/176\n            // TODO An open question is how encoders deal with the first AudioData having a non-zero timestamp, and with\n            // AudioDatas that have an overlapping timestamp range.\n            {\n                const startSampleIndex = Math.round(audioSample.timestamp * audioSample.sampleRate);\n                const endSampleIndex = Math.round((audioSample.timestamp + audioSample.duration) * audioSample.sampleRate);\n                if (this.lastEndSampleIndex === null) {\n                    this.lastEndSampleIndex = endSampleIndex;\n                }\n                else {\n                    const sampleDiff = startSampleIndex - this.lastEndSampleIndex;\n                    if (sampleDiff >= 64) {\n                        // The gap is big enough, let's add a correction sample\n                        const fillSample = new AudioSample({\n                            data: new Float32Array(sampleDiff * audioSample.numberOfChannels),\n                            format: 'f32-planar',\n                            sampleRate: audioSample.sampleRate,\n                            numberOfChannels: audioSample.numberOfChannels,\n                            numberOfFrames: sampleDiff,\n                            timestamp: this.lastEndSampleIndex / audioSample.sampleRate,\n                        });\n                        await this.encodeSample(fillSample, true); // Recursive call\n                    }\n                    this.lastEndSampleIndex += audioSample.numberOfFrames;\n                }\n            }\n            this.encodingConfig.onEncodedSample?.(audioSample);\n            if (this.customEncoder) {\n                this.customEncoderQueueSize++;\n                // We clone the sample so it cannot be closed on us from the outside before it reaches the encoder\n                const clonedSample = audioSample.clone();\n                const promise = this.customEncoderCallSerializer\n                    .call(() => this.customEncoder.encode(clonedSample))\n                    .catch((error) => this.setError(error))\n                    .finally(() => {\n                    this.customEncoderQueueSize--;\n                    clonedSample.close();\n                });\n                if (this.customEncoderQueueSize >= 4) {\n                    await promise;\n                }\n                await this.lastMuxerPromise; // Allow the writer to apply backpressure\n            }\n            else if (this.isPcmEncoder) {\n                await this.doPcmEncoding(audioSample, shouldClose);\n            }\n            else {\n                assert(this.encoder);\n                const audioData = audioSample.toAudioData();\n                this.encoder.encode(audioData);\n                audioData.close();\n                if (shouldClose) {\n                    audioSample.close();\n                }\n                if (this.encoder.encodeQueueSize >= 4) {\n                    await new Promise(resolve => this.encoder.addEventListener('dequeue', resolve, { once: true }));\n                }\n                await this.lastMuxerPromise; // Allow the writer to apply backpressure\n            }\n        }\n        finally {\n            if (shouldClose) {\n                audioSample.close();\n            }\n        }\n    }\n    async doPcmEncoding(audioSample, shouldClose) {\n        assert(this.outputSampleSize);\n        assert(this.writeOutputValue);\n        // Need to extract data from the audio data before we close it\n        const { numberOfChannels, numberOfFrames, sampleRate, timestamp } = audioSample;\n        const CHUNK_SIZE = 2048;\n        const outputs = [];\n        // Prepare all of the output buffers, each being bounded by CHUNK_SIZE so we don't generate huge packets\n        for (let frame = 0; frame < numberOfFrames; frame += CHUNK_SIZE) {\n            const frameCount = Math.min(CHUNK_SIZE, audioSample.numberOfFrames - frame);\n            const outputSize = frameCount * numberOfChannels * this.outputSampleSize;\n            const outputBuffer = new ArrayBuffer(outputSize);\n            const outputView = new DataView(outputBuffer);\n            outputs.push({ frameCount, view: outputView });\n        }\n        const isS32 = audioSample.format === 's32' || audioSample.format === 's32-planar';\n        const readFormat = isS32 ? 's32-planar' : 'f32-planar'; // Can't read in f32-planar due to precision loss\n        const scale = isS32 ? 1 / 2147483648 : 1;\n        const allocationSize = audioSample.allocationSize(({ planeIndex: 0, format: readFormat }));\n        const values = isS32\n            ? new Int32Array(allocationSize / 4)\n            : new Float32Array(allocationSize / 4);\n        for (let i = 0; i < numberOfChannels; i++) {\n            audioSample.copyTo(values, { planeIndex: i, format: readFormat });\n            for (let j = 0; j < outputs.length; j++) {\n                const { frameCount, view } = outputs[j];\n                for (let k = 0; k < frameCount; k++) {\n                    this.writeOutputValue(view, (k * numberOfChannels + i) * this.outputSampleSize, values[j * CHUNK_SIZE + k] * scale);\n                }\n            }\n        }\n        if (shouldClose) {\n            audioSample.close();\n        }\n        const meta = {\n            decoderConfig: {\n                codec: this.encodingConfig.codec,\n                numberOfChannels,\n                sampleRate,\n            },\n        };\n        for (let i = 0; i < outputs.length; i++) {\n            const { frameCount, view } = outputs[i];\n            const outputBuffer = view.buffer;\n            const startFrame = i * CHUNK_SIZE;\n            const packet = new EncodedPacket(new Uint8Array(outputBuffer), 'key', timestamp + startFrame / sampleRate, frameCount / sampleRate);\n            this.encodingConfig.onEncodedPacket?.(packet, meta);\n            await this.muxer.addEncodedAudioPacket(this.source._connectedTrack, packet, meta); // With backpressure\n        }\n    }\n    ensureEncoder(audioSample) {\n        this.ensureEncoderPromise = (async () => {\n            const { numberOfChannels, sampleRate } = audioSample;\n            // eslint-disable-next-line @typescript-eslint/no-deprecated\n            const quality = resolveQuality(this.encodingConfig.quality, this.encodingConfig.bitrate);\n            const encoderConfig = buildAudioEncoderConfig({\n                numberOfChannels,\n                sampleRate,\n                ...this.encodingConfig,\n                quality,\n            });\n            this.encodingConfig.onEncoderConfig?.(encoderConfig);\n            this.source._nominalBitrate = encoderConfig.bitrate ?? null;\n            const MatchingCustomEncoder = customAudioEncoders.find(x => x.supports(this.encodingConfig.codec, encoderConfig));\n            if (MatchingCustomEncoder) {\n                // @ts-expect-error \"Can't create instance of abstract class 🤓\"\n                this.customEncoder = new MatchingCustomEncoder();\n                // @ts-expect-error It's technically readonly\n                this.customEncoder.codec = this.encodingConfig.codec;\n                // @ts-expect-error It's technically readonly\n                this.customEncoder.config = encoderConfig;\n                // @ts-expect-error It's technically readonly\n                this.customEncoder.onPacket = (packet, meta) => {\n                    if (!(packet instanceof EncodedPacket)) {\n                        throw new TypeError('The first argument passed to onPacket must be an EncodedPacket.');\n                    }\n                    if (meta !== undefined && (!meta || typeof meta !== 'object')) {\n                        throw new TypeError('The second argument passed to onPacket must be an object or undefined.');\n                    }\n                    this.encodingConfig.onEncodedPacket?.(packet, meta);\n                    this.lastMuxerPromise\n                        = this.muxer.addEncodedAudioPacket(this.source._connectedTrack, packet, meta)\n                            .catch((error) => {\n                            this.setError(error);\n                        });\n                };\n                // @ts-expect-error It's technically readonly\n                this.customEncoder.onError = (error) => {\n                    this.setError(error);\n                };\n                await this.customEncoder.init();\n            }\n            else if (PCM_AUDIO_CODECS.includes(this.encodingConfig.codec)) {\n                this.initPcmEncoder();\n            }\n            else {\n                if (typeof AudioEncoder === 'undefined') {\n                    throw new Error(missingWebCodecsClassMessage('AudioEncoder'));\n                }\n                let supported;\n                try {\n                    const support = await AudioEncoder.isConfigSupported(encoderConfig);\n                    supported = support.supported ?? false;\n                }\n                catch {\n                    supported = false;\n                }\n                if (!supported) {\n                    throw new Error(`This specific encoder configuration (${encoderConfig.codec}, ${encoderConfig.bitrate} bps,`\n                        + ` ${encoderConfig.numberOfChannels} channels, ${encoderConfig.sampleRate} Hz) is not`\n                        + ` supported in this environment. Consider using another codec or changing your`\n                        + ` audio parameters.`);\n                }\n                const stack = new Error('Encoding error').stack;\n                this.encoder = new AudioEncoder({\n                    output: (chunk, meta) => {\n                        // WebKit emits an invalid description for AAC (https://bugs.webkit.org/show_bug.cgi?id=302253),\n                        // which we try to detect here. If detected, we'll provide our own description instead, derived\n                        // from the codec string and audio parameters.\n                        if (this.encodingConfig.codec === 'aac' && meta?.decoderConfig) {\n                            if (meta.decoderConfig.description\n                                && meta.decoderConfig.description.byteLength > 0\n                                && toUint8Array(meta.decoderConfig.description)[0] === 0x03) {\n                                // We were handed an ES descriptor instead of an AudioSpecificConfig\n                                const { decoderSpecificInfo } = readEsDescriptor(FileSlice.tempFromBytes(toUint8Array(meta.decoderConfig.description)));\n                                meta.decoderConfig.description = decoderSpecificInfo ?? undefined;\n                            }\n                            let needsDescriptionOverwrite = false;\n                            if (!meta.decoderConfig.description || meta.decoderConfig.description.byteLength < 2) {\n                                needsDescriptionOverwrite = true;\n                            }\n                            else {\n                                const audioSpecificConfig = parseAacAudioSpecificConfig(toUint8Array(meta.decoderConfig.description));\n                                needsDescriptionOverwrite = audioSpecificConfig.objectType === 0;\n                            }\n                            if (needsDescriptionOverwrite) {\n                                const objectType = Number(last(encoderConfig.codec.split('.')));\n                                meta.decoderConfig.description = buildAacAudioSpecificConfig({\n                                    objectType,\n                                    outputNumberOfChannels: meta.decoderConfig.numberOfChannels,\n                                    outputSampleRate: meta.decoderConfig.sampleRate,\n                                });\n                            }\n                        }\n                        let packet = EncodedPacket.fromEncodedChunk(chunk);\n                        // Snap the timing information to the sample rate to recover information lost in microsecond\n                        // conversion\n                        packet = packet.clone({\n                            timestamp: roundToDivisor(packet.timestamp, encoderConfig.sampleRate),\n                            duration: chunk.duration != null\n                                ? roundToDivisor(packet.duration, encoderConfig.sampleRate)\n                                : undefined,\n                        });\n                        this.encodingConfig.onEncodedPacket?.(packet, meta);\n                        this.lastMuxerPromise\n                            = this.muxer.addEncodedAudioPacket(this.source._connectedTrack, packet, meta)\n                                .catch((error) => {\n                                this.setError(error);\n                            });\n                    },\n                    error: (error) => {\n                        error.stack = stack; // Provide a more useful stack trace\n                        this.setError(error);\n                    },\n                });\n                this.encoder.configure(encoderConfig);\n            }\n            assert(this.source._connectedTrack);\n            this.muxer = this.source._connectedTrack.output._muxer;\n            this.encoderInitialized = true;\n        })();\n    }\n    initPcmEncoder() {\n        this.isPcmEncoder = true;\n        const codec = this.encodingConfig.codec;\n        const { dataType, sampleSize, littleEndian } = parsePcmCodec(codec);\n        this.outputSampleSize = sampleSize;\n        // All these functions receive a float sample as input and map it into the desired format\n        switch (sampleSize) {\n            case 1:\n                {\n                    if (dataType === 'unsigned') {\n                        this.writeOutputValue = (view, byteOffset, value) => view.setUint8(byteOffset, clamp(Math.round(value * 128) + 128, 0, 255));\n                    }\n                    else if (dataType === 'signed') {\n                        this.writeOutputValue = (view, byteOffset, value) => {\n                            view.setInt8(byteOffset, clamp(Math.round(value * 128), -128, 127));\n                        };\n                    }\n                    else if (dataType === 'ulaw') {\n                        this.writeOutputValue = (view, byteOffset, value) => {\n                            const int16 = clamp(Math.round(value * 32768), -32768, 32767);\n                            view.setUint8(byteOffset, toUlaw(int16));\n                        };\n                    }\n                    else if (dataType === 'alaw') {\n                        this.writeOutputValue = (view, byteOffset, value) => {\n                            const int16 = clamp(Math.round(value * 32768), -32768, 32767);\n                            view.setUint8(byteOffset, toAlaw(int16));\n                        };\n                    }\n                    else {\n                        assert(false);\n                    }\n                }\n                ;\n                break;\n            case 2:\n                {\n                    if (dataType === 'unsigned') {\n                        this.writeOutputValue = (view, byteOffset, value) => view.setUint16(byteOffset, clamp(Math.round(value * 32768) + 32768, 0, 65535), littleEndian);\n                    }\n                    else if (dataType === 'signed') {\n                        this.writeOutputValue = (view, byteOffset, value) => view.setInt16(byteOffset, clamp(Math.round(value * 32768), -32768, 32767), littleEndian);\n                    }\n                    else {\n                        assert(false);\n                    }\n                }\n                ;\n                break;\n            case 3:\n                {\n                    if (dataType === 'unsigned') {\n                        this.writeOutputValue = (view, byteOffset, value) => setUint24(view, byteOffset, clamp(Math.round(value * 8388608) + 8388608, 0, 16777215), littleEndian);\n                    }\n                    else if (dataType === 'signed') {\n                        this.writeOutputValue = (view, byteOffset, value) => setInt24(view, byteOffset, clamp(Math.round(value * 8388608), -8388608, 8388607), littleEndian);\n                    }\n                    else {\n                        assert(false);\n                    }\n                }\n                ;\n                break;\n            case 4:\n                {\n                    if (dataType === 'unsigned') {\n                        this.writeOutputValue = (view, byteOffset, value) => view.setUint32(byteOffset, clamp(Math.round(value * 2147483648) + 2147483648, 0, 4294967295), littleEndian);\n                    }\n                    else if (dataType === 'signed') {\n                        this.writeOutputValue = (view, byteOffset, value) => view.setInt32(byteOffset, clamp(Math.round(value * 2147483648), -2147483648, 2147483647), littleEndian);\n                    }\n                    else if (dataType === 'float') {\n                        this.writeOutputValue = (view, byteOffset, value) => view.setFloat32(byteOffset, value, littleEndian);\n                    }\n                    else {\n                        assert(false);\n                    }\n                }\n                ;\n                break;\n            case 8:\n                {\n                    if (dataType === 'float') {\n                        this.writeOutputValue = (view, byteOffset, value) => view.setFloat64(byteOffset, value, littleEndian);\n                    }\n                    else {\n                        assert(false);\n                    }\n                }\n                ;\n                break;\n            default:\n                {\n                    assertNever(sampleSize);\n                    assert(false);\n                }\n                ;\n        }\n    }\n    async flushAndClose(forceClose) {\n        try {\n            if (!forceClose) {\n                this.checkForEncoderError();\n                // Finalize the resampler to flush any buffered audio\n                if (this.resampler) {\n                    await this.resampler.finalize();\n                }\n            }\n            this.closed = true;\n            if (!forceClose) {\n                if (this.customEncoder) {\n                    void this.customEncoderCallSerializer.call(() => this.customEncoder.flush());\n                }\n                else if (this.encoder) {\n                    await this.encoder.flush();\n                }\n            }\n        }\n        finally {\n            // This cleanup must also run when flushing threw (e.g. due to an encoder error), otherwise the encoder\n            // would be left dangling\n            this.closed = true;\n            this.resampler = null;\n            if (this.customEncoder) {\n                await this.customEncoderCallSerializer.call(() => this.customEncoder.close())\n                    .catch((error) => this.setError(error));\n            }\n            else if (this.encoder && this.encoder.state !== 'closed') {\n                this.encoder.close();\n            }\n        }\n        if (!forceClose) {\n            this.checkForEncoderError();\n        }\n    }\n    getQueueSize() {\n        if (this.customEncoder) {\n            return this.customEncoderQueueSize;\n        }\n        else if (this.isPcmEncoder) {\n            return 0;\n        }\n        else {\n            return this.encoder?.encodeQueueSize ?? 0;\n        }\n    }\n    checkForEncoderError() {\n        if (this.errorSet) {\n            throw this.error;\n        }\n    }\n}\n/**\n * This source can be used to add raw, unencoded audio samples to an output audio track. These samples will\n * automatically be encoded and then piped into the output.\n * @group Media sources\n * @public\n */\nexport class AudioSampleSource extends AudioSource {\n    /**\n     * Creates a new {@link AudioSampleSource} whose samples are encoded according to the specified\n     * {@link AudioEncodingConfig}.\n     */\n    constructor(encodingConfig) {\n        validateAudioEncodingConfig(encodingConfig);\n        super(encodingConfig.codec);\n        this._encoder = new AudioEncoderWrapper(this, encodingConfig);\n    }\n    /**\n     * Encodes an audio sample and then adds it to the output.\n     *\n     * @returns A Promise that resolves once the output is ready to receive more samples. You should await this Promise\n     * to respect writer and encoder backpressure.\n     */\n    add(audioSample) {\n        if (!(audioSample instanceof AudioSample)) {\n            throw new TypeError('audioSample must be an AudioSample.');\n        }\n        return this._encoder.add(audioSample, false);\n    }\n    /** @internal */\n    _flushAndClose(forceClose) {\n        return this._encoder.flushAndClose(forceClose);\n    }\n}\n/**\n * This source can be used to add audio data from an AudioBuffer to the output track. This is useful when working with\n * the Web Audio API.\n * @group Media sources\n * @public\n */\nexport class AudioBufferSource extends AudioSource {\n    /**\n     * Creates a new {@link AudioBufferSource} whose `AudioBuffer` instances are encoded according to the specified\n     * {@link AudioEncodingConfig} and {@link AudioBufferSourceOptions}.\n     */\n    constructor(encodingConfig, options = {}) {\n        validateAudioEncodingConfig(encodingConfig);\n        if (typeof options !== 'object' || !options) {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.startTimestamp !== undefined && !Number.isFinite(options.startTimestamp)) {\n            throw new TypeError('options.startTimestamp, when provided, must be a finite number.');\n        }\n        super(encodingConfig.codec);\n        this._encoder = new AudioEncoderWrapper(this, encodingConfig);\n        this._accumulatedTime = options.startTimestamp ?? 0;\n    }\n    /**\n     * Converts an AudioBuffer to audio samples, encodes them and adds them to the output. The first `AudioBuffer` will\n     * be played at the configured start timestamp (the default is 0), and each subsequent `AudioBuffer` will be placed\n     * directly after the previous one.\n     *\n     * @returns A Promise that resolves once the output is ready to receive more samples. You should await this Promise\n     * to respect writer and encoder backpressure.\n     */\n    async add(audioBuffer) {\n        if (!(audioBuffer instanceof AudioBuffer)) {\n            throw new TypeError('audioBuffer must be an AudioBuffer.');\n        }\n        const iterator = AudioSample._fromAudioBuffer(audioBuffer, this._accumulatedTime);\n        this._accumulatedTime += audioBuffer.duration;\n        for (const audioSample of iterator) {\n            await this._encoder.add(audioSample, true);\n        }\n    }\n    /** @internal */\n    _flushAndClose(forceClose) {\n        return this._encoder.flushAndClose(forceClose);\n    }\n}\n/**\n * Audio source that encodes the data of a\n * [`MediaStreamAudioTrack`](https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack) and pipes it into the\n * output. This is useful for capturing live or real-time audio such as microphones or audio from other media elements.\n * Audio will automatically start being captured once the connected {@link Output} is started, and will keep being\n * captured until the {@link Output} is finalized or this source is closed.\n * @group Media sources\n * @public\n */\nexport class MediaStreamAudioTrackSource extends AudioSource {\n    /** A promise that rejects upon any error within this source. This promise never resolves. */\n    get errorPromise() {\n        this._errorPromiseAccessed = true;\n        return this._promiseWithResolvers.promise;\n    }\n    /** Whether this source is currently paused as a result of calling `.pause()`. */\n    get paused() {\n        return this._paused;\n    }\n    /**\n     * Creates a new {@link MediaStreamAudioTrackSource} from a `MediaStreamAudioTrack`, which will pull audio samples\n     * from the stream in real time and encode them according to {@link AudioEncodingConfig}.\n     */\n    constructor(track, encodingConfig, options = {}) {\n        if (!(track instanceof MediaStreamTrack) || track.kind !== 'audio') {\n            throw new TypeError('track must be an audio MediaStreamTrack.');\n        }\n        validateAudioEncodingConfig(encodingConfig);\n        if (typeof options !== 'object' || !options) {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.timestampBase !== undefined\n            && options.timestampBase !== 'synced-zero'\n            && options.timestampBase !== 'zero'\n            && options.timestampBase !== 'unix') {\n            throw new TypeError('options.timestampBase, when provided, must be one of \\'synced-zero\\', \\'zero\\', or \\'unix\\'.');\n        }\n        super(encodingConfig.codec);\n        /** @internal */\n        this._abortController = null;\n        /** @internal */\n        this._audioContext = null;\n        /** @internal */\n        // eslint-disable-next-line @typescript-eslint/no-deprecated\n        this._scriptProcessorNode = null; // Deprecated but goated\n        /** @internal */\n        this._promiseWithResolvers = promiseWithResolvers();\n        /** @internal */\n        this._errorPromiseAccessed = false;\n        /** @internal */\n        this._paused = false;\n        this._options = options;\n        this._encoder = new AudioEncoderWrapper(this, encodingConfig);\n        this._track = track;\n    }\n    /** @internal */\n    async _start() {\n        if (!this._errorPromiseAccessed) {\n            Logging._warn('Make sure not to ignore the `errorPromise` field on MediaStreamAudioTrackSource, so that any internal'\n                + ' errors get bubbled up properly.');\n        }\n        this._abortController = new AbortController();\n        let firstAudioDataTimestamp = null;\n        let errored = false;\n        let lastSampleTimestamp = null;\n        let timestampOffset = 0;\n        const onAudioSample = (audioSample) => {\n            if (errored) {\n                audioSample.close();\n                return;\n            }\n            const currentTimestamp = audioSample.timestamp;\n            if (this._paused) {\n                const dataSeen = firstAudioDataTimestamp !== null;\n                if (dataSeen) {\n                    if (lastSampleTimestamp !== null && this._options.timestampBase !== 'unix') {\n                        // In addition to dropping this sample, let's also keep track of the time we have lost due to\n                        // the pause. Doing it like this instead of simply keeping track of the paused time is better\n                        // since it retains the sample rate of the underlying source.\n                        const timeDelta = currentTimestamp - lastSampleTimestamp;\n                        timestampOffset -= timeDelta;\n                    }\n                    lastSampleTimestamp = currentTimestamp;\n                }\n                audioSample.close();\n                return;\n            }\n            if (firstAudioDataTimestamp === null) {\n                firstAudioDataTimestamp = audioSample.timestamp;\n                let target;\n                const timestampBase = this._options.timestampBase ?? 'synced-zero';\n                if (timestampBase === 'unix') {\n                    target = Date.now() / 1000;\n                }\n                else if (timestampBase === 'zero') {\n                    target = 0;\n                }\n                else {\n                    const output = this._connectedTrack.output;\n                    if (output._firstMediaStreamTimestamp === null) {\n                        output._firstMediaStreamTimestamp = performance.now() / 1000;\n                        target = 0;\n                    }\n                    else {\n                        target = performance.now() / 1000 - output._firstMediaStreamTimestamp;\n                    }\n                }\n                timestampOffset = target - firstAudioDataTimestamp;\n            }\n            lastSampleTimestamp = currentTimestamp;\n            if (this._encoder.getQueueSize() >= 8) {\n                // Drop data if the encoder is overloaded\n                audioSample.close();\n                return;\n            }\n            audioSample.setTimestamp(currentTimestamp + timestampOffset);\n            void this._encoder.add(audioSample, true)\n                .catch((error) => {\n                errored = true;\n                this._abortController?.abort();\n                this._promiseWithResolvers.reject(error);\n                void this._audioContext?.suspend();\n            });\n        };\n        if (typeof MediaStreamTrackProcessor !== 'undefined') {\n            // Great, MediaStreamTrackProcessor is supported, this is the preferred way of doing things\n            const processor = new MediaStreamTrackProcessor({ track: this._track });\n            const consumer = new WritableStream({\n                write: audioData => onAudioSample(new AudioSample(audioData)),\n            });\n            processor.readable.pipeTo(consumer, {\n                signal: this._abortController.signal,\n            }).catch((error) => {\n                // Handle AbortError silently\n                if (error instanceof DOMException && error.name === 'AbortError')\n                    return;\n                this._promiseWithResolvers.reject(error);\n            });\n        }\n        else {\n            // Let's fall back to an AudioContext approach\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n            const AudioContext = window.AudioContext || window.webkitAudioContext;\n            this._audioContext = new AudioContext({ sampleRate: this._track.getSettings().sampleRate });\n            const sourceNode = this._audioContext.createMediaStreamSource(new MediaStream([this._track]));\n            // eslint-disable-next-line @typescript-eslint/no-deprecated\n            this._scriptProcessorNode = this._audioContext.createScriptProcessor(4096);\n            if (this._audioContext.state === 'suspended') {\n                await this._audioContext.resume();\n            }\n            sourceNode.connect(this._scriptProcessorNode);\n            this._scriptProcessorNode.connect(this._audioContext.destination);\n            let totalDuration = 0;\n            // eslint-disable-next-line @typescript-eslint/no-deprecated\n            this._scriptProcessorNode.onaudioprocess = (event) => {\n                // eslint-disable-next-line @typescript-eslint/no-deprecated\n                const iterator = AudioSample._fromAudioBuffer(event.inputBuffer, totalDuration);\n                // eslint-disable-next-line @typescript-eslint/no-deprecated\n                totalDuration += event.inputBuffer.duration;\n                for (const audioSample of iterator) {\n                    onAudioSample(audioSample);\n                }\n            };\n        }\n    }\n    /**\n     * Pauses the capture of audio data - any audio data emitted by the underlying media stream will be ignored\n     * while paused. This does *not* close the underlying `MediaStreamAudioTrack`, it just ignores its output.\n     */\n    pause() {\n        this._paused = true;\n    }\n    /** Resumes the capture of audio data after being paused. */\n    resume() {\n        this._paused = false;\n    }\n    /** @internal */\n    async _flushAndClose(forceClose) {\n        try {\n            if (this._abortController) {\n                this._abortController.abort();\n                this._abortController = null;\n            }\n            if (this._audioContext) {\n                assert(this._scriptProcessorNode);\n                this._scriptProcessorNode.disconnect();\n                await this._audioContext.suspend();\n            }\n        }\n        finally {\n            // The encoder must be closed even if the track teardown above threw\n            await this._encoder.flushAndClose(forceClose);\n        }\n    }\n}\nconst mediaStreamTrackProcessorWorkerCode = () => {\n    const sendMessage = (message, transfer) => {\n        if (transfer) {\n            self.postMessage(message, { transfer });\n        }\n        else {\n            self.postMessage(message);\n        }\n    };\n    // Immediately send a message to the main thread, letting them know of the support\n    sendMessage({\n        type: 'support',\n        supported: typeof MediaStreamTrackProcessor !== 'undefined',\n    });\n    const abortControllers = new Map();\n    const activeTracks = new Map();\n    self.addEventListener('message', (event) => {\n        const message = event.data;\n        switch (message.type) {\n            case 'videoTrack':\n                {\n                    activeTracks.set(message.trackId, message.track);\n                    const processor = new MediaStreamTrackProcessor({ track: message.track });\n                    const consumer = new WritableStream({\n                        write: (videoFrame) => {\n                            if (!activeTracks.has(message.trackId)) {\n                                videoFrame.close();\n                                return;\n                            }\n                            // Send it to the main thread\n                            sendMessage({\n                                type: 'videoFrame',\n                                trackId: message.trackId,\n                                videoFrame,\n                            }, [videoFrame]);\n                        },\n                    });\n                    const abortController = new AbortController();\n                    abortControllers.set(message.trackId, abortController);\n                    processor.readable.pipeTo(consumer, {\n                        signal: abortController.signal,\n                    }).catch((error) => {\n                        // Handle AbortError silently\n                        if (error instanceof DOMException && error.name === 'AbortError')\n                            return;\n                        sendMessage({\n                            type: 'error',\n                            trackId: message.trackId,\n                            error,\n                        });\n                    });\n                }\n                ;\n                break;\n            case 'stopTrack':\n                {\n                    const abortController = abortControllers.get(message.trackId);\n                    if (abortController) {\n                        abortController.abort();\n                        abortControllers.delete(message.trackId);\n                    }\n                    const track = activeTracks.get(message.trackId);\n                    track?.stop();\n                    activeTracks.delete(message.trackId);\n                    sendMessage({\n                        type: 'trackStopped',\n                        trackId: message.trackId,\n                    });\n                }\n                ;\n                break;\n            default: assertNever(message);\n        }\n    });\n};\nlet nextMediaStreamTrackProcessorWorkerId = 0;\nlet mediaStreamTrackProcessorWorker = null;\nconst initMediaStreamTrackProcessorWorker = () => {\n    const blob = new Blob([`(${mediaStreamTrackProcessorWorkerCode.toString()})()`], { type: 'application/javascript' });\n    const url = URL.createObjectURL(blob);\n    mediaStreamTrackProcessorWorker = new Worker(url);\n};\nlet mediaStreamTrackProcessorIsSupportedInWorkerCache = null;\nconst mediaStreamTrackProcessorIsSupportedInWorker = async () => {\n    if (mediaStreamTrackProcessorIsSupportedInWorkerCache !== null) {\n        return mediaStreamTrackProcessorIsSupportedInWorkerCache;\n    }\n    if (!mediaStreamTrackProcessorWorker) {\n        initMediaStreamTrackProcessorWorker();\n    }\n    return new Promise((resolve) => {\n        assert(mediaStreamTrackProcessorWorker);\n        const listener = (event) => {\n            const message = event.data;\n            if (message.type === 'support') {\n                mediaStreamTrackProcessorIsSupportedInWorkerCache = message.supported;\n                mediaStreamTrackProcessorWorker.removeEventListener('message', listener);\n                resolve(message.supported);\n            }\n        };\n        mediaStreamTrackProcessorWorker.addEventListener('message', listener);\n    });\n};\nconst sendMessageToMediaStreamTrackProcessorWorker = (message, transfer) => {\n    assert(mediaStreamTrackProcessorWorker);\n    if (transfer) {\n        mediaStreamTrackProcessorWorker.postMessage(message, transfer);\n    }\n    else {\n        mediaStreamTrackProcessorWorker.postMessage(message);\n    }\n};\n/**\n * Base class for subtitle sources - sources for subtitle tracks.\n * @group Media sources\n * @public\n */\nexport class SubtitleSource extends MediaSource {\n    /** Internal constructor. */\n    constructor(codec) {\n        super();\n        if (!SUBTITLE_CODECS.includes(codec)) {\n            throw new TypeError(`Invalid subtitle codec '${codec}'. Must be one of: ${SUBTITLE_CODECS.join(', ')}.`);\n        }\n        this._codec = codec;\n    }\n}\n/**\n * This source can be used to add subtitles from a subtitle text file.\n * @group Media sources\n * @public\n */\nexport class TextSubtitleSource extends SubtitleSource {\n    /** Creates a new {@link TextSubtitleSource} where added text chunks are in the specified `codec`. */\n    constructor(codec) {\n        super(codec);\n        /** @internal */\n        this._error = null;\n        /** @internal */\n        this._errorSet = false;\n        /** @internal */\n        this._lastMuxerPromise = Promise.resolve();\n        this._parser = new SubtitleParser({\n            codec,\n            output: (cue, metadata) => {\n                this._lastMuxerPromise\n                    = this._connectedTrack.output._muxer.addSubtitleCue(this._connectedTrack, cue, metadata)\n                        .catch((error) => {\n                        this._setError(error);\n                    });\n            },\n        });\n    }\n    /**\n     * Parses the subtitle text according to the specified codec and adds it to the output track. You don't have to\n     * add the entire subtitle file at once here; you can provide it in chunks.\n     *\n     * @returns A Promise that resolves once the output is ready to receive more samples. You should await this Promise\n     * to respect writer and encoder backpressure.\n     */\n    add(text) {\n        if (typeof text !== 'string') {\n            throw new TypeError('text must be a string.');\n        }\n        this._checkForError();\n        this._ensureValidAdd();\n        this._parser.parse(text);\n        return this._lastMuxerPromise; // Allow the writer to apply backpressure\n    }\n    /** @internal */\n    _setError(error) {\n        if (!this._errorSet) {\n            this._error = error;\n            this._errorSet = true;\n        }\n    }\n    /** @internal */\n    _checkForError() {\n        if (this._errorSet) {\n            throw this._error;\n        }\n    }\n    /** @internal */\n    async _flushAndClose(forceClose) {\n        if (!forceClose) {\n            this._checkForError();\n        }\n    }\n}\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { AdtsMuxer } from './adts/adts-muxer.js';\nimport { AUDIO_CODECS, NON_PCM_AUDIO_CODECS, PCM_AUDIO_CODECS, SUBTITLE_CODECS, VIDEO_CODECS, } from './codec.js';\nimport { FlacMuxer } from './flac/flac-muxer.js';\nimport { IsobmffMuxer } from './isobmff/isobmff-muxer.js';\nimport { MatroskaMuxer } from './matroska/matroska-muxer.js';\nimport { Mp3Muxer } from './mp3/mp3-muxer.js';\nimport { OggMuxer } from './ogg/ogg-muxer.js';\nimport { MpegTsMuxer } from './mpeg-ts/mpeg-ts-muxer.js';\nimport { WaveMuxer } from './wave/wave-muxer.js';\nimport { HlsMuxer } from './hls/hls-muxer.js';\nimport { HLS_MIME_TYPE } from './hls/hls-misc.js';\nimport { isNumber, toArray } from './misc.js';\n/**\n * Base class representing an output media file format.\n * @group Output formats\n * @public\n */\nexport class OutputFormat {\n    /**\n     * Whether this output format supports video rotation metadata.\n     * @deprecated Use {@link OutputFormat.supportsVideoTransformationMetadata} instead.\n     */\n    get supportsVideoRotationMetadata() {\n        return this.supportsVideoTransformationMetadata;\n    }\n    /** Returns a list of video codecs that this output format can contain. */\n    getSupportedVideoCodecs() {\n        return this.getSupportedCodecs()\n            .filter(codec => VIDEO_CODECS.includes(codec));\n    }\n    /** Returns a list of audio codecs that this output format can contain. */\n    getSupportedAudioCodecs() {\n        return this.getSupportedCodecs()\n            .filter(codec => AUDIO_CODECS.includes(codec));\n    }\n    /** Returns a list of subtitle codecs that this output format can contain. */\n    getSupportedSubtitleCodecs() {\n        return this.getSupportedCodecs()\n            .filter(codec => SUBTITLE_CODECS.includes(codec));\n    }\n    /** @internal */\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    _codecUnsupportedHint(codec) {\n        return '';\n    }\n    /** @internal */\n    _isFragmentedIsobmff() {\n        return false;\n    }\n}\n/**\n * Format representing files compatible with the ISO base media file format (ISOBMFF), like MP4 or MOV files.\n * @group Output formats\n * @public\n */\nexport class IsobmffOutputFormat extends OutputFormat {\n    /** Internal constructor. */\n    constructor(options = {}) {\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.fastStart !== undefined\n            && ![false, 'in-memory', 'reserve', 'fragmented'].includes(options.fastStart)) {\n            throw new TypeError('options.fastStart, when provided, must be false, \\'in-memory\\', \\'reserve\\', or \\'fragmented\\'.');\n        }\n        if (options.minimumFragmentDuration !== undefined\n            && (!isNumber(options.minimumFragmentDuration) || options.minimumFragmentDuration < 0)) {\n            throw new TypeError('options.minimumFragmentDuration, when provided, must be a non-negative number.');\n        }\n        if (options.onFtyp !== undefined && typeof options.onFtyp !== 'function') {\n            throw new TypeError('options.onFtyp, when provided, must be a function.');\n        }\n        if (options.onMoov !== undefined && typeof options.onMoov !== 'function') {\n            throw new TypeError('options.onMoov, when provided, must be a function.');\n        }\n        if (options.onMdat !== undefined && typeof options.onMdat !== 'function') {\n            throw new TypeError('options.onMdat, when provided, must be a function.');\n        }\n        if (options.onMoof !== undefined && typeof options.onMoof !== 'function') {\n            throw new TypeError('options.onMoof, when provided, must be a function.');\n        }\n        if (options.metadataFormat !== undefined\n            && !['mdir', 'mdta', 'udta', 'auto'].includes(options.metadataFormat)) {\n            throw new TypeError('options.metadataFormat, when provided, must be either \\'auto\\', \\'mdir\\', \\'mdta\\', or \\'udta\\'.');\n        }\n        super();\n        this._options = options;\n    }\n    getSupportedTrackCounts() {\n        const max = 2 ** 32 - 1; // Have fun reaching this one\n        return {\n            video: { min: 0, max },\n            audio: { min: 0, max },\n            subtitle: { min: 0, max },\n            total: { min: 0, max },\n        };\n    }\n    get supportsVideoTransformationMetadata() {\n        return true;\n    }\n    get supportsTimestampedMediaData() {\n        return true;\n    }\n    get negativeTimestampSupport() {\n        return 'full';\n    }\n    /** @internal */\n    _createMuxer(output) {\n        return new IsobmffMuxer(output, this);\n    }\n    /** @internal */\n    _isFragmentedIsobmff() {\n        return this._options.fastStart === 'fragmented';\n    }\n}\n/**\n * MPEG-4 Part 14 (MP4) file format. Supports most codecs.\n * @group Output formats\n * @public\n */\nexport class Mp4OutputFormat extends IsobmffOutputFormat {\n    /** Creates a new {@link Mp4OutputFormat} configured with the specified `options`. */\n    constructor(options) {\n        super(options);\n    }\n    /** @internal */\n    get _name() {\n        return 'MP4';\n    }\n    get fileExtension() {\n        return '.mp4';\n    }\n    get mimeType() {\n        return 'video/mp4';\n    }\n    getSupportedCodecs() {\n        return [\n            ...VIDEO_CODECS,\n            ...NON_PCM_AUDIO_CODECS,\n            // These are supported via ISO/IEC 23003-5:\n            'pcm-s16',\n            'pcm-s16be',\n            'pcm-s24',\n            'pcm-s24be',\n            'pcm-s32',\n            'pcm-s32be',\n            'pcm-f32',\n            'pcm-f32be',\n            'pcm-f64',\n            'pcm-f64be',\n            ...SUBTITLE_CODECS,\n        ];\n    }\n    /** @internal */\n    _codecUnsupportedHint(codec) {\n        if (new MovOutputFormat().getSupportedCodecs().includes(codec)) {\n            return ' Switching to MOV will grant support for this codec.';\n        }\n        return '';\n    }\n}\n/**\n * Creates a single Common Media Application Format (CMAF) segment. An init segment will be written to the\n * {@link Target} specified in {@link OutputOptions.initTarget}. Supports most codecs.\n * @group Output formats\n * @public\n */\nexport class CmafOutputFormat extends IsobmffOutputFormat {\n    /** Creates a new {@link CmafOutputFormat} configured with the specified `options`. */\n    constructor(options) {\n        super(options);\n    }\n    /** @internal */\n    get _name() {\n        return 'CMAF';\n    }\n    get fileExtension() {\n        return '.m4s';\n    }\n    get mimeType() {\n        return 'video/mp4';\n    }\n    getSupportedCodecs() {\n        return [\n            ...VIDEO_CODECS,\n            ...NON_PCM_AUDIO_CODECS,\n            // These are supported via ISO/IEC 23003-5:\n            'pcm-s16',\n            'pcm-s16be',\n            'pcm-s24',\n            'pcm-s24be',\n            'pcm-s32',\n            'pcm-s32be',\n            'pcm-f32',\n            'pcm-f32be',\n            'pcm-f64',\n            'pcm-f64be',\n            ...SUBTITLE_CODECS,\n        ];\n    }\n}\n/**\n * QuickTime File Format (QTFF), often called MOV. Supports all video and audio codecs, but not subtitle codecs.\n * @group Output formats\n * @public\n */\nexport class MovOutputFormat extends IsobmffOutputFormat {\n    /** Creates a new {@link MovOutputFormat} configured with the specified `options`. */\n    constructor(options) {\n        super(options);\n    }\n    /** @internal */\n    get _name() {\n        return 'MOV';\n    }\n    get fileExtension() {\n        return '.mov';\n    }\n    get mimeType() {\n        return 'video/quicktime';\n    }\n    getSupportedCodecs() {\n        return [\n            ...VIDEO_CODECS,\n            ...AUDIO_CODECS,\n        ];\n    }\n    /** @internal */\n    _codecUnsupportedHint(codec) {\n        if (new Mp4OutputFormat().getSupportedCodecs().includes(codec)) {\n            return ' Switching to MP4 will grant support for this codec.';\n        }\n        return '';\n    }\n}\n/**\n * Matroska file format.\n *\n * Supports writing transparent video. For a video track to be marked as transparent, the first packet added must\n * contain alpha side data.\n *\n * @group Output formats\n * @public\n */\nexport class MkvOutputFormat extends OutputFormat {\n    /** Creates a new {@link MkvOutputFormat} configured with the specified `options`. */\n    constructor(options = {}) {\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.appendOnly !== undefined && typeof options.appendOnly !== 'boolean') {\n            throw new TypeError('options.appendOnly, when provided, must be a boolean.');\n        }\n        if (options.minimumClusterDuration !== undefined\n            && (!isNumber(options.minimumClusterDuration) || options.minimumClusterDuration < 0)) {\n            throw new TypeError('options.minimumClusterDuration, when provided, must be a non-negative number.');\n        }\n        if (options.onEbmlHeader !== undefined && typeof options.onEbmlHeader !== 'function') {\n            throw new TypeError('options.onEbmlHeader, when provided, must be a function.');\n        }\n        if (options.onSegmentHeader !== undefined && typeof options.onSegmentHeader !== 'function') {\n            throw new TypeError('options.onHeader, when provided, must be a function.');\n        }\n        if (options.onCluster !== undefined && typeof options.onCluster !== 'function') {\n            throw new TypeError('options.onCluster, when provided, must be a function.');\n        }\n        super();\n        this._options = options;\n    }\n    /** @internal */\n    _createMuxer(output) {\n        return new MatroskaMuxer(output, this);\n    }\n    /** @internal */\n    get _name() {\n        return 'Matroska';\n    }\n    getSupportedTrackCounts() {\n        const max = 127;\n        return {\n            video: { min: 0, max },\n            audio: { min: 0, max },\n            subtitle: { min: 0, max },\n            total: { min: 0, max },\n        };\n    }\n    get fileExtension() {\n        return '.mkv';\n    }\n    get mimeType() {\n        return 'video/x-matroska';\n    }\n    getSupportedCodecs() {\n        return [\n            ...VIDEO_CODECS,\n            ...NON_PCM_AUDIO_CODECS,\n            ...PCM_AUDIO_CODECS.filter(codec => !['pcm-s8', 'pcm-f32be', 'pcm-f64be', 'ulaw', 'alaw'].includes(codec)),\n            ...SUBTITLE_CODECS,\n        ];\n    }\n    get supportsVideoTransformationMetadata() {\n        // While it technically does support it with Projection, many players appear to ignore that stuff\n        return false;\n    }\n    get supportsTimestampedMediaData() {\n        return true;\n    }\n    get negativeTimestampSupport() {\n        return 'prefer-non-negative';\n    }\n}\n/**\n * WebM file format, based on Matroska.\n *\n * Supports writing transparent video. For a video track to be marked as transparent, the first packet added must\n * contain alpha side data.\n *\n * @group Output formats\n * @public\n */\nexport class WebMOutputFormat extends MkvOutputFormat {\n    /** Creates a new {@link WebMOutputFormat} configured with the specified `options`. */\n    constructor(options) {\n        super(options);\n    }\n    getSupportedCodecs() {\n        return [\n            ...VIDEO_CODECS.filter(codec => ['vp8', 'vp9', 'av1'].includes(codec)),\n            ...AUDIO_CODECS.filter(codec => ['opus', 'vorbis'].includes(codec)),\n            ...SUBTITLE_CODECS,\n        ];\n    }\n    /** @internal */\n    get _name() {\n        return 'WebM';\n    }\n    get fileExtension() {\n        return '.webm';\n    }\n    get mimeType() {\n        return 'video/webm';\n    }\n    /** @internal */\n    _codecUnsupportedHint(codec) {\n        if (new MkvOutputFormat().getSupportedCodecs().includes(codec)) {\n            return ' Switching to MKV will grant support for this codec.';\n        }\n        return '';\n    }\n}\n/**\n * MP3 file format.\n * @group Output formats\n * @public\n */\nexport class Mp3OutputFormat extends OutputFormat {\n    /** Creates a new {@link Mp3OutputFormat} configured with the specified `options`. */\n    constructor(options = {}) {\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.xingHeader !== undefined && typeof options.xingHeader !== 'boolean') {\n            throw new TypeError('options.xingHeader, when provided, must be a boolean.');\n        }\n        if (options.onXingFrame !== undefined && typeof options.onXingFrame !== 'function') {\n            throw new TypeError('options.onXingFrame, when provided, must be a function.');\n        }\n        super();\n        this._options = options;\n    }\n    /** @internal */\n    _createMuxer(output) {\n        return new Mp3Muxer(output, this);\n    }\n    /** @internal */\n    get _name() {\n        return 'MP3';\n    }\n    getSupportedTrackCounts() {\n        return {\n            video: { min: 0, max: 0 },\n            audio: { min: 1, max: 1 },\n            subtitle: { min: 0, max: 0 },\n            total: { min: 1, max: 1 },\n        };\n    }\n    get fileExtension() {\n        return '.mp3';\n    }\n    get mimeType() {\n        return 'audio/mpeg';\n    }\n    getSupportedCodecs() {\n        return ['mp3'];\n    }\n    get supportsVideoTransformationMetadata() {\n        return false;\n    }\n    get supportsTimestampedMediaData() {\n        return false;\n    }\n    get negativeTimestampSupport() {\n        return null;\n    }\n}\n/**\n * WAVE file format, based on RIFF.\n * @group Output formats\n * @public\n */\nexport class WavOutputFormat extends OutputFormat {\n    /** Creates a new {@link WavOutputFormat} configured with the specified `options`. */\n    constructor(options = {}) {\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.large !== undefined && typeof options.large !== 'boolean') {\n            throw new TypeError('options.large, when provided, must be a boolean.');\n        }\n        if (options.metadataFormat !== undefined && !['info', 'id3'].includes(options.metadataFormat)) {\n            throw new TypeError('options.metadataFormat, when provided, must be either \\'info\\' or \\'id3\\'.');\n        }\n        if (options.onHeader !== undefined && typeof options.onHeader !== 'function') {\n            throw new TypeError('options.onHeader, when provided, must be a function.');\n        }\n        super();\n        this._options = options;\n    }\n    /** @internal */\n    _createMuxer(output) {\n        return new WaveMuxer(output, this);\n    }\n    /** @internal */\n    get _name() {\n        return 'WAVE';\n    }\n    getSupportedTrackCounts() {\n        return {\n            video: { min: 0, max: 0 },\n            audio: { min: 1, max: 1 },\n            subtitle: { min: 0, max: 0 },\n            total: { min: 1, max: 1 },\n        };\n    }\n    get fileExtension() {\n        return '.wav';\n    }\n    get mimeType() {\n        return 'audio/wav';\n    }\n    getSupportedCodecs() {\n        return [\n            ...PCM_AUDIO_CODECS.filter(codec => ['pcm-s16', 'pcm-s24', 'pcm-s32', 'pcm-f32', 'pcm-f64', 'pcm-u8', 'ulaw', 'alaw'].includes(codec)),\n        ];\n    }\n    get supportsVideoTransformationMetadata() {\n        return false;\n    }\n    get supportsTimestampedMediaData() {\n        return false;\n    }\n    get negativeTimestampSupport() {\n        return null;\n    }\n}\n/**\n * Ogg file format.\n * @group Output formats\n * @public\n */\nexport class OggOutputFormat extends OutputFormat {\n    /** Creates a new {@link OggOutputFormat} configured with the specified `options`. */\n    constructor(options = {}) {\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.maximumPageDuration !== undefined\n            && (!isNumber(options.maximumPageDuration) || options.maximumPageDuration <= 0)) {\n            throw new TypeError('options.maximumPageDuration, when provided, must be a positive number.');\n        }\n        if (options.onPage !== undefined && typeof options.onPage !== 'function') {\n            throw new TypeError('options.onPage, when provided, must be a function.');\n        }\n        super();\n        this._options = options;\n    }\n    /** @internal */\n    _createMuxer(output) {\n        return new OggMuxer(output, this);\n    }\n    /** @internal */\n    get _name() {\n        return 'Ogg';\n    }\n    getSupportedTrackCounts() {\n        const max = 2 ** 32; // Have fun reaching this one\n        return {\n            video: { min: 0, max: 0 },\n            audio: { min: 0, max },\n            subtitle: { min: 0, max: 0 },\n            total: { min: 0, max },\n        };\n    }\n    get fileExtension() {\n        return '.ogg';\n    }\n    get mimeType() {\n        return 'application/ogg';\n    }\n    getSupportedCodecs() {\n        return [\n            ...AUDIO_CODECS.filter(codec => ['vorbis', 'opus'].includes(codec)),\n        ];\n    }\n    get supportsVideoTransformationMetadata() {\n        return false;\n    }\n    get supportsTimestampedMediaData() {\n        return true;\n    }\n    get negativeTimestampSupport() {\n        return 'none';\n    }\n}\n/**\n * ADTS file format.\n * @group Output formats\n * @public\n */\nexport class AdtsOutputFormat extends OutputFormat {\n    /** Creates a new {@link AdtsOutputFormat} configured with the specified `options`. */\n    constructor(options = {}) {\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.onFrame !== undefined && typeof options.onFrame !== 'function') {\n            throw new TypeError('options.onFrame, when provided, must be a function.');\n        }\n        super();\n        this._options = options;\n    }\n    /** @internal */\n    _createMuxer(output) {\n        return new AdtsMuxer(output, this);\n    }\n    /** @internal */\n    get _name() {\n        return 'ADTS';\n    }\n    getSupportedTrackCounts() {\n        return {\n            video: { min: 0, max: 0 },\n            audio: { min: 1, max: 1 },\n            subtitle: { min: 0, max: 0 },\n            total: { min: 1, max: 1 },\n        };\n    }\n    get fileExtension() {\n        return '.aac';\n    }\n    get mimeType() {\n        return 'audio/aac';\n    }\n    getSupportedCodecs() {\n        return ['aac'];\n    }\n    get supportsVideoTransformationMetadata() {\n        return false;\n    }\n    get supportsTimestampedMediaData() {\n        return false;\n    }\n    get negativeTimestampSupport() {\n        return null;\n    }\n}\n/**\n * FLAC file format.\n * @group Output formats\n * @public\n */\nexport class FlacOutputFormat extends OutputFormat {\n    /** Creates a new {@link FlacOutputFormat} configured with the specified `options`. */\n    constructor(options = {}) {\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.appendOnly !== undefined && typeof options.appendOnly !== 'boolean') {\n            throw new TypeError('options.appendOnly, when provided, must be a boolean.');\n        }\n        super();\n        this._options = options;\n    }\n    /** @internal */\n    _createMuxer(output) {\n        return new FlacMuxer(output, this);\n    }\n    /** @internal */\n    get _name() {\n        return 'FLAC';\n    }\n    getSupportedTrackCounts() {\n        return {\n            video: { min: 0, max: 0 },\n            audio: { min: 1, max: 1 },\n            subtitle: { min: 0, max: 0 },\n            total: { min: 1, max: 1 },\n        };\n    }\n    get fileExtension() {\n        return '.flac';\n    }\n    get mimeType() {\n        return 'audio/flac';\n    }\n    getSupportedCodecs() {\n        return ['flac'];\n    }\n    get supportsVideoTransformationMetadata() {\n        return false;\n    }\n    get supportsTimestampedMediaData() {\n        return false;\n    }\n    get negativeTimestampSupport() {\n        return null;\n    }\n}\n/**\n * MPEG Transport Stream file format.\n * @group Output formats\n * @public\n */\nexport class MpegTsOutputFormat extends OutputFormat {\n    /** Creates a new {@link MpegTsOutputFormat} configured with the specified `options`. */\n    constructor(options = {}) {\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.onPacket !== undefined && typeof options.onPacket !== 'function') {\n            throw new TypeError('options.onPacket, when provided, must be a function.');\n        }\n        super();\n        this._options = options;\n    }\n    /** @internal */\n    _createMuxer(output) {\n        return new MpegTsMuxer(output, this);\n    }\n    /** @internal */\n    get _name() {\n        return 'MPEG-TS';\n    }\n    getSupportedTrackCounts() {\n        const maxVideo = 16; // Stream IDs 0xE0-0xEF\n        const maxAudio = 32;\n        const maxTotal = maxVideo + maxAudio;\n        return {\n            video: { min: 0, max: maxVideo },\n            audio: { min: 0, max: maxAudio },\n            subtitle: { min: 0, max: 0 },\n            total: { min: 0, max: maxTotal },\n        };\n    }\n    get fileExtension() {\n        return '.ts';\n    }\n    get mimeType() {\n        return 'video/MP2T';\n    }\n    getSupportedCodecs() {\n        return [\n            ...VIDEO_CODECS.filter(codec => ['avc', 'hevc'].includes(codec)),\n            ...AUDIO_CODECS.filter(codec => ['aac', 'mp3', 'ac3', 'eac3', 'dts'].includes(codec)),\n        ];\n    }\n    get supportsVideoTransformationMetadata() {\n        return false;\n    }\n    get supportsTimestampedMediaData() {\n        return true;\n    }\n    get negativeTimestampSupport() {\n        return 'prefer-non-negative';\n    }\n}\n/**\n * HTTP Live Streaming (HLS) output format. HLS media is represented by a set of .m3u8 playlist files and media segment\n * files, meaning this format writes out multiple files, requiring the use of a _pathed Output_\n * ({@link OutputOptions.target} must be a {@link PathedTarget}).\n *\n * This output format creates the following files:\n * - A master playlist .m3u8 file, containing the list of available playlists. A master playlist is always emitted,\n * written to the root path.\n * - One .m3u8 file for each playlist, each containing a list of media segments.\n * - Many media segments, containing the actual media data.\n *\n * To emit media playlists that use the `#EXT-X-PROGRAM-DATE-TIME` tag to map segment timestamps to real-world time,\n * set {@link BaseTrackMetadata.isRelativeToUnixEpoch} to `true` for all tracks.\n *\n * @group Output formats\n * @public\n */\nexport class HlsOutputFormat extends OutputFormat {\n    /** Creates a new {@link HlsOutputFormat} configured with the specified `options`. */\n    constructor(options) {\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (!(options.segmentFormat instanceof OutputFormat)\n            && (!Array.isArray(options.segmentFormat)\n                || options.segmentFormat.length === 0\n                || !options.segmentFormat.every(format => format instanceof OutputFormat))) {\n            throw new TypeError('options.segmentFormat must be an OutputFormat or a non-empty array of OutputFormat instances.');\n        }\n        if (options.targetDuration !== undefined\n            && (typeof options.targetDuration !== 'number' || options.targetDuration <= 0)) {\n            throw new TypeError('options.targetDuration, when provided, must be a positive number.');\n        }\n        if (options.singleFilePerPlaylist !== undefined && typeof options.singleFilePerPlaylist !== 'boolean') {\n            throw new TypeError('options.singleFilePerPlaylist, when provided, must be a boolean.');\n        }\n        if (options.live !== undefined && typeof options.live !== 'boolean') {\n            throw new TypeError('options.live, when provided, must be a boolean.');\n        }\n        if (options.maxLiveSegmentCount !== undefined\n            && (typeof options.maxLiveSegmentCount !== 'number' || options.maxLiveSegmentCount < 1\n                || (Number.isFinite(options.maxLiveSegmentCount) && !Number.isInteger(options.maxLiveSegmentCount)))) {\n            throw new TypeError('options.maxLiveSegmentCount, when provided, must be a positive integer or Infinity.');\n        }\n        if (options.getPlaylistPath !== undefined && typeof options.getPlaylistPath !== 'function') {\n            throw new TypeError('options.getPlaylistPath, when provided, must be a function.');\n        }\n        if (options.getSegmentPath !== undefined && typeof options.getSegmentPath !== 'function') {\n            throw new TypeError('options.getSegmentPath, when provided, must be a function.');\n        }\n        if (options.getInitPath !== undefined && typeof options.getInitPath !== 'function') {\n            throw new TypeError('options.getInitPath, when provided, must be a function.');\n        }\n        if (options.onMaster !== undefined && typeof options.onMaster !== 'function') {\n            throw new TypeError('options.onMaster, when provided, must be a function.');\n        }\n        if (options.onPlaylist !== undefined && typeof options.onPlaylist !== 'function') {\n            throw new TypeError('options.onPlaylist, when provided, must be a function.');\n        }\n        if (options.onSegment !== undefined && typeof options.onSegment !== 'function') {\n            throw new TypeError('options.onSegment, when provided, must be a function.');\n        }\n        if (options.onInit !== undefined && typeof options.onInit !== 'function') {\n            throw new TypeError('options.onInit, when provided, must be a function.');\n        }\n        if (options.onSegmentPopped !== undefined && typeof options.onSegmentPopped !== 'function') {\n            throw new TypeError('options.onSegmentPopped, when provided, must be a function.');\n        }\n        super();\n        this._options = options;\n    }\n    /** @internal */\n    _createMuxer(output) {\n        return new HlsMuxer(output, this);\n    }\n    /** @internal */\n    get _name() {\n        return 'HTTP Live Streaming (HLS)';\n    }\n    get fileExtension() {\n        return '.m3u8';\n    }\n    get mimeType() {\n        return HLS_MIME_TYPE;\n    }\n    getSupportedCodecs() {\n        const uniqueCodecs = new Set(toArray(this._options.segmentFormat).flatMap(x => x.getSupportedCodecs()));\n        return [...uniqueCodecs];\n    }\n    getSupportedTrackCounts() {\n        let supportsVideo = false;\n        let supportsAudio = false;\n        let supportsSubtitle = false;\n        for (const format of toArray(this._options.segmentFormat)) {\n            const trackCounts = format.getSupportedTrackCounts();\n            supportsVideo ||= trackCounts.video.max > 0;\n            supportsAudio ||= trackCounts.audio.max > 0;\n            supportsSubtitle ||= trackCounts.subtitle.max > 0;\n        }\n        return {\n            video: { min: 0, max: supportsVideo ? Infinity : 0 },\n            audio: { min: 0, max: supportsAudio ? Infinity : 0 },\n            subtitle: { min: 0, max: 0 }, // Currently disabled\n            total: { min: 0, max: Infinity },\n        };\n    }\n    get supportsVideoTransformationMetadata() {\n        return toArray(this._options.segmentFormat).some(format => format.supportsVideoTransformationMetadata);\n    }\n    get supportsTimestampedMediaData() {\n        return true; // It's only half true, really, but \"false\" is not correct either\n    }\n    get negativeTimestampSupport() {\n        const formats = toArray(this._options.segmentFormat);\n        // Return the lowest baseline across all segment formats\n        if (formats.some(format => format.negativeTimestampSupport === 'none')) {\n            return 'none';\n        }\n        if (formats.some(format => format.negativeTimestampSupport === 'prefer-non-negative')) {\n            return 'prefer-non-negative';\n        }\n        if (formats.some(format => format.negativeTimestampSupport === 'full')) {\n            return 'full';\n        }\n        return null;\n    }\n    /** @internal */\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    _codecUnsupportedHint(codec) {\n        return ` Using different segment formats may grant support for this codec.`;\n    }\n}\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport { assert, AsyncMutex, EventEmitter, isIso639Dash2LanguageCode, isThenable, toArray, } from './misc.js';\nimport { validateMetadataTags, validateTrackDisposition } from './metadata.js';\nimport { OutputFormat } from './output-format.js';\nimport { AudioSource, SubtitleSource, VideoSource } from './media-source.js';\nimport { PathedTarget, Target } from './target.js';\nimport { Writer } from './writer.js';\nimport { Logging } from './logging.js';\nimport { EncodedPacket } from './packet.js';\nimport { validateAudioChunkMetadata, validateVideoChunkMetadata } from './codec.js';\n/**\n * List of all track types.\n * @group Miscellaneous\n * @public\n */\nexport const ALL_TRACK_TYPES = ['video', 'audio', 'subtitle'];\n/**\n * Represents a track added to an {@link Output}.\n * @group Output files\n * @public\n */\nexport class OutputTrack {\n    /** @internal */\n    constructor(id, output, type, source, metadata) {\n        this.id = id;\n        this.output = output;\n        this.type = type;\n        this.source = source;\n        this.metadata = metadata;\n    }\n    /** Returns true if and only if this track is a video track. */\n    isVideoTrack() {\n        return this.type === 'video';\n    }\n    /** Returns true if and only if this track is an audio track. */\n    isAudioTrack() {\n        return this.type === 'audio';\n    }\n    /** Returns true if and only if this track is a subtitle track. */\n    isSubtitleTrack() {\n        return this.type === 'subtitle';\n    }\n    /**\n     * Returns true if and only if this track can be paired with the given other track. Pairability can be set using\n     * the {@link BaseTrackMetadata.group} option.\n     */\n    canBePairedWith(other) {\n        if (!(other instanceof OutputTrack)) {\n            throw new TypeError('other must be an OutputTrack.');\n        }\n        if (this === other) {\n            return false;\n        }\n        const thisGroups = toArray(this.metadata.group);\n        const otherGroups = toArray(other.metadata.group);\n        for (const aGroup of thisGroups) {\n            const pairableInSameGroup = this.type !== other.type && otherGroups.some(bGroup => aGroup === bGroup);\n            if (pairableInSameGroup) {\n                return true;\n            }\n            const pairableAcrossGroups = otherGroups.some(bGroup => aGroup._pairedGroups.has(bGroup));\n            if (pairableAcrossGroups) {\n                return true;\n            }\n        }\n        return false;\n    }\n}\n/**\n * An {@link OutputTrack} providing video data, created using {@link Output.addVideoTrack}.\n * @group Output files\n * @public\n */\nexport class OutputVideoTrack extends OutputTrack {\n    /** @internal */\n    constructor(id, output, source, metadata) {\n        super(id, output, 'video', source, metadata);\n    }\n}\n/**\n * An {@link OutputTrack} providing audio data, created using {@link Output.addAudioTrack}.\n * @group Output files\n * @public\n */\nexport class OutputAudioTrack extends OutputTrack {\n    /** @internal */\n    constructor(id, output, source, metadata) {\n        super(id, output, 'audio', source, metadata);\n    }\n}\n/**\n * An {@link OutputTrack} providing subtitle data, created using {@link Output.addSubtitleTrack}.\n * @group Output files\n * @public\n */\nexport class OutputSubtitleTrack extends OutputTrack {\n    /** @internal */\n    constructor(id, output, source, metadata) {\n        super(id, output, 'subtitle', source, metadata);\n    }\n}\n/**\n * Used to define pairability between {@link OutputTrack} instances. First create the group, then assign tracks to it\n * via {@link BaseTrackMetadata.group}.\n *\n * Two tracks are considered _pairable_ if they are in the same group but have a different {@link TrackType}, or if they\n * are in different groups that are paired with each other. Groups can be paired with each other using the\n * {@link OutputTrackGroup.pairWith} method.\n *\n * @group Output files\n * @public\n */\nexport class OutputTrackGroup {\n    /** Creates a new {@link OutputTrackGroup}. */\n    constructor() {\n        /** @internal */\n        this._pairedGroups = new Set();\n        // The object's identity is the state\n    }\n    /**\n     * Marks this group as being pairable with another group, symmetrically. Output tracks where each track is assigned\n     * to one half of a group pairing are then considered pairable.\n     *\n     * You cannot pair a group with itself.\n     */\n    pairWith(other) {\n        if (!(other instanceof OutputTrackGroup)) {\n            throw new TypeError('other must be an OutputTrackGroup.');\n        }\n        if (this === other) {\n            throw new TypeError('Cannot pair a group with itself.');\n        }\n        this._pairedGroups.add(other);\n        other._pairedGroups.add(this);\n    }\n}\nconst validateBaseTrackMetadata = (metadata) => {\n    if (!metadata || typeof metadata !== 'object') {\n        throw new TypeError('metadata must be an object.');\n    }\n    if (metadata.languageCode !== undefined && !isIso639Dash2LanguageCode(metadata.languageCode)) {\n        throw new TypeError('metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.');\n    }\n    if (metadata.name !== undefined && typeof metadata.name !== 'string') {\n        throw new TypeError('metadata.name, when provided, must be a string.');\n    }\n    if (metadata.disposition !== undefined) {\n        validateTrackDisposition(metadata.disposition);\n    }\n    if (metadata.maximumPacketCount !== undefined\n        && (!Number.isInteger(metadata.maximumPacketCount) || metadata.maximumPacketCount < 0)) {\n        throw new TypeError('metadata.maximumPacketCount, when provided, must be a non-negative integer.');\n    }\n    if (metadata.bitrate !== undefined && (!Number.isFinite(metadata.bitrate) || metadata.bitrate < 0)) {\n        throw new TypeError('metadata.bitrate, when provided, must be a non-negative number.');\n    }\n    if (metadata.averageBitrate !== undefined\n        && (!Number.isFinite(metadata.averageBitrate) || metadata.averageBitrate < 0)) {\n        throw new TypeError('metadata.averageBitrate, when provided, must be a non-negative number.');\n    }\n    if (metadata.group !== undefined\n        && !(metadata.group instanceof OutputTrackGroup)\n        && (!Array.isArray(metadata.group) || metadata.group.some(group => !(group instanceof OutputTrackGroup)))) {\n        throw new TypeError('metadata.group, when provided, must be an OutputTrackGroup instance or an array of'\n            + ' OutputTrackGroup instances.');\n    }\n};\n/**\n * Main class orchestrating the creation of new media files.\n * @group Output files\n * @public\n */\nexport class Output extends EventEmitter {\n    /**\n     * The target to which the root file will be written. Throws when using {@link PathedTarget} with an async callback;\n     * prefer the `'target'` event for those cases.\n     */\n    get target() {\n        const errorMessage = 'Output.target cannot be used when using PathedTarget with an async callback.'\n            + ' Use the \\'target\\' event instead.';\n        // We use this field to make sure we can reliably throw in the `target` getter whenever retrieving the target\n        // requires awaiting a promise. We do this so there is no different behavior based on order: if the target has\n        // already been retrieved via the normal internal operations, and then somebody calls the `target` getter, even\n        // if the target is now available, the getter should still throw to be consistent in behavior and in definition.\n        if (this._rootTargetPromise) {\n            throw new TypeError(errorMessage);\n        }\n        const rootTargetResult = this._getRootTarget();\n        if (isThenable(rootTargetResult)) {\n            throw new TypeError(errorMessage);\n        }\n        return rootTargetResult;\n    }\n    /**\n     * Creates a new instance of {@link Output} which can then be used to create a new media file according to the\n     * specified {@link OutputOptions}.\n     */\n    constructor(options) {\n        super();\n        /** The current state of the output. */\n        this.state = 'pending';\n        /**\n         * The {@link OutputTrackGroup} that all tracks are assigned to by default unless otherwise specified by\n         * {@link BaseTrackMetadata.group}.\n         */\n        this.defaultTrackGroup = new OutputTrackGroup();\n        /**\n         * The tracks that have been added to this output. Treat it as a readonly field; to add tracks, use the methods.\n         */\n        this.tracks = [];\n        /** @internal */\n        this._onFinalize = null;\n        /** @internal */\n        this._unfinalizedTargets = new Set();\n        /** @internal */\n        this._rootWriterPromise = null;\n        /** @internal */\n        this._startPromise = null;\n        /** @internal */\n        this._cancelPromise = null;\n        /** @internal */\n        this._finalizePromise = null;\n        /** @internal */\n        this._mutex = new AsyncMutex();\n        /** @internal */\n        this._metadataTags = {};\n        /** @internal */\n        this._rootTarget = null;\n        /** @internal */\n        this._rootTargetPromise = null;\n        /**\n         * This field is used to synchronize multiple MediaStreamTracks. They use the same time coordinate system across\n         * tracks, and to ensure correct audio-video sync, we must use the same offset for all of them. The reason an offset\n         * is needed at all is because the timestamps typically don't start at zero.\n         * @internal\n         */\n        this._firstMediaStreamTimestamp = null;\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (!(options.format instanceof OutputFormat)) {\n            throw new TypeError('options.format must be an OutputFormat.');\n        }\n        if (!(options.target instanceof Target || options.target instanceof PathedTarget)) {\n            throw new TypeError('options.target must be a Target or a PathedTarget.');\n        }\n        if (options.target instanceof Target) {\n            this._rememberTarget(options.target);\n        }\n        if (options.initTarget !== undefined\n            && !(options.initTarget instanceof Target)\n            && typeof options.initTarget !== 'function') {\n            throw new Error('options.initTarget, when provided, must be a Target or a function that returns or resolves to'\n                + ' a Target.');\n        }\n        if (options.onFinalize !== undefined && typeof options.onFinalize !== 'function') {\n            throw new TypeError('options.onFinalize, when provided, must be a function.');\n        }\n        this.format = options.format;\n        this._target = options.target;\n        this._onFinalize = options.onFinalize ?? null;\n        this._initTarget = options.initTarget ?? null;\n        if (this._initTarget instanceof Target) {\n            this._rememberTarget(this._initTarget);\n        }\n        this._muxer = options.format._createMuxer(this);\n    }\n    /** @internal */\n    _getTargetValidated(request) {\n        assert(this._target instanceof PathedTarget);\n        const result = this._target.getTarget(request);\n        const handleResult = (result) => {\n            if (!(result instanceof Target)) {\n                throw new TypeError('getTarget must return a Target.');\n            }\n            return result;\n        };\n        if (isThenable(result)) {\n            return result.then(handleResult);\n        }\n        else {\n            return handleResult(result);\n        }\n    }\n    /** @internal */\n    async _getTarget(request) {\n        assert(this._target instanceof PathedTarget);\n        const target = await this._getTargetValidated(request);\n        this._emit('target', { target, request, isRoot: request.isRoot });\n        if (this.state === 'canceled') {\n            await target._close();\n        }\n        else {\n            this._rememberTarget(target);\n        }\n        return target;\n    }\n    /** @internal */\n    _rememberTarget(target) {\n        this._unfinalizedTargets.add(target);\n        target.on('finalized', () => this._unfinalizedTargets.delete(target), { once: true });\n    }\n    /** @internal */\n    async _getInitTarget() {\n        assert(this._initTarget !== null);\n        if (this._initTarget instanceof Target) {\n            return this._initTarget;\n        }\n        const target = await this._initTarget();\n        if (this.state === 'canceled') {\n            await target._close();\n        }\n        else {\n            this._rememberTarget(target);\n        }\n        return target;\n    }\n    /** @internal */\n    _hasInitTarget() {\n        return this._initTarget !== null;\n    }\n    /** @internal */\n    _getRootTarget() {\n        if (this._rootTarget) {\n            return this._rootTarget;\n        }\n        if (this._rootTargetPromise) {\n            return this._rootTargetPromise;\n        }\n        if (this._target instanceof Target) {\n            this._emit('target', { target: this._target, request: null, isRoot: true });\n            this._rootTarget = this._target;\n            return this._target;\n        }\n        const request = {\n            path: this._target.rootPath,\n            isRoot: true,\n            mimeType: this.format.mimeType,\n        };\n        const result = this._getTargetValidated(request);\n        const handleResult = (target) => {\n            if (this.state === 'canceled') {\n                // Promise thrown away here, but no way to surface it to the user really\n                void target._close();\n            }\n            else {\n                this._rememberTarget(target);\n            }\n            this._emit('target', { target, request, isRoot: true });\n            this._rootTarget = target;\n            return target;\n        };\n        if (isThenable(result)) {\n            return this._rootTargetPromise = result.then(handleResult);\n        }\n        else {\n            return handleResult(result);\n        }\n    }\n    /** @internal */\n    _getRootWriter(isMonotonic) {\n        return this._rootWriterPromise ??= (async () => {\n            const target = await this._getRootTarget();\n            const writer = new Writer(target, typeof isMonotonic === 'boolean' ? isMonotonic : isMonotonic(target));\n            writer.start();\n            return writer;\n        })();\n    }\n    /** Adds a video track to the output with the given source. Can only be called before the output is started. */\n    addVideoTrack(source, metadata = {}) {\n        if (!(source instanceof VideoSource)) {\n            throw new TypeError('source must be a VideoSource.');\n        }\n        validateBaseTrackMetadata(metadata);\n        if (metadata.rotation !== undefined && ![0, 90, 180, 270].includes(metadata.rotation)) {\n            throw new TypeError(`Invalid video rotation: ${metadata.rotation}. Has to be 0, 90, 180 or 270.`);\n        }\n        if (metadata.flip !== undefined && typeof metadata.flip !== 'boolean') {\n            throw new TypeError('metadata.flip, when provided, must be a boolean.');\n        }\n        if (metadata.transformationMatrix !== undefined\n            && (!Array.isArray(metadata.transformationMatrix)\n                || metadata.transformationMatrix.length !== 9\n                || !metadata.transformationMatrix.every(x => Number.isFinite(x)))) {\n            throw new TypeError('metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.');\n        }\n        if (metadata.frameRate !== undefined\n            && (!Number.isFinite(metadata.frameRate) || metadata.frameRate <= 0)) {\n            throw new TypeError(`Invalid video frame rate: ${metadata.frameRate}. Must be a positive number.`);\n        }\n        if (metadata.hasOnlyKeyPackets !== undefined && typeof metadata.hasOnlyKeyPackets !== 'boolean') {\n            throw new TypeError('metadata.hasOnlyKeyPackets, when provided, must be a boolean.');\n        }\n        if (metadata.canBeTransparent !== undefined && typeof metadata.canBeTransparent !== 'boolean') {\n            throw new TypeError('metadata.canBeTransparent, when provided, must be a boolean.');\n        }\n        if (metadata.decoderConfig !== undefined) {\n            validateVideoChunkMetadata({ decoderConfig: metadata.decoderConfig }, source._codec);\n        }\n        if (metadata.primingPacket !== undefined) {\n            if (!(metadata.primingPacket instanceof EncodedPacket)) {\n                throw new TypeError('metadata.primingPacket, when provided, must be an EncodedPacket.');\n            }\n            if (metadata.decoderConfig === undefined) {\n                throw new TypeError('metadata.primingPacket can only be provided alongside metadata.decoderConfig.');\n            }\n        }\n        const metadataCopy = { ...metadata };\n        metadataCopy.group ??= this.defaultTrackGroup;\n        return this._addTrack(new OutputVideoTrack(this.tracks.length + 1, this, source, metadataCopy));\n    }\n    /** Adds an audio track to the output with the given source. Can only be called before the output is started. */\n    addAudioTrack(source, metadata = {}) {\n        if (!(source instanceof AudioSource)) {\n            throw new TypeError('source must be an AudioSource.');\n        }\n        validateBaseTrackMetadata(metadata);\n        if (metadata.decoderConfig !== undefined) {\n            validateAudioChunkMetadata({ decoderConfig: metadata.decoderConfig }, source._codec);\n        }\n        if (metadata.primingPacket !== undefined) {\n            if (!(metadata.primingPacket instanceof EncodedPacket)) {\n                throw new TypeError('metadata.primingPacket, when provided, must be an EncodedPacket.');\n            }\n            if (metadata.decoderConfig === undefined) {\n                throw new TypeError('metadata.primingPacket can only be provided alongside metadata.decoderConfig.');\n            }\n        }\n        const metadataCopy = { ...metadata };\n        metadataCopy.group ??= this.defaultTrackGroup;\n        return this._addTrack(new OutputAudioTrack(this.tracks.length + 1, this, source, metadataCopy));\n    }\n    /** Adds a subtitle track to the output with the given source. Can only be called before the output is started. */\n    addSubtitleTrack(source, metadata = {}) {\n        if (!(source instanceof SubtitleSource)) {\n            throw new TypeError('source must be a SubtitleSource.');\n        }\n        validateBaseTrackMetadata(metadata);\n        const metadataCopy = { ...metadata };\n        metadataCopy.group ??= this.defaultTrackGroup;\n        return this._addTrack(new OutputSubtitleTrack(this.tracks.length + 1, this, source, metadataCopy));\n    }\n    /**\n     * Sets descriptive metadata tags about the media file, such as title, author, date, or cover art. When called\n     * multiple times, only the metadata from the last call will be used.\n     *\n     * Can only be called before the output is started.\n     */\n    setMetadataTags(tags) {\n        validateMetadataTags(tags);\n        if (this.state !== 'pending') {\n            throw new Error('Cannot set metadata tags after output has been started or canceled.');\n        }\n        this._metadataTags = tags;\n    }\n    /** @internal */\n    _addTrack(track) {\n        if (this.state !== 'pending') {\n            throw new Error('Cannot add track after output has been started or canceled.');\n        }\n        if (track.source._connectedTrack) {\n            throw new Error('Source is already used for a track.');\n        }\n        // Verify maximum track count constraints\n        const supportedTrackCounts = this.format.getSupportedTrackCounts();\n        const presentTracksOfThisType = this.tracks.reduce((count, t) => count + (t.type === track.type ? 1 : 0), 0);\n        const maxCount = supportedTrackCounts[track.type].max;\n        if (presentTracksOfThisType === maxCount) {\n            throw new Error(maxCount === 0\n                ? `${this.format._name} does not support ${track.type} tracks.`\n                : (`${this.format._name} does not support more than ${maxCount} ${track.type} track`\n                    + `${maxCount === 1 ? '' : 's'}.`));\n        }\n        const maxTotalCount = supportedTrackCounts.total.max;\n        if (this.tracks.length === maxTotalCount) {\n            throw new Error(`${this.format._name} does not support more than ${maxTotalCount} tracks`\n                + `${maxTotalCount === 1 ? '' : 's'} in total.`);\n        }\n        if (track.isVideoTrack()) {\n            const supportedVideoCodecs = this.format.getSupportedVideoCodecs();\n            if (supportedVideoCodecs.length === 0) {\n                throw new Error(`${this.format._name} does not support video tracks.`\n                    + this.format._codecUnsupportedHint(track.source._codec));\n            }\n            else if (!supportedVideoCodecs.includes(track.source._codec)) {\n                throw new Error(`Codec '${track.source._codec}' cannot be contained within ${this.format._name}. Supported`\n                    + ` video codecs are: ${supportedVideoCodecs.map(codec => `'${codec}'`).join(', ')}.`\n                    + this.format._codecUnsupportedHint(track.source._codec));\n            }\n        }\n        else if (track.isAudioTrack()) {\n            const supportedAudioCodecs = this.format.getSupportedAudioCodecs();\n            if (supportedAudioCodecs.length === 0) {\n                throw new Error(`${this.format._name} does not support audio tracks.`\n                    + this.format._codecUnsupportedHint(track.source._codec));\n            }\n            else if (!supportedAudioCodecs.includes(track.source._codec)) {\n                throw new Error(`Codec '${track.source._codec}' cannot be contained within ${this.format._name}. Supported`\n                    + ` audio codecs are: ${supportedAudioCodecs.map(codec => `'${codec}'`).join(', ')}.`\n                    + this.format._codecUnsupportedHint(track.source._codec));\n            }\n        }\n        else if (track.isSubtitleTrack()) {\n            const supportedSubtitleCodecs = this.format.getSupportedSubtitleCodecs();\n            if (supportedSubtitleCodecs.length === 0) {\n                throw new Error(`${this.format._name} does not support subtitle tracks.`\n                    + this.format._codecUnsupportedHint(track.source._codec));\n            }\n            else if (!supportedSubtitleCodecs.includes(track.source._codec)) {\n                throw new Error(`Codec '${track.source._codec}' cannot be contained within ${this.format._name}. Supported`\n                    + ` subtitle codecs are: ${supportedSubtitleCodecs.map(codec => `'${codec}'`).join(', ')}.`\n                    + this.format._codecUnsupportedHint(track.source._codec));\n            }\n        }\n        this.tracks.push(track);\n        track.source._connectedTrack = track;\n        return track;\n    }\n    /**\n     * Whether the output has enough tracks (of the correct type) to be started, based on the requirements of the output\n     * format.\n     */\n    hasEnoughTracks() {\n        const supportedTrackCounts = this.format.getSupportedTrackCounts();\n        for (const trackType of ALL_TRACK_TYPES) {\n            const presentTracksOfThisType = this.tracks.reduce((count, track) => count + (track.type === trackType ? 1 : 0), 0);\n            const minCount = supportedTrackCounts[trackType].min;\n            if (presentTracksOfThisType < minCount) {\n                return false;\n            }\n        }\n        const totalMinCount = supportedTrackCounts.total.min;\n        if (this.tracks.length < totalMinCount) {\n            return false;\n        }\n        return true;\n    }\n    /**\n     * Starts the creation of the output file. This method should be called after all tracks have been added. Only after\n     * the output has started can media samples be added to the tracks.\n     *\n     * @returns A promise that resolves when the output has successfully started and is ready to receive media samples.\n     */\n    async start() {\n        // Verify minimum track count constraints\n        const supportedTrackCounts = this.format.getSupportedTrackCounts();\n        for (const trackType of ALL_TRACK_TYPES) {\n            const presentTracksOfThisType = this.tracks.reduce((count, track) => count + (track.type === trackType ? 1 : 0), 0);\n            const minCount = supportedTrackCounts[trackType].min;\n            if (presentTracksOfThisType < minCount) {\n                throw new Error(minCount === supportedTrackCounts[trackType].max\n                    ? (`${this.format._name} requires exactly ${minCount} ${trackType}`\n                        + ` track${minCount === 1 ? '' : 's'}.`)\n                    : (`${this.format._name} requires at least ${minCount} ${trackType}`\n                        + ` track${minCount === 1 ? '' : 's'}.`));\n            }\n        }\n        const totalMinCount = supportedTrackCounts.total.min;\n        if (this.tracks.length < totalMinCount) {\n            throw new Error(totalMinCount === supportedTrackCounts.total.max\n                ? (`${this.format._name} requires exactly ${totalMinCount} track`\n                    + `${totalMinCount === 1 ? '' : 's'}.`)\n                : (`${this.format._name} requires at least ${totalMinCount} track`\n                    + `${totalMinCount === 1 ? '' : 's'}.`));\n        }\n        if (this.state === 'canceled') {\n            throw new Error('Output has been canceled.');\n        }\n        if (this._startPromise) {\n            Logging._warn('Output has already been started.');\n            return this._startPromise;\n        }\n        return this._startPromise = (async () => {\n            this.state = 'started';\n            // We want to call muxer.start immediately, so we avoid using an await here\n            const releasePromise = this._mutex.acquire();\n            try {\n                await this._muxer.start();\n                const promises = this.tracks.map(track => track.source._start());\n                await Promise.all(promises);\n            }\n            finally {\n                (await releasePromise)();\n            }\n        })();\n    }\n    /**\n     * Resolves with the full MIME type of the output file, including track codecs.\n     *\n     * The returned promise will resolve only once the precise codec strings of all tracks are known.\n     */\n    getMimeType() {\n        return this._muxer.getMimeType();\n    }\n    /**\n     * Cancels the creation of the output file, releasing internal resources like encoders and preventing further\n     * samples from being added.\n     *\n     * @returns A promise that resolves once all internal resources have been released.\n     */\n    async cancel() {\n        if (this.state === 'canceled') {\n            return this._cancelPromise ?? undefined;\n        }\n        else if (this.state === 'finalizing' || this.state === 'finalized') {\n            // Don't wanna warn when finalizing since that shows a warning when finalization fails and then cancel\n            // is called\n            if (this.state === 'finalized') {\n                Logging._warn('Output has already been finalized.');\n            }\n            return;\n        }\n        return this._cancelPromise = (async () => {\n            this.state = 'canceled';\n            const release = await this._mutex.acquire();\n            try {\n                const promises = this.tracks.map(x => x.source._flushOrWaitForOngoingClose(true)); // Force close\n                await Promise.all(promises);\n                await Promise.all([...this._unfinalizedTargets].map(target => target._close()));\n                this._unfinalizedTargets.clear();\n            }\n            finally {\n                release();\n            }\n        })();\n    }\n    /**\n     * Finalizes the output file. This method must be called after all media samples across all tracks have been added.\n     * Once the Promise returned by this method completes, the output file is ready.\n     */\n    async finalize() {\n        if (this.state === 'pending') {\n            throw new Error('Cannot finalize before starting.');\n        }\n        if (this.state === 'canceled') {\n            throw new Error('Cannot finalize after canceling.');\n        }\n        if (this._finalizePromise) {\n            Logging._warn('Output has already been finalized.');\n            return this._finalizePromise;\n        }\n        return this._finalizePromise = (async () => {\n            this.state = 'finalizing';\n            const release = await this._mutex.acquire();\n            try {\n                const promises = this.tracks.map(x => x.source._flushOrWaitForOngoingClose(false));\n                await Promise.all(promises);\n                await this._muxer.finalize();\n                if (this._rootWriterPromise) {\n                    const rootWriter = await this._rootWriterPromise;\n                    if (!rootWriter.finalized) {\n                        await rootWriter.flush();\n                        await rootWriter.finalize();\n                    }\n                }\n                if (this._onFinalize) {\n                    await this._onFinalize();\n                }\n                this.state = 'finalized';\n            }\n            catch (error) {\n                this.state = 'canceled';\n                throw error;\n            }\n            finally {\n                await Promise.all([...this._unfinalizedTargets].map(target => target._close().catch(() => { })));\n                this._unfinalizedTargets.clear();\n                release();\n            }\n        })();\n    }\n}\n","/*!\n * Copyright (c) 2026-present, Vanilagy and contributors\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nvar __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {\n    if (value !== null && value !== void 0) {\n        if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n        var dispose, inner;\n        if (async) {\n            if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n            dispose = value[Symbol.asyncDispose];\n        }\n        if (dispose === void 0) {\n            if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n            dispose = value[Symbol.dispose];\n            if (async) inner = dispose;\n        }\n        if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n        env.stack.push({ value: value, dispose: dispose, async: async });\n    }\n    else if (async) {\n        env.stack.push({ async: true });\n    }\n    return value;\n};\nvar __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {\n    return function (env) {\n        function fail(e) {\n            env.error = env.hasError ? new SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n            env.hasError = true;\n        }\n        var r, s = 0;\n        function next() {\n            while (r = env.stack.pop()) {\n                try {\n                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n                    if (r.dispose) {\n                        var result = r.dispose.call(r.value);\n                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n                    }\n                    else s |= 1;\n                }\n                catch (e) {\n                    fail(e);\n                }\n            }\n            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n            if (env.hasError) throw env.error;\n        }\n        return next();\n    };\n})(typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n    var e = new Error(message);\n    return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n});\nimport { AUDIO_CODECS, NON_PCM_AUDIO_CODECS, VIDEO_CODECS, } from './codec.js';\nimport { getEncodableAudioCodecs, getFirstEncodableVideoCodec, Quality, resolveQuality, } from './encode.js';\nimport { Input } from './input.js';\nimport { Logging } from './logging.js';\nimport { AudioSampleSink, EncodedPacketSink, VideoSampleSink, } from './media-sink.js';\nimport { EncodedVideoPacketSource, EncodedAudioPacketSource, VideoSampleSource, AudioSampleSource, } from './media-source.js';\nimport { assert, assertNever, ceilToMultipleOfTwo, clamp, isIso639Dash2LanguageCode, isNumber, composeRotationAndFlip, promiseWithResolvers, } from './misc.js';\nimport { Output, OutputTrackGroup } from './output.js';\nimport { Mp4OutputFormat } from './output-format.js';\nimport { AudioSample, clampCropRectangle, getBytesPerSample, validateCropRectangle, } from './sample.js';\nimport { validateMetadataTags } from './metadata.js';\nimport { NullTarget } from './target.js';\nconst validateVideoOptions = (videoOptions) => {\n    if (!videoOptions || typeof videoOptions !== 'object') {\n        throw new TypeError('options.video, when provided, must be an object.');\n    }\n    if (videoOptions?.discard !== undefined && typeof videoOptions.discard !== 'boolean') {\n        throw new TypeError('options.video.discard, when provided, must be a boolean.');\n    }\n    if (videoOptions?.forceTranscode !== undefined && typeof videoOptions.forceTranscode !== 'boolean') {\n        throw new TypeError('options.video.forceTranscode, when provided, must be a boolean.');\n    }\n    if (videoOptions?.codec !== undefined && !VIDEO_CODECS.includes(videoOptions.codec)) {\n        throw new TypeError(`options.video.codec, when provided, must be one of: ${VIDEO_CODECS.join(', ')}.`);\n    }\n    // eslint-disable-next-line @typescript-eslint/no-deprecated\n    const bitrate = videoOptions?.bitrate;\n    if (videoOptions?.quality !== undefined && !(videoOptions.quality instanceof Quality)) {\n        throw new TypeError('options.video.quality, when provided, must be a Quality.');\n    }\n    if (videoOptions?.quality !== undefined && bitrate !== undefined) {\n        throw new TypeError('options.video.quality and options.video.bitrate cannot both be provided.');\n    }\n    if (bitrate !== undefined && !(bitrate instanceof Quality) && (!Number.isInteger(bitrate) || bitrate <= 0)) {\n        throw new TypeError('options.video.bitrate, when provided, must be a positive integer or a quality.');\n    }\n    if (videoOptions?.width !== undefined\n        && (!Number.isInteger(videoOptions.width) || videoOptions.width <= 0)) {\n        throw new TypeError('options.video.width, when provided, must be a positive integer.');\n    }\n    if (videoOptions?.height !== undefined\n        && (!Number.isInteger(videoOptions.height) || videoOptions.height <= 0)) {\n        throw new TypeError('options.video.height, when provided, must be a positive integer.');\n    }\n    if (videoOptions?.fit !== undefined && !['fill', 'contain', 'cover'].includes(videoOptions.fit)) {\n        throw new TypeError('options.video.fit, when provided, must be one of \\'fill\\', \\'contain\\', or \\'cover\\'.');\n    }\n    if (videoOptions?.width !== undefined\n        && videoOptions.height !== undefined\n        && videoOptions.fit === undefined) {\n        throw new TypeError('When both options.video.width and options.video.height are provided, options.video.fit must also be'\n            + ' provided.');\n    }\n    if (videoOptions?.rotate !== undefined && ![0, 90, 180, 270].includes(videoOptions.rotate)) {\n        throw new TypeError('options.video.rotate, when provided, must be 0, 90, 180 or 270.');\n    }\n    if (videoOptions?.flip !== undefined && typeof videoOptions.flip !== 'boolean') {\n        throw new TypeError('options.video.flip, when provided, must be a boolean.');\n    }\n    if (videoOptions?.allowTransformationMetadata !== undefined\n        && typeof videoOptions.allowTransformationMetadata !== 'boolean') {\n        throw new TypeError('options.video.allowTransformationMetadata, when provided, must be a boolean.');\n    }\n    // eslint-disable-next-line @typescript-eslint/no-deprecated\n    if (videoOptions?.allowRotationMetadata !== undefined && typeof videoOptions.allowRotationMetadata !== 'boolean') {\n        throw new TypeError('options.video.allowRotationMetadata, when provided, must be a boolean.');\n    }\n    if (videoOptions?.crop !== undefined) {\n        validateCropRectangle(videoOptions.crop, 'options.video.');\n    }\n    if (videoOptions?.frameRate !== undefined\n        && (!Number.isFinite(videoOptions.frameRate) || videoOptions.frameRate <= 0)) {\n        throw new TypeError('options.video.frameRate, when provided, must be a finite positive number.');\n    }\n    if (videoOptions?.alpha !== undefined && !['discard', 'keep'].includes(videoOptions.alpha)) {\n        throw new TypeError('options.video.alpha, when provided, must be either \\'discard\\' or \\'keep\\'.');\n    }\n    if (videoOptions?.keyFrameInterval !== undefined\n        && (!Number.isFinite(videoOptions.keyFrameInterval) || videoOptions.keyFrameInterval < 0)) {\n        throw new TypeError('options.video.keyFrameInterval, when provided, must be a non-negative number.');\n    }\n    if (videoOptions?.process !== undefined && typeof videoOptions.process !== 'function') {\n        throw new TypeError('options.video.process, when provided, must be a function.');\n    }\n    if (videoOptions?.processedWidth !== undefined\n        && (!Number.isInteger(videoOptions.processedWidth) || videoOptions.processedWidth <= 0)) {\n        throw new TypeError('options.video.processedWidth, when provided, must be a positive integer.');\n    }\n    if (videoOptions?.processedHeight !== undefined\n        && (!Number.isInteger(videoOptions.processedHeight) || videoOptions.processedHeight <= 0)) {\n        throw new TypeError('options.video.processedHeight, when provided, must be a positive integer.');\n    }\n    if (videoOptions?.hardwareAcceleration !== undefined\n        && !['no-preference', 'prefer-hardware', 'prefer-software'].includes(videoOptions.hardwareAcceleration)) {\n        throw new TypeError('options.video.hardwareAcceleration, when provided, must be \\'no-preference\\', \\'prefer-hardware\\' or'\n            + ' \\'prefer-software\\'.');\n    }\n    if (videoOptions?.group !== undefined\n        && !(videoOptions.group instanceof OutputTrackGroup\n            || (Array.isArray(videoOptions.group) && videoOptions.group.every(x => x instanceof OutputTrackGroup)))) {\n        throw new TypeError('options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.');\n    }\n};\nconst validateAudioOptions = (audioOptions) => {\n    if (!audioOptions || typeof audioOptions !== 'object') {\n        throw new TypeError('options.audio, when provided, must be an object.');\n    }\n    if (audioOptions?.discard !== undefined && typeof audioOptions.discard !== 'boolean') {\n        throw new TypeError('options.audio.discard, when provided, must be a boolean.');\n    }\n    if (audioOptions?.forceTranscode !== undefined && typeof audioOptions.forceTranscode !== 'boolean') {\n        throw new TypeError('options.audio.forceTranscode, when provided, must be a boolean.');\n    }\n    if (audioOptions?.codec !== undefined && !AUDIO_CODECS.includes(audioOptions.codec)) {\n        throw new TypeError(`options.audio.codec, when provided, must be one of: ${AUDIO_CODECS.join(', ')}.`);\n    }\n    // eslint-disable-next-line @typescript-eslint/no-deprecated\n    const bitrate = audioOptions?.bitrate;\n    if (audioOptions?.quality !== undefined && !(audioOptions.quality instanceof Quality)) {\n        throw new TypeError('options.audio.quality, when provided, must be a Quality.');\n    }\n    if (audioOptions?.quality !== undefined && bitrate !== undefined) {\n        throw new TypeError('options.audio.quality and options.audio.bitrate cannot both be provided.');\n    }\n    if (bitrate !== undefined && !(bitrate instanceof Quality) && (!Number.isInteger(bitrate) || bitrate <= 0)) {\n        throw new TypeError('options.audio.bitrate, when provided, must be a positive integer or a quality.');\n    }\n    if (audioOptions?.numberOfChannels !== undefined\n        && (!Number.isInteger(audioOptions.numberOfChannels) || audioOptions.numberOfChannels <= 0)) {\n        throw new TypeError('options.audio.numberOfChannels, when provided, must be a positive integer.');\n    }\n    if (audioOptions?.sampleRate !== undefined\n        && (!Number.isInteger(audioOptions.sampleRate) || audioOptions.sampleRate <= 0)) {\n        throw new TypeError('options.audio.sampleRate, when provided, must be a positive integer.');\n    }\n    if (audioOptions?.sampleFormat !== undefined\n        && !['u8', 's16', 's32', 'f32'].includes(audioOptions.sampleFormat)) {\n        throw new TypeError('options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.');\n    }\n    if (audioOptions?.process !== undefined && typeof audioOptions.process !== 'function') {\n        throw new TypeError('options.audio.process, when provided, must be a function.');\n    }\n    if (audioOptions?.processedNumberOfChannels !== undefined\n        && (!Number.isInteger(audioOptions.processedNumberOfChannels) || audioOptions.processedNumberOfChannels <= 0)) {\n        throw new TypeError('options.audio.processedNumberOfChannels, when provided, must be a positive integer.');\n    }\n    if (audioOptions?.processedSampleRate !== undefined\n        && (!Number.isInteger(audioOptions.processedSampleRate) || audioOptions.processedSampleRate <= 0)) {\n        throw new TypeError('options.audio.processedSampleRate, when provided, must be a positive integer.');\n    }\n    if (audioOptions?.group !== undefined\n        && !(audioOptions.group instanceof OutputTrackGroup\n            || (Array.isArray(audioOptions.group) && audioOptions.group.every(x => x instanceof OutputTrackGroup)))) {\n        throw new TypeError('options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.');\n    }\n};\nconst FALLBACK_NUMBER_OF_CHANNELS = 2;\nconst FALLBACK_SAMPLE_RATE = 48000;\n/**\n * Represents a media file conversion process, used to convert one media file into another. In addition to conversion,\n * this class can be used to resize and rotate video, resample audio, drop tracks, or trim to a specific time range.\n * @group Conversion\n * @public\n */\nexport class Conversion {\n    /**\n     * The current state of the conversion.\n     *\n     * - `'idle'`: The conversion is not currently executing and isn't done; `execute` can be called.\n     * - `'executing'`: A call to `execute` is currently running.\n     * - `'canceled'`: The conversion has been canceled and can no longer be executed.\n     * - `'done'`: The conversion has run to completion. Subsequent calls to `execute` do nothing.\n     */\n    get state() {\n        return this._state;\n    }\n    /** Initializes a new conversion process without starting the conversion. */\n    static async init(options) {\n        const conversion = new Conversion(options);\n        await conversion._init();\n        return conversion;\n    }\n    /** Creates a new Conversion instance (duh). */\n    constructor(options) {\n        /** @internal */\n        this._state = 'idle';\n        /** @internal */\n        this._timestampOffset = 0;\n        /** @internal */\n        this._timestampOffsetAdjusted = false;\n        /** @internal */\n        this._copyTimestampPossible = new Map();\n        /** @internal */\n        this._copyStartPackets = new Map();\n        /** @internal */\n        this._nextOutputTrackId = 0;\n        /** @internal */\n        this._outputTrackIds = [];\n        /** @internal */\n        this._outputOwnTrackGroups = [];\n        /** @internal */\n        this._trackPumps = [];\n        /** @internal */\n        this._composable = false;\n        /** @internal */\n        this._executed = false;\n        /** @internal */\n        this._executionUntil = Infinity;\n        /** @internal */\n        this._pauseRequested = false;\n        /** @internal */\n        this._synchronizer = new TrackSynchronizer(this);\n        /** @internal */\n        this._totalDuration = null;\n        /** @internal */\n        this._maxTimestamps = new Map(); // Track ID -> timestamp\n        /**\n         * A callback that is fired whenever the conversion progresses. Gets passed as first argument a number between\n         * 0 and 1, indicating the completion of the conversion. Note that a progress of 1 doesn't necessarily mean the\n         * conversion is complete; the conversion is complete once `execute()` resolves.\n         *\n         * As second argument, this callback receives the input time in seconds that has been processed.\n         *\n         * In order for progress to be computed, this property must be set before `execute` is called.\n         */\n        this.onProgress = undefined;\n        /** @internal */\n        this._computeProgress = false;\n        /** @internal */\n        this._lastProgress = 0;\n        /** @internal */\n        this._lastProcessedTime = 0;\n        /**\n         * Whether this conversion, as it has been configured, is valid and can be executed. If this field is `false`, check\n         * the `discardedTracks` field for reasons. Composable conversions are always valid, even if they utilize\n         * zero tracks.\n         *\n         * Note: a conversion having discarded tracks does not automatically mean it is invalid; if the remaining, utilized\n         * tracks make for a valid output file, the conversion is still allowed.\n         */\n        this.isValid = false;\n        /**\n         * The list of tracks that are included in the output file. When fan-out is used, the same track appears in this\n         * array multiple times.\n         */\n        this.utilizedTracks = [];\n        /** The list of tracks from the input file that have been discarded, alongside the discard reason. */\n        this.discardedTracks = [];\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (!(options.input instanceof Input)) {\n            throw new TypeError('options.input must be an Input.');\n        }\n        if (!(options.output instanceof Output)) {\n            throw new TypeError('options.output must be an Output.');\n        }\n        if (options.tracks !== undefined\n            && options.tracks !== 'all'\n            && options.tracks !== 'primary') {\n            throw new TypeError('options.tracks, when provided, must be either \\'all\\' or \\'primary\\'.');\n        }\n        if (options.composable !== undefined && typeof options.composable !== 'boolean') {\n            throw new TypeError('options.composable, when provided, must be a boolean.');\n        }\n        if (options.copy !== undefined && options.copy !== false) {\n            if (!options.copy || typeof options.copy !== 'object') {\n                throw new TypeError('options.copy, when provided, must be an object or false.');\n            }\n            if (options.copy.mode !== undefined && !['forced', 'preferred'].includes(options.copy.mode)) {\n                throw new TypeError('options.copy.mode, when provided, must be \\'forced\\' or \\'preferred\\'.');\n            }\n            if (options.copy.shiftTolerance !== undefined\n                && (!isNumber(options.copy.shiftTolerance) || options.copy.shiftTolerance < 0)) {\n                throw new TypeError('options.copy.shiftTolerance, when provided, must be a non-negative number.');\n            }\n            if (options.copy.boundaryPolicy !== undefined\n                && !['expand', 'shrink'].includes(options.copy.boundaryPolicy)) {\n                throw new TypeError('options.copy.boundaryPolicy, when provided, must be \\'expand\\' or \\'shrink\\'.');\n            }\n            if (options.copy.boundaryTolerance !== undefined\n                && (!isNumber(options.copy.boundaryTolerance) || options.copy.boundaryTolerance < 0)) {\n                throw new TypeError('options.copy.boundaryTolerance, when provided, must be a non-negative number.');\n            }\n        }\n        const composable = options.composable ?? false;\n        if (!composable) {\n            if (options.output.tracks.length > 0\n                || Object.keys(options.output._metadataTags).length > 0\n                || options.output.state !== 'pending') {\n                throw new TypeError('options.output must be fresh: no tracks or metadata tags added and not started.');\n            }\n        }\n        else {\n            if (options.tags !== undefined) {\n                throw new TypeError('options.tags cannot be set by a composable conversion; set metadata directly on the output'\n                    + ' instead.');\n            }\n            if (options.output.state !== 'pending') {\n                throw new TypeError('options.output must not have been started yet.');\n            }\n        }\n        if (options.video !== undefined && typeof options.video !== 'function') {\n            if (Array.isArray(options.video)) {\n                for (const obj of options.video) {\n                    validateVideoOptions(obj);\n                }\n            }\n            else {\n                validateVideoOptions(options.video);\n            }\n        }\n        else {\n            // We'll validate the return value later\n        }\n        if (options.audio !== undefined && typeof options.audio !== 'function') {\n            if (Array.isArray(options.audio)) {\n                for (const obj of options.audio) {\n                    validateAudioOptions(obj);\n                }\n            }\n            else {\n                validateAudioOptions(options.audio);\n            }\n        }\n        else {\n            // We'll validate the return value later\n        }\n        if (options.trim !== undefined && (!options.trim || typeof options.trim !== 'object')) {\n            throw new TypeError('options.trim, when provided, must be an object.');\n        }\n        if (options.trim?.start !== undefined && (!Number.isFinite(options.trim.start))) {\n            throw new TypeError('options.trim.start, when provided, must be a finite number.');\n        }\n        if (options.trim?.end !== undefined && (!isNumber(options.trim.end))) {\n            throw new TypeError('options.trim.end, when provided, must be a number.');\n        }\n        if (options.trim?.start !== undefined\n            && options.trim.end !== undefined\n            && options.trim.start >= options.trim.end) {\n            throw new TypeError('options.trim.start must be less than options.trim.end.');\n        }\n        if (options.tags !== undefined\n            && (typeof options.tags !== 'object' || !options.tags)\n            && typeof options.tags !== 'function') {\n            throw new TypeError('options.tags, when provided, must be an object or a function.');\n        }\n        if (typeof options.tags === 'object') {\n            validateMetadataTags(options.tags);\n        }\n        if (options.showWarnings !== undefined && typeof options.showWarnings !== 'boolean') {\n            throw new TypeError('options.showWarnings, when provided, must be a boolean.');\n        }\n        this._options = options;\n        this._copyMode = options.copy === false ? false : options.copy?.mode ?? 'preferred';\n        this._copyTimestampShiftTolerance = options.copy === false ? 0 : options.copy?.shiftTolerance ?? 0;\n        this._copyBoundaryPolicy = options.copy === false ? 'expand' : options.copy?.boundaryPolicy ?? 'expand';\n        this._copyBoundaryTolerance = options.copy === false ? Infinity : options.copy?.boundaryTolerance ?? Infinity;\n        this._composable = composable;\n        this.input = options.input;\n        this.output = options.output;\n    }\n    /** @internal */\n    async _init() {\n        const inputFormat = await this.input.getFormat();\n        let tracks;\n        let trackMode = this._options.tracks;\n        if (trackMode === undefined) {\n            // HACK to keep bundle size low, temp for now\n            const defaultTrackMode = inputFormat.name.includes('(HLS)')\n                ? 'primary'\n                : 'all';\n            trackMode = defaultTrackMode;\n        }\n        if (trackMode === 'all') {\n            tracks = await this.input.getTracks();\n        }\n        else if (trackMode === 'primary') {\n            const primaryVideoTrack = await this.input.getPrimaryVideoTrack();\n            const primaryAudioTrack = await this.input.getPrimaryAudioTrack();\n            tracks = [primaryVideoTrack, primaryAudioTrack].filter(x => x !== null);\n        }\n        else {\n            assertNever(trackMode);\n            assert(false);\n        }\n        const outputTrackCounts = this.output.format.getSupportedTrackCounts();\n        // Input track counters\n        let nVideo = 1;\n        let nAudio = 1;\n        // All tracks that aren't discarded by the user\n        const filteredTracks = [];\n        const filteredTrackOptions = [];\n        for (const track of tracks) {\n            let trackOptions;\n            if (track.isVideoTrack()) {\n                if (this._options.video) {\n                    if (typeof this._options.video === 'function') {\n                        const returnedTrackOptions = await this._options.video(track, nVideo) ?? {};\n                        if (Array.isArray(returnedTrackOptions)) {\n                            for (const obj of returnedTrackOptions) {\n                                validateVideoOptions(obj);\n                            }\n                        }\n                        else {\n                            validateVideoOptions(returnedTrackOptions);\n                        }\n                        trackOptions = Array.isArray(returnedTrackOptions)\n                            ? returnedTrackOptions\n                            : [returnedTrackOptions];\n                        nVideo++;\n                    }\n                    else {\n                        // Already validated\n                        trackOptions = Array.isArray(this._options.video)\n                            ? this._options.video\n                            : [this._options.video];\n                    }\n                }\n                else {\n                    trackOptions = [{}];\n                }\n            }\n            else if (track.isAudioTrack()) {\n                if (this._options.audio) {\n                    if (typeof this._options.audio === 'function') {\n                        const returnedTrackOptions = await this._options.audio(track, nAudio) ?? {};\n                        if (Array.isArray(returnedTrackOptions)) {\n                            for (const obj of returnedTrackOptions) {\n                                validateAudioOptions(obj);\n                            }\n                        }\n                        else {\n                            validateAudioOptions(returnedTrackOptions);\n                        }\n                        trackOptions = Array.isArray(returnedTrackOptions)\n                            ? returnedTrackOptions\n                            : [returnedTrackOptions];\n                        nAudio++;\n                    }\n                    else {\n                        // Already validated\n                        trackOptions = Array.isArray(this._options.audio)\n                            ? this._options.audio\n                            : [this._options.audio];\n                    }\n                }\n                else {\n                    trackOptions = [{}];\n                }\n            }\n            else {\n                assert(false);\n            }\n            const discardOptions = trackOptions.filter(x => x.discard);\n            for (const discardOption of discardOptions) {\n                this.discardedTracks.push({\n                    track,\n                    reason: 'discarded_by_user',\n                    trackOptions: discardOption,\n                });\n            }\n            if (trackOptions.length === discardOptions.length) {\n                if (trackOptions.length === 0) {\n                    this.discardedTracks.push({\n                        track,\n                        reason: 'discarded_by_user',\n                        trackOptions: {},\n                    });\n                }\n                continue;\n            }\n            const nonDiscardOptions = trackOptions.filter(x => !x.discard);\n            filteredTracks.push(track);\n            filteredTrackOptions.push(nonDiscardOptions);\n        }\n        if (this._options.trim?.start !== undefined) {\n            this._startTimestamp = this._options.trim.start;\n        }\n        else {\n            // Compute the start timestamp from the set of filtered tracks. Technically these can still be narrowed\n            // down later due to discarded tracks, but we need to fix the start timestamp now due to track processing\n            // depending on it.\n            this._startTimestamp = Math.max(await this.input.getFirstTimestamp(filteredTracks), \n            // Samples can also have negative timestamps, but the meaning typically is \"don't present me\", so let's\n            // cut those out by default.\n            0);\n        }\n        this._endTimestamp = Math.max(this._options.trim?.end ?? Infinity, this._startTimestamp);\n        this._timestampOffset = -this._startTimestamp; // Initial value, may get refined later by track processing\n        // Run these sequentially so that output tracks have a deterministic order\n        for (let i = 0; i < filteredTracks.length; i++) {\n            const track = filteredTracks[i];\n            const options = filteredTrackOptions[i];\n            for (const option of options) {\n                if (this.output.tracks.length === outputTrackCounts.total.max) {\n                    this.discardedTracks.push({\n                        track,\n                        reason: 'max_track_count_reached',\n                        trackOptions: option,\n                    });\n                    continue;\n                }\n                const addedCountOfType = this.output.tracks.reduce((count, t) => count + (t.type === track.type ? 1 : 0), 0);\n                if (addedCountOfType === outputTrackCounts[track.type].max) {\n                    this.discardedTracks.push({\n                        track,\n                        reason: 'max_track_count_of_type_reached',\n                        trackOptions: option,\n                    });\n                    continue;\n                }\n                const outputTrackId = this._nextOutputTrackId++;\n                if (track.isVideoTrack()) {\n                    await this._processVideoTrack(track, option, outputTrackId);\n                }\n                else if (track.isAudioTrack()) {\n                    await this._processAudioTrack(track, option, outputTrackId);\n                }\n                else {\n                    assert(false);\n                }\n            }\n        }\n        // When no track groups are set by the user, then the output track pairability should be *identical* to the\n        // input's. We do the naive algorithm to achieve this: assign each track to its own group, and pair groups with\n        // each other based on input track pairability.\n        for (let i = 0; i < this.utilizedTracks.length - 1; i++) {\n            for (let j = i + 1; j < this.utilizedTracks.length; j++) {\n                const trackA = this.utilizedTracks[i];\n                const trackB = this.utilizedTracks[j];\n                const ownGroupA = this._outputOwnTrackGroups[i];\n                const ownGroupB = this._outputOwnTrackGroups[j];\n                assert(ownGroupA !== undefined);\n                assert(ownGroupB !== undefined);\n                if (ownGroupA && ownGroupB && trackA.canBePairedWith(trackB)) {\n                    ownGroupA.pairWith(ownGroupB);\n                }\n            }\n        }\n        // Now, let's deal with metadata tags. A composable conversion does not touch the output's metadata tags; that\n        // remains the responsibility of whoever owns the output.\n        if (!this._composable) {\n            const inputTags = await this.input.getMetadataTags();\n            let outputTags;\n            if (this._options.tags) {\n                const result = typeof this._options.tags === 'function'\n                    ? await this._options.tags(inputTags)\n                    : this._options.tags;\n                validateMetadataTags(result);\n                outputTags = result;\n            }\n            else {\n                outputTags = inputTags;\n            }\n            // Somewhat dirty but pragmatic\n            const inputAndOutputFormatMatch = inputFormat.mimeType === this.output.format.mimeType;\n            const rawTagsAreUnchanged = inputTags.raw === outputTags.raw;\n            if (rawTagsAreUnchanged && !inputAndOutputFormatMatch) {\n                // If the input and output formats aren't the same, copying over raw metadata tags makes no sense and\n                // only results in junk tags, so let's cut them out.\n                delete outputTags.raw;\n            }\n            this.output.setMetadataTags(outputTags);\n        }\n        // Let's check if the conversion can actually be executed\n        if (!this._composable) {\n            this.isValid = this.output.hasEnoughTracks() && this.output.tracks.length > 0;\n        }\n        else {\n            // Checking Output start validity is not up to us. We even consider zero-track conversions to be valid\n            this.isValid = true;\n        }\n        if (this._options.showWarnings ?? true) {\n            const warnElements = [];\n            const unintentionallyDiscardedTracks = this.discardedTracks.filter(x => x.reason !== 'discarded_by_user');\n            if (unintentionallyDiscardedTracks.length > 0) {\n                // Let's give the user a notice/warning about discarded tracks so they aren't confused\n                warnElements.push('Some tracks had to be discarded from the conversion:', unintentionallyDiscardedTracks);\n            }\n            if (!this.isValid) {\n                if (warnElements.length > 0) {\n                    warnElements.push('\\n\\n');\n                }\n                warnElements.push(this._getInvalidityExplanation().join(''));\n            }\n            if (warnElements.length > 0) {\n                Logging._warn(...warnElements);\n            }\n        }\n    }\n    /** @internal */\n    _getInvalidityExplanation() {\n        const elements = [];\n        if (this.discardedTracks.length === 0) {\n            elements.push('Due to missing tracks, this conversion cannot be executed.');\n        }\n        else {\n            const encodabilityIsTheProblem = this.discardedTracks.every(x => x.reason === 'discarded_by_user' || x.reason === 'no_encodable_target_codec') && this.discardedTracks.some(x => x.reason === 'no_encodable_target_codec');\n            elements.push('Due to discarded tracks, this conversion cannot be executed.');\n            if (encodabilityIsTheProblem) {\n                const codecs = this.discardedTracks.flatMap((x) => {\n                    if (x.reason === 'discarded_by_user')\n                        return [];\n                    let supportedCodecs;\n                    if (x.track.type === 'video') {\n                        supportedCodecs = this.output.format.getSupportedVideoCodecs();\n                    }\n                    else if (x.track.type === 'audio') {\n                        supportedCodecs = this.output.format.getSupportedAudioCodecs();\n                    }\n                    else {\n                        supportedCodecs = this.output.format.getSupportedSubtitleCodecs();\n                    }\n                    // If the user requested a specific codec, only that codec was ever attempted\n                    return supportedCodecs.filter(codec => !x.trackOptions.codec || codec === x.trackOptions.codec);\n                });\n                const uniqueCodecs = [...new Set(codecs)];\n                if (uniqueCodecs.length === 1) {\n                    elements.push(`\\nTracks were discarded because your environment is not able to encode '${uniqueCodecs[0]}'`\n                        + ' with the provided parameters.');\n                }\n                else {\n                    elements.push('\\nTracks were discarded because your environment is not able to encode any of the codecs'\n                        + ` ${uniqueCodecs.map(x => `'${x}'`).join(', ')} with the provided parameters.`);\n                }\n                if (uniqueCodecs.includes('mp3')) {\n                    elements.push(`\\nThe @mediabunny/mp3-encoder extension package provides support for encoding MP3.`);\n                }\n                if (uniqueCodecs.includes('aac')) {\n                    elements.push('\\nThe @mediabunny/aac-encoder extension package provides support for encoding AAC.');\n                }\n                if (uniqueCodecs.includes('ac3') || uniqueCodecs.includes('eac3')) {\n                    elements.push('\\nThe @mediabunny/ac3 extension package provides support'\n                        + ' for encoding and decoding AC-3/E-AC-3.');\n                }\n                if (uniqueCodecs.includes('flac')) {\n                    elements.push('\\nThe @mediabunny/flac-encoder extension package provides support for encoding FLAC.');\n                }\n            }\n            else {\n                elements.push('\\nCheck the discardedTracks field for more info.');\n            }\n        }\n        return elements;\n    }\n    /**\n     * Executes the conversion process and resolves when the conversion is complete. When\n     * {@link ConversionExecuteOptions.until} is provided, the conversion will be suspended once that output timestamp\n     * is reached and can be resumed with another call to `execute`. An ongoing execution may also be suspended via\n     * {@link ConversionExecuteOptions.pauseSignal}.\n     *\n     * Execution will throw if `isValid` is `false`.\n     */\n    async execute(options = {}) {\n        if (!options || typeof options !== 'object') {\n            throw new TypeError('options must be an object.');\n        }\n        if (options.until !== undefined && (typeof options.until !== 'number' || Number.isNaN(options.until))) {\n            throw new TypeError('options.until, when provided, must be a number.');\n        }\n        if (options.pauseSignal !== undefined && !(options.pauseSignal instanceof AbortSignal)) {\n            throw new TypeError('options.pauseSignal, when provided, must be an AbortSignal.');\n        }\n        if (!this.isValid) {\n            throw new Error('Cannot execute this conversion because its output configuration is invalid. Make sure to always check'\n                + ' the isValid field before executing a conversion.\\n'\n                + this._getInvalidityExplanation().join(''));\n        }\n        if (this._state === 'executing') {\n            throw new Error('Cannot call execute() while a previous call to execute() is still running.');\n        }\n        if (this._state === 'canceled') {\n            throw new ConversionCanceledError();\n        }\n        if (this._state === 'done') {\n            // The conversion already ran to completion, nothing left to do\n            return;\n        }\n        if (this._composable && this.output.state === 'pending') {\n            throw new Error('A composable conversion requires the output to be started. Call start() on the output before executing'\n                + ' the conversion.');\n        }\n        this._state = 'executing';\n        this._executionUntil = options.until ?? Infinity;\n        this._pauseRequested = options.pauseSignal?.aborted ?? false;\n        const onPause = () => {\n            if (this._state !== 'executing') {\n                return;\n            }\n            this._pauseRequested = true;\n            // Release any pumps stuck in the synchronizer so they can reach their next checkpoint and suspend\n            this._synchronizer.resolveAll();\n        };\n        options.pauseSignal?.addEventListener('abort', onPause);\n        for (const pump of this._trackPumps) {\n            if (!pump.done) {\n                pump.resolvers = promiseWithResolvers();\n            }\n        }\n        if (!this._executed) {\n            this._executed = true;\n            for (const id of this._outputTrackIds) {\n                this._synchronizer.declareTrack(id);\n            }\n            if (this.onProgress) {\n                // Compute duration using only the utilized tracks\n                const uniqueUtilizedTracks = new Set(this.utilizedTracks);\n                const durationPromises = [...uniqueUtilizedTracks].map(async (track) => {\n                    if (await track.isLive()) {\n                        return Infinity; // Upper bound (assuming no universe heat death)\n                    }\n                    return (await track.getDurationFromMetadata()) ?? (await track.computeDuration());\n                });\n                const duration = Math.max(0, ...await Promise.all(durationPromises));\n                this._computeProgress = true;\n                this._totalDuration = Math.min(duration - this._startTimestamp, this._endTimestamp - this._startTimestamp);\n                for (const id of this._outputTrackIds) {\n                    // Used for progress calculation. We start these at 0 which is technically not always the first\n                    // timestamp, but this is how we choose to model what \"progress\" means: it's how far we are done\n                    // with the trim region.\n                    this._maxTimestamps.set(id, 0);\n                }\n                this.onProgress?.(0, 0);\n            }\n            if (!this._composable) {\n                await this.output.start();\n            }\n            for (const pump of this._trackPumps) {\n                pump.start();\n            }\n        }\n        else {\n            // Wake all suspended track pumps\n            for (const pump of this._trackPumps) {\n                pump.wake?.();\n            }\n        }\n        try {\n            await Promise.all(this._trackPumps.map(x => x.resolvers.promise));\n        }\n        catch (error) {\n            if (this._state !== 'canceled') {\n                // Make sure to cancel to stop other encoding processes and clean up resources\n                void this.cancel();\n            }\n            throw error;\n        }\n        finally {\n            options.pauseSignal?.removeEventListener('abort', onPause);\n        }\n        if (this._state === 'canceled') {\n            throw new ConversionCanceledError();\n        }\n        const isDone = this._trackPumps.every(x => x.done);\n        this._state = isDone ? 'done' : 'idle';\n        if (isDone) {\n            if (!this._composable) {\n                await this.output.finalize();\n            }\n            if (this._computeProgress) {\n                // By this point, all tracks have closed and removed themselves from _maxTimestamps, so we use the last\n                // processed time we saw while they were still open\n                this.onProgress?.(1, this._lastProcessedTime);\n            }\n        }\n    }\n    /**\n     * Cancels the conversion process, causing any ongoing `execute` call to throw a `ConversionCanceledError`.\n     * Does nothing if the conversion is already complete.\n     */\n    async cancel() {\n        if (this._state === 'done') {\n            return;\n        }\n        if (this._state === 'canceled') {\n            Logging._warn('Conversion already canceled.');\n            return;\n        }\n        this._state = 'canceled';\n        // Wake all suspended track pumps so they can wind down\n        for (const pump of this._trackPumps) {\n            pump.wake?.();\n        }\n        this._synchronizer.resolveAll();\n        if (!this._composable) {\n            await this.output.cancel();\n        }\n    }\n    /** @internal */\n    async _processVideoTrack(track, trackOptions, outputTrackId) {\n        const sourceCodec = await track.getCodec();\n        if (!sourceCodec) {\n            this.discardedTracks.push({\n                track,\n                reason: 'unknown_source_codec',\n                trackOptions,\n            });\n            return;\n        }\n        let videoSource;\n        const innateRotation = await track.getRotation();\n        const innateFlip = await track.getFlip();\n        const { rotation: totalRotation, flip: totalFlip } = composeRotationAndFlip(innateRotation, innateFlip, trackOptions.rotate ?? 0, trackOptions.flip ?? false);\n        let outputTrackRotation = totalRotation;\n        let outputTrackFlip = totalFlip;\n        // When the transformation is left untouched, we forward the input's full matrix so nothing gets lost\n        let outputTrackMatrix = trackOptions.rotate || trackOptions.flip\n            ? null\n            : await track.getTransformationMatrix();\n        const canUseRotationMetadata = this.output.format.supportsVideoTransformationMetadata\n            // eslint-disable-next-line @typescript-eslint/no-deprecated\n            && (trackOptions.allowTransformationMetadata ?? trackOptions.allowRotationMetadata ?? true);\n        const squarePixelWidth = await track.getSquarePixelWidth();\n        const squarePixelHeight = await track.getSquarePixelHeight();\n        const [rotatedWidth, rotatedHeight] = totalRotation % 180 === 0\n            ? [squarePixelWidth, squarePixelHeight]\n            : [squarePixelHeight, squarePixelWidth];\n        let crop = trackOptions.crop;\n        if (crop) {\n            crop = clampCropRectangle(crop, rotatedWidth, rotatedHeight);\n        }\n        const [originalWidth, originalHeight] = crop\n            ? [crop.width, crop.height]\n            : [rotatedWidth, rotatedHeight];\n        let width = originalWidth;\n        let height = originalHeight;\n        const aspectRatio = width / height;\n        // A lot of video encoders require that the dimensions be multiples of 2\n        if (trackOptions.width !== undefined && trackOptions.height === undefined) {\n            width = ceilToMultipleOfTwo(trackOptions.width);\n            height = ceilToMultipleOfTwo(Math.round(width / aspectRatio));\n        }\n        else if (trackOptions.width === undefined && trackOptions.height !== undefined) {\n            height = ceilToMultipleOfTwo(trackOptions.height);\n            width = ceilToMultipleOfTwo(Math.round(height * aspectRatio));\n        }\n        else if (trackOptions.width !== undefined && trackOptions.height !== undefined) {\n            width = ceilToMultipleOfTwo(trackOptions.width);\n            height = ceilToMultipleOfTwo(trackOptions.height);\n        }\n        let videoCodecs = this.output.format.getSupportedVideoCodecs();\n        const alpha = trackOptions.alpha ?? 'discard';\n        let needsTranscode = !this._copyMode\n            || !!trackOptions.forceTranscode\n            || !!trackOptions.frameRate\n            || trackOptions.keyFrameInterval !== undefined\n            || trackOptions.process !== undefined\n            || trackOptions.quality !== undefined\n            // eslint-disable-next-line @typescript-eslint/no-deprecated\n            || trackOptions.bitrate !== undefined\n            || !videoCodecs.includes(sourceCodec)\n            || (trackOptions.codec && trackOptions.codec !== sourceCodec)\n            || width !== originalWidth\n            || height !== originalHeight\n            // TODO This is suboptimal: Forcing a rerender when both rotation and process are set is not\n            // performance-optimal, but right now there's no other way because we can't change the track rotation\n            // metadata after the output has already started. Should be possible with API changes in v2, though!\n            || (totalRotation !== 0 && !canUseRotationMetadata)\n            || (totalFlip && !canUseRotationMetadata)\n            || !!crop;\n        let copyStartPacket = null;\n        if (!needsTranscode) {\n            // Check if we can copy it\n            const sink = new EncodedPacketSink(track);\n            let startPacket = await sink.getKeyPacket(this._startTimestamp, { verifyKeyPackets: true })\n                ?? await sink.getFirstKeyPacket({ verifyKeyPackets: true });\n            if (startPacket\n                && startPacket.timestamp < this._startTimestamp\n                && startPacket.timestamp + startPacket.duration <= this._startTimestamp\n                && this._copyBoundaryPolicy === 'shrink') {\n                startPacket = await sink.getNextKeyPacket(startPacket, { verifyKeyPackets: true });\n            }\n            copyStartPacket = startPacket;\n            if (startPacket) {\n                // This clamp mirrors the packet timestamp clamping the copy loop does. The reason this is valid is\n                // because in the shrink case, we've already proven that the packet (at least partially) overlaps the\n                // trim region.\n                const effectiveStartTimestamp = this._copyBoundaryPolicy === 'shrink'\n                    ? Math.max(startPacket.timestamp, this._startTimestamp)\n                    : startPacket.timestamp;\n                const boundaryDeviation = this._copyBoundaryPolicy === 'shrink'\n                    ? effectiveStartTimestamp - this._startTimestamp\n                    : Math.max(this._startTimestamp - effectiveStartTimestamp, 0);\n                if (boundaryDeviation > this._copyBoundaryTolerance) {\n                    needsTranscode = true;\n                }\n                else if (!this.output.format.supportsTimestampedMediaData) {\n                    // Wants zero\n                    if (this._timestampOffsetAdjusted) {\n                        // We've already adjusted, we can't adjust twice\n                        const isValid = effectiveStartTimestamp + this._timestampOffset === 0;\n                        if (!isValid) {\n                            needsTranscode = true;\n                        }\n                    }\n                    else {\n                        const correction = clamp(this._startTimestamp - effectiveStartTimestamp, -this._copyTimestampShiftTolerance, this._copyTimestampShiftTolerance);\n                        const shiftedStartTimestamp = effectiveStartTimestamp + correction;\n                        const isValid = shiftedStartTimestamp === this._startTimestamp;\n                        if (isValid) {\n                            this._timestampOffset = -this._startTimestamp + correction;\n                            this._timestampOffsetAdjusted = true;\n                        }\n                        else {\n                            needsTranscode = true;\n                        }\n                    }\n                }\n                else if (this.output.format.negativeTimestampSupport !== 'full'\n                    && effectiveStartTimestamp < this._startTimestamp) {\n                    const correction = Math.min(this._startTimestamp - effectiveStartTimestamp, this._copyTimestampShiftTolerance);\n                    const shiftedStartTimestamp = effectiveStartTimestamp + correction;\n                    const isValid = shiftedStartTimestamp >= this._startTimestamp\n                        || (this.output.format.negativeTimestampSupport === 'prefer-non-negative'\n                            && this._copyMode === 'forced');\n                    if (isValid) {\n                        this._timestampOffset = Math.max(this._timestampOffset, -this._startTimestamp + correction);\n                    }\n                    else {\n                        needsTranscode = true;\n                    }\n                }\n            }\n        }\n        if (needsTranscode && this._copyMode === 'forced') {\n            this.discardedTracks.push({\n                track,\n                reason: 'cannot_copy',\n                trackOptions,\n            });\n            return;\n        }\n        if (!needsTranscode) {\n            // Fast path, we can simply copy over the encoded packets\n            const source = new EncodedVideoPacketSource(sourceCodec);\n            videoSource = source;\n            this._registerTrackPump(async (pump) => {\n                const sink = new EncodedPacketSink(track);\n                const decoderConfig = await track.getDecoderConfig();\n                const meta = { decoderConfig: decoderConfig ?? undefined };\n                let maxTimestamp = null;\n                // eslint-disable-next-line curly\n                if (copyStartPacket)\n                    for await (const packet of sink.packets(copyStartPacket, undefined, { verifyKeyPackets: true })) {\n                        if (this._state === 'canceled') {\n                            break;\n                        }\n                        if (packet.timestamp >= this._endTimestamp) {\n                            if (this._copyBoundaryPolicy === 'shrink') {\n                                break;\n                            }\n                            else {\n                                // Due to B-frames, there might still be packets we care about later on. Do a short\n                                // lookahead to find out if there are.\n                                let current = packet;\n                                let found = false;\n                                const lookahead = 6; // Heuristic, but should be enough for most streams\n                                for (let i = 0; i < lookahead; i++) {\n                                    const next = await sink.getNextPacket(current, { metadataOnly: true });\n                                    if (!next) {\n                                        break;\n                                    }\n                                    if (next.timestamp < this._endTimestamp) {\n                                        found = true;\n                                        break;\n                                    }\n                                    current = next;\n                                }\n                                if (!found) {\n                                    break;\n                                }\n                            }\n                        }\n                        let packetStartTimestamp = packet.timestamp;\n                        let packetEndTimestamp = packet.timestamp + packet.duration;\n                        if (this._copyBoundaryPolicy === 'shrink') {\n                            packetStartTimestamp = Math.max(packetStartTimestamp, this._startTimestamp);\n                            packetEndTimestamp = Math.min(packetEndTimestamp, this._endTimestamp);\n                            packetEndTimestamp = Math.max(packetEndTimestamp, packetStartTimestamp); // Just in case\n                        }\n                        packetStartTimestamp += this._timestampOffset;\n                        packetEndTimestamp += this._timestampOffset;\n                        // The muxer rejects key packets with a timestamp smaller than the largest timestamp of the\n                        // previous GOP. Some files in the wild actually violate this, so we demote such packets to delta\n                        // packets to keep them in the previous GOP and keep the rule satisfied\n                        let packetType = packet.type;\n                        if (packetType === 'key' && maxTimestamp !== null && packetStartTimestamp < maxTimestamp) {\n                            packetType = 'delta';\n                        }\n                        maxTimestamp = Math.max(maxTimestamp ?? -Infinity, packetStartTimestamp);\n                        const modifiedPacket = packet.clone({\n                            timestamp: packetStartTimestamp,\n                            duration: packetEndTimestamp - packetStartTimestamp,\n                            sideData: alpha === 'discard'\n                                ? {} // Remove alpha side data\n                                : packet.sideData,\n                            type: packetType,\n                        });\n                        this._updateProgress(outputTrackId, modifiedPacket.timestamp + modifiedPacket.duration);\n                        await source.add(modifiedPacket, meta);\n                        if (this._synchronizer.shouldWait(outputTrackId, modifiedPacket.timestamp)) {\n                            await this._synchronizer.wait(modifiedPacket.timestamp);\n                        }\n                        await this._checkpoint(pump, modifiedPacket.timestamp);\n                    }\n                source.close();\n                this._closeTrack(outputTrackId);\n            });\n        }\n        else {\n            // We need to decode & reencode the video\n            const canDecode = await track.canDecode();\n            if (!canDecode) {\n                this.discardedTracks.push({\n                    track,\n                    reason: 'undecodable_source_codec',\n                    trackOptions,\n                });\n                return;\n            }\n            if (trackOptions.codec) {\n                videoCodecs = videoCodecs.filter(codec => codec === trackOptions.codec);\n            }\n            // eslint-disable-next-line @typescript-eslint/no-deprecated\n            const quality = resolveQuality(trackOptions.quality, trackOptions.bitrate)\n                ?? new Quality('high');\n            const encodableCodec = await getFirstEncodableVideoCodec(videoCodecs, {\n                width: trackOptions.process && trackOptions.processedWidth\n                    ? trackOptions.processedWidth\n                    : width,\n                height: trackOptions.process && trackOptions.processedHeight\n                    ? trackOptions.processedHeight\n                    : height,\n                quality,\n            });\n            if (!encodableCodec) {\n                this.discardedTracks.push({\n                    track,\n                    reason: 'no_encodable_target_codec',\n                    trackOptions,\n                });\n                return;\n            }\n            const encodingConfig = {\n                codec: encodableCodec,\n                quality,\n                keyFrameInterval: trackOptions.keyFrameInterval,\n                sizeChangeBehavior: trackOptions.fit ?? 'passThrough',\n                alpha,\n                hardwareAcceleration: trackOptions.hardwareAcceleration,\n                transform: {},\n            };\n            assert(encodingConfig.transform);\n            let needsRerender = width !== originalWidth\n                || height !== originalHeight\n                || (totalRotation !== 0 && (!canUseRotationMetadata || trackOptions.process !== undefined))\n                || (totalFlip && (!canUseRotationMetadata || trackOptions.process !== undefined))\n                || !!crop\n                // Don't expect encoders to reliably handle non-square pixels:\n                || squarePixelWidth !== await track.getCodedWidth()\n                || squarePixelHeight !== await track.getCodedHeight();\n            if (!needsRerender) {\n                const env_1 = { stack: [], error: void 0, hasError: false };\n                try {\n                    // If we're directly passing decoded samples back to the encoder, sometimes the encoder may error due\n                    // to lack of support of certain video frame formats, like when HDR is at play. To check for this, we\n                    // first try to pass a single frame to the encoder to see how it behaves. If it throws, we then fall\n                    // back to the rerender path.\n                    //\n                    // Creating a new temporary Output is sort of hacky, but due to a lack of an isolated encoder API right\n                    // now, this is the simplest way. Will refactor in the future! TODO\n                    const tempOutput = new Output({\n                        format: new Mp4OutputFormat(), // Supports all video codecs\n                        target: new NullTarget(),\n                    });\n                    const tempSource = new VideoSampleSource(encodingConfig);\n                    tempOutput.addVideoTrack(tempSource);\n                    await tempOutput.start();\n                    // Let's just use the first sample to test\n                    const sink = new VideoSampleSink(track);\n                    const firstSample = __addDisposableResource(env_1, await sink.getSample(await track.getFirstTimestamp()), false);\n                    if (firstSample) {\n                        try {\n                            await tempSource.add(firstSample);\n                            firstSample.close();\n                            await tempOutput.finalize();\n                        }\n                        catch (error) {\n                            Logging._warn('An error occurred when probing encoder support. Falling back to rerender path.', error);\n                            void tempOutput.cancel();\n                            needsRerender = true;\n                            encodingConfig.transform.force = true;\n                        }\n                    }\n                    else {\n                        await tempOutput.cancel();\n                    }\n                }\n                catch (e_1) {\n                    env_1.error = e_1;\n                    env_1.hasError = true;\n                }\n                finally {\n                    __disposeResources(env_1);\n                }\n            }\n            if (trackOptions.frameRate) {\n                encodingConfig.transform.frameRate = trackOptions.frameRate;\n            }\n            if (trackOptions.process) {\n                encodingConfig.transform.process = trackOptions.process;\n            }\n            if (needsRerender) {\n                // Since the transform is baked into the output:\n                outputTrackRotation = 0;\n                outputTrackFlip = false;\n                outputTrackMatrix = null;\n                encodingConfig.transform.width = width;\n                encodingConfig.transform.height = height;\n                encodingConfig.transform.fit = trackOptions.fit ?? 'fill';\n                // The decoded samples already carry the innate rotation and flip, so only the additional ones go here\n                encodingConfig.transform.rotate = trackOptions.rotate;\n                encodingConfig.transform.flip = trackOptions.flip;\n                encodingConfig.transform.crop = crop;\n                encodingConfig.transform.alpha = alpha;\n            }\n            // We need to do this because `process` can emit new timestamps\n            let lastSampleTimestamp = null;\n            encodingConfig.onEncodedSample = (sample) => {\n                lastSampleTimestamp = sample.timestamp;\n            };\n            const source = new VideoSampleSource(encodingConfig);\n            videoSource = source;\n            this._registerTrackPump(async (pump) => {\n                const sink = new VideoSampleSink(track);\n                for await (const sample_1 of sink.samples(this._startTimestamp, this._endTimestamp)) {\n                    const env_2 = { stack: [], error: void 0, hasError: false };\n                    try {\n                        const sample = __addDisposableResource(env_2, sample_1, false);\n                        if (this._state === 'canceled') {\n                            break;\n                        }\n                        const clampedStartTimestamp = Math.max(this._startTimestamp, sample.timestamp);\n                        const clampedEndTimestamp = Math.min(this._endTimestamp, sample.timestamp + sample.duration);\n                        if (clampedStartTimestamp >= clampedEndTimestamp) {\n                            // Wholly out of the trim region\n                            continue;\n                        }\n                        sample.setTimestamp(clampedStartTimestamp + this._timestampOffset);\n                        sample.setDuration(clampedEndTimestamp - clampedStartTimestamp);\n                        this._updateProgress(outputTrackId, sample.timestamp + sample.duration);\n                        await source.add(sample);\n                        sample.close();\n                        if (lastSampleTimestamp !== null) {\n                            if (this._synchronizer.shouldWait(outputTrackId, lastSampleTimestamp)) {\n                                await this._synchronizer.wait(lastSampleTimestamp);\n                            }\n                            await this._checkpoint(pump, lastSampleTimestamp);\n                        }\n                    }\n                    catch (e_2) {\n                        env_2.error = e_2;\n                        env_2.hasError = true;\n                    }\n                    finally {\n                        __disposeResources(env_2);\n                    }\n                }\n                source.close();\n                this._closeTrack(outputTrackId);\n            });\n        }\n        let ownGroup = null;\n        if (!trackOptions.group && !this._composable) {\n            // Create per-track groups to replicate the input's pairability graph. Don't do this for composable\n            // conversions.\n            ownGroup = new OutputTrackGroup();\n        }\n        const videoTrackLanguageCode = await track.getLanguageCode();\n        const trackName = await track.getName();\n        const trackDisposition = await track.getDisposition();\n        // The input's bitrate metadata only stays meaningful when packets are copied\n        const bitrate = needsTranscode ? null : await track.getBitrate();\n        const averageBitrate = needsTranscode ? null : await track.getAverageBitrate();\n        const canBeTransparent = alpha === 'keep' && await track.canBeTransparent();\n        this.output.addVideoTrack(videoSource, {\n            frameRate: trackOptions.frameRate,\n            // TODO: This condition can be removed when all demuxers properly homogenize to BCP47 in v2\n            languageCode: isIso639Dash2LanguageCode(videoTrackLanguageCode)\n                ? videoTrackLanguageCode\n                : undefined,\n            name: trackName ?? undefined,\n            disposition: trackDisposition,\n            rotation: outputTrackRotation,\n            flip: outputTrackFlip,\n            transformationMatrix: outputTrackMatrix ?? undefined,\n            canBeTransparent,\n            group: ownGroup ?? trackOptions.group,\n            bitrate: bitrate ?? undefined,\n            averageBitrate: averageBitrate ?? undefined,\n        });\n        this.utilizedTracks.push(track);\n        this._outputTrackIds.push(outputTrackId);\n        this._outputOwnTrackGroups.push(ownGroup);\n    }\n    /** @internal */\n    async _processAudioTrack(track, trackOptions, outputTrackId) {\n        const sourceCodec = await track.getCodec();\n        if (!sourceCodec) {\n            this.discardedTracks.push({\n                track,\n                reason: 'unknown_source_codec',\n                trackOptions,\n            });\n            return;\n        }\n        let audioSource;\n        const originalNumberOfChannels = await track.getNumberOfChannels();\n        const originalSampleRate = await track.getSampleRate();\n        let numberOfChannels = trackOptions.numberOfChannels ?? originalNumberOfChannels;\n        let sampleRate = trackOptions.sampleRate ?? originalSampleRate;\n        let audioCodecs = this.output.format.getSupportedAudioCodecs();\n        let needsTranscode = !this._copyMode\n            || !!trackOptions.forceTranscode\n            || !!trackOptions.quality\n            // eslint-disable-next-line @typescript-eslint/no-deprecated\n            || !!trackOptions.bitrate\n            || numberOfChannels !== originalNumberOfChannels\n            || sampleRate !== originalSampleRate\n            || !audioCodecs.includes(sourceCodec)\n            || (!!trackOptions.codec && trackOptions.codec !== sourceCodec)\n            || trackOptions.process !== undefined\n            || trackOptions.sampleFormat !== undefined;\n        let copyStartPacket = null;\n        if (!needsTranscode) {\n            // Check if we can copy it\n            const sink = new EncodedPacketSink(track);\n            let startPacket = await sink.getKeyPacket(this._startTimestamp)\n                ?? await sink.getFirstKeyPacket();\n            if (startPacket\n                && ((this._copyBoundaryPolicy === 'shrink'\n                    && startPacket.timestamp < this._startTimestamp)\n                    || (this._copyBoundaryPolicy === 'expand'\n                        // Check if packet is wholly before the start\n                        && startPacket.timestamp + startPacket.duration <= this._startTimestamp))) {\n                startPacket = await sink.getNextKeyPacket(startPacket);\n            }\n            const hasDecoderWarmup = NON_PCM_AUDIO_CODECS.includes(sourceCodec)\n                && sourceCodec !== 'flac';\n            if (startPacket && this._copyBoundaryPolicy === 'expand' && hasDecoderWarmup) {\n                // Go one packet back\n                const previousPacket = await sink.getKeyPacket(startPacket.timestamp - 1 / (await track.getTimeResolution()));\n                if (previousPacket) {\n                    startPacket = previousPacket;\n                }\n            }\n            copyStartPacket = startPacket;\n            if (startPacket) {\n                const boundaryDeviation = this._copyBoundaryPolicy === 'shrink'\n                    ? Math.max(startPacket.timestamp - this._startTimestamp, 0)\n                    : Math.max(this._startTimestamp - startPacket.timestamp, 0);\n                if (boundaryDeviation > this._copyBoundaryTolerance) {\n                    needsTranscode = true;\n                }\n                else if (!this.output.format.supportsTimestampedMediaData) {\n                    // Wants zero\n                    if (this._timestampOffsetAdjusted) {\n                        // We've already adjusted, we can't adjust twice\n                        const isValid = startPacket.timestamp + this._timestampOffset === 0;\n                        if (!isValid) {\n                            needsTranscode = true;\n                        }\n                    }\n                    else {\n                        const correction = clamp(this._startTimestamp - startPacket.timestamp, -this._copyTimestampShiftTolerance, this._copyTimestampShiftTolerance);\n                        const shiftedStartTimestamp = startPacket.timestamp + correction;\n                        const isValid = shiftedStartTimestamp === this._startTimestamp;\n                        if (isValid) {\n                            this._timestampOffset = -this._startTimestamp + correction;\n                            this._timestampOffsetAdjusted = true;\n                        }\n                        else {\n                            needsTranscode = true;\n                        }\n                    }\n                }\n                else if (this.output.format.negativeTimestampSupport !== 'full'\n                    && startPacket.timestamp < this._startTimestamp) {\n                    const correction = Math.min(this._startTimestamp - startPacket.timestamp, this._copyTimestampShiftTolerance);\n                    const shiftedStartTimestamp = startPacket.timestamp + correction;\n                    const isValid = shiftedStartTimestamp >= this._startTimestamp\n                        || (this.output.format.negativeTimestampSupport === 'prefer-non-negative'\n                            && this._copyMode === 'forced');\n                    if (isValid) {\n                        this._timestampOffset = Math.max(this._timestampOffset, -this._startTimestamp + correction);\n                    }\n                    else {\n                        needsTranscode = true;\n                    }\n                }\n            }\n        }\n        if (needsTranscode && this._copyMode === 'forced') {\n            this.discardedTracks.push({\n                track,\n                reason: 'cannot_copy',\n                trackOptions,\n            });\n            return;\n        }\n        if (!needsTranscode) {\n            // Fast path, we can simply copy over the encoded packets\n            const source = new EncodedAudioPacketSource(sourceCodec);\n            audioSource = source;\n            this._registerTrackPump(async (pump) => {\n                const sink = new EncodedPacketSink(track);\n                const decoderConfig = await track.getDecoderConfig();\n                const meta = { decoderConfig: decoderConfig ?? undefined };\n                let maxTimestamp = null;\n                // eslint-disable-next-line curly\n                if (copyStartPacket)\n                    for await (const packet of sink.packets(copyStartPacket)) {\n                        if (this._state === 'canceled') {\n                            break;\n                        }\n                        if (packet.timestamp >= this._endTimestamp) {\n                            break;\n                        }\n                        if (this._copyBoundaryPolicy === 'shrink'\n                            && packet.timestamp + packet.duration > this._endTimestamp) {\n                            break;\n                        }\n                        const packetTimestamp = packet.timestamp + this._timestampOffset;\n                        // Drop packets that would violate the GOP timestamp monotonicity rule\n                        if (maxTimestamp !== null && packetTimestamp < maxTimestamp) {\n                            continue;\n                        }\n                        maxTimestamp = packetTimestamp;\n                        const modifiedPacket = packet.clone({\n                            timestamp: packetTimestamp,\n                            duration: packet.duration,\n                        });\n                        this._updateProgress(outputTrackId, modifiedPacket.timestamp + modifiedPacket.duration);\n                        await source.add(modifiedPacket, meta);\n                        if (this._synchronizer.shouldWait(outputTrackId, modifiedPacket.timestamp)) {\n                            await this._synchronizer.wait(modifiedPacket.timestamp);\n                        }\n                        await this._checkpoint(pump, modifiedPacket.timestamp);\n                    }\n                source.close();\n                this._closeTrack(outputTrackId);\n            });\n        }\n        else {\n            // We need to decode & reencode the audio\n            const canDecode = await track.canDecode();\n            if (!canDecode) {\n                this.discardedTracks.push({\n                    track,\n                    reason: 'undecodable_source_codec',\n                    trackOptions,\n                });\n                return;\n            }\n            let codecOfChoice = null;\n            if (trackOptions.codec) {\n                audioCodecs = audioCodecs.filter(codec => codec === trackOptions.codec);\n            }\n            // eslint-disable-next-line @typescript-eslint/no-deprecated\n            const quality = resolveQuality(trackOptions.quality, trackOptions.bitrate)\n                ?? new Quality('high');\n            const encodableCodecs = await getEncodableAudioCodecs(audioCodecs, {\n                numberOfChannels: trackOptions.process && trackOptions.processedNumberOfChannels\n                    ? trackOptions.processedNumberOfChannels\n                    : numberOfChannels,\n                sampleRate: trackOptions.process && trackOptions.processedSampleRate\n                    ? trackOptions.processedSampleRate\n                    : sampleRate,\n                quality,\n            });\n            if (!encodableCodecs.some(codec => NON_PCM_AUDIO_CODECS.includes(codec))\n                && audioCodecs.some(codec => NON_PCM_AUDIO_CODECS.includes(codec))\n                && (numberOfChannels !== FALLBACK_NUMBER_OF_CHANNELS || sampleRate !== FALLBACK_SAMPLE_RATE)) {\n                // We could not find a compatible non-PCM codec despite the container supporting them. This can be\n                // caused by strange channel count or sample rate configurations. Therefore, let's try again but with\n                // fallback parameters.\n                const encodableCodecsWithDefaultParams = await getEncodableAudioCodecs(audioCodecs, {\n                    numberOfChannels: FALLBACK_NUMBER_OF_CHANNELS,\n                    sampleRate: FALLBACK_SAMPLE_RATE,\n                    quality,\n                });\n                const nonPcmCodec = encodableCodecsWithDefaultParams\n                    .find(codec => NON_PCM_AUDIO_CODECS.includes(codec));\n                if (nonPcmCodec) {\n                    // We are able to encode using a non-PCM codec, but it'll require resampling\n                    codecOfChoice = nonPcmCodec;\n                    numberOfChannels = FALLBACK_NUMBER_OF_CHANNELS;\n                    sampleRate = FALLBACK_SAMPLE_RATE;\n                }\n            }\n            else {\n                codecOfChoice = encodableCodecs[0] ?? null;\n            }\n            if (codecOfChoice === null) {\n                this.discardedTracks.push({\n                    track,\n                    reason: 'no_encodable_target_codec',\n                    trackOptions,\n                });\n                return;\n            }\n            const encodingConfig = {\n                codec: codecOfChoice,\n                quality,\n                transform: {\n                    sampleFormat: trackOptions.sampleFormat,\n                    process: trackOptions.process,\n                },\n            };\n            assert(encodingConfig.transform);\n            if (numberOfChannels !== originalNumberOfChannels) {\n                encodingConfig.transform.numberOfChannels = numberOfChannels;\n            }\n            if (sampleRate !== originalSampleRate) {\n                encodingConfig.transform.sampleRate = sampleRate;\n            }\n            let lastSampleTimestamp = null;\n            encodingConfig.onEncodedSample = (sample) => {\n                lastSampleTimestamp = sample.timestamp;\n            };\n            const source = new AudioSampleSource(encodingConfig);\n            audioSource = source;\n            this._registerTrackPump(async (pump) => {\n                let paddingLengthInSamples = null;\n                const sink = new AudioSampleSink(track);\n                for await (const sample_2 of sink.samples(this._startTimestamp, this._endTimestamp)) {\n                    const env_3 = { stack: [], error: void 0, hasError: false };\n                    try {\n                        const sample = __addDisposableResource(env_3, sample_2, false);\n                        if (this._state === 'canceled') {\n                            break;\n                        }\n                        let startFrame = 0;\n                        let endFrame = sample.numberOfFrames;\n                        if (sample.timestamp < this._startTimestamp) {\n                            startFrame = Math.round((this._startTimestamp - sample.timestamp) * sample.sampleRate);\n                        }\n                        if (sample.timestamp + sample.duration > this._endTimestamp) {\n                            endFrame = Math.round((this._endTimestamp - sample.timestamp) * sample.sampleRate);\n                        }\n                        if (startFrame >= endFrame) {\n                            // Sample lies wholly out of trim region\n                            sample.close();\n                            continue; // No break since we may be before the start\n                        }\n                        // Can't assign to \"using\" identifiers so we gotta do this\n                        let finalSampleLet;\n                        if (startFrame > 0 || endFrame < sample.numberOfFrames) {\n                            // Trim the sample if it sticks out of the trim region on either end\n                            const trimmedSample = sample.trim(startFrame, endFrame);\n                            sample.close();\n                            finalSampleLet = trimmedSample;\n                            if (trimmedSample.numberOfFrames === 0) {\n                                trimmedSample.close();\n                                continue;\n                            }\n                        }\n                        else {\n                            finalSampleLet = sample;\n                        }\n                        const finalSample = __addDisposableResource(env_3, finalSampleLet, false);\n                        // Offset the timestamp as needed\n                        finalSample.setTimestamp(finalSample.timestamp + this._timestampOffset);\n                        if (paddingLengthInSamples === null) {\n                            paddingLengthInSamples = this.output.format.supportsTimestampedMediaData\n                                ? 0\n                                : Math.round(finalSample.timestamp * originalSampleRate);\n                        }\n                        if (paddingLengthInSamples > 0) {\n                            const env_4 = { stack: [], error: void 0, hasError: false };\n                            try {\n                                // Add one padding sample at the beginning\n                                const bytesPerSample = getBytesPerSample(sample.format);\n                                const data = new Uint8Array(bytesPerSample * paddingLengthInSamples * originalNumberOfChannels);\n                                if (sample.format === 'u8' || sample.format === 'u8-planar') {\n                                    data.fill(2 ** 7); // Fill it with the silent value\n                                }\n                                const silentSample = __addDisposableResource(env_4, new AudioSample({\n                                    data,\n                                    // Use the same format the decoder is spitting out. This avoids feeding changing sample\n                                    // formats to the audio encoder.\n                                    format: sample.format,\n                                    numberOfChannels: originalNumberOfChannels,\n                                    sampleRate: originalSampleRate,\n                                    timestamp: 0,\n                                }), false);\n                                await this._registerAudioSample(pump, silentSample, source, outputTrackId, () => lastSampleTimestamp);\n                                paddingLengthInSamples = 0;\n                            }\n                            catch (e_3) {\n                                env_4.error = e_3;\n                                env_4.hasError = true;\n                            }\n                            finally {\n                                __disposeResources(env_4);\n                            }\n                        }\n                        await this._registerAudioSample(pump, finalSample, source, outputTrackId, () => lastSampleTimestamp);\n                    }\n                    catch (e_4) {\n                        env_3.error = e_4;\n                        env_3.hasError = true;\n                    }\n                    finally {\n                        __disposeResources(env_3);\n                    }\n                }\n                source.close();\n                this._closeTrack(outputTrackId);\n            });\n        }\n        let ownGroup = null;\n        if (!trackOptions.group && !this._composable) {\n            // Create per-track groups to replicate the input's pairability graph. Don't do this for composable\n            // conversions.\n            ownGroup = new OutputTrackGroup();\n        }\n        const audioTrackLanguageCode = await track.getLanguageCode();\n        const trackName = await track.getName();\n        const trackDisposition = await track.getDisposition();\n        // The input's bitrate metadata only stays meaningful when packets are copied\n        const bitrate = needsTranscode ? null : await track.getBitrate();\n        const averageBitrate = needsTranscode ? null : await track.getAverageBitrate();\n        this.output.addAudioTrack(audioSource, {\n            // TODO: This condition can be removed when all demuxers properly homogenize to BCP47 in v2\n            languageCode: isIso639Dash2LanguageCode(audioTrackLanguageCode)\n                ? audioTrackLanguageCode\n                : undefined,\n            name: trackName ?? undefined,\n            disposition: trackDisposition,\n            group: ownGroup ?? trackOptions.group,\n            bitrate: bitrate ?? undefined,\n            averageBitrate: averageBitrate ?? undefined,\n        });\n        this.utilizedTracks.push(track);\n        this._outputTrackIds.push(outputTrackId);\n        this._outputOwnTrackGroups.push(ownGroup);\n    }\n    /** @internal */\n    async _registerAudioSample(pump, sample, source, outputTrackId, getLastSampleTimestamp) {\n        this._updateProgress(outputTrackId, sample.timestamp + sample.duration);\n        await source.add(sample);\n        sample.close();\n        const lastSampleTimestamp = getLastSampleTimestamp();\n        if (lastSampleTimestamp !== null) {\n            if (this._synchronizer.shouldWait(outputTrackId, lastSampleTimestamp)) {\n                await this._synchronizer.wait(lastSampleTimestamp);\n            }\n            await this._checkpoint(pump, lastSampleTimestamp);\n        }\n    }\n    /** @internal */\n    _registerTrackPump(fn) {\n        const pump = {\n            done: false,\n            resolvers: promiseWithResolvers(),\n            wake: null,\n            start: () => {\n                void fn(pump).then(() => {\n                    pump.done = true;\n                    pump.resolvers.resolve();\n                }, (error) => {\n                    pump.resolvers.reject(error);\n                });\n            },\n        };\n        this._trackPumps.push(pump);\n    }\n    /** @internal */\n    async _checkpoint(pump, timestamp) {\n        while (this._state !== 'canceled' && (timestamp >= this._executionUntil || this._pauseRequested)) {\n            // We've reached the target; signal it and suspend until the next execution wakes us up\n            pump.resolvers.resolve();\n            const { promise, resolve } = promiseWithResolvers();\n            pump.wake = resolve;\n            await promise;\n        }\n    }\n    /** @internal */\n    _closeTrack(id) {\n        this._synchronizer.closeTrack(id);\n        this._maxTimestamps.delete(id);\n        this._reportProgress();\n    }\n    /** @internal */\n    _updateProgress(trackId, endTimestamp) {\n        if (!this._computeProgress) {\n            return;\n        }\n        this._maxTimestamps.set(trackId, Math.max(endTimestamp, this._maxTimestamps.get(trackId)));\n        this._reportProgress();\n    }\n    /** @internal */\n    _reportProgress() {\n        if (!this._computeProgress || this._maxTimestamps.size === 0) {\n            return;\n        }\n        assert(this._totalDuration !== null);\n        const minTimestamp = Math.min(...this._maxTimestamps.values());\n        const newProgress = clamp(minTimestamp / this._totalDuration, 0, 1);\n        this._lastProcessedTime = minTimestamp;\n        if (newProgress !== this._lastProgress) {\n            this._lastProgress = newProgress;\n            this.onProgress?.(newProgress, minTimestamp);\n        }\n    }\n}\n/**\n * Thrown when a conversion couldn't complete due to being canceled.\n * @group Conversion\n * @public\n */\nexport class ConversionCanceledError extends Error {\n    /** Creates a new {@link ConversionCanceledError}. */\n    constructor(message = 'Conversion has been canceled.') {\n        super(message);\n        this.name = 'ConversionCanceledError';\n    }\n}\nconst MAX_TIMESTAMP_GAP = 1; // in seconds\n/**\n * Utility class for synchronizing multiple track packet consumers with one another. We don't want one consumer to get\n * too out-of-sync with the others, as that may lead to a large number of packets that need to be internally buffered\n * before they can be written. Therefore, we use this class to slow down a consumer if it is too far ahead of the\n * slowest consumer.\n */\nclass TrackSynchronizer {\n    constructor(conversion) {\n        this.maxTimestamps = new Map(); // Track ID -> timestamp\n        this.resolvers = [];\n        this.conversion = conversion;\n    }\n    declareTrack(trackId) {\n        // Using -Infinity will automatically cause all tracks to wait for each other at the start until they figure out\n        // the true min timestamp\n        this.maxTimestamps.set(trackId, -Infinity);\n    }\n    shouldWait(trackId, timestamp) {\n        const currentValue = this.maxTimestamps.get(trackId);\n        assert(currentValue !== undefined);\n        this.maxTimestamps.set(trackId, Math.max(timestamp, currentValue));\n        const newMin = this.computeMinAndMaybeResolve();\n        if (this.conversion._state === 'canceled'\n            || this.conversion._pauseRequested\n            || timestamp >= this.conversion._executionUntil) {\n            // No point in throttling consumers that are about to suspend or wind down anyway\n            return false;\n        }\n        return timestamp - newMin > MAX_TIMESTAMP_GAP; // Should wait if it is too far ahead of the slowest consumer\n    }\n    wait(timestamp) {\n        const { promise, resolve } = promiseWithResolvers();\n        this.resolvers.push({\n            timestamp,\n            resolve,\n        });\n        return promise;\n    }\n    closeTrack(trackId) {\n        this.maxTimestamps.delete(trackId);\n        this.computeMinAndMaybeResolve();\n    }\n    resolveAll() {\n        for (const entry of this.resolvers) {\n            entry.resolve();\n        }\n        this.resolvers.length = 0;\n    }\n    computeMinAndMaybeResolve() {\n        let newMin = Infinity;\n        for (const [, timestamp] of this.maxTimestamps) {\n            newMin = Math.min(newMin, timestamp);\n        }\n        for (let i = 0; i < this.resolvers.length; i++) {\n            const entry = this.resolvers[i];\n            if (entry.timestamp - newMin < MAX_TIMESTAMP_GAP) {\n                // The gap has gotten small enough again, the consumer can continue again\n                entry.resolve();\n                this.resolvers.splice(i, 1);\n                i--;\n            }\n        }\n        return newMin;\n    }\n}\n","import {\n  BlobSource,\n  Conversion,\n  Input,\n  MATROSKA,\n  MP4,\n  MPEG_TS,\n  Mp4OutputFormat,\n  Output,\n  QTFF,\n  Quality,\n  StreamTarget,\n  WEBM,\n  type StreamTargetChunk,\n  type VideoCodec,\n} from \"mediabunny\";\n\n/** 转格式参数，与原生 `VideoConvertOptions` 一一对应。 */\nexport type ConvertVideoOptions = {\n  /** 输出宽度上限，只缩不放。 */\n  maxWidth?: number;\n  /** 输出高度上限，只缩不放。 */\n  maxHeight?: number;\n};\n\n/** 转格式结果。`url` 为 null 表示无需转码（已是 H.264 且尺寸合规）；转码失败抛出异常。 */\nexport type ConvertVideoResult = {\n  /** 产物 MP4 的 blob URL。 */\n  url: string | null;\n  /** 产物字节数；无需转码时为 0。 */\n  size: number;\n  /** 无需转码的原因；转码成功时为空串。 */\n  note: string;\n};\n\n/**\n * 已合规、无需转码的视频编码：只有 H.264，与原生 `compliant_codec` 一致。\n * HEVC 即使尺寸没超上限也要转码，所以不在这里。\n */\nconst COMPLIANT_CODECS: readonly VideoCodec[] = [\"avc\"];\n\n/** 估算源码率/帧率时采样的包数：只影响缩小场景的码率封顶，不扫全片。 */\nconst BITRATE_SAMPLE_PACKETS = 256;\n\n/**\n * Web 端把视频流式转成 H.264/MP4（Mediabunny + WebCodecs），与原生\n * `convert_video_file` 对齐：\n *\n * - 视频已是 H.264 且显示尺寸不超上限时保留原文件；\n * - 其余（包括 HEVC）都转为 H.264/MP4：分辨率按上限等比缩小、只缩不放，码率沿用源（缩小时\n *   按目标分辨率封顶），旋转/镜像烘进画面，音频统一输出 AAC（源是 AAC 时直拷）。\n *\n * 全程不把完整视频读进 JS 堆：输入是浏览器托管的 `Blob`，解封装按 range 读取；输出由\n * {@link BlobPartsSink} 按 muxer 的写入位置累积成 Blob 分片。Mediabunny 读不了的容器、\n * 浏览器没有 H.264 编码器、源编码解不开或音频无法转成 AAC 时抛出异常，由调用方退回\n * 原文件；只有「已是 H.264 且尺寸合规」返回 `url: null`。\n */\nexport async function convertVideo(\n  source: string | Uint8Array<ArrayBuffer>,\n  options: ConvertVideoOptions,\n): Promise<ConvertVideoResult> {\n  let input: Input | undefined;\n\n  try {\n    // string 时按 blob:/http URL 取回 Blob：浏览器可能把 Blob 落在磁盘上，不进 JS 堆\n    const blob = typeof source === \"string\" ? await (await fetch(source)).blob() : new Blob([source]);\n    // 可识别的输入容器与原生对齐；Mediabunny 不支持 AVI，读不出轨道时抛错，由调用方退回原文件\n    input = new Input({\n      source: new BlobSource(blob),\n      formats: [MP4, QTFF, WEBM, MATROSKA, MPEG_TS],\n    });\n\n    const videoTrack = await input.getPrimaryVideoTrack();\n    if (!videoTrack) throw new Error(\"no video track\");\n\n    const codec = await videoTrack.getCodec();\n    // getDisplayWidth / getDisplayHeight 已按 tkhd matrix 的旋转换算过宽高\n    const [displayWidth, displayHeight] = await Promise.all([\n      videoTrack.getDisplayWidth(),\n      videoTrack.getDisplayHeight(),\n    ]);\n    if (displayWidth === 0 || displayHeight === 0) {\n      throw new Error(\"video track has zero dimensions\");\n    }\n\n    // 与原生一致：只有已是 H.264 且显示尺寸不超上限时才保留原文件，HEVC 也要转码\n    if (codec !== null && COMPLIANT_CODECS.includes(codec) && withinLimits(displayWidth, displayHeight, options)) {\n      return alreadyCompliant(`kept original: already ${codec} within size limit`);\n    }\n\n    const dims = fitWithin(displayWidth, displayHeight, options.maxWidth, options.maxHeight);\n    // 先采样头部若干包估算源码率与帧率：缩小时用于给目标分辨率封顶\n    const stats = await videoTrack.computePacketStats(BITRATE_SAMPLE_PACKETS);\n    const videoBitrate = resolveBitrate(stats.averageBitrate, stats.averagePacketRate, displayWidth, displayHeight, dims);\n\n    const audioTrack = await input.getPrimaryAudioTrack();\n\n    const sink = new BlobPartsSink();\n    const streamTarget = new StreamTarget(\n      new WritableStream<StreamTargetChunk>({ write: (chunk) => sink.write(chunk) }),\n      // 不合并 chunk：muxer 的回填（mdat 尺寸补丁）需要按 position 逐次处理\n      { chunked: false },\n    );\n    const output = new Output({\n      // moov 放文件尾：写入基本是追加，不需要把整个产物缓冲在内存里做 fast start\n      format: new Mp4OutputFormat({ fastStart: false }),\n      target: streamTarget,\n    });\n\n    const conversion = await Conversion.init({\n      input,\n      output,\n      tracks: \"primary\",\n      showWarnings: false,\n      video: {\n        codec: \"avc\",\n        quality: new Quality({ bitrate: videoBitrate }),\n        // 目标尺寸始终显式给出（已向下取偶数）；fit: \"fill\" 配等比尺寸，避免 contain 的 letterbox\n        width: dims.width,\n        height: dims.height,\n        fit: \"fill\",\n        forceTranscode: true,\n        // 旋转/镜像烘进画面，产物不带 transformation 元数据，与原生链路一致\n        allowTransformationMetadata: false,\n      },\n      // 音频对齐原生：统一输出 AAC，源是 AAC 时直拷；浏览器编不了 AAC 时音轨被丢弃，下面兜底\n      audio: { codec: \"aac\" },\n    });\n\n    if (!conversion.isValid) {\n      const reasons = conversion.discardedTracks.map((track) => `${track.track.type}: ${track.reason}`).join(\", \");\n      throw new Error(`mediabunny unsupported (${reasons})`);\n    }\n    // 有音轨却被丢弃时不要产出静音视频\n    if (audioTrack && conversion.discardedTracks.some((track) => track.track === audioTrack)) {\n      throw new Error(\"audio track not convertible to AAC\");\n    }\n\n    await conversion.execute();\n\n    const size = sink.size;\n    if (size === 0) throw new Error(\"mediabunny produced no output\");\n\n    const outBlob = sink.toBlob(\"video/mp4\");\n    return { url: URL.createObjectURL(outBlob), size: outBlob.size, note: \"\" };\n  } catch (error) {\n    throw new Error(`mediabunny failed: ${String(error)}`);\n  } finally {\n    input?.dispose();\n  }\n}\n\n/** 已是 H.264 且尺寸合规：不需要转码，调用方沿用原文件。 */\nfunction alreadyCompliant(note: string): ConvertVideoResult {\n  return { url: null, size: 0, note };\n}\n\n/** 显示尺寸是否已在 `maxWidth`/`maxHeight` 限制内。 */\nfunction withinLimits(width: number, height: number, options: ConvertVideoOptions) {\n  return (options.maxWidth == null || width <= options.maxWidth)\n    && (options.maxHeight == null || height <= options.maxHeight);\n}\n\n/** 等比缩进 `maxW x maxH` 盒子，只缩不放；宽高向下取偶数（H.264 要求），与原生一致。 */\nfunction fitWithin(srcW: number, srcH: number, maxW?: number, maxH?: number) {\n  if (srcW === 0 || srcH === 0) return { width: srcW, height: srcH };\n\n  const scaleW = maxW ? maxW / srcW : 1;\n  const scaleH = maxH ? maxH / srcH : 1;\n  const scale = Math.min(1, scaleW, scaleH);\n\n  return {\n    width: evenFloor(srcW * scale),\n    height: evenFloor(srcH * scale),\n  };\n}\n\nfunction evenFloor(value: number) {\n  return Math.max(2, Math.floor(value / 2) * 2);\n}\n\n/**\n * 目标码率，与原生 `H264Target::resolve_bitrate_bps` 一致：尺寸不变沿用源码率；缩小时\n * 按目标分辨率的估算值封顶，避免源码率属于更大的画面、把缩小的产物撑大；源未报告码率\n * 时直接用估算值。\n */\nfunction resolveBitrate(sourceBitrate: number, fps: number, srcW: number, srcH: number, target: { width: number; height: number }) {\n  const estimated = fallbackBitrate(target.width, target.height, fps);\n  if (!(sourceBitrate > 0)) return estimated;\n\n  return target.width === srcW && target.height === srcH\n    ? Math.round(sourceBitrate)\n    : Math.min(Math.round(sourceBitrate), estimated);\n}\n\n/** 源未报告码率时的估算：约 0.1 bit/像素/帧，上下限与原生一致。 */\nfunction fallbackBitrate(width: number, height: number, fps: number) {\n  // 与原生一样按整数帧率估算；帧率读不到或过小时退回 30fps\n  const rate = Number.isFinite(fps) && fps > 1 ? Math.round(fps) : 30;\n  const pixelsPerSecond = width * height * rate;\n  return Math.round(Math.min(100_000_000, Math.max(1_000_000, pixelsPerSecond * 0.1)));\n}\n\n/**\n * 把 muxer 的按位置写入收敛成 Blob。\n *\n * MP4 muxer 绝大多数写入是追加，只有文件头里的 mdat 尺寸等少量回填；回填用 Blob 分片记录，\n * 最后用 `Blob.slice`（只读引用，不复制字节）拼回产物，避免把整个文件放进 JS 堆。\n */\nclass BlobPartsSink {\n  private parts: Blob[] = [];\n  private patches: Patch[] = [];\n  /** 已顺序写入的末尾位置。 */\n  private cursor = 0;\n  private maxEnd = 0;\n\n  write(chunk: StreamTargetChunk) {\n    const start = chunk.position;\n    const end = start + chunk.data.byteLength;\n    this.maxEnd = Math.max(this.maxEnd, end);\n\n    if (start > this.cursor) {\n      // 理论上不该有空洞，补零保持 parts 连续，后续按偏移切片才有意义\n      this.parts.push(blobOf(new Uint8Array(start - this.cursor)));\n      this.cursor = start;\n    }\n\n    if (start >= this.cursor) {\n      this.parts.push(blobOf(chunk.data));\n      this.cursor = end;\n      return;\n    }\n\n    // 回填：覆盖已写入区间的部分记为 patch，超出部分继续追加\n    const covered = Math.min(this.cursor, end);\n    if (covered > start) this.addPatch(start, covered, chunk.data);\n    if (end > this.cursor) {\n      this.parts.push(blobOf(chunk.data.subarray(covered - start)));\n      this.cursor = end;\n    }\n  }\n\n  get size() {\n    return this.maxEnd;\n  }\n\n  toBlob(type: string): Blob {\n    const body = new Blob(this.parts, { type });\n    if (this.patches.length === 0) return body;\n\n    const merged: Blob[] = [];\n    let offset = 0;\n    for (const patch of [...this.patches].sort((a, b) => a.start - b.start)) {\n      if (patch.start > offset) merged.push(body.slice(offset, patch.start));\n      merged.push(patch.blob);\n      offset = Math.max(offset, patch.end);\n    }\n    merged.push(body.slice(offset));\n    return new Blob(merged, { type });\n  }\n\n  /** 后写覆盖先写：与新区间重叠的旧 patch 先裁掉。 */\n  private addPatch(start: number, end: number, data: Uint8Array<ArrayBuffer>) {\n    const kept: Patch[] = [];\n    for (const patch of this.patches) {\n      if (patch.end <= start || patch.start >= end) {\n        kept.push(patch);\n        continue;\n      }\n      if (patch.start < start) {\n        kept.push({ start: patch.start, end: start, blob: patch.blob.slice(0, start - patch.start) });\n      }\n      if (patch.end > end) {\n        kept.push({ start: end, end: patch.end, blob: patch.blob.slice(end - patch.start) });\n      }\n    }\n    kept.push({ start, end, blob: blobOf(data.subarray(0, end - start)) });\n    this.patches = kept;\n  }\n}\n\ntype Patch = { start: number; end: number; blob: Blob };\n\nfunction blobOf(bytes: Uint8Array<ArrayBuffer>): Blob {\n  // 交给浏览器托管，Uint8Array 随即可回收\n  return new Blob([bytes]);\n}\n","import init, { xxh3_64 } from \"wasm-tgg\";\n\nexport { setBadge, clearBadge } from \"./badge.ts\";\nexport { convertVideo } from \"./videoConvert.ts\";\nexport { xxh3_64 as xxh3 } from \"wasm-tgg\";\n\ninit();\n\nexport default {};\n"],"names":["wasm","getStringFromWasm0","ptr","len","decodeText","cachedUint8ArrayMemory0","getUint8ArrayMemory0","passStringToWasm0","arg","malloc","realloc","buf","cachedTextEncoder","WASM_VECTOR_LEN","mem","offset","code","view","ret","cachedTextDecoder","MAX_SAFARI_DECODE_BYTES","numBytesDecoded","xxh3_64","data","deferred2_0","deferred2_1","ptr0","len0","EXPECTED_RESPONSE_TYPES","__wbg_load","module","imports","e","bytes","instance","__wbg_get_imports","table","__wbg_finalize_init","__wbg_init","module_or_path","Favico","opt","_def","_opt","_orig","_h","_w","_canvas","_context","_img","_ready","_lastBadge","_running","_readyCb","_stop","_browser","_animTimeout","_drawTimeout","_doc","_queue","init","merge","hexToRgb","animation","isUp","isLeft","i","step","type","link","icon","finished","run","a","options","more","badge","number","opts","q","o","image","imageElement","w","h","newImg","ratio","video","videoElement","drawVideo","webcam","action","obj","newVideo","stream","elm","getLink","l","canvas","url","old","hex","shorthandRegex","m","r","g","b","result","def","mergedOpt","attrname","isPageHidden","cb","revert","animationType","favicon","currentBadgeValue","originalTitle","updateTitleWithBadge","title","setBadge","value","clearBadge","observer","match","newTitle","assert","x","DEG_TO_RAD","RAD_TO_DEG","normalizeRotation","rotation","mappedRotation","IDENTITY_MATRIX","centeredTransformationMatrix","linear","width","height","c","d","transformedWidth","transformedHeight","multiplyMatrices","translationMatrix","extractRotationFromMatrix","matrix","radians","matrixIsFlipped","roundToMultiple","rotationMatrix","rotationInDegrees","theta","cosTheta","sinTheta","y","scaleMatrix","j","composeRotationAndFlip","rotation1","flip1","rotation2","flip2","last","arr","isU32","isI32","readExpGolomb","bitstream","leadingZeroBits","writeExpGolomb","codeNum","readSignedExpGolomb","toUint8Array","source","toDataView","TextEncoder","input","n","next","TextDecoder","label","normalized","units","lead","continuationCount","codePoint","lowerBound","upperBound","byte","littleEndian","bomLow","bomHigh","unit","textDecoder","textEncoder","invertObject","object","key","COLOR_PRIMARIES_MAP","COLOR_PRIMARIES_MAP_INVERSE","TRANSFER_CHARACTERISTICS_MAP","TRANSFER_CHARACTERISTICS_MAP_INVERSE","MATRIX_COEFFICIENTS_MAP","MATRIX_COEFFICIENTS_MAP_INVERSE","colorSpaceIsComplete","colorSpace","colorSpaceIsEmpty","EMPTY_COLOR_SPACE","isAllowSharedBufferSource","AsyncMutex","resolver","nextPromise","resolve","resolved","currentPromiseAlias","HEX_STRING_REGEX","bytesToHexString","hexStringToBytes","hexString","reverseBitsU32","binarySearchExact","valueGetter","low","high","ans","mid","midVal","binarySearchLessOrEqual","insertSorted","item","insertionIndex","promiseWithResolvers","reject","res","rej","removeItem","index","findLastIndex","predicate","toAsyncIterator","validateAnyIterable","iterable","assertNever","getUint24","byteOffset","byte1","byte2","byte3","getInt24","setUint24","setInt24","clamp","min","max","lerp","from","to","UNDETERMINED_LANGUAGE","roundIfAlmostInteger","rounded","multiple","roundToDivisor","floorToMultiple","floorToDivisor","popcount","count","ISO_639_2_REGEX","isIso639Dash2LanguageCode","SECOND_TO_MICROSECOND_FACTOR","computeRationalApproximation","maxDenominator","sign","prevNumerator","prevDenominator","currNumerator","currDenominator","remainder","integer","nextNumerator","nextDenominator","CallSerializer","fn","isWebKitCache","isWebKit","isFirefoxCache","isFirefox","isChromiumCache","isChromium","chromiumVersionCache","getChromiumVersion","missingWebCodecsClassMessage","className","isCodecReclaimedError","error","NativePromiseConstructor","isThenable","closedIntervalsOverlap","startA","endA","startB","endB","keyValueIterator","uint8ArraysAreEqual","polyfillSymbolDispose","isNumber","arrayCount","array","arrayArgmin","getValue","minIndex","minValue","simplifyRational","rational","t","gcd","validateRectangle","rect","propertyPath","wait","ms","toArray","EventEmitter","event","listener","entry","args","listeners","ceilToMultipleOfTwo","isRecordStringString","LogLevel","Logging","RichImageData","mimeType","AttachedFile","name","description","validateMetadataTags","tags","DEFAULT_TRACK_DISPOSITION","validateTrackDisposition","disposition","Bitstream","byteIndex","bitIndex","bit","end","other","leftover","clone","aacFrequencyTable","aacChannelMap","parseAacAudioSpecificConfig","objectType","readAacObjectType","frequencyIndex","sampleRate","readAacSamplingFrequency","channelConfiguration","numberOfChannels","coreObjectType","psPresent","outputSampleRate","searchStart","buildAacAudioSpecificConfig","config","usesSbr","usesPs","coreSampleRate","coreNumberOfChannels","bitCount","findAacFrequencyIndex","byteCount","writeAacObjectType","writeAacSamplingFrequency","AC3_SAMPLE_RATES","EAC3_REDUCED_SAMPLE_RATES","VERSION","VERSIONED_NAME","AvcNalUnitType","HevcNalUnitType","iterateNalUnitsInAnnexB","packetData","nalStart","zeroIndex","startCodeLength","iterateNalUnitsInLengthPrefixed","lengthSize","dataView","nalUnitLength","iterateAvcNalUnits","decoderConfig","extractNalUnitTypeForAvc","removeEmulationPreventionBytes","resultLength","addEmulationPreventionBytes","zeroCount","ANNEX_B_START_CODE","concatNalUnitsInAnnexB","nalUnits","totalLength","nalUnit","concatNalUnitsInLengthPrefixed","concatAvcNalUnits","extractAvcDecoderConfigurationRecord","spsUnits","ppsUnits","spsExtUnits","loc","spsData","spsInfo","parseAvcSps","hasExtendedData","serializeAvcDecoderConfigurationRecord","record","sps","length","pps","spsExt","deserializeAvcDecoderConfigurationRecord","configurationVersion","avcProfileIndication","profileCompatibility","avcLevelIndication","lengthSizeMinusOne","numOfSequenceParameterSets","sequenceParameterSets","numOfPictureParameterSets","pictureParameterSets","chromaFormat","bitDepthLumaMinus8","bitDepthChromaMinus8","numOfSequenceParameterSetExt","sequenceParameterSetExt","AVC_HEVC_ASPECT_RATIO_IDC_TABLE","emulationUnpreventedBytes","profileIdc","constraintFlags","levelIdc","chromaFormatIdc","separateColourPlaneFlag","sizeOfScalingList","lastScale","nextScale","deltaScale","picOrderCntType","numRefFramesInPicOrderCntCycle","picWidthInMbsMinus1","picHeightInMapUnitsMinus1","codedWidth","codedHeight","displayWidth","displayHeight","frameMbsOnlyFlag","frameCropLeftOffset","frameCropRightOffset","frameCropTopOffset","frameCropBottomOffset","cropUnitX","cropUnitY","subWidthC","subHeightC","colourPrimaries","transferCharacteristics","matrixCoefficients","fullRangeFlag","pixelAspectRatio","numReorderFrames","maxDecFrameBuffering","bitstreamRestrictionFlagBitOffset","bitstreamRestrictionFlag","vuiParametersFlagBitOffset","aspectRatioIdc","aspectRatio","nalHrdParametersPresentFlag","skipAvcHrdParameters","vclHrdParametersPresentFlag","constraintSet3Flag","picWidthInMbs","picHeightInMapUnits","frameHeightInMbs","levelInfo","AVC_LEVEL_TABLE","maxDpbFrames","cpb_cnt_minus1","addAvcBitstreamRestriction","modifiedBytes","oldBitstream","newBitstream","byteLength","concatHevcNalUnits","iterateHevcNalUnits","extractNalUnitTypeForHevc","parseHevcSps","spsMaxSubLayersMinus1","spsTemporalIdNestingFlag","general_profile_space","general_tier_flag","general_profile_idc","general_profile_compatibility_flags","general_constraint_indicator_flags","general_level_idc","parseProfileTierLevel","picWidthInLumaSamples","picHeightInLumaSamples","confWinLeftOffset","confWinRightOffset","confWinTopOffset","confWinBottomOffset","chromaArrayType","startI","spsMaxNumReorderPics","skipScalingListData","numShortTermRefPicSets","skipAllStRefPicSets","numLongTermRefPicsSps","minSpatialSegmentationIdc","vui","parseHevcVui","extractHevcDecoderConfigurationRecord","vpsUnits","seiUnits","parallelismType","ppsBitstream","tiles_enabled_flag","entropy_coding_sync_enabled_flag","arrays","maxNumSubLayersMinus1","sub_layer_profile_present_flag","sub_layer_level_present_flag","sizeId","matrixId","coefNum","num_short_term_ref_pic_sets","NumDeltaPocs","stRpsIdx","skipStRefPicSet","NumDeltaPocsThis","inter_ref_pic_set_prediction_flag","RefRpsIdx","delta_idx_minus1","numDelta","num_negative_pics","num_positive_pics","sps_max_sub_layers_minus1","aspect_ratio_idc","skipHevcHrdParameters","commonInfPresentFlag","nal_hrd_parameters_present_flag","vcl_hrd_parameters_present_flag","sub_pic_hrd_params_present_flag","fixed_pic_rate_general_flag","fixed_pic_rate_within_cvs_flag","low_delay_hrd_flag","CpbCnt","skipSubLayerHrdParameters","serializeHevcDecoderConfigurationRecord","nal","deserializeHevcDecoderConfigurationRecord","generalProfileSpace","generalTierFlag","generalProfileIdc","generalProfileCompatibilityFlags","generalConstraintIndicatorFlags","generalLevelIdc","avgFrameRate","byte21","constantFrameRate","numTemporalLayers","temporalIdNested","numOfArrays","arrByte","arrayCompleteness","nalUnitType","numNalus","HevcNaluOrderState","sanitizeHevcPacketForChromium","removedNalUnits","orderState","remove","filteredNalUnits","VP9_COLOR_SPACE_TABLE","extractVp9CodecInfoFromPacket","packet","profileLowBit","profile","bitDepth","chromaSubsampling","videoFullRangeFlag","subsamplingX","subsamplingY","widthMinusOne","heightMinusOne","pictureSize","level","VP9_LEVEL_TABLE","colorSpaceValues","vp9CodecInfoHasColorInfo","info","iterateAv1PacketObus","readLeb128","obuType","obuExtension","obuHasSizeField","obuSize","obuSizeValue","extractAv1CodecInfoFromPacket","seqProfile","reducedStillPictureHeader","seqLevel","seqTier","bufferDelayLengthMinus1","timingInfoPresentFlag","decoderModelInfoPresentFlag","leadingZeros","initialDisplayDelayPresentFlag","operatingPointsCntMinus1","seqLevelIdx","seqTierTemp","frameWidthBitsMinus1","frameHeightBitsMinus1","n1","n2","frameIdNumbersPresentFlag","enableOrderHint","seqChooseScreenContentTools","seqForceScreenContentTools","highBitdepth","monochrome","chromaSubsamplingX","chromaSubsamplingY","chromaSamplePosition","av1CodecInfoHasColorInfo","extractProresCodecInfoFromPacket","parseOpusIdentificationHeader","outputChannelCount","preSkip","inputSampleRate","outputGain","channelMappingFamily","channelMappingTable","determineVideoPacketType","codec","nalTypeByte","pos","payloadType","nextByte","payloadSize","recoveryFrameCount","exactMatchFlag","FlacBlockType","AC3_ACMOD_CHANNEL_COUNTS","parseAc3SyncFrame","fscod","frmsizecod","bsid","bsmod","acmod","lfeon","bitRateCode","AC3_FRAME_SIZES","AC3_SAMPLES_PER_FRAME","EAC3_NUMBLKS_TABLE","parseEac3SyncFrame","strmtyp","frmsiz","fscod2","numblkscod","numblks","fs","parseEac3Config","dataRate","numIndSub","substreams","numDepSub","chanLoc","getEac3SampleRate","sub","getEac3ChannelCount","channels","CHAN_LOC_COUNTS","DTS_EXSS_SYNC_WORD","DTS_CORE_FRAME_HEADER_SIZE","DTS_EXSS_HEADER_PREFIX_SIZE","DTS_EXSS_MAX_HEADER_SIZE","DTS_PCM_BLOCK_SAMPLES","DTS_SPECIFIC_BOX_SIZE","DTS_SUBBAND_SAMPLES","DTS_CORE_SAMPLE_RATES","DTS_CORE_BIT_RATES","DTS_PCM_RESOLUTIONS","DTS_AMODE_CHANNEL_COUNTS","DTS_AMODE_CHANNEL_LAYOUTS","DTS_CHANNEL_LAYOUT_LFE1","DTS_CHANNEL_LAYOUT_PAIR_MASK","DTS_EXSS_REF_CLOCKS","DTS_EXSS_SAMPLE_RATES","DTS_SPECIFIC_BOX_FRAME_DURATIONS","parseDtsFrame","core","parseDtsCoreFrameHeader","firstExss","exss","parseDtsExssHeader","asset","extractDtsFourCcFromPacket","frameInfo","cpf","npcmblocks","frameSize","amode","bitRate","lff","pcmResolution","lfePresent","extSsIndex","wideHeader","headerSizeBits","frameSizeBits","incomplete","refClock","frameDurationCycles","numAudioPresentations","numAssets","activeExssMasks","mask","spkrMaskBits","numMixOutConfigs","channelLayout","parseDtsSpecificBox","frameDuration","coreLfePresent","coreLayout","getDtsChannelCount","buildDtsSpecificBox","streamConstruction","VIDEO_CODECS","PCM_AUDIO_CODECS","NON_PCM_AUDIO_CODECS","AUDIO_CODECS","SUBTITLE_CODECS","HEVC_LEVEL_TABLE","AV1_LEVEL_TABLE","VP9_DEFAULT_SUFFIX","AV1_DEFAULT_SUFFIX","PRORES_FOURCCS","DTS_FOURCCS","PRORES_PROFILE_TARGET_BITRATES","buildVideoCodecString","bitrate","alpha","totalMacroblocks","levelIndication","hexProfileIndication","hexProfileCompatibility","hexLevelIndication","scaleFactor","candidates","bestFourCc","smallestDifference","fourCc","targetBitrate","difference","generateAv1CodecConfigurationFromCodecString","codecString","parts","firstByte","levelAndTier","secondByte","tier","highBitDepth","twelveBit","thirdByte","extractVideoCodecString","trackInfo","codecDescription","avcCodecInfo","hevcCodecInfo","vp9CodecInfo","av1CodecInfo","proresFormat","compatibilityFlags","profileByte","string","colorPrimaries","extractColorSpace","buildAudioCodecString","extractAudioCodecString","aacCodecInfo","dtsFormat","OPUS_SAMPLE_RATE","PCM_CODEC_REGEX","parsePcmCodec","dataType","sampleSize","silentValue","inferCodecFromCodecString","getVideoEncoderConfigExtension","getAudioEncoderConfigExtension","VALID_VIDEO_CODEC_STRING_PREFIXES","AVC_CODEC_STRING_REGEX","HEVC_CODEC_STRING_REGEX","VP9_CODEC_STRING_REGEX","AV1_CODEC_STRING_REGEX","validateVideoChunkMetadata","metadata","trackCodec","prefix","primariesValues","transferValues","matrixValues","VALID_AUDIO_CODEC_STRING_PREFIXES","validateAudioChunkMetadata","validateSubtitleMetadata","MP3_FRAME_HEADER_SIZE","SAMPLING_RATES","KILOBIT_RATES","computeMp3FrameSize","lowSamplingFrequency","layer","padding","readMp3FrameHeader","word","remainingBytes","fourthByte","mpeg25","mpegVersionId","bitrateIndex","channel","modeExtension","copyright","original","emphasis","kilobitRate","frameLength","audioSamplesInFrame","XingFlags","getMp3ChannelCount","Demuxer","PLACEHOLDER_DATA","EncodedPacket","timestamp","duration","sequenceNumber","sideData","chunk","buildIsobmffMimeType","uniqueCodecMimeTypes","parsePsshBoxContents","contents","version","systemId","keyIds","kidCount","dataSize","psshBoxesAreEqual","MIN_BOX_HEADER_SIZE","MAX_BOX_HEADER_SIZE","readBoxHeader","slice","totalSize","readU32Be","readAscii","headerSize","readU64Be","contentSize","readFixed_16_16","readI32Be","readFixed_2_30","readIsomVariableInteger","readU8","readEsDescriptor","mixed","streamDependenceFlag","urlFlag","ocrStreamFlag","urlLength","decoderConfigDescriptorLength","payloadStart","objectTypeIndication","decoderSpecificInfo","decoderSpecificInfoLength","readBytes","readMetadataStringShort","stringLength","readU16Be","readDataBox","header","typeIndicator","AES_128_BLOCK_SIZE","Te4","Td0","Td1","Td2","Td3","Td4","rcon","tablesGenerated","generateAesTables","sbox","log","pow","p","mul","s","is","b0","b1","b2","b3","Aes128CbcContext","iv","keyView","ivView","temp","k","rk","s0","s1","s2","s3","temp0","temp1","temp2","temp3","t0","t1","t2","t3","round","f0","f1","f2","f3","MAX_BOX_NESTING_DEPTH","IsobmffDemuxer","track","backings","codecStrings","currentPos","lookForMfraBox","foundMovieBoxes","startPos","boxInfo","majorBrand","moovSlice","previousSegmentDurationsInSeconds","lastWordSlice","lastWord","potentialMfraPos","mfraHeaderSlice","mfraSlice","writeIndex","initInput","initDemuxer","foreignTrack","videoTrack","IsobmffVideoTrackBacking","audioTrack","IsobmffAudioTrackBacking","internalTrack","sampleTable","stblContainerSlice","lastTimingEntry","lastChunkEntryIndex","lastChunkEntry","capEntryCounts","pcmInfo","newSampleTimingEntries","newSampleSizes","chunkEntry","nextEntry","chunkCount","newStartSampleIndex","startSampleIndex","endSampleIndex","startTimingEntryIndex","startTimingEntry","endTimingEntryIndex","endTimingEntry","firstSampleTimestamp","delta","lastSampleTimingEntry","chunkSize","entries","lastEntry","coveredSampleCount","sortedEntries","timingEntries","timingEntryIndex","getDecodeTimestampAhead","sampleIndex","timingEntry","lastSampleIndex","maxLastTimestamp","headerSlice","moofBoxInfo","entireSlice","fragment","trackData","fragmentPositionCache","lookupEntryIndex","lookupEntry","sample","timestampOffset","offsetFragmentTrackDataByTimestamp","lastCacheIndex","lastCache","previousEntry","resolveEncryptionAuxInfo","startIndex","contentStartPos","boxEndPos","readMatrix","trackEnabled","readU24Be","trackMatrix","relevantEntryFound","previousSegmentDurations","entryCount","segmentDuration","mediaTime","readI64Be","mediaRate","language","handlerType","stsdVersion","sampleBoxStartPos","sampleBoxInfo","lowercaseBoxName","codecName","channelCount","lpcmFlags","readF64Be","pcmSampleSize","bytesPerSample","isFloat","isBigEndian","sFlags","lowercase","schemeType","patternByte","constantIvSize","constantIv","applySpsPixelAspectRatio","configObus","configObuInfo","colourType","fullRange","num","den","maxBitrate","avgBitrate","audioSpecificConfig","formatFlags","readI16Be","BLOCK_TYPE_MASK","LAST_METADATA_BLOCK_FLAG_MASK","flagAndType","metadataBlockLength","endPos","currentIndex","currentTimestamp","sampleCount","sampleDelta","sampleOffset","fieldSize","skippedEntryCount","startChunkIndex","samplesPerChunk","sampleDescriptionIndex","chunkOffset","fragmentDuration","trackId","defaultSampleDescriptionIndex","defaultSampleDuration","defaultSampleSize","defaultSampleFlags","lengthSizeOfTrafNum","lengthSizeOfTrunNum","lengthSizeOfSampleNum","functions","readTrafNum","readTrunNum","readSampleNum","numberOfEntries","time","moofOffset","trunNumber","sampleNumber","cond","currentEntry","currentSample","firstSample","lastSample","currentFragmentState","psshBox","flags","baseDataOffsetPresent","sampleDescriptionIndexPresent","defaultSampleDurationPresent","defaultSampleSizePresent","defaultSampleFlagsPresent","durationIsEmpty","defaultBaseIsMoof","defaults","baseMediaDecodeTime","dataOffsetPresent","firstSampleFlagsPresent","sampleDurationPresent","sampleSizePresent","sampleFlagsPresent","sampleCompositionTimeOffsetsPresent","dataOffset","firstSampleFlags","sampleDuration","sampleFlags","sampleCompositionTimeOffset","isKeyFrame","auxInfoType","auxInfoTypeParam","defaultSampleInfoSize","sampleSizes","aux","getOrCreateEncryptionAuxInfo","useSubsamples","ivSize","subsamples","subsampleCount","clearLen","protectedLen","iterator","date","isQuickTime","keySize","keyName","metadataKey","nameAsNumber","bpm","trackNum","tracksTotal","trackNumber","discNumber","discNumberMax","IsobmffTrackBacking","demuxer","trackType","regularPacket","timestampInTimescale","getSampleIndexForTimestamp","sampleTableIsEmpty","correctSampleFound","regularSampleIndex","locationInFragment","getKeyframeSampleIndexForTimestamp","nextKeyFrameSampleIndex","getNextKeyframeIndexForSample","keyFrameIndex","sampleInfo","getSampleInfo","sampleEncryption","getDefaultSampleEncryption","decryptSample","fragmentSample","startFragment","getMatchInFragment","searchTimestamp","latestTimestamp","stopPos","lookupRetryCount","currentFragment","bestFragment","bestSampleIndex","positionCacheIndex","positionCacheEntry","lookupEntryPosition","lookupTableWins","scanStartPos","summary","boxStartPos","newSearchTimestamp","firstPacket","packetInfo","timescaleUnits","performPresentationTimeLookup","presentationTimestamp","offsetEntryIndex","offsetEntry","chunkEntryIndex","chunkIndex","startSampleIndexOfChunk","nextPresentationTimestamp","getNextPresentationTimestamp","keyFramesOnly","bestTimestamp","findFirstSampleInEntry","_","otherTimestamp","keySampleIndex","getDecodeTimestamp","lastStartedEntryIndex","nextTimestamp","nextSampleIndex","otherSampleIndex","reader","encryptionInfo","entrySize","keyId","keyBytes","cacheEntry","promise","psshBoxes","keyResult","decryptCtr","decryptCbcs","counter","cryptoKey","cryptApply","plaintext","cryptRanges","collectCryptRanges","totalCryptLen","range","seg","cryptBuffer","writePos","plain","output","readPos","ctx","cryptByteBlock","skipByteBlock","numBlocks","off","dataLength","ranges","hasPattern","cursor","subsample","perSubsample","remaining","cryptBytes","skipBytes","EBMLId","LEVEL_0_EBML_IDS","LEVEL_1_EBML_IDS","LEVEL_0_AND_1_EBML_IDS","MAX_VAR_INT_SIZE","MIN_HEADER_SIZE","MAX_HEADER_SIZE","readVarIntSize","readVarInt","readUnsignedInt","readUnsignedBigInt","readElementId","size","readElementSize","readElementHeader","id","readAsciiString","str","readUnicodeString","strLength","readFloat","readF32Be","searchForNextElementId","ids","until","idsSet","elementHeader","assertDefinedSize","resync","positionsToCheck","elementId","CODEC_STRING_MAP","buildMatroskaMimeType","BlockLacing","ContentEncodingScope","ContentCompAlgo","METADATA_ELEMENTS","MAX_RESYNC_LENGTH","MAX_ELEMENT_NESTING_DEPTH","MatroskaDemuxer","segment","metadataTags","dataStartPos","lastSegment","segmentDataStart","visitedSeekHeadPositions","elementStartPos","nextPos","metadataElementIndex","field","seekEntry","dataSlice","target","cuePoint","cuePoints","trackWithMostCuePoints","maxCuePointCount","cluster","hasLacedBlocks","block","currentBlock","firstBlock","lastBlock","blocks","expandedBlocks","originalBlock","FileSlice","frameSizes","frameCount","totalUsedSize","totalDataSize","firstResult","currentSize","diffResult","unsignedDiff","bias","diff","blockDuration","frameData","frameTimestamp","position","stopIds","lastSeekEntry","timestampScale","instruction","slashIndex","codecIdWithoutSuffix","format","MatroskaVideoTrackBacking","MatroskaAudioTrackBacking","languageSubtag","mapped","primaries","yaw","pitch","flippedRotation","lastCuePoint","blockSlice","relativeTimestamp","lacing","blockData","hasDecodingInstructions","blockAdditional","fileName","kind","lowerName","rawData","currentData","newData","discParts","discNum","discsTotal","MatroskaTrackBacking","blockIndex","correctBlockFound","locationInCluster","startCluster","getMatchInCluster","currentCluster","bestCluster","bestBlockIndex","cuePointIndex","cuePointWins","codecInfo","MIN_ADTS_FRAME_HEADER_SIZE","MAX_ADTS_FRAME_HEADER_SIZE","readAdtsFrameHeader","protectionAbsence","samplingFrequencyIndex","numberOfAacFrames","crcCheck","SAMPLES_PER_AAC_FRAME","TIMESCALE","TIMESTAMP_MODULUS","TS_PACKET_SIZE","buildMpegTsMimeType","uniqueCodecStrings","MISSING_PTS_ERROR_MESSAGE","REGISTRATION_DESCRIPTOR_TAG","HDMV_FORMAT_IDENTIFIER","HDPR_FORMAT_IDENTIFIER","DTS_FORMAT_IDENTIFIER_PREFIX","BLU_RAY_DTS_STREAM_TYPES","ignoredStreamTypes","MpegTsDemuxer","lengthToCheck","startingSlice","startingBytes","MIN_REFERENCE_POINT_PACKET_DISTANCE","programMapPid","hasProgramAssociationTable","hasProgramMap","packetHeader","section","BYTES_BEFORE_SECTION_LENGTH","BITS_IN_CRC_32","isProbablyProgramMap","pointerField","sectionLength","programNumber","programInfoLength","programInfoEndPos","isBluRayProgram","descriptorTag","descriptorLength","descriptorEndPos","formatIdentifier","streamType","elementaryPid","esInfoLength","esInfoEndPos","hasAc3Descriptor","hasEac3Descriptor","hasDtsDescriptor","effectiveStreamType","elementaryStream","outer","pesPacket","readPesPacket","matchingStream","context","PacketReadingContext","contextAlias","spsUnit","MpegTsVideoTrackBacking","MpegTsAudioTrackBacking","full","contiguous","chunks","chunksByteLength","mustAddSectionEnd","randomAccessIndicator","hasAdaptationField","hasPayload","adaptationFieldLength","merged","sum","nextTwoBytes","payloadUnitStartIndicator","pid","adaptationFieldControl","tolerance","reference","readPesPacketHeader","expectPts","streamId","ptsDtsFlags","pts","pesPacketLength","BYTES_UNTIL_END_OF_PES_PACKET_LENGTH","pesHeaderDataLength","pesHeaderEndPos","bytePos","MpegTsTrackBacking","backing","suppliedPacket","packetType","buffer","PacketBuffer","newPacket","sectionStartPos","targetSequenceNumber","currentPacket","keyframesOnly","searchPts","seekChunkSize","findFirstPesPacketHeaderInChunk","readSectionInFull","pesPacketHeader","firstSection","firstPesPacketHeader","referencePesPackets","referencePointIndex","referencePoint","numChunks","chunkStartPos","chunkEndPos","currentPesHeader","reorderSize","retrieveEncodedPacket","targetIndex","targetPacket","lastDuration","nextPesHeader","maybeInsertReferencePacket","currentChunkStartPos","nextChunkStartPos","readSectionsInFull","bestKeyPesHeader","isFirstChunk","pesHeader","pesHeaderSection","passedSearchPts","lookaheadCount","isKeyPacket","startPesHeader","encodedPacket","minByteDistance","startingPesPacket","targetEndPos","nextSection","nextPesPacket","currentPesPacket","relativeStartOffset","relativeEndOffset","relativeOffset","currentEndPos","CHUNK_SIZE","nalHeaderSize","packetStartPos","frameStartFound","lastFirstMacroblockInSlice","posBeforeZero","startCodePos","nalHeaderStart","AVC_SLICE_HEADER_PEEK_SIZE","headerByte0","isSlice","isAccessUnitStart","isAccessUnitDelimiter","isFrameBoundary","startsNewPicture","headerBytes","firstMacroblockInSlice","packetLength","possibleHeaderStartPos","possibleSyncPos","samplesPerFrame","leadingExss","headerBound","nextSubstreamPos","neededBytes","intrinsicDuration","isKey","presentationIndex","first","current","DEFAULT_MIN_READ_POSITION","DEFAULT_MAX_READ_POSITION","cleanup","Source","InputDisposedError","RangedSource","start","SourceRef","PathedSource","rootPath","requestHandler","request","handle","ref","sourceRequestsAreEqual","blobReaderRegistry","BlobSource","blob","ReadOrchestrator","worker","PREFETCH_PROFILES","minReadPosition","maxReadPosition","done","innerStart","innerEnd","prefetchRange","outerStart","outerEnd","innerCacheStartIndex","innerStartEntry","outerCacheStartIndex","contiguousBytesWriteEnd","lastEnd","outerHoles","cappedOuterStart","cappedOuterEnd","cappedInnerStart","cappedInnerEnd","innerHoles","outerHole","cappedStart","cappedEnd","pendingSlice","strictTarget","newWorker","hole","pendingSlices","wasTrueOnce","queuedRead","targetPos","oldestWorker","oldestIndex","clampedStart","clampedEnd","otherWorker","previous","joined","oldestEntry","baseSource","baseSize","processResult","InputFormat","IsobmffInputFormat","Mp4InputFormat","iter","sizeExtensionSlice","QuickTimeInputFormat","MatroskaInputFormat","desiredDocType","varIntSize","WebMInputFormat","MpegTsInputFormat","MP4","QTFF","MATROSKA","WEBM","MPEG_TS","validateInputFormatOptions","__addDisposableResource","env","async","dispose","inner","__disposeResources","SuppressedError","fail","suppressed","message","lastVideoGcErrorLog","lastAudioGcErrorLog","finalizationRegistry","now","VideoSampleResource","VIDEO_SAMPLE_PIXEL_FORMATS","VIDEO_SAMPLE_PIXEL_FORMATS_SET","VideoSample","plane","layout","createDefaultPlaneLayout","colorSpaceInit","VideoSampleColorSpace","transfer","visibleRect","isVideoFrame","validateVideoFrameCopyToOptions","ParseVideoFrameCopyToOptions","destination","env_1","rgbSample","e_1","tempFrame","combinedLayout","destBytes","planeConfigs","getPlaneConfigs","dataPlanes","planeLayout","imageData","planeLayouts","numPlanes","planeIndex","computedLayout","sourceStride","sourceData","sourceOffset","destinationOffset","rowBytes","row","srcSub","needsRgbConversion","needsAlphaConversion","planes","offsets","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","sx","sy","sWidth","sHeight","dx","dy","dWidth","dHeight","centerX","centerY","aspectRatioChange","validateCropRectangle","canvasWidth","canvasHeight","flip","rotatedWidth","rotatedHeight","finalCrop","clampCropRectangle","newWidth","newHeight","sampleWidth","sampleHeight","scale","targetCanvas","targetContext","targetWidth","targetHeight","sourceWidth","sourceHeight","mipLevels","drawWidth","drawHeight","isNew","getTransformationCanvas","levelWidth","levelHeight","videoFrame","cropWidth","cropHeight","originalAspectRatio","transformer","registeredVideoSampleTransformers","newRotation","newFlip","newTimestamp","newDuration","newEncodeOptions","TRANSFORMATION_CANVAS_CACHE_MAX_SIZE","transformationCanvasCache","transformationCanvasCacheNextAge","crop","outerWidth","outerHeight","left","top","layouts","currentOffset","planeWidth","planeHeight","stride","planeSize","yuv","yBytes","uvBytes","subX","subY","hasAlpha","configs","defaultRect","overrideRect","parsedRect","ParseVisibleRect","optLayout","ComputeLayoutAndAllocationSize","sourceRect","VerifyRectOffsetAlignment","minAllocationSize","computedLayouts","endOffsets","sampleBytes","planeEnd","earlierPlaneIndex","earlierLayout","AUDIO_SAMPLE_FORMATS","AudioSampleResource","AudioSample","isAudioData","numberOfFrames","getBytesPerSample","dataBuffer","expectedSize","destFormat","frameOffset","copyFrameCount","isPlanar","formatIsPlanar","optFrameCount","optFrameOffset","srcFormat","numFrames","numChannels","destBytesPerSample","destIsPlanar","requiredSize","destView","writeFn","getWriteFunction","doAudioDataCopyToWebKitWorkaround","readFn","getReadFunction","srcBytesPerSample","srcIsPlanar","uint8Data","getDataPlaneValidated","ch","planeData","srcView","destOffset","srcOffset","startFrame","endFrame","audioBuffer","dataBytes","MAX_FLOAT_COUNT","totalFrames","maxFramesPerChunk","currentRelativeFrame","remainingFrames","framesToCopy","chunkData","audioSample","toInterleavedAudioFormat","audioData","idx","audioSampleToInterleavedFormat","canEncodeVideoMemo","canEncodeAudioMemo","validateVideoEncodingConfig","Quality","validateVideoEncodingAdditionalOptions","bitrateMode","buildVideoEncoderConfigs","fallbackBitrateMode","rateControl","buildConfig","bitrateEstimate","validateAudioEncodingConfig","validateAudioEncodingAdditionalOptions","buildAudioEncoderConfig","QUALITY_LEVELS","quantizerSupport","VIDEO_CODEC_QUANTIZER_SUPPORT","quantizer","quality","computeVideoBitrate","qualityToBitrateFactor","factor","baseBitrate","finalBitrate","prev","curr","pixels","referencePixels","referenceBitrate","codecEfficiencyFactors","buildQuantizerEncodeOptions","canEncodeVideo","frameRate","restOptions","resolvedQuality","resolveQuality","memoized","customVideoEncoders","encoder","frame","canEncodeAudio","encoderConfig","customAudioEncoders","getEncodableAudioCodecs","checkedCodecs","bools","getFirstEncodableVideoCodec","customVideoDecoders","customAudioDecoders","toUlaw","s16","lsb","fromUlaw","u8","decoded","toAlaw","fromAlaw","validatePacketRetrievalOptions","validateTimestamp","maybeFixPacketType","determinedType","EncodedPacketSink","InputTrack","previousPacket","nextPacket","startPacket","endPacket","packetQueue","queueNotEmpty","onQueueNotEmpty","queueDequeue","onQueueDequeue","ended","terminated","outOfBandError","hasOutOfBandError","timestamps","maxQueueSize","MAX_QUEUE_SIZE","DecoderWrapper","onSample","onError","BaseMediaSampleSink","startTimestamp","endTimestamp","sampleQueue","firstSampleQueued","decoderIsFlushed","decoder","packetRetrievalOptions","packetSink","keyPacket","packets","packetResult","closeSamples","timestampIterator","timestampsOfInterest","pushToQueue","retrievalOptions","sampleUses","lastPacket","lastKeyPacket","maxSequenceNumber","decodePackets","flushDecoder","VideoDecoderWrapper","timeResolution","MatchingCustomDecoder","colorHandler","alphaFrame","stack","hasFrameData","sanitizedData","ColorAlphaMerger","alphaHandler","colorFrame","color","finalFrame","mergerWorkerUrl","colorAlphaMergerWorkerCode","poolSize","pending","cpuAlphaBuffer","cpuColorBuffer","chain","alphaFormat","colorIs10","colorIs12","alphaIs10","alphaIs12","mergeInterleavedRgba","mergePlanarYuv","mergeNv12","pixelCount","alphaY","readAlpha","is10","is12","chromaW","chromaH","ySamples","uvSamples","aBytes","outputBytes","aOffset","ySize","uvSize","sourceSize","uOffset","vOffset","uvStart","rOffset","yPlane","samples","validateVideoSinkDecoderOptions","decoderOptions","VideoSampleSink","InputVideoTrack","AudioDecoderWrapper","sampleHandler","sampleTimestamp","preciseTimestamp","PcmAudioDecoderWrapper","inputView","outputBufferSize","outputBuffer","outputView","inputIndex","outputIndex","preciseDuration","AudioSampleSink","InputAudioTrack","requireSync","targetPacketCount","sink","packetCount","totalPacketBytes","query","mergeInputTrackQueries","toValidatedPredicate","tracks","getterName","asyncName","toPixelAspectRatio","metadataRaw","fromMetadata","maxTimestamp","probedPacketCount","ticks","activeTicks","underlyingFrameRate","findUnderlyingFrameRate","unitRate","ticksPerFrame","histogram","minDifference","maxDifference","totalDifference","tickDifference","differenceCount","sortedDifferences","middleA","middleB","medianDifferenceA","medianDifferenceB","cumulativeCount","medianFrameRate","getBestGuessFrameRate","desc","prefer","toValidatedInputTrackQuery","bool","queryA","queryB","resultA","handleResultA","resultB","join","queryInputTracks","matched","filterMatches","resolvedFilterMatches","sortValues","resolvedSortValues","aValues","bValues","maxLength","aValue","bValue","resolution","DELTA_TOLERANCE","MAX_EFFECTIVE_FRAME_SPAN","KNOWN_FRAME_RATES","gaps","gap","sortedGaps","period","iteration","totalTicks","refinedPeriod","inlierCount","uncertainty","periodLo","periodHi","fpsLo","fpsHi","fittedFps","fps","bestKnownError","candidate","periodFraction","simplestFractionBetween","fpsFraction","finalPeriod","finalInlierCount","lo","hi","SPECIAL_FRAME_RATES","COMMON_FRAME_RATES","SPECIAL_TOLERANCE","COMMON_TOLERANCE","best","bestError","DEFAULT_SOURCE_CACHE_GROUP","Input","cacheGroup","cachedEntry","cachedPromiseEntry","sourceRef","minAgeIndex","promiseIndex","Reader","UnsupportedInputFormatError","filtered","firstPackets","tracksDurations","nonNullDurations","videoTracks","audioTracks","primaryVideoTrack","existing","minLength","promisedAttempt","handleAttempt","attempt","filePos","checkIsInRange","bytesToRead","Muxer","timestampInSeconds","timestampInfo","inlineTimestampRegex","formatSubtitleTimestamp","hours","minutes","seconds","milliseconds","IsobmffBoxWriter","writer","text","box","child","boxOffset","u16","i16","u24","u32","i32","u64","i64","fixed_8_8","fixed_16_16","fixed_2_30","variableUnsignedInt","ascii","nullTerminated","matrixToBytes","children","fullBox","ftyp","details","styp","sidx","muxer","referencedSize","earliestPresentationTime","GLOBAL_TIMESCALE","intoTimescale","mdat","reserveLargeSize","free","moov","mvhd","trak","mvex","udta","creationTime","trackDatas","presentationSpan","nextTrackId","needsU64","u32OrU64","trackMetadata","getTrackMetadata","needsEditList","tkhd","edts","mdia","durationInGlobalTimescale","alternateGroup","startOffset","mediaDuration","needs64Bits","i32OrI64","mdhd","hdlr","TRACK_TYPE_TO_COMPONENT_SUBTYPE","TRACK_TYPE_TO_HANDLER_NAME","minf","localDuration","getLanguageCodeInt","hasComponentType","manufacturer","TRACK_TYPE_TO_HEADER_BOX","dinf","stbl","vmhd","smhd","nmhd","dref","needsCtts","stsd","stts","ctts","cslg","stsc","stsz","stco","stss","sampleDescription","videoSampleDescription","videoCodecToBoxName","boxName","audioCodecToBoxName","soundSampleDescription","subtitleSampleDescription","SUBTITLE_CODEC_TO_BOX_NAME","compressionType","VIDEO_CODEC_TO_CONFIGURATION_BOX","pasp","colr","btrt","avcC","hvcC","vpcC","av1C","sampleSizeInBits","isPcmCodec","compressionId","audioCodecToConfigurationBox","esds","wave","frma","enda","dOps","dfLa","pcmC","dac3","dec3","totalBits","ddts","SUBTITLE_CODEC_TO_CONFIGURATION_BOX","vttC","keySamples","acc","leastDecodeToDisplayDelta","greatestDecodeToDisplayDelta","compositionStartTime","compositionEndTime","compositionToDtsShift","trex","moof","mfhd","traf","fragmentSampleFlags","byte4","sampleIsDifferenceSample","tfhd","tfdt","trun","tfFlags","referenceSample","referenceSampleInfo","allSampleDurations","allSampleSizes","allSampleFlags","allSampleCompositionTimeOffsets","uniqueSampleDurations","uniqueSampleSizes","uniqueSampleFlags","uniqueSampleCompositionTimeOffsets","mfra","tfra","mfro","vtte","vttc","payload","identifier","settings","sourceId","vtta","notes","boxes","metadataFormat","metaBox","metaMdir","metaMdta","addQuickTimeMetadataTagBoxes","metadataTagStringBoxShort","encoded","DATA_BOX_MIME_TYPE_MAP","generateMetadataPairs","isMdta","pairs","dataStringBoxLong","pair","fullCodecString","Writer","isMonotonic","newPos","neededSize","newLength","copy","Target","monotonicity","RangedTarget","ARRAY_BUFFER_INITIAL_SIZE","ARRAY_BUFFER_MAX_SIZE","BufferTarget","newBuffer","newBytes","DEFAULT_CHUNK_SIZE","MAX_CHUNKS_AT_ONCE","StreamTarget","writable","paddingBytesNeeded","sorted","lastChunk","relativePosition","toWrite","includesPosition","force","isPartialView","NullTarget","baseTarget","PathedTarget","getTarget","TIMESTAMP_OFFSET","timeInSeconds","timescale","minTimestamp","maxEndTimestamp","IsobmffMuxer","MovOutputFormat","CmafOutputFormat","release","initTarget","initWriter","holdsAvc","boxWriter","meta","existingTrackData","requiresAnnexBTransformation","decoderConfigurationRecord","displayAspectWidth","displayAspectHeight","hasAlphaChannel","newTrackData","requiresAdtsStripping","adtsFrame","internalSample","headerLength","paddedDuration","deltaInTimescale","samplesNeeded","paddingSample","cue","sortedTimestamps","sampleStart","sampleEnd","body","containsTimestamp","nextSample","totalDuration","durationInTimescale","lastTableEntry","entryBefore","lastCompositionTimeOffsetTableEntry","maximumPacketCount","beginNewChunk","currentChunkDuration","keyFrameQueuedEverywhere","otherTrackData","firstQueuedSample","isFinalCall","trackWithMinTimestamp","flushWriter","movieBox","stypSize","sidxSize","tracksInFragment","fragmentNumber","moofBox","mdatStartPos","fragmentStartTimestamp","mdatSize","needsLargeMdatSize","newMoofBox","mdatBox","moovBox","reservedSize","firstTrack","span","totalBytes","windowStart","windowBytes","maxWindowBytes","movieBoxSize","currentChunkPos","mfraBox","mfraBoxSize","mdatPos","remainingSpace","AudioResampler","sourceNum","targetNum","sourceFrameIndex","targetChannelIndex","baseIdx","requiredSamples","overflowFrames","sourceDataSize","sourceView","inputStartTime","inputEndTime","outputStartFrame","outputEndFrame","outputFrame","bufferFrameIndex","sourcePosition","sourceLowerFrame","sourceUpperFrame","fraction","targetChannel","lowerSample","upperSample","outputSample","samplesWritten","outputData","MediaSource","forceClose","connectedTrack","VideoSource","maybeEnsureIsKeyPacket","EncodedVideoPacketSource","VideoEncoderWrapper","encodingConfig","videoSample","shouldClose","encodeOptions","originalSample","sizeChangeBehavior","isSizeChange","appliedFit","transformed","originalEndTimestamp","alignedTimestamp","samplesToEncode","processed","mappedSamples","sampleToEncode","keyFrameInterval","multipleOfKeyFrameInterval","mergedEncodeOptions","finalEncodeOptions","clonedSample","preciseTimingIndex","existingEntry","ColorAlphaSplitter","frameDifference","selected","MatchingCustomEncoder","candidateConfig","firstConfig","rateControls","detectAvcChunkTimestampShift","colorChunkQueue","nullAlphaChunkQueue","encodedAlphaChunkCount","alphaEncoderQueue","handleError","colorChunk","alphaChunk","alphaData","parsed","microsecondTimestamp","actualType","alignedEnd","avcChunkTimestampShiftPromise","chunkTimestamp","splitterWorkerUrl","sourceFrame","colorAlphaSplitterWorkerCode","cpuSourceBuffer","split","splitInterleavedRgba","splitPlanarYuvA","alphaSize","alphaBuffer","alphaInit","colorBytes","colorFormat","alphaChromaW","alphaChromaH","alphaUvSamples","alphaUvBytes","aPlaneStart","uvOffset","neutralChroma","VideoSampleSource","AudioSource","EncodedAudioPacketSource","AudioEncoderWrapper","newSample","sampleDiff","fillSample","outputs","outputSize","isS32","readFormat","allocationSize","values","supported","needsDescriptionOverwrite","int16","AudioSampleSource","SubtitleSource","OutputFormat","IsobmffOutputFormat","Mp4OutputFormat","ALL_TRACK_TYPES","OutputTrack","thisGroups","otherGroups","aGroup","bGroup","OutputVideoTrack","OutputAudioTrack","OutputSubtitleTrack","OutputTrackGroup","validateBaseTrackMetadata","group","Output","errorMessage","rootTargetResult","handleResult","metadataCopy","supportedTrackCounts","presentTracksOfThisType","maxCount","maxTotalCount","supportedVideoCodecs","supportedAudioCodecs","supportedSubtitleCodecs","minCount","totalMinCount","releasePromise","promises","rootWriter","validateVideoOptions","videoOptions","validateAudioOptions","audioOptions","FALLBACK_NUMBER_OF_CHANNELS","FALLBACK_SAMPLE_RATE","Conversion","conversion","TrackSynchronizer","composable","inputFormat","trackMode","primaryAudioTrack","outputTrackCounts","nVideo","nAudio","filteredTracks","filteredTrackOptions","trackOptions","returnedTrackOptions","discardOptions","discardOption","nonDiscardOptions","option","outputTrackId","trackA","trackB","ownGroupA","ownGroupB","inputTags","outputTags","inputAndOutputFormatMatch","warnElements","unintentionallyDiscardedTracks","elements","encodabilityIsTheProblem","codecs","supportedCodecs","uniqueCodecs","ConversionCanceledError","onPause","pump","durationPromises","isDone","sourceCodec","videoSource","innateRotation","innateFlip","totalRotation","totalFlip","outputTrackRotation","outputTrackFlip","outputTrackMatrix","canUseRotationMetadata","squarePixelWidth","squarePixelHeight","originalWidth","originalHeight","videoCodecs","needsTranscode","copyStartPacket","effectiveStartTimestamp","correction","encodableCodec","needsRerender","tempOutput","tempSource","lastSampleTimestamp","sample_1","env_2","clampedStartTimestamp","clampedEndTimestamp","e_2","found","lookahead","packetStartTimestamp","packetEndTimestamp","modifiedPacket","ownGroup","videoTrackLanguageCode","trackName","trackDisposition","averageBitrate","canBeTransparent","audioSource","originalNumberOfChannels","originalSampleRate","audioCodecs","hasDecoderWarmup","codecOfChoice","encodableCodecs","nonPcmCodec","paddingLengthInSamples","sample_2","env_3","finalSampleLet","trimmedSample","finalSample","env_4","silentSample","e_3","e_4","packetTimestamp","audioTrackLanguageCode","getLastSampleTimestamp","newProgress","MAX_TIMESTAMP_GAP","currentValue","newMin","COMPLIANT_CODECS","BITRATE_SAMPLE_PACKETS","convertVideo","withinLimits","alreadyCompliant","dims","fitWithin","stats","videoBitrate","resolveBitrate","BlobPartsSink","streamTarget","reasons","outBlob","note","srcW","srcH","maxW","maxH","scaleW","scaleH","evenFloor","sourceBitrate","estimated","fallbackBitrate","rate","pixelsPerSecond","blobOf","covered","patch","kept"],"mappings":"AAAA,IAAIA;AAEJ,SAASC,GAAmBC,GAAKC,GAAK;AAClC,SAAAD,IAAMA,MAAQ,GACPE,GAAWF,GAAKC,CAAG;AAC9B;AAEA,IAAIE,KAA0B;AAC9B,SAASC,KAAuB;AAC5B,UAAID,OAA4B,QAAQA,GAAwB,eAAe,OAC3EA,KAA0B,IAAI,WAAWL,GAAK,OAAO,MAAM,IAExDK;AACX;AAEA,SAASE,GAAkBC,GAAKC,GAAQC,GAAS;AAC7C,MAAIA,MAAY,QAAW;AACvB,UAAMC,IAAMC,GAAkB,OAAOJ,CAAG,GAClCN,IAAMO,EAAOE,EAAI,QAAQ,CAAC,MAAM;AACtC,WAAAL,GAAoB,EAAG,SAASJ,GAAKA,IAAMS,EAAI,MAAM,EAAE,IAAIA,CAAG,GAC9DE,KA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