diff --git a/README.md b/README.md index beca2ed74da0c5a2d25c6f78e9df7f4cf28e364f..385e70a345e848cd938e9dae3c9a2947c9986e6e 100644 --- a/README.md +++ b/README.md @@ -147,8 +147,8 @@ python shouhouzi/tools/subset_font.py # 重新做字 | # | 阶段 | 状态 | |---|------|------| | E1 | 写计划(本节)+ 作品导航首页 | ✅ 完成 | -| E2 | 史实核对 + 真实 ETH 价格数据入库 + 旁白文案(含画面同步标记) | ⏳ | -| E3 | TTS 配音(逐词时间戳)→ 自动解析画面同步点 | ⏳ | +| E2 | 史实核对(众筹、ETF 首日、各升级时间、Glamsterdam 测试网)+ 真实 ETH 日线入库(2015-08 → 2026-10,1361 点)+ 13 章 63 句文案 | ✅ 完成 | +| E3 | TTS 配音(晓晓·纪录片声线,逐词时间戳)→ 自动解析 120+ 个画面同步点,语音约 357 秒 | ✅ 完成 | | E4 | 渲染引擎:3D 投影、发光合成、连续镜头系统、响应式构图(横/竖) | ⏳ | | E5 | 13 个章节的分镜动画 | ⏳ | | E6 | 音频:Web Worker 内纯 DSP 合成配乐与音效 + 卷积混响 + 母带处理 | ⏳ | diff --git a/ethereum/audio/burn-00.mp3 b/ethereum/audio/burn-00.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..44b1a3205dfa91d24534d8bdf3ce8c08abc6ada4 Binary files /dev/null and b/ethereum/audio/burn-00.mp3 differ diff --git a/ethereum/audio/burn-00.mp3.json b/ethereum/audio/burn-00.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..d178921dc58e87a5544d16aebd0ecb6542751e54 --- /dev/null +++ b/ethereum/audio/burn-00.mp3.json @@ -0,0 +1 @@ +{"text": "2021年,以太坊迎来了属于自己的高光时刻。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["2021", 0.098541, 0.703875], ["年", 0.802416, 0.327666], ["以", 1.372833, 0.121375], ["太坊", 1.506291, 0.521833], ["迎来", 2.052416, 0.339791], ["了", 2.39225, 0.072833], ["属于自己", 2.489333, 0.594666], ["的", 3.084, 0.084958], ["高光", 3.193208, 0.339791], ["时刻", 3.545125, 0.497583]]} \ No newline at end of file diff --git a/ethereum/audio/burn-01.mp3 b/ethereum/audio/burn-01.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..575f2f8875d931e1b876d2932b504f31dca8ee5d Binary files /dev/null and b/ethereum/audio/burn-01.mp3 differ diff --git a/ethereum/audio/burn-01.mp3.json b/ethereum/audio/burn-01.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..c5760fb612da664e748dee12732507c81b0dc3ed --- /dev/null +++ b/ethereum/audio/burn-01.mp3.json @@ -0,0 +1 @@ +{"text": "3月,数字艺术家 Beeple 的一件NFT 作品,在佳士得拍出了约6900万美元。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["3月", 0.098541, 0.534], ["数字", 0.972333, 0.29125], ["艺术家", 1.275708, 0.594666], ["Beeple", 1.979625, 0.339791], ["的", 2.319416, 0.084958], ["一", 2.4165, 0.15775], ["件", 2.574291, 0.29125], ["NFT", 2.962625, 0.631083], ["作品", 3.605833, 0.473291], ["在", 4.394666, 0.182041], ["佳士", 4.588833, 0.327666], ["得", 4.9165, 0.267], ["拍出", 5.20775, 0.351958], ["了", 5.559708, 0.109208], ["约", 5.693208, 0.15775], ["6900万", 5.863125, 0.898041], ["美元", 6.773291, 0.449041]]} \ No newline at end of file diff --git a/ethereum/audio/burn-02.mp3 b/ethereum/audio/burn-02.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..468e6ae1bbfff7880ca474fd0e93bdd9691e9a28 Binary files /dev/null and b/ethereum/audio/burn-02.mp3 differ diff --git a/ethereum/audio/burn-02.mp3.json b/ethereum/audio/burn-02.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..c3aa234c691eecaa73e2dc40b49886c927cddf8d --- /dev/null +++ b/ethereum/audio/burn-02.mp3.json @@ -0,0 +1 @@ +{"text": "8月,伦敦升级上线。其中的 EIP-1559,让每笔交易的基础手续费被直接燃烧销毁。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["8月", 0.098541, 0.497583], ["伦敦", 0.87525, 0.351958], ["升级", 1.251458, 0.364083], ["上线", 1.627666, 0.521833], ["其中", 2.706291, 0.4005], ["的", 3.106791, 0.182041], ["EIP", 3.300958, 0.606791], ["1559", 4.004875, 0.8252489], ["让", 5.097083, 0.145625], ["每", 5.254875, 0.182], ["笔", 5.436875, 0.15775], ["交易", 5.606791, 0.315541], ["的", 5.922333, 0.109208], ["基础", 6.055833, 0.303416], ["手续", 6.371375, 0.364041], ["费", 6.735416, 0.267], ["被", 7.0995, 0.169916], ["直接", 7.281541, 0.351958], ["燃烧", 7.645625, 0.339791], ["销毁", 7.997583, 0.509708]]} \ No newline at end of file diff --git a/ethereum/audio/burn-03.mp3 b/ethereum/audio/burn-03.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..32f4f2a3cf8a7da14317f47f6cdf38a17fd5b942 Binary files /dev/null and b/ethereum/audio/burn-03.mp3 differ diff --git a/ethereum/audio/burn-03.mp3.json b/ethereum/audio/burn-03.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..cf6b89fa2373a2e0bfa11bdf810ffc5dc409f660 --- /dev/null +++ b/ethereum/audio/burn-03.mp3.json @@ -0,0 +1 @@ +{"text": "以太币第一次有了一股持续的通缩力量。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["以", 0.098541, 0.145625], ["太币", 0.256291, 0.436875], ["第一", 0.717458, 0.279125], ["次", 0.996583, 0.267], ["有", 1.287875, 0.15775], ["了", 1.445625, 0.072833], ["一", 1.530583, 0.1335], ["股", 1.664083, 0.169916], ["持续", 1.85825, 0.388333], ["的", 2.246583, 0.084958], ["通缩", 2.355833, 0.364083], ["力量", 2.732041, 0.42475]]} \ No newline at end of file diff --git a/ethereum/audio/burn-04.mp3 b/ethereum/audio/burn-04.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..d2e1b74668681cd2726bb319f4e1dc06dc8af8ae Binary files /dev/null and b/ethereum/audio/burn-04.mp3 differ diff --git a/ethereum/audio/burn-04.mp3.json b/ethereum/audio/burn-04.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..76061325e3bfcaff0b426f758ed94c099b83b63a --- /dev/null +++ b/ethereum/audio/burn-04.mp3.json @@ -0,0 +1 @@ +{"text": "11月,以太币涨到4700多美元,创下当时的历史新高。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["11月", 0.098541, 0.679625], ["以", 1.057291, 0.1335], ["太币", 1.202916, 0.461166], ["涨", 1.688333, 0.194166], ["到", 1.882541, 0.194166], ["4700", 2.100958, 0.740291], ["多", 2.853416, 0.121375], ["美元", 2.986875, 0.485416], ["创下", 3.678625, 0.412625], ["当时", 4.115541, 0.339791], ["的", 4.455333, 0.097083], ["历史", 4.576708, 0.254875], ["新高", 4.843708, 0.497583]]} \ No newline at end of file diff --git a/ethereum/audio/dao-00.mp3 b/ethereum/audio/dao-00.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..7cd0dd49297839fa992271b2d114e1af27e0b3e2 Binary files /dev/null and b/ethereum/audio/dao-00.mp3 differ diff --git a/ethereum/audio/dao-00.mp3.json b/ethereum/audio/dao-00.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..572d6f94fbb3ae6d81d39f99a222d9f51ce983cc --- /dev/null +++ b/ethereum/audio/dao-00.mp3.json @@ -0,0 +1 @@ +{"text": "2016年,一个叫The DAO 的项目,在以太坊上募集了价值约1.5亿美元的以太币。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["2016", 0.098541, 0.667458], ["年", 0.766, 0.327666], ["一个", 1.312125, 0.230583], ["叫", 1.554875, 0.218458], ["The", 1.797583, 0.097083], ["DAO", 1.906791, 0.206291], ["的", 2.113125, 0.084958], ["项目", 2.210208, 0.461166], ["在", 3.011166, 0.182041], ["以", 3.193208, 0.084958], ["太坊", 3.290291, 0.4005], ["上", 3.690791, 0.303416], ["募集", 4.09125, 0.279125], ["了", 4.370375, 0.084958], ["价值", 4.467458, 0.473291], ["约", 4.965041, 0.182041], ["1.5亿", 5.159208, 0.655333], ["美元", 5.826708, 0.327666], ["的", 6.154375, 0.084958], ["以", 6.263583, 0.109208], ["太币", 6.384958, 0.473291]]} \ No newline at end of file diff --git a/ethereum/audio/dao-01.mp3 b/ethereum/audio/dao-01.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..9f5221ca7332d1bf985ca067114b6354e6f8ff98 Binary files /dev/null and b/ethereum/audio/dao-01.mp3 differ diff --git a/ethereum/audio/dao-01.mp3.json b/ethereum/audio/dao-01.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..68c6c3b1beb39c86a3c76ac9c2ce00b3b1542cb5 --- /dev/null +++ b/ethereum/audio/dao-01.mp3.json @@ -0,0 +1 @@ +{"text": "它想做一个没有老板、完全由代码管理的投资基金。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["它", 0.098541, 0.15775], ["想", 0.256291, 0.206291], ["做", 0.47475, 0.145625], ["一个", 0.620375, 0.194166], ["没有", 0.838833, 0.242708], ["老板", 1.093708, 0.485416], ["完全", 1.870375, 0.4005], ["由", 2.283, 0.182041], ["代码", 2.489333, 0.303416], ["管理", 2.804875, 0.327666], ["的", 3.132541, 0.084958], ["投资基金", 3.24175, 0.788833]]} \ No newline at end of file diff --git a/ethereum/audio/dao-02.mp3 b/ethereum/audio/dao-02.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..1b0394b419a8664bcf277d9f8f0e5c0908c075f8 Binary files /dev/null and b/ethereum/audio/dao-02.mp3 differ diff --git a/ethereum/audio/dao-02.mp3.json b/ethereum/audio/dao-02.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..f7573169e60c585d8d32c2edf331b61e73bcccd8 --- /dev/null +++ b/ethereum/audio/dao-02.mp3.json @@ -0,0 +1 @@ +{"text": "可是6月,攻击者利用合约里的一个漏洞,转走了约360万枚以太币。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["可是", 0.098541, 0.267], ["6月", 0.377666, 0.485416], ["攻击者", 1.1665, 0.618916], ["利用", 1.809708, 0.279125], ["合约", 2.100958, 0.42475], ["里", 2.525708, 0.109208], ["的", 2.634958, 0.072833], ["一个", 2.732041, 0.194166], ["漏洞", 2.938333, 0.436875], ["转走", 3.64225, 0.388333], ["了", 4.030583, 0.109208], ["约", 4.164083, 0.182041], ["360万", 4.35825, 0.910207], ["枚", 5.268458, 0.145625], ["以", 5.426208, 0.109208], ["太币", 5.547583, 0.485416]]} \ No newline at end of file diff --git a/ethereum/audio/dao-03.mp3 b/ethereum/audio/dao-03.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..e4eb675263bdf85c06a2e4edfc94672722dd1918 Binary files /dev/null and b/ethereum/audio/dao-03.mp3 differ diff --git a/ethereum/audio/dao-03.mp3.json b/ethereum/audio/dao-03.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..57c63febb95644ff669c50fad7d9044faedc613f --- /dev/null +++ b/ethereum/audio/dao-03.mp3.json @@ -0,0 +1 @@ +{"text": "社区陷入激烈争论:代码即法律,还是把钱追回来?", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["社区", 0.098541, 0.485416], ["陷入", 0.596125, 0.376208], ["激烈", 0.996583, 0.303416], ["争论", 1.312125, 0.42475], ["代码", 2.040291, 0.339791], ["即", 2.404375, 0.169916], ["法律", 2.586416, 0.485416], ["还是", 3.266, 0.242708], ["把", 3.520875, 0.1335], ["钱", 3.654375, 0.230583], ["追", 3.909208, 0.182041], ["回来", 4.09125, 0.388333]]} \ No newline at end of file diff --git a/ethereum/audio/dao-04.mp3 b/ethereum/audio/dao-04.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..a4d7fad86bcc14843e60640f83ed57a3db7938cc Binary files /dev/null and b/ethereum/audio/dao-04.mp3 differ diff --git a/ethereum/audio/dao-04.mp3.json b/ethereum/audio/dao-04.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..ec9ac5cd29c675ecb3b686f4f48603fd893c3051 --- /dev/null +++ b/ethereum/audio/dao-04.mp3.json @@ -0,0 +1 @@ +{"text": "7月20日,以太坊执行硬分叉,让被盗资金回到了可以退还的合约里。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["7月20日", 0.098541, 0.885916], ["以", 1.227166, 0.1335], ["太坊", 1.372833, 0.436875], ["执行", 1.834, 0.303416], ["硬", 2.161666, 0.169875], ["分叉", 2.331541, 0.461166], ["让", 3.10825, 0.169916], ["被盗", 3.290291, 0.267], ["资金", 3.569416, 0.473291], ["回到", 4.127666, 0.376208], ["了", 4.503875, 0.084958], ["可以", 4.613125, 0.218458], ["退还", 4.843708, 0.400458], ["的", 5.244166, 0.084958], ["合约", 5.34125, 0.436875], ["里", 5.778166, 0.206291]]} \ No newline at end of file diff --git a/ethereum/audio/dao-05.mp3 b/ethereum/audio/dao-05.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..5dc550022926110a29fc0b0bc33b54800d588cf8 Binary files /dev/null and b/ethereum/audio/dao-05.mp3 differ diff --git a/ethereum/audio/dao-05.mp3.json b/ethereum/audio/dao-05.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..589ac3f84012b5ead1d273b9810aada0c923cc8d --- /dev/null +++ b/ethereum/audio/dao-05.mp3.json @@ -0,0 +1 @@ +{"text": "不同意的人留在了原来的链上,那条链,就是今天的以太坊经典,ETC。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["不", 0.098541, 0.1335], ["同意", 0.232041, 0.364083], ["的", 0.596125, 0.1335], ["人", 0.729625, 0.303416], ["留", 1.130083, 0.169916], ["在", 1.3, 0.182041], ["了", 1.482041, 0.072833], ["原来", 1.579125, 0.315541], ["的", 1.894666, 0.072833], ["链上", 1.979625, 0.497583], ["那", 2.804875, 0.121333], ["条链", 2.926208, 0.521833], ["就", 3.678625, 0.145625], ["是", 3.824291, 0.121375], ["今天", 3.95775, 0.351958], ["的", 4.309708, 0.072833], ["以", 4.406791, 0.109208], ["太坊", 4.528166, 0.364083], ["经典", 4.904375, 0.485416], ["ETC", 5.632541, 0.667458]]} \ No newline at end of file diff --git a/ethereum/audio/defi-00.mp3 b/ethereum/audio/defi-00.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..c469bfb486b76dca113208fef538efbd544d0dca Binary files /dev/null and b/ethereum/audio/defi-00.mp3 differ diff --git a/ethereum/audio/defi-00.mp3.json b/ethereum/audio/defi-00.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..5fcb9e1f93bb472db0882784862828e1bd53eafc --- /dev/null +++ b/ethereum/audio/defi-00.mp3.json @@ -0,0 +1 @@ +{"text": "熊市里,建设者们没有离开。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["熊市", 0.098541, 0.521833], ["里", 0.620375, 0.242708], ["建设者", 1.105833, 0.533958], ["们", 1.639791, 0.121375], ["没有", 1.785416, 0.242708], ["离开", 2.040291, 0.497583]]} \ No newline at end of file diff --git a/ethereum/audio/defi-01.mp3 b/ethereum/audio/defi-01.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..ec2fd952368a018f32e3240709118e7940d79737 Binary files /dev/null and b/ethereum/audio/defi-01.mp3 differ diff --git a/ethereum/audio/defi-01.mp3.json b/ethereum/audio/defi-01.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..d2e7c49d6d68b3ac4b72a7693c2d3328cdb27c2a --- /dev/null +++ b/ethereum/audio/defi-01.mp3.json @@ -0,0 +1 @@ +{"text": "2020年夏天,去中心化金融,DeFi,突然爆发。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["2020", 0.098541, 0.655333], ["年", 0.753875, 0.15775], ["夏天", 0.923791, 0.534], ["去", 1.664083, 0.169916], ["中心化", 1.846125, 0.534], ["金融", 2.39225, 0.473291], ["DeFi", 3.071833, 0.436875], ["突然", 3.702916, 0.351958], ["爆发", 4.067, 0.42475]]} \ No newline at end of file diff --git a/ethereum/audio/defi-02.mp3 b/ethereum/audio/defi-02.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..8b947c62f89f58c8de10858cc1792080593b09a0 Binary files /dev/null and b/ethereum/audio/defi-02.mp3 differ diff --git a/ethereum/audio/defi-02.mp3.json b/ethereum/audio/defi-02.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..e34c6f46e04c27a8b41525fd1791d5c920c45494 --- /dev/null +++ b/ethereum/audio/defi-02.mp3.json @@ -0,0 +1 @@ +{"text": "在 Uniswap 上,不需要交易所就能兑换代币;在借贷协议里,不需要银行就能存款和借款。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["在", 0.098541, 0.230583], ["Uniswap", 0.353416, 0.655333], ["上", 1.00875, 0.279125], ["不", 1.542708, 0.1335], ["需要", 1.676208, 0.267], ["交易所", 1.955333, 0.606791], ["就", 2.659208, 0.145625], ["能", 2.804875, 0.121375], ["兑换", 2.938333, 0.327666], ["代币", 3.266, 0.436875], ["在", 4.054875, 0.182041], ["借贷", 4.249041, 0.279125], ["协议", 4.540291, 0.412625], ["里", 4.952916, 0.218458], ["不", 5.377666, 0.1335], ["需要", 5.511166, 0.267], ["银行", 5.790291, 0.546125], ["就", 6.4335, 0.145625], ["能", 6.579125, 0.121375], ["存款", 6.712625, 0.412625], ["和", 7.1495, 0.121375], ["借款", 7.283, 0.509708]]} \ No newline at end of file diff --git a/ethereum/audio/defi-03.mp3 b/ethereum/audio/defi-03.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..f36e182bd2f5b081c6f359a90d20026c7ba57406 Binary files /dev/null and b/ethereum/audio/defi-03.mp3 differ diff --git a/ethereum/audio/defi-03.mp3.json b/ethereum/audio/defi-03.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..8f2b52a0773b50625b9570f86a8c489e92782907 --- /dev/null +++ b/ethereum/audio/defi-03.mp3.json @@ -0,0 +1 @@ +{"text": "这些协议能像乐高积木一样互相拼接,被称作“货币乐高”。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["这些", 0.098541, 0.339791], ["协议", 0.4505, 0.509708], ["能", 1.057291, 0.145625], ["像", 1.202916, 0.182041], ["乐高积木", 1.409208, 0.643208], ["一样", 2.064583, 0.412625], ["互相", 2.574291, 0.376208], ["拼接", 2.962625, 0.497583], ["被", 3.739333, 0.145625], ["称作", 3.897083, 0.4005], ["货币", 4.321833, 0.339791], ["乐高", 4.673791, 0.461166]]} \ No newline at end of file diff --git a/ethereum/audio/defi-04.mp3 b/ethereum/audio/defi-04.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..00422e46cb65a3df25a86f2e832d21708d049ee2 Binary files /dev/null and b/ethereum/audio/defi-04.mp3 differ diff --git a/ethereum/audio/defi-04.mp3.json b/ethereum/audio/defi-04.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..d2cbb5a9fcc9ef38820fe9f362d553399bb7aa5e --- /dev/null +++ b/ethereum/audio/defi-04.mp3.json @@ -0,0 +1 @@ +{"text": "同年12月1日,信标链上线,权益证明的新引擎,开始在主链旁边试运行。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["同年", 0.098541, 0.42475], ["12月1日", 0.547583, 0.910166], ["信标链", 1.736875, 0.55825], ["上线", 2.295125, 0.509708], ["权益", 3.023291, 0.388333], ["证明", 3.423791, 0.327666], ["的", 3.751458, 0.072833], ["新", 3.848541, 0.194166], ["引擎", 4.042708, 0.521833], ["开始", 4.770875, 0.315541], ["在", 5.086416, 0.182041], ["主链", 5.292708, 0.351958], ["旁边", 5.656791, 0.4005], ["试运行", 6.081541, 0.679625]]} \ No newline at end of file diff --git a/ethereum/audio/end-00.mp3 b/ethereum/audio/end-00.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..33e0cc58606d7634ebefe05296eac116daf7eb37 Binary files /dev/null and b/ethereum/audio/end-00.mp3 differ diff --git a/ethereum/audio/end-00.mp3.json b/ethereum/audio/end-00.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..2845fafd7deb82bafd168e368445a65a3148a15d --- /dev/null +++ b/ethereum/audio/end-00.mp3.json @@ -0,0 +1 @@ +{"text": "从一个19岁年轻人的想法,到一台全球共享的计算机;", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["从", 0.098541, 0.194166], ["一个", 0.304875, 0.194166], ["19岁", 0.523291, 0.5825], ["年轻人", 1.117958, 0.485416], ["的", 1.603416, 0.072833], ["想法", 1.688333, 0.485416], ["到", 2.440791, 0.145625], ["一", 2.598541, 0.1335], ["台", 2.732041, 0.279125], ["全球", 3.035416, 0.388333], ["共享", 3.435916, 0.364083], ["的", 3.8, 0.084958], ["计算机", 3.897083, 0.631083]]} \ No newline at end of file diff --git a/ethereum/audio/end-01.mp3 b/ethereum/audio/end-01.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..da6840560319b9121378027143f9992ba6746fe2 Binary files /dev/null and b/ethereum/audio/end-01.mp3 differ diff --git a/ethereum/audio/end-01.mp3.json b/ethereum/audio/end-01.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..3c7d5152ef11abf7ae08da795ad550df74f61791 --- /dev/null +++ b/ethereum/audio/end-01.mp3.json @@ -0,0 +1 @@ +{"text": "它经历过黑客、分裂、泡沫与寒冬,也完成了最艰难的一次引擎更换。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["它", 0.098541, 0.145625], ["经历", 0.256291, 0.315541], ["过", 0.571833, 0.121375], ["黑客", 0.717458, 0.534], ["分裂", 1.45775, 0.497583], ["泡沫", 2.137375, 0.412625], ["与", 2.574291, 0.097083], ["寒冬", 2.6835, 0.509708], ["也", 3.472333, 0.1335], ["完成", 3.617958, 0.327666], ["了", 3.945625, 0.097083], ["最", 4.067, 0.194166], ["艰难", 4.261166, 0.351958], ["的", 4.613125, 0.072833], ["一次", 4.698041, 0.315541], ["引擎更换", 5.037875, 0.873791]]} \ No newline at end of file diff --git a/ethereum/audio/end-02.mp3 b/ethereum/audio/end-02.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..659459f98ddff69b47d62f0aa2ff77a09f9fdfd1 Binary files /dev/null and b/ethereum/audio/end-02.mp3 differ diff --git a/ethereum/audio/end-02.mp3.json b/ethereum/audio/end-02.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..9a2ab8da98c3f659bc68d1439897a3ed1783285b --- /dev/null +++ b/ethereum/audio/end-02.mp3.json @@ -0,0 +1 @@ +{"text": "以太坊的故事,还远没有写完。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["以", 0.098541, 0.145625], ["太坊", 0.256291, 0.388333], ["的", 0.644666, 0.072833], ["故事", 0.729625, 0.521833], ["还", 1.45775, 0.145625], ["远", 1.603416, 0.169916], ["没有", 1.785416, 0.206291], ["写完", 2.003875, 0.509708]]} \ No newline at end of file diff --git a/ethereum/audio/end-03.mp3 b/ethereum/audio/end-03.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..b30156d6e487701bc8cc598f9b1fbc481e86d37b Binary files /dev/null and b/ethereum/audio/end-03.mp3 differ diff --git a/ethereum/audio/end-03.mp3.json b/ethereum/audio/end-03.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..026495fc249a6a1a8eb744c0aca14184dfbc8341 --- /dev/null +++ b/ethereum/audio/end-03.mp3.json @@ -0,0 +1 @@ +{"text": "你觉得下一个十年,它会走向哪里?欢迎在评论区聊聊。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["你", 0.098541, 0.169916], ["觉得", 0.268458, 0.206291], ["下", 0.499041, 0.218416], ["一个", 0.717458, 0.169916], ["十", 0.8995, 0.242708], ["年", 1.14225, 0.303416], ["它", 1.639791, 0.145625], ["会", 1.785416, 0.145625], ["走向", 1.943208, 0.351958], ["哪里", 2.307291, 0.449041], ["欢迎", 3.300958, 0.42475], ["在", 3.725708, 0.15775], ["评论区", 3.90775, 0.497583], ["聊聊", 4.417458, 0.473291]]} \ No newline at end of file diff --git a/ethereum/audio/end-04.mp3 b/ethereum/audio/end-04.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..f4dcb6a448658e6fdf227cdeef6d44286029909b Binary files /dev/null and b/ethereum/audio/end-04.mp3 differ diff --git a/ethereum/audio/end-04.mp3.json b/ethereum/audio/end-04.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..76ac362f0a7fb33710a61d9ffb0e75078ef18be0 --- /dev/null +++ b/ethereum/audio/end-04.mp3.json @@ -0,0 +1 @@ +{"text": "本视频仅作科普,不构成任何投资建议。我们下期见。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["本", 0.098541, 0.169916], ["视频", 0.268458, 0.497583], ["仅", 0.790291, 0.194166], ["作", 0.984458, 0.1335], ["科普", 1.130083, 0.509708], ["不", 1.870375, 0.121375], ["构成", 1.99175, 0.364083], ["任何", 2.380083, 0.327666], ["投资", 2.719916, 0.315541], ["建议", 3.047583, 0.473291], ["我们", 4.077666, 0.218458], ["下", 4.30825, 0.218458], ["期见", 4.526708, 0.534]]} \ No newline at end of file diff --git a/ethereum/audio/genesis-00.mp3 b/ethereum/audio/genesis-00.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..e7d635dc8ecf720a475778e2d1f73d05b0ec6196 Binary files /dev/null and b/ethereum/audio/genesis-00.mp3 differ diff --git a/ethereum/audio/genesis-00.mp3.json b/ethereum/audio/genesis-00.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..3031869e0b7f8a8b298707214ec6bb7d0e1ea6e9 --- /dev/null +++ b/ethereum/audio/genesis-00.mp3.json @@ -0,0 +1 @@ +{"text": "2015年7月30日,以太坊主网 Frontier 正式启动。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["2015年7月30日", 0.098541, 1.771875], ["以", 2.12525, 0.15775], ["太坊", 2.295125, 0.376208], ["主网", 2.671375, 0.436875], ["Frontier", 3.205333, 0.594666], ["正式", 3.909208, 0.327666], ["启动", 4.249041, 0.461166]]} \ No newline at end of file diff --git a/ethereum/audio/genesis-01.mp3 b/ethereum/audio/genesis-01.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..c1eafe8f9f0427b8909fa2d148c46e409bdf5f20 Binary files /dev/null and b/ethereum/audio/genesis-01.mp3 differ diff --git a/ethereum/audio/genesis-01.mp3.json b/ethereum/audio/genesis-01.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..ff86b684c10e33eb383faa2710a3f1b4a29eefc6 --- /dev/null +++ b/ethereum/audio/genesis-01.mp3.json @@ -0,0 +1 @@ +{"text": "第0号区块,创世区块诞生。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["第", 0.098541, 0.182041], ["0", 0.280583, 0.169916], ["号", 0.4505, 0.194166], ["区块", 0.656791, 0.461166], ["创世", 1.372833, 0.436875], ["区块", 1.821833, 0.327666], ["诞生", 2.161666, 0.473291]]} \ No newline at end of file diff --git a/ethereum/audio/genesis-02.mp3 b/ethereum/audio/genesis-02.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..2a1093cfaf04523337468e205ecdb63b063d4c43 Binary files /dev/null and b/ethereum/audio/genesis-02.mp3 differ diff --git a/ethereum/audio/genesis-02.mp3.json b/ethereum/audio/genesis-02.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..396c3af138dd9defc943e6b53c2de01a62a2147d --- /dev/null +++ b/ethereum/audio/genesis-02.mp3.json @@ -0,0 +1 @@ +{"text": "从这一刻起,新区块每隔十几秒就产生一个,链条开始生长。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["从", 0.098541, 0.218458], ["这", 0.329125, 0.121375], ["一刻", 0.4505, 0.303375], ["起", 0.753875, 0.303416], ["新", 1.360666, 0.230583], ["区块", 1.59125, 0.351958], ["每", 1.967458, 0.182041], ["隔", 2.1495, 0.169916], ["十几", 2.331541, 0.339791], ["秒", 2.671375, 0.29125], ["就", 2.986875, 0.1335], ["产生", 3.132541, 0.376208], ["一个", 3.520875, 0.388333], ["链条", 4.2005, 0.364083], ["开始", 4.588833, 0.279125], ["生长", 4.880083, 0.521833]]} \ No newline at end of file diff --git a/ethereum/audio/genesis-03.mp3 b/ethereum/audio/genesis-03.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..03540060246620f401eaccb1123654830f39aa42 Binary files /dev/null and b/ethereum/audio/genesis-03.mp3 differ diff --git a/ethereum/audio/genesis-03.mp3.json b/ethereum/audio/genesis-03.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..ebb5b4d241eb09b40ce2a6d6c679891e03251e73 --- /dev/null +++ b/ethereum/audio/genesis-03.mp3.json @@ -0,0 +1 @@ +{"text": "那时候,一枚以太币还不到3美元。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["那时候", 0.098541, 0.631083], ["一", 0.984458, 0.145625], ["枚", 1.130083, 0.303416], ["以", 1.518458, 0.121375], ["太币", 1.651958, 0.509708], ["还", 2.25875, 0.145625], ["不", 2.404375, 0.084958], ["到", 2.489333, 0.1335], ["3美元", 2.647083, 0.667499]]} \ No newline at end of file diff --git a/ethereum/audio/ico-00.mp3 b/ethereum/audio/ico-00.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..10443069bf97ef1185a5f25d2fe55ab40c8af86d Binary files /dev/null and b/ethereum/audio/ico-00.mp3 differ diff --git a/ethereum/audio/ico-00.mp3.json b/ethereum/audio/ico-00.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..0d5f4cb92dc712ed34623af3866c41cf82a68028 --- /dev/null +++ b/ethereum/audio/ico-00.mp3.json @@ -0,0 +1 @@ +{"text": "2014年1月,以太坊在迈阿密的比特币大会上正式亮相。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["2014年1月", 0.098541, 1.3107079], ["以", 1.712625, 0.121375], ["太坊", 1.846125, 0.534], ["在", 2.404375, 0.15775], ["迈阿密", 2.574291, 0.473291], ["的", 3.047583, 0.097083], ["比特币", 3.168916, 0.436875], ["大会", 3.617958, 0.376208], ["上", 3.994166, 0.254875], ["正式", 4.346125, 0.339791], ["亮相", 4.698041, 0.497583]]} \ No newline at end of file diff --git a/ethereum/audio/ico-01.mp3 b/ethereum/audio/ico-01.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..be12081a9845be7343bebb7c5e3c10e2c2bc2b77 Binary files /dev/null and b/ethereum/audio/ico-01.mp3 differ diff --git a/ethereum/audio/ico-01.mp3.json b/ethereum/audio/ico-01.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..2fb1b65822a2e7382ff042d793ff262fb10a7004 --- /dev/null +++ b/ethereum/audio/ico-01.mp3.json @@ -0,0 +1 @@ +{"text": "同年7月22日,以太坊开启公开众筹,持续了六周。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["同年", 0.098541, 0.449041], ["7月22日", 0.571833, 0.95875], ["以", 1.809708, 0.121375], ["太坊", 1.943208, 0.473291], ["开启", 2.440791, 0.339791], ["公开", 2.804875, 0.303416], ["众筹", 3.120375, 0.546125], ["持续", 3.836416, 0.412625], ["了", 4.249041, 0.084958], ["六周", 4.346125, 0.473291]]} \ No newline at end of file diff --git a/ethereum/audio/ico-02.mp3 b/ethereum/audio/ico-02.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..963062109b3227e920022c324cfeb3cdb36ed5b4 Binary files /dev/null and b/ethereum/audio/ico-02.mp3 differ diff --git a/ethereum/audio/ico-02.mp3.json b/ethereum/audio/ico-02.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..604faf2ffa5177e94f3ec5aa9a54242ae9729275 --- /dev/null +++ b/ethereum/audio/ico-02.mp3.json @@ -0,0 +1 @@ +{"text": "每枚以太币,价格大约0.31美元。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["每", 0.098541, 0.182041], ["枚", 0.280583, 0.1335], ["以", 0.426208, 0.084958], ["太币", 0.523291, 0.473291], ["价格", 1.275708, 0.339791], ["大约", 1.627666, 0.412625], ["0.31美元", 2.064583, 1.177166]]} \ No newline at end of file diff --git a/ethereum/audio/ico-03.mp3 b/ethereum/audio/ico-03.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..5d6a872f5f7a3c4f7a783d6d188121f7a4da0619 Binary files /dev/null and b/ethereum/audio/ico-03.mp3 differ diff --git a/ethereum/audio/ico-03.mp3.json b/ethereum/audio/ico-03.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..89d566f2ae7ee8e07eba5461185a8aa6a05d192e --- /dev/null +++ b/ethereum/audio/ico-03.mp3.json @@ -0,0 +1 @@ +{"text": "最终募得约1830万美元,是当时规模最大的众筹项目之一。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["最终", 0.098541, 0.376208], ["募得", 0.486875, 0.436875], ["约", 0.948041, 0.218458], ["1830万", 1.178625, 1.213583], ["美元", 2.39225, 0.461166], ["是", 3.120375, 0.1335], ["当时", 3.266, 0.436875], ["规模", 3.727166, 0.376208], ["最大", 4.115541, 0.400458], ["的", 4.516, 0.121375], ["众筹", 4.661666, 0.327666], ["项目", 5.001458, 0.303416], ["之一", 5.317, 0.436875]]} \ No newline at end of file diff --git a/ethereum/audio/ico-04.mp3 b/ethereum/audio/ico-04.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..ffb52f60368a852f7582386246488b379f18b3c8 Binary files /dev/null and b/ethereum/audio/ico-04.mp3 differ diff --git a/ethereum/audio/ico-04.mp3.json b/ethereum/audio/ico-04.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..1b314fbb6b8f87f2c9a9a334277158649a0263bb --- /dev/null +++ b/ethereum/audio/ico-04.mp3.json @@ -0,0 +1 @@ +{"text": "团队在瑞士成立了以太坊基金会,开始了一年的紧张开发。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["团队", 0.098541, 0.485416], ["在", 0.60825, 0.145625], ["瑞士", 0.766, 0.412625], ["成立", 1.190791, 0.376208], ["了", 1.567, 0.084958], ["以", 1.676208, 0.109208], ["太坊", 1.797583, 0.388333], ["基金会", 2.198041, 0.606791], ["开始", 3.071833, 0.351958], ["了", 3.423791, 0.084958], ["一", 3.533, 0.1335], ["年", 3.6665, 0.194166], ["的", 3.860666, 0.097083], ["紧张", 3.982041, 0.376208], ["开发", 4.370375, 0.473291]]} \ No newline at end of file diff --git a/ethereum/audio/mania-00.mp3 b/ethereum/audio/mania-00.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..2ceb473d5961cb14e42642623483d8c6b03097d8 Binary files /dev/null and b/ethereum/audio/mania-00.mp3 differ diff --git a/ethereum/audio/mania-00.mp3.json b/ethereum/audio/mania-00.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..09e22e5cdd5170a4c9b1f06454ece9be456353ec --- /dev/null +++ b/ethereum/audio/mania-00.mp3.json @@ -0,0 +1 @@ +{"text": "危机过后,一个叫ERC-20的代币标准,让任何人都能在以太坊上轻松发行代币。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["危机", 0.098541, 0.339791], ["过后", 0.4505, 0.473291], ["一个", 1.1665, 0.242708], ["叫", 1.421375, 0.254833], ["ERC", 1.676208, 0.327666], ["20", 2.100958, 0.376208], ["的", 2.477166, 0.084958], ["代币", 2.586416, 0.29125], ["标准", 2.889791, 0.485416], ["让", 3.6665, 0.169916], ["任何", 3.848541, 0.376208], ["人", 4.22475, 0.267], ["都", 4.516, 0.15775], ["能", 4.673791, 0.15775], ["在", 4.831541, 0.145625], ["以", 5.001458, 0.097083], ["太坊", 5.110666, 0.4005], ["上", 5.511166, 0.254875], ["轻松", 5.863125, 0.461166], ["发行", 6.336416, 0.327666], ["代币", 6.676208, 0.42475]]} \ No newline at end of file diff --git a/ethereum/audio/mania-01.mp3 b/ethereum/audio/mania-01.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..1d93b1e23df7336030e1376214c14ba1ceb314aa Binary files /dev/null and b/ethereum/audio/mania-01.mp3 differ diff --git a/ethereum/audio/mania-01.mp3.json b/ethereum/audio/mania-01.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..979acf27f2de48891e12dcb0293c09975f37b51e --- /dev/null +++ b/ethereum/audio/mania-01.mp3.json @@ -0,0 +1 @@ +{"text": "2017年,ICO 狂潮席卷全球,新项目动辄募资数千万美元。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["2017", 0.098541, 0.643208], ["年", 0.74175, 0.327666], ["ICO", 1.3, 0.55825], ["狂潮", 1.870375, 0.42475], ["席卷", 2.319416, 0.351958], ["全球", 2.6835, 0.546125], ["新", 3.472333, 0.206291], ["项目", 3.678625, 0.449041], ["动辄", 4.151958, 0.29125], ["募资", 4.455333, 0.351958], ["数千万", 4.831541, 0.55825], ["美元", 5.401958, 0.449041]]} \ No newline at end of file diff --git a/ethereum/audio/mania-02.mp3 b/ethereum/audio/mania-02.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..3b9e4d4e8857a71d00a1d12cac545cb2d54cbd88 Binary files /dev/null and b/ethereum/audio/mania-02.mp3 differ diff --git a/ethereum/audio/mania-02.mp3.json b/ethereum/audio/mania-02.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..5ca33fc4dcc4c666e3e915add244bec2045685a5 --- /dev/null +++ b/ethereum/audio/mania-02.mp3.json @@ -0,0 +1 @@ +{"text": "那年12月,一款养猫游戏“加密猫”,甚至把整个网络堵得水泄不通。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["那年", 0.098541, 0.339791], ["12月", 0.462625, 0.618916], ["一", 1.384958, 0.145625], ["款", 1.530583, 0.230583], ["养", 1.785416, 0.169916], ["猫", 1.955333, 0.15775], ["游戏", 2.12525, 0.364083], ["加密", 2.513583, 0.303416], ["猫", 2.817, 0.279125], ["甚至", 3.338833, 0.279125], ["把", 3.630083, 0.1335], ["整个", 3.775708, 0.327666], ["网络", 4.115541, 0.436875], ["堵得", 4.576708, 0.267], ["水泄不通", 4.855833, 0.800958]]} \ No newline at end of file diff --git a/ethereum/audio/mania-03.mp3 b/ethereum/audio/mania-03.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..932b08bc1901377c4edca320b56e08f38648da92 Binary files /dev/null and b/ethereum/audio/mania-03.mp3 differ diff --git a/ethereum/audio/mania-03.mp3.json b/ethereum/audio/mania-03.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..e3675fa7ab4964db6582aa0d3a6accea80771b4e --- /dev/null +++ b/ethereum/audio/mania-03.mp3.json @@ -0,0 +1 @@ +{"text": "2018年1月,以太币冲上了1400多美元。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["2018年1月", 0.098541, 1.237834], ["以", 1.615541, 0.1335], ["太币", 1.749041, 0.521833], ["冲", 2.295125, 0.194166], ["上", 2.489333, 0.15775], ["了", 2.647083, 0.072833], ["1400", 2.744166, 0.679625], ["多", 3.435916, 0.1335], ["美元", 3.581541, 0.461166]]} \ No newline at end of file diff --git a/ethereum/audio/mania-04.mp3 b/ethereum/audio/mania-04.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..0b25ed9a89319a3d230d1527f3be74d30a3156ec Binary files /dev/null and b/ethereum/audio/mania-04.mp3 differ diff --git a/ethereum/audio/mania-04.mp3.json b/ethereum/audio/mania-04.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..81d10a7d155128921b86e6cea44faf8f0cf14691 --- /dev/null +++ b/ethereum/audio/mania-04.mp3.json @@ -0,0 +1 @@ +{"text": "但泡沫来得快,去得更快。到年底,它跌到了不足100美元,跌幅超过九成。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["但", 0.098541, 0.15775], ["泡沫", 0.268458, 0.376208], ["来得", 0.668916, 0.242708], ["快", 0.911666, 0.315541], ["去", 1.445625, 0.182041], ["得", 1.627666, 0.084958], ["更", 1.72475, 0.206291], ["快", 1.931083, 0.315541], ["到", 2.79125, 0.182041], ["年底", 2.985416, 0.509708], ["它", 3.762125, 0.145625], ["跌到", 3.90775, 0.315541], ["了", 4.223291, 0.072833], ["不足", 4.320375, 0.230583], ["100美元", 4.563125, 0.837332], ["跌幅", 5.618916, 0.376208], ["超过", 6.019416, 0.327666], ["九成", 6.359208, 0.546125]]} \ No newline at end of file diff --git a/ethereum/audio/merge-00.mp3 b/ethereum/audio/merge-00.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..b25aa8efc2d8a9a5c96d68fa08df70584774e1d7 Binary files /dev/null and b/ethereum/audio/merge-00.mp3 differ diff --git a/ethereum/audio/merge-00.mp3.json b/ethereum/audio/merge-00.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..7bd5309dc68d7f9d418526f2d70b86fbff8fb7a7 --- /dev/null +++ b/ethereum/audio/merge-00.mp3.json @@ -0,0 +1 @@ +{"text": "然而,最难的一步还在后面。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["然而", 0.098541, 0.509708], ["最", 0.887375, 0.230583], ["难", 1.117958, 0.169916], ["的", 1.287875, 0.072833], ["一", 1.384958, 0.097083], ["步", 1.482041, 0.109208], ["还", 1.615541, 0.145625], ["在", 1.761166, 0.121375], ["后面", 1.894666, 0.509708]]} \ No newline at end of file diff --git a/ethereum/audio/merge-01.mp3 b/ethereum/audio/merge-01.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..2eff59e54753d9b24c982f69339d9220cadc8b0a Binary files /dev/null and b/ethereum/audio/merge-01.mp3 differ diff --git a/ethereum/audio/merge-01.mp3.json b/ethereum/audio/merge-01.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..e88e110a9880707d677cf5afcf3d962c7189fd0f --- /dev/null +++ b/ethereum/audio/merge-01.mp3.json @@ -0,0 +1 @@ +{"text": "以太坊要把共识机制,从工作量证明,切换到权益证明。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["以", 0.098541, 0.145625], ["太坊", 0.256291, 0.461166], ["要", 0.74175, 0.145625], ["把", 0.887375, 0.1335], ["共识", 1.045125, 0.339791], ["机制", 1.397083, 0.461166], ["从", 2.12525, 0.206291], ["工作量", 2.355833, 0.461166], ["证明", 2.829125, 0.461166], ["切换", 3.472333, 0.364083], ["到", 3.848541, 0.145625], ["权益", 4.018458, 0.4005], ["证明", 4.431083, 0.461166]]} \ No newline at end of file diff --git a/ethereum/audio/merge-02.mp3 b/ethereum/audio/merge-02.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..9c6ff32bf66f9e1bcec3e5702d3042e4d39f024b Binary files /dev/null and b/ethereum/audio/merge-02.mp3 differ diff --git a/ethereum/audio/merge-02.mp3.json b/ethereum/audio/merge-02.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..baf90e616871b8ac26e8b184866af3ce5c139698 --- /dev/null +++ b/ethereum/audio/merge-02.mp3.json @@ -0,0 +1 @@ +{"text": "这就像给一架正在飞行的飞机,在空中更换引擎。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["这", 0.098541, 0.194166], ["就", 0.292708, 0.121375], ["像", 0.414083, 0.206291], ["给", 0.620375, 0.121375], ["一", 0.753875, 0.1335], ["架", 0.887375, 0.242708], ["正在", 1.154375, 0.315541], ["飞行", 1.482041, 0.339791], ["的", 1.821833, 0.084958], ["飞机", 1.918916, 0.485416], ["在", 2.647083, 0.15775], ["空中", 2.817, 0.412625], ["更换", 3.253875, 0.364083], ["引擎", 3.630083, 0.534]]} \ No newline at end of file diff --git a/ethereum/audio/merge-03.mp3 b/ethereum/audio/merge-03.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..ebbd2e2f61444f210aec3760cc0f7f0f9e020279 Binary files /dev/null and b/ethereum/audio/merge-03.mp3 differ diff --git a/ethereum/audio/merge-03.mp3.json b/ethereum/audio/merge-03.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..ecc00d945096020b873c9f0e56fadf4f30e5d8ed --- /dev/null +++ b/ethereum/audio/merge-03.mp3.json @@ -0,0 +1 @@ +{"text": "2022年9月15日,合并完成。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["2022年9月15日", 0.098541, 1.80825], ["合并", 2.113125, 0.364083], ["完成", 2.489333, 0.485416]]} \ No newline at end of file diff --git a/ethereum/audio/merge-04.mp3 b/ethereum/audio/merge-04.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..30bb1eddc743dc3870565027e410f22cccd554d2 Binary files /dev/null and b/ethereum/audio/merge-04.mp3 differ diff --git a/ethereum/audio/merge-04.mp3.json b/ethereum/audio/merge-04.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..2964ef2e14019760e0a121641938a61fe96a096d --- /dev/null +++ b/ethereum/audio/merge-04.mp3.json @@ -0,0 +1 @@ +{"text": "矿机熄灭,验证者接手。以太坊的能耗,下降了约99.95%。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["矿机", 0.098541, 0.4005], ["熄灭", 0.511166, 0.473291], ["验证", 1.227166, 0.376208], ["者", 1.603416, 0.15775], ["接手", 1.773291, 0.546125], ["以", 2.876208, 0.145625], ["太坊", 3.034, 0.400458], ["的", 3.434458, 0.072833], ["能耗", 3.519416, 0.461166], ["下降", 4.259708, 0.388333], ["了", 4.648041, 0.097083], ["约", 4.769416, 0.1335], ["99.95%", 4.902916, 1.747583]]} \ No newline at end of file diff --git a/ethereum/audio/now-00.mp3 b/ethereum/audio/now-00.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..283115e02d29ba3092be9ffac842c2f43d4781a5 Binary files /dev/null and b/ethereum/audio/now-00.mp3 differ diff --git a/ethereum/audio/now-00.mp3.json b/ethereum/audio/now-00.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..64f69ef7ce1b28ca69df4f35d5ae49543d631186 --- /dev/null +++ b/ethereum/audio/now-00.mp3.json @@ -0,0 +1 @@ +{"text": "而就在今天,2026年10月6日,下一次大升级 Glamsterdam,在 Sepolia 测试网上线。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["而", 0.098541, 0.169916], ["就", 0.280583, 0.145625], ["在", 0.426208, 0.1335], ["今天", 0.571833, 0.497583], ["2026年10月6日", 1.312125, 1.711166], ["下", 3.314583, 0.242708], ["一次", 3.557291, 0.242708], ["大", 3.824291, 0.1335], ["升级", 3.969916, 0.497541], ["Glamsterdam", 4.467458, 0.922333], ["在", 5.632541, 0.206291], ["Sepolia", 5.863125, 0.69175], ["测试网", 6.567, 0.521833], ["上线", 7.088833, 0.485416]]} \ No newline at end of file diff --git a/ethereum/audio/now-01.mp3 b/ethereum/audio/now-01.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..cdea0e40682a7d68d5e127698dd7b11b003cf580 Binary files /dev/null and b/ethereum/audio/now-01.mp3 differ diff --git a/ethereum/audio/now-01.mp3.json b/ethereum/audio/now-01.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..ab87e2f572c99c615db8d3e5b99ed1bcbde76427 --- /dev/null +++ b/ethereum/audio/now-01.mp3.json @@ -0,0 +1 @@ +{"text": "它将带来协议内的提议者与构建者分离,以及区块级访问列表,为主网的下一次扩容铺路。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["它", 0.098541, 0.145625], ["将", 0.244166, 0.15775], ["带来", 0.414083, 0.29125], ["协议", 0.729625, 0.351916], ["内", 1.081541, 0.15775], ["的", 1.239333, 0.084958], ["提议者", 1.348541, 0.655333], ["与", 2.100958, 0.145625], ["构建", 2.25875, 0.364083], ["者", 2.622833, 0.145625], ["分离", 2.780583, 0.497583], ["以及", 3.533, 0.376208], ["区块级", 3.9335, 0.570375], ["访问", 4.528166, 0.327666], ["列表", 4.867958, 0.509708], ["为主网", 5.606791, 0.497583], ["的", 6.104375, 0.072833], ["下", 6.201458, 0.242708], ["一次", 6.444166, 0.303416], ["扩容", 6.771833, 0.339791], ["铺路", 7.123791, 0.436875]]} \ No newline at end of file diff --git a/ethereum/audio/now-02.mp3 b/ethereum/audio/now-02.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..e723d679869b88fa4b49db1f75a79588eda6d23d Binary files /dev/null and b/ethereum/audio/now-02.mp3 differ diff --git a/ethereum/audio/now-02.mp3.json b/ethereum/audio/now-02.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..862db969bdaf23726e8903f21f85e41166e2cc14 --- /dev/null +++ b/ethereum/audio/now-02.mp3.json @@ -0,0 +1 @@ +{"text": "此刻,以太币的价格约为2700美元,距离高点仍有不小的距离。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["此刻", 0.098541, 0.473291], ["以", 0.887375, 0.1335], ["太币", 1.033, 0.376208], ["的", 1.409208, 0.084958], ["价格", 1.506291, 0.546125], ["约", 2.137375, 0.15775], ["为", 2.295125, 0.145625], ["2700美元", 2.465041, 1.177166], ["距离", 3.921375, 0.254875], ["高", 4.188333, 0.206291], ["点", 4.394666, 0.303416], ["仍", 4.795125, 0.182041], ["有", 4.977166, 0.15775], ["不", 5.159208, 0.097083], ["小", 5.256291, 0.206291], ["的", 5.462625, 0.084958], ["距离", 5.559708, 0.449041]]} \ No newline at end of file diff --git a/ethereum/audio/now-03.mp3 b/ethereum/audio/now-03.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..39bd12ab2c7a5cd4baa7f3e458c74de6444bf1c0 Binary files /dev/null and b/ethereum/audio/now-03.mp3 differ diff --git a/ethereum/audio/now-03.mp3.json b/ethereum/audio/now-03.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..289e074f05795996ad6619391b54bc1c3c960f35 --- /dev/null +++ b/ethereum/audio/now-03.mp3.json @@ -0,0 +1 @@ +{"text": "但这条链,依然在一刻不停地出块。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["但", 0.098541, 0.169916], ["这", 0.280583, 0.1335], ["条", 0.414083, 0.230583], ["链", 0.644666, 0.267], ["依然", 1.1665, 0.376208], ["在", 1.542708, 0.15775], ["一刻", 1.72475, 0.279125], ["不停", 2.016, 0.351958], ["地", 2.367958, 0.084958], ["出", 2.465041, 0.182041], ["块", 2.647083, 0.303416]]} \ No newline at end of file diff --git a/ethereum/audio/open-00.mp3 b/ethereum/audio/open-00.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..68531aad1cea383cebcad43029b08941826c4b70 Binary files /dev/null and b/ethereum/audio/open-00.mp3 differ diff --git a/ethereum/audio/open-00.mp3.json b/ethereum/audio/open-00.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..9f76a2550b192e7241031d726863e1f6e09e88da --- /dev/null +++ b/ethereum/audio/open-00.mp3.json @@ -0,0 +1 @@ +{"text": "2013年冬天,一个19岁的年轻人,写下了一份白皮书。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["2013", 0.098541, 0.655333], ["年", 0.753875, 0.182041], ["冬天", 0.948041, 0.509708], ["一个", 1.749041, 0.194166], ["19岁", 1.967458, 0.546124], ["的", 2.513583, 0.084958], ["年轻人", 2.610666, 0.667458], ["写", 3.496583, 0.194166], ["下", 3.690791, 0.182041], ["了", 3.872833, 0.060666], ["一", 3.945625, 0.1335], ["份", 4.079125, 0.194166], ["白皮书", 4.297583, 0.667458]]} \ No newline at end of file diff --git a/ethereum/audio/open-01.mp3 b/ethereum/audio/open-01.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..9609b37452b5ca4b1baf161fdd7db2b7a7203cbd Binary files /dev/null and b/ethereum/audio/open-01.mp3 differ diff --git a/ethereum/audio/open-01.mp3.json b/ethereum/audio/open-01.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..6816aafbe463ba459e4f1a3634d298b4b6f5bf0e --- /dev/null +++ b/ethereum/audio/open-01.mp3.json @@ -0,0 +1 @@ +{"text": "他叫维塔利克·布特林。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["他", 0.098541, 0.145625], ["叫", 0.244166, 0.182041], ["维塔利克", 0.4505, 0.813125], ["布特林", 1.494166, 0.667458]]} \ No newline at end of file diff --git a/ethereum/audio/open-02.mp3 b/ethereum/audio/open-02.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..228af03440e58292f45cbf8090842369b48f2d6e Binary files /dev/null and b/ethereum/audio/open-02.mp3 differ diff --git a/ethereum/audio/open-02.mp3.json b/ethereum/audio/open-02.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..29494c71278578f1b2ddffd58eae51620d832a0a --- /dev/null +++ b/ethereum/audio/open-02.mp3.json @@ -0,0 +1 @@ +{"text": "那时没有人想到,这份文件会长成一个承载数千亿美元价值的网络。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["那时", 0.098541, 0.327666], ["没有", 0.4505, 0.242708], ["人", 0.693208, 0.121375], ["想到", 0.826708, 0.473291], ["这", 1.651958, 0.169875], ["份", 1.821833, 0.145625], ["文件", 1.979625, 0.521833], ["会长", 2.586416, 0.339791], ["成", 2.926208, 0.145625], ["一个", 3.084, 0.4005], ["承载", 3.581541, 0.376208], ["数千亿", 3.982041, 0.546125], ["美元", 4.540291, 0.327666], ["价值", 4.880083, 0.327666], ["的", 5.20775, 0.084958], ["网络", 5.304875, 0.473291]]} \ No newline at end of file diff --git a/ethereum/audio/open-03.mp3 b/ethereum/audio/open-03.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..ce3bf218373cf6daf5dc365c098e89fed37486f4 Binary files /dev/null and b/ethereum/audio/open-03.mp3 differ diff --git a/ethereum/audio/open-03.mp3.json b/ethereum/audio/open-03.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..2128befef59e3d8e2094ccf102457388fd4f0e7c --- /dev/null +++ b/ethereum/audio/open-03.mp3.json @@ -0,0 +1 @@ +{"text": "接下来的六分钟,我们一起走完以太坊的十三年。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["接下来", 0.098541, 0.473291], ["的", 0.571833, 0.072833], ["六分钟", 0.656791, 0.606791], ["我们一起走", 1.554875, 0.946583], ["完", 2.598541, 0.182041], ["以", 2.780583, 0.097083], ["太坊", 2.889791, 0.388333], ["的", 3.278166, 0.072833], ["十三", 3.37525, 0.42475], ["年", 3.8, 0.29125]]} \ No newline at end of file diff --git a/ethereum/audio/origin-00.mp3 b/ethereum/audio/origin-00.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..94d9de528731274dd2c8cce7f97adb04dcaa2abf Binary files /dev/null and b/ethereum/audio/origin-00.mp3 differ diff --git a/ethereum/audio/origin-00.mp3.json b/ethereum/audio/origin-00.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..57e19a11e9ecd2ff819c706276a175a680b8ccc7 --- /dev/null +++ b/ethereum/audio/origin-00.mp3.json @@ -0,0 +1 @@ +{"text": "故事要从比特币说起。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["故事", 0.098541, 0.315541], ["要", 0.426208, 0.169916], ["从", 0.596125, 0.206291], ["比特币", 0.826708, 0.497583], ["说起", 1.324291, 0.509708]]} \ No newline at end of file diff --git a/ethereum/audio/origin-01.mp3 b/ethereum/audio/origin-01.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..cb7941f42aec6fdc10c44c9c285ef04853c3cb78 Binary files /dev/null and b/ethereum/audio/origin-01.mp3 differ diff --git a/ethereum/audio/origin-01.mp3.json b/ethereum/audio/origin-01.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..b19ac8a1b335e174e6c853ea40a7bdf7e33c1b43 --- /dev/null +++ b/ethereum/audio/origin-01.mp3.json @@ -0,0 +1 @@ +{"text": "比特币很伟大,但它更像一台计算器:功能简单,只专注于记账和转账。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["比特币", 0.098541, 0.521833], ["很", 0.644666, 0.182041], ["伟大", 0.826708, 0.449041], ["但", 1.603416, 0.145625], ["它", 1.749041, 0.121375], ["更", 1.882541, 0.182041], ["像", 2.064583, 0.182041], ["一", 2.25875, 0.109208], ["台", 2.367958, 0.182041], ["计算器", 2.574291, 0.643208], ["功能", 3.472333, 0.327666], ["简单", 3.812125, 0.485416], ["只", 4.503875, 0.169916], ["专注", 4.673791, 0.339791], ["于", 5.013583, 0.194166], ["记账", 5.232041, 0.4005], ["和", 5.656791, 0.121375], ["转账", 5.790291, 0.497583]]} \ No newline at end of file diff --git a/ethereum/audio/origin-02.mp3 b/ethereum/audio/origin-02.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..4dae2f9ad36ae3510ae5e15c6fb4ae90494e7904 Binary files /dev/null and b/ethereum/audio/origin-02.mp3 differ diff --git a/ethereum/audio/origin-02.mp3.json b/ethereum/audio/origin-02.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..293990a4fb34847e0e28d94223f9b2c967ce8223 --- /dev/null +++ b/ethereum/audio/origin-02.mp3.json @@ -0,0 +1 @@ +{"text": "维塔利克想的是:如果区块链能运行任何程序呢?", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["维塔利克", 0.098541, 0.703875], ["想", 0.802416, 0.218458], ["的", 1.020875, 0.084958], ["是", 1.105833, 0.303416], ["如果", 1.736875, 0.254875], ["区块", 2.016, 0.327666], ["链能", 2.355833, 0.254875], ["运行", 2.622833, 0.376208], ["任何", 3.023291, 0.327666], ["程序", 3.363125, 0.412583], ["呢", 3.775708, 0.230583]]} \ No newline at end of file diff --git a/ethereum/audio/origin-03.mp3 b/ethereum/audio/origin-03.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..77f675e2d991509e3a07b89caeb5b5a903aa8db1 Binary files /dev/null and b/ethereum/audio/origin-03.mp3 differ diff --git a/ethereum/audio/origin-03.mp3.json b/ethereum/audio/origin-03.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..69685e22f8e37f5b5fbccd8f38090b759e1b5c27 --- /dev/null +++ b/ethereum/audio/origin-03.mp3.json @@ -0,0 +1 @@ +{"text": "那它就不再是计算器,而是一台全世界共享的计算机。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["那", 0.098541, 0.15775], ["它", 0.256291, 0.1335], ["就", 0.401958, 0.1335], ["不再", 0.547583, 0.339791], ["是", 0.887375, 0.1335], ["计算器", 1.033, 0.679625], ["而是", 2.028166, 0.267], ["一", 2.307291, 0.121333], ["台", 2.428625, 0.230583], ["全世界", 2.6835, 0.570375], ["共享", 3.278166, 0.400458], ["的", 3.678625, 0.084958], ["计算机", 3.775708, 0.655333]]} \ No newline at end of file diff --git a/ethereum/audio/origin-04.mp3 b/ethereum/audio/origin-04.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..b1f3c03424ae2600e0b7ecd93b91bab62ad940f1 Binary files /dev/null and b/ethereum/audio/origin-04.mp3 differ diff --git a/ethereum/audio/origin-04.mp3.json b/ethereum/audio/origin-04.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..6d2cfccb8e68eba2927784ad9e80d4eef7e5ca52 --- /dev/null +++ b/ethereum/audio/origin-04.mp3.json @@ -0,0 +1 @@ +{"text": "运行在上面的程序,叫智能合约:规则写进代码,条件一满足,就自动执行,不需要任何中间人。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["运行", 0.098541, 0.42475], ["在", 0.535416, 0.145625], ["上面", 0.705333, 0.315541], ["的", 1.020875, 0.072833], ["程序", 1.105833, 0.534], ["叫", 1.882541, 0.169916], ["智能", 2.076708, 0.279125], ["合约", 2.367958, 0.521833], ["规则", 3.205333, 0.388333], ["写进", 3.617958, 0.351958], ["代码", 3.982041, 0.436875], ["条件", 4.637375, 0.412625], ["一", 5.062125, 0.109208], ["满足", 5.171375, 0.534], ["就", 5.887375, 0.15775], ["自动", 6.057291, 0.364083], ["执行", 6.4335, 0.497583], ["不", 7.148041, 0.145625], ["需要", 7.293708, 0.327666], ["任何", 7.645625, 0.351958], ["中间人", 8.009708, 0.643208]]} \ No newline at end of file diff --git a/ethereum/audio/scale-00.mp3 b/ethereum/audio/scale-00.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..d468e7f1da1acd0b7082ac2d7d2aac406c57d733 Binary files /dev/null and b/ethereum/audio/scale-00.mp3 differ diff --git a/ethereum/audio/scale-00.mp3.json b/ethereum/audio/scale-00.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..b33449669e0524bea97cdfe79f0d3405d3c23808 --- /dev/null +++ b/ethereum/audio/scale-00.mp3.json @@ -0,0 +1 @@ +{"text": "接下来的问题是:太贵,太挤。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["接下来", 0.098541, 0.473291], ["的", 0.571833, 0.072833], ["问题", 0.656791, 0.327666], ["是", 0.984458, 0.327666], ["太", 1.542708, 0.242708], ["贵", 1.785416, 0.279125], ["太", 2.319416, 0.254875], ["挤", 2.574291, 0.315541]]} \ No newline at end of file diff --git a/ethereum/audio/scale-01.mp3 b/ethereum/audio/scale-01.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..2a1decb392b865728fe8deafa1770e3d85979a4a Binary files /dev/null and b/ethereum/audio/scale-01.mp3 differ diff --git a/ethereum/audio/scale-01.mp3.json b/ethereum/audio/scale-01.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..9229ab2b54f892c61cae3a29d28e9fbda2c91d22 --- /dev/null +++ b/ethereum/audio/scale-01.mp3.json @@ -0,0 +1 @@ +{"text": "以太坊给出的答案,是二层网络 Rollup:把大量交易放到二层处理,再把结果打包交回主网。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["以", 0.098541, 0.145625], ["太坊", 0.256291, 0.388333], ["给出", 0.668916, 0.327666], ["的", 0.996583, 0.084958], ["答案", 1.093708, 0.42475], ["是", 1.72475, 0.182041], ["二", 1.931083, 0.169875], ["层", 2.100958, 0.182041], ["网络", 2.295125, 0.473291], ["Rollup", 2.865541, 0.570375], ["把", 3.763583, 0.15775], ["大量", 3.9335, 0.351958], ["交易", 4.297583, 0.388333], ["放", 4.710208, 0.182041], ["到", 4.89225, 0.121375], ["二", 5.037875, 0.169875], ["层", 5.20775, 0.194166], ["处理", 5.414083, 0.412625], ["再", 6.105833, 0.15775], ["把", 6.263583, 0.121375], ["结果", 6.397083, 0.42475], ["打包", 6.834, 0.351958], ["交回", 7.210208, 0.364083], ["主网", 7.574291, 0.461166]]} \ No newline at end of file diff --git a/ethereum/audio/scale-02.mp3 b/ethereum/audio/scale-02.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..ba11d06e63669a12304ff2a739d5d4a94632f2e6 Binary files /dev/null and b/ethereum/audio/scale-02.mp3 differ diff --git a/ethereum/audio/scale-02.mp3.json b/ethereum/audio/scale-02.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..117ae534c37977bd1bb96f9c7e143b303dd78b20 --- /dev/null +++ b/ethereum/audio/scale-02.mp3.json @@ -0,0 +1 @@ +{"text": "2023年4月,上海升级开放了质押提款。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["2023年4月", 0.098541, 1.3713329], ["上海", 1.773291, 0.351958], ["升级", 2.137375, 0.509708], ["开放", 2.671375, 0.351916], ["了", 3.023291, 0.084958], ["质", 3.132541, 0.121333], ["押", 3.253875, 0.194166], ["提款", 3.460208, 0.473291]]} \ No newline at end of file diff --git a/ethereum/audio/scale-03.mp3 b/ethereum/audio/scale-03.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..55d1a189a4dcd15541655e130b64a9f917612555 Binary files /dev/null and b/ethereum/audio/scale-03.mp3 differ diff --git a/ethereum/audio/scale-03.mp3.json b/ethereum/audio/scale-03.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..d0415dcd4f35775e32d016addf84236372f37881 --- /dev/null +++ b/ethereum/audio/scale-03.mp3.json @@ -0,0 +1 @@ +{"text": "2024年3月,坎昆升级引入了 Blob 数据空间,二层网络的手续费大幅下降。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["2024年3月", 0.098541, 1.359208], ["坎昆", 1.7005, 0.376208], ["升级", 2.088833, 0.521833], ["引入", 2.634958, 0.351916], ["了", 2.986875, 0.169916], ["Blob", 3.181083, 0.327666], ["数据", 3.533, 0.303416], ["空间", 3.848541, 0.509708], ["二", 4.613125, 0.254833], ["层", 4.867958, 0.182041], ["网络", 5.062125, 0.315541], ["的", 5.377666, 0.084958], ["手续费", 5.47475, 0.643208], ["大幅", 6.215041, 0.315541], ["下降", 6.542708, 0.497583]]} \ No newline at end of file diff --git a/ethereum/audio/scale-04.mp3 b/ethereum/audio/scale-04.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..ffc9ac4b28f7d4ee122796f4813a0cdc07bd5e0f Binary files /dev/null and b/ethereum/audio/scale-04.mp3 differ diff --git a/ethereum/audio/scale-04.mp3.json b/ethereum/audio/scale-04.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..3fc5183e4aa8fa98adcf4891ef2813124774a8b6 --- /dev/null +++ b/ethereum/audio/scale-04.mp3.json @@ -0,0 +1 @@ +{"text": "以太坊正在变成一座多层的城市:主网负责安全与结算,二层负责速度。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["以", 0.098541, 0.145625], ["太坊", 0.256291, 0.521833], ["正在", 0.802416, 0.267], ["变成", 1.081541, 0.534], ["一", 1.7005, 0.145625], ["座", 1.846125, 0.169916], ["多", 2.040291, 0.169916], ["层", 2.210208, 0.182041], ["的", 2.39225, 0.072833], ["城市", 2.477166, 0.521833], ["主网", 3.326708, 0.351958], ["负责", 3.702916, 0.267], ["安全", 3.982041, 0.4005], ["与", 4.406791, 0.121375], ["结算", 4.540291, 0.485416], ["二", 5.256291, 0.182041], ["层", 5.438333, 0.206291], ["负责", 5.668916, 0.267], ["速度", 5.948041, 0.473291]]} \ No newline at end of file diff --git a/ethereum/audio/wall-00.mp3 b/ethereum/audio/wall-00.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..9672b3e423cb21f89ab861781a1f7f9a64a4c423 Binary files /dev/null and b/ethereum/audio/wall-00.mp3 differ diff --git a/ethereum/audio/wall-00.mp3.json b/ethereum/audio/wall-00.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..6ef2fcd0edd235ff939689210c4e750bc0dbecd1 --- /dev/null +++ b/ethereum/audio/wall-00.mp3.json @@ -0,0 +1 @@ +{"text": "与此同时,华尔街也来了。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["与此同时", 0.098541, 0.800958], ["华尔街", 1.093708, 0.509708], ["也", 1.627666, 0.121375], ["来", 1.749041, 0.206291], ["了", 1.955333, 0.206291]]} \ No newline at end of file diff --git a/ethereum/audio/wall-01.mp3 b/ethereum/audio/wall-01.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..e9e7f6dda5533ebf9d13ee035b38cd5a044ec247 Binary files /dev/null and b/ethereum/audio/wall-01.mp3 differ diff --git a/ethereum/audio/wall-01.mp3.json b/ethereum/audio/wall-01.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..f98afcf22ed23f4a0f32f86922b38b51e7297503 --- /dev/null +++ b/ethereum/audio/wall-01.mp3.json @@ -0,0 +1 @@ +{"text": "2024年7月23日,美国现货以太坊 ETF 正式开始交易。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["2024年7月23日", 0.098541, 1.966], ["美国", 2.404375, 0.254875], ["现货", 2.671375, 0.546125], ["以", 3.314583, 0.145625], ["太坊", 3.472333, 0.42475], ["ETF", 3.897083, 0.716], ["正式", 4.710208, 0.339791], ["开始", 5.062125, 0.315541], ["交易", 5.389791, 0.436875]]} \ No newline at end of file diff --git a/ethereum/audio/wall-02.mp3 b/ethereum/audio/wall-02.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..095bda7e391fdd71d0217315f3819fedb7a578aa Binary files /dev/null and b/ethereum/audio/wall-02.mp3 differ diff --git a/ethereum/audio/wall-02.mp3.json b/ethereum/audio/wall-02.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..2d65d582de9f8fb3828bc447cb7ae93ed3724052 --- /dev/null +++ b/ethereum/audio/wall-02.mp3.json @@ -0,0 +1 @@ +{"text": "2025年5月,Pectra 升级上线,质押和钱包体验再次进化。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["2025年5月", 0.098541, 1.298541], ["Pectra", 1.627666, 0.497583], ["升级", 2.1495, 0.315541], ["上线", 2.477166, 0.497583], ["质", 3.253875, 0.182041], ["押", 3.435916, 0.230583], ["和", 3.690791, 0.1335], ["钱包", 3.836416, 0.351958], ["体验", 4.2005, 0.449041], ["再次", 4.673791, 0.339791], ["进化", 5.025708, 0.461166]]} \ No newline at end of file diff --git a/ethereum/audio/wall-03.mp3 b/ethereum/audio/wall-03.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..20f063842b48398b87dcc5a4f0f0ca2cb6b71ebe Binary files /dev/null and b/ethereum/audio/wall-03.mp3 differ diff --git a/ethereum/audio/wall-03.mp3.json b/ethereum/audio/wall-03.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..4a7af46e9e611093a73a2b6eac153ed2e10e7668 --- /dev/null +++ b/ethereum/audio/wall-03.mp3.json @@ -0,0 +1 @@ +{"text": "同年8月,以太币再创历史新高,日收盘价一度超过4800美元。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["同年", 0.098541, 0.339791], ["8月", 0.4505, 0.473291], ["以", 1.202916, 0.1335], ["太币", 1.348541, 0.497583], ["再", 1.870375, 0.182041], ["创", 2.052416, 0.206291], ["历史", 2.283, 0.242708], ["新高", 2.537875, 0.485416], ["日", 3.326708, 0.1335], ["收盘价", 3.460208, 0.679625], ["一度", 4.236875, 0.303416], ["超过", 4.552416, 0.436875], ["4800美元", 5.013583, 1.177208]]} \ No newline at end of file diff --git a/ethereum/audio/wall-04.mp3 b/ethereum/audio/wall-04.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..b5920c932bd8bfc11fc85854b6af77c0ca4c991f Binary files /dev/null and b/ethereum/audio/wall-04.mp3 differ diff --git a/ethereum/audio/wall-04.mp3.json b/ethereum/audio/wall-04.mp3.json new file mode 100644 index 0000000000000000000000000000000000000000..34bb78f451df4591d70cbd4ff9e5dedd0090a75b --- /dev/null +++ b/ethereum/audio/wall-04.mp3.json @@ -0,0 +1 @@ +{"text": "12月,Fusaka 升级启用 PeerDAS,继续为二层网络扩容。", "voice": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+3%", "pitch": "+0Hz"}, "words": [["12月", 0.098541, 0.69175], ["Fusaka", 1.057291, 0.643208], ["升级", 1.72475, 0.351958], ["启用", 2.088833, 0.4005], ["PeerDAS", 2.513583, 0.995125], ["继续", 3.763583, 0.327666], ["为", 4.103416, 0.182041], ["二", 4.309708, 0.182041], ["层", 4.49175, 0.182041], ["网络", 4.685916, 0.303416], ["扩容", 5.001458, 0.485416]]} \ No newline at end of file diff --git a/ethereum/data/eth-price.js b/ethereum/data/eth-price.js new file mode 100644 index 0000000000000000000000000000000000000000..13a2aff015f46f5b595ac771144be5a8d004e6ac --- /dev/null +++ b/ethereum/data/eth-price.js @@ -0,0 +1,2 @@ +// ETH 日收盘价(每 3 天取样),数据:Surf market-price ETH daily close +window.ETH_PRICE = {"meta":{"source":"Surf market-price ETH daily close","from":"2015-08-07","to":"2026-10-07","ath_close":["2025-08-23",4817.76],"last":["2026-10-07",2722.74]},"pts":[[16654,2.83],[16658,1.07],[16661,1.83],[16664,1.2],[16667,1.48],[16670,1.36],[16673,1.12],[16676,1.17],[16679,1.35],[16682,1.27],[16685,1.26],[16688,1.17],[16691,0.94],[16694,0.9],[16697,0.88],[16700,0.9],[16703,0.74],[16706,0.58],[16709,0.69],[16712,0.67],[16715,0.61],[16718,0.63],[16721,0.6],[16724,0.53],[16727,0.49],[16730,0.57],[16733,0.63],[16736,1.01],[16739,0.91],[16742,1.0],[16745,0.91],[16748,1.0],[16751,0.9],[16754,0.91],[16757,0.99],[16760,0.97],[16763,0.9],[16766,0.87],[16769,0.87],[16772,0.82],[16775,0.83],[16778,0.79],[16781,0.97],[16784,1.02],[16787,0.92],[16790,0.9],[16793,0.86],[16796,0.86],[16799,0.9],[16802,0.94],[16805,0.95],[16808,1.0],[16811,1.07],[16814,1.16],[16817,1.32],[16820,1.57],[16823,1.69],[16826,2.09],[16829,2.49],[16832,2.22],[16835,2.56],[16838,2.95],[16841,4.43],[16844,5.37],[16847,4.37],[16850,4.49],[16853,5.61],[16856,5.94],[16859,6.44],[16862,8.4],[16865,10.94],[16868,9.8],[16871,11.21],[16874,12.29],[16877,10.96],[16880,10.22],[16883,12.4],[16886,10.97],[16889,11.74],[16892,11.64],[16895,11.19],[16898,10.03],[16901,8.81],[16904,8.02],[16907,8.56],[16910,8.7],[16913,7.86],[16916,7.81],[16919,7.25],[16922,8.83],[16925,9.41],[16928,9.38],[16931,9.35],[16934,10.59],[16937,11.13],[16940,14.72],[16943,14.25],[16946,12.5],[16949,11.76],[16952,14.01],[16955,13.84],[16958,13.94],[16961,14.44],[16964,15.7],[16967,18.42],[16970,11.2],[16973,12.98],[16976,13.94],[16979,13.93],[16982,13.34],[16985,11.83],[16988,10.51],[16991,11.0],[16994,10.61],[16997,11.33],[17000,11.02],[17003,12.61],[17006,12.8],[17009,12.97],[17012,12.55],[17015,8.35],[17018,10.94],[17021,11.25],[17024,11.99],[17027,11.26],[17030,10.74],[17033,11.26],[17036,11.01],[17039,11.26],[17042,10.91],[17045,12.0],[17048,11.66],[17051,11.55],[17054,12.12],[17057,11.88],[17060,12.52],[17063,13.16],[17066,13.23],[17069,13.05],[17072,13.31],[17075,13.27],[17078,13.26],[17081,12.66],[17084,11.84],[17087,11.96],[17090,11.93],[17093,11.97],[17096,12.05],[17099,11.27],[17102,11.52],[17105,10.88],[17108,10.81],[17111,10.92],[17114,10.66],[17117,9.66],[17120,10.2],[17123,9.45],[17126,9.58],[17129,9.18],[17132,8.91],[17135,8.65],[17138,7.89],[17141,7.63],[17144,8.5],[17147,8.47],[17150,7.77],[17153,7.86],[17156,7.86],[17159,7.22],[17162,7.17],[17165,8.15],[17168,8.36],[17171,10.12],[17174,10.27],[17177,9.66],[17180,9.7],[17183,10.26],[17186,10.55],[17189,10.75],[17192,10.56],[17195,10.43],[17198,10.7],[17201,11.33],[17204,11.43],[17207,11.28],[17210,11.28],[17213,12.84],[17216,12.78],[17219,12.6],[17222,13.55],[17225,15.7],[17228,19.59],[17231,19.67],[17234,17.63],[17237,23.1],[17240,34.2],[17243,32.27],[17246,42.48],[17249,50.89],[17252,49.02],[17255,52.31],[17258,48.38],[17261,45.59],[17264,44.5],[17267,43.86],[17270,47.56],[17273,48.35],[17276,50.07],[17279,50.61],[17282,54.88],[17285,70.45],[17288,77.35],[17291,91.16],[17294,87.95],[17297,88.46],[17300,90.06],[17303,88.21],[17306,123.03],[17309,171.08],[17312,162.94],[17315,196.08],[17318,221.83],[17321,247.43],[17324,256.22],[17327,337.79],[17330,389.94],[17333,358.28],[17336,362.04],[17339,326.96],[17342,288.05],[17345,317.29],[17348,262.48],[17351,269.74],[17354,241.48],[17357,210.53],[17360,206.41],[17363,156.47],[17366,199.59],[17369,231.14],[17372,206.81],[17375,192.59],[17378,203.29],[17381,224.87],[17384,263.22],[17387,297.07],[17390,308.63],[17393,288.45],[17396,296.11],[17399,322.2],[17402,321.79],[17405,343.34],[17408,378.91],[17411,346.4],[17414,318.97],[17417,304.48],[17420,296.48],[17423,214.31],[17426,249.67],[17429,279.42],[17432,283.22],[17435,283.93],[17438,288.11],[17441,295.84],[17444,293.72],[17447,307.06],[17450,303.25],[17453,335.34],[17456,317.9],[17459,302.36],[17462,289.41],[17465,295.71],[17468,303.74],[17471,292.33],[17474,299.95],[17477,295.24],[17480,301.35],[17483,315.34],[17486,330.02],[17489,353.44],[17492,379.41],[17495,467.45],[17498,474.18],[17501,469.86],[17504,472.25],[17507,451.83],[17510,446.69],[17513,709.88],[17516,702.24],[17519,829.99],[17522,669.28],[17525,733.9],[17528,736.84],[17531,774.7],[17534,963.06],[17537,1052.02],[17540,1361.44],[17543,1315.62],[17546,1329.67],[17549,1036.07],[17552,1053.63],[17555,1056.88],[17558,1095.78],[17561,1161.91],[17564,988.81],[17567,821.23],[17570,771.82],[17573,840.09],[17576,837.34],[17579,940.51],[17582,937.39],[17585,799.62],[17588,839.13],[17591,842.66],[17594,839.7],[17597,811.28],[17600,727.44],[17603,694.82],[17606,611.6],[17609,543.43],[17612,561.61],[17615,518.55],[17618,448.88],[17621,395.64],[17624,385.59],[17627,382.29],[17630,397.31],[17633,426.76],[17636,495.36],[17639,498.37],[17642,613.1],[17645,636.53],[17648,655.82],[17651,679.68],[17654,676.99],[17657,807.18],[17660,741.47],[17663,674.36],[17666,727.38],[17669,663.46],[17672,704.01],[17675,579.9],[17678,581.56],[17681,563.53],[17684,573.59],[17687,585.97],[17690,595.9],[17693,524.43],[17696,475.48],[17699,491.9],[17702,531.93],[17705,465.3],[17708,459.8],[17711,420.18],[17714,448.23],[17717,463.3],[17720,483.03],[17723,431.53],[17726,431.02],[17729,476.26],[17732,465.0],[17735,455.08],[17738,468.82],[17741,465.69],[17744,432.35],[17747,416.96],[17750,404.86],[17753,363.98],[17756,319.87],[17759,281.58],[17762,293.08],[17765,281.0],[17768,281.59],[17771,287.28],[17774,285.09],[17777,294.58],[17780,228.96],[17783,196.95],[17786,184.45],[17789,209.37],[17792,196.37],[17795,224.41],[17798,244.85],[17801,214.32],[17804,231.38],[17807,226.04],[17810,227.83],[17813,229.56],[17816,191.61],[17819,196.25],[17822,211.15],[17825,207.01],[17828,204.07],[17831,203.49],[17834,195.83],[17837,199.27],[17840,205.89],[17843,218.69],[17846,212.57],[17849,208.83],[17852,176.08],[17855,149.45],[17858,126.01],[17861,117.37],[17864,122.61],[17867,118.07],[17870,109.75],[17873,93.0],[17876,89.82],[17879,86.04],[17882,84.49],[17885,99.08],[17888,115.7],[17891,127.96],[17894,134.84],[17897,131.57],[17900,145.74],[17903,154.72],[17906,148.98],[17909,123.97],[17912,119.83],[17915,119.37],[17918,115.76],[17921,116.53],[17924,112.14],[17927,108.27],[17930,109.37],[17933,107.3],[17936,119.24],[17939,120.95],[17942,120.41],[17945,133.59],[17948,148.9],[17951,157.64],[17954,136.36],[17957,135.17],[17960,125.9],[17963,136.82],[17966,135.48],[17969,131.64],[17972,140.95],[17975,138.41],[17978,136.02],[17981,133.71],[17984,137.79],[17987,141.52],[17990,159.86],[17993,165.45],[17996,175.04],[17999,164.41],[18002,160.23],[18005,173.67],[18008,169.77],[18011,165.6],[18014,158.26],[18017,160.89],[18020,166.63],[18023,172.45],[18026,170.52],[18029,187.81],[18032,248.29],[18035,234.68],[18038,254.76],[18041,248.91],[18044,272.18],[18047,255.21],[18050,269.72],[18053,245.89],[18056,244.12],[18059,245.37],[18062,263.56],[18065,273.58],[18068,272.29],[18071,308.19],[18074,337.99],[18077,319.95],[18080,291.2],[18083,287.93],[18086,313.12],[18089,269.63],[18092,227.64],[18095,211.42],[18098,228.9],[18101,212.74],[18104,219.19],[18107,210.94],[18110,216.87],[18113,222.02],[18116,225.64],[18119,206.46],[18122,209.05],[18125,185.44],[18128,202.78],[18131,190.29],[18134,186.77],[18137,172.78],[18140,171.94],[18143,178.64],[18146,169.01],[18149,180.6],[18152,181.21],[18155,189.76],[18158,210.15],[18161,215.21],[18164,167.54],[18167,174.18],[18170,180.61],[18173,174.63],[18176,170.61],[18179,193.3],[18182,179.68],[18185,180.57],[18188,172.98],[18191,174.28],[18194,160.67],[18197,184.15],[18200,183.14],[18203,183.23],[18206,188.51],[18209,183.7],[18212,184.77],[18215,184.74],[18218,183.99],[18221,174.68],[18224,152.36],[18227,147.57],[18230,154.34],[18233,148.8],[18236,147.8],[18239,150.3],[18242,143.13],[18245,141.82],[18248,121.8],[18251,128.29],[18254,128.08],[18257,125.35],[18260,134.33],[18263,130.54],[18266,134.09],[18269,142.98],[18272,144.1],[18275,143.35],[18278,164.41],[18281,166.66],[18284,167.83],[18287,160.41],[18290,175.31],[18293,179.26],[18296,189.83],[18299,213.08],[18302,228.45],[18305,265.7],[18308,264.04],[18311,282.15],[18314,265.1],[18317,265.32],[18320,226.93],[18323,218.89],[18326,224.21],[18329,237.67],[18332,200.64],[18335,133.84],[18338,111.3],[18341,136.61],[18344,122.44],[18347,136.27],[18350,131.43],[18353,133.02],[18356,141.31],[18359,170.43],[18362,170.09],[18365,158.98],[18368,153.08],[18371,187.39],[18374,170.52],[18377,187.39],[18380,196.52],[18383,206.32],[18386,210.01],[18389,199.21],[18392,210.43],[18395,189.35],[18398,194.34],[18401,214.55],[18404,198.92],[18407,200.69],[18410,207.85],[18413,243.06],[18416,237.27],[18419,240.25],[18422,246.22],[18425,231.59],[18428,231.49],[18431,233.84],[18434,228.84],[18437,243.13],[18440,229.64],[18443,227.98],[18446,226.51],[18449,228.02],[18452,246.8],[18455,239.18],[18458,240.47],[18461,232.71],[18464,235.93],[18467,275.31],[18470,311.27],[18473,317.82],[18476,387.49],[18479,389.54],[18482,379.61],[18485,395.62],[18488,427.49],[18491,433.99],[18494,406.09],[18497,395.84],[18500,382.45],[18503,395.28],[18506,434.52],[18509,382.91],[18512,352.57],[18515,351.24],[18518,387.94],[18521,364.43],[18524,384.05],[18527,340.07],[18530,348.89],[18533,357.34],[18536,359.35],[18539,346.05],[18542,340.47],[18545,365.03],[18548,386.88],[18551,377.58],[18554,377.97],[18557,391.49],[18560,411.88],[18563,403.52],[18566,382.07],[18569,383.22],[18572,416.74],[18575,454.31],[18578,463.49],[18581,461.95],[18584,482.08],[18587,509.23],[18590,607.92],[18593,519.95],[18596,576.22],[18599,599.16],[18602,596.48],[18605,554.56],[18608,544.98],[18611,585.62],[18614,643.25],[18617,638.37],[18620,586.21],[18623,636.83],[18626,735.12],[18629,729.63],[18632,1022.87],[18635,1232.45],[18638,1257.6],[18641,1136.31],[18644,1225.9],[18647,1375.32],[18650,1240.24],[18653,1318.78],[18656,1337.44],[18659,1310.26],[18662,1669.69],[18665,1677.81],[18668,1768.5],[18671,1839.88],[18674,1775.56],[18677,1937.3],[18680,1936.01],[18683,1632.35],[18686,1462.36],[18689,1496.11],[18692,1540.07],[18695,1836.28],[18698,1831.43],[18701,1856.71],[18704,1838.74],[18707,1812.44],[18710,1674.88],[18713,1707.17],[18716,1817.26],[18719,1969.73],[18722,2078.74],[18725,1979.46],[18728,2140.76],[18731,2309.21],[18734,2432.67],[18737,2161.2],[18740,2416.71],[18743,2317.49],[18746,2749.93],[18749,2946.09],[18752,3242.22],[18755,3488.73],[18758,3977.44],[18761,3745.45],[18764,3604.75],[18767,2490.75],[18770,2289.59],[18773,2712.49],[18776,2429.24],[18779,2705.8],[18782,2868.76],[18785,2718.76],[18788,2616.2],[18791,2380.86],[18794,2559.73],[18797,2229.01],[18800,1894.44],[18803,1991.24],[18806,1978.14],[18809,2273.41],[18812,2233.2],[18815,2323.52],[18818,2152.93],[18821,2042.42],[18824,1922.39],[18827,1902.06],[18830,2003.19],[18833,2192.94],[18836,2298.4],[18839,2463.28],[18842,2600.63],[18845,2820.4],[18848,3002.84],[18851,3161.31],[18854,3267.21],[18857,3015.87],[18860,3280.79],[18863,3312.3],[18866,3112.7],[18869,3232.19],[18872,3815.12],[18875,3890.16],[18878,3445.11],[18881,3218.1],[18884,3291.22],[18887,3573.25],[18890,3336.96],[18893,3080.77],[18896,2942.2],[18899,2801.06],[18902,3310.25],[18905,3389.55],[18908,3588.45],[18911,3423.0],[18914,3612.32],[18917,3850.26],[18920,3884.37],[18923,3972.43],[18926,4234.9],[18929,4294.49],[18932,4292.73],[18935,4604.56],[18938,4529.85],[18941,4742.49],[18944,4687.57],[18947,4581.33],[18950,3998.84],[18953,4314.43],[18956,4270.51],[18959,4090.12],[18962,4629.56],[18965,4235.02],[18968,4357.62],[18971,4135.85],[18974,4136.58],[18977,4024.76],[18980,3962.86],[18983,4030.7],[18986,4055.77],[18989,4042.52],[18992,3715.95],[18995,3833.86],[18998,3553.14],[19001,3091.79],[19004,3248.96],[19007,3319.83],[19010,3220.68],[19013,3006.58],[19016,2539.68],[19019,2468.67],[19022,2606.55],[19025,2796.63],[19028,2993.35],[19031,3145.16],[19034,3070.3],[19037,2882.11],[19040,3126.25],[19043,2769.66],[19046,2642.84],[19049,2772.58],[19052,2929.53],[19055,2836.69],[19058,2559.04],[19061,2725.55],[19064,2573.57],[19067,2620.45],[19070,2943.26],[19073,2891.46],[19076,3106.75],[19079,3284.65],[19082,3380.2],[19085,3442.28],[19088,3414.21],[19091,3195.93],[19094,2987.02],[19097,3024.5],[19100,2993.04],[19103,3078.21],[19106,2938.94],[19109,2811.0],[19112,2818.63],[19115,2860.0],[19118,2753.94],[19121,2523.07],[19124,2089.99],[19127,2064.23],[19130,2095.18],[19133,1963.99],[19136,1991.27],[19139,1803.82],[19142,1814.77],[19145,1824.22],[19148,1804.71],[19151,1819.01],[19154,1663.6],[19157,1208.04],[19160,1066.53],[19163,1127.83],[19166,1051.19],[19169,1242.68],[19172,1143.29],[19175,1064.26],[19178,1152.06],[19181,1236.74],[19184,1168.63],[19187,1114.86],[19190,1355.62],[19193,1542.56],[19196,1537.65],[19199,1443.68],[19202,1725.58],[19205,1681.17],[19208,1621.57],[19211,1691.78],[19214,1696.66],[19217,1958.2],[19220,1902.76],[19223,1849.67],[19226,1620.68],[19229,1657.61],[19232,1493.47],[19235,1523.29],[19238,1577.41],[19241,1614.62],[19244,1635.1],[19247,1760.75],[19250,1636.44],[19253,1470.68],[19256,1325.54],[19259,1330.26],[19262,1335.54],[19265,1334.89],[19268,1277.35],[19271,1352.75],[19274,1315.91],[19277,1280.0],[19280,1297.71],[19283,1332.26],[19286,1284.43],[19289,1363.73],[19292,1567.48],[19295,1618.97],[19298,1579.38],[19301,1644.48],[19304,1569.02],[19307,1301.68],[19310,1221.49],[19313,1217.12],[19316,1219.89],[19319,1139.36],[19322,1199.65],[19325,1169.92],[19328,1276.6],[19331,1281.31],[19334,1232.83],[19337,1266.21],[19340,1320.65],[19343,1168.39],[19346,1168.7],[19349,1218.13],[19352,1219.51],[19355,1189.86],[19358,1196.44],[19361,1214.75],[19364,1269.7],[19367,1322.24],[19370,1416.88],[19373,1553.93],[19376,1516.33],[19379,1625.65],[19382,1559.05],[19385,1598.6],[19388,1567.42],[19391,1645.67],[19394,1630.3],[19397,1651.04],[19400,1541.68],[19403,1555.03],[19406,1698.8],[19409,1700.53],[19412,1649.66],[19415,1640.6],[19418,1664.04],[19421,1568.96],[19424,1562.19],[19427,1428.38],[19430,1682.08],[19433,1679.88],[19436,1790.55],[19439,1746.39],[19442,1755.17],[19445,1774.99],[19448,1823.88],[19451,1811.65],[19454,1873.21],[19457,1858.9],[19460,1919.18],[19463,2092.19],[19466,2105.21],[19469,1850.12],[19472,1842.01],[19475,1910.0],[19478,1878.05],[19481,1904.69],[19484,1900.46],[19487,1848.1],[19490,1807.63],[19493,1816.4],[19496,1802.18],[19499,1805.85],[19502,1799.46],[19505,1830.08],[19508,1901.33],[19511,1907.58],[19514,1810.99],[19517,1845.57],[19520,1752.27],[19523,1649.79],[19526,1727.06],[19529,1792.12],[19532,1892.4],[19535,1859.72],[19538,1853.16],[19541,1937.93],[19544,1910.35],[19547,1865.93],[19550,1878.28],[19553,1937.94],[19556,1911.91],[19559,1891.32],[19562,1888.98],[19565,1871.04],[19568,1881.17],[19571,1877.06],[19574,1828.61],[19577,1828.2],[19580,1851.03],[19583,1839.42],[19586,1805.72],[19589,1669.13],[19592,1633.69],[19595,1653.16],[19598,1652.72],[19601,1645.45],[19604,1635.64],[19607,1632.36],[19610,1634.45],[19613,1593.01],[19616,1641.05],[19619,1637.61],[19622,1584.04],[19625,1580.01],[19628,1597.71],[19631,1670.99],[19634,1656.8],[19637,1646.13],[19640,1579.61],[19643,1539.89],[19646,1558.43],[19649,1563.7],[19652,1629.27],[19655,1785.27],[19658,1780.89],[19661,1809.53],[19664,1801.07],[19667,1893.31],[19670,1887.8],[19673,2053.6],[19676,1978.57],[19679,1962.66],[19682,2021.93],[19685,2063.15],[19688,2062.87],[19691,2029.37],[19694,2165.69],[19697,2293.76],[19700,2358.07],[19703,2225.36],[19706,2314.36],[19709,2195.74],[19712,2201.67],[19715,2308.67],[19718,2231.49],[19721,2300.86],[19724,2350.09],[19727,2269.92],[19730,2222.97],[19733,2581.7],[19736,2577.53],[19739,2588.77],[19742,2490.65],[19745,2311.96],[19748,2217.35],[19751,2251.17],[19754,2285.2],[19757,2295.74],[19760,2372.07],[19763,2488.38],[19766,2662.19],[19769,2823.19],[19772,2875.49],[19775,2975.24],[19778,2991.05],[19781,3243.73],[19784,3433.11],[19787,3633.77],[19790,3865.97],[19793,3887.88],[19796,4005.85],[19799,3517.77],[19802,3159.0],[19805,3327.72],[19808,3589.3],[19811,3561.58],[19814,3649.64],[19817,3310.16],[19820,3355.71],[19823,3503.76],[19826,3242.63],[19829,3101.4],[19832,3066.62],[19835,3146.65],[19838,3139.08],[19841,3251.48],[19844,3010.01],[19847,3103.58],[19850,3063.76],[19853,3035.8],[19856,2928.75],[19859,3036.4],[19862,3122.66],[19865,3788.62],[19868,3726.53],[19871,3893.78],[19874,3747.64],[19877,3780.79],[19880,3863.41],[19883,3682.02],[19886,3497.47],[19889,3479.89],[19892,3509.86],[19895,3510.02],[19898,3418.59],[19901,3369.45],[19904,3373.0],[19907,3417.89],[19910,2979.24],[19913,3019.44],[19916,3099.51],[19919,3238.35],[19922,3388.23],[19925,3518.07],[19928,3481.46],[19931,3276.34],[19934,3319.98],[19937,3202.68],[19940,2690.65],[19943,2339.81],[19946,2610.48],[19949,2704.11],[19952,2592.14],[19955,2636.96],[19958,2622.63],[19961,2747.43],[19964,2527.95],[19967,2512.32],[19970,2427.48],[19973,2224.47],[19976,2358.89],[19979,2362.41],[19982,2317.79],[19985,2375.67],[19988,2615.16],[19991,2652.73],[19994,2696.24],[19997,2603.55],[20000,2349.1],[20003,2439.57],[20006,2367.45],[20009,2476.31],[20012,2607.62],[20015,2641.24],[20018,2664.1],[20021,2534.31],[20024,2505.89],[20027,2657.36],[20030,2492.6],[20033,2425.12],[20036,2961.69],[20039,3380.22],[20042,3059.67],[20045,3076.95],[20048,3074.47],[20051,3398.52],[20054,3326.48],[20057,3597.26],[20060,3645.09],[20063,3791.37],[20066,4007.41],[20069,3832.65],[20072,3868.32],[20075,3887.28],[20078,3462.58],[20081,3419.1],[20084,3331.43],[20087,3347.85],[20090,3352.22],[20093,3656.82],[20096,3378.84],[20099,3266.97],[20102,3136.13],[20105,3306.82],[20108,3202.87],[20111,3238.02],[20114,3317.75],[20117,3077.92],[20120,3298.53],[20123,2880.28],[20126,2687.81],[20129,2630.44],[20132,2737.2],[20135,2693.5],[20138,2671.69],[20141,2655.11],[20144,2514.86],[20147,2305.03],[20150,2508.35],[20153,2242.3],[20156,2201.42],[20159,1925.1],[20162,1910.99],[20165,1926.43],[20168,1979.91],[20171,2007.21],[20174,2009.34],[20177,1827.77],[20180,1905.22],[20183,1814.6],[20186,1553.65],[20189,1521.32],[20192,1596.41],[20195,1577.84],[20198,1613.63],[20201,1757.93],[20204,1787.36],[20207,1800.1],[20210,1838.93],[20213,1808.16],[20216,1811.71],[20219,2582.98],[20222,2679.44],[20225,2541.69],[20228,2527.81],[20231,2658.67],[20234,2548.15],[20237,2679.88],[20240,2531.53],[20243,2594.78],[20246,2478.8],[20249,2682.35],[20252,2650.1],[20255,2547.2],[20258,2523.18],[20261,2294.01],[20264,2447.33],[20267,2423.23],[20270,2487.47],[20273,2592.43],[20276,2570.82],[20279,2770.46],[20282,2942.79],[20285,3136.79],[20288,3548.42],[20291,3764.79],[20294,3701.45],[20297,3871.95],[20300,3807.38],[20303,3400.74],[20306,3611.96],[20309,4010.92],[20312,4226.51],[20315,4560.32],[20318,4485.03],[20321,4335.1],[20324,4782.43],[20327,4591.77],[20330,4359.24],[20333,4314.34],[20336,4302.63],[20339,4305.71],[20342,4347.48],[20345,4669.03],[20348,4503.4],[20351,4470.1],[20354,4201.89],[20357,3896.06],[20360,4139.68],[20363,4354.38],[20366,4488.8],[20369,4453.78],[20372,3841.67],[20375,4245.45],[20378,3893.76],[20381,3982.36],[20384,3805.88],[20387,3954.0],[20390,3978.81],[20393,3846.96],[20396,3600.36],[20399,3312.45],[20402,3578.8],[20405,3412.54],[20408,3169.7],[20411,3121.51],[20414,2763.9],[20417,2952.33],[20420,3014.82],[20423,2990.8],[20426,3188.88],[20429,3036.88],[20432,3318.72],[20435,3086.73],[20438,2963.89],[20441,2826.67],[20444,3004.22],[20447,2945.37],[20450,2947.71],[20453,2967.98],[20456,3135.11],[20459,3227.39],[20462,3106.06],[20465,3120.17],[20468,3351.82],[20471,3307.07],[20474,2941.88],[20477,2955.12],[20480,2925.76],[20483,2822.63],[20486,2264.35],[20489,2143.29],[20492,2087.99],[20495,2021.44],[20498,2048.32],[20501,1998.18],[20504,1949.61],[20507,1886.45],[20510,2053.1],[20513,1966.72],[20516,1982.95],[20519,1979.08],[20522,1992.98],[20525,2071.92],[20528,2182.07],[20531,2203.13],[20534,2066.16],[20537,2156.39],[20540,1991.55],[20543,2024.01],[20546,2052.34],[20549,2066.2],[20552,2179.79],[20555,2283.06],[20558,2326.45],[20561,2421.29],[20564,2314.64],[20567,2331.1],[20570,2369.15],[20573,2253.62],[20576,2322.29],[20579,2360.64],[20582,2307.47],[20585,2338.59],[20588,2282.6],[20591,2130.75],[20594,2127.47],[20597,2116.43],[20600,2072.35],[20603,2012.56],[20606,2003.58],[20609,1769.03],[20612,1687.88],[20615,1620.92],[20618,1680.31],[20621,1791.39],[20624,1708.88],[20627,1725.16],[20630,1566.01],[20633,1570.08],[20636,1608.25],[20639,1779.91],[20642,1771.22],[20645,1795.24],[20648,1774.09],[20651,1863.01],[20654,1870.82],[20657,1933.41],[20660,1874.46],[20663,1920.49],[20666,1860.59],[20669,1858.54],[20672,1902.16],[20675,1908.94],[20678,1877.74],[20681,1880.96],[20684,1916.4],[20687,2514.97],[20690,2481.88],[20693,2511.46],[20696,2416.24],[20699,2390.78],[20702,2480.0],[20705,2485.07],[20708,2514.85],[20711,2514.76],[20714,2446.14],[20717,2644.73],[20720,2684.34],[20723,2695.6],[20726,2677.38],[20729,2667.95],[20732,2710.42],[20733,2722.74]]}; diff --git a/ethereum/js/data-script.js b/ethereum/js/data-script.js new file mode 100644 index 0000000000000000000000000000000000000000..1e98f67c76e962c54f303f2eb6cb55e3b14b90f9 --- /dev/null +++ b/ethereum/js/data-script.js @@ -0,0 +1,2 @@ +// 自动生成:tools/build_voice.py —— 请勿手改 +window.ETH_SCRIPT = [{"id":"open","title":"序章","year":"2013","lines":[{"text":"2013年冬天,一个19岁的年轻人,写下了一份白皮书。","file":"audio/open-00.mp3","marks":{"dark":0.099,"spark":1.749},"dur":5.544,"words":[[0,4,0.099,0.754],[4,5,0.754,0.936],[5,7,0.948,1.458],[8,10,1.749,1.943],[10,13,1.967,2.514],[13,14,2.514,2.599],[14,17,2.611,3.278],[18,19,3.497,3.691],[19,20,3.691,3.873],[20,21,3.873,3.933],[21,22,3.946,4.079],[22,23,4.079,4.273],[23,26,4.298,4.965]]},{"text":"他叫维塔利克·布特林。","file":"audio/open-01.mp3","marks":{"name":0.451},"dur":2.712,"words":[[0,1,0.099,0.244],[1,2,0.244,0.426],[2,6,0.451,1.264],[7,10,1.494,2.162]]},{"text":"那时没有人想到,这份文件会长成一个承载数千亿美元价值的网络。","file":"audio/open-02.mp3","marks":{"grow":3.582},"dur":6.336,"words":[[0,2,0.099,0.426],[2,4,0.451,0.693],[4,5,0.693,0.815],[5,7,0.827,1.3],[8,9,1.652,1.822],[9,10,1.822,1.967],[10,12,1.98,2.501],[12,14,2.586,2.926],[14,15,2.926,3.072],[15,17,3.084,3.485],[17,19,3.582,3.958],[19,22,3.982,4.528],[22,24,4.54,4.868],[24,26,4.88,5.208],[26,27,5.208,5.293],[27,29,5.305,5.778]]},{"text":"接下来的六分钟,我们一起走完以太坊的十三年。","file":"audio/open-03.mp3","marks":{"title":2.312},"dur":4.656,"words":[[0,3,0.099,0.572],[3,4,0.572,0.645],[4,7,0.657,1.264],[8,13,1.555,2.501],[13,14,2.599,2.781],[14,15,2.781,2.878],[15,17,2.89,3.278],[17,18,3.278,3.351],[18,20,3.375,3.8],[20,21,3.8,4.091]]}]},{"id":"origin","title":"起源","year":"2013","lines":[{"text":"故事要从比特币说起。","file":"audio/origin-00.mp3","marks":{},"dur":2.4,"words":[[0,2,0.099,0.414],[2,3,0.426,0.596],[3,4,0.596,0.802],[4,7,0.827,1.324],[7,9,1.324,1.834]]},{"text":"比特币很伟大,但它更像一台计算器:功能简单,只专注于记账和转账。","file":"audio/origin-01.mp3","marks":{"calc":2.574},"dur":6.864,"words":[[0,3,0.099,0.62],[3,4,0.645,0.827],[4,6,0.827,1.276],[7,8,1.603,1.749],[8,9,1.749,1.87],[9,10,1.883,2.065],[10,11,2.065,2.247],[11,12,2.259,2.368],[12,13,2.368,2.55],[13,16,2.574,3.217],[17,19,3.472,3.8],[19,21,3.812,4.298],[22,23,4.504,4.674],[23,25,4.674,5.014],[25,26,5.014,5.208],[26,28,5.232,5.633],[28,29,5.657,5.778],[29,31,5.79,6.288]]},{"text":"维塔利克想的是:如果区块链能运行任何程序呢?","file":"audio/origin-02.mp3","marks":{"code":3.023},"dur":4.56,"words":[[0,4,0.099,0.802],[4,5,0.802,1.021],[5,6,1.021,1.106],[6,7,1.106,1.409],[8,10,1.737,1.992],[10,12,2.016,2.344],[12,14,2.356,2.611],[14,16,2.623,2.999],[16,18,3.023,3.351],[18,20,3.363,3.776],[20,21,3.776,4.006]]},{"text":"那它就不再是计算器,而是一台全世界共享的计算机。","file":"audio/origin-03.mp3","marks":{"world":2.683},"dur":4.992,"words":[[0,1,0.099,0.256],[1,2,0.256,0.39],[2,3,0.402,0.535],[3,5,0.548,0.887],[5,6,0.887,1.021],[6,9,1.033,1.713],[10,12,2.028,2.295],[12,13,2.307,2.429],[13,14,2.429,2.659],[14,17,2.683,3.254],[17,19,3.278,3.679],[19,20,3.679,3.764],[20,23,3.776,4.431]]},{"text":"运行在上面的程序,叫智能合约:规则写进代码,条件一满足,就自动执行,不需要任何中间人。","file":"audio/origin-04.mp3","marks":{"contract":2.077,"auto":6.057},"dur":9.216,"words":[[0,2,0.099,0.523],[2,3,0.535,0.681],[3,5,0.705,1.021],[5,6,1.021,1.094],[6,8,1.106,1.64],[9,10,1.883,2.052],[10,12,2.077,2.356],[12,14,2.368,2.89],[15,17,3.205,3.594],[17,19,3.618,3.97],[19,21,3.982,4.419],[22,24,4.637,5.05],[24,25,5.062,5.171],[25,27,5.171,5.705],[28,29,5.887,6.045],[29,31,6.057,6.421],[31,33,6.434,6.931],[34,35,7.148,7.294],[35,37,7.294,7.621],[37,39,7.646,7.998],[39,42,8.01,8.653]]}]},{"id":"ico","title":"众筹","year":"2014","lines":[{"text":"2014年1月,以太坊在迈阿密的比特币大会上正式亮相。","file":"audio/ico-00.mp3","marks":{"miami":2.574},"dur":5.76,"words":[[0,7,0.099,1.409],[8,9,1.713,1.834],[9,11,1.846,2.38],[11,12,2.404,2.562],[12,15,2.574,3.048],[15,16,3.048,3.145],[16,19,3.169,3.606],[19,21,3.618,3.994],[21,22,3.994,4.249],[22,24,4.346,4.686],[24,26,4.698,5.196]]},{"text":"同年7月22日,以太坊开启公开众筹,持续了六周。","file":"audio/ico-01.mp3","marks":{"sale":1.81},"dur":5.376,"words":[[0,2,0.099,0.548],[2,7,0.572,1.531],[8,9,1.81,1.931],[9,11,1.943,2.416],[11,13,2.441,2.781],[13,15,2.805,3.108],[15,17,3.12,3.667],[18,20,3.836,4.249],[20,21,4.249,4.334],[21,23,4.346,4.819]]},{"text":"每枚以太币,价格大约0.31美元。","file":"audio/ico-02.mp3","marks":{"price":2.065},"dur":3.816,"words":[[0,1,0.099,0.281],[1,2,0.281,0.414],[2,3,0.426,0.511],[3,5,0.523,0.997],[6,8,1.276,1.615],[8,10,1.628,2.04],[10,16,2.065,3.242]]},{"text":"最终募得约1830万美元,是当时规模最大的众筹项目之一。","file":"audio/ico-03.mp3","marks":{"raise":1.179},"dur":6.312,"words":[[0,2,0.099,0.475],[2,4,0.487,0.924],[4,5,0.948,1.166],[5,10,1.179,2.392],[10,12,2.392,2.853],[13,14,3.12,3.254],[14,16,3.266,3.703],[16,18,3.727,4.103],[18,20,4.116,4.516],[20,21,4.516,4.637],[21,23,4.662,4.989],[23,25,5.001,5.305],[25,27,5.317,5.754]]},{"text":"团队在瑞士成立了以太坊基金会,开始了一年的紧张开发。","file":"audio/ico-04.mp3","marks":{"found":1.676},"dur":5.4,"words":[[0,2,0.099,0.584],[2,3,0.608,0.754],[3,5,0.766,1.179],[5,7,1.191,1.567],[7,8,1.567,1.652],[8,9,1.676,1.785],[9,11,1.798,2.186],[11,14,2.198,2.805],[15,17,3.072,3.424],[17,18,3.424,3.509],[18,19,3.533,3.667],[19,20,3.667,3.861],[20,21,3.861,3.958],[21,23,3.982,4.358],[23,25,4.37,4.844]]}]},{"id":"genesis","title":"创世","year":"2015","lines":[{"text":"2015年7月30日,以太坊主网 Frontier 正式启动。","file":"audio/genesis-00.mp3","marks":{"boot":2.125},"dur":5.28,"words":[[0,10,0.099,1.87],[11,12,2.125,2.283],[12,14,2.295,2.671],[14,16,2.671,3.108],[17,25,3.205,3.8],[26,28,3.909,4.237],[28,30,4.249,4.71]]},{"text":"第0号区块,创世区块诞生。","file":"audio/genesis-01.mp3","marks":{"block0":1.373},"dur":3.192,"words":[[0,1,0.099,0.281],[1,2,0.281,0.45],[2,3,0.451,0.645],[3,5,0.657,1.118],[6,8,1.373,1.81],[8,10,1.822,2.149],[10,12,2.162,2.635]]},{"text":"从这一刻起,新区块每隔十几秒就产生一个,链条开始生长。","file":"audio/genesis-02.mp3","marks":{"chain":1.361},"dur":5.976,"words":[[0,1,0.099,0.317],[1,2,0.329,0.451],[2,4,0.451,0.754],[4,5,0.754,1.057],[6,7,1.361,1.591],[7,9,1.591,1.943],[9,10,1.967,2.149],[10,11,2.15,2.319],[11,13,2.332,2.671],[13,14,2.671,2.963],[14,15,2.987,3.12],[15,17,3.133,3.509],[17,19,3.521,3.909],[20,22,4.2,4.565],[22,24,4.589,4.868],[24,26,4.88,5.402]]},{"text":"那时候,一枚以太币还不到3美元。","file":"audio/genesis-03.mp3","marks":{"p2015":2.259},"dur":3.864,"words":[[0,3,0.099,0.73],[4,5,0.984,1.13],[5,6,1.13,1.433],[6,7,1.518,1.64],[7,9,1.652,2.162],[9,10,2.259,2.404],[10,11,2.404,2.489],[11,12,2.489,2.623],[12,15,2.647,3.315]]}]},{"id":"dao","title":"至暗时刻","year":"2016","lines":[{"text":"2016年,一个叫The DAO 的项目,在以太坊上募集了价值约1.5亿美元的以太币。","file":"audio/dao-00.mp3","marks":{"dao":1.798},"dur":7.416,"words":[[0,4,0.099,0.766],[4,5,0.766,1.094],[6,8,1.312,1.543],[8,9,1.555,1.773],[9,12,1.798,1.895],[13,16,1.907,2.113],[17,18,2.113,2.198],[18,20,2.21,2.671],[21,22,3.011,3.193],[22,23,3.193,3.278],[23,25,3.29,3.691],[25,26,3.691,3.994],[26,28,4.091,4.37],[28,29,4.37,4.455],[29,31,4.467,4.941],[31,32,4.965,5.147],[32,36,5.159,5.815],[36,38,5.827,6.154],[38,39,6.154,6.239],[39,40,6.264,6.373],[40,42,6.385,6.858]]},{"text":"它想做一个没有老板、完全由代码管理的投资基金。","file":"audio/dao-01.mp3","marks":{"nohead":0.839},"dur":4.584,"words":[[0,1,0.099,0.256],[1,2,0.256,0.463],[2,3,0.475,0.62],[3,5,0.62,0.815],[5,7,0.839,1.082],[7,9,1.094,1.579],[10,12,1.87,2.271],[12,13,2.283,2.465],[13,15,2.489,2.793],[15,17,2.805,3.133],[17,18,3.133,3.217],[18,22,3.242,4.031]]},{"text":"可是6月,攻击者利用合约里的一个漏洞,转走了约360万枚以太币。","file":"audio/dao-02.mp3","marks":{"hack":1.167,"drain":3.642},"dur":6.6,"words":[[0,2,0.099,0.366],[2,4,0.378,0.863],[5,8,1.167,1.785],[8,10,1.81,2.089],[10,12,2.101,2.526],[12,13,2.526,2.635],[13,14,2.635,2.708],[14,16,2.732,2.926],[16,18,2.938,3.375],[19,21,3.642,4.031],[21,22,4.031,4.14],[22,23,4.164,4.346],[23,27,4.358,5.268],[27,28,5.268,5.414],[28,29,5.426,5.535],[29,31,5.548,6.033]]},{"text":"社区陷入激烈争论:代码即法律,还是把钱追回来?","file":"audio/dao-03.mp3","marks":{"debate":2.04},"dur":5.04,"words":[[0,2,0.099,0.584],[2,4,0.596,0.972],[4,6,0.997,1.3],[6,8,1.312,1.737],[9,11,2.04,2.38],[11,12,2.404,2.574],[12,14,2.586,3.072],[15,17,3.266,3.509],[17,18,3.521,3.654],[18,19,3.654,3.885],[19,20,3.909,4.091],[20,22,4.091,4.48]]},{"text":"7月20日,以太坊执行硬分叉,让被盗资金回到了可以退还的合约里。","file":"audio/dao-04.mp3","marks":{"fork":1.834},"dur":6.528,"words":[[0,5,0.099,0.984],[6,7,1.227,1.361],[7,9,1.373,1.81],[9,11,1.834,2.137],[11,12,2.162,2.332],[12,14,2.332,2.793],[15,16,3.108,3.278],[16,18,3.29,3.557],[18,20,3.569,4.043],[20,22,4.128,4.504],[22,23,4.504,4.589],[23,25,4.613,4.832],[25,27,4.844,5.244],[27,28,5.244,5.329],[28,30,5.341,5.778],[30,31,5.778,5.984]]},{"text":"不同意的人留在了原来的链上,那条链,就是今天的以太坊经典,ETC。","file":"audio/dao-05.mp3","marks":{"etc":4.407},"dur":6.864,"words":[[0,1,0.099,0.232],[1,3,0.232,0.596],[3,4,0.596,0.73],[4,5,0.73,1.033],[5,6,1.13,1.3],[6,7,1.3,1.482],[7,8,1.482,1.555],[8,10,1.579,1.895],[10,11,1.895,1.967],[11,13,1.98,2.477],[14,15,2.805,2.926],[15,17,2.926,3.448],[18,19,3.679,3.824],[19,20,3.824,3.946],[20,22,3.958,4.31],[22,23,4.31,4.383],[23,24,4.407,4.516],[24,26,4.528,4.892],[26,28,4.904,5.39],[29,32,5.633,6.3]]}]},{"id":"mania","title":"狂潮","year":"2017","lines":[{"text":"危机过后,一个叫ERC-20的代币标准,让任何人都能在以太坊上轻松发行代币。","file":"audio/mania-00.mp3","marks":{"erc20":1.676},"dur":7.68,"words":[[0,2,0.099,0.438],[2,4,0.451,0.924],[5,7,1.167,1.409],[7,8,1.421,1.676],[8,11,1.676,2.004],[12,14,2.101,2.477],[14,15,2.477,2.562],[15,17,2.586,2.878],[17,19,2.89,3.375],[20,21,3.667,3.836],[21,23,3.849,4.225],[23,24,4.225,4.492],[24,25,4.516,4.674],[25,26,4.674,4.832],[26,27,4.832,4.977],[27,28,5.001,5.099],[28,30,5.111,5.511],[30,31,5.511,5.766],[31,33,5.863,6.324],[33,35,6.336,6.664],[35,37,6.676,7.101]]},{"text":"2017年,ICO 狂潮席卷全球,新项目动辄募资数千万美元。","file":"audio/mania-01.mp3","marks":{"ico":1.3},"dur":6.408,"words":[[0,4,0.099,0.742],[4,5,0.742,1.069],[6,9,1.3,1.858],[10,12,1.87,2.295],[12,14,2.319,2.671],[14,16,2.683,3.23],[17,18,3.472,3.679],[18,20,3.679,4.128],[20,22,4.152,4.443],[22,24,4.455,4.807],[24,27,4.832,5.39],[27,29,5.402,5.851]]},{"text":"那年12月,一款养猫游戏“加密猫”,甚至把整个网络堵得水泄不通。","file":"audio/mania-02.mp3","marks":{"cats":1.785},"dur":6.216,"words":[[0,2,0.099,0.438],[2,5,0.463,1.082],[6,7,1.385,1.531],[7,8,1.531,1.761],[8,9,1.785,1.955],[9,10,1.955,2.113],[10,12,2.125,2.489],[13,15,2.514,2.817],[15,16,2.817,3.096],[18,20,3.339,3.618],[20,21,3.63,3.764],[21,23,3.776,4.103],[23,25,4.116,4.552],[25,27,4.577,4.844],[27,31,4.856,5.657]]},{"text":"2018年1月,以太币冲上了1400多美元。","file":"audio/mania-03.mp3","marks":{"peak18":1.616},"dur":4.608,"words":[[0,7,0.099,1.336],[8,9,1.616,1.749],[9,11,1.749,2.271],[11,12,2.295,2.489],[12,13,2.489,2.647],[13,14,2.647,2.72],[14,18,2.744,3.424],[18,19,3.436,3.569],[19,21,3.582,4.043]]},{"text":"但泡沫来得快,去得更快。到年底,它跌到了不足100美元,跌幅超过九成。","file":"audio/mania-04.mp3","marks":{"crash18":2.791},"dur":7.464,"words":[[0,1,0.099,0.256],[1,3,0.268,0.645],[3,5,0.669,0.912],[5,6,0.912,1.227],[7,8,1.446,1.628],[8,9,1.628,1.713],[9,10,1.725,1.931],[10,11,1.931,2.247],[12,13,2.791,2.973],[13,15,2.985,3.495],[16,17,3.762,3.908],[17,19,3.908,4.223],[19,20,4.223,4.296],[20,22,4.32,4.551],[22,27,4.563,5.4],[28,30,5.619,5.995],[30,32,6.019,6.347],[32,34,6.359,6.905]]}]},{"id":"defi","title":"DeFi 之夏","year":"2020","lines":[{"text":"熊市里,建设者们没有离开。","file":"audio/defi-00.mp3","marks":{"builders":1.106},"dur":3.096,"words":[[0,2,0.099,0.62],[2,3,0.62,0.863],[4,7,1.106,1.64],[7,8,1.64,1.761],[8,10,1.785,2.028],[10,12,2.04,2.538]]},{"text":"2020年夏天,去中心化金融,DeFi,突然爆发。","file":"audio/defi-01.mp3","marks":{"defi":1.664},"dur":5.064,"words":[[0,4,0.099,0.754],[4,5,0.754,0.912],[5,7,0.924,1.458],[8,9,1.664,1.834],[9,12,1.846,2.38],[12,14,2.392,2.866],[15,19,3.072,3.509],[20,22,3.703,4.055],[22,24,4.067,4.492]]},{"text":"在 Uniswap 上,不需要交易所就能兑换代币;在借贷协议里,不需要银行就能存款和借款。","file":"audio/defi-02.mp3","marks":{"swap":0.099,"lend":4.055},"dur":8.352,"words":[[0,1,0.099,0.329],[2,9,0.353,1.009],[10,11,1.009,1.288],[12,13,1.543,1.676],[13,15,1.676,1.943],[15,18,1.955,2.562],[18,19,2.659,2.805],[19,20,2.805,2.926],[20,22,2.938,3.266],[22,24,3.266,3.703],[25,26,4.055,4.237],[26,28,4.249,4.528],[28,30,4.54,4.953],[30,31,4.953,5.171],[32,33,5.378,5.511],[33,35,5.511,5.778],[35,37,5.79,6.336],[37,38,6.434,6.579],[38,39,6.579,6.7],[39,41,6.713,7.125],[41,42,7.149,7.271],[42,44,7.283,7.793]]},{"text":"这些协议能像乐高积木一样互相拼接,被称作“货币乐高”。","file":"audio/defi-03.mp3","marks":{"lego":1.409},"dur":5.712,"words":[[0,2,0.099,0.438],[2,4,0.451,0.96],[4,5,1.057,1.203],[5,6,1.203,1.385],[6,10,1.409,2.052],[10,12,2.065,2.477],[12,14,2.574,2.95],[14,16,2.963,3.46],[17,18,3.739,3.885],[18,20,3.897,4.298],[21,23,4.322,4.662],[23,25,4.674,5.135]]},{"text":"同年12月1日,信标链上线,权益证明的新引擎,开始在主链旁边试运行。","file":"audio/defi-04.mp3","marks":{"beacon":1.737},"dur":7.32,"words":[[0,2,0.099,0.523],[2,7,0.548,1.458],[8,11,1.737,2.295],[11,13,2.295,2.805],[14,16,3.023,3.412],[16,18,3.424,3.751],[18,19,3.751,3.824],[19,20,3.849,4.043],[20,22,4.043,4.565],[23,25,4.771,5.086],[25,26,5.086,5.268],[26,28,5.293,5.645],[28,30,5.657,6.057],[30,33,6.082,6.761]]}]},{"id":"burn","title":"燃烧与 NFT","year":"2021","lines":[{"text":"2021年,以太坊迎来了属于自己的高光时刻。","file":"audio/burn-00.mp3","marks":{"spot":3.193},"dur":4.608,"words":[[0,4,0.099,0.802],[4,5,0.802,1.13],[6,7,1.373,1.494],[7,9,1.506,2.028],[9,11,2.052,2.392],[11,12,2.392,2.465],[12,16,2.489,3.084],[16,17,3.084,3.169],[17,19,3.193,3.533],[19,21,3.545,4.043]]},{"text":"3月,数字艺术家 Beeple 的一件NFT 作品,在佳士得拍出了约6900万美元。","file":"audio/burn-01.mp3","marks":{"nft":2.963},"dur":7.8,"words":[[0,2,0.099,0.633],[3,5,0.972,1.264],[5,8,1.276,1.87],[9,15,1.98,2.319],[16,17,2.319,2.404],[17,18,2.417,2.574],[18,19,2.574,2.866],[19,22,2.963,3.594],[23,25,3.606,4.079],[26,27,4.395,4.577],[27,29,4.589,4.916],[29,30,4.917,5.184],[30,32,5.208,5.56],[32,33,5.56,5.669],[33,34,5.693,5.851],[34,39,5.863,6.761],[39,41,6.773,7.222]]},{"text":"8月,伦敦升级上线。其中的 EIP-1559,让每笔交易的基础手续费被直接燃烧销毁。","file":"audio/burn-02.mp3","marks":{"london":0.875,"fire":7.099},"dur":9.072,"words":[[0,2,0.099,0.596],[3,5,0.875,1.227],[5,7,1.251,1.616],[7,9,1.628,2.149],[10,12,2.706,3.107],[12,13,3.107,3.289],[14,17,3.301,3.908],[18,22,4.005,4.83],[23,24,5.097,5.243],[24,25,5.255,5.437],[25,26,5.437,5.595],[26,28,5.607,5.922],[28,29,5.922,6.032],[29,31,6.056,6.359],[31,33,6.371,6.735],[33,34,6.735,7.002],[34,35,7.099,7.269],[35,37,7.282,7.633],[37,39,7.646,7.985],[39,41,7.998,8.507]]},{"text":"以太币第一次有了一股持续的通缩力量。","file":"audio/burn-03.mp3","marks":{"deflation":2.356},"dur":3.72,"words":[[0,1,0.099,0.244],[1,3,0.256,0.693],[3,5,0.717,0.997],[5,6,0.997,1.264],[6,7,1.288,1.446],[7,8,1.446,1.518],[8,9,1.531,1.664],[9,10,1.664,1.834],[10,12,1.858,2.247],[12,13,2.247,2.332],[13,15,2.356,2.72],[15,17,2.732,3.157]]},{"text":"11月,以太币涨到4700多美元,创下当时的历史新高。","file":"audio/burn-04.mp3","marks":{"peak21":1.057},"dur":5.904,"words":[[0,3,0.099,0.778],[4,5,1.057,1.191],[5,7,1.203,1.664],[7,8,1.688,1.882],[8,9,1.883,2.077],[9,13,2.101,2.841],[13,14,2.853,2.975],[14,16,2.987,3.472],[17,19,3.679,4.091],[19,21,4.116,4.455],[21,22,4.455,4.552],[22,24,4.577,4.832],[24,26,4.844,5.341]]}]},{"id":"merge","title":"合并","year":"2022","lines":[{"text":"然而,最难的一步还在后面。","file":"audio/merge-00.mp3","marks":{},"dur":2.952,"words":[[0,2,0.099,0.608],[3,4,0.887,1.118],[4,5,1.118,1.288],[5,6,1.288,1.361],[6,7,1.385,1.482],[7,8,1.482,1.591],[8,9,1.616,1.761],[9,10,1.761,1.883],[10,12,1.895,2.404]]},{"text":"以太坊要把共识机制,从工作量证明,切换到权益证明。","file":"audio/merge-01.mp3","marks":{"pow":2.356,"pos":4.018},"dur":5.448,"words":[[0,1,0.099,0.244],[1,3,0.256,0.717],[3,4,0.742,0.887],[4,5,0.887,1.021],[5,7,1.045,1.385],[7,9,1.397,1.858],[10,11,2.125,2.332],[11,14,2.356,2.817],[14,16,2.829,3.29],[17,19,3.472,3.836],[19,20,3.849,3.994],[20,22,4.018,4.419],[22,24,4.431,4.892]]},{"text":"这就像给一架正在飞行的飞机,在空中更换引擎。","file":"audio/merge-02.mp3","marks":{"engine":2.647},"dur":4.728,"words":[[0,1,0.099,0.293],[1,2,0.293,0.414],[2,3,0.414,0.62],[3,4,0.62,0.742],[4,5,0.754,0.887],[5,6,0.887,1.13],[6,8,1.154,1.47],[8,10,1.482,1.822],[10,11,1.822,1.907],[11,13,1.919,2.404],[14,15,2.647,2.805],[15,17,2.817,3.23],[17,19,3.254,3.618],[19,21,3.63,4.164]]},{"text":"2022年9月15日,合并完成。","file":"audio/merge-03.mp3","marks":{"merge":2.113},"dur":3.552,"words":[[0,10,0.099,1.907],[11,13,2.113,2.477],[13,15,2.489,2.975]]},{"text":"矿机熄灭,验证者接手。以太坊的能耗,下降了约99.95%。","file":"audio/merge-04.mp3","marks":{"mine":0.099,"energy":4.26},"dur":7.224,"words":[[0,2,0.099,0.499],[2,4,0.511,0.984],[5,7,1.227,1.603],[7,8,1.603,1.761],[8,10,1.773,2.319],[11,12,2.876,3.022],[12,14,3.034,3.434],[14,15,3.434,3.507],[15,17,3.519,3.981],[18,20,4.26,4.648],[20,21,4.648,4.745],[21,22,4.769,4.903],[22,28,4.903,6.65]]}]},{"id":"scale","title":"扩容","year":"2023","lines":[{"text":"接下来的问题是:太贵,太挤。","file":"audio/scale-00.mp3","marks":{"jam":1.543},"dur":3.456,"words":[[0,3,0.099,0.572],[3,4,0.572,0.645],[4,6,0.657,0.984],[6,7,0.984,1.312],[8,9,1.543,1.785],[9,10,1.785,2.065],[11,12,2.319,2.574],[12,13,2.574,2.89]]},{"text":"以太坊给出的答案,是二层网络 Rollup:把大量交易放到二层处理,再把结果打包交回主网。","file":"audio/scale-01.mp3","marks":{"l2":1.931,"pack":6.834},"dur":8.592,"words":[[0,1,0.099,0.244],[1,3,0.256,0.645],[3,5,0.669,0.997],[5,6,0.997,1.082],[6,8,1.094,1.518],[9,10,1.725,1.907],[10,11,1.931,2.101],[11,12,2.101,2.283],[12,14,2.295,2.768],[15,21,2.866,3.436],[22,23,3.764,3.921],[23,25,3.933,4.285],[25,27,4.298,4.686],[27,28,4.71,4.892],[28,29,4.892,5.014],[29,30,5.038,5.208],[30,31,5.208,5.402],[31,33,5.414,5.827],[34,35,6.106,6.264],[35,36,6.264,6.385],[36,38,6.397,6.822],[38,40,6.834,7.186],[40,42,7.21,7.574],[42,44,7.574,8.035]]},{"text":"2023年4月,上海升级开放了质押提款。","file":"audio/scale-02.mp3","marks":{"shapella":1.773},"dur":4.512,"words":[[0,7,0.099,1.47],[8,10,1.773,2.125],[10,12,2.137,2.647],[12,14,2.671,3.023],[14,15,3.023,3.108],[15,16,3.133,3.254],[16,17,3.254,3.448],[17,19,3.46,3.933]]},{"text":"2024年3月,坎昆升级引入了 Blob 数据空间,二层网络的手续费大幅下降。","file":"audio/scale-03.mp3","marks":{"dencun":1.7,"fees":4.613},"dur":7.608,"words":[[0,7,0.099,1.458],[8,10,1.7,2.077],[10,12,2.089,2.611],[12,14,2.635,2.987],[14,15,2.987,3.157],[16,20,3.181,3.509],[21,23,3.533,3.836],[23,25,3.849,4.358],[26,27,4.613,4.868],[27,28,4.868,5.05],[28,30,5.062,5.378],[30,31,5.378,5.463],[31,34,5.475,6.118],[34,36,6.215,6.531],[36,38,6.543,7.04]]},{"text":"以太坊正在变成一座多层的城市:主网负责安全与结算,二层负责速度。","file":"audio/scale-04.mp3","marks":{"city":2.04},"dur":6.984,"words":[[0,1,0.099,0.244],[1,3,0.256,0.778],[3,5,0.802,1.069],[5,7,1.082,1.616],[7,8,1.7,1.846],[8,9,1.846,2.016],[9,10,2.04,2.21],[10,11,2.21,2.392],[11,12,2.392,2.465],[12,14,2.477,2.999],[15,17,3.327,3.679],[17,19,3.703,3.97],[19,21,3.982,4.383],[21,22,4.407,4.528],[22,24,4.54,5.026],[25,26,5.256,5.438],[26,27,5.438,5.645],[27,29,5.669,5.936],[29,31,5.948,6.421]]}]},{"id":"wall","title":"走向主流","year":"2024","lines":[{"text":"与此同时,华尔街也来了。","file":"audio/wall-00.mp3","marks":{"wallst":1.094},"dur":2.712,"words":[[0,4,0.099,0.899],[5,8,1.094,1.603],[8,9,1.628,1.749],[9,10,1.749,1.955],[10,11,1.955,2.162]]},{"text":"2024年7月23日,美国现货以太坊 ETF 正式开始交易。","file":"audio/wall-01.mp3","marks":{"etf":2.404},"dur":6.384,"words":[[0,10,0.099,2.065],[11,13,2.404,2.659],[13,15,2.671,3.217],[15,16,3.315,3.46],[16,18,3.472,3.897],[19,22,3.897,4.613],[23,25,4.71,5.05],[25,27,5.062,5.378],[27,29,5.39,5.827]]},{"text":"2025年5月,Pectra 升级上线,质押和钱包体验再次进化。","file":"audio/wall-02.mp3","marks":{"pectra":1.628},"dur":6.048,"words":[[0,7,0.099,1.397],[8,14,1.628,2.125],[15,17,2.15,2.465],[17,19,2.477,2.975],[20,21,3.254,3.436],[21,22,3.436,3.666],[22,23,3.691,3.824],[23,25,3.836,4.188],[25,27,4.2,4.65],[27,29,4.674,5.014],[29,31,5.026,5.487]]},{"text":"同年8月,以太币再创历史新高,日收盘价一度超过4800美元。","file":"audio/wall-03.mp3","marks":{"ath":1.203},"dur":6.768,"words":[[0,2,0.099,0.438],[2,4,0.451,0.924],[5,6,1.203,1.336],[6,8,1.349,1.846],[8,9,1.87,2.052],[9,10,2.052,2.259],[10,12,2.283,2.526],[12,14,2.538,3.023],[15,16,3.327,3.46],[16,19,3.46,4.14],[19,21,4.237,4.54],[21,23,4.552,4.989],[23,29,5.014,6.191]]},{"text":"12月,Fusaka 升级启用 PeerDAS,继续为二层网络扩容。","file":"audio/wall-04.mp3","marks":{"fusaka":1.057},"dur":6.048,"words":[[0,3,0.099,0.79],[4,10,1.057,1.7],[11,13,1.725,2.077],[13,15,2.089,2.489],[16,23,2.514,3.509],[24,26,3.764,4.091],[26,27,4.103,4.285],[27,28,4.31,4.492],[28,29,4.492,4.674],[29,31,4.686,4.989],[31,33,5.001,5.487]]}]},{"id":"now","title":"此刻","year":"2026","lines":[{"text":"而就在今天,2026年10月6日,下一次大升级 Glamsterdam,在 Sepolia 测试网上线。","file":"audio/now-00.mp3","marks":{"today":0.572,"sepolia":5.633},"dur":8.136,"words":[[0,1,0.099,0.268],[1,2,0.281,0.426],[2,3,0.426,0.56],[3,5,0.572,1.069],[6,16,1.312,3.023],[17,18,3.315,3.557],[18,20,3.557,3.8],[20,21,3.824,3.958],[21,23,3.97,4.467],[24,35,4.467,5.39],[36,37,5.633,5.839],[38,45,5.863,6.555],[46,49,6.567,7.089],[49,51,7.089,7.574]]},{"text":"它将带来协议内的提议者与构建者分离,以及区块级访问列表,为主网的下一次扩容铺路。","file":"audio/now-01.mp3","marks":{"epbs":0.73},"dur":8.136,"words":[[0,1,0.099,0.244],[1,2,0.244,0.402],[2,4,0.414,0.705],[4,6,0.73,1.082],[6,7,1.082,1.239],[7,8,1.239,1.324],[8,11,1.349,2.004],[11,12,2.101,2.247],[12,14,2.259,2.623],[14,15,2.623,2.768],[15,17,2.781,3.278],[18,20,3.533,3.909],[20,23,3.933,4.504],[23,25,4.528,4.856],[25,27,4.868,5.378],[28,31,5.607,6.104],[31,32,6.104,6.177],[32,33,6.201,6.444],[33,35,6.444,6.748],[35,37,6.772,7.112],[37,39,7.124,7.561]]},{"text":"此刻,以太币的价格约为2700美元,距离高点仍有不小的距离。","file":"audio/now-02.mp3","marks":{"pnow":2.465},"dur":6.576,"words":[[0,2,0.099,0.572],[3,4,0.887,1.021],[4,6,1.033,1.409],[6,7,1.409,1.494],[7,9,1.506,2.052],[9,10,2.137,2.295],[10,11,2.295,2.441],[11,17,2.465,3.642],[18,20,3.921,4.176],[20,21,4.188,4.395],[21,22,4.395,4.698],[22,23,4.795,4.977],[23,24,4.977,5.135],[24,25,5.159,5.256],[25,26,5.256,5.463],[26,27,5.463,5.548],[27,29,5.56,6.009]]},{"text":"但这条链,依然在一刻不停地出块。","file":"audio/now-03.mp3","marks":{"blocks":1.167},"dur":3.504,"words":[[0,1,0.099,0.268],[1,2,0.281,0.414],[2,3,0.414,0.645],[3,4,0.645,0.912],[5,7,1.167,1.543],[7,8,1.543,1.7],[8,10,1.725,2.004],[10,12,2.016,2.368],[12,13,2.368,2.453],[13,14,2.465,2.647],[14,15,2.647,2.95]]}]},{"id":"end","title":"结语","year":"∞","lines":[{"text":"从一个19岁年轻人的想法,到一台全球共享的计算机;","file":"audio/end-00.mp3","marks":{"globe":3.035},"dur":5.088,"words":[[0,1,0.099,0.293],[1,3,0.305,0.499],[3,6,0.523,1.106],[6,9,1.118,1.603],[9,10,1.603,1.676],[10,12,1.688,2.174],[13,14,2.441,2.586],[14,15,2.599,2.732],[15,16,2.732,3.011],[16,18,3.035,3.424],[18,20,3.436,3.8],[20,21,3.8,3.885],[21,24,3.897,4.528]]},{"text":"它经历过黑客、分裂、泡沫与寒冬,也完成了最艰难的一次引擎更换。","file":"audio/end-01.mp3","marks":{"s1":0.717,"s2":1.458,"s3":2.137,"s4":4.067},"dur":6.48,"words":[[0,1,0.099,0.244],[1,3,0.256,0.572],[3,4,0.572,0.693],[4,6,0.717,1.251],[7,9,1.458,1.955],[10,12,2.137,2.55],[12,13,2.574,2.671],[13,15,2.683,3.193],[16,17,3.472,3.606],[17,19,3.618,3.946],[19,20,3.946,4.043],[20,21,4.067,4.261],[21,23,4.261,4.613],[23,24,4.613,4.686],[24,26,4.698,5.014],[26,30,5.038,5.912]]},{"text":"以太坊的故事,还远没有写完。","file":"audio/end-02.mp3","marks":{"open":1.458},"dur":3.072,"words":[[0,1,0.099,0.244],[1,3,0.256,0.645],[3,4,0.645,0.717],[4,6,0.73,1.251],[7,8,1.458,1.603],[8,9,1.603,1.773],[9,11,1.785,1.992],[11,13,2.004,2.514]]},{"text":"你觉得下一个十年,它会走向哪里?欢迎在评论区聊聊。","file":"audio/end-03.mp3","marks":{"cta":3.301},"dur":5.448,"words":[[0,1,0.099,0.268],[1,3,0.268,0.475],[3,4,0.499,0.717],[4,6,0.717,0.887],[6,7,0.899,1.142],[7,8,1.142,1.446],[9,10,1.64,1.785],[10,11,1.785,1.931],[11,13,1.943,2.295],[13,15,2.307,2.756],[16,18,3.301,3.726],[18,19,3.726,3.883],[19,22,3.908,4.405],[22,24,4.417,4.891]]},{"text":"本视频仅作科普,不构成任何投资建议。我们下期见。","file":"audio/end-04.mp3","marks":{"bye":0.099},"dur":5.592,"words":[[0,1,0.099,0.268],[1,3,0.268,0.766],[3,4,0.79,0.984],[4,5,0.984,1.118],[5,7,1.13,1.64],[8,9,1.87,1.992],[9,11,1.992,2.356],[11,13,2.38,2.708],[13,15,2.72,3.035],[15,17,3.048,3.521],[18,20,4.078,4.296],[20,21,4.308,4.527],[21,23,4.527,5.061]]}]}]; diff --git a/ethereum/tools/build_voice.py b/ethereum/tools/build_voice.py new file mode 100644 index 0000000000000000000000000000000000000000..3526170fe3621f0e92dcc36efa7109d9b3b71a29 --- /dev/null +++ b/ethereum/tools/build_voice.py @@ -0,0 +1,199 @@ +# -*- coding: utf-8 -*- +""" +以太坊简史 · 旁白构建 +文案中用 {标记} 标出画面同步点 → edge-tts 逐词时间戳 → 标记换算成秒 +输出:audio/*.mp3 + js/data-script.js +""" +import asyncio, json, os, re +import edge_tts +from mutagen.mp3 import MP3 + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +VOICE = dict(voice='zh-CN-XiaoxiaoNeural', rate='+3%', pitch='+0Hz') + +CHAPTERS = [ + ('open', '序章', '2013', [ + '{dark}2013年冬天,{spark}一个19岁的年轻人,写下了一份白皮书。', + '他叫{name}维塔利克·布特林。', + '那时没有人想到,这份文件会长成一个{grow}承载数千亿美元价值的网络。', + '接下来的六分钟,我们一起{title}走完以太坊的十三年。', + ]), + ('origin', '起源', '2013', [ + '故事要从比特币说起。', + '比特币很伟大,但它更像一台{calc}计算器:功能简单,只专注于记账和转账。', + '维塔利克想的是:如果区块链能运行{code}任何程序呢?', + '那它就不再是计算器,而是一台{world}全世界共享的计算机。', + '运行在上面的程序,叫{contract}智能合约:规则写进代码,条件一满足,就{auto}自动执行,不需要任何中间人。', + ]), + ('ico', '众筹', '2014', [ + '2014年1月,以太坊在{miami}迈阿密的比特币大会上正式亮相。', + '同年7月22日,{sale}以太坊开启公开众筹,持续了六周。', + '每枚以太币,价格大约{price}0.31美元。', + '最终募得约{raise}1830万美元,是当时规模最大的众筹项目之一。', + '团队在瑞士成立了{found}以太坊基金会,开始了一年的紧张开发。', + ]), + ('genesis', '创世', '2015', [ + '2015年7月30日,{boot}以太坊主网 Frontier 正式启动。', + '第0号区块,{block0}创世区块诞生。', + '从这一刻起,{chain}新区块每隔十几秒就产生一个,链条开始生长。', + '那时候,一枚以太币{p2015}还不到3美元。', + ]), + ('dao', '至暗时刻', '2016', [ + '2016年,一个叫{dao}The DAO 的项目,在以太坊上募集了价值约1.5亿美元的以太币。', + '它想做一个{nohead}没有老板、完全由代码管理的投资基金。', + '可是6月,{hack}攻击者利用合约里的一个漏洞,{drain}转走了约360万枚以太币。', + '社区陷入激烈争论:{debate}代码即法律,还是把钱追回来?', + '7月20日,以太坊{fork}执行硬分叉,让被盗资金回到了可以退还的合约里。', + '不同意的人留在了原来的链上,那条链,就是今天的{etc}以太坊经典,ETC。', + ]), + ('mania', '狂潮', '2017', [ + '危机过后,一个叫{erc20}ERC-20的代币标准,让任何人都能在以太坊上轻松发行代币。', + '2017年,{ico}ICO 狂潮席卷全球,新项目动辄募资数千万美元。', + '那年12月,一款{cats}养猫游戏“加密猫”,甚至把整个网络堵得水泄不通。', + '2018年1月,{peak18}以太币冲上了1400多美元。', + '但泡沫来得快,去得更快。{crash18}到年底,它跌到了不足100美元,跌幅超过九成。', + ]), + ('defi', 'DeFi 之夏', '2020', [ + '熊市里,{builders}建设者们没有离开。', + '2020年夏天,{defi}去中心化金融,DeFi,突然爆发。', + '{swap}在 Uniswap 上,不需要交易所就能兑换代币;{lend}在借贷协议里,不需要银行就能存款和借款。', + '这些协议能像{lego}乐高积木一样互相拼接,被称作“货币乐高”。', + '同年12月1日,{beacon}信标链上线,权益证明的新引擎,开始在主链旁边试运行。', + ]), + ('burn', '燃烧与 NFT', '2021', [ + '2021年,以太坊迎来了属于自己的{spot}高光时刻。', + '3月,数字艺术家 Beeple 的一件{nft}NFT 作品,在佳士得拍出了约6900万美元。', + '8月,{london}伦敦升级上线。其中的 EIP-1559,让每笔交易的基础手续费{fire}被直接燃烧销毁。', + '以太币第一次有了一股持续的{deflation}通缩力量。', + '11月,{peak21}以太币涨到4700多美元,创下当时的历史新高。', + ]), + ('merge', '合并', '2022', [ + '然而,最难的一步还在后面。', + '以太坊要把共识机制,从{pow}工作量证明,切换到{pos}权益证明。', + '这就像给一架正在飞行的飞机,{engine}在空中更换引擎。', + '2022年9月15日,{merge}合并完成。', + '{mine}矿机熄灭,验证者接手。以太坊的能耗,{energy}下降了约99.95%。', + ]), + ('scale', '扩容', '2023', [ + '接下来的问题是:{jam}太贵,太挤。', + '以太坊给出的答案,是{l2}二层网络 Rollup:把大量交易放到二层处理,再把结果{pack}打包交回主网。', + '2023年4月,{shapella}上海升级开放了质押提款。', + '2024年3月,{dencun}坎昆升级引入了 Blob 数据空间,{fees}二层网络的手续费大幅下降。', + '以太坊正在变成一座{city}多层的城市:主网负责安全与结算,二层负责速度。', + ]), + ('wall', '走向主流', '2024', [ + '与此同时,{wallst}华尔街也来了。', + '2024年7月23日,{etf}美国现货以太坊 ETF 正式开始交易。', + '2025年5月,{pectra}Pectra 升级上线,质押和钱包体验再次进化。', + '同年8月,{ath}以太币再创历史新高,日收盘价一度超过4800美元。', + '12月,{fusaka}Fusaka 升级启用 PeerDAS,继续为二层网络扩容。', + ]), + ('now', '此刻', '2026', [ + '而就在{today}今天,2026年10月6日,下一次大升级 Glamsterdam,{sepolia}在 Sepolia 测试网上线。', + '它将带来{epbs}协议内的提议者与构建者分离,以及区块级访问列表,为主网的下一次扩容铺路。', + '此刻,以太币的价格约为{pnow}2700美元,距离高点仍有不小的距离。', + '但这条链,{blocks}依然在一刻不停地出块。', + ]), + ('end', '结语', '∞', [ + '从一个19岁年轻人的想法,到一台{globe}全球共享的计算机;', + '它经历过{s1}黑客、{s2}分裂、{s3}泡沫与寒冬,也完成了{s4}最艰难的一次引擎更换。', + '以太坊的故事,{open}还远没有写完。', + '你觉得下一个十年,它会走向哪里?{cta}欢迎在评论区聊聊。', + '{bye}本视频仅作科普,不构成任何投资建议。我们下期见。', + ]), +] + +MARK = re.compile(r'\{([a-z0-9_]+)\}') + + +def parse(raw): + marks, out, i = [], '', 0 + for m in MARK.finditer(raw): + out += raw[i:m.start()] + marks.append((m.group(1), len(out))) + i = m.end() + out += raw[i:] + return out, marks + + +async def synth(text, path, sem): + async with sem: + for k in range(5): + try: + c = edge_tts.Communicate(text, boundary='WordBoundary', **VOICE) + words, audio = [], bytearray() + async for ch in c.stream(): + if ch['type'] == 'audio': + audio.extend(ch['data']) + elif ch['type'] == 'WordBoundary': + words.append((ch['text'], ch['offset'] / 1e7, ch['duration'] / 1e7)) + open(path, 'wb').write(bytes(audio)) + return words + except Exception as e: # noqa + print('retry', path, e) + await asyncio.sleep(1 + k) + raise RuntimeError('tts failed: ' + path) + + +def align(text, words): + """把 TTS 单词映射回字符区间 [c0,c1,t0,t1]""" + res, cur = [], 0 + for w, t0, d in words: + w2 = w.strip() + if not w2: + continue + j = text.find(w2, cur) + if j < 0 or j - cur > 12: + continue + res.append([j, j + len(w2), round(t0, 3), round(t0 + d, 3)]) + cur = j + len(w2) + return res + + +async def main(): + os.makedirs(os.path.join(ROOT, 'audio'), exist_ok=True) + sem = asyncio.Semaphore(6) + jobs, data = [], [] + for cid, title, year, lines in CHAPTERS: + ch = dict(id=cid, title=title, year=year, lines=[]) + for i, raw in enumerate(lines): + text, marks = parse(raw) + fn = f'audio/{cid}-{i:02d}.mp3' + ln = dict(text=text, file=fn, marks=marks) + ch['lines'].append(ln) + jobs.append((ln, os.path.join(ROOT, fn))) + data.append(ch) + + async def run(ln, path): + cache = path + '.json' + if os.path.exists(cache) and os.path.exists(path): + c = json.load(open(cache, encoding='utf-8')) + if c.get('text') == ln['text'] and c.get('voice') == VOICE: + ln['_words'] = c['words']; return + words = await synth(ln['text'], path, sem) + json.dump(dict(text=ln['text'], voice=VOICE, words=words), open(cache, 'w', encoding='utf-8'), ensure_ascii=False) + ln['_words'] = words + await asyncio.gather(*[run(l, p) for l, p in jobs]) + + total = 0 + for ch in data: + for ln in ch['lines']: + ln['dur'] = round(MP3(os.path.join(ROOT, ln['file'])).info.length, 3) + ln['words'] = align(ln['text'], ln.pop('_words')) + mk = {} + for name, pos in ln['marks']: + t = None + for c0, c1, t0, t1 in ln['words']: + if c1 > pos: + t = t0 if c0 >= pos else t0 + (t1 - t0) * (pos - c0) / max(1, c1 - c0) + break + if t is None: + t = ln['dur'] * pos / max(1, len(ln['text'])) + mk[name] = round(t, 3) + ln['marks'] = mk + total += ln['dur'] + js = '// 自动生成:tools/build_voice.py —— 请勿手改\nwindow.ETH_SCRIPT = ' + json.dumps(data, ensure_ascii=False, separators=(',', ':')) + ';\n' + open(os.path.join(ROOT, 'js', 'data-script.js'), 'w', encoding='utf-8').write(js) + print('chapters', len(data), 'lines', sum(len(c['lines']) for c in data), 'speech seconds', round(total, 1)) + +asyncio.run(main()) diff --git a/ethereum/vendor/mediabunny.min.mjs b/ethereum/vendor/mediabunny.min.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3eaef18975c051b34d3968ea036d7bb4cf476ba7 --- /dev/null +++ b/ethereum/vendor/mediabunny.min.mjs @@ -0,0 +1,50 @@ +/*! + * Copyright (c) 2026-present, Vanilagy and contributors + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ +var If=Object.create;var Sl=Object.defineProperty;var Ef=Object.getOwnPropertyDescriptor;var vf=Object.getOwnPropertyNames;var _f=Object.getPrototypeOf,Rf=Object.prototype.hasOwnProperty;var Tl=(i,t)=>(t=Symbol[i])?t:Symbol.for("Symbol."+i),wl=i=>{throw TypeError(i)};var Ff=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports);var Mf=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of vf(t))!Rf.call(i,n)&&n!==e&&Sl(i,n,{get:()=>t[n],enumerable:!(r=Ef(t,n))||r.enumerable});return i};var Al=(i,t,e)=>(e=i!=null?If(_f(i)):{},Mf(t||!i||!i.__esModule?Sl(e,"default",{value:i,enumerable:!0}):e,i));var st=(i,t,e)=>{if(t!=null){typeof t!="object"&&typeof t!="function"&&wl("Object expected");var r,n;e&&(r=t[Tl("asyncDispose")]),r===void 0&&(r=t[Tl("dispose")],e&&(n=r)),typeof r!="function"&&wl("Object not disposable"),n&&(r=function(){try{n.call(this)}catch(a){return Promise.reject(a)}}),i.push([e,r,t])}else e&&i.push([e]);return t},ot=(i,t,e)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(s,o,c,u){return u=Error(c),u.name="SuppressedError",u.error=s,u.suppressed=o,u},n=s=>t=e?new r(s,t,"An error was suppressed during disposal"):(e=!0,s),a=s=>{for(;s=i.pop();)try{var o=s[1]&&s[1].call(s[2]);if(s[0])return Promise.resolve(o).then(a,c=>(n(c),a()))}catch(c){n(c)}if(e)throw t};return a()};var iu=Ff(()=>{});function g(i){if(!i)throw new Error("Assertion failed.")}var Ba=Math.PI/180,Oa=180/Math.PI,mr=i=>{let t=(i%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw new Error(`Invalid rotation ${i}.`)},Dr=[1,0,0,0,1,0,0,0,1],Da=(i,t,e)=>{let[r,n,,a,s]=i,o=Math.abs(r)*t+Math.abs(a)*e,c=Math.abs(n)*t+Math.abs(s)*e;return Lt(Lt(xl(-t/2,-e/2),i),xl(o/2,c/2))},fi=i=>{let[t,e]=i,r=Math.atan2(e,uc(i)?-t:t);return mr(La(r*Oa,90))},uc=i=>{let[t,e,,r,n]=i;return t*n-e*r<0},qi=i=>{let t=i*Ba,e=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[e,r,0,-r,e,0,0,0,1]},xl=(i,t)=>[1,0,0,0,1,0,i,t,1],Va=(i,t)=>[i,0,0,0,t,0,0,0,1],Lt=(i,t)=>{let e=new Array(9);for(let r=0;r<3;r++)for(let n=0;n<3;n++)e[3*r+n]=i[3*r]*t[n]+i[3*r+1]*t[3+n]+i[3*r+2]*t[6+n];return e},Ua=(i,t,e,r)=>({rotation:mr(i+(t?-e:e)),flip:t!==r}),Z=i=>i&&i[i.length-1],Wt=i=>i>=0&&i<2**32,Pl=i=>i>=-(2**31)&&i<2**31,B=i=>{let t=0;for(;i.readBits(1)===0&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<{let e=t+1,r=Math.floor(Math.log2(e));i.writeBits(r,0),i.writeBits(1,1),i.writeBits(r,e-2**r)},Ht=i=>{let t=B(i);return(t&1)===0?-(t>>1):t+1>>1},Il=(i,t,e,r)=>{for(let n=t;n>e-n-1<i.constructor===Uint8Array?i:ArrayBuffer.isView(i)?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i),N=i=>i.constructor===DataView?i:ArrayBuffer.isView(i)?new DataView(i.buffer,i.byteOffset,i.byteLength):new DataView(i),Bf=typeof globalThis.TextEncoder<"u"?globalThis.TextEncoder:class{constructor(){this.encoding="utf-8"}encode(t=""){let e=new Uint8Array(3*t.length),r=0;for(let n=0;n>6,e[r++]=128|a&63;else if(a<55296||a>57343)e[r++]=224|a>>12,e[r++]=128|a>>6&63,e[r++]=128|a&63;else{let s=n+1=56320&&s<=57343?(a=65536+(a-55296<<10)+(s-56320),n++,e[r++]=240|a>>18,e[r++]=128|a>>12&63,e[r++]=128|a>>6&63,e[r++]=128|a&63):(e[r++]=239,e[r++]=191,e[r++]=189)}}return e.slice(0,r)}},hi=typeof globalThis.TextDecoder<"u"?globalThis.TextDecoder:class{constructor(t="utf-8"){let e=t.trim().toLowerCase();if(e==="utf-8"||e==="utf8"||e==="unicode-1-1-utf-8")this.encoding="utf-8";else if(e==="utf-16le"||e==="utf-16")this.encoding="utf-16le";else if(e==="utf-16be")this.encoding="utf-16be";else throw new RangeError(`The encoding label provided ('${t}') is invalid.`)}decode(t){let e=t?$(t):new Uint8Array(0),r=[];if(this.encoding==="utf-8"){let a=e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191?3:0;for(;a=194&&s<224)o=1,c=s&31;else if(s>=224&&s<240)o=2,c=s&15;else if(s>=240&&s<245)o=3,c=s&7;else{r.push(65533),a++;continue}let u=s===224?160:s===240?144:128,l=s===237?159:s===244?143:191,d=1;for(;d<=o;d++){let m=a+dl)break;c=c<<6|m&63,u=128,l=191}a+=d,d<=o?r.push(65533):c>=65536?(c-=65536,r.push(55296|c>>10,56320|c&1023)):r.push(c)}}else{let a=this.encoding==="utf-16le",s=a?255:254,o=a?254:255,c=e.length>=2&&e[0]===s&&e[1]===o?2:0;for(;c+1=55296&&u<=56319){let l=c+1=56320&&l<=57343?(r.push(u,l),c+=2):r.push(65533)}else u>=56320&&u<=57343?r.push(65533):r.push(u)}c{for(let t=0;t255)return!1;return!0},lc=i=>Object.fromEntries(Object.entries(i).map(([t,e])=>[e,t])),Pt={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ut=lc(Pt),It={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},lt=lc(It),Et={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},dt=lc(Et),Ki=i=>!!i&&!!i.primaries&&!!i.transfer&&!!i.matrix&&i.fullRange!==void 0,za=i=>!i||i.primaries==null&&i.transfer==null&&i.matrix==null&&i.fullRange==null,Na={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},fr=i=>i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer||ArrayBuffer.isView(i),Le=class{constructor(){this.currentPromise=Promise.resolve();this.pending=0}async acquire(){let t,e=new Promise(n=>{let a=!1;t=()=>{a||(n(),this.pending--,a=!0)}}),r=this.currentPromise;return this.currentPromise=e,this.pending++,await r,t}},El=/^[0-9a-fA-F]+$/,Vr=i=>[...i].map(t=>t.toString(16).padStart(2,"0")).join(""),vl=i=>{g(i.length%2===0);let t=new Uint8Array(i.length/2);for(let e=0;e(i=i>>1&1431655765|(i&1431655765)<<1,i=i>>2&858993459|(i&858993459)<<2,i=i>>4&252645135|(i&252645135)<<4,i=i>>8&16711935|(i&16711935)<<8,i=i>>16&65535|(i&65535)<<16,i>>>0),pr=(i,t,e)=>{let r=0,n=i.length-1,a=-1;for(;r<=n;){let s=r+n>>1,o=e(i[s]);o===t?(a=s,n=s-1):o{let r=0,n=i.length-1,a=-1;for(;r<=n;){let s=r+(n-r+1)/2|0;e(i[s])<=t?(a=s,r=s+1):n=s-1}return a},mc=(i,t,e)=>{let r=Q(i,e(t),e);i.splice(r+1,0,t)},J=()=>{let i,t;return{promise:new Promise((r,n)=>{i=r,t=n}),resolve:i,reject:t}},Qi=(i,t)=>{let e=i.indexOf(t);e!==-1&&i.splice(e,1)},fc=(i,t)=>{for(let e=i.length-1;e>=0;e--)if(t(i[e]))return i[e]},Ur=(i,t)=>{for(let e=i.length-1;e>=0;e--)if(t(i[e]))return e;return-1},_l=async function*(i){Symbol.iterator in i?yield*i[Symbol.iterator]():yield*i[Symbol.asyncIterator]()},Rl=i=>{if(!(Symbol.iterator in i)&&!(Symbol.asyncIterator in i))throw new TypeError("Argument must be an iterable or async iterable.")},ne=i=>{throw new Error(`Unexpected value: ${i}`)},gi=(i,t,e)=>{let r=i.getUint8(t),n=i.getUint8(t+1),a=i.getUint8(t+2);return e?r|n<<8|a<<16:r<<16|n<<8|a},Fl=(i,t,e)=>gi(i,t,e)<<8>>8,bi=(i,t,e,r)=>{e=e>>>0,e=e&16777215,r?(i.setUint8(t,e&255),i.setUint8(t+1,e>>>8&255),i.setUint8(t+2,e>>>16&255)):(i.setUint8(t,e>>>16&255),i.setUint8(t+1,e>>>8&255),i.setUint8(t+2,e&255))},Ml=(i,t,e,r)=>{e=ee(e,-8388608,8388607),e<0&&(e=e+16777216&16777215),bi(i,t,e,r)},Bl=(i,t,e,r)=>{r?(i.setUint32(t+0,e,!0),i.setInt32(t+4,Math.floor(e/2**32),!0)):(i.setInt32(t+0,Math.floor(e/2**32),!0),i.setUint32(t+4,e,!0))},zn=(i,t)=>({async next(){let e=await i.next();return e.done?{value:void 0,done:!0}:{value:t(e.value),done:!1}},return(){return i.return()},throw(e){return i.throw(e)},[Symbol.asyncIterator](){return this}}),ee=(i,t,e)=>Math.max(t,Math.min(e,i)),Ol=(i,t,e)=>i+(t-i)*e,pc=(i,t)=>i-Math.floor(i/t)*t,se="und",hr=i=>{let t=Math.round(i);return Math.abs(i/t-1)<10*Number.EPSILON?t:i},La=(i,t)=>Math.round(i/t)*t,qt=(i,t)=>Math.round(i*t)/t,Wa=(i,t)=>Math.floor(i/t)*t,hc=(i,t)=>Math.floor(i*t)/t,Dl=i=>{let t=0;for(;i;)t++,i>>=1;return t},Ha=i=>{let t=0;for(;i!==0;)i&=i-1,t++;return t},Of=/^[a-z]{3}$/,gr=i=>Of.test(i),Kt=1e6*(1+Number.EPSILON),gc=(i,t)=>{let e={...i,...t};if(i.headers||t.headers){let r=i.headers?Ma(i.headers):{},n=t.headers?Ma(t.headers):{},a={...r};Object.entries(n).forEach(([s,o])=>{let c=Object.keys(a).find(u=>u.toLowerCase()===s.toLowerCase());c&&delete a[c],a[s]=o}),e.headers=a}return e},Ma=i=>{if(i instanceof Headers){let t={};return i.forEach((e,r)=>{t[r]=e}),t}if(Array.isArray(i)){let t={};return i.forEach(([e,r])=>{t[e]=r}),t}return i},bc=async(i,t,e,r,n)=>{let a=0;for(;;)try{return await i(t,e)}catch(s){if(n())throw s;a++;let o=r(a,s,t);if(o===null)throw s;if(z._error("Retrying failed fetch. Error:",s),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await zr(1e3*o),n())throw s}},Vl=(i,t)=>{let e=i<0?-1:1;i=Math.abs(i);let r=0,n=1,a=1,s=0,o=i;for(;;){let c=Math.floor(o),u=c*a+r,l=c*s+n;if(l>t)return{num:e*a,den:s};if(r=a,n=s,a=u,s=l,o=1/(o-c),!isFinite(o))break}return{num:e*a,den:s}},Or=class{constructor(){this.currentPromise=Promise.resolve()}call(t){return this.currentPromise=this.currentPromise.then(t)}},ac=null,Qt=()=>ac!==null?ac:ac=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),sc=null,yi=()=>sc!==null?sc:sc=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),oc=null,Nn=()=>oc!==null?oc:oc=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent)));var Gi=i=>typeof globalThis.isSecureContext<"u"&&!globalThis.isSecureContext?`${i} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`:`${i} is not available in this environment.`,Ul=i=>i instanceof DOMException&&i.name==="QuotaExceededError"&&/reclaimed/i.test(i.message),Df=(async()=>{})().constructor,_=i=>i instanceof Df||i instanceof Promise?!0:typeof i?.then=="function",ki=(i,t)=>i!==-1?i:t,qa=(i,t,e,r)=>i<=r&&e<=t,vt=function*(i){for(let t in i){let e=i[t];e!==void 0&&(yield{key:t,value:e})}},zl=i=>{switch(i.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},Ti=i=>{let t=atob(i),e=new Uint8Array(t.length);for(let r=0;r{let t="";for(let e=0;e{if(i.length!==t.length)return!1;for(let e=0;e{Symbol.dispose??=Symbol("Symbol.dispose")},ve=i=>typeof i=="number"&&!Number.isNaN(i),we=(i,t)=>{if(t.includes("://"))return t;if(i.includes("://")){let o=i.indexOf("?");o!==-1&&(i=i.slice(0,o))}let e;if(t.startsWith("/")){let o=i.indexOf("://");if(o===-1)e=t;else{let c=i.indexOf("/",o+3);c===-1?e=i+t:e=i.slice(0,c)+t}}else{let o=i.lastIndexOf("/");o===-1?e=t:e=i.slice(0,o+1)+t}let r="",n=e.indexOf("://");if(n!==-1){let o=e.indexOf("/",n+3);o!==-1&&(r=e.slice(0,o),e=e.slice(o))}let a=e.split("/"),s=[];for(let o of a)o===".."?s.pop():o!=="."&&s.push(o);return r+s.join("/")},Ll=(i,t)=>{let e=i.indexOf("?");if(e===-1)return null;let r=i.indexOf("#",e),n=i.slice(e+1,r===-1?void 0:r);for(let a of n.split("&")){let s=a.indexOf("="),o=s===-1?a:a.slice(0,s);if(decodeURIComponent(o)!==t)continue;let c=s===-1?"":a.slice(s+1);return decodeURIComponent(c)}return null},wi=(i,t)=>{let e=0;for(let r=0;r{let e=-1,r=1/0;for(let n=0;n{let e=-1,r=-1/0;for(let n=0;nr&&(r=a,e=n)}return e},Gt=i=>{g(Number.isInteger(i.num)),g(Number.isInteger(i.den)),g(i.den!==0);let t=Math.abs(i.num),e=Math.abs(i.den);for(;e!==0;){let n=t%e;t=e,e=n}let r=t||1;return{num:i.num/r,den:i.den/r}},Qa=(i,t)=>{if(typeof i!="object"||!i)throw new TypeError(`${t} must be an object.`);if(!Number.isInteger(i.left)||i.left<0)throw new TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(i.top)||i.top<0)throw new TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(i.width)||i.width<0)throw new TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(i.height)||i.height<0)throw new TypeError(`${t}.height must be a non-negative integer.`)},Un,Vf=1,Cl=new Map,yc=new Map,Hl=()=>typeof window>"u",Uf=()=>{let i=new Map,t=new Map;self.onmessage=e=>{let r=e.data;switch(r.type){case"set-timeout":{let n=setTimeout(()=>{i.delete(r.timerId),self.postMessage({type:"fire",timerId:r.timerId})},r.delay);i.set(r.timerId,n)}break;case"set-interval":{let n=setInterval(()=>{self.postMessage({type:"fire",timerId:r.timerId})},r.delay);t.set(r.timerId,n)}break;case"clear-timeout":{let n=i.get(r.timerId);n!==void 0&&(clearTimeout(n),i.delete(r.timerId))}break;case"clear-interval":{let n=t.get(r.timerId);n!==void 0&&(clearInterval(n),t.delete(r.timerId))}break}}},ql=()=>{if(Un)return Un;let i=`(${Uf.toString()})();`,t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));return Un=new Worker(t),URL.revokeObjectURL(t),Un.onmessage=e=>{let r=e.data,n=Cl.get(r.timerId);if(n){Cl.delete(r.timerId),n();return}let a=yc.get(r.timerId);a&&a()},Un};var Kl=(i,t)=>{if(Hl())return{id:setInterval(i,t)};let e=Vf++;return yc.set(e,()=>{i()}),ql().postMessage({type:"set-interval",timerId:e,delay:t}),{id:e}},Ql=i=>{if(Hl()){clearInterval(i.id);return}g(typeof i.id=="number"),yc.delete(i.id),ql().postMessage({type:"clear-interval",timerId:i.id})},zr=i=>new Promise(t=>setTimeout(t,i));var jt=i=>Array.isArray(i)?i:[i],ct=class{constructor(){this._listeners=new Map}on(t,e,r){this._listeners.has(t)||this._listeners.set(t,new Set);let n={fn:e,once:r?.once??!1};return this._listeners.get(t).add(n),()=>{this._listeners.get(t)?.delete(n)}}_emit(...t){let[e,r]=t,n=this._listeners.get(e);if(n)for(let a of n){try{a.fn(r)}catch(s){console.error(s)}a.once&&n.delete(a)}}},Si=i=>Math.ceil(i/2)*2,cc=class{constructor(t){this._queue=[];this._errored=!1;this.parallelism=t}get errored(){return this._errored}get inFlightCount(){return this._queue.length}async run(t){for(this._errored&&await Promise.race(this._queue);this._queue.length>=this.parallelism;)await Promise.race(this._queue);let e=t();this._queue.push(e),e.then(()=>Qi(this._queue,e)).catch(()=>this._errored=!0)}async flush(){await Promise.all(this._queue)}},Ga=i=>i!==null&&typeof i=="object"&&Object.getPrototypeOf(i)===Object.prototype&&Object.values(i).every(t=>typeof t=="string");var Gl=(n=>(n[n.Silent=0]="Silent",n[n.Errors=1]="Errors",n[n.Warnings=2]="Warnings",n[n.Info=3]="Info",n))(Gl||{}),$e=class $e{constructor(){}static get level(){return $e._level}static set level(t){if(t!==0&&t!==1&&t!==2&&t!==3)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");$e._level=t}static get _emitter(){return $e._emitterInstance??=new ct}static on(t,e,r){return $e._emitter.on(t,e,r)}static _error(...t){$e._emitter._emit("error",t),$e._level>=1&&console.error(...t)}static _warn(...t){$e._emitter._emit("warn",t),$e._level>=2&&console.warn(...t)}static _info(...t){$e._emitter._emit("info",t),$e._level>=3&&console.info(...t)}};$e._level=3,$e._emitterInstance=null;var z=$e;var yt=class{constructor(t,e){this.data=t;this.mimeType=e;if(!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof e!="string")throw new TypeError("mimeType must be a string.")}},Nr=class{constructor(t,e,r,n){this.data=t;this.mimeType=e;this.name=r;this.description=n;if(!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(e!==void 0&&typeof e!="string")throw new TypeError("mimeType, when provided, must be a string.");if(r!==void 0&&typeof r!="string")throw new TypeError("name, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("description, when provided, must be a string.")}},Ln=i=>{if(!i||typeof i!="object")throw new TypeError("tags must be an object.");if(i.title!==void 0&&typeof i.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(i.description!==void 0&&typeof i.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(i.artist!==void 0&&typeof i.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(i.album!==void 0&&typeof i.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(i.albumArtist!==void 0&&typeof i.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(i.trackNumber!==void 0&&(!Number.isInteger(i.trackNumber)||i.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(i.tracksTotal!==void 0&&(!Number.isInteger(i.tracksTotal)||i.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(i.discNumber!==void 0&&(!Number.isInteger(i.discNumber)||i.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(i.discsTotal!==void 0&&(!Number.isInteger(i.discsTotal)||i.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(i.genre!==void 0&&typeof i.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(i.date!==void 0&&(!(i.date instanceof Date)||Number.isNaN(i.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(i.beatsPerMinute!==void 0&&(!Number.isInteger(i.beatsPerMinute)||i.beatsPerMinute<=0))throw new TypeError("tags.beatsPerMinute, when provided, must be a positive integer.");if(i.lyrics!==void 0&&typeof i.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(i.images!==void 0){if(!Array.isArray(i.images))throw new TypeError("tags.images, when provided, must be an array.");for(let t of i.images){if(!t||typeof t!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(t.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof t.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(t.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(i.comment!==void 0&&typeof i.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(i.raw!==void 0){if(!i.raw||typeof i.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(let t of Object.values(i.raw))if(t!==null&&typeof t!="string"&&!(Array.isArray(t)&&t.every(e=>typeof e=="string"))&&!(t instanceof Uint8Array)&&!(t instanceof yt)&&!(t instanceof Nr)&&!Ga(t))throw new TypeError("Each value in tags.raw must be a string, string array, Uint8Array, RichImageData, AttachedFile, Record, or null.")}},br=i=>i.title===void 0&&i.description===void 0&&i.artist===void 0&&i.album===void 0&&i.albumArtist===void 0&&i.trackNumber===void 0&&i.tracksTotal===void 0&&i.discNumber===void 0&&i.discsTotal===void 0&&i.genre===void 0&&i.beatsPerMinute===void 0&&i.date===void 0&&i.lyrics===void 0&&(!i.images||i.images.length===0)&&i.comment===void 0&&(i.raw===void 0||Object.keys(i.raw).length===0),_e={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},jl=i=>{if(!i||typeof i!="object")throw new TypeError("disposition must be an object.");if(i.default!==void 0&&typeof i.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(i.primary!==void 0&&typeof i.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(i.forced!==void 0&&typeof i.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(i.original!==void 0&&typeof i.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(i.commentary!==void 0&&typeof i.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(i.hearingImpaired!==void 0&&typeof i.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(i.visuallyImpaired!==void 0&&typeof i.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};var H=class i{constructor(t){this.bytes=t;this.pos=0}seekToByte(t){this.pos=8*t}readBit(){let t=Math.floor(this.pos/8),e=this.bytes[t]??0,r=7-(this.pos&7),n=(e&1<>r;return this.pos++,n}readBits(t){if(t===1)return this.readBit();let e=0;for(let r=0;r>r-n-1<0&&this.writeBits(n,e.readBits(n))}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let t=this.pos/8,e=this.bytes[t]??0;return this.pos+=8,e}skipBits(t){this.pos+=t}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let t=new i(this.bytes);return t.pos=this.pos,t}};var kt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Xt=[-1,1,2,3,4,5,6,8],$t=i=>{if(!i||i.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let t=new H(i),e=kc(t),{frequencyIndex:r,sampleRate:n}=Tc(t),a=t.readBits(4),s=null;a>=1&&a<=7&&(s=Xt[a]);let o=e,c=!1,u=n;if(e===5||e===29)c=e===29,u=Tc(t).sampleRate,o=kc(t),o===22&&t.skipBits(4);else for(;t.getBitsLeft()>15;){let l=t.pos;if(t.readBits(11)!==695){t.pos=l+1;continue}kc(t)===5&&t.readBits(1)&&(u=Tc(t).sampleRate,t.getBitsLeft()>11&&t.readBits(11)===1352&&(c=!!t.readBits(1)));break}return s!==null&&s>1&&(c=!1),{objectType:e,coreObjectType:o,frequencyIndex:r,channelConfiguration:a,outputSampleRate:u,outputNumberOfChannels:c&&s===1?2:s}},kc=i=>{let t=i.readBits(5);return t===31?32+i.readBits(6):t},Tc=i=>{let t=i.readBits(4);return t===15?{frequencyIndex:t,sampleRate:i.readBits(24)}:{frequencyIndex:t,sampleRate:t{let t=i.objectType===5||i.objectType===29,e=i.objectType===29,r=t?i.outputSampleRate/2:i.outputSampleRate,n=e?1:i.outputNumberOfChannels,a=Xt.indexOf(n);if(a===-1)throw new TypeError(`Unsupported number of channels: ${i.outputNumberOfChannels}`);let s=16;i.objectType>=32&&(s+=6),wc(r)===15&&(s+=24),t&&(s+=9,wc(i.outputSampleRate)===15&&(s+=24));let o=Math.ceil(s/8),c=new Uint8Array(o),u=new H(c);return Xl(u,i.objectType),$l(u,r),u.writeBits(4,a),t&&($l(u,i.outputSampleRate),Xl(u,2)),u.writeBits(3,0),c},Xl=(i,t)=>{t<32?i.writeBits(5,t):(i.writeBits(5,31),i.writeBits(6,t-32))},$l=(i,t)=>{let e=wc(t);i.writeBits(4,e),e===15&&i.writeBits(24,t)},wc=i=>{let t=kt.indexOf(i);return t===-1?15:t},ja=i=>{let t=new Uint8Array(7),e=new H(t),{coreObjectType:r,frequencyIndex:n,channelConfiguration:a}=i,s=r-1;return e.writeBits(12,4095),e.writeBits(1,0),e.writeBits(2,0),e.writeBits(1,1),e.writeBits(2,s),e.writeBits(4,n),e.writeBits(1,0),e.writeBits(3,a),e.writeBits(1,0),e.writeBits(1,0),e.writeBits(1,0),e.writeBits(1,0),e.skipBits(13),e.writeBits(11,2047),e.writeBits(2,0),{header:t,bitstream:e}},Xa=(i,t)=>{i.pos=30,i.writeBits(13,t)};var Ai=[48e3,44100,32e3],Sc=[24e3,22050,16e3];var zf="1.61.3",yr=`Mediabunny v${zf}`;var Lr=function*(i){let t=0,e=-1;for(;t=i.length-2)break;t=r;let n=0;if(t+3e&&(yield{offset:e,length:t-e}),e=t+n,t=e}e!==-1&&e{if(t.description){let n=($(t.description)[4]&3)+1;return Ya(i,n)}else return Lr(i)},Yt=i=>i&31,Za=i=>{let t=[],e=i.length;for(let r=0;r{let t=[],e=0;for(let r of i)e===2&&r<=3&&(t.push(3),e=0),t.push(r),e=r===0?e+1:0;return new Uint8Array(t)},Ac=new Uint8Array([0,0,0,1]),qn=i=>{let t=i.reduce((n,a)=>n+Ac.byteLength+a.byteLength,0),e=new Uint8Array(t),r=0;for(let n of i)e.set(Ac,r),r+=Ac.byteLength,e.set(n,r),r+=n.byteLength;return e},Ja=(i,t)=>{let e=i.reduce((a,s)=>a+t+s.byteLength,0),r=new Uint8Array(e),n=0;for(let a of i){let s=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:s.setUint8(n,a.byteLength);break;case 2:s.setUint16(n,a.byteLength,!1);break;case 3:bi(s,n,a.byteLength,!1);break;case 4:s.setUint32(n,a.byteLength,!1);break}n+=t,r.set(a,n),n+=a.byteLength}return r},ed=(i,t)=>{if(t.description){let n=($(t.description)[4]&3)+1;return Ja(i,n)}else return qn(i)},Zt=i=>{try{let t=[],e=[],r=[];for(let o of Lr(i)){let c=i.subarray(o.offset,o.offset+o.length),u=Yt(c[0]);u===7?t.push(c):u===8?e.push(c):u===13&&r.push(c)}if(t.length===0||e.length===0)return null;let n=t[0],a=Jt(n);g(a!==null);let s=a.profileIdc===100||a.profileIdc===110||a.profileIdc===122||a.profileIdc===144;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:e,chromaFormat:s?a.chromaFormatIdc:null,bitDepthLumaMinus8:s?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:s?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:s?r:null}}catch(t){return z._error("Error building AVC Decoder Configuration Record:",t),null}},es=i=>{let t=[];t.push(i.configurationVersion),t.push(i.avcProfileIndication),t.push(i.profileCompatibility),t.push(i.avcLevelIndication),t.push(252|i.lengthSizeMinusOne&3),t.push(224|i.sequenceParameterSets.length&31);for(let e of i.sequenceParameterSets){let r=e.byteLength;t.push(r>>8),t.push(r&255);for(let n=0;n>8),t.push(r&255);for(let n=0;n>8),t.push(r&255);for(let n=0;n{try{let t=N(i),e=0,r=t.getUint8(e++),n=t.getUint8(e++),a=t.getUint8(e++),s=t.getUint8(e++),o=t.getUint8(e++)&3,c=t.getUint8(e++)&31,u=[];for(let f=0;f{try{let t=Za(i),e=new H(t);if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let n=e.readAlignedByte(),a=e.readAlignedByte(),s=e.readAlignedByte();B(e);let o=1,c=0,u=0,l=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(o=B(e),o===3&&(l=e.readBits(1)),c=B(e),u=B(e),e.skipBits(1),e.readBits(1))){for(let U=0;U<(o!==3?8:12);U++)if(e.readBits(1)){let ie=U<6?16:64,pe=8,Ie=8;for(let Nt=0;NtNt.level>=s)??Z(Hn),Ie=Math.min(Math.floor(pe.maxDpbMbs/(U*ie)),16);S=Ie,I=Ie}}return g(I!==null),{emulationUnpreventedBytes:t,profileIdc:n,constraintFlags:a,levelIdc:s,frameMbsOnlyFlag:k,chromaFormatIdc:o,bitDepthLumaMinus8:c,bitDepthChromaMinus8:u,codedWidth:p,codedHeight:b,displayWidth:h,displayHeight:y,pixelAspectRatio:P,colourPrimaries:w,matrixCoefficients:x,transferCharacteristics:A,fullRangeFlag:C,numReorderFrames:S,maxDecFrameBuffering:I,vuiParametersFlagBitOffset:F,bitstreamRestrictionFlagBitOffset:E,bitstreamRestrictionFlag:v}}catch(t){return z._error("Error parsing AVC SPS:",t),null}},Yl=i=>{let t=B(i);i.skipBits(4),i.skipBits(4);for(let e=0;e<=t;e++)B(i),B(i),i.skipBits(1);i.skipBits(5),i.skipBits(5),i.skipBits(5),i.skipBits(5)},Cc=i=>{g(i.bitstreamRestrictionFlag!==1);let t=new Uint8Array(i.emulationUnpreventedBytes.byteLength+64),e=new H(i.emulationUnpreventedBytes),r=new H(t);i.bitstreamRestrictionFlag===null?(r.copyBits(i.vuiParametersFlagBitOffset,e),r.writeBits(1,1),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0)):(g(i.bitstreamRestrictionFlagBitOffset!==null),r.copyBits(i.bitstreamRestrictionFlagBitOffset,e)),r.writeBits(1,1),r.writeBits(1,1),pi(r,2),pi(r,1),pi(r,16),pi(r,16),pi(r,i.numReorderFrames),pi(r,i.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);let n=r.pos/8;return g(Number.isInteger(n)),Nf(t.subarray(0,n))},Lf=(i,t)=>{if(t.description){let n=($(t.description)[21]&3)+1;return Ja(i,n)}else return qn(i)},Wn=(i,t)=>{if(t.description){let n=($(t.description)[21]&3)+1;return Ya(i,n)}else return Lr(i)},_t=i=>i>>1&63,xi=i=>{try{let t=new H(Za(i));t.skipBits(16),t.readBits(4);let e=t.readBits(3),r=t.readBits(1),{general_profile_space:n,general_tier_flag:a,general_profile_idc:s,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:u}=Wf(t,e);B(t);let l=B(t),d=0;l===3&&(d=t.readBits(1));let m=B(t),f=B(t),p=m,b=f;if(t.readBits(1)){let v=B(t),F=B(t),O=B(t),D=B(t),U=1,K=1,ie=d===0?l:0;ie===1?(U=2,K=2):ie===2&&(U=2,K=1),p-=(v+F)*U,b-=(O+D)*K}let h=B(t),y=B(t);B(t);let T=t.readBits(1)?0:e,w=0;for(let v=T;v<=e;v++)B(t),w=B(t),B(t);B(t),B(t),B(t),B(t),B(t),B(t),t.readBits(1)&&t.readBits(1)&&Hf(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),B(t),B(t),t.skipBits(1));let A=B(t);if(qf(t,A),t.readBits(1)){let v=B(t);for(let F=0;F{try{let t=[],e=[],r=[],n=[];for(let u of Lr(i)){let l=i.subarray(u.offset,u.offset+u.length),d=_t(l[0]);d===32?t.push(l):d===33?e.push(l):d===34?r.push(l):(d===39||d===40)&&n.push(l)}if(e.length===0||r.length===0)return null;let a=xi(e[0]);if(!a)return null;let s=0;if(r.length>0){let u=r[0],l=new H(Za(u));l.skipBits(16),B(l),B(l),l.skipBits(1),l.skipBits(1),l.skipBits(3),l.skipBits(1),l.skipBits(1),B(l),B(l),Ht(l),l.skipBits(1),l.skipBits(1),l.readBits(1)&&B(l),Ht(l),Ht(l),l.skipBits(1),l.skipBits(1),l.skipBits(1),l.skipBits(1);let d=l.readBits(1),m=l.readBits(1);!d&&!m?s=0:d&&!m?s=2:!d&&m?s=3:s=0}let o=[...t.length?[{arrayCompleteness:1,nalUnitType:32,nalUnits:t}]:[],...e.length?[{arrayCompleteness:1,nalUnitType:33,nalUnits:e}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:34,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:_t(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:a.generalProfileSpace,generalTierFlag:a.generalTierFlag,generalProfileIdc:a.generalProfileIdc,generalProfileCompatibilityFlags:a.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:a.generalConstraintIndicatorFlags,generalLevelIdc:a.generalLevelIdc,minSpatialSegmentationIdc:a.minSpatialSegmentationIdc,parallelismType:s,chromaFormatIdc:a.chromaFormatIdc,bitDepthLumaMinus8:a.bitDepthLumaMinus8,bitDepthChromaMinus8:a.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:a.spsMaxSubLayersMinus1+1,temporalIdNested:a.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(t){return z._error("Error building HEVC Decoder Configuration Record:",t),null}},Wf=(i,t)=>{let e=i.readBits(2),r=i.readBits(1),n=i.readBits(5),a=0;for(let l=0;l<32;l++)a=a<<1|i.readBits(1);let s=new Uint8Array(6);for(let l=0;l<6;l++)s[l]=i.readBits(8);let o=i.readBits(8),c=[],u=[];for(let l=0;l0)for(let l=t;l<8;l++)i.skipBits(2);for(let l=0;l{for(let t=0;t<4;t++)for(let e=0;e<(t===3?2:6);e++)if(!i.readBits(1))B(i);else{let n=Math.min(64,1<<4+(t<<1));t>1&&Ht(i);for(let a=0;a{let e=[];for(let r=0;r{let n=0,a=0,s=0;if(t!==0&&(a=i.readBits(1)),a){if(t===e){let c=B(i);s=t-(c+1)}else s=t-1;i.readBits(1),B(i);let o=r[s]??0;for(let c=0;c<=o;c++)i.readBits(1)||i.readBits(1);n=r[s]}else{let o=B(i),c=B(i);for(let u=0;u{let e=2,r=2,n=2,a=0,s=0,o={num:1,den:1};if(i.readBits(1)){let c=i.readBits(8);if(c===255)o={num:i.readBits(16),den:i.readBits(16)};else{let u=td[c];u&&(o=u)}}return i.readBits(1)&&i.readBits(1),i.readBits(1)&&(i.readBits(3),a=i.readBits(1),i.readBits(1)&&(e=i.readBits(8),r=i.readBits(8),n=i.readBits(8))),i.readBits(1)&&(B(i),B(i)),i.readBits(1),i.readBits(1),i.readBits(1),i.readBits(1)&&(B(i),B(i),B(i),B(i)),i.readBits(1)&&(i.readBits(32),i.readBits(32),i.readBits(1)&&B(i),i.readBits(1)&&Gf(i,!0,t)),i.readBits(1)&&(i.readBits(1),i.readBits(1),i.readBits(1),s=B(i),B(i),B(i),B(i),B(i)),{pixelAspectRatio:o,colourPrimaries:e,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:a,minSpatialSegmentationIdc:s}},Gf=(i,t,e)=>{let r=!1,n=!1,a=!1;t&&(r=i.readBits(1)===1,n=i.readBits(1)===1,(r||n)&&(a=i.readBits(1)===1,a&&(i.readBits(8),i.readBits(5),i.readBits(1),i.readBits(5)),i.readBits(4),i.readBits(4),a&&i.readBits(4),i.readBits(5),i.readBits(5),i.readBits(5)));for(let s=0;s<=e;s++){let o=i.readBits(1)===1,c=!0;o||(c=i.readBits(1)===1);let u=!1;c?B(i):u=i.readBits(1)===1;let l=1;u||(l=B(i)+1),r&&Zl(i,l,a),n&&Zl(i,l,a)}},Zl=(i,t,e)=>{for(let r=0;r{let t=[];t.push(i.configurationVersion),t.push((i.generalProfileSpace&3)<<6|(i.generalTierFlag&1)<<5|i.generalProfileIdc&31),t.push(i.generalProfileCompatibilityFlags>>>24&255),t.push(i.generalProfileCompatibilityFlags>>>16&255),t.push(i.generalProfileCompatibilityFlags>>>8&255),t.push(i.generalProfileCompatibilityFlags&255),t.push(...i.generalConstraintIndicatorFlags),t.push(i.generalLevelIdc&255),t.push(240|i.minSpatialSegmentationIdc>>8&15),t.push(i.minSpatialSegmentationIdc&255),t.push(252|i.parallelismType&3),t.push(252|i.chromaFormatIdc&3),t.push(248|i.bitDepthLumaMinus8&7),t.push(248|i.bitDepthChromaMinus8&7),t.push(i.avgFrameRate>>8&255),t.push(i.avgFrameRate&255),t.push((i.constantFrameRate&3)<<6|(i.numTemporalLayers&7)<<3|(i.temporalIdNested&1)<<2|i.lengthSizeMinusOne&3),t.push(i.arrays.length&255);for(let e of i.arrays){t.push((e.arrayCompleteness&1)<<7|0|e.nalUnitType&63),t.push(e.nalUnits.length>>8&255),t.push(e.nalUnits.length&255);for(let r of e.nalUnits){t.push(r.length>>8&255),t.push(r.length&255);for(let n=0;n{try{let t=N(i),e=0,r=t.getUint8(e++),n=t.getUint8(e++),a=n>>6&3,s=n>>5&1,o=n&31,c=t.getUint32(e,!1);e+=4;let u=i.subarray(e,e+6);e+=6;let l=t.getUint8(e++),d=(t.getUint8(e++)&15)<<8|t.getUint8(e++),m=t.getUint8(e++)&3,f=t.getUint8(e++)&3,p=t.getUint8(e++)&7,b=t.getUint8(e++)&7,h=t.getUint16(e,!1);e+=2;let y=t.getUint8(e++),k=y>>6&3,T=y>>3&7,w=y>>2&1,A=y&3,x=t.getUint8(e++),C=[];for(let P=0;P>7&1,E=S&63,v=t.getUint16(e,!1);e+=2;let F=[];for(let O=0;O{let e=new Set,r=0;for(let a of Wn(i,t)){if(r===4){e.add(a.offset);continue}let s=_t(i[a.offset]);if(r===3&&s!==37){e.add(a.offset);continue}let o=!1;s===35?r>0?o=!0:r=1:s<=31?r>2?o=!0:r=2:s===36?r!==2?o=!0:r=3:s===37?r<2?o=!0:r=4:s===32||s===33||s===34||s===39||s>=41&&s<=44||s>=48&&s<=55?r>1?o=!0:r=1:(s===38||s===40||s>=45&&s<=47||s>=56&&s<=63)&&r<2&&(o=!0),o&&e.add(a.offset)}if(e.size===0)return null;let n=[];for(let a of Wn(i,t))e.has(a.offset)||n.push(i.subarray(a.offset,a.offset+a.length));return Lf(n,t)},jf={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},Zi=i=>{let t=new H(i);if(t.readBits(2)!==2)return null;let r=t.readBits(1),a=(t.readBits(1)<<1)+r;if(a===3&&t.skipBits(1),t.readBits(1)===1||t.readBits(1)!==0||(t.skipBits(2),t.readBits(24)!==4817730))return null;let u=8;a>=2&&(u=t.readBits(1)?12:10);let l=t.readBits(3),d=0,m=0;if(l!==7)if(m=t.readBits(1),a===1||a===3){let P=t.readBits(1),S=t.readBits(1);d=!P&&!S?3:P&&!S?2:1,t.skipBits(1)}else d=1;else d=3,m=1;let f=t.readBits(16),p=t.readBits(16),b=f+1,h=p+1,y=b*h,k=Z(kr).level;for(let C of kr)if(y<=C.maxPictureSize){k=C.level;break}let T=jf[l],w=T?.colourPrimaries??2,A=T?.transferCharacteristics??2,x=T?.matrixCoefficients??2;return{profile:a,level:k,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:m,colourPrimaries:w,transferCharacteristics:A,matrixCoefficients:x}},nd=i=>i.colourPrimaries!==2||i.transferCharacteristics!==2||i.matrixCoefficients!==2,ad=function*(i){let t=new H(i),e=()=>{let r=0;for(let n=0;n<8;n++){let a=t.readAlignedByte();if(r+=(a&127)*2**(n*7),!(a&128))break;if(n===7&&a&128)return null}return r>2**32-1?null:r};for(;t.getBitsLeft()>=8;){t.skipBits(1);let r=t.readBits(4),n=t.readBits(1),a=t.readBits(1);t.skipBits(1),n&&t.skipBits(8);let s;if(a){let o=e();if(o===null)return;s=o}else s=Math.floor(t.getBitsLeft()/8);g(t.pos%8===0),yield{type:r,data:i.subarray(t.pos/8,t.pos/8+s)},t.skipBits(s*8)}},Ci=i=>{for(let{type:t,data:e}of ad(i)){if(t!==1)continue;let r=new H(e),n=r.readBits(3),a=r.readBits(1),s=r.readBits(1),o=0,c=0,u=0;if(s)o=r.readBits(5);else{let I=r.readBits(1),E=0;if(I){if(r.skipBits(32),r.skipBits(32),r.readBits(1)){let D=0;for(;D<32&&!r.readBits(1);)D++;D<32&&r.skipBits(D)}E=r.readBits(1),E&&(u=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5))}let v=r.readBits(1),F=r.readBits(5);for(let O=0;O<=F;O++){r.skipBits(12);let D=r.readBits(5);if(O===0&&(o=D),D>7){let U=r.readBits(1);O===0&&(c=U)}if(E&&r.readBits(1)){let K=u+1;r.skipBits(K),r.skipBits(K),r.skipBits(1)}v&&r.readBits(1)&&r.skipBits(4)}}let l=r.readBits(4),d=r.readBits(4),m=l+1;r.skipBits(m);let f=d+1;r.skipBits(f);let p=0;if(s?p=0:p=r.readBits(1),p&&(r.skipBits(4),r.skipBits(3)),r.skipBits(1),r.skipBits(1),r.skipBits(1),!s){r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);let I=r.readBits(1);I&&(r.skipBits(1),r.skipBits(1));let E=r.readBits(1),v=0;E?v=2:v=r.readBits(1),v>0&&(r.readBits(1)||r.skipBits(1)),I&&r.skipBits(3)}r.skipBits(1),r.skipBits(1),r.skipBits(1);let b=r.readBits(1),h=8;n===2&&b?h=r.readBits(1)?12:10:n<=2&&(h=b?10:8);let y=0;n!==1&&(y=r.readBits(1));let k=2,T=2,w=2;r.readBits(1)&&(k=r.readBits(8),T=r.readBits(8),w=r.readBits(8));let x=0,C=1,P=1,S=0;return y?x=r.readBits(1):k===1&&T===13&&w===0?(x=1,C=0,P=0):(x=r.readBits(1),n===0?(C=1,P=1):n===1?(C=0,P=0):h===12?(C=r.readBits(1),P=C?r.readBits(1):0):(C=1,P=0),C&&P&&(S=r.readBits(2))),{profile:n,level:o,tier:c,bitDepth:h,monochrome:y,chromaSubsamplingX:C,chromaSubsamplingY:P,chromaSamplePosition:S,videoFullRangeFlag:x,colourPrimaries:k,transferCharacteristics:T,matrixCoefficients:w}}return null},ts=i=>i.colourPrimaries!==2||i.transferCharacteristics!==2||i.matrixCoefficients!==2,rs=i=>{if(i.length<36)return null;let e=N(i);return e.getUint32(4)!==1768124518||e.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:e.getUint8(22),transferCharacteristics:e.getUint8(23),matrixCoefficients:e.getUint8(24)}},Hr=i=>{let t=N(i),e=t.getUint8(9),r=t.getUint16(10,!0),n=t.getUint32(12,!0),a=t.getInt16(16,!0),s=t.getUint8(18),o=null;return s&&(o=i.subarray(19,21+e)),{outputChannelCount:e,preSkip:r,inputSampleRate:n,outputGain:a,channelMappingFamily:s,channelMappingTable:o}},Xf=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],sd=i=>{let t=i[0]>>3,e=i[0]&3,r;return e===0?r=1:e===1||e===2?r=2:r=i[1]&63,{durationInSamples:Xf[t]*r}},is=i=>{if(i.length<7)throw new Error("Setup header is too short.");if(i[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...i.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let e=i.length,r=new Uint8Array(e);for(let d=0;d97;)if(n.readBits(1)===1){a=n.pos;break}if(a===0)throw new Error("Invalid Setup header: framing bit not found.");let s=0,o=!1,c=0;for(;n.getBitsLeft()>=97;){let d=n.pos,m=n.readBits(8),f=n.readBits(16),p=n.readBits(16);if(m>63||f!==0||p!==0){n.pos=d;break}if(n.skipBits(1),s++,s>64)break;n.clone().readBits(6)+1===s&&(o=!0,c=s)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let u=c;n.pos=0,n.skipBits(a);let l=Array(u).fill(0);for(let d=u-1;d>=0;d--)n.skipBits(40),l[d]=n.readBits(1);return{modeBlockflags:l}},qr=(i,t,e)=>{switch(i){case"avc":{for(let r of xc(e,t)){let n=e[r.offset],a=Yt(n);if(a>=1&&a<=4)return"delta";if(a===5)return"key";if(a===6&&!Nn()){let s=e.subarray(r.offset,r.offset+r.length),o=Za(s),c=1;do{let u=0;for(;;){let m=o[c++];if(m===void 0||(u+=m,m<255))break}let l=0;for(;;){let m=o[c++];if(m===void 0||(l+=m,m<255))break}if(u===6){let m=new H(o);m.pos=8*c;let f=B(m),p=m.readBits(1);if(f===0&&p===1)return"key"}c+=l}while(c{let e=N(i),r=0,n=e.getUint32(r,!0);r+=4;let a=ye.decode(i.subarray(r,r+n));r+=n,n>0&&(t.raw??={},t.raw.vendor??=a);let s=e.getUint32(r,!0);r+=4;for(let o=0;o0&&(t.trackNumber??=p),b&&Number.isInteger(b)&&b>0&&(t.tracksTotal??=b)}break;case"TRACKTOTAL":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(t.tracksTotal??=f)}break;case"DISCNUMBER":{let f=m.split("/"),p=Number.parseInt(f[0],10),b=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(t.discNumber??=p),b&&Number.isInteger(b)&&b>0&&(t.discsTotal??=b)}break;case"DISCTOTAL":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(t.discsTotal??=f)}break;case"DATE":{let f=new Date(m);Number.isNaN(f.getTime())||(t.date??=f)}break;case"BPM":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(t.beatsPerMinute??=f)}break;case"GENRE":t.genre??=m;break;case"METADATA_BLOCK_PICTURE":{let f=Ti(m),p=N(f),b=p.getUint32(0,!1),h=p.getUint32(4,!1),y=String.fromCharCode(...f.subarray(8,8+h)),k=p.getUint32(8+h,!1),T=ye.decode(f.subarray(12+h,12+h+k)),w=p.getUint32(h+k+28),A=f.subarray(h+k+32,h+k+32+w);t.images??=[],t.images.push({data:A,mimeType:y,kind:b===3?"coverFront":b===4?"coverBack":"unknown",name:void 0,description:T||void 0})}break}}},Qn=(i,t,e)=>{let r=[i],n=Y.encode(yr),a=new Uint8Array(4+n.length),s=new DataView(a.buffer);s.setUint32(0,n.length,!0),a.set(n,4),r.push(a);let o=[],c=(f,p)=>{let b=`${f}=${p}`,h=Y.encode(b);a=new Uint8Array(4+h.length),s=new DataView(a.buffer),s.setUint32(0,h.length,!0),a.set(h,4),r.push(a),o.push(f)};for(let{key:f,value:p}of vt(t))switch(f){case"title":c("TITLE",p);break;case"description":c("DESCRIPTION",p);break;case"artist":c("ARTIST",p);break;case"album":c("ALBUM",p);break;case"albumArtist":c("ALBUMARTIST",p);break;case"genre":c("GENRE",p);break;case"date":c("DATE",p.toISOString().slice(0,10));break;case"comment":c("COMMENT",p);break;case"lyrics":c("LYRICS",p);break;case"trackNumber":c("TRACKNUMBER",p.toString());break;case"tracksTotal":c("TRACKTOTAL",p.toString());break;case"discNumber":c("DISCNUMBER",p.toString());break;case"discsTotal":c("DISCTOTAL",p.toString());break;case"beatsPerMinute":c("BPM",p.toString());break;case"images":{if(!e)break;for(let b of p){let h=b.kind==="coverFront"?3:b.kind==="coverBack"?4:0,y=new Uint8Array(b.mimeType.length);for(let x=0;xtypeof h=="string"))for(let h of p)c(f,h)}}let u=new Uint8Array(4);N(u).setUint32(0,o.length,!0),r.splice(2,0,u);let l=r.reduce((f,p)=>f+p.length,0),d=new Uint8Array(l),m=0;for(let f of r)d.set(f,m),m+=f.length;return d},Gn=[2,1,2,3,3,4,4,5],ns=i=>{if(i.length<7||i[0]!==11||i[1]!==119)return null;let t=new H(i);t.skipBits(16),t.skipBits(16);let e=t.readBits(2);if(e===3)return null;let r=t.readBits(6),n=t.readBits(5);if(n>8)return null;let a=t.readBits(3),s=t.readBits(3);(s&1)!==0&&s!==1&&t.skipBits(2),(s&4)!==0&&t.skipBits(2),s===2&&t.skipBits(2);let o=t.readBits(1),c=Math.floor(r/2);return{fscod:e,bsid:n,bsmod:a,acmod:s,lfeon:o,bitRateCode:c}},od=[64*2,69*2,96*2,64*2,70*2,96*2,80*2,87*2,120*2,80*2,88*2,120*2,96*2,104*2,144*2,96*2,105*2,144*2,112*2,121*2,168*2,112*2,122*2,168*2,128*2,139*2,192*2,128*2,140*2,192*2,160*2,174*2,240*2,160*2,175*2,240*2,192*2,208*2,288*2,192*2,209*2,288*2,224*2,243*2,336*2,224*2,244*2,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],cd=1536,jn=new Uint8Array([5,4,65,67,45,51]),Xn=new Uint8Array([5,4,69,65,67,51]),Pc=[1,2,3,6],as=i=>{if(i.length<6||i[0]!==11||i[1]!==119)return null;let t=new H(i);t.skipBits(16);let e=t.readBits(2);if(t.skipBits(3),e!==0&&e!==2)return null;let r=t.readBits(11),n=t.readBits(2),a=0,s;n===3?(a=t.readBits(2),s=3):s=t.readBits(2);let o=t.readBits(3),c=t.readBits(1),u=t.readBits(5);if(u<11||u>16)return null;let l=Pc[s],d;return n<3?d=Ai[n]/1e3:d=Sc[a]/1e3,{dataRate:Math.round((r+1)*d/(l*16)),substreams:[{fscod:n,fscod2:a,bsid:u,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},ud=i=>{if(i.length<2)return null;let t=new H(i),e=t.readBits(13),r=t.readBits(3),n=[];for(let a=0;a<=r&&!(Math.ceil(t.pos/8)+3>i.length);a++){let s=t.readBits(2),o=t.readBits(5);t.skipBits(1),t.skipBits(1);let c=t.readBits(3),u=t.readBits(3),l=t.readBits(1);t.skipBits(3);let d=t.readBits(4),m=0;d>0?m=t.readBits(9):t.skipBits(1),n.push({fscod:s,fscod2:null,bsid:o,bsmod:c,acmod:u,lfeon:l,numDepSub:d,chanLoc:m})}return n.length===0?null:{dataRate:e,substreams:n}},ss=i=>{let t=i.substreams[0];return g(t),t.fscod<3?Ai[t.fscod]:t.fscod2!==null&&t.fscod2<3?Sc[t.fscod2]:null},os=i=>{let t=i.substreams[0];g(t);let e=Gn[t.acmod]+t.lfeon;if(t.numDepSub>0){let r=[2,2,1,1,2,2,2,1,1];for(let n=0;n<9;n++)t.chanLoc&1<<8-n&&(e+=r[n])}return e};var $f=1683496997,$n=18,cs=10,ld=4096,Jl=32,us=20,Yf=8,Zf=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Jf=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],ep=[16,16,20,20,0,24,24,0],$a=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],tp=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],rp=8,ip=44646,np=[32e3,44100,48e3,0],ap=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],dd=[512,1024,2048,4096],Yn=i=>{let t=Ic(i),e=N(i),r=t?Math.ceil(t.frameSize/4)*4:0,n=null;for(;r+4<=i.length&&e.getUint32(r)===$f;){let s=Zn(i.subarray(r));if(!s)break;n??=s,r+=s.frameSize}if(t)return{frameSize:n?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:n!==null};if(!n?.asset)return null;let{asset:a}=n;return{frameSize:r,sampleRate:a.sampleRate,numberOfChannels:a.numberOfChannels,sampleCount:a.sampleCount,channelLayout:a.channelLayout,pcmResolution:a.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},ls=i=>{let t=Yn(i);return t?.core?t.hasExtensions?"dtsh":"dtsc":null},Ic=i=>{if(i.length<$n||i[0]!==127||i[1]!==254||i[2]!==128||i[3]!==1)return null;let t=new H(i);if(t.skipBits(32),t.skipBits(1),t.readBits(5)!==Jl-1)return null;let e=t.readBits(1),r=t.readBits(7)+1;if(r%Yf!==0)return null;let n=t.readBits(14)+1;if(n<96)return null;let a=t.readBits(6);if(a>=$a.length)return null;let s=Zf[t.readBits(4)];if(s===0)return null;let o=Jf[t.readBits(5)];if(t.readBits(1)!==0)return null;t.skipBits(4),t.skipBits(5);let c=t.readBits(2);if(c===3)return null;t.skipBits(1),e&&t.skipBits(16),t.skipBits(7);let u=ep[t.readBits(3)];if(u===0)return null;let l=c!==0;return{frameSize:n,sampleRate:s,numberOfChannels:$a[a]+(l?1:0),sampleCount:r*Jl,channelLayout:tp[a]|(l?rp:0),amode:a,lfePresent:l,bitRate:o,pcmResolution:u}},Zn=i=>{if(i.length2&&t.skipBits(1),b>6&&t.skipBits(1),t.readBits(1))){let y=t.readBits(2)+1<<2;h=t.readBits(y)}return c===0||t.getBitsLeft()<0?o:{frameSize:s,asset:{sampleRate:p,numberOfChannels:b,sampleCount:Math.round(u*p/c),channelLayout:h,pcmResolution:f}}},md=i=>{if(i.length{let t=new Uint8Array(us),e=N(t);e.setUint32(0,i.sampleRate),e.setUint32(4,i.bitRate),e.setUint32(8,i.bitRate),t[12]=i.pcmResolution;let r=i.core&&!i.hasExtensions?1:0,n=new H(t);return n.seekToByte(13),n.writeBits(2,Math.max(dd.indexOf(i.sampleCount),0)),n.writeBits(5,r),n.writeBits(1,i.core?.lfePresent?1:0),n.writeBits(6,i.core?.amode??0),n.writeBits(14,i.core?i.core.frameSize-1:0),n.writeBits(1,0),n.writeBits(3,0),n.writeBits(16,i.channelLayout),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(5,0),t},sp=i=>Ha(i)+Ha(i&ip);var le=["avc","hevc","vp9","av1","vp8","prores"],ae=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],Rt=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],fe=[...Rt,...ae],Ye=["webvtt"],Hn=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],pd=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],kr=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],hd=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],gd=".01.01.01.01.00",bd=".0.110.01.01.01.0",Tr=["ap4x","ap4h","apch","apcn","apcs","apco"],Jn=["dtsc","dtsh","dtsl","dtse"],op=[{fourCc:"apco",bitrate:45e6,alpha:!1},{fourCc:"apcs",bitrate:102e6,alpha:!1},{fourCc:"apcn",bitrate:147e6,alpha:!1},{fourCc:"apch",bitrate:22e7,alpha:!1},{fourCc:"ap4h",bitrate:33e7,alpha:!0},{fourCc:"ap4x",bitrate:5e8,alpha:!0}],ms=(i,t,e,r,n)=>{if(i==="avc"){let s=Math.ceil(t/16)*Math.ceil(e/16),o=Hn.find(m=>s<=m.maxMacroblocks&&r<=m.maxBitrate)??Z(Hn),c=o?o.level:0,u="64".padStart(2,"0"),l="00",d=c.toString(16).padStart(2,"0");return`avc1.${u}${l}${d}`}else if(i==="hevc"){let a="",o="6",c=t*e,u=pd.find(d=>c<=d.maxPictureSize&&r<=d.maxBitrate)??Z(pd);return`hev1.${a}1.${o}.${u.tier}${u.level}.B0`}else{if(i==="vp8")return"vp8";if(i==="vp9"){let a="00",s=t*e,o=kr.find(u=>s<=u.maxPictureSize&&r<=u.maxBitrate)??Z(kr);return`vp09.${a}.${o.level.toString().padStart(2,"0")}.08`}else if(i==="av1"){let s=t*e,o=hd.find(l=>s<=l.maxPictureSize&&r<=l.maxBitrate)??Z(hd);return`av01.0.${o.level.toString().padStart(2,"0")}${o.tier}.08`}else if(i==="prores"){let s=Math.pow(t*e/2073600,.95),o=op.filter(l=>l.alpha===n),c=o[0].fourCc,u=1/0;for(let{fourCc:l,bitrate:d}of o){let m=Math.abs(d*s-r);m{let t=i.split("."),e=Number(t[1]),r=Number(t[2]),n=Number(t[3]),a=t[4]?Number(t[4]):1;return[1,1,e,2,1,r,3,1,n,4,1,a]},fs=i=>{let t=i.split("."),n=(1<<7)+1,a=Number(t[1]),s=t[2],o=Number(s.slice(0,-1)),c=(a<<5)+o,u=s.slice(-1)==="H"?1:0,l=Number(t[3]),d=l===8?0:1,m=l===12?1:0,f=t[4]?Number(t[4]):0,p=t[5]?Number(t[5][0]):1,b=t[5]?Number(t[5][1]):1,h=t[5]?Number(t[5][2]):0,y=(u<<7)+(d<<6)+(m<<5)+(f<<4)+(p<<3)+(b<<2)+h;return[n,c,y,0]},Kr=i=>{let{codec:t,codecDescription:e,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:a,vp9CodecInfo:s,av1CodecInfo:o,proresFormat:c}=i;if(t==="avc"){if(g(i.avcType!==null),n){let u=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${i.avcType}.${Vr(u)}`}if(!e||e.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${i.avcType}.${Vr(e.subarray(1,4))}`}else if(t==="hevc"){let u,l,d,m,f,p;if(a)u=a.generalProfileSpace,l=a.generalProfileIdc,d=dc(a.generalProfileCompatibilityFlags),m=a.generalTierFlag,f=a.generalLevelIdc,p=[...a.generalConstraintIndicatorFlags];else{if(!e||e.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let h=N(e),y=h.getUint8(1);u=y>>6&3,l=y&31,d=dc(h.getUint32(2)),m=y>>5&1,f=h.getUint8(12),p=[];for(let k=0;k<6;k++)p.push(h.getUint8(6+k))}let b="hev1.";for(b+=["","A","B","C"][u]+l,b+=".",b+=d.toString(16).toUpperCase(),b+=".",b+=m===0?"L":"H",b+=f;p.length>0&&p[p.length-1]===0;)p.pop();return p.length>0&&(b+=".",b+=p.map(h=>h.toString(16).toUpperCase()).join(".")),b}else{if(t==="vp8")return"vp8";if(t==="vp9"){if(!s){let k=i.width*i.height,T=Z(kr).level;for(let w of kr)if(k<=w.maxPictureSize){T=w.level;break}return`vp09.00.${T.toString().padStart(2,"0")}.08`}let u=s.profile.toString().padStart(2,"0"),l=s.level.toString().padStart(2,"0"),d=s.bitDepth.toString().padStart(2,"0"),m=s.chromaSubsampling.toString().padStart(2,"0"),f=s.colourPrimaries.toString().padStart(2,"0"),p=s.transferCharacteristics.toString().padStart(2,"0"),b=s.matrixCoefficients.toString().padStart(2,"0"),h=s.videoFullRangeFlag.toString().padStart(2,"0"),y=`vp09.${u}.${l}.${d}.${m}`;return y+=`.${f}.${p}.${b}.${h}`,y.endsWith(gd)&&(y=y.slice(0,-gd.length)),y}else if(t==="av1"){if(!o){let w=i.width*i.height,A=Z(kr).level;for(let x of kr)if(w<=x.maxPictureSize){A=x.level;break}return`av01.0.${A.toString().padStart(2,"0")}M.08`}let u=o.profile,l=o.level.toString().padStart(2,"0"),d=o.tier?"H":"M",m=o.bitDepth.toString().padStart(2,"0"),f=o.monochrome?"1":"0",p=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),b,h,y,k;ts(o)?(b=o.colourPrimaries,h=o.transferCharacteristics,y=o.matrixCoefficients,k=o.videoFullRangeFlag):(b=r?.primaries?Pt[r.primaries]:1,h=r?.transfer?It[r.transfer]:1,y=r?.matrix?Et[r.matrix]:1,k=r?.fullRange?1:0);let T=`av01.${u}.${l}${d}.${m}`;return T+=`.${f}.${p.toString().padStart(3,"0")}`,T+=`.${b.toString().padStart(2,"0")}`,T+=`.${h.toString().padStart(2,"0")}`,T+=`.${y.toString().padStart(2,"0")}`,T+=`.${k}`,T.endsWith(bd)&&(T=T.slice(0,-bd.length)),T}else{if(t==="prores")return c??"apch";t!==null&&ne(t)}}throw new TypeError(`Unhandled codec '${t}'.`)},ps=i=>{switch(i.codec){case"avc":{let t=i.avcCodecInfo?.sequenceParameterSets[0];if(!t&&i.codecDescription&&(t=Wr(i.codecDescription)?.sequenceParameterSets[0]),t){let e=Jt(t);if(e)return{primaries:ut[e.colourPrimaries],transfer:lt[e.transferCharacteristics],matrix:dt[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=i.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===33)?.nalUnits[0];if(!t&&i.codecDescription&&(t=Yi(i.codecDescription)?.arrays.find(e=>e.nalUnitType===33)?.nalUnits[0]),t){let e=xi(t);if(e)return{primaries:ut[e.colourPrimaries],transfer:lt[e.transferCharacteristics],matrix:dt[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(i.vp9CodecInfo)return{primaries:ut[i.vp9CodecInfo.colourPrimaries],transfer:lt[i.vp9CodecInfo.transferCharacteristics],matrix:dt[i.vp9CodecInfo.matrixCoefficients],fullRange:!!i.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(i.av1CodecInfo)return{primaries:ut[i.av1CodecInfo.colourPrimaries],transfer:lt[i.av1CodecInfo.transferCharacteristics],matrix:dt[i.av1CodecInfo.matrixCoefficients],fullRange:!!i.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(i.proresCodecInfo)return{primaries:ut[i.proresCodecInfo.colourPrimaries],transfer:lt[i.proresCodecInfo.transferCharacteristics],matrix:dt[i.proresCodecInfo.matrixCoefficients],fullRange:i.proresCodecInfo.fullRange};break}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},hs=(i,t,e)=>{if(i==="aac")return t>=2&&e<=24e3?"mp4a.40.29":e<=24e3?"mp4a.40.5":"mp4a.40.2";if(i==="mp3")return"mp3";if(i==="opus")return"opus";if(i==="vorbis")return"vorbis";if(i==="flac")return"flac";if(i==="ac3")return"ac-3";if(i==="eac3")return"ec-3";if(i==="dts")return"dtsc";if(ae.includes(i))return i;throw new TypeError(`Unhandled codec '${i}'.`)},Ji=i=>{let{codec:t,codecDescription:e,aacCodecInfo:r,dtsFormat:n}=i;if(t==="aac"){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let a;return r.objectType!==null?a=r.objectType:a=$t(e).objectType,`mp4a.40.${a}`}}else{if(t==="mp3")return"mp3";if(t==="opus")return"opus";if(t==="vorbis")return"vorbis";if(t==="flac")return"flac";if(t==="ac3")return"ac-3";if(t==="eac3")return"ec-3";if(t==="dts")return n??"dtsc";if(t&&ae.includes(t))return t}throw new TypeError(`Unhandled codec '${t}'.`)},kd=i=>{},Td=i=>{switch(i.codec){case"flac":{let t=Ti("ZkxhQ4AAACIQABAAAAYtACWtCsRC8AANRBhVFucAcYu5ASE2m1Dxv8tw");return i.sampleRate>=1<<20||i.numberOfChannels>8?!1:(t[18]=i.sampleRate>>>12,t[19]=i.sampleRate>>>4,t[20]=(i.sampleRate&15)<<4|i.numberOfChannels-1<<1,t)}case"vorbis":{let t=Ti("Ah7/AgF2b3JiaXMAAAAAAoC7AAAAAAAAgLUBAAAAAAC4AQN2b3JiaXMNAAAATGF2ZjU4Ljc2LjEwMAgAAAAMAAAAbGFuZ3VhZ2U9dW5kGQAAAGhhbmRsZXJfbmFtZT1Tb3VuZEhhbmRsZXIWAAAAdmVuZG9yX2lkPVswXVswXVswXVswXSAAAABlbmNvZGVyPUxhdmM1OC4xMzQuMTAwIGxpYnZvcmJpcxAAAABtYWpvcl9icmFuZD1pc29tEQAAAG1pbm9yX3ZlcnNpb249NTEyIgAAAGNvbXBhdGlibGVfYnJhbmRzPWlzb21pc28yYXZjMW1wNDEmAAAAREVTQ1JJUFRJT049TWFkZSB3aXRoIFJlbW90aW9uIDQuMC4yNzgBBXZvcmJpcyVCQ1YBAEAAACRzGCpGpXMWhBAaQlAZ4xxCzmvsGUJMEYIcMkxbyyVzkCGkoEKIWyiB0JBVAABAAACHQXgUhIpBCCGEJT1YkoMnPQghhIg5eBSEaUEIIYQQQgghhBBCCCGERTlokoMnQQgdhOMwOAyD5Tj4HIRFOVgQgydB6CCED0K4moOsOQghhCQ1SFCDBjnoHITCLCiKgsQwuBaEBDUojILkMMjUgwtCiJqDSTX4GoRnQXgWhGlBCCGEJEFIkIMGQcgYhEZBWJKDBjm4FITLQagahCo5CB+EIDRkFQCQAACgoiiKoigKEBqyCgDIAAAQQFEUx3EcyZEcybEcCwgNWQUAAAEACAAAoEiKpEiO5EiSJFmSJVmSJVmS5omqLMuyLMuyLMsyEBqyCgBIAABQUQxFcRQHCA1ZBQBkAAAIoDiKpViKpWiK54iOCISGrAIAgAAABAAAEDRDUzxHlETPVFXXtm3btm3btm3btm3btm1blmUZCA1ZBQBAAAAQ0mlmqQaIMAMZBkJDVgEACAAAgBGKMMSA0JBVAABAAACAGEoOogmtOd+c46BZDppKsTkdnEi1eZKbirk555xzzsnmnDHOOeecopxZDJoJrTnnnMSgWQqaCa0555wnsXnQmiqtOeeccc7pYJwRxjnnnCateZCajbU555wFrWmOmkuxOeecSLl5UptLtTnnnHPOOeecc84555zqxekcnBPOOeecqL25lpvQxTnnnE/G6d6cEM4555xzzjnnnHPOOeecIDRkFQAABABAEIaNYdwpCNLnaCBGEWIaMulB9+gwCRqDnELq0ehopJQ6CCWVcVJKJwgNWQUAAAIAQAghhRRSSCGFFFJIIYUUYoghhhhyyimnoIJKKqmooowyyyyzzDLLLLPMOuyssw47DDHEEEMrrcRSU2011lhr7jnnmoO0VlprrbVSSimllFIKQkNWAQAgAAAEQgYZZJBRSCGFFGKIKaeccgoqqIDQkFUAACAAgAAAAABP8hzRER3RER3RER3RER3R8RzPESVREiVREi3TMjXTU0VVdWXXlnVZt31b2IVd933d933d+HVhWJZlWZZlWZZlWZZlWZZlWZYgNGQVAAACAAAghBBCSCGFFFJIKcYYc8w56CSUEAgNWQUAAAIACAAAAHAUR3EcyZEcSbIkS9IkzdIsT/M0TxM9URRF0zRV0RVdUTdtUTZl0zVdUzZdVVZtV5ZtW7Z125dl2/d93/d93/d93/d93/d9XQdCQ1YBABIAADqSIymSIimS4ziOJElAaMgqAEAGAEAAAIriKI7jOJIkSZIlaZJneZaomZrpmZ4qqkBoyCoAABAAQAAAAAAAAIqmeIqpeIqoeI7oiJJomZaoqZoryqbsuq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq4LhIasAgAkAAB0JEdyJEdSJEVSJEdygNCQVQCADACAAAAcwzEkRXIsy9I0T/M0TxM90RM901NFV3SB0JBVAAAgAIAAAAAAAAAMybAUy9EcTRIl1VItVVMt1VJF1VNVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVN0zRNEwgNWQkAkAEAkBBTLS3GmgmLJGLSaqugYwxS7KWxSCpntbfKMYUYtV4ah5RREHupJGOKQcwtpNApJq3WVEKFFKSYYyoVUg5SIDRkhQAQmgHgcBxAsixAsiwAAAAAAAAAkDQN0DwPsDQPAAAAAAAAACRNAyxPAzTPAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAA0DwP8DwR8EQRAAAAAAAAACzPAzTRAzxRBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAAsDwP8EQR0DwRAAAAAAAAACzPAzxRBDzRAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEOAAABBgIRQasiIAiBMAcEgSJAmSBM0DSJYFTYOmwTQBkmVB06BpME0AAAAAAAAAAAAAJE2DpkHTIIoASdOgadA0iCIAAAAAAAAAAAAAkqZB06BpEEWApGnQNGgaRBEAAAAAAAAAAAAAzzQhihBFmCbAM02IIkQRpgkAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAGHAAAAgwoQwUGrIiAIgTAHA4imUBAIDjOJYFAACO41gWAABYliWKAABgWZooAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAYcAAACDChDBQashIAiAIAcCiKZQHHsSzgOJYFJMmyAJYF0DyApgFEEQAIAAAocAAACLBBU2JxgEJDVgIAUQAABsWxLE0TRZKkaZoniiRJ0zxPFGma53meacLzPM80IYqiaJoQRVE0TZimaaoqME1VFQAAUOAAABBgg6bE4gCFhqwEAEICAByKYlma5nmeJ4qmqZokSdM8TxRF0TRNU1VJkqZ5niiKommapqqyLE3zPFEURdNUVVWFpnmeKIqiaaqq6sLzPE8URdE0VdV14XmeJ4qiaJqq6roQRVE0TdNUTVV1XSCKpmmaqqqqrgtETxRNU1Vd13WB54miaaqqq7ouEE3TVFVVdV1ZBpimaaqq68oyQFVV1XVdV5YBqqqqruu6sgxQVdd1XVmWZQCu67qyLMsCAAAOHAAAAoygk4wqi7DRhAsPQKEhKwKAKAAAwBimFFPKMCYhpBAaxiSEFEImJaXSUqogpFJSKRWEVEoqJaOUUmopVRBSKamUCkIqJZVSAADYgQMA2IGFUGjISgAgDwCAMEYpxhhzTiKkFGPOOScRUoox55yTSjHmnHPOSSkZc8w556SUzjnnnHNSSuacc845KaVzzjnnnJRSSuecc05KKSWEzkEnpZTSOeecEwAAVOAAABBgo8jmBCNBhYasBABSAQAMjmNZmuZ5omialiRpmud5niiapiZJmuZ5nieKqsnzPE8URdE0VZXneZ4oiqJpqirXFUXTNE1VVV2yLIqmaZqq6rowTdNUVdd1XZimaaqq67oubFtVVdV1ZRm2raqq6rqyDFzXdWXZloEsu67s2rIAAPAEBwCgAhtWRzgpGgssNGQlAJABAEAYg5BCCCFlEEIKIYSUUggJAAAYcAAACDChDBQashIASAUAAIyx1lprrbXWQGettdZaa62AzFprrbXWWmuttdZaa6211lJrrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmstpZRSSimllFJKKaWUUkoppZRSSgUA+lU4APg/2LA6wknRWGChISsBgHAAAMAYpRhzDEIppVQIMeacdFRai7FCiDHnJKTUWmzFc85BKCGV1mIsnnMOQikpxVZjUSmEUlJKLbZYi0qho5JSSq3VWIwxqaTWWoutxmKMSSm01FqLMRYjbE2ptdhqq7EYY2sqLbQYY4zFCF9kbC2m2moNxggjWywt1VprMMYY3VuLpbaaizE++NpSLDHWXAAAd4MDAESCjTOsJJ0VjgYXGrISAAgJACAQUooxxhhzzjnnpFKMOeaccw5CCKFUijHGnHMOQgghlIwx5pxzEEIIIYRSSsaccxBCCCGEkFLqnHMQQgghhBBKKZ1zDkIIIYQQQimlgxBCCCGEEEoopaQUQgghhBBCCKmklEIIIYRSQighlZRSCCGEEEIpJaSUUgohhFJCCKGElFJKKYUQQgillJJSSimlEkoJJYQSUikppRRKCCGUUkpKKaVUSgmhhBJKKSWllFJKIYQQSikFAAAcOAAABBhBJxlVFmGjCRcegEJDVgIAZAAAkKKUUiktRYIipRikGEtGFXNQWoqocgxSzalSziDmJJaIMYSUk1Qy5hRCDELqHHVMKQYtlRhCxhik2HJLoXMOAAAAQQCAgJAAAAMEBTMAwOAA4XMQdAIERxsAgCBEZohEw0JweFAJEBFTAUBigkIuAFRYXKRdXECXAS7o4q4DIQQhCEEsDqCABByccMMTb3jCDU7QKSp1IAAAAAAADADwAACQXAAREdHMYWRobHB0eHyAhIiMkAgAAAAAABcAfAAAJCVAREQ0cxgZGhscHR4fICEiIyQBAIAAAgAAAAAggAAEBAQAAAAAAAIAAAAEBA=="),e=N(t);return e.setUint8(15,i.numberOfChannels),e.setUint32(16,i.sampleRate,!0),t}default:return}},Ft=48e3,wd=/^pcm-([usf])(\d+)(be)?$/,Re=i=>{if(g(ae.includes(i)),i==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(i==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let t=wd.exec(i);g(t);let e;t[1]==="u"?e="unsigned":t[1]==="s"?e="signed":e="float";let r=Number(t[2])/8,n=t[3]!=="be",a=i==="pcm-u8"?2**7:0;return{dataType:e,sampleSize:r,littleEndian:n,silentValue:a}},Ze=i=>i.startsWith("avc1")||i.startsWith("avc3")?"avc":i.startsWith("hev1")||i.startsWith("hvc1")?"hevc":i==="vp8"?"vp8":i.startsWith("vp09")?"vp9":i.startsWith("av01")?"av1":Tr.includes(i)?"prores":i==="mp3"||i==="mp4a.69"||i==="mp4a.6B"||i==="mp4a.6b"||i==="mp4a.40.34"?"mp3":i.startsWith("mp4a.40.")||i==="mp4a.67"?"aac":i==="opus"||i==="Opus"?"opus":i==="vorbis"?"vorbis":i==="flac"?"flac":i==="ac-3"||i==="ac3"?"ac3":i==="ec-3"||i==="eac3"?"eac3":Jn.includes(i)?"dts":i==="ulaw"?"ulaw":i==="alaw"?"alaw":wd.test(i)?i:i==="webvtt"?"webvtt":null,Sd=i=>i==="avc"?{avc:{format:"avc"}}:i==="hevc"?{hevc:{format:"hevc"}}:{},Ad=i=>i==="aac"?{aac:{format:"aac"}}:i==="opus"?{opus:{format:"opus"}}:{},cp=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Tr],up=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,lp=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,dp=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,mp=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,tr=(i,t)=>{if(!i)throw new TypeError("Video chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Video chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!cp.some(e=>i.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(i.decoderConfig.codedWidth)||i.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(i.decoderConfig.codedHeight)||i.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(i.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(i.decoderConfig.displayAspectWidth)||i.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(i.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(i.decoderConfig.displayAspectHeight)||i.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(i.decoderConfig.displayAspectWidth!==void 0!=(i.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(i.decoderConfig.description!==void 0&&!fr(i.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.colorSpace!==void 0){let{colorSpace:e}=i.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let r=Object.keys(Pt);if(e.primaries!=null&&!r.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);let n=Object.keys(It);if(e.transfer!=null&&!n.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${n.join(", ")}.`);let a=Object.keys(Et);if(e.matrix!=null&&!a.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${a.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(i.decoderConfig.codec.startsWith("avc1")||i.decoderConfig.codec.startsWith("avc3")){if(!up.test(i.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(i.decoderConfig.codec.startsWith("hev1")||i.decoderConfig.codec.startsWith("hvc1")){if(!lp.test(i.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(i.decoderConfig.codec.startsWith("vp8")){if(i.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(i.decoderConfig.codec.startsWith("vp09")){if(!dp.test(i.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(i.decoderConfig.codec.startsWith("av01")){if(!mp.test(i.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')}else if(Tr.some(e=>i.decoderConfig.codec.startsWith(e))&&!Tr.some(e=>i.decoderConfig.codec===e))throw new TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${Tr.join(", ")}.`);if(t!==null&&Ze(i.decoderConfig.codec)!==t)throw new TypeError(`Video chunk metadata decoder configuration codec string '${i.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},fp=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts"],Se=(i,t)=>{if(!i)throw new TypeError("Audio chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!fp.some(e=>i.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(i.decoderConfig.sampleRate)||i.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(i.decoderConfig.numberOfChannels)||i.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(i.decoderConfig.description!==void 0&&!fr(i.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.codec.startsWith("mp4a")&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(i.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(i.decoderConfig.codec.startsWith("mp3")||i.decoderConfig.codec.startsWith("mp4a")){if(i.decoderConfig.codec!=="mp3"&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(i.decoderConfig.codec.startsWith("opus")){if(i.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(i.decoderConfig.description&&i.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(i.decoderConfig.codec.startsWith("vorbis")){if(i.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!i.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(i.decoderConfig.codec.startsWith("flac")){if(i.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!i.decoderConfig.description||i.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(i.decoderConfig.codec.startsWith("ac-3")||i.decoderConfig.codec.startsWith("ac3")){if(i.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(i.decoderConfig.codec.startsWith("ec-3")||i.decoderConfig.codec.startsWith("eac3")){if(i.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if(i.decoderConfig.codec.startsWith("dts")){if(!Jn.includes(i.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${Jn.join(", ")}.`)}else if((i.decoderConfig.codec.startsWith("pcm")||i.decoderConfig.codec.startsWith("ulaw")||i.decoderConfig.codec.startsWith("alaw"))&&!ae.includes(i.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${ae.join(", ")}).`);if(t!==null&&Ze(i.decoderConfig.codec)!==t)throw new TypeError(`Audio chunk metadata decoder configuration codec string '${i.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},gs=i=>{if(!i)throw new TypeError("Subtitle metadata must be provided.");if(typeof i!="object")throw new TypeError("Subtitle metadata must be an object.");if(!i.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof i.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof i.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};var Ec=[44100,48e3,32e3],bs=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],Qr=1483304551,en=1231971951,ys=(i,t,e,r,n)=>t===0?0:t===1?Math.floor(144*e/(r<t===0?0:t===1?144*e/(r<i===3?t===3?21:36:t===3?13:21,jr=(i,t)=>{let e=i>>>24,r=i>>>16&255,n=i>>>8&255,a=i&255;if(e!==255&&r!==255&&n!==255&&a!==255)return{header:null,bytesAdvanced:4};if(e!==255)return{header:null,bytesAdvanced:1};if((r&224)!==224)return{header:null,bytesAdvanced:1};let s=0,o=0;r&16?s=r&8?0:1:(s=1,o=1);let c=r>>3&3,u=r>>1&3,l=n>>4&15,d=(n>>2&3)%3,m=n>>1&1,f=a>>6&3,p=a>>4&3,b=a>>3&1,h=a>>2&1,y=a&3,k=bs[s*16*4+u*16+l];if(k===-1)return{header:null,bytesAdvanced:1};let T=k*1e3,w=Ec[d]>>s+o,A=ys(s,u,T,w,m);if(t!==null&&t{let t=127,e=0,r=i;for(;(t^2147483647)!==0;)e=r&~t,e<<=1,e|=r&t,t=(t+1<<8)-1,r=e;return e},ks=i=>{let t=2130706432,e=0;for(;t!==0;)e>>=1,e|=i&t,t>>=8;return e};var Xr=i=>i===3?1:2;var Ae=class{constructor(t){this.input=t}dispose(){}};var Te=new Uint8Array(0),X=class i{constructor(t,e,r,n,a=-1,s,o){this.data=t;this.type=e;this.timestamp=r;this.duration=n;this.sequenceNumber=a;if(t===Te&&s===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(s===void 0&&(s=t.byteLength),!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(e!=="key"&&e!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(n)||n<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(a))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Te}get microsecondTimestamp(){return Math.trunc(Kt*this.timestamp)}get microsecondDuration(){return Math.trunc(Kt*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(t=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:t,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,e){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let r=new Uint8Array(t.byteLength);return t.copyTo(r),new i(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,e)}clone(t){if(t!==void 0&&(typeof t!="object"||t===null))throw new TypeError("options, when provided, must be an object.");if(t?.data!==void 0&&!(t.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(t?.type!==void 0&&t.type!=="key"&&t.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(t?.timestamp!==void 0&&!Number.isFinite(t.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&!Number.isFinite(t.duration))throw new TypeError("options.duration, when provided, must be a number.");if(t?.sequenceNumber!==void 0&&!Number.isFinite(t.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(t?.sideData!==void 0&&(typeof t.sideData!="object"||t.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new i(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,this.byteLength,t?.sideData??this.sideData)}};var Ts=i=>{let e=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isQuickTime?"quicktime":"mp4");if(i.codecStrings.length>0){let r=[...new Set(i.codecStrings)];e+=`; codecs="${r.join(", ")}"`}return e},ws=i=>{let t=N(i),e=0,r=t.getUint8(e);e+=1,e+=3;let n=Vr(i.subarray(e,e+16));e+=16;let a=null;if(r>0){let o=t.getUint32(e);if(e+=4,o>0){a=[];for(let c=0;ci.systemId===t.systemId&&Ka(i.data,t.data);var Mt=8,wr=16,Sr=i=>{let t=M(i),e=oe(i,4),r=8;t===1&&(t=We(i),r=16);let a=t-r;return a<0?null:{name:e,totalSize:t,headerSize:r,contentSize:a}},$r=i=>Ar(i)/65536,As=i=>Ar(i)/1073741824,xs=i=>{let t=0;for(let e=0;e<4;e++){t<<=7;let r=L(i);if(t|=r&127,(r&128)===0)break}return t},Bt=i=>{let t=he(i);return i.skip(2),t=Math.min(t,i.remainingLength),ye.decode(V(i,t))},Pd=i=>{let t=Sr(i);if(!t||t.name!=="data"||i.remainingLength<8)return null;let e=M(i);i.skip(4);let r=V(i,t.contentSize-8);switch(e){case 1:return ye.decode(r);case 2:return new hi("utf-16be").decode(r);case 13:return new yt(r,"image/jpeg");case 14:return new yt(r,"image/png");case 27:return new yt(r,"image/bmp");default:return r}};var Ot=16,xr=new Uint32Array(256),tn=new Uint32Array(256),rn=new Uint32Array(256),nn=new Uint32Array(256),an=new Uint32Array(256),De=new Uint32Array(256),Id=new Uint32Array(10),Ed=!1,pp=()=>{let i=new Uint8Array(256),t=new Uint8Array(256),e=new Uint8Array(256);for(let a=0,s=1;a<256;a++)e[a]=s,t[s]=a,s=s^s<<1^(s&128?283:0);let r=(a,s)=>a&&s?e[(t[a]+t[s])%255]:0;i[0]=99;for(let a=1;a<256;a++){let s=e[255-t[a]],o=s^s<<1^s<<2^s<<3^s<<4;o=o>>>8^o&255^99,i[a]=o}for(let a=0;a<256;a++){let s=i[a],o=i.indexOf(a);xr[a]=s<<24|s<<16|s<<8|s,De[a]=o<<24|o<<16|o<<8|o;let c=r(o,14),u=r(o,9),l=r(o,13),d=r(o,11),m=c<<24|u<<16|l<<8|d;tn[a]=m,rn[a]=m>>>8|m<<24,nn[a]=m>>>16|m<<16,an[a]=m>>>24|m<<8}let n=1;for(let a=0;a<10;a++)Id[a]=n<<24,n=n<<1^(n&128?283:0);Ed=!0},ea=class{constructor(){this.roundkey=new Uint32Array(44);this.iv=new Uint32Array(Ot/Uint32Array.BYTES_PER_ELEMENT);this.in=new Uint8Array(Ot);this.out=new Uint8Array(Ot);this.inView=new DataView(this.in.buffer);this.outView=new DataView(this.out.buffer)}init({key:t,iv:e}){g(t.byteLength===16),g(e.byteLength===16),Ed||pp();let r=new DataView(t.buffer,t.byteOffset,t.byteLength),n=new DataView(e.buffer,e.byteOffset,e.byteLength);this.roundkey[0]=r.getUint32(0,!1),this.roundkey[1]=r.getUint32(4,!1),this.roundkey[2]=r.getUint32(8,!1),this.roundkey[3]=r.getUint32(12,!1),this.iv[0]=n.getUint32(0,!1),this.iv[1]=n.getUint32(4,!1),this.iv[2]=n.getUint32(8,!1),this.iv[3]=n.getUint32(12,!1);for(let a=4;a<44;a+=4){let s=this.roundkey[a-1];this.roundkey[a]=this.roundkey[a-4]^xr[s>>>16&255]&4278190080^xr[s>>>8&255]&16711680^xr[s>>>0&255]&65280^xr[s>>>24&255]&255^Id[a/4-1],this.roundkey[a+1]=this.roundkey[a-3]^this.roundkey[a],this.roundkey[a+2]=this.roundkey[a-2]^this.roundkey[a+1],this.roundkey[a+3]=this.roundkey[a-1]^this.roundkey[a+2]}for(let a=0,s=40;a>>24&255]&255]^rn[xr[o>>>16&255]&255]^nn[xr[o>>>8&255]&255]^an[xr[o>>>0&255]&255]}}decrypt(){let t=this.inView.getUint32(0,!1)^this.roundkey[0],e=this.inView.getUint32(4,!1)^this.roundkey[1],r=this.inView.getUint32(8,!1)^this.roundkey[2],n=this.inView.getUint32(12,!1)^this.roundkey[3],a=this.inView.getUint32(0,!1),s=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),c=this.inView.getUint32(12,!1),u,l,d,m;for(let y=1;y<10;y++){let k=y*4;u=tn[t>>>24]^rn[n>>>16&255]^nn[r>>>8&255]^an[e&255]^this.roundkey[k],l=tn[e>>>24]^rn[t>>>16&255]^nn[n>>>8&255]^an[r&255]^this.roundkey[k+1],d=tn[r>>>24]^rn[e>>>16&255]^nn[t>>>8&255]^an[n&255]^this.roundkey[k+2],m=tn[n>>>24]^rn[r>>>16&255]^nn[e>>>8&255]^an[t&255]^this.roundkey[k+3],t=u,e=l,r=d,n=m}let f=De[t>>>24&255]&4278190080^De[n>>>16&255]&16711680^De[r>>>8&255]&65280^De[e>>>0&255]&255^this.roundkey[40],p=De[e>>>24&255]&4278190080^De[t>>>16&255]&16711680^De[n>>>8&255]&65280^De[r>>>0&255]&255^this.roundkey[41],b=De[r>>>24&255]&4278190080^De[e>>>16&255]&16711680^De[t>>>8&255]&65280^De[n>>>0&255]&255^this.roundkey[42],h=De[n>>>24&255]&4278190080^De[r>>>16&255]&16711680^De[e>>>8&255]&65280^De[t>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,f^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,b^this.iv[2],!1),this.outView.setUint32(12,h^this.iv[3],!1),this.iv[0]=a,this.iv[1]=s,this.iv[2]=o,this.iv[3]=c}},vd=(i,t,e)=>{let r=!1,n=0,a=2**16,s=16,o=new ea;return new ReadableStream({pull:async c=>{r||(o.init(await t()),r=!0);let u=a+s,l=i.requestSliceRange(n,0,u);if(_(l)&&(l=await l),!l||l.length===0)throw new Error("Invalid ciphertext.");let d=l.length;if(d%16!==0)throw new Error("Invalid ciphertext.");let m=d===u?d-s:d,f=V(l,m),p=new Uint8Array(m);for(let b=0;b16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");let h=p.subarray(0,m-b);c.enqueue(h),c.close(),e()}},cancel:()=>{e()}})};var Cs=class i extends Ae{constructor(e){super(e);this.moovSlice=null;this.currentTrack=null;this.tracks=[];this.metadataPromise=null;this.movieTimescale=-1;this.movieDurationInTimescale=-1;this.movieMatrix=Dr;this.isQuickTime=!1;this.metadataTags={};this.currentMetadataKeys=null;this.isFragmented=!1;this.fragmentTrackDefaults=[];this.psshBoxes=[];this.currentFragment=null;this.lastReadFragment=null;this.decryptionKeyCache=new Map;this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),r=await Promise.all(e.map(n=>n.getDecoderConfig().then(a=>a?.codec??null)));return Ts({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(n=>n.info?.type==="video"),hasAudio:this.tracks.some(n=>n.info?.type==="audio"),codecStrings:r.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,r=!1,n=!1;for(;;){let a=this.reader.requestSliceRange(e,Mt,wr);if(_(a)&&(a=await a),!a)break;let s=e,o=Sr(a);if(!o)break;if(o.name==="ftyp"||o.name==="styp"){let c=oe(a,4);this.isQuickTime=c==="qt "}else if(o.name==="moov"){let c=this.reader.requestSlice(a.filePos,o.contentSize);if(_(c)&&(c=await c),!c)break;this.moovSlice=c,this.readContiguousBoxes(this.moovSlice);for(let u of this.tracks){let l=u.editListPreviousSegmentDurations/this.movieTimescale;u.editListOffset-=Math.round(l*u.timescale)}r=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>s+o.totalSize,n=!0;break}else if(o.name==="moof"){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');await this.copyMetadataFromInitInput(this.input._initInput),r=!1,n=!0;break}e=s+o.totalSize}if(!n&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),r){g(this.reader.fileSize!==null);let a=this.reader.requestSlice(this.reader.fileSize-4,4);_(a)&&(a=await a),g(a);let s=M(a),o=this.reader.fileSize-s;if(o>=0&&o<=this.reader.fileSize-wr){let c=this.reader.requestSliceRange(o,Mt,wr);if(_(c)&&(c=await c),c){let u=Sr(c);if(u&&u.name==="mfra"){let l=this.reader.requestSlice(c.filePos,u.contentSize);_(l)&&(l=await l),l&&this.readContiguousBoxes(l)}}}}})()}async copyMetadataFromInitInput(e){let r=await e._getDemuxer();if(r.constructor!==i)throw new Error("Init input must match the input's format.");await r.readMetadata(),this.movieTimescale=r.movieTimescale,this.movieDurationInTimescale=r.movieDurationInTimescale,this.movieMatrix=r.movieMatrix,this.metadataTags=r.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=r.fragmentTrackDefaults,this.psshBoxes=r.psshBoxes;for(let n of r.tracks){let a={id:n.id,demuxer:this,trackBacking:null,disposition:n.disposition,timescale:n.timescale,durationInMediaTimescale:n.durationInMediaTimescale,durationInMovieTimescale:n.durationInMovieTimescale,matrix:n.matrix,internalCodecId:n.internalCodecId,name:n.name,languageCode:n.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:n.editListPreviousSegmentDurations,editListOffset:n.editListOffset,encryptionInfo:n.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:n.maxBitrate,avgBitrate:n.avgBitrate,info:n.info};if(n.trackBacking){if(g(a.info),a.info.type==="video"&&a.info.width!==-1){let s=a;a.trackBacking=new Is(s),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){let s=a;a.trackBacking=new Es(s),this.tracks.push(a)}}}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=r,e.sampleTableByteOffset===null)return r;g(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&ae.includes(e.info.codec)&&r.sampleCompositionTimeOffsets.length===0){g(e.info?.type==="audio");let s=Re(e.info.codec),o=[],c=[];for(let u=0;uS.startIndex),y=r.sampleTimingEntries[h],k=Q(r.sampleTimingEntries,b,S=>S.startIndex),T=r.sampleTimingEntries[k],w=y.startDecodeTimestamp+(p-y.startIndex)*y.delta,x=T.startDecodeTimestamp+(b-T.startIndex)*T.delta-w,C=Z(o);C&&C.delta===x?C.count++:o.push({startIndex:l.startChunkIndex+f,startDecodeTimestamp:w,count:1,delta:x});let P=l.samplesPerChunk*s.sampleSize*e.info.numberOfChannels;c.push(P)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}r.sampleTimingEntries=o,r.sampleSizes=c}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(let s of r.sampleTimingEntries)for(let o=0;os.presentationTimestamp-o.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let s=0;sm.moofOffset===s.moofOffset);if(d)vc(o,d.timestamp);else{let m=Q(u,s.moofOffset-1,f=>f.moofOffset);if(m!==-1){let f=u[m];vc(o,f.endTimestamp)}}o.startTimestampIsFinal=!0}let l=Q(u,o.startTimestamp,d=>d.startTimestamp);if((l===-1||u[l].moofOffset!==s.moofOffset)&&u.splice(l+1,0,{moofOffset:s.moofOffset,startTimestamp:o.startTimestamp,endTimestamp:o.endTimestamp}),o.encryptionAuxInfo&&c.encryptionInfo){let d=await Vd(this.reader,c.encryptionInfo,o.encryptionAuxInfo);for(let m=0;m0){o.languageCode="";for(let l=0;l<3;l++)o.languageCode=String.fromCharCode(96+(u&31))+o.languageCode,u>>=5;gr(o.languageCode)||(o.languageCode=se)}}break;case"hdlr":{let o=this.currentTrack;if(!o)break;e.skip(8);let c=oe(e,4);c==="vide"?o.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...Na},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:c==="soun"&&(o.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{let o=this.currentTrack;if(!o)break;o.sampleTableByteOffset=r,this.readContiguousBoxes(e.slice(a,n.contentSize))}break;case"stsd":{let o=this.currentTrack;if(!o||o.info===null||o.sampleTable)break;let c=L(e);e.skip(3);let u=M(e);for(let l=0;l0&&(p===1?(e.skip(4),h=8*M(e),e.skip(2*4)):p===2&&(e.skip(4),y=vs(e),b=M(e),e.skip(4),h=M(e),k=M(e),e.skip(2*4))),o.info.numberOfChannels=b,o.info.sampleRate=y,o.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,d+m.totalSize-e.filePos));let T=f==="enca"?o.frmaCodecString:f;if(o.frmaCodecString=null,T!=="mp4a")if(T==="opus")o.info.codec="opus",o.info.sampleRate=Ft;else if(T==="flac")o.info.codec="flac";else if(T==="ulaw")o.info.codec="ulaw";else if(T==="alaw")o.info.codec="alaw";else if(T==="ac-3")o.info.codec="ac3";else if(T==="ec-3")o.info.codec="eac3";else if(Jn.includes(T))o.info.codec="dts",o.info.dtsFormat=T;else if(T==="twos")h===8?o.info.codec="pcm-s8":h===16?o.info.codec=o.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(z._warn(`Unsupported sample size ${h} for codec 'twos'.`),o.info.codec=null);else if(T==="sowt")h===8?o.info.codec="pcm-s8":h===16?o.info.codec="pcm-s16":(z._warn(`Unsupported sample size ${h} for codec 'sowt'.`),o.info.codec=null);else if(T==="raw ")o.info.codec="pcm-u8";else if(T==="in24")o.info.codec=o.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(T==="in32")o.info.codec=o.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(T==="fl32")o.info.codec=o.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(T==="fl64")o.info.codec=o.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(T==="ipcm"){let w=o.info.pcmSampleSize;o.info.pcmLittleEndian?w===16?o.info.codec="pcm-s16":w===24?o.info.codec="pcm-s24":w===32?o.info.codec="pcm-s32":(z._warn(`Invalid ipcm sample size ${w}.`),o.info.codec=null):w===16?o.info.codec="pcm-s16be":w===24?o.info.codec="pcm-s24be":w===32?o.info.codec="pcm-s32be":(z._warn(`Invalid ipcm sample size ${w}.`),o.info.codec=null)}else if(T==="fpcm"){let w=o.info.pcmSampleSize;o.info.pcmLittleEndian?w===32?o.info.codec="pcm-f32":w===64?o.info.codec="pcm-f64":(z._warn(`Invalid fpcm sample size ${w}.`),o.info.codec=null):w===32?o.info.codec="pcm-f32be":w===64?o.info.codec="pcm-f64be":(z._warn(`Invalid fpcm sample size ${w}.`),o.info.codec=null)}else if(T==="lpcm"&&k!==null){let w=h+7>>3,A=!!(k&1),x=!!(k&2),C=k&4?-1:0;h>0&&h<=64&&(A?h===32&&(o.info.codec=x?"pcm-f32be":"pcm-f32"):C&1<0?(o.encryptionInfo.defaultCryptByteBlock=u>>4,o.encryptionInfo.defaultSkipByteBlock=u&15):(o.encryptionInfo.defaultCryptByteBlock=0,o.encryptionInfo.defaultSkipByteBlock=0),o.encryptionInfo.defaultIsProtected=L(e)!==0,o.encryptionInfo.defaultPerSampleIvSize=L(e),o.encryptionInfo.defaultKid=Vr(V(e,16)),o.encryptionInfo.defaultIsProtected&&o.encryptionInfo.defaultPerSampleIvSize===0){let l=L(e),d=new Uint8Array(16);d.set(V(e,l),0),o.encryptionInfo.defaultConstantIv=d}}break;case"avcC":{let o=this.currentTrack;if(!o||(g(o.info),n.contentSize===0))break;o.info.codecDescription=V(e,n.contentSize);let c=Wr(o.info.codecDescription)?.sequenceParameterSets[0],u=c&&Jt(c);u&&Rd(o,u.pixelAspectRatio)}break;case"hvcC":{let o=this.currentTrack;if(!o||(g(o.info),n.contentSize===0))break;o.info.codecDescription=V(e,n.contentSize);let c=Yi(o.info.codecDescription)?.arrays.find(l=>l.nalUnitType===33)?.nalUnits[0],u=c&&xi(c);u&&Rd(o,u.pixelAspectRatio)}break;case"vpcC":{let o=this.currentTrack;if(!o)break;g(o.info?.type==="video"),e.skip(4);let c=L(e),u=L(e),l=L(e),d=l>>4,m=l>>1&7,f=l&1,p=L(e),b=L(e),h=L(e);o.info.vp9CodecInfo={profile:c,level:u,bitDepth:d,chromaSubsampling:m,videoFullRangeFlag:f,colourPrimaries:p,transferCharacteristics:b,matrixCoefficients:h}}break;case"av1C":{let o=this.currentTrack;if(!o)break;g(o.info?.type==="video"),e.skip(1);let c=L(e),u=c>>5,l=c&31,d=L(e),m=d>>7,f=d>>6&1,p=d>>5&1,b=d>>4&1,h=d>>3&1,y=d>>2&1,k=d&3,T=u===2&&f?p?12:10:f?10:8;e.skip(1);let w=V(e,n.contentSize-4),A=Ci(w);o.info.av1CodecInfo={profile:u,level:l,tier:m,bitDepth:T,monochrome:b,chromaSubsamplingX:h,chromaSubsamplingY:y,chromaSamplePosition:k,videoFullRangeFlag:A?.videoFullRangeFlag??0,colourPrimaries:A?.colourPrimaries??2,transferCharacteristics:A?.transferCharacteristics??2,matrixCoefficients:A?.matrixCoefficients??2}}break;case"colr":{let o=this.currentTrack;if(!o)break;g(o.info?.type==="video");let c=oe(e,4);if(c!=="nclx"&&c!=="nclc")break;let u=he(e),l=he(e),d=he(e),m;c==="nclx"&&(m=!!(L(e)&128)),o.info.colorSpace={primaries:ut[u],transfer:lt[l],matrix:dt[d],fullRange:m}}break;case"pasp":{let o=this.currentTrack;if(!o)break;g(o.info?.type==="video");let c=M(e),u=M(e);c>0&&u>0&&(o.info.squarePixelWidth=o.info.width,o.info.squarePixelHeight=o.info.height,c>u?o.info.squarePixelWidth=Math.round(o.info.width*c/u):o.info.squarePixelHeight=Math.round(o.info.height*u/c))}break;case"btrt":{let o=this.currentTrack;if(!o)break;e.skip(4);let c=M(e),u=M(e);o.maxBitrate=c>0?c:null,o.avgBitrate=u>0?u:null}break;case"wave":this.readContiguousBoxes(e.slice(a,n.contentSize));break;case"esds":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;e.skip(4);let c=L(e);g(c===3),xs(e),e.skip(2);let u=L(e),l=(u&128)!==0,d=(u&64)!==0,m=(u&32)!==0;if(l&&e.skip(2),d){let y=L(e);e.skip(y)}m&&e.skip(2);let f=L(e);g(f===4);let p=xs(e),b=e.filePos,h=L(e);if(h===64||h===103?(o.info.codec="aac",o.info.aacCodecInfo={isMpeg2:h===103,objectType:null}):h===105||h===107?o.info.codec="mp3":h===221?o.info.codec="vorbis":h===169?o.info.codec="dts":z._warn(`Unsupported audio codec (objectTypeIndication ${h}) - discarding track.`),e.skip(12),p>e.filePos-b){let y=L(e);g(y===5);let k=xs(e);if(o.info.codecDescription=V(e,k),o.info.codec==="aac"){let T=$t(o.info.codecDescription);T.outputNumberOfChannels!==null&&(o.info.numberOfChannels=T.outputNumberOfChannels),T.outputSampleRate!==null&&(o.info.sampleRate=T.outputSampleRate)}}}break;case"enda":{let o=this.currentTrack;if(!o)break;g(o.info?.type==="audio"),o.info.pcmLittleEndian=!!(he(e)&255)}break;case"pcmC":{let o=this.currentTrack;if(!o)break;g(o.info?.type==="audio"),e.skip(4);let c=L(e);o.info.pcmLittleEndian=!!(c&1),o.info.pcmSampleSize=L(e)}break;case"dOps":{let o=this.currentTrack;if(!o)break;g(o.info?.type==="audio"),e.skip(1);let c=L(e),u=he(e),l=M(e),d=ta(e),m=L(e),f;m!==0?f=V(e,2+c):f=new Uint8Array(0);let p=new Uint8Array(19+f.byteLength),b=new DataView(p.buffer);b.setUint32(0,1332770163,!1),b.setUint32(4,1214603620,!1),b.setUint8(8,1),b.setUint8(9,c),b.setUint16(10,u,!0),b.setUint32(12,l,!0),b.setInt16(16,d,!0),b.setUint8(18,m),p.set(f,19),o.info.codecDescription=p,o.info.numberOfChannels=c}break;case"dfLa":{let o=this.currentTrack;if(!o)break;g(o.info?.type==="audio"),e.skip(4);let c=127,u=128,l=e.filePos;for(;e.filePos>>12,w=(k>>9&7)+1;o.info.sampleRate=T,o.info.numberOfChannels=w,e.skip(20)}else e.skip(h);if(b&u)break}let d=e.filePos;e.filePos=l;let m=V(e,d-l),f=new Uint8Array(4+m.byteLength);new DataView(f.buffer).setUint32(0,1716281667,!1),f.set(m,4),o.info.codecDescription=f}break;case"dac3":{let o=this.currentTrack;if(!o)break;g(o.info?.type==="audio");let c=V(e,3),u=new H(c),l=u.readBits(2);u.skipBits(8);let d=u.readBits(3),m=u.readBits(1);l<3&&(o.info.sampleRate=Ai[l]),o.info.numberOfChannels=Gn[d]+m}break;case"dec3":{let o=this.currentTrack;if(!o)break;g(o.info?.type==="audio");let c=V(e,n.contentSize),u=ud(c);if(!u){z._warn("Invalid dec3 box contents, ignoring.");break}let l=ss(u);l!==null&&(o.info.sampleRate=l),o.info.numberOfChannels=os(u)}break;case"ddts":{let o=this.currentTrack;if(!o)break;g(o.info?.type==="audio");let c=V(e,Math.min(n.contentSize,us)),u=md(c);if(!u){z._warn("Invalid ddts box contents, ignoring.");break}o.info.sampleRate=u.sampleRate,u.numberOfChannels!==null&&(o.info.numberOfChannels=u.numberOfChannels)}break;case"stts":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=M(e),u=0,l=0;for(let d=0;dT.id===c);if(!u)break;let l=M(e),d=(l&48)>>4,m=(l&12)>>2,f=l&3,p=[L,he,Dt,M],b=p[d],h=p[m],y=p[f],k=M(e);for(let T=0;TT.timestamp-w.timestamp);for(let T=0;T({presentationTimestamp:d.presentationTimestamp,sampleIndex:m})).sort((d,m)=>d.presentationTimestamp-m.presentationTimestamp);for(let d=0;dk.id===b);if(!h)break;let y=this.fragmentTrackDefaults.find(k=>k.trackId===b);this.currentTrack=h,h.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:y?.defaultSampleDescriptionIndex??null,defaultSampleDuration:y?.defaultSampleDuration??null,defaultSampleSize:y?.defaultSampleSize??null,defaultSampleFlags:y?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},c?h.currentFragmentState.baseDataOffset=We(e):p&&(h.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),u&&(h.currentFragmentState.sampleDescriptionIndex=M(e)),l&&(h.currentFragmentState.defaultSampleDuration=M(e)),d&&(h.currentFragmentState.defaultSampleSize=M(e)),m&&(h.currentFragmentState.defaultSampleFlags=M(e)),f&&(h.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let o=this.currentTrack;if(!o)break;g(o.currentFragmentState);let c=L(e);e.skip(3);let u=c===0?M(e):We(e);o.currentFragmentState.startTimestamp=u}break;case"trun":{let o=this.currentTrack;if(!o)break;g(this.currentFragment),g(o.currentFragmentState),e.skip(1);let c=Dt(e),u=!!(c&1),l=!!(c&4),d=!!(c&256),m=!!(c&512),f=!!(c&1024),p=!!(c&2048),b=M(e),h=null;u&&(h=Ar(e));let y=null;l&&(y=M(e));let k;this.currentFragment.trackData.has(o.id)?(k=this.currentFragment.trackData.get(o.id),h!==null&&(k.currentOffset=o.currentFragmentState.baseDataOffset+h)):(k={track:o,currentTimestamp:0,currentOffset:o.currentFragmentState.baseDataOffset+(h??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(o.id,k));for(let T=0;T0&&(d=V(e,l));let m=Md(o);m.defaultSampleInfoSize=u,m.sampleSizes=d,m.sampleCount=l}break;case"saio":{let o=this.currentTrack;if(!o||!o.encryptionInfo)break;let c=L(e);if(Dt(e)&1){let f=oe(e,4),p=M(e);if(f!==o.encryptionInfo.scheme||p!==0)break}let l=M(e);if(l===0)break;l>1&&z._warn("Multiple saio entries are not supported; using the first offset only.");let d=c===0?M(e):Number(We(e));this.currentFragment&&(d+=this.currentFragment.moofOffset);let m=Md(o);m.offset=d}break;case"senc":{let o=this.currentTrack;if(!o||!o.encryptionInfo)break;g(this.currentFragment);let c=this.currentFragment.trackData.get(o.id);if(!c)break;e.skip(1);let l=!!(Dt(e)&2),d=M(e),m=o.encryptionInfo.defaultPerSampleIvSize;g(m!==null);for(let f=0;f0?p.set(V(e,m),0):p.set(o.encryptionInfo.defaultConstantIv,0);let b=null;if(l){let y=he(e);b=[];for(let k=0;k=2){let f=N(m).getInt16(0,!1);f>0&&(this.metadataTags.beatsPerMinute??=f)}break;case"covr":case"com.apple.quicktime.artwork":m instanceof yt?(this.metadataTags.images??=[],this.metadataTags.images.push({data:m.data,kind:"coverFront",mimeType:m.mimeType})):m instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:m,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof m=="string"){let f=m.split("/"),p=Number.parseInt(f[0],10),b=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(this.metadataTags.trackNumber??=p),b&&Number.isInteger(b)&&b>0&&(this.metadataTags.tracksTotal??=b)}break;case"trkn":if(m instanceof Uint8Array&&m.length>=6){let f=N(m),p=f.getUint16(2,!1),b=f.getUint16(4,!1);p>0&&(this.metadataTags.trackNumber??=p),b>0&&(this.metadataTags.tracksTotal??=b)}break;case"disc":case"disk":if(m instanceof Uint8Array&&m.length>=6){let f=N(m),p=f.getUint16(2,!1),b=f.getUint16(4,!1);p>0&&(this.metadataTags.discNumber??=p),b>0&&(this.metadataTags.discsTotal??=b)}break}}}break}return e.filePos=s,!0}},Ps=class{constructor(t){this.internalTrack=t;this.packetToSampleIndex=new WeakMap;this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let t=this.internalTrack.demuxer,e=this.internalTrack.trackBacking.getType(),r=0;for(let n of t.tracks)if(n.trackBacking.getType()===e&&r++,n===this.internalTrack)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return this.internalTrack.maxBitrate}getAverageBitrate(){return this.internalTrack.avgBitrate}async getDurationFromMetadata(){let t=this.internalTrack;return t.durationInMediaTimescale<=0?null:(g(t.trackBacking),((await t.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+t.durationInMediaTimescale/t.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(t){let e=await this.fetchPacketForSampleIndex(0,t);return e||!this.internalTrack.demuxer.isFragmented?e:this.performFragmentedLookup(null,r=>r.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,t)}mapTimestampIntoTimescale(t){return hr(t*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(t,e){let r=this.mapTimestampIntoTimescale(t),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=_c(n,r),s=await this.fetchPacketForSampleIndex(a,e);return!Fd(n)||!this.internalTrack.demuxer.isFragmented?s:this.performFragmentedLookup(null,o=>{let c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let u=Q(c.presentationTimestamps,r,m=>m.presentationTimestamp),l=u!==-1?c.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&r{if(a===n.fragment){let s=a.trackData.get(this.internalTrack.id);if(n.sampleIndex+1{let c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let u=Ur(c.presentationTimestamps,m=>c.samples[m.sampleIndex].isKeyFrame&&m.presentationTimestamp<=r),l=u!==-1?c.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&r{if(a===n.fragment){let o=a.trackData.get(this.internalTrack.id).samples.findIndex((c,u)=>c.isKeyFrame&&u>n.sampleIndex);if(o!==-1)return{sampleIndex:o,correctSampleFound:!0}}else{let s=a.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){let o=s.samples.findIndex(c=>c.isKeyFrame);return g(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,e)}async fetchPacketForSampleIndex(t,e){if(t===-1)return null;let r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=gp(r,t);if(!n)return null;let a;if(e.metadataOnly)a=Te;else{let u=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);if(_(u)&&(u=await u),!u)return null;if(a=V(u,n.sampleSize),this.internalTrack.encryptionInfo){let l=null;if(this.internalTrack.encryptionAuxInfo){let d=await Vd(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);th.timestamp),d=l!==-1?this.internalTrack.fragmentLookupTable[l]:null,m=Q(this.internalTrack.fragmentPositionCache,r,h=>h.startTimestamp),f=m!==-1?this.internalTrack.fragmentPositionCache[m]:null,p=Math.max(d?.moofOffset??0,f?.moofOffset??0)||null,b;for(t?p===null||t.moofOffset>=p?(b=t.moofOffset+t.moofSize,o=t):b=p:b=p??0;;){if(o){let T=o.trackData.get(this.internalTrack.id);if(T&&T.startTimestamp>n)break}let h=s.reader.requestSliceRange(b,Mt,wr);if(_(h)&&(h=await h),!h)break;let y=b,k=Sr(h);if(!k)break;if(k.name==="moof"){o=await s.readFragment(y);let{sampleIndex:T,correctSampleFound:w}=e(o);if(w)return this.fetchPacketInFragment(o,T,a);T!==-1&&(c=o,u=T)}b=y+k.totalSize}if(d&&(!c||c.moofOffset{if(this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription){let r=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=r&&Zt(r.data)}else if(this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription){let r=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=r&&er(r.data)}else if(this.internalTrack.info.codec==="vp9"&&(!this.internalTrack.info.vp9CodecInfo||!nd(this.internalTrack.info.vp9CodecInfo))){let r=await this.getFirstPacket({}),n=r&&Zi(r.data);n&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??n,videoFullRangeFlag:n.videoFullRangeFlag,colourPrimaries:n.colourPrimaries,transferCharacteristics:n.transferCharacteristics,matrixCoefficients:n.matrixCoefficients})}else if(this.internalTrack.info.codec==="av1"&&(!this.internalTrack.info.av1CodecInfo||!ts(this.internalTrack.info.av1CodecInfo))){let r=await this.getFirstPacket({}),n=r&&Ci(r.data);n&&(this.internalTrack.info.av1CodecInfo=n)}else if(this.internalTrack.info.codec==="prores"&&!this.internalTrack.info.proresCodecInfo){let r=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=r&&rs(r.data)}if(!Ki(this.internalTrack.info.colorSpace)){let r=ps(this.internalTrack.info);this.internalTrack.info.colorSpace.primaries??=r.primaries,this.internalTrack.info.colorSpace.transfer??=r.transfer,this.internalTrack.info.colorSpace.matrix??=r.matrix,this.internalTrack.info.colorSpace.fullRange??=r.fullRange}let e={codec:Kr(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}},Es=class extends Ps{constructor(e){super(e);this.decoderConfigPromise=null}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="dts"&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&ls(e.data)}return{codec:Ji(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}},_c=(i,t)=>{if(i.presentationTimestamps){let e=Q(i.presentationTimestamps,t,r=>r.presentationTimestamp);return e===-1?-1:i.presentationTimestamps[e].sampleIndex}else{let e=Q(i.sampleTimingEntries,t,n=>n.startDecodeTimestamp);if(e===-1)return-1;let r=i.sampleTimingEntries[e];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},hp=(i,t)=>{if(!i.keySampleIndices)return _c(i,t);if(i.presentationTimestamps){let e=Q(i.presentationTimestamps,t,r=>r.presentationTimestamp);if(e===-1)return-1;for(let r=e;r>=0;r--){let n=i.presentationTimestamps[r].sampleIndex;if(pr(i.keySampleIndices,n,s=>s)!==-1)return n}return-1}else{let e=_c(i,t),r=Q(i.keySampleIndices,e,n=>n);return i.keySampleIndices[r]??-1}},gp=(i,t)=>{let e=Q(i.sampleTimingEntries,t,y=>y.startIndex),r=i.sampleTimingEntries[e];if(!r||r.startIndex+r.count<=t)return null;let a=r.startDecodeTimestamp+(t-r.startIndex)*r.delta,s=Q(i.sampleCompositionTimeOffsets,t,y=>y.startIndex),o=i.sampleCompositionTimeOffsets[s];o&&t-o.startIndexy.startSampleIndex),l=i.sampleToChunk[u];g(l);let d=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),m=i.chunkOffsets[d],f=l.startSampleIndex+(d-l.startChunkIndex)*l.samplesPerChunk,p=0,b=m;if(i.sampleSizes.length===1)b+=c*(t-f),p+=c*l.samplesPerChunk;else for(let y=f;yy)!==-1:!0}},bp=(i,t)=>{if(!i.keySampleIndices)return t+1;let e=Q(i.keySampleIndices,t,r=>r);return i.keySampleIndices[e+1]??-1},vc=(i,t)=>{i.startTimestamp+=t,i.endTimestamp+=t;for(let e of i.samples)e.presentationTimestamp+=t;for(let e of i.presentationTimestamps)e.presentationTimestamp+=t},_d=i=>[$r(i),$r(i),As(i),$r(i),$r(i),As(i),$r(i),$r(i),As(i)],Rd=(i,t)=>{let e=i.info;if(e.type!=="video")return;let{num:r,den:n}=t;!(r>0&&n>0)||r===n||(r>n?(e.squarePixelWidth=Math.round(e.width*r/n),e.squarePixelHeight=e.height):(e.squarePixelWidth=e.width,e.squarePixelHeight=Math.round(e.height*n/r)))},Fd=i=>i.sampleSizes.length===0,Md=i=>i.currentFragmentState?i.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:i.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},Vd=async(i,t,e)=>{if(e.resolved)return e.resolved;if(e.offset===null||e.sampleCount===0)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(e.defaultSampleInfoSize>0)r=e.defaultSampleInfoSize*e.sampleCount;else{g(e.sampleSizes);for(let o=0;o0?e.defaultSampleInfoSize:e.sampleSizes[o],u=new Uint8Array(16);a>0?u.set(V(n,a),0):u.set(t.defaultConstantIv,0);let l=null;if(c>a){let d=he(n);l=[];for(let m=0;mi.defaultConstantIv?{iv:i.defaultConstantIv,subsamples:null}:null,Od=async(i,t,e,r)=>{g(i.encryptionInfo);let n=i.encryptionInfo;g(n.defaultKid!==null);let a=n.defaultKid,s,o=i.demuxer.decryptionKeyCache.get(a);if(o)s=await o;else{if(!i.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");let c=(async()=>{let u=i.demuxer.psshBoxes;if(r){u=[...u,...r.psshBoxes].filter(d=>d.keyIds===null||d.keyIds.includes(a));for(let d=0;d{let n=new Uint8Array(16);n.set(e.iv,0);let a=await crypto.subtle.importKey("raw",i,{name:"AES-CTR"},!1,["decrypt"]),s=async p=>{let b=await crypto.subtle.decrypt({name:"AES-CTR",counter:n,length:64},a,p);return new Uint8Array(b)};if(!e.subsamples)return s(r);g(t.defaultCryptByteBlock!==null&&t.defaultSkipByteBlock!==null);let o=Ud(e.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock),c=0;for(let p of o)for(let b of p.perSubsample)c+=b.length;let u=new Uint8Array(c),l=0;for(let p of o)for(let b of p.perSubsample)u.set(r.subarray(b.offset,b.offset+b.length),l),l+=b.length;let d=await s(u),m=new Uint8Array(r),f=0;for(let p of o)for(let b of p.perSubsample)m.set(d.subarray(f,f+b.length),b.offset),f+=b.length;return m},kp=(i,t,e,r)=>{let n=new ea;n.init({key:i,iv:e.iv});let a=t.defaultCryptByteBlock,s=t.defaultSkipByteBlock;if(g(a!==null&&s!==null),!e.subsamples){let l=new Uint8Array(r),d=Math.floor(r.length/16);for(let m=0;m{let r=[],n=t!==0||e!==0,a=0;for(let s of i){a+=s.clearLen;let o=[];if(!n)s.protectedLen>0&&o.push({offset:a,length:s.protectedLen}),a+=s.protectedLen;else{let c=s.protectedLen,u=a;for(;c>0&&!(c<16*t);){let l=16*t;o.push({offset:u,length:l}),u+=l,c-=l;let d=Math.min(16*e,c);u+=d,c-=d}a+=s.protectedLen}r.push({perSubsample:o})}return r};var Yr=class{constructor(t){this.value=t}},sn=class{constructor(t){this.value=t}},ra=class{constructor(t){this.value=t}},Vt=class{constructor(t){this.value=t}};var Tp=[440786851,408125543],on=[290298740,357149030,524531317,374648427,475249515,423732329,272869232,307544935],ia=[...Tp,...on],Nd=i=>i<256?1:i<65536?2:i<1<<24?3:i<2**32?4:i<2**40?5:6,Ld=i=>i<1n<<8n?1:i<1n<<16n?2:i<1n<<24n?3:i<1n<<32n?4:i<1n<<40n?5:i<1n<<48n?6:i<1n<<56n?7:8,Wd=i=>i>=-64&&i<64?1:i>=-8192&&i<8192?2:i>=-(1<<20)&&i<1<<20?3:i>=-(1<<27)&&i<1<<27?4:i>=-(2**34)&&i<2**34?5:6,wp=i=>{if(i<127)return 1;if(i<16383)return 2;if(i<(1<<21)-1)return 3;if(i<(1<<28)-1)return 4;if(i<2**35-1)return 5;if(i<2**42-1)return 6;throw new Error("EBML varint size not supported "+i)},_s=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer);this.offsets=new WeakMap;this.dataOffsets=new WeakMap}writeByte(t){this.helperView.setUint8(0,t),this.writer.write(this.helper.subarray(0,1))}writeFloat32(t){this.helperView.setFloat32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(t){this.helperView.setFloat64(0,t,!1),this.writer.write(this.helper)}writeUnsignedInt(t,e=Nd(t)){let r=0;switch(e){case 6:this.helperView.setUint8(r++,t/2**40|0);case 5:this.helperView.setUint8(r++,t/2**32|0);case 4:this.helperView.setUint8(r++,t>>24);case 3:this.helperView.setUint8(r++,t>>16);case 2:this.helperView.setUint8(r++,t>>8);case 1:this.helperView.setUint8(r++,t);break;default:throw new Error("Bad unsigned int size "+e)}this.writer.write(this.helper.subarray(0,r))}writeUnsignedBigInt(t,e=Ld(t)){let r=0;for(let n=e-1;n>=0;n--)this.helperView.setUint8(r++,Number(t>>BigInt(n*8)&0xffn));this.writer.write(this.helper.subarray(0,r))}writeSignedInt(t,e=Wd(t)){t<0&&(t+=2**(e*8)),this.writeUnsignedInt(t,e)}writeVarInt(t,e=wp(t)){let r=0;switch(e){case 1:this.helperView.setUint8(r++,128|t);break;case 2:this.helperView.setUint8(r++,64|t>>8),this.helperView.setUint8(r++,t);break;case 3:this.helperView.setUint8(r++,32|t>>16),this.helperView.setUint8(r++,t>>8),this.helperView.setUint8(r++,t);break;case 4:this.helperView.setUint8(r++,16|t>>24),this.helperView.setUint8(r++,t>>16),this.helperView.setUint8(r++,t>>8),this.helperView.setUint8(r++,t);break;case 5:this.helperView.setUint8(r++,8|t/2**32&7),this.helperView.setUint8(r++,t>>24),this.helperView.setUint8(r++,t>>16),this.helperView.setUint8(r++,t>>8),this.helperView.setUint8(r++,t);break;case 6:this.helperView.setUint8(r++,4|t/2**40&3),this.helperView.setUint8(r++,t/2**32|0),this.helperView.setUint8(r++,t>>24),this.helperView.setUint8(r++,t>>16),this.helperView.setUint8(r++,t>>8),this.helperView.setUint8(r++,t);break;default:throw new Error("Bad EBML varint size "+e)}this.writer.write(this.helper.subarray(0,r))}writeAsciiString(t){this.writer.write(new Uint8Array(t.split("").map(e=>e.charCodeAt(0))))}writeEBML(t){if(t!==null)if(t instanceof Uint8Array)this.writer.write(t);else if(Array.isArray(t))for(let e of t)this.writeEBML(e);else if(this.offsets.set(t,this.writer.getPos()),this.writeUnsignedInt(t.id),Array.isArray(t.data)){let e=this.writer.getPos(),r=t.size===-1?1:t.size??4;t.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+r);let n=this.writer.getPos();if(this.dataOffsets.set(t,n),this.writeEBML(t.data),t.size!==-1){let a=this.writer.getPos()-n,s=this.writer.getPos();this.writer.seek(e),this.writeVarInt(a,r),this.writer.seek(s)}}else if(typeof t.data=="number"){let e=t.size??Nd(t.data);this.writeVarInt(e),this.writeUnsignedInt(t.data,e)}else if(typeof t.data=="bigint"){let e=t.size??Ld(t.data);this.writeVarInt(e),this.writeUnsignedBigInt(t.data,e)}else if(typeof t.data=="string")this.writeVarInt(t.data.length),this.writeAsciiString(t.data);else if(t.data instanceof Uint8Array)this.writeVarInt(t.data.byteLength,t.size),this.writer.write(t.data);else if(t.data instanceof Yr)this.writeVarInt(4),this.writeFloat32(t.data.value);else if(t.data instanceof sn)this.writeVarInt(8),this.writeFloat64(t.data.value);else if(t.data instanceof ra){let e=t.size??Wd(t.data.value);this.writeVarInt(e),this.writeSignedInt(t.data.value,e)}else if(t.data instanceof Vt){let e=Y.encode(t.data.value);this.writeVarInt(e.length),this.writer.write(e)}else ne(t.data)}},Rc=8,je=2,Tt=2*Rc,Fc=i=>{if(i.remainingLength<1)return null;let t=L(i);if(i.skip(-1),t===0)return null;let e=1,r=128;for(;(t&r)===0;)e++,r>>=1;return i.remainingLength{if(i.remainingLength<1)return null;let t=L(i);if(t===0)return null;let e=1,r=128;for(;(t&r)===0;)e++,r>>=1;if(i.remainingLength{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let e=0;for(let r=0;r{if(t<1)throw new Error("Bad unsigned int size "+t);let e=0n;for(let r=0;r{let t=Fc(i);return t===null||i.remainingLength{if(i.remainingLength<1)return null;if(L(i)===255)return;i.skip(-1);let e=cn(i);if(e===null)return null;if(e!==72057594037927940)return e},wt=i=>{g(i.remainingLength>=je);let t=Rs(i);if(t===null)return null;let e=Mc(i);return e===null?null:{id:t,size:e}},Zr=(i,t)=>{let e=V(i,t),r=0;for(;r{let e=V(i,t),r=0;for(;r{if(t===0)return 0;if(t!==4&&t!==8)throw new Error("Bad float size "+t);return t===4?qd(i):vs(i)},Fs=async(i,t,e,r)=>{let n=new Set(e),a=t;for(;r===null||aa?r:a,found:!1}},Bc=async(i,t,e,r)=>{let a=new Set(e),s=t;for(;s{let e=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isWebM?"webm":"x-matroska");if(i.codecStrings.length>0){let r=[...new Set(i.codecStrings.filter(Boolean))];e+=`; codecs="${r.join(", ")}"`}return e};var Oc=[{id:290298740,flag:"seekHeadSeen"},{id:357149030,flag:"infoSeen"},{id:374648427,flag:"tracksSeen"},{id:475249515,flag:"cuesSeen"}],Qd=10*2**20,Bs=class extends Ae{constructor(e){super(e);this.readMetadataPromise=null;this.segments=[];this.currentSegment=null;this.currentTrack=null;this.currentCluster=null;this.currentBlock=null;this.currentBlockAdditional=null;this.currentCueTime=null;this.currentDecodingInstruction=null;this.currentTagTargetIsMovie=!0;this.currentSimpleTagName=null;this.currentAttachedFile=null;this.isWebM=!1;this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(r=>r.trackBacking))}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),r=await Promise.all(e.map(n=>n.getDecoderConfig().then(a=>a?.codec??null)));return Ms({isWebM:this.isWebM,hasVideo:this.segments.some(n=>n.tracks.some(a=>a.info?.type==="video")),hasAudio:this.segments.some(n=>n.tracks.some(a=>a.info?.type==="audio")),codecStrings:r.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let r of this.segments)r.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(r),r.metadataTagsCollected=!0);let e={};for(let r of this.segments)e={...e,...r.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,je,Tt);if(_(r)&&(r=await r),!r)break;let n=wt(r);if(!n)break;let a=n.id,s=n.size,o=r.filePos;if(a===440786851){rr(s);let c=this.reader.requestSlice(o,s);if(_(c)&&(c=await c),!c)break;this.readContiguousElements(c)}else if(a===408125543){if(await this.readSegment(o,s),s===void 0||this.reader.fileSize===null)break}else if(a===524531317){if(this.reader.fileSize===null)break;s===void 0&&(s=(await Fs(this.reader,o,ia,this.reader.fileSize)).pos-o);let c=Z(this.segments);c&&(c.elementEndPos=o+s)}rr(s),e=o+s}})()}async readSegment(e,r){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:r===void 0?null:e+r,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e,a=new Set;for(;this.currentSegment.elementEndPos===null||nh.id===m);if(b!==-1){let h=Oc[b].flag;this.currentSegment[h]=!0,m===290298740&&a.add(l-e),rr(f);let y=this.reader.requestSlice(p,f);_(y)&&(y=await y),y&&this.readContiguousElements(y)}else if(m===307544935||m===423732329){m===307544935?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,rr(f);let h=this.reader.requestSlice(p,f);_(h)&&(h=await h),h&&this.readContiguousElements(h)}else if(m===524531317){this.currentSegment.clusterSeekStartPos=l;break}if(f===void 0)break;n=p+f}if(this.reader.fileSize!==null)for(;;){let u=this.currentSegment.seekEntries.find(p=>p.id===290298740&&!a.has(p.segmentPosition));if(!u)break;a.add(u.segmentPosition);let l=this.reader.requestSliceRange(e+u.segmentPosition,je,Tt);if(_(l)&&(l=await l),!l)continue;let d=wt(l);if(!d||d.id!==290298740)continue;let{size:m}=d;rr(m);let f=this.reader.requestSlice(l.filePos,m);_(f)&&(f=await f),f&&this.readContiguousElements(f)}if(this.currentSegment.seekEntries.sort((u,l)=>u.segmentPosition-l.segmentPosition),this.reader.fileSize!==null)for(let u of this.currentSegment.seekEntries){let l=Oc.find(h=>h.id===u.id);if(!l||this.currentSegment[l.flag])continue;let d=this.reader.requestSliceRange(e+u.segmentPosition,je,Tt);if(_(d)&&(d=await d),!d)continue;let m=wt(d);if(!m)continue;let{id:f,size:p}=m;if(f!==l.id)continue;rr(p),this.currentSegment[l.flag]=!0;let b=this.reader.requestSlice(d.filePos,p);_(b)&&(b=await b),b&&this.readContiguousElements(b)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(let u of this.currentSegment.tracks)u.defaultDurationNs!==null&&(u.defaultDuration=this.currentSegment.timestampFactor*u.defaultDurationNs/1e9);let s=new Map(this.currentSegment.tracks.map(u=>[u.id,u]));for(let u of this.currentSegment.cuePoints){let l=s.get(u.trackId);l&&l.cuePoints.push(u)}for(let u of this.currentSegment.tracks){u.cuePoints.sort((l,d)=>l.time-d.time);for(let l=0;lc&&(c=u.cuePoints.length,o=u);for(let u of this.currentSegment.tracks)u.cuePoints.length===0&&(u.cuePoints=o.cuePoints);this.currentSegment=null}async readCluster(e,r){if(r.lastReadCluster?.elementStartPos===e)return r.lastReadCluster;let n=this.reader.requestSliceRange(e,je,Tt);_(n)&&(n=await n),g(n);let a=e,s=wt(n);g(s);let o=s.id;g(o===524531317);let c=s.size,u=n.filePos;c===void 0&&(c=(await Fs(this.reader,u,ia,r.elementEndPos)).pos-u);let l=this.reader.requestSlice(u,c);_(l)&&(l=await l);let d={segment:r,elementStartPos:a,elementEndPos:u+c,dataStartPos:u,timestamp:-1,trackData:new Map};if(this.currentCluster=d,l){let m=this.readContiguousElements(l,ia);d.elementEndPos=m}for(let[,m]of d.trackData){let f=m.track;g(m.blocks.length>0);let p=!1;for(let k=0;k({timestamp:k.timestamp,blockIndex:T})).sort((k,T)=>k.timestamp-T.timestamp);for(let k=0;k({timestamp:k.timestamp,blockIndex:T})).sort((k,T)=>k.timestamp-T.timestamp));let b=m.blocks[m.presentationTimestamps[0].blockIndex],h=m.blocks[Z(m.presentationTimestamps).blockIndex];m.startTimestamp=b.timestamp,m.endTimestamp=h.timestamp+h.duration;let y=Q(f.clusterPositionCache,m.startTimestamp,k=>k.startTimestamp);(y===-1||f.clusterPositionCache[y].elementStartPos!==a)&&f.clusterPositionCache.splice(y+1,0,{elementStartPos:d.elementStartPos,startTimestamp:m.startTimestamp})}return r.lastReadCluster=d,d}getTrackDataInCluster(e,r){let n=e.trackData.get(r);if(!n){let a=e.segment.tracks.find(s=>s.id===r);if(!a)return null;n={track:a,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(r,n)}return n}expandLacedBlocks(e,r){for(let n=0;n=je;){let n=e.filePos;if(!this.traverseElement(e,r))return n}return e.filePos}traverseElement(e,r){let n=wt(e);if(!n||r&&r.includes(n.id))return!1;let{id:a,size:s}=n,o=e.filePos;switch(rr(s),a){case 17026:this.isWebM=Zr(e,s)==="webm";break;case 19899:{if(!this.currentSegment)break;let c={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(c),this.readContiguousElements(e.slice(o,s)),(c.id===-1||c.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case 21419:{let c=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!c)break;c.id=G(e,s)}break;case 21420:{let c=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!c)break;c.segmentPosition=G(e,s)}break;case 2807729:{if(!this.currentSegment)break;this.currentSegment.timestampScale=G(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case 17545:{if(!this.currentSegment)break;this.currentSegment.duration=ln(e,s)}break;case 174:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{..._e,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(o,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(c=>c.data?.type!=="decompress"||c.scope!==1||c.data.algorithm!==3)&&(z._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let c=this.currentTrack.codecId.indexOf("/"),u=c===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,c);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let d=this.currentTrack.info.displayWidth*this.currentTrack.info.height,m=this.currentTrack.info.displayHeight*this.currentTrack.info.width;d>0&&m>0&&(d>m?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*d/m):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*m/d))}if(this.currentTrack.codecId===Ve.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Ve.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(u===Ve.vp8)this.currentTrack.info.codec="vp8";else if(u===Ve.vp9)this.currentTrack.info.codec="vp9";else if(u===Ve.av1)this.currentTrack.info.codec="av1";else if(u===Ve.prores){let d=this.currentTrack.codecPrivate?ye.decode(this.currentTrack.codecPrivate):"";Tr.includes(d)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=d)}let l=this.currentTrack;this.currentTrack.trackBacking=new Dc(l),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){u===Ve.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Ve.mp3?this.currentTrack.info.codec="mp3":u===Ve.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Ft):u===Ve.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):u===Ve.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):u===Ve.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):u===Ve.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):u===Ve.dts?(this.currentTrack.info.codec="dts",this.currentTrack.codecId==="A_DTS/EXPRESS"?this.currentTrack.info.dtsFormat="dtse":this.currentTrack.codecId==="A_DTS/LOSSLESS"&&(this.currentTrack.info.dtsFormat="dtsl")):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));let l=this.currentTrack;this.currentTrack.trackBacking=new Vc(l),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case 215:{if(!this.currentTrack)break;this.currentTrack.id=G(e,s)}break;case 131:{if(!this.currentTrack)break;let c=G(e,s);c===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,horizontalScale:1,verticalScale:1,rotation:0,codec:null,codecDescription:null,colorSpace:{...Na},alphaMode:!1,proresFormat:null}:c===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case 185:{if(!this.currentTrack)break;G(e,s)||(this.currentTrack=null)}break;case 136:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!G(e,s)}break;case 21930:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!G(e,s)}break;case 21934:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!G(e,s)}break;case 21931:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!G(e,s)}break;case 21932:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!G(e,s)}break;case 21935:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!G(e,s)}break;case 134:{if(!this.currentTrack)break;this.currentTrack.codecId=Zr(e,s)}break;case 25506:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=V(e,s)}break;case 2352003:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=G(e,s)}break;case 21358:{if(!this.currentTrack)break;this.currentTrack.name=un(e,s)}break;case 2274716:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Zr(e,s),gr(this.currentTrack.languageCode)||(this.currentTrack.languageCode=se)}break;case 2274717:{if(!this.currentTrack)break;let u=Zr(e,s).split("-")[0];u?this.currentTrack.languageCode=u:this.currentTrack.languageCode=se,this.currentTrack.hasLanguageBcp47=!0}break;case 224:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(o,s))}break;case 176:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=G(e,s)}break;case 186:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=G(e,s)}break;case 21680:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=G(e,s)}break;case 21690:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=G(e,s)}break;case 21682:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=G(e,s)}break;case 21440:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=G(e,s)===1}break;case 21936:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(o,s))}break;case 21937:{if(this.currentTrack?.info?.type!=="video")break;let c=G(e,s),u=dt[c];this.currentTrack.info.colorSpace.matrix=u}break;case 21945:{if(this.currentTrack?.info?.type!=="video")break;let c=G(e,s);this.currentTrack.info.colorSpace.fullRange=c===1||c===2?c===2:void 0}break;case 21946:{if(this.currentTrack?.info?.type!=="video")break;let c=G(e,s),u=lt[c];this.currentTrack.info.colorSpace.transfer=u}break;case 21947:{if(this.currentTrack?.info?.type!=="video")break;let c=G(e,s),u=ut[c];this.currentTrack.info.colorSpace.primaries=u}break;case 30320:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(o,s))}break;case 30323:{if(this.currentTrack?.info?.type!=="video")break;let c=ln(e,s);try{let u=mr(c);this.currentTrack.info.horizontalScale=Math.round(Math.cos(u*Ba))}catch{}}break;case 30324:{if(this.currentTrack?.info?.type!=="video")break;let c=ln(e,s);try{let u=mr(c);this.currentTrack.info.verticalScale=Math.round(Math.cos(u*Ba))}catch{}}break;case 30325:{if(this.currentTrack?.info?.type!=="video")break;let u=-ln(e,s);try{this.currentTrack.info.rotation=mr(u)}catch{}}break;case 225:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(o,s))}break;case 181:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=ln(e,s)}break;case 159:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=G(e,s)}break;case 25188:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=G(e,s)}break;case 187:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(o,s)),this.currentCueTime=null}break;case 179:this.currentCueTime=G(e,s);break;case 183:{if(this.currentCueTime===null)break;g(this.currentSegment);let c={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(c),this.readContiguousElements(e.slice(o,s)),(c.trackId===-1||c.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case 247:{let c=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!c)break;c.trackId=G(e,s)}break;case 241:{let c=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!c)break;g(this.currentSegment),c.clusterPosition=this.currentSegment.dataStartPos+G(e,s)}break;case 231:{if(!this.currentCluster)break;this.currentCluster.timestamp=G(e,s)}break;case 163:{if(!this.currentCluster)break;let c=cn(e);if(c===null)break;let u=this.getTrackDataInCluster(this.currentCluster,c);if(!u)break;let l=ta(e),d=L(e),m=d>>1&3,f=!!(d&128);u.track.info?.type==="audio"&&u.track.info.codec&&(f=!0);let p=V(e,s-(e.filePos-o)),b=u.track.decodingInstructions.length>0;u.blocks.push({timestamp:l,duration:0,isKeyFrame:f,data:p,lacing:m,decoded:!b,postProcessed:!1,mainAdditional:null})}break;case 160:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(o,s)),this.currentBlock=null}break;case 161:{if(!this.currentCluster)break;let c=cn(e);if(c===null)break;let u=this.getTrackDataInCluster(this.currentCluster,c);if(!u)break;let l=ta(e),m=L(e)>>1&3,f=V(e,s-(e.filePos-o)),p=u.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:f,lacing:m,decoded:!p,postProcessed:!1,mainAdditional:null},u.blocks.push(this.currentBlock)}break;case 30113:this.readContiguousElements(e.slice(o,s));break;case 166:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(o,s)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case 165:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=V(e,s)}break;case 238:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=G(e,s)}break;case 155:{if(!this.currentBlock)break;this.currentBlock.duration=G(e,s)}break;case 251:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case 29555:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(o,s));break;case 25536:this.readContiguousElements(e.slice(o,s));break;case 26826:G(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case 25541:case 25545:case 25540:case 25542:this.currentTagTargetIsMovie=!1;break;case 26568:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(o,s))}break;case 17827:this.currentSimpleTagName=un(e,s);break;case 17543:{if(!this.currentSimpleTagName)break;let c=un(e,s);this.processTagValue(this.currentSimpleTagName,c)}break;case 17541:{if(!this.currentSimpleTagName)break;let c=V(e,s);this.processTagValue(this.currentSimpleTagName,c)}break;case 24999:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(o,s));let c=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(c.raw??={},c.raw[this.currentAttachedFile.fileUid.toString()]=new Nr(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let u=this.currentAttachedFile.fileName,l="unknown";if(u){let d=u.toLowerCase();d.startsWith("cover.")?l="coverFront":d.startsWith("back.")&&(l="coverBack")}c.images??=[],c.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:l,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case 18094:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=Hd(e,s)}break;case 18030:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=un(e,s)}break;case 18016:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Zr(e,s)}break;case 18012:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=V(e,s)}break;case 18046:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=un(e,s)}break;case 28032:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(o,s)),this.currentTrack.decodingInstructions.sort((c,u)=>u.order-c.order)}break;case 25152:this.currentDecodingInstruction={order:0,scope:1,data:null},this.readContiguousElements(e.slice(o,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case 20529:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=G(e,s)}break;case 20530:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=G(e,s)}break;case 20532:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:0,settings:null},this.readContiguousElements(e.slice(o,s))}break;case 16980:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=G(e,s)}break;case 16981:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=V(e,s)}break;case 20533:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=o+s,!0}decodeBlockData(e,r){g(e.decodingInstructions.length>0);let n=r;for(let a of e.decodingInstructions)switch(g(a.data),a.data.type){case"decompress":switch(a.data.algorithm){case 3:if(a.data.settings&&a.data.settings.length>0){let s=a.data.settings,o=new Uint8Array(s.length+n.length);o.set(s,0),o.set(n,s.length),n=o}break;default:}break;default:}return n}processTagValue(e,r){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=r,typeof r=="string")switch(e.toLowerCase()){case"title":n.title??=r;break;case"description":n.description??=r;break;case"artist":n.artist??=r;break;case"album":n.album??=r;break;case"album_artist":n.albumArtist??=r;break;case"genre":n.genre??=r;break;case"bpm":{let a=Number.parseInt(r,10);Number.isInteger(a)&&a>0&&(n.beatsPerMinute??=a)}break;case"comment":n.comment??=r;break;case"lyrics":n.lyrics??=r;break;case"date":{let a=new Date(r);Number.isNaN(a.getTime())||(n.date??=a)}break;case"track_number":case"part_number":{let a=r.split("/"),s=Number.parseInt(a[0],10),o=a[1]&&Number.parseInt(a[1],10);Number.isInteger(s)&&s>0&&(n.trackNumber??=s),o&&Number.isInteger(o)&&o>0&&(n.tracksTotal??=o)}break;case"disc_number":case"disc":{let a=r.split("/"),s=Number.parseInt(a[0],10),o=a[1]&&Number.parseInt(a[1],10);Number.isInteger(s)&&s>0&&(n.discNumber??=s),o&&Number.isInteger(o)&&o>0&&(n.discsTotal??=o)}break}}getDurationFromMetadata(e){return e.duration<=0?null:e.duration/e.timestampFactor}},Os=class{constructor(t){this.internalTrack=t;this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let t=this.internalTrack.demuxer,e=this.internalTrack.trackBacking.getType(),r=0;for(let n of t.segments)for(let a of n.tracks)if(a.trackBacking.getType()===e&&r++,a===this.internalTrack)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)}async getLiveRefreshInterval(){return null}async getFirstPacket(t){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,t)}intoTimescale(t){return hr(t*this.internalTrack.segment.timestampFactor)}async getPacket(t,e){let r=this.intoTimescale(t);return this.performClusterLookup(null,n=>{let a=n.trackData.get(this.internalTrack.id);if(!a)return{blockIndex:-1,correctBlockFound:!1};let s=Q(a.presentationTimestamps,r,u=>u.timestamp),o=s!==-1?a.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&r{if(n===r.cluster){let a=n.trackData.get(this.internalTrack.id);if(r.blockIndex+1{let a=n.trackData.get(this.internalTrack.id);if(!a)return{blockIndex:-1,correctBlockFound:!1};let s=Ur(a.presentationTimestamps,u=>a.blocks[u.blockIndex].isKeyFrame&&u.timestamp<=r),o=s!==-1?a.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&r{if(n===r.cluster){let s=n.trackData.get(this.internalTrack.id).blocks.findIndex((o,c)=>o.isKeyFrame&&c>r.blockIndex);if(s!==-1)return{blockIndex:s,correctBlockFound:!0}}else{let a=n.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){let s=a.blocks.findIndex(o=>o.isKeyFrame);return g(s!==-1),{blockIndex:s,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,e)}async fetchPacketInCluster(t,e,r){if(e===-1)return null;let a=t.trackData.get(this.internalTrack.id).blocks[e];if(g(a),a.decoded||(a.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,a.data),a.decoded=!0),!a.postProcessed){if(this.internalTrack.info?.codec==="prores"&&!(a.data.length>=8&&a.data[4]===105&&a.data[5]===99&&a.data[6]===112&&a.data[7]===102)){let m=new Uint8Array(a.data.length+8);N(m).setUint32(0,m.length,!1),m[4]=105,m[5]=99,m[6]=112,m[7]=102,m.set(a.data,8),a.data=m}a.postProcessed=!0}let s=r.metadataOnly?Te:a.data,o=a.timestamp/this.internalTrack.segment.timestampFactor,c=a.duration/this.internalTrack.segment.timestampFactor,u={};a.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(u.alpha=r.metadataOnly?Te:a.mainAdditional,u.alphaByteLength=a.mainAdditional.byteLength);let l=new X(s,a.isKeyFrame?"key":"delta",o,c,t.dataStartPos+e,a.data.byteLength,u);return this.packetToClusterLocation.set(l,{cluster:t,blockIndex:e}),l}async performClusterLookup(t,e,r,n,a){let{demuxer:s,segment:o}=this.internalTrack,c=null,u=null,l=-1;if(t){let{blockIndex:y,correctBlockFound:k}=e(t);if(k)return this.fetchPacketInCluster(t,y,a);y!==-1&&(u=t,l=y)}let d=Q(this.internalTrack.cuePoints,r,y=>y.time),m=d!==-1?this.internalTrack.cuePoints[d]:null,f=Q(this.internalTrack.clusterPositionCache,r,y=>y.startTimestamp),p=f!==-1?this.internalTrack.clusterPositionCache[f]:null,b=Math.max(m?.clusterPosition??0,p?.elementStartPos??0)||null,h;for(t?b===null||t.elementStartPos>=b?(h=t.elementEndPos,c=t):h=b:h=b??o.clusterSeekStartPos;o.elementEndPos===null||h<=o.elementEndPos-je;){if(c){let P=c.trackData.get(this.internalTrack.id);if(P&&P.startTimestamp>n)break}let y=s.reader.requestSliceRange(h,je,Tt);if(_(y)&&(y=await y),!y)break;let k=h,T=wt(y);if(!T||!on.includes(T.id)&&T.id!==236){let P=await Bc(s.reader,k,on,Math.min(o.elementEndPos??1/0,k+Qd));if(P){h=P;continue}else break}let w=T.id,A=T.size,x=y.filePos;if(w===524531317){c=await s.readCluster(k,o),A=c.elementEndPos-x;let{blockIndex:P,correctBlockFound:S}=e(c);if(S)return this.fetchPacketInCluster(c,P,a);P!==-1&&(u=c,l=P)}A===void 0&&(g(w!==524531317),A=(await Fs(s.reader,x,ia,o.elementEndPos)).pos-x);let C=x+A;if(o.elementEndPos===null){let P=s.reader.requestSliceRange(C,je,Tt);if(_(P)&&(P=await P),!P)break;if(Rs(P)===408125543){o.elementEndPos=C;break}}h=C}if(m&&(!u||u.elementStartPos{let e=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="prores"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));let n={width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?Zt(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?er(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?Zi(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Ci(e.data):null,proresCodecInfo:this.internalTrack.info.codec==="prores"&&e?rs(e.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!Ki(this.internalTrack.info.colorSpace)){let s=ps(n);this.internalTrack.info.colorSpace.primaries??=s.primaries,this.internalTrack.info.colorSpace.transfer??=s.transfer,this.internalTrack.info.colorSpace.matrix??=s.matrix,this.internalTrack.info.colorSpace.fullRange??=s.fullRange}let a={codec:Kr(n),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(a.displayAspectWidth=this.internalTrack.info.squarePixelWidth,a.displayAspectHeight=this.internalTrack.info.squarePixelHeight),a})():null}},Vc=class extends Os{constructor(e){super(e);this.decoderConfigPromise=null}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="dts"&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&ls(e.data)}return{codec:Ji({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}};var na=async(i,t,e,r=null)=>{let a=t;for(;e===null||a=4;){let c=o.filePos,u=M(o),l=i.fileSize!==null?i.fileSize-a:null,d=jr(u,l);if(d.header&&(!r||d.header.sampleRate===r.sampleRate&&d.header.mpegVersionId===r.mpegVersionId&&d.header.layer===r.layer&&Xr(d.header.channel)===Xr(r.channel)))return{header:d.header,startPos:a};o.filePos=c+d.bytesAdvanced,a=o.filePos}}return null};var Ds=class extends Ae{constructor(e){super(e);this.metadataPromise=null;this.firstFrameHeader=null;this.firstFrameHeaderPos=null;this.xingFrameHeader=null;this.xingFrameHeaderPos=null;this.loadedSamples=[];this.metadataTags=null;this.xingData=null;this.trackBackings=[];this.readingMutex=new Le;this.lastSampleLoaded=!1;this.lastLoadedPos=0;this.nextTimestampInSamples=0;this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new Uc(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let c=this.reader.requestSlice(this.lastLoadedPos,Ue);if(_(c)&&(c=await c),!c){this.lastSampleLoaded=!0;return}let u=Je(c);if(!u)break;this.lastLoadedPos=c.filePos+u.size}let e=await na(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e){this.lastSampleLoaded=!0;return}let r=e.header;this.lastLoadedPos=e.startPos+r.totalSize-1;let n=Gr(r.mpegVersionId,r.channel),a=this.reader.requestSlice(e.startPos+n,4);if(_(a)&&(a=await a),a){let c=M(a);if(c===Qr||c===en){if(this.xingFrameHeader||(this.xingFrameHeader=r,this.xingFrameHeaderPos=e.startPos),!this.xingData){let l=this.reader.requestSlice(e.startPos+n+4,12);if(_(l)&&(l=await l),l){let d=V(l,12),m=N(d),f=m.getUint32(0,!1);this.xingData={frameCount:f&1?m.getUint32(4,!1):null,fileSize:f&2?m.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=r,this.firstFrameHeaderPos=e.startPos);let s=r.audioSamplesInFrame/this.firstFrameHeader.sampleRate,o={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:r.totalSize};this.loadedSamples.push(o),this.nextTimestampInSamples+=r.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let r=0,n=!1;for(;;){let a=this.reader.requestSlice(r,Ue);if(_(a)&&(a=await a),!a)break;let s=Je(a);if(!s)break;n=!0;let o=this.reader.requestSlice(a.filePos,s.size);if(_(o)&&(o=await o),!o)break;Jr(o,s,this.metadataTags),r=a.filePos+s.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=aa){let a=this.reader.requestSlice(this.reader.fileSize-aa,aa);_(a)&&(a=await a),g(a),oe(a,3)==="TAG"&&Gd(a,this.metadataTags)}return this.metadataTags}finally{e()}}},Uc=class{constructor(t){this.demuxer=t}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return g(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let t=this.demuxer;if(g(t.firstFrameHeader!==null),g(t.firstFrameHeaderPos!==null),t.xingData){if(t.xingData.frameCount!==null)return t.xingData.frameCount*t.firstFrameHeader.audioSamplesInFrame/t.firstFrameHeader.sampleRate}else if(t.reader.fileSize!==null){let e=xd(t.firstFrameHeader.lowSamplingFrequency,t.firstFrameHeader.layer,t.firstFrameHeader.bitrate,t.firstFrameHeader.sampleRate),r=(t.reader.fileSize-t.firstFrameHeaderPos)/e;return Math.round(r)*t.firstFrameHeader.audioSamplesInFrame/t.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return se}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return g(this.demuxer.firstFrameHeader),Xr(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return g(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{..._e}}async getDecoderConfig(){return g(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:Xr(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(t,e){if(t===-1)return null;let r=this.demuxer.loadedSamples[t];if(!r)return null;let n;if(e.metadataOnly)n=Te;else{let a=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(_(a)&&(a=await a),!a)return null;n=V(a,r.dataSize)}return new X(n,"key",r.timestamp,r.duration,t,r.dataSize)}getFirstPacket(t){return this.getPacketAtIndex(0,t)}async getNextPacket(t,e){let r=await this.demuxer.readingMutex.acquire();try{let n=pr(this.demuxer.loadedSamples,t.timestamp,s=>s.timestamp);if(n===-1)throw new Error("Packet was not created from this track.");let a=n+1;for(;a>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(a,e)}finally{r()}}async getPacket(t,e){let r=await this.demuxer.readingMutex.acquire();try{for(;;){let n=Q(this.demuxer.loadedSamples,t,a=>a.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(n,e);if(n>=0&&n+1>>0&4294967295}var Vs=i=>{let t=N(i),e=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let n=0;n>>24^a])>>>0}return t.setUint32(22,e,!0),r},oa=(i,t,e)=>{let r=0,n=null;if(i.length>0)if(t.codec==="vorbis"){g(t.vorbisInfo);let a=t.vorbisInfo.modeBlockflags.length,o=(1<>1;if(c>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let u=e,l=t.vorbisInfo.modeBlockflags[c];if(n=t.vorbisInfo.blocksizes[l],l===1){let d=(o|1)+1,m=i[0]&d?1:0;u=t.vorbisInfo.blocksizes[m]}r=u!==null?u+n>>2:0}else t.codec==="opus"&&(r=sd(i).durationInSamples);return{durationInSamples:r,vorbisBlockSize:n}},Us=i=>{let t="audio/ogg";if(i.codecStrings){let e=[...new Set(i.codecStrings)];t+=`; codecs="${e.join(", ")}"`}return t};var Pr=27,Ii=282,zs=Ii+255*255,dn=i=>{let t=i.filePos;if(Pi(i)!==sa)return null;i.skip(1);let r=L(i),n=$d(i),a=Pi(i),s=Pi(i),o=Pi(i),c=L(i),u=new Uint8Array(c);for(let f=0;ff+p,0),m=l+d;return{headerStartPos:t,totalSize:m,dataStartPos:t+l,dataSize:d,headerType:r,granulePosition:n,serialNumber:a,sequenceNumber:s,checksum:o,lacingValues:u}},Xd=(i,t)=>{for(;i.filePos>>8&255,a=e>>>16&255,s=e>>>24&255,o=79;if(!(r!==o&&n!==o&&a!==o&&s!==o)){if(i.skip(-4),e===sa)return!0;i.skip(1)}}return!1};var Ns=class extends Ae{constructor(e){super(e);this.metadataPromise=null;this.bitstreams=[];this.trackBackings=[];this.metadataTags={};this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,Pr,Ii);if(_(r)&&(r=await r),!r)break;let n=dn(r);if(!n||!!!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let r of this.bitstreams){let n=await this.readPacket(r.bosPage,0);n&&(n.data.byteLength>=7&&n.data[0]===1&&n.data[1]===118&&n.data[2]===111&&n.data[3]===114&&n.data[4]===98&&n.data[5]===105&&n.data[6]===115?await this.readVorbisMetadata(n,r):n.data.byteLength>=8&&n.data[0]===79&&n.data[1]===112&&n.data[2]===117&&n.data[3]===115&&n.data[4]===72&&n.data[5]===101&&n.data[6]===97&&n.data[7]===100&&await this.readOpusMetadata(n,r),r.codecInfo.codec!==null&&this.trackBackings.push(new zc(r,this)))}})()}async readVorbisMetadata(e,r){let n=await this.findNextPacketStart(e);if(!n)return;let a=await this.readPacket(n.startPage,n.startSegmentIndex);if(!a||(n=await this.findNextPacketStart(a),!n))return;let s=await this.readPacket(n.startPage,n.startSegmentIndex);if(!s||a.data[0]!==3||s.data[0]!==5)return;let o=[],c=m=>{for(;o.push(Math.min(255,m)),!(m<255);)m-=255};c(e.data.length),c(a.data.length);let u=new Uint8Array(1+o.length+e.data.length+a.data.length+s.data.length);u[0]=2,u.set(o,1),u.set(e.data,1+o.length),u.set(a.data,1+o.length+e.data.length),u.set(s.data,1+o.length+e.data.length+a.data.length),r.codecInfo.codec="vorbis",r.description=u,r.lastMetadataPacket=s;let l=N(e.data);r.numberOfChannels=l.getUint8(11),r.sampleRate=l.getUint32(12,!0);let d=l.getUint8(28);r.codecInfo.vorbisInfo={blocksizes:[1<<(d&15),1<<(d>>4)],modeBlockflags:is(s.data).modeBlockflags},Kn(a.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,r){let n=await this.findNextPacketStart(e);if(!n)return;let a=await this.readPacket(n.startPage,n.startSegmentIndex);if(!a)return;r.codecInfo.codec="opus",r.description=e.data,r.lastMetadataPacket=a;let s=Hr(e.data);r.numberOfChannels=s.outputChannelCount,r.sampleRate=Ft,r.codecInfo.opusInfo={preSkip:s.preSkip},Kn(a.data.subarray(8),this.metadataTags)}async readPacket(e,r){g(rm+f.length,0);if(u===0)return null;let l=new Uint8Array(u),d=0;for(let m=0;mr.getDecoderConfig().then(n=>n?.codec??null)));return Us({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},zc=class{constructor(t,e){this.bitstream=t;this.demuxer=e;this.encodedPacketToMetadata=new WeakMap;this.sequentialScanCache=[];this.sequentialScanMutex=new Le;this.firstTimestampInSamplesPromise=null;this.internalSampleRate=t.codecInfo.codec==="opus"?Ft:t.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){let t=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return g(t!==-1),t+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return g(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return se}getDisposition(){return{..._e,primary:!1}}granulePositionToTimestampInSamples(t){return this.bitstream.codecInfo.codec==="opus"?(g(this.bitstream.codecInfo.opusInfo),t-this.bitstream.codecInfo.opusInfo.preSkip):t}createEncodedPacketFromOggPacket(t,e,r){if(!t)return null;let n=oa(t.data,this.bitstream.codecInfo,e.vorbisLastBlocksize),{vorbisBlockSize:a}=n,{durationInSamples:s}=n;if(!!(t.endPage.headerType&4)&&t.endSegmentIndex===t.endPage.lacingValues.length-1){let d=this.granulePositionToTimestampInSamples(t.endPage.granulePosition);s=ee(d-e.timestampInSamples,0,s)}let c=Math.max(e.timestampInSamples,0),u=Math.max(e.timestampInSamples+s,0),l=new X(r.metadataOnly?Te:t.data,"key",c/this.internalSampleRate,(u-c)/this.internalSampleRate,t.endPage.headerStartPos+t.endSegmentIndex,t.data.byteLength);return this.encodedPacketToMetadata.set(l,{packet:t,timestampInSamples:e.timestampInSamples,durationInSamples:s,vorbisLastBlockSize:e.vorbisLastBlocksize,vorbisBlockSize:a}),l}getFirstTimestampInSamples(){return this.firstTimestampInSamplesPromise??=(async()=>{let t=this.granulePositionToTimestampInSamples(0);g(this.bitstream.lastMetadataPacket);let e=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!e)return t;let r=null,n=0,a=null;for(;e;){let s=await this.demuxer.readPacket(e.startPage,e.startSegmentIndex);if(!s||(r??=s.endPage,s.endPage.headerStartPos!==r.headerStartPos))break;let{durationInSamples:o,vorbisBlockSize:c}=oa(s.data,this.bitstream.codecInfo,a);n+=o,a=c,e=await this.demuxer.findNextPacketStart(s)}return r?t+Math.max(r.granulePosition-n,0):t})()}async getFirstPacket(t){g(this.bitstream.lastMetadataPacket);let e=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!e)return null;let r=await this.getFirstTimestampInSamples(),n=await this.demuxer.readPacket(e.startPage,e.startSegmentIndex);return this.createEncodedPacketFromOggPacket(n,{timestampInSamples:r,vorbisLastBlocksize:null},t)}async getNextPacket(t,e){let r=this.encodedPacketToMetadata.get(t);if(!r)throw new Error("Packet was not created from this track.");let n=await this.demuxer.findNextPacketStart(r.packet);if(!n)return null;let a=r.timestampInSamples+r.durationInSamples,s=await this.demuxer.readPacket(n.startPage,n.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:a,vorbisLastBlocksize:r.vorbisBlockSize},e)}async getPacket(t,e){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(t,e);let r=hr(t*this.internalSampleRate),n=await this.getFirstTimestampInSamples();if(r===Math.max(n,0))return this.getFirstPacket(e);if(rr?o=I.headerStartPos:(s=I,c.push(I));continue e}}let u=a.startPage;for(let T of c){if(T.granulePosition===s.granulePosition)break;(!u||T.headerStartPos>u.headerStartPos)&&(u=T)}let l=u,d=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===s.granulePosition);){let T=l.headerStartPos+l.totalSize,w=this.demuxer.reader.requestSliceRange(T,Pr,Ii);_(w)&&(w=await w),g(w);let A=dn(w);g(A),l=A,l.serialNumber===this.bitstream.serialNumber&&d.push(l)}g(l.granulePosition!==-1);let m=null,f,p,b=l,h=0;if(l.headerStartPos===a.startPage.headerStartPos)f=n,p=!0,m=0;else{f=0,p=!1;for(let A=l.lacingValues.length-1;A>=0;A--)if(l.lacingValues[A]<255){m=A+1;break}if(m===null)throw new Error("Invalid page with granule position: no packets end on this page.");h=m-1;let T={data:Te,endPage:b,endSegmentIndex:h};if(await this.demuxer.findNextPacketStart(T)){let A=Zd(d,l,m);g(A);let x=Yd(d,A.page,A.segmentIndex);x&&(l=x.page,m=x.segmentIndex)}else for(;;){let A=Zd(d,l,m);if(!A)break;let x=Yd(d,A.page,A.segmentIndex);if(!x)break;if(l=x.page,m=x.segmentIndex,A.page.headerStartPos!==b.headerStartPos){b=A.page,h=A.segmentIndex;break}}}let y=null,k=null;for(;l!==null;){g(m!==null);let T=await this.demuxer.readPacket(l,m);if(!T)break;if(!(l.headerStartPos===a.startPage.headerStartPos&&mr||Math.max(C.timestampInSamples,0)===r))break}let A=await this.demuxer.findNextPacketStart(T);if(!A)break;l=A.startPage,m=A.startSegmentIndex}return y}async getPacketSequential(t,e){let r=await this.sequentialScanMutex.acquire();try{let n=hr(t*this.internalSampleRate);t=n/this.internalSampleRate;let a=Q(this.sequentialScanCache,n,c=>c.timestampInSamples),s;if(a!==-1){let c=this.sequentialScanCache[a];s=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},e)}else if(s=await this.getFirstPacket(e),s&&s.timestamp>t)return null;let o=0;for(;s&&s.timestampt)break;if(s=c,o++,o===100){o=0;let u=this.encodedPacketToMetadata.get(s);g(u),this.sequentialScanCache.length>0&&g(Z(this.sequentialScanCache).timestampInSamples<=u.timestampInSamples),this.sequentialScanCache.push(u)}}return s}finally{r()}}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}},Yd=(i,t,e)=>{let r=t,n=e;e:for(;;){for(n--,n;n>=0;n--)if(r.lacingValues[n]<255){n++;break e}if(g(n===-1),!(r.headerType&1)){n=0;break}let s=fc(i,o=>o.headerStartPos{if(e>0)return{page:t,segmentIndex:e-1};let r=fc(i,n=>n.headerStartPos{let e=this.reader.requestSlice(0,12);_(e)&&(e=await e),g(e);let r=oe(e,4),n=r!=="RIFX",a=r==="RF64",s=Ir(e,n),o=a?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(oe(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let u=0,l=null,d=e.filePos;for(;o===null||d=18&&s!==357){let d=fn(a,n),m=r-18;if(Math.min(m,d)>=22&&s===65534){a.skip(6);let p=V(a,16);s=p[0]|p[1]<<8}}if((s===7||s===6)&&(l=8),s!==1&&s!==3&&s!==6&&s!==7)throw new Error(`Unsupported WAVE codec (format tag ${s}). Only integer/float PCM, A-law, and \u03BC-law are supported.`);if(s===1&&![8,16,24,32].includes(l))throw new Error(`Unsupported WAVE PCM bit depth (${l}). Only 8, 16, 24, and 32 bits are supported.`);if(s===3&&![32,64].includes(l))throw new Error(`Unsupported WAVE float bit depth (${l}). Only 32 and 64 bits are supported.`);this.audioInfo={format:s,numberOfChannels:o,sampleRate:c,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:u}}async parseListChunk(e,r,n){let a=this.reader.requestSlice(e,r);if(_(a)&&(a=await a),!a)return;let s=oe(a,4);if(s!=="INFO"&&s!=="INF0")return;let o=a.filePos;for(;o<=e+r-8;){a.filePos=o;let c=oe(a,4),u=Ir(a,n),l=V(a,u),d=0;for(let f=0;f0&&(this.metadataTags.trackNumber??=p),b&&Number.isInteger(b)&&b>0&&(this.metadataTags.tracksTotal??=b)}break;case"ICRD":case"IDIT":{let f=new Date(m);Number.isNaN(f.getTime())||(this.metadataTags.date??=f)}break;case"YEAR":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(this.metadataTags.date??=new Date(f,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=m;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=m;break}o+=8+u+(u&1)}}async parseId3Chunk(e,r){let n=this.reader.requestSlice(e,r);if(_(n)&&(n=await n),!n)return;let a=Je(n);if(a){let s=r-Ue;if(a.size=Math.min(a.size,s),a.size>0){let o=n.slice(e+Ue,a.size);Jr(o,a,this.metadataTags)}}}getCodec(){if(g(this.audioInfo),this.audioInfo.format===7)return"ulaw";if(this.audioInfo.format===6)return"alaw";if(this.audioInfo.format===1){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}if(this.audioInfo.format===3){if(this.audioInfo.sampleSizeInBytes===4)return"pcm-f32";if(this.audioInfo.sampleSizeInBytes===8)return"pcm-f64"}g(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},mn=2048,Nc=class{constructor(t){this.demuxer=t}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let t=this.demuxer.getCodec();return t?(g(this.demuxer.audioInfo),{codec:t,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return g(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return se}getDisposition(){return{..._e}}async getPacketAtIndex(t,e){g(t>=0),g(this.demuxer.audioInfo);let r=t*mn*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;let n=Math.min(mn*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,n);if(_(c)&&(c=await c),!c)return null}let a;if(e.metadataOnly)a=Te;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,n);_(c)&&(c=await c),g(c),a=V(c,n)}let s=t*mn/this.demuxer.audioInfo.sampleRate,o=n/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(t,this.demuxer.lastKnownPacketIndex),new X(a,"key",s,o,t,n)}getFirstPacket(t){return this.getPacketAtIndex(0,t)}async getPacket(t,e){g(this.demuxer.audioInfo);let r=Math.floor(Math.min(t*this.demuxer.audioInfo.sampleRate/mn,(this.demuxer.dataSize-1)/(mn*this.demuxer.audioInfo.blockSizeInBytes)));if(r<0)return null;let n=await this.getPacketAtIndex(r,e);if(n)return n;if(r===0)return null;g(this.demuxer.reader.fileSize===null);let a=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,e);for(;a;){let s=await this.getNextPacket(a,e);if(!s)break;a=s}return a}getNextPacket(t,e){g(this.demuxer.audioInfo);let r=Math.round(t.timestamp*this.demuxer.audioInfo.sampleRate/mn);return this.getPacketAtIndex(r+1,e)}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}};var Er=7,mt=9,et=i=>{let t=i.filePos,e=V(i,9),r=new H(e);if(r.readBits(12)!==4095||(r.skipBits(1),r.readBits(2)!==0))return null;let s=r.readBits(1),o=r.readBits(2)+1,c=r.readBits(4);if(c===15)return null;r.skipBits(1);let u=r.readBits(3);if(u===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);let l=r.readBits(13);r.skipBits(11);let d=r.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let m=null;return s===1?i.filePos-=2:m=r.readBits(16),{objectType:o,samplingFrequencyIndex:c,channelConfiguration:u,frameLength:l,numberOfAacFrames:d,crcCheck:m,startPos:t}};var ca=1024,Ws=class extends Ae{constructor(e){super(e);this.metadataPromise=null;this.firstFrameHeader=null;this.loadedSamples=[];this.metadataTags=null;this.trackBackings=[];this.readingMutex=new Le;this.lastSampleLoaded=!1;this.lastLoadedPos=0;this.nextTimestampInSamples=0;this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();g(this.firstFrameHeader),this.trackBackings=[new Wc(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,Ue);if(_(o)&&(o=await o),!o){this.lastSampleLoaded=!0;return}let c=Je(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,Er,mt);if(_(e)&&(e=await e),!e){this.lastSampleLoaded=!0;return}let r=et(e);if(!r){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&r.startPos+r.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=r);let n=kt[r.samplingFrequencyIndex];g(n!==void 0);let a=ca/n,s={timestamp:this.nextTimestampInSamples/n,duration:a,dataStart:r.startPos,dataSize:r.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=ca,this.lastLoadedPos=r.startPos+r.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let r=0;for(;;){let n=this.reader.requestSlice(r,Ue);if(_(n)&&(n=await n),!n)break;let a=Je(n);if(!a)break;let s=this.reader.requestSlice(n.filePos,a.size);if(_(s)&&(s=await s),!s)break;Jr(s,a,this.metadataTags),r=n.filePos+a.size}return this.metadataTags}finally{e()}}},Wc=class{constructor(t){this.demuxer=t}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/ca}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return se}getCodec(){return"aac"}getInternalCodecId(){return g(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){g(this.demuxer.firstFrameHeader);let t=Xt[this.demuxer.firstFrameHeader.channelConfiguration];return g(t!==void 0),t}getSampleRate(){g(this.demuxer.firstFrameHeader);let t=kt[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return g(t!==void 0),t}getDisposition(){return{..._e}}async getDecoderConfig(){return g(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(t,e){if(t===-1)return null;let r=this.demuxer.loadedSamples[t];if(!r)return null;let n;if(e.metadataOnly)n=Te;else{let a=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(_(a)&&(a=await a),!a)return null;n=V(a,r.dataSize)}return new X(n,"key",r.timestamp,r.duration,t,r.dataSize)}getFirstPacket(t){return this.getPacketAtIndex(0,t)}async getNextPacket(t,e){let r=await this.demuxer.readingMutex.acquire();try{let n=pr(this.demuxer.loadedSamples,t.timestamp,s=>s.timestamp);if(n===-1)throw new Error("Packet was not created from this track.");let a=n+1;for(;a>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(a,e)}finally{r()}}async getPacket(t,e){let r=await this.demuxer.readingMutex.acquire();try{for(;;){let n=Q(this.demuxer.loadedSamples,t,a=>a.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(n,e);if(n>=0&&n+1i===0?null:i===1?192:i>=2&&i<=5?144*2**i:i===6?"uncommon-u8":i===7?"uncommon-u16":i>=8&&i<=15?2**i:null,Jd=(i,t)=>{switch(i){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},qs=i=>{let t=0,e=new H(V(i,1));for(;e.readBits(1)===1;)t++;if(t===0)return e.readBits(7);let r=[],n=t-1,a=new H(V(i,n)),s=8-t-1;for(let c=0;cc|u<{if(t==="uncommon-u16")return he(i)+1;if(t==="uncommon-u8")return L(i)+1;if(typeof t=="number")return t;ne(t),g(!1)},em=(i,t)=>t==="uncommon-u16"?he(i):t==="uncommon-u16-10"?he(i)*10:t==="uncommon-u8"?L(i):typeof t=="number"?t:null,tm=i=>{let e=0;for(let r of i){e^=r;for(let n=0;n<8;n++)(e&128)!==0?e=e<<1^7:e<<=1,e&=255}return e};var Qs=class extends Ae{constructor(e){super(e);this.loadedSamples=[];this.metadataPromise=null;this.trackBacking=null;this.metadataTags={};this.audioInfo=null;this.lastLoadedPos=null;this.blockingBit=null;this.readingMutex=new Le;this.lastSampleLoaded=!1;this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),g(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSlice(e,Ue);if(_(r)&&(r=await r),!r){this.lastSampleLoaded=!0;return}let n=Je(r);if(!n)break;let a=this.reader.requestSlice(r.filePos,n.size);_(a)&&(a=await a),g(a),Jr(a,n,this.metadataTags),e=r.filePos+n.size}for(e+=4;this.reader.fileSize===null||ed.end-n)return{num:m.num,blockSize:m.blockSize,sampleRate:m.sampleRate,size:d.end-e,isLastFrame:!0};if(L(d)===255){let p=d.filePos,b=L(d),h=this.blockingBit===1?249:248;if(b!==h){d.filePos=p;continue}d.skip(-2);let y=d.filePos-e,k=this.readFlacFrameHeader({slice:d,isFirstPacket:!1});if(!k){d.filePos=p;continue}if(this.blockingBit===0){if(k.num-m.num!==1){d.filePos=p;continue}}else if(k.num-m.num!==m.blockSize){d.filePos=p;continue}return{num:m.num,blockSize:m.blockSize,sampleRate:m.sampleRate,size:y,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:r}){let n=e.filePos,a=V(e,4),s=new H(a);if(s.readBits(15)!==32764)return null;if(this.blockingBit===null){g(r);let y=s.readBits(1);this.blockingBit=y}else if(this.blockingBit===1){if(g(!r),s.readBits(1)!==1)return null}else if(this.blockingBit===0){if(g(!r),s.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");let c=Hs(s.readBits(4));if(!c)return null;g(this.audioInfo);let u=Jd(s.readBits(4),this.audioInfo.sampleRate);if(!u||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;let d=qs(e),m=Ks(e,c),f=em(e,u);if(f===null||f!==this.audioInfo.sampleRate)return null;let p=e.filePos-n,b=L(e);e.skip(-p),e.skip(-1);let h=tm(V(e,p));return b!==h?null:{num:d,blockSize:m,sampleRate:f}}async advanceReader(){await this.readMetadata(),g(this.lastLoadedPos!==null),g(this.audioInfo);let e=this.lastLoadedPos,r=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!r){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],s={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:r.blockSize,byteOffset:e,byteSize:r.size};if(this.lastLoadedPos=this.lastLoadedPos+r.size,this.loadedSamples.push(s),r.isLastFrame){this.lastSampleLoaded=!0;return}}},Hc=class{constructor(t){this.demuxer=t}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return se}getTimeResolution(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return g(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{..._e}}async getDecoderConfig(){return g(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(t,e){if(g(this.demuxer.audioInfo),t<0)return null;let r=await this.demuxer.readingMutex.acquire();try{for(;;){let n=Q(this.demuxer.loadedSamples,t,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(n===-1){await this.demuxer.advanceReader();continue}let a=this.demuxer.loadedSamples[n],s=a.blockOffset/this.demuxer.audioInfo.sampleRate,o=a.blockSize/this.demuxer.audioInfo.sampleRate;if(s+o<=t){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,e);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(n,e)}}finally{r()}}async getNextPacket(t,e){let r=await this.demuxer.readingMutex.acquire();try{let n=t.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&n>=this.demuxer.loadedSamples.length)return null;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,e)}finally{r()}}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}async getPacketAtIndex(t,e){let r=this.demuxer.loadedSamples[t];if(!r)return null;let n;if(e.metadataOnly)n=Te;else{let o=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(_(o)&&(o=await o),!o)return null;n=V(o,r.byteSize)}g(this.demuxer.audioInfo);let a=r.blockOffset/this.demuxer.audioInfo.sampleRate,s=r.blockSize/this.demuxer.audioInfo.sampleRate;return new X(n,"key",a,s,t,r.byteSize)}async getFirstPacket(t){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,t)}};var Gs=i=>{let t="video/MP2T",e=[...new Set(i.filter(Boolean))];return e.length>0&&(t+=`; codecs="${e.join(", ")}"`),t};var am="PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.",rm=5,Cp=1212435798,Pp=1212436562,Ip=1146376960,Ep=new Set([133,134,162]),im=new Set,js=class extends Ae{constructor(e){super(e);this.metadataPromise=null;this.elementaryStreams=[];this.trackBackingEntries=[];this.packetOffset=0;this.packetStride=-1;this.sectionEndPositions=[];this.seekChunkSize=5*1024*1024;this.minReferencePointByteDistance=-1;this.timestampWrapInfo=null;this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=205,r=this.reader.requestSlice(0,e);_(r)&&(r=await r),g(r);let n=V(r,e);if(n[0]===71&&n[188]===71)this.packetOffset=0,this.packetStride=188;else if(n[0]===71&&n[204]===71)this.packetOffset=0,this.packetStride=204;else if(n[4]===71&&n[196]===71)this.packetOffset=4,this.packetStride=192;else throw new Error("Unreachable.");let a=256;this.minReferencePointByteDistance=a*this.packetStride;let s=this.packetOffset,o=null,c=!1,u=!1;for(;;){let l=await this.readPacketHeader(s);if(!l)break;if(l.payloadUnitStartIndicator===0){s+=this.packetStride;continue}if(u&&!this.elementaryStreams.some(h=>h.pid===l.pid)){s+=this.packetStride;continue}let d=await this.readSection(s,!0,!u);if(!d)break;let m=3,f=32,p=!1;if(!u&&d.pid!==0&&!(d.payload[0]===0&&d.payload[1]===0&&d.payload[2]===1)){let y=new H(d.payload),k=y.readAlignedByte();y.skipBits(8*k),p=y.readBits(8)===2}if(d.pid===0&&!c){let h=new H(d.payload),y=h.readAlignedByte();h.skipBits(8*y),h.skipBits(14);let k=h.readBits(10);for(h.skipBits(40);8*(k+m)-h.pos>f;){let T=h.readBits(16);h.skipBits(3);let w=h.readBits(13);if(T!==0){if(o!==null)throw new Error("Only files with a single program are supported.");o=w}}if(o===null)throw new Error("Program Association Table must link to a Program Map Table.");c=!0}else if((d.pid===o||p)&&!u){let h=new H(d.payload),y=h.readAlignedByte();h.skipBits(8*y),h.skipBits(12);let k=h.readBits(12);h.skipBits(43);let T=h.readBits(13);h.skipBits(6);let w=h.readBits(10),A=h.pos+8*w,x=!1;for(;h.pos=4){let I=h.readBits(32);x||=I===Cp||I===Pp}h.pos=S}for(h.pos=A;8*(k+m)-h.pos>f;){let C=h.readBits(8);h.skipBits(3);let P=h.readBits(13);h.skipBits(6);let S=h.readBits(10),I=h.pos+8*S,E=!1,v=!1,F=!1;for(;h.pos=4){let pe=h.readBits(32);F||=(pe&4294967040)===Ip}h.pos=ie}let O=null,D=x&&Ep.has(C)?130:C;switch(D){case 27:case 36:O={type:"video",codec:C===27?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:case 130:case 138:{let U;D===3||D===4?U="mp3":D===15?U="aac":D===129?U="ac3":D===135?U="eac3":U="dts",O={type:"audio",codec:U,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:v?O={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:E?O={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:F&&(O={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:im.has(C)||(z._warn(`Note: MPEG-TS streams with stream_type 0x${C.toString(16)} are not currently supported.`),im.add(C))}O&&this.elementaryStreams.push({demuxer:this,pid:P,streamType:C,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:O,referencePesPackets:[]})}u=!0}else{let h=this.elementaryStreams.find(y=>y.pid===d.pid);e:if(h&&!h.initialized){let y=pn(this,d,!0);if(!y)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${h.pid}`);if(h.firstSection=d,h.canBeTrustedWithKeyPackets=d.randomAccessIndicator===1,this.input._initInput){let w=(await this.input._initInput._getDemuxer()).elementaryStreams.find(A=>A.pid===d.pid&&A.info.codec===h.info.codec);if(w){h.info=w.info,h.initialized=!0;break e}}let k=new vi(h,y);if(h.info.type==="video"){for(;;){let T=k;if(T.suppliedPacket=null,await k.markNextPacket(),h.info.codec==="avc"){if(!k.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(h.info.avcCodecInfo=Zt(k.suppliedPacket.data),!h.info.avcCodecInfo)continue;let w=h.info.avcCodecInfo.sequenceParameterSets[0];g(w);let A=Jt(w);h.info.width=A.displayWidth,h.info.height=A.displayHeight;let x=A.pixelAspectRatio.num,C=A.pixelAspectRatio.den;h.info.squarePixelWidth=h.info.width,h.info.squarePixelHeight=h.info.height,x>0&&C>0&&(x>C?h.info.squarePixelWidth=Math.round(h.info.width*x/C):h.info.squarePixelHeight=Math.round(h.info.height*C/x)),h.info.colorSpace={primaries:ut[A.colourPrimaries],transfer:lt[A.transferCharacteristics],matrix:dt[A.matrixCoefficients],fullRange:!!A.fullRangeFlag},h.info.reorderSize=A.maxDecFrameBuffering;break}else if(h.info.codec==="hevc"){if(!k.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(h.info.hevcCodecInfo=er(k.suppliedPacket.data),!h.info.hevcCodecInfo)continue;let A=h.info.hevcCodecInfo.arrays.find(S=>S.nalUnitType===33).nalUnits[0];g(A);let x=xi(A);h.info.width=x.displayWidth,h.info.height=x.displayHeight;let C=x.pixelAspectRatio.num,P=x.pixelAspectRatio.den;h.info.squarePixelWidth=h.info.width,h.info.squarePixelHeight=h.info.height,C>0&&P>0&&(C>P?h.info.squarePixelWidth=Math.round(h.info.width*C/P):h.info.squarePixelHeight=Math.round(h.info.height*P/C)),h.info.colorSpace={primaries:ut[x.colourPrimaries],transfer:lt[x.transferCharacteristics],matrix:dt[x.matrixCoefficients],fullRange:!!x.fullRangeFlag},h.info.reorderSize=x.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}h.info.decoderConfig={codec:Kr({width:h.info.width,height:h.info.height,codec:h.info.codec,codecDescription:null,colorSpace:h.info.colorSpace,avcType:1,avcCodecInfo:h.info.avcCodecInfo,hevcCodecInfo:h.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:h.info.width,codedHeight:h.info.height,colorSpace:h.info.colorSpace},(h.info.width!==h.info.squarePixelWidth||h.info.height!==h.info.squarePixelHeight)&&(h.info.decoderConfig.displayAspectWidth=h.info.squarePixelWidth,h.info.decoderConfig.displayAspectHeight=h.info.squarePixelHeight),h.initialized=!0}else{if(await k.markNextPacket(),!k.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${h.pid}`);if(h.info.codec==="aac"){let T=xe.tempFromBytes(k.suppliedPacket.data),w=et(T);if(!w)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");h.info.aacCodecInfo={isMpeg2:!1,objectType:w.objectType},h.info.numberOfChannels=Xt[w.channelConfiguration],h.info.sampleRate=kt[w.samplingFrequencyIndex]}else if(h.info.codec==="mp3"){let T=M(xe.tempFromBytes(k.suppliedPacket.data)),w=jr(T,k.suppliedPacket.data.byteLength);if(!w.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");h.info.numberOfChannels=Xr(w.header.channel),h.info.sampleRate=w.header.sampleRate}else if(h.info.codec==="ac3"){let T=ns(k.suppliedPacket.data);if(!T)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(T.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");h.info.numberOfChannels=Gn[T.acmod]+T.lfeon,h.info.sampleRate=Ai[T.fscod]}else if(h.info.codec==="eac3"){let T=as(k.suppliedPacket.data);if(!T)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");let w=ss(T);if(w===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");h.info.numberOfChannels=os(T),h.info.sampleRate=w}else if(h.info.codec==="dts"){let T=Yn(k.suppliedPacket.data);if(!T)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");h.info.numberOfChannels=T.numberOfChannels,h.info.sampleRate=T.sampleRate,T.core&&(h.info.dtsFormat=T.hasExtensions?"dtsh":"dtsc")}else throw new Error("Unhandled.");h.info.decoderConfig={codec:Ji({codec:h.info.codec,codecDescription:null,aacCodecInfo:h.info.aacCodecInfo,dtsFormat:h.info.dtsFormat}),numberOfChannels:h.info.numberOfChannels,sampleRate:h.info.sampleRate},h.initialized=!0}}}if(u&&this.elementaryStreams.every(h=>h.initialized))break;s+=this.packetStride}if(!u)throw c?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(let l of this.elementaryStreams)l.initialized&&(l.info.type==="video"?this.trackBackingEntries.push(new qc(l)):this.trackBackingEntries.push(new Kc(l)))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackingEntries.map(r=>r.getDecoderConfig().then(n=>n?.codec??null)));return Gs(e)}async readSection(e,r,n=!1){let a=e,s=e,o=[],c=0,u=null,l=!0,d=0;for(;;){let f=await this.readPacket(s);if(s+=this.packetStride,!f)break;if(u){if(f.pid!==u.pid){if(n)break;continue}if(f.payloadUnitStartIndicator===1)break}else{if(f.payloadUnitStartIndicator===0)break;u=f}let p=!!(f.adaptationFieldControl&2),b=!!(f.adaptationFieldControl&1),h=0;if(p&&(h=1+f.body[0],f===u&&h>1&&(d=f.body[1]>>6&1)),b&&(h===0?(o.push(f.body),c+=f.body.byteLength):(o.push(f.body.subarray(h)),c+=f.body.byteLength-h)),a=s,!r&&c>=64){l=!1;break}if(pr(this.sectionEndPositions,a,k=>k)!==-1){l=!1;break}}if(l){let f=Q(this.sectionEndPositions,a,p=>p);this.sectionEndPositions.splice(f+1,0,a)}if(!u)return null;let m;if(o.length===1)m=o[0];else{let f=o.reduce((b,h)=>b+h.length,0);m=new Uint8Array(f);let p=0;for(let b of o)m.set(b,p),p+=b.length}return{startPos:e,endPos:r?a:null,pid:u.pid,payload:m,randomAccessIndicator:d}}async readPacketHeader(e){let r=this.reader.requestSlice(e,4);if(_(r)&&(r=await r),!r)return null;if(L(r)!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let a=he(r),s=a>>15,o=a>>14&1,c=a>>13&1,u=a&8191,l=L(r),d=l>>6,m=l>>4&3,f=l&15;return{payloadUnitStartIndicator:o,pid:u,adaptationFieldControl:m}}async readPacket(e){let r=this.reader.requestSlice(e,188);if(_(r)&&(r=await r),!r)return null;let n=V(r,188);if(n[0]!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let s=(n[1]<<8)+n[2],o=s>>15,c=s>>14&1,u=s>>13&1,l=s&8191,d=n[3],m=d>>6,f=d>>4&3,p=d&15;return{payloadUnitStartIndicator:c,pid:l,adaptationFieldControl:f,body:n.subarray(4)}}normalizeTimestamp(e){if(!this.timestampWrapInfo){let a=60*9e4;this.timestampWrapInfo={reference:e-a,offset:e>=8589934592-a?-8589934592:8589934592}}let{reference:r,offset:n}=this.timestampWrapInfo;return n<0&&e>=r||n>0&&e{if(t.payload.byteLength<3)return null;let r=new H(t.payload);if(r.readBits(24)!==1)return null;let a=r.readBits(8);if(r.skipBits(16),a===188||a===190||a===191||a===240||a===241||a===255||a===242||a===248)return null;r.skipBits(8);let s=r.readBits(2);r.skipBits(14);let o=null;if(s===2||s===3)o=0,r.skipBits(4),o+=r.readBits(3)*(1<<30),r.skipBits(1),o+=r.readBits(15)*32768,r.skipBits(1),o+=r.readBits(15),o=i.normalizeTimestamp(o);else if(e)throw new Error(am);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:o,randomAccessIndicator:t.randomAccessIndicator}},pn=(i,t,e)=>{g(t.endPos!==null);let r=Ei(i,t,e);if(!r)return null;let n=new H(t.payload);n.skipBits(32);let a=n.readBits(16),s=6;n.skipBits(16);let o=n.readBits(8),c=n.pos+8*o;n.pos=c;let u=c/8;g(Number.isInteger(u));let l=t.payload.subarray(u,a>0?s+a:t.payload.byteLength);return{...r,data:l}},Xs=class i{constructor(t){this.elementaryStream=t;this.packetBuffers=new WeakMap;this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let t=this.elementaryStream.demuxer,e=this.elementaryStream.info.type,r=0;for(let n of t.trackBackingEntries)if(n.getType()===e&&r++,g(n instanceof i),n.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return se}getDisposition(){return{..._e,primary:!1}}getTimeResolution(){return 9e4}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(t,e,r){let n;return this.allPacketsAreKeyPackets()?n="key":n=t.randomAccessIndicator===1?"key":"delta",new X(r.metadataOnly?Te:t.data,n,t.pts/9e4,Math.max(e/9e4,0),t.sequenceNumber,t.data.byteLength)}async getFirstPacket(t){let e=this.elementaryStream.firstSection;g(e);let r=pn(this.elementaryStream.demuxer,e,!0);g(r);let n=new vi(this.elementaryStream,r),a=new ua(this,n),s=await a.readNext();if(!s)return null;let o=this.createEncodedPacket(s.packet,s.duration,t);return this.packetBuffers.set(o,a),this.packetSectionStarts.set(o,s.packet.sectionStartPos),o}async getNextPacket(t,e){let r=this.packetBuffers.get(t);if(r){let l=await r.readNext();if(!l)return null;this.packetBuffers.delete(t);let d=this.createEncodedPacket(l.packet,l.duration,e);return this.packetBuffers.set(d,r),this.packetSectionStarts.set(d,l.packet.sectionStartPos),d}let n=this.packetSectionStarts.get(t);if(n===void 0)throw new Error("Packet was not created from this track.");let a=this.elementaryStream.demuxer,s=await a.readSection(n,!0);g(s);let o=pn(a,s,!0);g(o);let c=new vi(this.elementaryStream,o);r=new ua(this,c);let u=t.sequenceNumber;for(;;){let l=await r.readNext();if(!l)return null;if(l.packet.sequenceNumber>u){let d=this.createEncodedPacket(l.packet,l.duration,e);return this.packetBuffers.set(d,r),this.packetSectionStarts.set(d,l.packet.sectionStartPos),d}}}async getNextKeyPacket(t,e){let r=t;for(;;){if(r=await this.getNextPacket(r,e),!r)return null;if(r.type==="key")return r}}getPacket(t,e){return this.doPacketLookup(t,!1,e)}getKeyPacket(t,e){return this.doPacketLookup(t,!0,e)}async doPacketLookup(t,e,r){let n=hr(t*9e4),a=this.elementaryStream.demuxer,{reader:s,seekChunkSize:o}=a,c=this.elementaryStream.pid,u=async(w,A,x)=>{let C=w;for(;Cw.pts),b=p!==-1?f[p]:null;if(b&&n-b.pts<9e4/2)m=b.sectionStartPos;else{let w=0;if(s.fileSize!==null){let A=Math.ceil(s.fileSize/o);if(A>1){let x=0,C=A-1;for(w=x;x<=C;){let P=Math.floor((x+C)/2),S=Wa(P*o,a.packetStride)+d.sectionStartPos,I=S+o,E=await u(S,I,!1);if(!E){C=P-1;continue}E.pesPacketHeader.pts<=n?(w=P,x=P+1):C=P-1}}}m=Wa(w*o,a.packetStride)+d.sectionStartPos}let y=(await u(m,s.fileSize??1/0,!1))?.pesPacketHeader??null;y||(y=d);let k=this.getReorderSize(),T=async(w,A)=>{let x=await a.readSection(w,!0);g(x);let C=pn(a,x,!0);g(C);let P=new vi(this.elementaryStream,C),S=new ua(this,P);for(;!((Z(S.presentationOrderPackets)?.pts??-1/0)>=n||!await S.readNextPacket()););let I=Ur(S.presentationOrderPackets,A);if(I===-1)return null;let E=S.presentationOrderPackets[I],v=I===0?0:E.pts-S.presentationOrderPackets[I-1].pts;for(;S.decodeOrderPackets[0]!==E;)S.decodeOrderPackets.shift();S.lastDuration=v;let F=await S.readNext();g(F);let O=this.createEncodedPacket(F.packet,F.duration,r);return this.packetBuffers.set(O,S),this.packetSectionStarts.set(O,F.packet.sectionStartPos),O};if(!e||this.allPacketsAreKeyPackets()){e:for(;;){let w=y.sectionStartPos+a.packetStride;for(;;){let A=await a.readPacketHeader(w);if(!A)break e;if(A.pid===c&&A.payloadUnitStartIndicator===1){let x=await a.readSection(w,!1);if(x){let C=Ei(a,x,!1);if(C&&C.pts!==null){if(C.pts>n)break e;y=C,Qc(this.elementaryStream,y);break}}}w+=a.packetStride}}e:for(let w=0;w=a.packetOffset;){let x=await a.readPacketHeader(A);if(!x)break e;if(x.pid===c&&x.payloadUnitStartIndicator===1){let C=await a.readSection(A,!1);if(C){let P=Ei(a,C,!1);if(P&&P.pts!==null){y=P;break}}}A-=a.packetStride}}return T(y.sectionStartPos,w=>w.pts<=n)}else{let w=m,A=null,x=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let C=null,P=w<=d.sectionStartPos,S,I=null;if(P)S=d,I=l;else{let F=await u(w,s.fileSize??1/0,x);S=F?.pesPacketHeader??null,I=F?.section??null}let E=!1,v=0;e:for(;S&&!(A!==null&&S.sectionStartPos>=A);){if(S.pts<=n){let O;if(this.elementaryStream.canBeTrustedWithKeyPackets)O=S.randomAccessIndicator===1;else{g(I);let D=pn(a,I,!0);g(D);let U=new vi(this.elementaryStream,D);await U.markNextPacket(),O=U.suppliedPacket?.randomAccessIndicator===1}O&&(C=S)}if(S.pts>n&&(E=!0),E&&(v++,v>k))break;let F=S.sectionStartPos+a.packetStride;for(;;){let O=await a.readPacketHeader(F);if(!O)break e;if(O.pid===c&&O.payloadUnitStartIndicator===1){let D=await a.readSection(F,x);if(D){let U=Ei(a,D,!1);if(U&&U.pts!==null){S=U,I=D,Qc(this.elementaryStream,S);break}}}F+=a.packetStride}}if(C){let F=C;if(v===0)e:for(let D=0;D=a.packetOffset;){let K=await a.readPacketHeader(U);if(!K)break e;if(K.pid===c&&K.payloadUnitStartIndicator===1){let ie=await a.readSection(U,x);if(ie){let pe=Ei(a,ie,!1);if(pe&&pe.pts!==null){F=pe;break}}}U-=a.packetStride}}let O=await T(F.sectionStartPos,D=>D.pts<=n&&D.randomAccessIndicator===1);return g(O),O}if(P)return null;A=w,w=Math.max(Wa(w-d.sectionStartPos-o,a.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}},qc=class extends Xs{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getTransformationMatrix(){return[...Dr]}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return g(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},Kc=class extends Xs{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return g(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}},Qc=(i,t)=>{let e=i.referencePesPackets,r=Q(e,t.sectionStartPos,n=>n.sectionStartPos);if(r>=0){let n=e[r];if(t.pts<=n.pts)return!1;let a=i.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-n.sectionStartPos=t?t:this.bufferData(t-e).then(()=>Math.min(this.endPos-this.currentPos,t))}getCurrentPesPacket(){let t=this.pesPackets[this.currentPesPacketIndex];return g(t),t}async bufferData(t){let e=this.endPos+t;for(;this.endPos=d)break;m=f;let p=u+m;if(m+3>=d){this.seekTo(p);break}let b=l[m+1],h=l[m+2],y=l[m+3],k=0;if(b===0&&h===0&&y===1?k=4:b===0&&h===1&&(k=3),k===0){m++;continue}let T=p;a??=T;let w=m+k,A=w+n,x=6;if(A+(e==="avc"?x:1)>d){this.seekTo(p);break}let P=l[w],S,I,E;if(e==="avc")S=Yt(P),I=S===1||S===2||S===5,E=S===6||S===7||S===8||S===9;else{if(S=_t(P),((P&1)<<5|l[w+1]>>3)>0){m+=k;continue}I=S<=9||S>=16&&S<=21,E=S>=32&&S<=37||S===39||S>=41&&S<=44||S>=48&&S<=55}let v=!1;if(I){let F;if(e==="avc"){let O=l.subarray(A,A+x),D=B(new H(O));F=!s||D<=o,o=D}else F=l[A]>>7===1;F&&(s?v=!0:s=!0)}else E&&s&&(v=!0);if(v){let F=T-a;return this.seekTo(a),this.supplyPacket(F,0)}m+=k}if(ca){let c=this.endPos-a;return this.seekTo(a),this.supplyPacket(c,0)}}else{let e=t.info.codec,r=128;for(;;){let n=this.ensureBuffered(r);_(n)&&(n=await n);let a=this.currentPos;for(;this.currentPos-a>6,d=u[4]&63;if(l===3||d>37){this.seekTo(o+1);continue}let m=od[3*d+l];g(m!==void 0),this.seekTo(o),c=this.ensureBuffered(m),_(c)&&(c=await c);let f=Math.round(cd*9e4/t.info.sampleRate);return this.supplyPacket(c,f)}else if(e==="eac3"){if(s!==11)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(5);if(_(c)&&(c=await c),c<5)return;let u=this.readBytes(5);if(u[0]!==11||u[1]!==119){this.seekTo(o+1);continue}let d=(((u[2]&7)<<8|u[3])+1)*2,f=u[4]>>6===3?3:u[4]>>4&3,p=Pc[f];this.seekTo(o),c=this.ensureBuffered(d),_(c)&&(c=await c);let b=p*256,h=Math.round(b*9e4/t.info.sampleRate);return this.supplyPacket(c,h)}else if(e==="dts"){if(s!==127&&s!==100)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered($n);if(_(c)&&(c=await c),c<$n)return;let u=this.readBytes($n),l=Ic(u),d=l?null:Zn(u);if(!l&&!d){this.seekTo(o+1);continue}if(d&&!d.asset){this.seekTo(o);let b=Math.min(d.frameSize,ld),h=this.ensureBuffered(b);_(h)&&(h=await h),d=Zn(this.readBytes(h))??d}let m=l?l.frameSize:d.frameSize;if(l){let b=Math.ceil(l.frameSize/4)*4;for(;;){this.seekTo(o);let h=b+cs,y=this.ensureBuffered(h);if(_(y)&&(y=await y),y=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let t=this.decodeOrderPackets[0],e=this.presentationOrderPackets.indexOf(t);g(e!==-1);let r;for(e===this.presentationOrderPackets.length-1?r=this.lastDuration:(r=this.presentationOrderPackets[e+1].pts-t.pts,this.lastDuration=r),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let n=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(n))break;this.presentationOrderPackets.shift()}return{packet:t,duration:r}}async readNextPacket(){if(this.reachedEnd)return!1;let t;return this.context.suppliedPacket?t=this.context.suppliedPacket:(await this.context.markNextPacket(),t=this.context.suppliedPacket),this.context.suppliedPacket=null,t?(this.decodeOrderPackets.push(t),this.processPacketThroughReorderBuffer(t),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){let t=this.decodeOrderPackets[0];for(g(t);;){let e=this.presentationOrderPackets.indexOf(t);if(e!==-1&&e<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(t){if(this.reorderBuffer.push(t),this.reorderBuffer.length>this.reorderSize){let e=0;for(let n=1;nt.pts-e.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}};var nr="application/vnd.apple.mpegurl",Gc="#EXT-X-STREAM-INF:",jc="#EXT-X-I-FRAME-STREAM-INF:",Xc="#EXT-X-MEDIA:",bn="#EXT-X-DEFINE:",la="#EXTINF:",$c="#EXT-X-MAP:",Yc="#EXT-X-KEY:",Zc="#EXT-X-MEDIA-SEQUENCE:",Jc="#EXT-X-BYTERANGE:",eu="#EXT-X-PROGRAM-DATE-TIME:",sm="#EXT-X-DISCONTINUITY",tu="#EXT-X-TARGETDURATION:",om="#EXT-X-ENDLIST",ru="#EXT-X-PLAYLIST-TYPE:",cm="#EXT-X-I-FRAMES-ONLY",$s=i=>i.length===0||i.startsWith("#")&&!i.startsWith("#EXT"),ir=class{constructor(t,e){this._attributes={};let r="",n="",a=!1,s=!1,o=!1,c=()=>{if(!r)return;let u=r.trim().toLowerCase();Object.prototype.hasOwnProperty.call(this._attributes,u)&&z._warn(`Duplicate AttributeName "${u}"; using last value`);let l=o||n.startsWith("0x")||n.startsWith("0X");this._attributes[u]=l&&e?e.substitute(n):n,r="",n="",a=!1,o=!1};for(let u=0;uo!==null).length!==1)throw new Error("Invalid #EXT-X-DEFINE tag; exactly one of NAME, IMPORT, or QUERYPARAM must be present.");if(r!==null){let o=e.get("value");if(o===null)throw new Error("Invalid #EXT-X-DEFINE tag; NAME requires VALUE.");this.set(r,o)}else if(n!==null){let o=this.importedVariables?.get(n);if(o===void 0)throw new Error(`Invalid #EXT-X-DEFINE tag; cannot import undefined variable "${n}".`);this.set(n,o)}else if(a!==null){let o=Ll(this.playlistPath,a);if(o===null)throw new Error(`Invalid #EXT-X-DEFINE tag; query parameter "${a}" is missing.`);this.set(a,o)}}substitute(t){return t.replaceAll(_p,(e,r)=>{let n=this.variables.get(r);if(n===void 0)throw new Error(`Invalid M3U8 file; variable "${r}" is referenced before being defined.`);return n})}get(t){return this.variables.get(t)}set(t,e){if(!vp.test(t))throw new Error(`Invalid #EXT-X-DEFINE tag; invalid variable name "${t}".`);if(this.variables.has(t))throw new Error(`Invalid #EXT-X-DEFINE tag; variable "${t}" is already defined.`);this.variables.set(t,e)}};var Ys=class{constructor(t,e,r){this.nextInputCacheAge=0;this.inputCache=[];this.trackBackingsPromise=null;this.firstSegment=null;this.firstSegmentFirstTimestamps=new WeakMap;this.firstTimestampCache=new WeakMap;this.input=t,this.path=e,this.trackDeclarations=r}async getDurationFromMetadata(t){let e=await this.getSegmentAt(1/0,{skipLiveWait:t.skipLiveWait});return e?e.timestamp+e.duration:null}async getUnixTimeForTimestamp(t){let e=await this.getSegmentAt(t,{});if(e??=await this.getFirstSegment({}),!e||e.unixEpochTimestamp===null)return null;let r=t-e.timestamp;return e.unixEpochTimestamp+r}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{let t=[];if(this.trackDeclarations){for(let e of this.trackDeclarations)if(e.type==="video"){let r=wi(t,n=>n.getType()==="video")+1;t.push(new Js(this,e,r))}else if(e.type==="audio"){let r=wi(t,n=>n.getType()==="audio")+1;t.push(new eo(this,e,r))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];let r=await this.getInputForSegment(this.firstSegment).getTracks();for(let n of r)if(n.type==="video"){let a=wi(t,s=>s.getType()==="video")+1;t.push(new Js(this,{id:t.length+1,type:"video"},a))}else if(n.type==="audio"){let a=wi(t,s=>s.getType()==="audio")+1;t.push(new eo(this,{id:t.length+1,type:"audio"},a))}}return t})()}async getFirstTimestampForInput(t){let e=this.firstTimestampCache.get(t);if(e!==void 0)return e;let r=await t.getFirstTimestamp();return this.firstTimestampCache.set(t,r),r}async getMediaOffset(t,e){let r=t.firstSegment??t,n;if(this.firstSegmentFirstTimestamps.has(r))n=this.firstSegmentFirstTimestamps.get(r);else{let u=this.getInputForSegment(r);n=await this.getFirstTimestampForInput(u),this.firstSegmentFirstTimestamps.set(r,n)}if(r===t)return r.timestamp-n;let a=await this.getFirstTimestampForInput(e),s=t.timestamp-r.timestamp,c=a-n-s;return Math.abs(c)<=Math.min(.25,s)?r.timestamp-n:t.timestamp-a}dispose(){for(let t of this.inputCache)t.input.dispose();this.inputCache.length=0}},Zs=class{constructor(t,e,r){this.packetInfos=new WeakMap;this.hydrationPromise=null;this.firstInputTrack=null;this.firstSegment=null;this.segmentedInput=t,this.decl=e,this.number=r}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");let t=this.segmentedInput.firstSegment,e=null;for(;t&&(e=(await this.segmentedInput.getInputForSegment(t).getTracks()).find(a=>a.type===this.decl.type&&a.number===this.number)??null,!e);)t=await this.segmentedInput.getNextSegment(t,{});if(!e)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=e,this.firstSegment=t})()}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(t){return this.firstInputTrack?t():this.hydrate().then(t)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),g(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(t){return this.segmentedInput.getUnixTimeForTimestamp(t)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(t){return this.segmentedInput.getDurationFromMetadata(t)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(t,e,r){g(t.sequenceNumber>=0),g(this.segmentedInput.firstSegment);let n=await this.segmentedInput.getMediaOffset(e,r.input),a=e.timestamp-this.segmentedInput.firstSegment.timestamp,s=t.clone({timestamp:qt(t.timestamp+n,await r.getTimeResolution()),sequenceNumber:Math.floor(1e8*a)+t.sequenceNumber});return this.packetInfos.set(s,{segment:e,track:r,sourcePacket:t}),s}async getFirstPacket(t){await this.hydrate(),g(this.firstInputTrack),g(this.firstSegment);let e=this.firstInputTrack,r=this.firstSegment;for(;;){if(e){let s=await e._backing.getFirstPacket(t);if(s)return this.createAdjustedPacket(s,r,e)}if(r=await this.segmentedInput.getNextSegment(r,{skipLiveWait:t.skipLiveWait}),!r)break;e=(await this.segmentedInput.getInputForSegment(r).getTracks()).find(s=>s.type===this.firstInputTrack.type&&s.number===this.firstInputTrack.number)??null}return null}getNextPacket(t,e){return this._getNextInternal(t,e,!1)}getNextKeyPacket(t,e){return this._getNextInternal(t,e,!0)}async _getNextInternal(t,e,r){let n=this.packetInfos.get(t);if(!n)throw new Error("Packet was not created from this track.");let a=r?await n.track._backing.getNextKeyPacket(n.sourcePacket,e):await n.track._backing.getNextPacket(n.sourcePacket,e);if(a)return this.createAdjustedPacket(a,n.segment,n.track);let s=n.segment;for(;;){let o=await this.segmentedInput.getNextSegment(s,{skipLiveWait:e.skipLiveWait});if(!o)return null;let l=(await this.segmentedInput.getInputForSegment(o).getTracks()).find(m=>m.type===n.track.type&&m.number===n.track.number);if(!l){s=o;continue}let d=await l._backing.getFirstPacket(e);return d?this.createAdjustedPacket(d,o,l):null}}getPacket(t,e){return this._getPacketInternal(t,e,!1)}getKeyPacket(t,e){return this._getPacketInternal(t,e,!0)}async _getPacketInternal(t,e,r){let n=await this.segmentedInput.getSegmentAt(t,{skipLiveWait:e.skipLiveWait});if(!n)return null;for(await this.hydrate();n;){let a=this.segmentedInput.getInputForSegment(n),o=(await a.getTracks()).find(d=>d.type===this.firstInputTrack.type&&d.number===this.firstInputTrack.number);if(!o){n=await this.segmentedInput.getPreviousSegment(n,{skipLiveWait:e.skipLiveWait});continue}let c=await this.segmentedInput.getMediaOffset(n,a),u=t-c,l=r?await o._backing.getKeyPacket(u,e):await o._backing.getPacket(u,e);if(!l){n=await this.segmentedInput.getPreviousSegment(n,{skipLiveWait:e.skipLiveWait});continue}return this.createAdjustedPacket(l,n,o)}return null}},Js=class extends Zs{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getTransformationMatrix(){return this.delegate(()=>this.firstInputTrack._backing.getTransformationMatrix())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}},eo=class extends Zs{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}};var um=Al(iu(),1);ji();var lm=typeof um<"u"?um:void 0,uu=0,lu=1/0,nu=null;typeof FinalizationRegistry<"u"&&(nu=new FinalizationRegistry(i=>{i()}));var qe=class extends ct{constructor(){super();this._disposed=!1;this._refCount=0;this._usedForHls=!1;this._refFinalizationRegistry=null;this._sizePromise=null;this.onread=null;typeof FinalizationRegistry<"u"&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new ke;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,uu,lu),e=this._getFileSize(),g(e!==void 0)),e})()}async getSize(){if(this._disposed)throw new ke;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,r){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new to(this,e,r)}_dispatchRead(e,r){this.onread?.(e,r),this._emit("read",{start:e,end:r})}ref(){return new _i(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},_i=class{constructor(t){this._freed=!1;if(t._disposed)throw new Error("Cannot ref a disposed source.");t._incrementRefCount(),t._refFinalizationRegistry?.register(this,t,this),this._source=t}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");let t=this.source;g(t._refCount>0),t._decrementRefCount(),t._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},rt=class extends qe{constructor(e,r){if(typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof r!="function")throw new TypeError("requestHandler must be a function.");super();this.rootPath=e;this.requestHandler=r}_resolveRequest(e){let r=this.requestHandler(e),n=a=>{if(!(a instanceof qe||a instanceof _i))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");let s=a instanceof qe?a.ref():a;return s.source._usedForHls||=this._usedForHls,s};return _(r)?r.then(n):n(r)}},du=(i,t)=>i.path===t.path,da=class extends rt{constructor(){super(...arguments);this._root=null;this._rootRequest=null}_read(e,r,n,a){if(!this._root){if(!this._rootRequest){let s=this._resolveRequest({path:this.rootPath,isRoot:!0}),o=c=>{let u=c instanceof qe?c.ref():c;return this._root=u,this._rootRequest=null,u};_(s)?this._rootRequest=s.then(o):(o(s),g(this._root))}if(this._rootRequest)return this._rootRequest.then(s=>s.source._read(e,r,n,a))}return this._root.source._read(e,r,n,a)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}},au=class extends qe{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw new TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super();this._onreadCalled=!1;this._bytes=$(e),this._view=N(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this._dispatchRead(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}},dm=typeof FinalizationRegistry<"u"?new FinalizationRegistry(i=>{i.cancel().catch(()=>{})}):null,su=class extends qe{constructor(e,r={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.maxCacheSize!==void 0&&(!ve(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(r.useStreamReader!==void 0&&typeof r.useStreamReader!="boolean")throw new TypeError("options.useStreamReader, when provided, must be a boolean.");if(r.handleUnhandledError!==void 0&&typeof r.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super();this._readers=new WeakMap;this._blob=e,this._options=r,this._orchestrator=new fa({maxCacheSize:r.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:n=>{let a=this._readers.get(n);a&&(this._readers.delete(n),dm?.unregister(n),a.cancel().catch(()=>{}))},prefetchProfile:mu.fileSystem,handleUnhandledError:r.handleUnhandledError}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,r,n,a){return this._orchestrator.read(e,r,n,a)}async _runWorker(e){g(e.strictTarget);let r=this._readers.get(e);for(r===void 0&&("stream"in this._blob&&!Qt()&&this._options.useStreamReader!==!1?(r=this._blob.slice(e.currentPos).stream().getReader(),dm?.register(e,r,e)):r=null,this._readers.set(e,r));e.currentPos{})}_dispose(){this._orchestrator.dispose()}},Rp=.5*2**20,Fp=(i,t,e)=>{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))&&typeof window<"u"){let n=null;try{typeof window<"u"&&typeof window.location<"u"&&(n=new URL(e instanceof Request?e.url:e,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&n!==null&&n!==window.location.origin)return z._warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(i-2),16)},mm=new Set,ou=class i extends rt{constructor(e,r={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.requestInit!==void 0&&(!r.requestInit||typeof r.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(r.getRetryDelay!==void 0&&typeof r.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(r.maxCacheSize!==void 0&&(!ve(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(r.parallelism!==void 0&&(!Number.isInteger(r.parallelism)||r.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(r.fetchFn!==void 0&&typeof r.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");if(r.handleUnhandledError!==void 0&&typeof r.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");let n=e instanceof Request?e.url:e instanceof URL?e.href:e;super(n,o=>new i(o.path,this._options));this._offset=0;this._length=null;this._fileSizeDetermined=!1;this._sequentialBacking=null;this._abortControllers=new Map;this._sequentialAbortController=null;this._url=e,this._options=r,this._getRetryDelay=r.getRetryDelay??Fp,this._requestInit={...r.requestInit};let a=null;if(r.requestInit?.headers){let o={...Ma(r.requestInit.headers)},c=Object.keys(o).find(u=>u.toLowerCase()==="range");c!==void 0&&(a=o[c],delete o[c],this._requestInit.headers=o)}if(e instanceof Request){let o=e.headers.get("Range");if(o!==null){a??=o;let c=new Request(e);c.headers.delete("Range"),this._url=c}}if(a!==null){let o=Bp(a);o&&(this._offset=o.offset,this._length=o.length)}let s=2;this._orchestrator=new fa({maxCacheSize:r.maxCacheSize??64*2**20,maxWorkerCount:r.parallelism??s,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:o=>this._abortControllers.delete(o),prefetchProfile:mu.network,handleUnhandledError:r.handleUnhandledError})}_getFileSize(){if(!this._fileSizeDetermined)return this._length!==null?this._length:void 0;let e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return e===null?this._length!==null?this._length:null:ee(e-this._offset,0,this._length??1/0)}_read(e,r,n,a){if(this._length!==null&&r>this._length)return null;let s=this._offset,o=this._sequentialBacking?this._sequentialBacking._read(s+e,s+r):this._orchestrator.read(s+e,s+r,Math.max(s+n,s),s+Math.min(a,this._length??1/0)),c=u=>u?(u.offset-=this._offset,u):null;return _(o)?o.then(c):c(o)}async _runWorker(e){for(;;){if(e.aborted){this._orchestrator.signalWorkerStoppedRunning(e);return}let r=new AbortController;this._abortControllers.set(e,r);let n=await bc(this._options.fetchFn??fetch,this._url,gc(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:r.signal}),this._getRetryDelay,()=>r.signal.aborted);if(!n.ok)throw new Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);n.redirected&&(this.rootPath=n.url);e:if(this._orchestrator.fileSize===null&&!n.headers.has("Content-Encoding")&&(n.status===206||n.type==="basic")){let s=n.headers.get("Content-Range");if(s){let c=/\/(\d+)/.exec(s);if(c){this._orchestrator.supplyFileSize(Number(c[1]));break e}}let o=n.headers.get("Content-Length");if(o){let c=n.status===206?e.currentPos:0;this._orchestrator.supplyFileSize(c+Number(o))}}if(this._fileSizeDetermined=!0,!n.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(n.status!==206){if(this._sequentialBacking){n.body.cancel().catch(()=>{});return}if(!this._usedForHls){let s=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<"u"?window.location.href:void 0);s.origin!=="null"&&!(s.pathname.endsWith(".m3u8")||s.pathname.endsWith(".m3u"))&&(mm.has(s.origin)||(z._warn(`HTTP server (origin ${s.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),mm.add(s.origin)))}this._abortControllers.delete(e),this._transitionToSequentialMode(n.body,r);return}let a=n.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){r.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let s;try{s=await a.read()}catch(u){if(r.signal.aborted)throw u;let l=this._getRetryDelay(1,u,this._url);if(l!==null){z._error("Error while reading response stream. Attempting to resume.",u),await zr(1e3*l);break}else throw u}if(e.aborted)continue;let{done:o,value:c}=s;if(o){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(e.strictTarget)break;this._orchestrator.onWorkerFinished(e);return}this._dispatchRead(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}}}_transitionToSequentialMode(e,r){this._sequentialAbortController=r;let n=e.getReader(),a=0,s=0,o=new ReadableStream({pull:async l=>{for(;;){let d;try{d=await n.read()}catch(f){if(this._disposed)throw f;let p=this._getRetryDelay(1,f,this._url);if(p===null)throw f;z._error("Error while reading response stream. Attempting to resume.",f),await zr(1e3*p),this._sequentialAbortController=new AbortController,this._disposed&&this._sequentialAbortController.abort();let b=await bc(this._options.fetchFn??fetch,this._url,gc(this._requestInit,{headers:{Range:`bytes=${a}-`},signal:this._sequentialAbortController.signal}),this._getRetryDelay,()=>this._disposed);if(!b.ok)throw new Error(`Error fetching ${String(this._url)}: ${b.status} ${b.statusText}`);if(!b.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");n=b.body.getReader(),s=b.status===206?0:a;continue}if(d.done){l.close();return}let m=d.value;if(s>0){let f=Math.min(s,m.length);s-=f,m=m.subarray(f)}if(m.length!==0){a+=m.length,l.enqueue(m);return}}},cancel:()=>n.cancel().catch(()=>{})}),c=new yn(o,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});c._endIndex=this._orchestrator.fileSize,c._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.",c.on("read",({start:l,end:d})=>this._dispatchRead(l,d)),this._sequentialBacking=c;let u=new Set;for(let l of this._orchestrator.workers){for(let d of l.pendingSlices)u.add(d);l.aborted=!0,l.pendingSlices.length=0}for(let l of this._orchestrator.queuedReads)for(let d of l.pendingSlices)u.add(d);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(let[,l]of this._abortControllers)l.abort();this._abortControllers.clear();for(let l of u){let d=c._read(l.start,l.start+l.bytes.length);_(d)?d.then(m=>{m?(g(m.offset===l.start),l.resolve(m.bytes)):l.resolve(null)},m=>l.reject(m)):(g(d===null),l.resolve(null))}}_dispose(){this._orchestrator.dispose();for(let[,e]of this._abortControllers)e.abort();this._abortControllers.clear(),this._sequentialAbortController?.abort(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}},Mp=/^bytes=(\d+)-(\d*)$/,Bp=i=>{let t=Mp.exec(i.trim());if(!t)return null;let e=Number(t[1]),r=t[2]===""?null:Number(t[2]);return r!==null&&rnew i(n.path,r));this._fileHandle=null;this._customSource=new ma({getSize:async()=>{let n=await lm.fs.open(e,"r");return this._fileHandle=n,nu?.register(this,()=>{n.close()},this),(await n.stat()).size},read:async(n,a)=>{g(this._fileHandle);let s=new Uint8Array(a-n);return await this._fileHandle.read(s,0,a-n,n),s},maxCacheSize:r.maxCacheSize,prefetchProfile:"fileSystem",handleUnhandledError:r.handleUnhandledError})}_read(e,r,n,a){return this._customSource._read(e,r,n,a)}_getFileSize(){return this._customSource._getFileSize()}_dispose(){this._customSource._dispose(),this._fileHandle&&(this._fileHandle.close(),this._fileHandle=null,nu?.unregister(this))}},ma=class extends qe{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(typeof e.getSize!="function")throw new TypeError("options.getSize must be a function.");if(typeof e.read!="function")throw new TypeError("options.read must be a function.");if(e.dispose!==void 0&&typeof e.dispose!="function")throw new TypeError("options.dispose, when provided, must be a function.");if(e.handleUnhandledError!==void 0&&typeof e.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");if(e.maxCacheSize!==void 0&&(!ve(e.maxCacheSize)||e.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(e.prefetchProfile&&!["none","fileSystem","network"].includes(e.prefetchProfile))throw new TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super();this._readers=new Set;this._options=e,this._orchestrator=new fa({maxCacheSize:e.maxCacheSize??8*2**20,maxWorkerCount:2,prefetchProfile:mu[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this),handleUnhandledError:e.handleUnhandledError})}_getFileSize(){return this._orchestrator.fileSize??void 0}_read(e,r,n,a){if(this._orchestrator.fileSize!==null)return this._orchestrator.read(e,r,n,a);let s=this._options.getSize();if(_(s))return s.then(o=>{if(!Number.isInteger(o)||o<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=o,this._orchestrator.read(e,r,n,a)});if(!Number.isInteger(s)||s<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=s,this._orchestrator.read(e,r,n,a)}async _runWorker(e){for(;e.currentPos{});break}if(a instanceof Uint8Array){if(a=$(a),a.length!==n-e.currentPos)throw new Error(`options.read returned a Uint8Array with unexpected length: Requested ${n-e.currentPos} bytes, but got ${a.length}.`);this._dispatchRead(e.currentPos,e.currentPos+a.length),this._orchestrator.supplyWorkerData(e,a)}else if(a instanceof ReadableStream){let s=a.getReader();this._readers.add(s);try{for(;e.currentPos{});this._readers.clear(),this._options.dispose?.()}},Op=ma,yn=class extends qe{constructor(e,r={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.handleUnhandledError!==void 0&&typeof r.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");if(r.maxCacheSize!==void 0&&(!ve(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super();this._reader=null;this._cache=[];this._pendingSlices=[];this._currentIndex=0;this._targetIndex=0;this._maxRequestedIndex=0;this._endIndex=null;this._pulling=!1;this._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.";this._stream=e,this._maxCacheSize=r.maxCacheSize??32*2**20,this._handleUnhandledError=r.handleUnhandledError}_getFileSize(){return this._endIndex}_read(e,r){if(this._endIndex!==null&&r>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,r);let n=Q(this._cache,e,d=>d.start),a=n!==-1?this._cache[n]:null;if(a&&a.start<=e&&r<=a.end)return{bytes:a.bytes,view:a.view,offset:a.start};let s=e,o=new Uint8Array(r-e);if(n!==-1)for(let d=n;d=r)break;let f=Math.max(e,m.start);f>s&&this._throwDueToCacheMiss();let p=Math.min(r,m.end);fs&&this._throwDueToCacheMiss();let{promise:c,resolve:u,reject:l}=J();return this._pendingSlices.push({start:e,end:r,bytes:o,resolve:u,reject:l}),this._targetIndex=Math.max(this._targetIndex,r),this._pulling||(this._pulling=!0,this._pull().catch(d=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(m=>m.reject(d)),this._pendingSlices.length=0;else if(this._handleUnhandledError)this._handleUnhandledError(d);else throw d})),c}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex0;){let s=this._cache[0];if(this._maxRequestedIndex-s.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=r.byteLength}this._pulling=!1}_dispose(){for(let e of this._pendingSlices)e.reject(new ke);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel().catch(()=>{})}},mu={none:(i,t)=>({start:i,end:t}),fileSystem:(i,t)=>(i=Math.floor((i-65536)/65536)*65536,t=Math.ceil((t+65536)/65536)*65536,{start:i,end:t}),network:(i,t,e)=>{i=Math.max(0,Math.floor((i-65536)/65536)*65536);for(let n of e){let s=Math.max((n.startPos+n.targetPos)/2,n.targetPos-8388608);if(qa(i,t,s,n.targetPos)){let o=n.targetPos-n.startPos,c=Math.ceil((o+1)/8388608)*8388608,u=2**Math.ceil(Math.log2(o+1)),l=Math.min(u,c);t=Math.max(t,n.startPos+l)}}return t=Math.max(t,i+Rp),{start:i,end:t}}},fa=class{constructor(t){this.options=t;this.fileSize=null;this.nextAge=0;this.workers=[];this.cache=[];this.currentCacheSize=0;this.disposed=!1;this.queuedReads=[]}read(t,e,r,n){g(!this.disposed);let a=this.options.prefetchProfile(t,e,this.workers),s=Math.max(a.start,r),o=Math.min(a.end,this.fileSize??1/0,n);g(s<=t&&e<=o);let c=null,u=Q(this.cache,t,A=>A.start),l=u!==-1?this.cache[u]:null;l&&l.start<=t&&e<=l.end&&(l.age=this.nextAge++,c={bytes:l.bytes,view:l.view,offset:l.start});let d=Q(this.cache,s,A=>A.start),m=c?null:new Uint8Array(e-t),f=0,p=s,b=[];if(d!==-1){for(let A=d;A=o)break;if(x.end<=s)continue;let C=Math.max(s,x.start),P=Math.min(o,x.end);if(g(C<=P),p=m.length&&(c={bytes:m,view:N(m),offset:t}),b.length===0)return g(c),c;let{promise:h,resolve:y,reject:k}=J(),T=[];for(let A of b){let x=Math.max(t,A.start),C=Math.min(e,A.end);x===A.start&&C===A.end?T.push(A):xI.hole.start),S=P!==-1?this.queuedReads[P]:null;for(S&&A.start<=S.hole.end?(S.hole.end=Math.max(S.hole.end,A.end),S.strictTarget&&=x,w&&S.pendingSlices.push(w)):(P++,S={hole:{start:A.start,end:A.end},strictTarget:x,pendingSlices:w?[w]:[],age:this.nextAge++},this.queuedReads.splice(P,0,S));P+1S.hole.end)break;S.hole.end=Math.max(S.hole.end,I.hole.end),S.pendingSlices.push(...I.pendingSlices),S.strictTarget&&=I.strictTarget,S.age=Math.min(S.age,I.age),this.queuedReads.splice(P+1,1)}}}return c?h.catch(A=>{if(!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(A);else throw A}):(g(m),c=h.then(A=>A&&{bytes:A,view:N(A),offset:t})),c}checkHoleAgainstWorker(t,e,r){if(qa(e.start-131072,e.start,t.currentPos,t.targetPos)){t.targetPos=Math.max(t.targetPos,e.end);for(let a=0;a=this.options.maxWorkerCount){let a=null,s=null;for(let o=0;o{if(t.running=!1,t.pendingSlices.length>0)t.pendingSlices.forEach(r=>r.reject(e)),t.pendingSlices.length=0;else if(!t.aborted&&!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(e);else throw e}).finally(()=>{if(!t.running&&this.queuedReads.length>0){let e=0;for(let a=1;at.targetPos&&(t.targetPos=t.currentPos,this.checkQueuedReadsAgainstWorker(t));for(let a=0;al.start&&(l.start=n),l.end<=l.start&&(s.holes.splice(u,1),u--)}s.holes.length===0&&(s.resolve(s.bytes),t.pendingSlices.splice(a,1),a--)}for(let a=0;at){n.resolve(null),e.pendingSlices.splice(r,1),r--;break}}}for(let e=0;e=t){for(let n of r.pendingSlices)n.resolve(null);this.queuedReads.splice(e,1),e--}else if(r.hole.end>t){r.hole.end=t,r.strictTarget=!0;for(let n=0;n=t&&(a.resolve(null),r.pendingSlices.splice(n,1),n--)}}}}signalWorkerStoppedRunning(t){t.running=!1,t.aborted||(t.pendingSlices.length=0)}onWorkerFinished(t){let e=this.workers.indexOf(t);g(e!==-1),t.running=!1,this.workers.splice(e,1),this.options.onIdleWorkerRemoved?.(t),this.fileSize===null&&this.supplyFileSize(t.currentPos);for(let r of t.pendingSlices)r.resolve(null)}insertIntoCache(t){if(this.options.maxCacheSize===0)return;let e=Q(this.cache,t.start,r=>r.start)+1;if(e>0){let r=this.cache[e-1];if(r.end>=t.end)return;if(r.end>t.start){let n=new Uint8Array(t.end-r.start);n.set(r.bytes,0),n.set(t.bytes,t.start-r.start),this.currentCacheSize+=t.end-r.end,r.bytes=n,r.view=N(n),r.end=t.end,e--,t=r}else this.cache.splice(e,0,t),this.currentCacheSize+=t.bytes.length}else this.cache.splice(e,0,t),this.currentCacheSize+=t.bytes.length;for(let r=e+1;r=n.end){this.cache.splice(r,1),this.currentCacheSize-=n.bytes.length,r--;continue}let a=new Uint8Array(n.end-t.start);a.set(t.bytes,0),a.set(n.bytes,n.start-t.start),this.currentCacheSize-=t.end-n.start,t.bytes=a,t.view=N(a),t.end=n.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let r=0,n=this.cache[0];for(let a=1;athis._length)return null;let s=this._baseSource._read(this._offset+e,this._offset+r,this._offset+n,this._offset+a),o=c=>c?(c.offset-=this._offset,c):null;return _(s)?s.then(o):o(s)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}};var Dp=/^0[xX][0-9a-fA-F]+$/,Vp=/^data:.*;base64,/i,pa=class extends Ys{constructor(e,r,n,a){super(e.input,r,n);this.segments=[];this.nextLines=null;this.currentUpdateSegmentsPromise=null;this.streamHasEnded=!1;this.lastSegmentUpdateTime=-1/0;this.refreshInterval=5;this.rootPath=r,this.demuxer=e,this.nextLines=a}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let e=this.getRemainingWaitTimeMs();e>0&&await zr(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){let e=performance.now()-this.lastSegmentUpdateTime,r=Math.max(0,1e3*this.refreshInterval-e);return r<=50?0:r}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){var A=[];try{let S=st(A,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}));let I=new ei(S.source);let E=await I.requestEntireFile();g(E);e=ro(E,E.length,{ignore:$s});S.source instanceof rt&&(this.rootPath=S.source.rootPath)}catch(x){var C=x,P=!0}finally{ot(A,C,P)}}let r=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1,n=new gn(this.rootPath,this.demuxer.hasMasterPlaylist?this.demuxer.masterPlaylistVariables:null),a=!1,s=0,o=null,c=null,u=null,l=0,d=null,m=null,f=null,p=null,b=null,h=null,y=!1,k=Z(this.segments)??null,T=S=>{let I=S.indexOf("@"),E=Number(I===-1?S:S.slice(0,I));if(!Number.isInteger(E)||E<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${S}'.`);let v=null;if(I!==-1&&(v=Number(S.slice(I+1)),!Number.isInteger(v)||v<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${S}'.`);return{length:E,offset:v}},w=S=>{l=S,k&&(g(k.sequenceNumber!==null),k.sequenceNumber0&&h!==null&&(s=l*h),y=!0);let E=I.slice(la.length),v=E.indexOf(","),F=v===-1?E:E.slice(0,v),O=Number(F);if(!Number.isFinite(O)||O<0)throw new Error(`Invalid #EXTINF tag duration '${F}'.`);c=O}else if(I.startsWith(bn))n.define(I.slice(bn.length));else if(I.startsWith($c)){let E=new ir(I.slice($c.length),n),v=E.get("uri");if(!v)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");let F=E.get("byterange"),O=null;if(F!==null&&(O=T(F)),O&&O.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!k){let U={path:we(this.rootPath,v),offset:O?.offset??0,length:O?.length??null};if(u?.method==="AES-128"&&!u.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");m={timestamp:s,unixEpochTimestamp:o,firstSegment:null,sequenceNumber:null,location:U,duration:0,encryption:u,initSegment:null,lastProgramDateTimeSeconds:b}}c=null,p===null?f=null:p=null}else if(I.startsWith(Yc)){let E=new ir(I.slice(Yc.length),n),v=E.get("method");if(v==="NONE")u=null;else if(v==="AES-128"){let F=E.get("uri");if(!F)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let O=null,D=E.get("iv");if(D){if(!Dp.test(D))throw new Error(`Unsupported IV format '${D}'.`);let K=D.slice(2);K=K.padStart(2*Ot,"0"),K=K.slice(-2*Ot),O=new Uint8Array(Ot);for(let ie=0;ie=8&&K[4]===112&&K[5]===115&&K[6]===115&&K[7]===104){let ie=N(K).getUint32(0);D=ws(K.subarray(8,Math.min(ie,K.length)))}}u={method:v,psshBox:D}}else throw new Error(`Unsupported encryption method '${v}'. If you think this method should be supported, please raise an issue.`)}else if(I.startsWith(Zc)){let E=I.slice(Zc.length),v=Number(E);if(!Number.isInteger(v)||v<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${E}'.`);w(v)}else if(I.startsWith(Jc)){let E=T(I.slice(Jc.length));if(E.offset===null){if(f===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");E.offset=f}p=E,f=E.offset+E.length}else if(I.startsWith(eu)){if(k)continue;let E=I.slice(eu.length),v=Date.parse(E);if(!Number.isFinite(v))continue;let F=v/1e3;if(b===F)continue;if(b===null&&this.segments.length>0){let O=Z(this.segments),D=O.timestamp+O.duration,U=F-D;for(let K of this.segments)K.unixEpochTimestamp=K.timestamp+U,r&&(K.timestamp=K.unixEpochTimestamp)}b=F,o=F,r&&(s=F)}else if(I===sm)d=null;else if(I.startsWith(tu)){let E=I.slice(tu.length),v=Number(E);if(!Number.isFinite(v)||v<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${E}'.`);this.refreshInterval=v,h=v}else if(I===om){this.streamHasEnded=!0;break}else I.startsWith(ru)&&I.slice(ru.length).toLowerCase()==="vod"&&(this.streamHasEnded=!0)}if(!a)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,r){this.segments.length===0&&await this.runUpdateSegments();let n=!!r.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){let a=Q(this.segments,e,o=>o.timestamp);if(a===-1)return null;if(a0;for(;;){if(au.segment===r);if(n)return n.age=this.nextInputCacheAge++,n.input;let a=null;(r.initSegment||r.firstSegment)&&(a=this.getInputForSegment(r.initSegment??r.firstSegment));let s={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(u=>{if(!r.encryption||!(r.encryption.method==="SAMPLE-AES"||r.encryption.method==="SAMPLE-AES-CTR")||!r.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(u);let l=u.psshBoxes,{psshBox:d}=r.encryption;return(d.keyIds===null||d.keyIds.includes(u.keyId))&&!l.some(m=>Ss(m,d))&&(l=[...l,d]),this.input._formatOptions.isobmff.resolveKeyId({...u,psshBoxes:l})})}},o=new Ri({source:new da(r.location.path,async u=>{g(u.isRoot);let l={...u,isRoot:!1},d,m=r.location.offset>0||r.location.length!==null;if(!r.encryption||r.encryption.method==="SAMPLE-AES"||r.encryption.method==="SAMPLE-AES-CTR"){if(d=await this.input._getSourceCached(l),m){let p=d.source.slice(r.location.offset,r.location.length??void 0).ref();d.free(),d=p}}else if(r.encryption.method==="AES-128"){let f=r.encryption;g(f.iv);let p=await this.input._getSourceCached(l);if(m){let k=p.source.slice(r.location.offset,r.location.length??void 0).ref();p.free(),p=k}let b=new ei(p.source),h=vd(b,async()=>{var A=[];try{let y=st(A,await this.input._getSourceCached({path:f.keyUri,isRoot:!1},fm));let k=new ei(y.source);let T=await k.requestSlice(0,Ot);if(!T)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");let w=V(T,Ot);return{key:w,iv:f.iv}}catch(x){var C=x,P=!0}finally{ot(A,C,P)}},()=>{p.free()});d=new yn(h).ref()}else g(!1);return d}),formats:this.input._formats.filter(u=>!(u instanceof kn)),initInput:a??void 0,formatOptions:s});if(o._onFormatDetermined=u=>{if((r.encryption?.method==="SAMPLE-AES"||r.encryption?.method==="SAMPLE-AES-CTR")&&!u._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:r,input:o,age:this.nextInputCacheAge++}),this.inputCache.length>4){let u=Xi(this.inputCache,l=>l.age);g(u!==-1),this.inputCache.splice(u,1)}return o}async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}};var no=class extends Ae{constructor(e){super(e);this.metadataPromise=null;this.trackBackings=null;this.internalTracks=null;this.segmentedInputs=[];this.hasMasterPlaylist=!0;this.masterPlaylistVariables=null}readMetadata(){return this.metadataPromise??=(async()=>{g(this.input._rootSource instanceof rt);let e=await this.input._reader.requestEntireFile();g(e);let r=ro(e,e.length,{ignore:$s}),{rootPath:n}=this.input._rootSource,a=new gn(n,null),s=[],o=[];for(let d=1;d{let f=[],p=d.attributes.get("codecs"),b;if(p)b=p.split(",").map(S=>S.trim());else{let I=await this.getSegmentedInputForPath(d.fullPath).getTrackBackings(),E=await Promise.all(I.map(async v=>({track:v,codec:await v.getCodec()})));b=await Promise.all(E.filter(v=>v.codec!==null).map(v=>v.track.getDecoderConfig().then(F=>F.codec)))}let h=d.attributes.get("video"),y=d.attributes.get("audio"),k=b.some(S=>le.includes(Ze(S))),T=b.some(S=>fe.includes(Ze(S)));if(h!==null&&!k){let S=o.find(I=>{let E=I.attributes.get("group-id"),v=I.attributes.get("type");return E===h&&v.toLowerCase()==="video"});e:if(S){let I=S.attributes.get("uri");if(I===null)break e;let E=we(n,I),O=(await this.getSegmentedInputForPath(E).getTrackBackings()).find(U=>U.getType()==="video");if(!O||await O.getCodec()===null)break e;let D=await O.getDecoderConfig().then(U=>U?.codec??null);g(D!==null),b.push(D)}}if(y!==null&&!T){let S=o.find(I=>{let E=I.attributes.get("group-id"),v=I.attributes.get("type");return E===y&&v.toLowerCase()==="audio"});e:if(S){let I=S.attributes.get("uri");if(I===null)break e;let E=we(n,I),O=(await this.getSegmentedInputForPath(E).getTrackBackings()).find(U=>U.getType()==="audio");if(!O||await O.getCodec()===null)break e;let D=await O.getDecoderConfig().then(U=>U?.codec??null);g(D!==null),b.push(D)}}b=[...new Set(b)];let w=null,A=null,x=d.attributes.getAsNumber("bandwidth");g(x!==null);let C=d.attributes.getAsNumber("average-bandwidth"),P=d.attributes.get("name");for(let S of b){let I=Ze(S);if(I!==null){if(le.includes(I)){if(w!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");w=S;let E=d.attributes.get("video");if(E===null){let v=d.attributes.get("resolution"),F=null,O=null;if(v){let D=v.match(/^(\d+)x(\d+)$/);D&&(F=Number(D[1]),O=Number(D[2]))}f.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:se,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:w,pairingMask:1n<0?F:null}})}else for(let v of o){let F=v.attributes.get("group-id"),O=v.attributes.get("type");if(F!==E||O.toLowerCase()!=="audio")continue;let D=v.attributes.get("channels")??d.attributes.get("channels"),U=D!==null?Number(D.split("/")[0]):null;f.push({id:-1,demuxer:this,backingTrack:null,default:io(v.attributes),autoselect:io(v.attributes)||pm(v.attributes),languageCode:hm(v.attributes.get("language")),lineNumber:v.lineNumber,fullPath:v.fullPath??d.fullPath,fullCodecString:A,pairingMask:1n<0?U:null}})}}}}return f})),u=[],l=d=>{let m=u.find(f=>f.fullPath===d.fullPath&&f.info.type===d.info.type);m?(m.pairingMask|=d.pairingMask,m.default||=d.default,m.autoselect||=d.autoselect,m.lineNumber=Math.min(m.lineNumber,d.lineNumber),d.peakBitrate!==null&&(m.peakBitrate=Math.max(m.peakBitrate??-1/0,d.peakBitrate)),d.averageBitrate!==null&&(m.averageBitrate=Math.max(m.averageBitrate??-1/0,d.averageBitrate)),m.languageCode===se&&(m.languageCode=d.languageCode)):(d.id=u.length+1,u.push(d))};for(let d of c)for(let m of d)l(m);u.sort((d,m)=>d.lineNumber-m.lineNumber),this.trackBackings=[];for(let d of u)d.info.type==="video"?this.trackBackings.push(new so(d)):this.trackBackings.push(new oo(d));this.internalTracks=u})()}async getTrackBackings(){return await this.readMetadata(),g(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let r=this.segmentedInputs.find(a=>a.path===e);if(r)return r;let n=null;return this.internalTracks&&(n=this.internalTracks.filter(s=>s.fullPath===e).map(s=>({id:s.id,type:s.info.type}))),r=new pa(this,e,n,null),this.segmentedInputs.push(r),r}async getMetadataTags(){return{}}async getMimeType(){return nr}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},ao=class{constructor(t){this.internalTrack=t;this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let t=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),e=null,n=(await t.getTrackBackings()).filter(a=>a.getType()===this.getType());if(n.length===1)e=n[0];else if(this instanceof so){for(let a of n)if(await a.getCodec()===this.getCodec()){e=a;break}}else{g(this instanceof oo);for(let a of n)if(await a.getCodec()===this.getCodec()){e=a;break}}if(!e)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=e})()}delegate(t){return this.internalTrack.backingTrack?t():this.hydrate().then(t)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{..._e,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){g(this.internalTrack.demuxer.internalTracks);let t=this.internalTrack.info.type,e=0;for(let r of this.internalTrack.demuxer.internalTracks)if(r.info.type===t&&e++,r===this.internalTrack)break;return e}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(t){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(t))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(t){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(t)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(t){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(t)}async getPacket(t,e){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(t,e)}async getKeyPacket(t,e){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(t,e)}async getNextPacket(t,e){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(t,e)}async getNextKeyPacket(t,e){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(t,e)}},so=class extends ao{constructor(t){super(t)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Ze(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getTransformationMatrix(){return this.delegate(()=>this.backingVideoTrack.getTransformationMatrix())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}},oo=class extends ao{constructor(t){super(t)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Ze(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels!==null?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}},io=i=>{let t=i.get("default");if(t===null)return!1;let e=t.toUpperCase();if(e==="YES")return!0;if(e==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${t}".`)},pm=i=>{let t=i.get("autoselect");if(t===null)return!1;let e=t.toUpperCase();if(e==="YES")return!0;if(e==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${t}".`)},hm=i=>{if(i===null)return se;let t=i.split("-")[0];return t||se};var it=class{constructor(){this._isIsobmff=!1}},ha=class extends it{constructor(){super(...arguments);this._isIsobmff=!0}async _getMajorBrand(e){let r=e._reader.requestSlice(0,12);if(_(r)&&(r=await r),!r)return null;r.skip(4);let n=oe(r,4);return n!=="ftyp"&&n!=="styp"?null:oe(r,4)}_createDemuxer(e){return new Cs(e)}},co=class extends ha{async _canReadInput(t){let e=await this._getMajorBrand(t);if(e!==null)return e!=="qt ";let r=0;for(let n=0;n<10;n++){let a=t._reader.requestSlice(r,8);if(_(a)&&(a=await a),!a)return!1;let s=M(a),o=8;if(s===1){let u=t._reader.requestSlice(r+8,8);if(_(u)&&(u=await u),!u)return!1;s=We(u),o=16}if(s8||G(r,n)!==440786851)return!1;let s=Mc(r);if(typeof s!="number")return!1;let o=t._reader.requestSlice(r.filePos,s);if(_(o)&&(o=await o),!o)return!1;let c=r.filePos;for(;o.filePos<=c+s-je;){let u=wt(o);if(!u)break;let{id:l,size:d}=u,m=o.filePos;if(d===void 0)return!1;switch(l){case 17030:if(G(o,d)!==1)return!1;break;case 17143:if(G(o,d)!==1)return!1;break;case 17026:if(Zr(o,d)!==e)return!1;break;case 17031:if(G(o,d)>4)return!1;break}o.filePos=m+d}return!0}_canReadInput(t){return this.isSupportedEBMLOfDocType(t,"matroska")}_createDemuxer(t){return new Bs(t)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},lo=class extends ga{_canReadInput(t){return this.isSupportedEBMLOfDocType(t,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},mo=class extends it{async _canReadInput(t){let e=0;for(;;){let d=t._reader.requestSlice(e,Ue);if(_(d)&&(d=await d),!d)break;let m=Je(d);if(!m)break;e=d.filePos+m.size}let r=await na(t._reader,e,e+4096);if(!r)return!1;let n=r.header,a=Gr(n.mpegVersionId,n.channel),s=t._reader.requestSlice(r.startPos+a,4);if(_(s)&&(s=await s),!s)return!1;let o=M(s);if(o===Qr||o===en)return!0;e=r.startPos+r.header.totalSize;let u=await na(t._reader,e,e+4);if(!u)return!1;let l=u.header;return!(n.channel!==l.channel||n.sampleRate!==l.sampleRate)}_createDemuxer(t){return new Ds(t)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},fo=class extends it{async _canReadInput(t){let e=t._reader.requestSlice(0,12);if(_(e)&&(e=await e),!e)return!1;let r=oe(e,4);return r!=="RIFF"&&r!=="RIFX"&&r!=="RF64"?!1:(e.skip(4),oe(e,4)==="WAVE")}_createDemuxer(t){return new Ls(t)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},po=class extends it{async _canReadInput(t){let e=t._reader.requestSlice(0,4);return _(e)&&(e=await e),e?oe(e,4)==="OggS":!1}_createDemuxer(t){return new Ns(t)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},ho=class extends it{async _canReadInput(t){let e=0;for(;;){let n=t._reader.requestSlice(e,Ue);if(_(n)&&(n=await n),!n)break;let a=Je(n);if(!a)break;e=n.filePos+a.size}let r=t._reader.requestSlice(e,4);return _(r)&&(r=await r),r?oe(r,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(t){return new Qs(t)}},go=class extends it{async _canReadInput(t){let e=0;for(;;){let s=t._reader.requestSlice(e,Ue);if(_(s)&&(s=await s),!s)break;let o=Je(s);if(!o)break;e=s.filePos+o.size}let r=t._reader.requestSliceRange(e,Er,mt);if(_(r)&&(r=await r),!r)return!1;let n=et(r);if(!n||(e+=n.frameLength,r=t._reader.requestSliceRange(e,Er,mt),_(r)&&(r=await r),!r))return!1;let a=et(r);return a?n.objectType===a.objectType&&n.samplingFrequencyIndex===a.samplingFrequencyIndex&&n.channelConfiguration===a.channelConfiguration:!1}_createDemuxer(t){return new Ws(t)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},bo=class extends it{async _canReadInput(t){let e=205,r=t._reader.requestSlice(0,e);if(_(r)&&(r=await r),!r)return!1;let n=V(r,e);return n[0]===71&&n[188]===71||n[0]===71&&n[204]===71?!0:n[4]===71&&n[196]===71}_createDemuxer(t){return new js(t)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}},kn=class extends it{async _canReadInput(t){let e=t._reader.requestSlice(0,7);if(_(e)&&(e=await e),!e||!(oe(e,7)==="#EXTM3U"))return!1;if(!(t._rootSource instanceof rt))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return t._rootSource._usedForHls=!0,!0}_createDemuxer(t){return new no(t)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return nr}},fu=new co,pu=new uo,gm=new ga,bm=new lo,hu=new mo,ym=new fo,km=new po,gu=new go,Tm=new ho,bu=new bo,yu=new kn,Up=[yu,fu,pu,gm,bm,ym,km,Tm,hu,gu,bu],zp=[yu,fu,pu,hu,gu,bu],wm=(i,t)=>{if(!i||typeof i!="object")throw new TypeError(`${t}, when provided, must be an object.`);if(i.isobmff!==void 0){if(!i.isobmff||typeof i.isobmff!="object")throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(i.isobmff.resolveKeyId!==void 0&&typeof i.isobmff.resolveKeyId!="function")throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(i.hls!==void 0){if(!i.hls||typeof i.hls!="object")throw new TypeError(`${t}.hls, when provided, must be an object.`);if(i.hls.offsetTimestampsByDateTime!==void 0&&typeof i.hls.offsetTimestampsByDateTime!="boolean")throw new TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}};var yo=new Map,ko=new Map,Np=(i,t)=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.codec!==void 0&&typeof t.codec!="string")throw new TypeError("options.codec, when provided, must be a string.");if(t.codec!==void 0&&Ze(t.codec)!==i)throw new TypeError(`options.codec, when provided, must match the specified codec (${i}).`);if(t.codedWidth!==void 0&&(!Number.isInteger(t.codedWidth)||t.codedWidth<=0))throw new TypeError("options.codedWidth, when provided, must be a positive integer.");if(t.codedHeight!==void 0&&(!Number.isInteger(t.codedHeight)||t.codedHeight<=0))throw new TypeError("options.codedHeight, when provided, must be a positive integer.");if(t.displayAspectWidth!==void 0&&(!Number.isInteger(t.displayAspectWidth)||t.displayAspectWidth<=0))throw new TypeError("options.displayAspectWidth, when provided, must be a positive integer.");if(t.displayAspectHeight!==void 0&&(!Number.isInteger(t.displayAspectHeight)||t.displayAspectHeight<=0))throw new TypeError("options.displayAspectHeight, when provided, must be a positive integer.");if(t.description!==void 0&&!fr(t.description))throw new TypeError("options.description, when provided, must be a buffer source.");if(t.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(t.hardwareAcceleration))throw new TypeError("options.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(t.optimizeForLatency!==void 0&&typeof t.optimizeForLatency!="boolean")throw new TypeError("options.optimizeForLatency, when provided, must be a boolean.")},Lp=(i,t)=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.codec!==void 0&&typeof t.codec!="string")throw new TypeError("options.codec, when provided, must be a string.");if(t.codec!==void 0&&Ze(t.codec)!==i)throw new TypeError(`options.codec, when provided, must match the specified codec (${i}).`);if(t.numberOfChannels!==void 0&&(!Number.isInteger(t.numberOfChannels)||t.numberOfChannels<=0))throw new TypeError("options.numberOfChannels, when provided, must be a positive integer.");if(t.sampleRate!==void 0&&(!Number.isInteger(t.sampleRate)||t.sampleRate<=0))throw new TypeError("options.sampleRate, when provided, must be a positive integer.");if(t.description!==void 0&&!fr(t.description))throw new TypeError("options.description, when provided, must be a buffer source.")},Wp=i=>le.includes(i)?ku(i):fe.includes(i)?Tu(i):!1,ku=async(i,t={})=>{if(!le.includes(i))return!1;Np(i,t);let e={...t,codedWidth:t.codedWidth??1280,codedHeight:t.codedHeight??720,codec:t.codec??ms(i,1280,720,1e6,!1)};e.description??=kd(e);let r=JSON.stringify(e),n=yo.get(r);if(n)return n;let a=(async()=>ti.some(o=>o.supports(i,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0)();return yo.set(r,a),a},Tu=async(i,t={})=>{if(!fe.includes(i))return!1;Lp(i,t);let e={...t,numberOfChannels:t.numberOfChannels??2,sampleRate:t.sampleRate??48e3,codec:t.codec??hs(i,2,48e3)};if(e.description===void 0){let s=Td(e);if(s===!1)return!1;e.description=s}let r=JSON.stringify(e),n=ko.get(r);if(n)return n;let a=(async()=>ri.some(o=>o.supports(i,e))||ae.includes(i)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0)();return ko.set(r,a),a},Hp=async()=>{let[i,t]=await Promise.all([Sm(),Am()]);return[...i,...t]},Sm=async(i=le,t)=>{let e=await Promise.all(i.map(r=>ku(r,t)));return i.filter((r,n)=>e[n])},Am=async(i=fe,t)=>{let e=await Promise.all(i.map(r=>Tu(r,t)));return i.filter((r,n)=>e[n])};ji();var xm=-1/0,Cm=-1/0,Ta=null;typeof FinalizationRegistry<"u"&&(Ta=new FinalizationRegistry(i=>{let t=performance.now();i.type==="video"?(t-xm>=1e3&&(z._error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),xm=t),typeof VideoFrame<"u"&&i.data instanceof VideoFrame&&i.data.close()):(t-Cm>=1e3&&(z._error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Cm=t),typeof AudioData<"u"&&i.data instanceof AudioData&&i.data.close())}));var ar=class{constructor(){this._referenceCount=0;this._lastAllocationBuffer=null}},wo=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],qp=new Set(wo),Xe=class i{constructor(t,e){this._closed=!1;if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)){if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.format===void 0||!qp.has(e.format))throw new TypeError("init.format must be one of: "+wo.join(", "));if(!Number.isInteger(e.codedWidth)||e.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(e.codedHeight)||e.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(e.layout!==void 0){if(!Array.isArray(e.layout))throw new TypeError("init.layout, when provided, must be an array.");for(let a of e.layout){if(!a||typeof a!="object"||Array.isArray(a))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(a.offset)||a.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(a.stride)||a.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(e.visibleRect!==void 0&&Qa(e.visibleRect,"init.visibleRect"),e.displayWidth!==void 0&&(!Number.isInteger(e.displayWidth)||e.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(e.displayHeight!==void 0&&(!Number.isInteger(e.displayHeight)||e.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(e.displayWidth!==void 0!=(e.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=e.format,this.rotation=e.rotation??0,this.flip=e.flip??!1,this.timestamp=e.timestamp,this.duration=e.duration??0;let r=e.layout??Gp(e.format,e.codedWidth,e.codedHeight),n=e.colorSpace??null;n===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?n={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:n={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:e.visibleRect?.left??0,top:e.visibleRect?.top??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},e.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?e.displayWidth:e.displayHeight,this.squarePixelHeight=this.rotation%180===0?e.displayHeight:e.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=e._doNotCopy?$(t):$(t).slice(),this._layout=r,this.colorSpace=new Tn(n)}else if(typeof VideoFrame<"u"&&t instanceof VideoFrame){if(e?.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(e?.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(e?.timestamp!==void 0&&!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");e?.visibleRect!==void 0&&Qa(e.visibleRect,"init.visibleRect"),this._data=t,this._layout=null,this.format=t.format,this.visibleRect={left:t.visibleRect?.x??0,top:t.visibleRect?.y??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},this.rotation=e?.rotation??0,this.flip=e?.flip??!1,this.squarePixelWidth=t.displayWidth,this.squarePixelHeight=t.displayHeight,this.timestamp=e?.timestamp??t.timestamp/1e6,this.duration=e?.duration??(t.duration??0)/1e6,this.colorSpace=new Tn(t.colorSpace)}else if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof SVGImageElement<"u"&&t instanceof SVGImageElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas){if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(e.visibleRect!==void 0&&Qa(e.visibleRect,"init.visibleRect"),typeof VideoFrame<"u")return new i(new VideoFrame(t,{timestamp:Math.trunc(e.timestamp*Kt),duration:Math.trunc((e.duration??0)*Kt)||void 0,visibleRect:e.visibleRect&&{x:e.visibleRect.left,y:e.visibleRect.top,width:e.visibleRect.width,height:e.visibleRect.height}}),e);let r=0,n=0;if("naturalWidth"in t?(r=t.naturalWidth,n=t.naturalHeight):"videoWidth"in t?(r=t.videoWidth,n=t.videoHeight):"width"in t&&(r=Number(t.width),n=Number(t.height)),!r||!n)throw new TypeError("Could not determine dimensions.");let a=e.visibleRect??{left:0,top:0,width:r,height:n},s=new OffscreenCanvas(a.width,a.height),o=s.getContext("2d",{alpha:yi(),willReadFrequently:!0});if(!o)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");o.drawImage(t,-a.left,-a.top),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:a.width,height:a.height},this.squarePixelWidth=a.width,this.squarePixelHeight=a.height,this.rotation=e.rotation??0,this.flip=e.flip??!1,this.timestamp=e.timestamp,this.duration=e.duration??0,this.colorSpace=new Tn({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(t instanceof ar){if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=t,t._referenceCount++,this.format=t.getFormat(),this.format!==null&&!wo.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:t.getCodedWidth(),height:t.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=t.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=t.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=e.rotation??0,this.flip=e.flip??!1,this.timestamp=e.timestamp,this.duration=e.duration??0,this.colorSpace=t.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=e?.encodeOptions??{},this.pixelAspectRatio=Gt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Ta?.register(this,{type:"video",data:this._data},this)}get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(Kt*this.timestamp)}get microsecondDuration(){return Math.trunc(Kt*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}clone(){if(this._closed)throw new Error("VideoSample is closed.");return g(this._data!==null),this._data instanceof ar?new i(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):ya(this._data)?new i(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(g(this._layout),new i(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new i(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(Ta?.unregister(this),this._data instanceof ar?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):ya(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(t={}){if(Em(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return ya(this._data)?this._data.allocationSize(t):vm(this,t).allocationSize}async copyTo(t,e={}){if(!fr(t))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Em(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(g(this._data!==null),ya(this._data))return this._data.copyTo(t,e);if(e.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(e.format))if(this._data instanceof ar){var u=[];try{let f=st(u,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip},e.colorSpace??"srgb"));if(!(f instanceof i))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(f.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${f.format}' instead.`);return await f.copyTo(t,e)}catch(l){var d=l,m=!0}finally{ot(u,d,m)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");let f=this.toVideoFrame(),p=await f.copyTo(t,e);return f.close(),p}let r=vm(this,e);g(this.format);let n=$(t);if(n.byteLength!(p.data instanceof Uint8Array)||!Number.isInteger(p.stride)||p.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');s=f}else if(this._data instanceof Uint8Array)g(this._layout),g(this._layout.length===a.length),s=this._layout.map((f,p)=>{let b=Math.ceil(this.codedHeight/a[p].heightDivisor);return{data:this._data.subarray(f.offset,f.offset+f.stride*b),stride:f.stride}});else{let p=this._data.getContext("2d");g(p);let b=p.getImageData(0,0,this.codedWidth,this.codedHeight);s=[{data:$(b.data),stride:4*this.codedWidth}]}let o=[],c=a.length;for(let f=0;fh.byteLength)throw new Error("Source buffer OOB read.");if(k+T>n.byteLength)throw new Error("Destination buffer OOB write.");let x=h.subarray(y,y+T);n.set(x,k),y+=b,k+=p.destinationStride}o.push(w)}if(e.format!==void 0){let f=this.format.startsWith("RGB")!==e.format.startsWith("RGB"),p=this.format.includes("X")&&e.format.includes("A");if(f||p)for(let b=0;bs+o.data.byteLength,0),r=new Uint8Array(e),n=0,a=[];for(let s of t)r.set(s.data,n),a.push(n),n+=s.data.byteLength;return new VideoFrame(r,{format:this.format,layout:t.map((s,o)=>({offset:a[o],stride:s.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return ya(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(g(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(t,e,r,n,a,s,o,c,u){let l=0,d=0,m=this.displayWidth,f=this.displayHeight,p=0,b=0,h=this.displayWidth,y=this.displayHeight;if(s!==void 0?(l=e,d=r,m=n,f=a,p=s,b=o,c!==void 0?(h=c,y=u):(h=m,y=f)):(p=e,b=r,n!==void 0&&(h=n,y=a)),!(typeof CanvasRenderingContext2D<"u"&&t instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(m)||m<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(b))throw new TypeError("dy must be a number.");if(!Number.isFinite(h)||h<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:d,sWidth:m,sHeight:f}=this._unmapSourceRegion(l,d,m,f,this.rotation,this.flip));let k=this.toCanvasImageSource();t.save();let T=p+h/2,w=b+y/2;t.translate(T,w),this.flip&&t.scale(-1,1),t.rotate(this.rotation*Math.PI/180);let A=this.rotation%180===0?1:h/y;t.scale(1/A,A),t.drawImage(k,l,d,m,f,-h/2,-y/2,h,y),t.restore()}drawWithFit(t,e){if(!(typeof CanvasRenderingContext2D<"u"&&t instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(e.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");e.crop!==void 0&&ni(e.crop,"options.");let r=t.canvas.width,n=t.canvas.height,a=e.rotation??this.rotation,s=e.flip??this.flip,[o,c]=a%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],u=e.crop;u&&(u=wn(u,o,c));let l,d,m,f,{sx:p,sy:b,sWidth:h,sHeight:y}=this._unmapSourceRegion(e.crop?.left??0,e.crop?.top??0,e.crop?.width??o,e.crop?.height??c,a,s);if(e.fit==="fill")l=0,d=0,m=r,f=n;else{let[T,w]=e.crop?[e.crop.width,e.crop.height]:[o,c],A=e.fit==="contain"?Math.min(r/T,n/w):Math.max(r/T,n/w);m=T*A,f=w*A,l=(r-m)/2,d=(n-f)/2}t.save();let k=a%180===0?1:m/f;t.translate(r/2,n/2),s&&t.scale(-1,1),t.rotate(a*Math.PI/180),t.scale(1/k,k),t.translate(-r/2,-n/2),t.drawImage(this.toCanvasImageSource(),p,b,h,y,l,d,m,f),t.restore()}_unmapSourceRegion(t,e,r,n,a,s){return s&&(t=(a%180===0?this.squarePixelWidth:this.squarePixelHeight)-t-r),a===90?[t,e,r,n]=[e,this.squarePixelHeight-t-r,n,r]:a===180?[t,e]=[this.squarePixelWidth-t-r,this.squarePixelHeight-e-n]:a===270&&([t,e,r,n]=[this.squarePixelWidth-e-n,t,n,r]),{sx:t,sy:e,sWidth:r,sHeight:n}}_drawWithFitAndMipmapping(t,e,r){let n=t.width,a=t.height,[s,o]=r.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],c=r.crop?r.crop.width:s,u=r.crop?r.crop.height:o,l=0;2*n0?Im(d,m):{canvas:t,context:e,isNew:r.targetIsFresh};p.imageSmoothingQuality="high",r.fillBlack?(p.fillStyle="black",p.fillRect(0,0,d,m)):b||p.clearRect(0,0,d,m),this.drawWithFit(p,{fit:r.fit,rotation:r.rotation,flip:r.flip,crop:r.crop}),p.globalCompositeOperation="copy";for(let h=l;h>1;h--){let y=n*2**h,k=a*2**h;p.drawImage(f,0,0,y,k,0,0,y/2,k/2)}p.globalCompositeOperation="source-over",l>0&&(e.imageSmoothingQuality="high",e.globalCompositeOperation="copy",e.drawImage(f,0,0,2*n,2*a,0,0,n,a),e.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(g(this._data!==null),this._data instanceof ar||this._data instanceof Uint8Array){let t=this.toVideoFrame();return queueMicrotask(()=>t.close()),t}else return this._data}async transform(t){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(t.roundDimensionsTo!==void 0&&(!Number.isInteger(t.roundDimensionsTo)||t.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(t.fit!==void 0&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(t.rotate!==void 0&&![0,90,180,270].includes(t.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");if(t.crop!==void 0&&ni(t.crop,"options."),t.alpha!==void 0&&!["keep","discard"].includes(t.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");let{rotation:e,flip:r}=Ua(this.rotation,this.flip,t.rotate??0,t.flip??!1),[n,a]=e%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],s=t.crop;s&&(s=wn(s,n,a));let o=s?s.width:n,c=s?s.height:a,u=o/c,l,d;t.width!==void 0&&t.height===void 0?(l=t.width,d=l/u):t.width===void 0&&t.height!==void 0?(d=t.height,l=d*u):t.width!==void 0&&t.height!==void 0?(l=t.width,d=t.height):(l=o,d=c),l=La(l,t.roundDimensionsTo??1),d=La(d,t.roundDimensionsTo??1);let m={width:l,height:d,fit:t.fit??"fill",rotation:e,flip:r,crop:s??{left:0,top:0,width:n,height:a},alpha:t.alpha??"keep"};for(let h of wu){let y=h(this,m);if(_(y)&&(y=await y),y!==null)return y}let{canvas:f,context:p,isNew:b}=Im(m.width,m.height);return this._drawWithFitAndMipmapping(f,p,{fit:m.fit,rotation:m.rotation,flip:m.flip,crop:m.crop,targetIsFresh:b,fillBlack:m.alpha==="discard"}),new i(f,{timestamp:this.timestamp,duration:this.duration,rotation:0,flip:!1})}setRotation(t){if(![0,90,180,270].includes(t))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=t}setFlip(t){if(typeof t!="boolean")throw new TypeError("newFlip must be a boolean.");this.flip=t}setTimestamp(t){if(!Number.isFinite(t))throw new TypeError("newTimestamp must be a number.");this.timestamp=t}setDuration(t){if(!Number.isFinite(t)||t<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=t}setEncodeOptions(t){if(!t||typeof t!="object")throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=t}[Symbol.dispose](){this.close()}},wu=[],Kp=i=>{wu.includes(i)||wu.push(i)},Qp=3,ba=[],Pm=0,Im=(i,t)=>{for(let n of ba)if(n.canvas.width===i&&n.canvas.height===t)return n.age=Pm++,{canvas:n.canvas,context:n.context,isNew:!1};let e;if(typeof OffscreenCanvas<"u")e=new OffscreenCanvas(i,t);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");e=document.createElement("canvas"),e.width=i,e.height=t}let r=e.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return ba.length>=Qp&&ba.splice(Xi(ba,n=>n.age),1),ba.push({canvas:e,context:r,age:Pm++}),{canvas:e,context:r,isNew:!0}},Tn=class{constructor(t){if(t!==void 0){if(!t||typeof t!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");let e=Object.keys(Pt);if(t.primaries!=null&&!e.includes(t.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${e.join(", ")}.`);let r=Object.keys(It);if(t.transfer!=null&&!r.includes(t.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${r.join(", ")}.`);let n=Object.keys(Et);if(t.matrix!=null&&!n.includes(t.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${n.join(", ")}.`);if(t.fullRange!=null&&typeof t.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=t?.primaries??null,this.transfer=t?.transfer??null,this.matrix=t?.matrix??null,this.fullRange=t?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},ya=i=>typeof VideoFrame<"u"&&i instanceof VideoFrame,wn=(i,t,e)=>{let r=Math.min(i.left,t),n=Math.min(i.top,e),a=Math.min(i.width,t-r),s=Math.min(i.height,e-n);return g(a>=0),g(s>=0),{left:r,top:n,width:a,height:s}},ni=(i,t)=>{if(!i||typeof i!="object")throw new TypeError(t+"crop, when provided, must be an object.");if(!Number.isInteger(i.left)||i.left<0)throw new TypeError(t+"crop.left must be a non-negative integer.");if(!Number.isInteger(i.top)||i.top<0)throw new TypeError(t+"crop.top must be a non-negative integer.");if(!Number.isInteger(i.width)||i.width<0)throw new TypeError(t+"crop.width must be a non-negative integer.");if(!Number.isInteger(i.height)||i.height<0)throw new TypeError(t+"crop.height must be a non-negative integer.")},Em=i=>{if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.colorSpace!==void 0&&!["display-p3","srgb"].includes(i.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(i.format!==void 0&&typeof i.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(i.layout!==void 0){if(!Array.isArray(i.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let t of i.layout){if(!t||typeof t!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(t.offset)||t.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(t.stride)||t.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(i.rect!==void 0){if(!i.rect||typeof i.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(i.rect.x!==void 0&&(!Number.isInteger(i.rect.x)||i.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(i.rect.y!==void 0&&(!Number.isInteger(i.rect.y)||i.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(i.rect.width!==void 0&&(!Number.isInteger(i.rect.width)||i.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(i.rect.height!==void 0&&(!Number.isInteger(i.rect.height)||i.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},Gp=(i,t,e)=>{let r=So(i),n=[],a=0;for(let s of r){let o=Math.ceil(t/s.widthDivisor),c=Math.ceil(e/s.heightDivisor),u=o*s.sampleBytes,l=u*c;n.push({offset:a,stride:u}),a+=l}return n},So=i=>{let t=(e,r,n,a,s)=>{let o=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:r,widthDivisor:n,heightDivisor:a},{sampleBytes:r,widthDivisor:n,heightDivisor:a}];return s&&o.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),o};switch(i){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:ne(i),g(!1)}},vm=(i,t)=>{let e={left:0,top:0,width:i.codedWidth,height:i.codedHeight},r=t.rect,n=jp(e,r,i.codedWidth,i.codedHeight,i.format),a=t.layout,s;if(!t.format||t.format===i.format)s=i.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(t.format))s=t.format;else throw new Error("NotSupportedError: Invalid destination format.");return $p(n,s,a)},jp=(i,t,e,r,n)=>{let a={...i};if(t!==void 0){if(t.width===0||t.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((t.x||0)+(t.width||0)>e)throw new TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");a.x=t.x||0,a.y=t.y||0,a.width=t.width||0,a.height=t.height||0}if(!Xp(n,a))throw new TypeError("visibleRect alignment is invalid for the format.");return a},Xp=(i,t)=>{if(i===null)return!0;let e=So(i);for(let r=0;r{let r=So(t),n=r.length;if(e!==void 0&&e.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let a=0,s=[],o=[];for(let c=0;c4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(b),a=Math.max(a,b);for(let h=0;h 0.");if(!Number.isInteger(t.numberOfChannels)||t.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp must be a number.");let e=t.data.byteLength/(sr(t.format)*t.numberOfChannels);if(!Number.isInteger(e))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=t.format,this.sampleRate=t.sampleRate,this.numberOfFrames=e,this.numberOfChannels=t.numberOfChannels,this.timestamp=t.timestamp,this.duration=e/t.sampleRate;let r;if(t.data instanceof ArrayBuffer)r=new Uint8Array(t.data);else if(ArrayBuffer.isView(t.data))r=new Uint8Array(t.data.buffer,t.data.byteOffset,t.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let n=this.numberOfFrames*this.numberOfChannels*sr(this.format);if(r.byteLength=this.numberOfFrames)throw new RangeError("frameOffset out of range");let n=t.frameCount!==void 0?t.frameCount:this.numberOfFrames-r;if(n>this.numberOfFrames-r)throw new RangeError("frameCount out of range");let a=sr(e),s=Fi(e);if(s&&t.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!s&&t.planeIndex!==0)throw new RangeError("planeIndex out of range");return(s?n:n*this.numberOfChannels)*a}copyTo(t,e){if(!fr(t))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!To.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{format:r,frameCount:n,frameOffset:a}=e,{planeIndex:s}=e,o=this.format,c=r??this.format;if(!c)throw new Error("Destination format not determined");let u=this.numberOfFrames,l=this.numberOfChannels,d=a??0;if(d>=u)throw new RangeError("frameOffset out of range");let m=n!==void 0?n:u-d;if(m>u-d)throw new RangeError("frameCount out of range");let f=sr(c),p=Fi(c);if(p&&s>=l)throw new RangeError("planeIndex out of range");if(!p&&s!==0)throw new RangeError("planeIndex out of range");let h=(p?m:m*l)*f;if(t.byteLength2&&c!==o){Yp(this._data,y,o,c,l,s,d,m);return}else try{this._data.copyTo(t,{planeIndex:s,frameOffset:d,frameCount:m,format:c});return}catch(P){if(c==="f32-planar")throw P;o="f32-planar"}let T=_m(o),w=sr(o),A=Fi(o),x;if(this._data instanceof ii){let P=S=>{let I=this._data.getDataPlane(S);if(!(I instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");let E=u*w*(A?1:l);if(I.byteLength!==E)throw new TypeError(`Data plane ${S} has invalid size. Expected exactly ${E} bytes, got ${I.byteLength} bytes.`);return I};if(A)if(p)x=P(s),s=0;else{x=new Uint8Array(u*w*l);for(let S=0;Sthis.numberOfFrames)throw new RangeError("startFrame out of range.");if(e>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(e0)for(let o=0;o0&&this.copyTo(a,{planeIndex:0,format:this.format,frameOffset:t,frameCount:r});return new i({data:a,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+t/this.sampleRate})}close(){this._closed||(Ta?.unregister(this),this._data instanceof ii?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):ka(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof ii?this._createAudioDataFromData():ka(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(Fi(this.format)){let t=this.allocationSize({planeIndex:0,format:this.format}),e=new ArrayBuffer(t*this.numberOfChannels);for(let r=0;r0;){let l=Math.min(o,u),d=new Float32Array(n*l);for(let m=0;m0;){let d=Math.min(o,u),m=new Float32Array(n*d);for(let p=0;p{switch(i){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},Fi=i=>{switch(i){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},_m=i=>{switch(i){case"u8":case"u8-planar":return(t,e)=>(t.getUint8(e)-128)/128;case"s16":case"s16-planar":return(t,e)=>t.getInt16(e,!0)/32768;case"s32":case"s32-planar":return(t,e)=>t.getInt32(e,!0)/2147483648;case"f32":case"f32-planar":return(t,e)=>t.getFloat32(e,!0)}},Rm=i=>{switch(i){case"u8":case"u8-planar":return(t,e,r)=>t.setUint8(e,ee(Math.round(r*128)+128,0,255));case"s16":case"s16-planar":return(t,e,r)=>t.setInt16(e,ee(Math.round(r*32768),-32768,32767),!0);case"s32":case"s32-planar":return(t,e,r)=>t.setInt32(e,ee(Math.round(r*2147483648),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(t,e,r)=>t.setFloat32(e,r,!0)}},ka=i=>typeof AudioData<"u"&&i instanceof AudioData,Fm=i=>{switch(i){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return i}},Yp=(i,t,e,r,n,a,s,o)=>{let c=_m(e),u=Rm(r),l=sr(e),d=sr(r),m=Fi(e);if(Fi(r))if(m){let p=new ArrayBuffer(o*l),b=N(p);i.copyTo(p,{planeIndex:a,frameOffset:s,frameCount:o,format:e});for(let h=0;h{let e=i.allocationSize({format:t,planeIndex:0}),r=new ArrayBuffer(e);return i.copyTo(r,{format:t,planeIndex:0}),new Ce({data:r,format:t,numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,timestamp:i.timestamp,duration:i.duration})};var Ao=new Map,xo=new Map,Co=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!le.includes(i.codec))throw new TypeError(`Invalid video codec '${i.codec}'. Must be one of: ${le.join(", ")}.`);let t=i.bitrate;if(i.quality===void 0&&t===void 0)throw new TypeError("config.quality must be provided.");if(i.quality!==void 0&&t!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(i.quality!==void 0&&!(i.quality instanceof ce))throw new TypeError("config.quality, when provided, must be a Quality.");if(t!==void 0&&!(t instanceof ce)&&(!Number.isInteger(t)||t<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(i.keyFrameInterval!==void 0&&(!Number.isFinite(i.keyFrameInterval)||i.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(i.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(i.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(i.transform!==void 0){if(typeof i.transform!="object"||!i.transform)throw new TypeError("config.transform, when provided, must be an object.");if(i.transform.width!==void 0&&(!Number.isInteger(i.transform.width)||i.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(i.transform.height!==void 0&&(!Number.isInteger(i.transform.height)||i.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(i.transform.fit!==void 0&&!["fill","contain","cover"].includes(i.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(i.transform.width!==void 0&&i.transform.height!==void 0&&i.transform.fit===void 0&&!["fill","contain","cover"].includes(i.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(i.transform.fit!==void 0&&["fill","contain","cover"].includes(i.sizeChangeBehavior)&&i.transform.fit!==i.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(i.transform.rotate!==void 0&&![0,90,180,270].includes(i.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(i.transform.flip!==void 0&&typeof i.transform.flip!="boolean")throw new TypeError("config.transform.flip, when provided, must be a boolean.");if(i.transform.crop!==void 0&&ni(i.transform.crop,"config.transform."),i.transform.process!==void 0&&typeof i.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(i.transform.frameRate!==void 0&&(!Number.isFinite(i.transform.frameRate)||i.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(i.transform.force!==void 0&&typeof i.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(i.onEncoderConfig!==void 0&&typeof i.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(i.onEncodedSample!==void 0&&typeof i.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");Dm(i.codec,i)},Dm=(i,t)=>{if(!t||typeof t!="object")throw new TypeError("Encoding options must be an object.");if(t.alpha!==void 0&&!["discard","keep"].includes(t.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");let e=t.bitrateMode;if(e!==void 0&&!["constant","variable"].includes(e))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(t.latencyMode!==void 0&&!["quality","realtime"].includes(t.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(t.fullCodecString!==void 0&&typeof t.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(t.fullCodecString!==void 0&&Ze(t.fullCodecString)!==i)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${i}).`);if(t.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(t.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(t.scalabilityMode!==void 0&&typeof t.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(t.contentHint!==void 0&&typeof t.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},Au=i=>{let t=i.bitrateMode,e=i.quality._toVideoRateControl(i.codec,i.width,i.height,t),r=(a,s,o)=>({codec:i.fullCodecString??ms(i.codec,i.width,i.height,o,i.alpha==="keep"),width:i.width,height:i.height,displayWidth:i.squarePixelWidth,displayHeight:i.squarePixelHeight,bitrate:a,bitrateMode:s,alpha:i.alpha??"discard",framerate:i.framerate,latencyMode:i.latencyMode,hardwareAcceleration:i.hardwareAcceleration,scalabilityMode:i.scalabilityMode,contentHint:i.contentHint,...Sd(i.codec)}),n=[];return e.quantizer!==null&&n.push({config:r(void 0,"quantizer",e.bitrate),quantizer:e.quantizer}),e.bitrateMode!=="quantizer"&&n.push({config:r(e.bitrate,e.bitrateMode,e.bitrate),quantizer:null}),g(n.length>0),n},Po=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!fe.includes(i.codec))throw new TypeError(`Invalid audio codec '${i.codec}'. Must be one of: ${fe.join(", ")}.`);let t=i.bitrate;if(i.quality===void 0&&t===void 0&&!(ae.includes(i.codec)||i.codec==="flac"))throw new TypeError("config.quality must be provided for compressed audio codecs.");if(i.quality!==void 0&&t!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(i.quality!==void 0&&!(i.quality instanceof ce))throw new TypeError("config.quality, when provided, must be a Quality.");if(t!==void 0&&!(t instanceof ce)&&(!Number.isInteger(t)||t<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(i.transform!==void 0){if(typeof i.transform!="object"||!i.transform)throw new TypeError("config.transform, when provided, must be an object.");if(i.transform.numberOfChannels!==void 0&&(!Number.isInteger(i.transform.numberOfChannels)||i.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(i.transform.sampleRate!==void 0&&(!Number.isInteger(i.transform.sampleRate)||i.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(i.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(i.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(i.transform.process!==void 0&&typeof i.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(i.onEncoderConfig!==void 0&&typeof i.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(i.onEncodedSample!==void 0&&typeof i.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");Vm(i.codec,i)},Vm=(i,t)=>{if(!t||typeof t!="object")throw new TypeError("Encoding options must be an object.");let e=t.bitrateMode;if(e!==void 0&&!["constant","variable"].includes(e))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(t.fullCodecString!==void 0&&typeof t.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(t.fullCodecString!==void 0&&Ze(t.fullCodecString)!==i)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${i}).`)},xu=i=>{let t=i.bitrateMode;return{codec:i.fullCodecString??hs(i.codec,i.numberOfChannels,i.sampleRate),numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,bitrate:i.quality?._toAudioBitrate(i.codec),bitrateMode:i.quality?._bitrateMode??t,...Ad(i.codec)}},ce=class{constructor(t){if((typeof t=="number"||typeof t=="string")&&(t={quality:t}),!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.bitrateMode!==void 0&&!["constant","variable"].includes(t.bitrateMode))throw new TypeError("options.bitrateMode, when provided, must be 'constant' or 'variable'.");if("quality"in t){if(typeof t.quality=="string"?!(t.quality in Bm):typeof t.quality!="number"||Number.isNaN(t.quality))throw new TypeError("options.quality must be a number, or one of 'very-low', 'low', 'medium', 'high' or 'very-high'.");if(t.preferBitrate!==void 0&&typeof t.preferBitrate!="boolean")throw new TypeError("options.preferBitrate, when provided, must be a boolean.");if("bitrate"in t||"quantizer"in t)throw new TypeError("options.quality cannot be combined with options.bitrate or options.quantizer.");this._quality=typeof t.quality=="string"?Bm[t.quality]:t.quality,this._preferBitrate=t.preferBitrate??!1,this._bitrate=void 0,this._quantizer=void 0}else{if(t.bitrate!==void 0&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("options.bitrate, when provided, must be a positive integer.");if(t.quantizer!==void 0&&(!Number.isInteger(t.quantizer)||t.quantizer<0))throw new TypeError("options.quantizer, when provided, must be a non-negative integer.");if(t.bitrate===void 0&&t.quantizer===void 0)throw new TypeError("At least one of options.bitrate or options.quantizer must be set.");if("preferBitrate"in t)throw new TypeError("options.preferBitrate can only be combined with options.quality.");this._quality=void 0,this._preferBitrate=!1,this._bitrate=t.bitrate,this._quantizer=t.quantizer}this._bitrateMode=t.bitrateMode}_toVideoRateControl(t,e,r,n){let a=Zp[t],s=null,o=this._bitrateMode??n??"variable";if(this._quantizer!==void 0){if(a)if(this._quantizera.max){if(this._bitrate===void 0)throw new Error(`Quantizer ${this._quantizer} is out of range for codec '${t}'; must be between ${a.min} and ${a.max}.`)}else s=this._quantizer,this._bitrate===void 0&&(o="quantizer");else if(this._bitrate===void 0)throw new Error(`Codec '${t}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else this._bitrate===void 0&&a&&!this._preferBitrate&&(g(this._quality!==void 0),s=ee(Math.round(Ol(a.worst,a.best,this._quality)),a.min,a.max));let c;if(this._bitrate!==void 0)c=this._bitrate;else{let u=this._quality;u===void 0&&(g(s!==null&&a),u=ee((s-a.worst)/(a.best-a.worst),0,1)),c=Om(t,e,r,Su(u))}return{quantizer:s,bitrate:c,bitrateMode:o}}_toVideoBitrate(t,e,r){return this._bitrate!==void 0?this._bitrate:(g(this._quality!==void 0),Om(t,e,r,Su(this._quality)))}_toAudioBitrate(t){if(ae.includes(t)||t==="flac")return;if(this._bitrate!==void 0)return this._bitrate;if(this._quality===void 0)throw new Error("This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.");let e=Su(this._quality),n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[t];if(!n)throw new Error(`Unhandled codec: ${t}`);let a=n*e;return t==="aac"?a=[96e3,128e3,16e4,192e3].reduce((o,c)=>Math.abs(c-a)Math.abs(c-a).3*Math.exp(2.5538*i),Om=(i,t,e,r)=>{let n=t*e,a=1920*1080,s=3e6,o=Math.pow(n/a,.95),c=s*o,u={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/s},d=c*u[i]*r;return Math.ceil(d/1e3)*1e3},Cu=(i,t)=>{if(i==="avc")return{avc:{quantizer:t}};if(i==="hevc")return{hevc:{quantizer:t}};if(i==="vp9")return{vp9:{quantizer:t}};if(i==="av1")return{av1:{quantizer:t}};g(!1)},Jp=new ce("very-low"),eh=new ce("low"),th=new ce("medium"),rh=new ce("high"),ih=new ce("very-high"),nh=i=>{if(le.includes(i))return Io(i);if(fe.includes(i))return Eo(i);if(Ye.includes(i))return vo(i);throw new TypeError(`Unknown codec '${i}'.`)},Io=async(i,t={})=>{let{width:e=1280,height:r=720,quality:n,bitrate:a,frameRate:s,...o}=t;if(!le.includes(i))return!1;if(!Number.isInteger(e)||e<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("height must be a positive integer.");if(n!==void 0&&!(n instanceof ce))throw new TypeError("quality, when provided, must be a Quality.");if(n!==void 0&&a!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(a!==void 0&&!(a instanceof ce)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer or a quality.");if(s!==void 0&&(!Number.isFinite(s)||s<=0))throw new TypeError("frameRate, when provided, must be a finite positive number.");Dm(i,o);let c=ai(n,a)??new ce("medium"),u;try{u=Au({codec:i,width:e,height:r,quality:c,framerate:s,...o,alpha:"discard"})}catch{return!1}let l=JSON.stringify(u),d=Ao.get(l);if(d)return d;let m=(async()=>{for(let{config:p}of u)if(Sn.some(b=>b.supports(i,p)))return!0;if(typeof VideoEncoder>"u"||(e%2===1||r%2===1)&&(i==="avc"||i==="hevc"))return!1;for(let{config:p,quantizer:b}of u){try{if(!(await VideoEncoder.isConfigSupported(p)).supported)continue}catch{continue}if(!yi()||await new Promise(async y=>{try{let k=new VideoEncoder({output:()=>{},error:()=>y(!1)});k.configure(p);let T=new Uint8Array(e*r*4),w=new VideoFrame(T,{format:"RGBA",codedWidth:e,codedHeight:r,timestamp:0});k.encode(w,b!==null?Cu(i,b):void 0),w.close(),await k.flush(),y(!0)}catch{y(!1)}}))return!0}return!1})();return Ao.set(l,m),m},Eo=async(i,t={})=>{let{numberOfChannels:e=2,sampleRate:r=48e3,quality:n,bitrate:a,...s}=t;if(!fe.includes(i))return!1;if(!Number.isInteger(e)||e<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("sampleRate must be a positive integer.");if(n!==void 0&&!(n instanceof ce))throw new TypeError("quality, when provided, must be a Quality.");if(n!==void 0&&a!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(a!==void 0&&!(a instanceof ce)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer.");Vm(i,s);let o=ai(n,a)??new ce("medium"),c=xu({codec:i,numberOfChannels:e,sampleRate:r,quality:o,...s}),u=JSON.stringify(c),l=xo.get(u);if(l)return l;let d=(async()=>{if(An.some(m=>m.supports(i,c))||ae.includes(i))return!0;if(typeof AudioEncoder>"u")return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return xo.set(u,d),d},ai=(i,t)=>{if(i!==void 0)return i;if(t!==void 0)return t instanceof ce?t:new ce({bitrate:t})},vo=async i=>!!Ye.includes(i),ah=async()=>{let[i,t,e]=await Promise.all([Um(),wa(),zm()]);return[...i,...t,...e]},Um=async(i=le,t)=>{let e=await Promise.all(i.map(r=>Io(r,t)));return i.filter((r,n)=>e[n])},wa=async(i=fe,t)=>{let e=await Promise.all(i.map(r=>Eo(r,t)));return i.filter((r,n)=>e[n])},zm=async(i=Ye)=>{let t=await Promise.all(i.map(vo));return i.filter((e,r)=>t[r])},Pu=async(i,t)=>{for(let e of i)if(await Io(e,t))return e;return null},sh=async(i,t)=>{for(let e of i)if(await Eo(e,t))return e;return null},oh=async i=>{for(let t of i)if(await vo(t))return t;return null};var _o=class{static supports(t,e){return!1}},Ro=class{static supports(t,e){return!1}},Fo=class{static supports(t,e){return!1}},Mo=class{static supports(t,e){return!1}},ti=[],ri=[],Sn=[],An=[],ch=i=>{if(i.prototype instanceof _o){let t=i;if(ti.includes(t)){z._warn("Video decoder already registered.");return}ti.push(t),yo.clear()}else if(i.prototype instanceof Ro){let t=i;if(ri.includes(t)){z._warn("Audio decoder already registered.");return}ri.push(t),ko.clear()}else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},uh=i=>{if(i.prototype instanceof Fo){let t=i;if(Sn.includes(t)){z._warn("Video encoder already registered.");return}Sn.push(t),Ao.clear()}else if(i.prototype instanceof Mo){let t=i;if(An.includes(t)){z._warn("Audio encoder already registered.");return}An.push(t),xo.clear()}else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};var Nm=i=>{let r=i>>2,n=4096,a=0,s=12,o=0;for(r<0&&(r=-r,a=128),r+=33,r>8191&&(r=8191);(r&n)!==n&&s>=5;)n>>=1,s--;return o=r>>s-4&15,~(a|s-5<<4|o)&255},Lm=i=>{let e=0,r=0,n=~i;n&128&&(n&=-129,e=-1),r=((n&240)>>4)+5;let a=(1<{let e=2048,r=0,n=11,a=0,s=i>>3;for(s<0?s=-s-1:r=128,s>4095&&(s=4095);(s&e)!==e&&n>=5;)e>>=1,n--;return a=s>>(n===4?1:n-4)&15,(r|n-4<<4|a)^85},Hm=i=>{let t=0,e=0,r=i^85;r&128&&(r&=-129,t=-1),e=((r&240)>>4)+4;let n=0;return e!==4?n=1<{if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.metadataOnly!==void 0&&typeof i.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(i.verifyKeyPackets!==void 0&&typeof i.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(i.verifyKeyPackets&&i.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(i.skipLiveWait!==void 0&&typeof i.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},vr=i=>{if(!ve(i))throw new TypeError("timestamp must be a number.")},Iu=(i,t,e)=>e.verifyKeyPackets?t.then(async r=>{if(!r||r.type==="delta")return r;let n=await i.determinePacketType(r);return n&&(r.type=n),r}):t,ft=class{constructor(t){if(!(t instanceof Oi))throw new TypeError("track must be an InputTrack.");this._track=t}async getFirstPacket(t={}){if(Mi(t),this._track.input._disposed)throw new ke;return Iu(this._track,this._track._backing.getFirstPacket(t),t)}async getFirstKeyPacket(t={}){Mi(t);let e=await this.getFirstPacket(t);return e?e.type==="key"?e:this.getNextKeyPacket(e,t):null}async getPacket(t,e={}){if(vr(t),Mi(e),this._track.input._disposed)throw new ke;return Iu(this._track,this._track._backing.getPacket(t,e),e)}async getNextPacket(t,e={}){if(!(t instanceof X))throw new TypeError("packet must be an EncodedPacket.");if(Mi(e),this._track.input._disposed)throw new ke;return Iu(this._track,this._track._backing.getNextPacket(t,e),e)}async getKeyPacket(t,e={}){if(vr(t),Mi(e),this._track.input._disposed)throw new ke;if(!e.verifyKeyPackets)return this._track._backing.getKeyPacket(t,e);let r=await this._track._backing.getKeyPacket(t,e);return r&&(g(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),e):r)}async getNextKeyPacket(t,e={}){if(!(t instanceof X))throw new TypeError("packet must be an EncodedPacket.");if(Mi(e),this._track.input._disposed)throw new ke;if(!e.verifyKeyPackets)return this._track._backing.getNextKeyPacket(t,e);let r=await this._track._backing.getNextKeyPacket(t,e);return r&&(g(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getNextKeyPacket(r,e):r)}packets(t,e,r={}){if(t!==void 0&&!(t instanceof X))throw new TypeError("startPacket must be an EncodedPacket.");if(t!==void 0&&t.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(e!==void 0&&!(e instanceof X))throw new TypeError("endPacket must be an EncodedPacket.");if(Mi(r),this._track.input._disposed)throw new ke;let n=[],{promise:a,resolve:s}=J(),{promise:o,resolve:c}=J(),u=!1,l=!1,d=null,m=!1,f=[],p=()=>Math.max(2,f.length);(async()=>{let h=t??await this.getFirstPacket(r);for(;h&&!l&&!this._track.input._disposed&&!(e&&h.sequenceNumber>=e?.sequenceNumber);){if(n.length>p()){({promise:o,resolve:c}=J()),await o;continue}n.push(h),s(),{promise:a,resolve:s}=J(),h=await this.getNextPacket(h,r)}u=!0,s()})().catch(h=>{m||(d=h,m=!0,s())});let b=this._track;return{async next(){for(;;){if(b.input._disposed)throw new ke;if(l)return{value:void 0,done:!0};if(m)throw d;if(n.length>0){let h=n.shift(),y=performance.now();for(f.push(y);f.length>0&&y-f[0]>=1e3;)f.shift();return c(),{value:h,done:!1}}else{if(u)return{value:void 0,done:!0};await a}}},async return(){return l=!0,c(),s(),{value:void 0,done:!0}},async throw(h){throw h},[Symbol.asyncIterator](){return this}}}},Sa=class{constructor(t,e){this.onSample=t;this.onError=e}},Aa=class{mediaSamplesInRange(t=-1/0,e=1/0,r){vr(t),vr(e);let n=[],a=!1,s=null,{promise:o,resolve:c}=J(),{promise:u,resolve:l}=J(),d=!1,m=!1,f=!1,p=null,b=null,h=!1,y={...r,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=await this._createDecoder(S=>{if(l(),S.timestamp>=e&&(m=!0),m){S.close();return}s&&(S.timestamp>t?(n.push(s),a=!0):s.close()),S.timestamp>=t&&(n.push(S),a=!0),s=a?null:S,n.length>0&&(c(),{promise:o,resolve:c}=J())},S=>{h||(b=S,h=!0,c())});let w=this._createPacketSink(),A=await w.getKeyPacket(t,y)??await w.getFirstKeyPacket(y),x=A,P=w.packets(A??void 0,void 0,y);for(await P.next();x&&!m&&!this._track.input._disposed;){let S=qm(n.length);if(n.length+p.getDecodeQueueSize()>S){({promise:u,resolve:l}=J()),await u;continue}p.decode(x);let I=await P.next();if(I.done)break;x=I.value}await P.return(),!f&&!this._track.input._disposed&&await p.flush(),!a&&s&&n.push(s),d=!0,c()})().catch(w=>{h||(b=w,h=!0,c())}).finally(()=>{p?.close()});let k=this._track,T=()=>{s?.close();for(let w of n)w.close()};return{async next(){for(;;){if(k.input._disposed)throw f=!0,m=!0,T(),new ke;if(f)return{value:void 0,done:!0};if(h)throw f=!0,m=!0,T(),b;if(n.length>0){let w=n.shift();return l(),{value:w,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return f=!0,m=!0,l(),c(),T(),{value:void 0,done:!0}},async throw(w){throw w},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(t,e){Rl(t);let r=_l(t),n=[],a=[],{promise:s,resolve:o}=J(),{promise:c,resolve:u}=J(),l=!1,d=!1,m=null,f=null,p=!1,b=T=>{a.push(T),o(),{promise:s,resolve:o}=J()},h={...e,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{m=await this._createDecoder(S=>{if(u(),d){S.close();return}let I=0;for(;n.length>0&&S.timestamp-n[0]>-1e-10;)I++,n.shift();if(I>0)for(let E=0;E{p||(f=S,p=!0,o())});let T=this._createPacketSink(),w=null,A=null,x=-1,C=async()=>{g(A),g(m);let S=A;for(m.decode(S);S.sequenceNumberI&&!d;)({promise:c,resolve:u}=J()),await c;if(d)break;let E=await T.getNextPacket(S,h);g(E),m.decode(E),S=E}x=-1},P=async()=>{g(m),await m.flush();for(let S=0;S{p||(f=T,p=!0,o())}).finally(()=>{m?.close()});let y=this._track,k=()=>{for(let T of a)T?.close()};return{async next(){for(;;){if(y.input._disposed)throw d=!0,k(),new ke;if(d)return{value:void 0,done:!0};if(p)throw d=!0,k(),f;if(a.length>0){let T=a.shift();return g(T!==void 0),u(),{value:T,done:!1}}else if(!l)await s;else return{value:void 0,done:!0}}},async return(){return d=!0,u(),o(),k(),{value:void 0,done:!0}},async throw(T){throw T},[Symbol.asyncIterator](){return this}}}},qm=i=>i===0?40:8,vu=class extends Sa{constructor(e,r,n,a,s,o,c){super(e,r);this.codec=n;this.decoderConfig=a;this.rotation=s;this.flip=o;this.timeResolution=c;this.decoder=null;this.customDecoder=null;this.customDecoderCallSerializer=new Or;this.customDecoderQueueSize=0;this.inputTimestamps=[];this.sampleQueue=[];this.currentPacketIndex=0;this.raslSkipped=!1;this.alphaDecoder=null;this.alphaHadKeyframe=!1;this.colorQueue=[];this.alphaQueue=[];this.merger=null;this.decodedAlphaChunkCount=0;this.alphaDecoderQueueSize=0;this.nullAlphaFrameQueue=[];this.currentAlphaPacketIndex=0;this.alphaRaslSkipped=!1;this.finalSamples=[];this.mergeAlphaPromises=[];let u=ti.find(l=>l.supports(n,a));if(u)this.customDecoder=new u,this.customDecoder.codec=n,this.customDecoder.config=a,this.customDecoder.onSample=l=>{if(!(l instanceof Xe))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(l)},this.customDecoder.onError=l=>{r(l)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(l=>r(l));else{let l=m=>{if(this.alphaQueue.length>0){let f=this.alphaQueue.shift();g(f!==void 0),this.mergeAlpha(m,f)}else this.colorQueue.push(m)};if(Nn()){if(n==="avc"&&this.decoderConfig.description){let m=Wr($(this.decoderConfig.description));if(m&&m.sequenceParameterSets.length>0){let f=Jt(m.sequenceParameterSets[0]);f&&(f.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}),f.maxDecFrameBuffering!==0&&f.bitstreamRestrictionFlag!==1&&(m.sequenceParameterSets[0]=Cc(f),this.decoderConfig={...this.decoderConfig,description:es(m)}))}}Ki(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:this.decoderConfig.colorSpace?.primaries??"bt709",matrix:this.decoderConfig.colorSpace?.matrix??"bt709",transfer:this.decoderConfig.colorSpace?.transfer??"bt709",fullRange:this.decoderConfig.colorSpace?.fullRange??!1}})}let d=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:m=>{try{l(m)}catch(f){this.onError(f)}},error:m=>{m.stack=d,this.onError(m)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(g(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(r=>this.onError(r)).finally(()=>this.customDecoderQueueSize--);else{if(g(this.decoder),Qt()||mc(this.inputTimestamps,e.timestamp,r=>r),Nn()&&this.currentPacketIndex===0){if(this.codec==="avc"){let r=[],n=!1;for(let s of xc(e.data,this.decoderConfig)){let o=Yt(e.data[s.offset]);if(n||=o>=1&&o<=5,o===9){if(n)break;r.length=0}o>=20&&o<=31||r.push(e.data.subarray(s.offset,s.offset+s.length))}if(!this.decoderConfig.description)for(let s=0;s{if(this.colorQueue.length>0){let o=this.colorQueue.shift();g(o!==void 0),this.mergeAlpha(o,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let o=this.colorQueue.shift();g(o!==void 0),this.mergeAlpha(o,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},a=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{n(s)}catch(o){this.onError(o)}},error:s=>{s.stack=a,this.onError(s)}}),this.alphaDecoder.configure({...this.decoderConfig,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"}})}let r=qr(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=r==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(r??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let r of Wn(e,this.decoderConfig)){let n=_t(e[r.offset]);if(n===8||n===9)return!0}return!1}sampleHandler(e){if(Qt()){if(this.sampleQueue.length>0&&e.timestamp>=Z(this.sampleQueue).timestamp){for(let r of this.sampleQueue)this.finalizeAndEmitSample(r);this.sampleQueue.length=0}mc(this.sampleQueue,e,r=>r.timestamp)}else{let r=this.inputTimestamps.shift();g(r!==void 0),e.setTimestamp(r),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),e.setFlip(this.flip),this.onSample(e)}async mergeAlpha(e,r){let n=J();this.mergeAlphaPromises.push(n.promise);let a={sample:null};this.finalSamples.push(a);try{if(!r)a.sample=new Xe(e);else{g(this.merger);let s=await this.merger.merge(e,r);a.sample=new Xe(s)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){let s=this.finalSamples.shift();this.sampleHandler(s.sample)}}catch(s){Qi(this.finalSamples,a),this.onError(s)}finally{Qi(this.mergeAlphaPromises,n.promise),n.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(g(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Qt()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(g(this.decoder),this.decoder.state!=="closed"&&this.decoder.close(),this.alphaDecoder&&this.alphaDecoder.state!=="closed"&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},Eu=null,_u=class{constructor(){this.workers=[];this.nextWorkerIndex=0;this.pendingRequests=new Map;this.nextRequestId=0}merge(t,e){if(this.workers.length===0){if(!Eu){let o=new Blob([`(${lh.toString()})()`],{type:"application/javascript"});Eu=URL.createObjectURL(o)}let s=ee(navigator.hardwareConcurrency,1,4);for(let o=0;o{let l=u.data,d=this.pendingRequests.get(l.id);d&&(this.pendingRequests.delete(l.id),"error"in l?d.reject(new Error(l.error)):d.resolve(l.frame))}),c.addEventListener("error",u=>{let l=new Error(u.message||"Color/alpha merge worker error.");for(let d of this.pendingRequests.values())d.reject(l);this.pendingRequests.clear()}),this.workers.push(c)}}let r=this.nextRequestId++,n=J();this.pendingRequests.set(r,n);let a=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,a.postMessage({id:r,color:t,alpha:e},{transfer:[t,e]}),n.promise}close(){for(let e of this.workers)e.terminate();this.workers.length=0;let t=new Error("Color/alpha merger closed.");for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},lh=()=>{let i=null,t=null,e=Promise.resolve();self.addEventListener("message",c=>{let{id:u,color:l,alpha:d}=c.data;e=e.then(async()=>{try{let m=await r(l,d);self.postMessage({id:u,frame:m},{transfer:[m]})}catch(m){self.postMessage({id:u,error:m.message})}finally{l.close(),d.close()}})});let r=async(c,u)=>{let l=c.format,d=u.format;if(!l||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");let m=l.includes("P10"),f=l.includes("P12"),p=d.includes("P10"),b=d.includes("P12");if(p!==m||b!==f)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${l}', alpha: '${d}').`);if(l==="RGBX"||l==="RGBA"||l==="BGRX"||l==="BGRA")return await n(c,u,l);if(l==="I420"||l==="I420P10"||l==="I420P12"||l==="I422"||l==="I422P10"||l==="I422P12"||l==="I444"||l==="I444P10"||l==="I444P12")return await a(c,u,l);if(l==="NV12")return await s(c,u);throw new Error(`CPU color/alpha merging does not support format '${l}'.`)},n=async(c,u,l)=>{let d=c.visibleRect?.width??c.codedWidth,m=c.visibleRect?.height??c.codedHeight,f=d*m,p=new Uint8Array(f*4);await c.copyTo(p);let b=await o(u,d,m,1);for(let k=0,T=3;k{let d=c.visibleRect?.width??c.codedWidth,m=c.visibleRect?.height??c.codedHeight,f=l.includes("P10"),p=l.includes("P12"),b=f||p?2:1,h,y;l.startsWith("I420")?(h=Math.ceil(d/2),y=Math.ceil(m/2)):l.startsWith("I422")?(h=Math.ceil(d/2),y=m):(h=d,y=m);let k=d*m,T=h*y,w=k*b,A=T*b,x=k*b,C=w+2*A+x,P=new Uint8Array(C);await c.copyTo(P);let S=await o(u,d,m,b),I=w+2*A;P.set(S,I);let v={format:l.slice(0,4)+"A"+l.slice(4),codedWidth:d,codedHeight:m,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[P.buffer]};return new VideoFrame(P,v)},s=async(c,u)=>{let l=c.visibleRect?.width??c.codedWidth,d=c.visibleRect?.height??c.codedHeight,m=l*d,f=Math.ceil(l/2),p=Math.ceil(d/2),b=f*p,h=c.allocationSize();(!t||t.byteLength!==h)&&(t=new Uint8Array(h)),await c.copyTo(t);let y=new Uint8Array(m+2*b+m);y.set(t.subarray(0,m),0);let k=m,T=m+b,w=m;for(let C=0;C{let m=c.allocationSize();(!i||i.byteLength!==m)&&(i=new Uint8Array(m)),await c.copyTo(i);let f=c.format;if(f==="RGBA"||f==="BGRA"||f==="RGBX"||f==="BGRX"){let p=f==="RGBA"||f==="RGBX"?0:2,b=u*l;for(let h=0;h{if(!i||typeof i!="object")throw new TypeError("decoderOptions must be an object.");if(i.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(i.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(i.optimizeForLatency!==void 0&&typeof i.optimizeForLatency!="boolean")throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")},Bi=class extends Aa{constructor(t,e={}){if(!(t instanceof _r))throw new TypeError("videoTrack must be an InputVideoTrack.");Km(e),super(),this._track=t,this._decoderOptions=e}async _createDecoder(t,e){if(!await this._track.canDecode())throw typeof VideoDecoder>"u"?new Error(Gi("VideoDecoder")):new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.");let r=await this._track.getCodec(),n=await this._track.getRotation(),a=await this._track.getFlip(),s=await this._track.getDecoderConfig(),o=await this._track.getTimeResolution();return g(r&&s),s={...s,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new vu(t,e,r,s,n,a,o)}_createPacketSink(){return new ft(this._track)}async getSample(t,e={}){vr(t);for await(let r of this.mediaSamplesAtTimestamps([t],e))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(t,e,r={}){return this.mediaSamplesInRange(t,e,r)}samplesAtTimestamps(t,e={}){return this.mediaSamplesAtTimestamps(t,e)}},Ru=class{constructor(t,e={}){this._rotation=0;this._flip=!1;this._initPromise=null;this._nextCanvasIndex=0;if(!(t instanceof _r))throw new TypeError("videoTrack must be an InputVideoTrack.");if(e&&typeof e!="object")throw new TypeError("options must be an object.");if(e.alpha!==void 0&&typeof e.alpha!="boolean")throw new TypeError("options.alpha, when provided, must be a boolean.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");if(e.crop!==void 0&&ni(e.crop,"options."),e.poolSize!==void 0&&(typeof e.poolSize!="number"||!Number.isInteger(e.poolSize)||e.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");e.decoderOptions!==void 0&&Km(e.decoderOptions),this._videoTrack=t,this._alpha=e.alpha??!1,this._options=e,this._fit=e.fit??"fill",this._videoSampleSink=new Bi(t,e.decoderOptions),this._canvasPool=Array.from({length:e.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??=(async()=>{let t=this._options,e=this._videoTrack,r=t.rotation??await e.getRotation(),n=t.flip??await e.getFlip(),a=await e.getSquarePixelWidth(),s=await e.getSquarePixelHeight(),[o,c]=r%180===0?[a,s]:[s,a],u=t.crop;u&&(u=wn(u,o,c));let[l,d]=u?[u.width,u.height]:[o,c],m=l/d;t.width!==void 0&&t.height===void 0?(l=t.width,d=Math.round(l/m)):t.width===void 0&&t.height!==void 0?(d=t.height,l=Math.round(d*m)):t.width!==void 0&&t.height!==void 0&&(l=t.width,d=t.height),this._width=l,this._height=d,this._rotation=r,this._flip=n,this._crop=u})()}_videoSampleToWrappedCanvas(t){let e=this._width,r=this._height,n=this._canvasPool[this._nextCanvasIndex],a=!1;n||(typeof document<"u"?(n=document.createElement("canvas"),n.width=e,n.height=r):n=new OffscreenCanvas(e,r),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=n),a=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let s=n.getContext("2d",{alpha:this._alpha||yi()});g(s),t._drawWithFitAndMipmapping(n,s,{fit:this._fit,rotation:this._rotation,flip:this._flip,crop:this._crop,targetIsFresh:a,fillBlack:!this._alpha&&yi()});let o={canvas:n,timestamp:t.timestamp,duration:t.duration};return t.close(),o}async getCanvas(t,e){vr(t),await this._ensureInit();let r=await this._videoSampleSink.getSample(t,e);return r&&this._videoSampleToWrappedCanvas(r)}async*canvases(t,e,r){await this._ensureInit(),yield*zn(this._videoSampleSink.samples(t,e,r),n=>this._videoSampleToWrappedCanvas(n))}async*canvasesAtTimestamps(t,e){await this._ensureInit(),yield*zn(this._videoSampleSink.samplesAtTimestamps(t,e),r=>r&&this._videoSampleToWrappedCanvas(r))}},Fu=class extends Sa{constructor(e,r,n,a){super(e,r);this.decoder=null;this.customDecoder=null;this.customDecoderCallSerializer=new Or;this.customDecoderQueueSize=0;this.currentTimestamp=null;this.expectedFirstTimestamp=null;this.timestampOffset=0;let s=c=>{let u=c.timestamp;this.expectedFirstTimestamp!==null&&this.currentTimestamp===null&&(this.timestampOffset=this.expectedFirstTimestamp-u),u+=this.timestampOffset,(this.currentTimestamp===null||Math.abs(u-this.currentTimestamp)>=c.duration)&&(this.currentTimestamp=u);let l=this.currentTimestamp;if(this.currentTimestamp+=c.duration,c.numberOfFrames===0){c.close();return}let d=a.sampleRate;c.setTimestamp(Math.round(l*d)/d),e(c)},o=ri.find(c=>c.supports(n,a));if(o)this.customDecoder=new o,this.customDecoder.codec=n,this.customDecoder.config=a,this.customDecoder.onSample=c=>{if(!(c instanceof Ce))throw new TypeError("The argument passed to onSample must be an AudioSample.");s(c)},this.customDecoder.onError=c=>{r(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(c=>r(c));else{let c=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:u=>{try{s(new Ce(u))}catch(l){this.onError(l)}},error:u=>{u.stack=c,this.onError(u)}}),this.decoder.configure(a)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(g(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(r=>this.onError(r)).finally(()=>this.customDecoderQueueSize--)):(g(this.decoder),this.expectedFirstTimestamp??=e.timestamp,this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(g(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(g(this.decoder),this.decoder.state!=="closed"&&this.decoder.close())}},Mu=class extends Sa{constructor(e,r,n){super(e,r);this.decoderConfig=n;this.currentTimestamp=null;g(ae.includes(n.codec)),this.codec=n.codec;let{dataType:a,sampleSize:s,littleEndian:o}=Re(this.codec);switch(this.inputSampleSize=s,s){case 1:a==="unsigned"?this.readInputValue=(c,u)=>c.getUint8(u)-2**7:a==="signed"?this.readInputValue=(c,u)=>c.getInt8(u):a==="ulaw"?this.readInputValue=(c,u)=>Lm(c.getUint8(u)):a==="alaw"?this.readInputValue=(c,u)=>Hm(c.getUint8(u)):g(!1);break;case 2:a==="unsigned"?this.readInputValue=(c,u)=>c.getUint16(u,o)-2**15:a==="signed"?this.readInputValue=(c,u)=>c.getInt16(u,o):g(!1);break;case 3:a==="unsigned"?this.readInputValue=(c,u)=>gi(c,u,o)-2**23:a==="signed"?this.readInputValue=(c,u)=>Fl(c,u,o):g(!1);break;case 4:a==="unsigned"?this.readInputValue=(c,u)=>c.getUint32(u,o)-2**31:a==="signed"?this.readInputValue=(c,u)=>c.getInt32(u,o):a==="float"?this.readInputValue=(c,u)=>c.getFloat32(u,o):g(!1);break;case 8:a==="float"?this.readInputValue=(c,u)=>c.getFloat64(u,o):g(!1);break;default:ne(s),g(!1)}switch(s){case 1:a==="ulaw"||a==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,u,l)=>c.setInt16(u,l,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(c,u,l)=>c.setUint8(u,l+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,u,l)=>c.setInt16(u,l,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(c,u,l)=>c.setInt32(u,l<<8,!0);break;case 4:this.outputSampleSize=4,a==="float"?(this.outputFormat="f32",this.writeOutputValue=(c,u,l)=>c.setFloat32(u,l,!0)):(this.outputFormat="s32",this.writeOutputValue=(c,u,l)=>c.setInt32(u,l,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(c,u,l)=>c.setFloat32(u,l,!0);break;default:ne(s),g(!1)}}getDecodeQueueSize(){return 0}decode(e){let r=N(e.data),n=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,a=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(a),o=new DataView(s);for(let d=0;d=c)&&(this.currentTimestamp=e.timestamp);let u=this.currentTimestamp;this.currentTimestamp+=c;let l=new Ce({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:u});this.onSample(l)}async flush(){}close(){}},xn=class extends Aa{constructor(t){if(!(t instanceof Rr))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=t}async _createDecoder(t,e){if(!await this._track.canDecode())throw typeof AudioDecoder>"u"?new Error(Gi("AudioDecoder")):new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.");let r=await this._track.getCodec(),n=await this._track.getDecoderConfig();return g(r&&n),ae.includes(n.codec)?new Mu(t,e,n):new Fu(t,e,r,n)}_createPacketSink(){return new ft(this._track)}async getSample(t,e={}){vr(t);for await(let r of this.mediaSamplesAtTimestamps([t],e))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(t,e,r={}){return this.mediaSamplesInRange(t,e,r)}samplesAtTimestamps(t,e={}){return this.mediaSamplesAtTimestamps(t,e)}},Bu=class{constructor(t){if(!(t instanceof Rr))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new xn(t)}_audioSampleToWrappedArrayBuffer(t){let e={buffer:t.toAudioBuffer(),timestamp:t.timestamp,duration:t.duration};return t.close(),e}async getBuffer(t,e){vr(t);let r=await this._audioSampleSink.getSample(t,e);return r&&this._audioSampleToWrappedArrayBuffer(r)}buffers(t,e,r){return zn(this._audioSampleSink.samples(t,e,r),n=>this._audioSampleToWrappedArrayBuffer(n))}buffersAtTimestamps(t,e){return zn(this._audioSampleSink.samplesAtTimestamps(t,e),r=>r&&this._audioSampleToWrappedArrayBuffer(r))}};var Oi=class i{constructor(t,e){this.input=t,this._backing=e}isVideoTrack(){return this instanceof _r}isAudioTrack(){return this instanceof Rr}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return ge(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return ge(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return ge(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return ge(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(t){return this._backing.getUnixTimeForTimestamp(t)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return ge(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(t){let e=await this._backing.getPacket(1/0,{metadataOnly:!0,...t}),r=(e?.timestamp??0)+(e?.duration??0);return qt(r,await this.getTimeResolution())}async getDurationFromMetadata(t={}){return this._backing.getDurationFromMetadata(t)}async computePacketStats(t=1/0,e){let r=new ft(this),n=1/0,a=-1/0,s=0,o=0;for await(let c of r.packets(void 0,void 0,{metadataOnly:!0,...e})){if(s>=t&&c.timestamp>=a)break;n=Math.min(n,c.timestamp),a=Math.max(a,c.timestamp+c.duration),s++,o+=c.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(a-n)).toPrecision(16)):0,averageBitrate:s?Number((8*o/(a-n)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(t){if(!(t instanceof i))throw new TypeError("other must be an InputTrack.");return this.input!==t.input||this===t?!1:(this._backing.getPairingMask()&t._backing.getPairingMask())!==0n}async getPairableTracks(t){return this.input.getTracks(si({filter:e=>e.canBePairedWith(this)},t))}async getPairableVideoTracks(t){return this.input.getVideoTracks(si({filter:e=>e.canBePairedWith(this)},t))}async getPairableAudioTracks(t){return this.input.getAudioTracks(si({filter:e=>e.canBePairedWith(this)},t))}async getPrimaryPairableVideoTrack(t){return this.input.getPrimaryVideoTrack(si({filter:e=>e.canBePairedWith(this)},t))}async getPrimaryPairableAudioTrack(t){return this.input.getPrimaryAudioTrack(si({filter:e=>e.canBePairedWith(this)},t))}async hasPairableTrack(t){t&&=Ou(t);let e=await this.input.getTracks();for(let r of e)if(this.canBePairedWith(r)&&(!t||await t(r)))return!0;return!1}hasPairableVideoTrack(t){return t&&=Ou(t),this.hasPairableTrack(async e=>e.isVideoTrack()&&(!t||await t(e)))}hasPairableAudioTrack(t){return t&&=Ou(t),this.hasPairableTrack(async e=>e.isAudioTrack()&&(!t||await t(e)))}},ge=(i,t,e)=>{if(_(i))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${e}()' instead.`);return i},Ou=i=>{if(i!==void 0&&typeof i!="function")throw new TypeError("predicate, when provided, must be a function.");return i?t=>{let e=n=>{if(typeof n!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return n},r=i(t);return _(r)?r.then(e):e(r)}:void 0},_r=class extends Oi{constructor(e,r){super(e,r);this._pixelAspectRatioCache=null}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return ge(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??await this._backing.getCodec()==="prores"}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return ge(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return ge(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getTransformationMatrix(){return this._backing.getTransformationMatrix()}async getRotation(){return fi(await this._backing.getTransformationMatrix())}get rotation(){return fi(ge(this._backing.getTransformationMatrix(),"rotation","getRotation"))}async getFlip(){return uc(await this._backing.getTransformationMatrix())}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return ge(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return ge(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=Gt({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=Gt({num:ge(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*ge(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:ge(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*ge(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}async getDisplayWidth(){let e=await this._backing.getMetadataDisplayWidth?.();return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){let e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){let a=ge(e,"displayWidth","getDisplayWidth");if(a!==null)return a}let n=fi(ge(this._backing.getTransformationMatrix(),"displayWidth","getDisplayWidth"))%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return ge(n,"displayWidth","getDisplayWidth")}async getDisplayHeight(){let e=await this._backing.getMetadataDisplayHeight?.();return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){let e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){let a=ge(e,"displayHeight","getDisplayHeight");if(a!==null)return a}let n=fi(ge(this._backing.getTransformationMatrix(),"displayHeight","getDisplayHeight"))%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return ge(n,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pq"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let r=await this._backing.getCodec();return g(r!==null),ti.some(a=>a.supports(r,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return z._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof X))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");let r=await this.getCodec();if(r===null)return null;let n=await this.getDecoderConfig();return g(n),qr(r,n,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.targetPacketCount!==void 0&&(!ve(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");let r=await this.getTimeResolution(),n=e.targetPacketCount??256,a=new ft(this),s=[],o=-1/0,c=0;for await(let E of a.packets(void 0,void 0,{metadataOnly:!0})){if(s.length>=n&&E.timestamp>=o)break;s.push(E.timestamp),o=Math.max(o,E.timestamp),c++}let u=new Float64Array(s.length);for(let E=0;EE-v),A=T-1>>1,x=T>>1,C=0,P=0,S=0;for(let E of w)if(S+=b.get(E),C===0&&S>A&&(C=E),S>x){P=E;break}let I=(f/C+f/P)/2;return{underlyingFrameRate:m,bestGuessFrameRate:m!==null?m:fh(I),minFrameRate:f/y,maxFrameRate:f/h,averageFrameRate:f*T/k,medianFrameRate:I,frameRateIsConstant:m!==null&&h===1&&y===1,probedPacketCount:c}}},Rr=class extends Oi{constructor(t,e){super(t,e)}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return ge(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return ge(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return ge(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let t=await this._backing.getMetadataCodecParameterString?.();return t??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let t=await this._backing.getDecoderConfig();if(!t)return!1;let e=await this._backing.getCodec();return g(e!==null),ri.some(r=>r.supports(e,t))||ae.includes(t.codec)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(t)).supported===!0}catch(t){return z._error("Error during decodability check:",t),!1}}async determinePacketType(t){if(!(t instanceof X))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}},dh=i=>i??1/0,Bo=i=>-(i??-1/0),Di=i=>-i,Cn=i=>{if(typeof i!="object"||!i)throw new TypeError("query must be an object.");if(i.filter!==void 0&&typeof i.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(i.sortBy!==void 0&&typeof i.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:i.filter?t=>{let e=n=>{if(typeof n!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return n},r=i.filter(t);return _(r)?r.then(e):e(r)}:void 0,sortBy:i.sortBy?t=>{let e=n=>{if(typeof n!="number"&&(!Array.isArray(n)||!n.every(a=>typeof a=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return n},r=i.sortBy(t);return _(r)?r.then(e):e(r)}:void 0}},si=(i,t)=>({filter:i?.filter||t?.filter?e=>{let r=i?.filter?.(e)??!0,n=a=>a===!1?!1:t?.filter?.(e)??!0;return _(r)?r.then(n):n(r)}:void 0,sortBy:i?.sortBy||t?.sortBy?e=>{let r=i?.sortBy?.(e)??[],n=t?.sortBy?.(e)??[],a=(s,o)=>[...Array.isArray(s)?s:[s],...Array.isArray(o)?o:[o]];return _(r)||_(n)?Promise.all([r,n]).then(([s,o])=>a(s,o)):a(r,n)}:void 0}),Oo=async(i,t)=>{let e=i;if(t?.filter){let s=i.map(c=>t.filter(c));if(s.some(c=>_(c))){let c=await Promise.all(s);e=i.filter((u,l)=>c[l])}else e=i.filter((c,u)=>s[u])}if(!t?.sortBy)return e;let r=e.map(s=>t.sortBy(s)),a=r.some(s=>_(s))?await Promise.all(r):r;return e.map((s,o)=>({track:s,sortValue:a[o]})).sort((s,o)=>{let c=Array.isArray(s.sortValue)?s.sortValue:[s.sortValue],u=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],l=Math.max(c.length,u.length);for(let d=0;ds.track)},mh=(i,t)=>{let n=1.000000001,a=1e3,s=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(i.length<2)return null;let o=new Float64Array(i.length-1);for(let C=1;C0))return null;o[C-1]=P}let c=o.slice();c.sort();let u=c[Math.floor(c.length*.05)];for(let C=0;C<6;C++){let P=0,S=0;for(let E of o){let v=Math.max(1,Math.round(E/u));Math.abs(E-v*u)>=n||(P+=E,S+=v)}if(S===0)return null;let I=P/S;if(Math.abs(I-u)<=1e-12*Math.max(1,u)){u=I;break}u=I}let l=0,d=0,m=0;for(let C of o){let P=Math.max(1,Math.round(C/u));Math.abs(C-P*u)>=n||(l++,d+=C,m+=P)}if(l/o.length<.98)return null;u=d/m;let f=1/Math.min(m,a),p=Math.max(Number.EPSILON,u-f),b=u+f,h=t/b,y=t/p,k=t/u,T=null,w=1/0;for(let C of s){if(Cy)continue;let P=Math.abs(C/k-1);P{for(let r=1;r<=e;r++){let n=Math.floor(i*r)+1;if(n/r{let t=[23.976023976023978,29.970029970029973,59.940059940059946,119.88011988011989],e=[12,15,20,24,25,30,48,50,60,100,120,144,240],r=5e-4,n=.025;for(let o of t)if(Math.abs(o/i-1)<=r)return o;let a=i,s=1/0;for(let o of e){let c=Math.abs(o/i-1);c<=n&&c!(r instanceof it)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof qe||e.source instanceof _i))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof qe&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof i))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&wm(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof qe?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get disposed(){return this._disposed}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){g(this._rootSource instanceof rt);let r=await this._rootSource._resolveRequest(e);return this._emit("source",{source:r.source,request:e,isRoot:e.isRoot}),r}_getSourceCached(e,r=ph){let n=this._sourceCache.find(o=>o.cacheGroup===r&&du(o.request,e));if(n)return n.age++,Promise.resolve(n.sourceRef.source.ref());let a=this._sourceCachePromises.find(o=>o.cacheGroup===r&&du(o.request,e));if(a)return a.promise.then(o=>o.sourceRef.source.ref());let s=(async()=>{let o=await this._getSourceUncached(e);if(wi(this._sourceCache,m=>m.cacheGroup===r&&m.sourceRef.source._refCount===1)>=4){let m=Xi(this._sourceCache,p=>p.cacheGroup===r&&p.sourceRef.source._refCount===1?p.age:1/0);g(m!==-1);let f=this._sourceCache[m];this._sourceCache.splice(m,1),f.sourceRef.free(),Qi(this._sourceRefs,f.sourceRef)}this._sourceRefs.push(o);let l=this._sourceCachePromises.findIndex(m=>m.request===e);return g(l!==-1),this._sourceCachePromises.splice(l,1),{request:e,sourceRef:o,age:this._nextSourceCacheAge++,cacheGroup:r}})();return this._sourceCachePromises.push({request:e,cacheGroup:r,promise:s}),s.then(o=>{let c=o.sourceRef.source.ref();return this._sourceCache.push(o),c})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new ei(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new xa})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),g(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof xa)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();let r=e.filter(s=>s!==null);if(r.length===0)return 0;let n=await Promise.all(r.map(s=>s._backing.getFirstPacket({metadataOnly:!0}))),a=Math.min(...n.map(s=>s?.timestamp??1/0));return a===1/0?0:a}async computeDuration(e,r){e??=await this.getTracks();let n=e.filter(s=>s!==null);if(n.length===0)return 0;let a=await Promise.all(n.map(s=>s.computeDuration(r)));return Math.max(...a)}async getDurationFromMetadata(e,r){e??=await this.getTracks();let n=e.filter(o=>o!==null),s=(await Promise.all(n.map(o=>o.getDurationFromMetadata(r)))).filter(o=>o!==null);return s.length===0?null:Math.max(...s)}async getTracks(e){e&&=Cn(e);let n=(await this._getTrackBackings()).map(a=>this._wrapBackingAsTrack(a));return Oo(n,e)}async getVideoTracks(e){e&&=Cn(e);let n=(await this.getTracks()).filter(a=>a.isVideoTrack());return Oo(n,e)}async getAudioTracks(e){e&&=Cn(e);let n=(await this.getTracks()).filter(a=>a.isAudioTrack());return Oo(n,e)}async getPrimaryVideoTrack(e){e&&=Cn(e);let r=si(e,{sortBy:async a=>[Di((await a.getDisposition()).default),Di(await a.hasPairableAudioTrack()),Di(!await a.hasOnlyKeyPackets()),Bo(await a.getBitrate())]});return(await this.getVideoTracks(r))[0]??null}async getPrimaryAudioTrack(e){e&&=Cn(e);let r=await this.getPrimaryVideoTrack(),n=si(e,{sortBy:async s=>[Di(!r||s.canBePairedWith(r)),Di((await s.getDisposition()).default),Bo(await s.getBitrate())]});return(await this.getAudioTracks(n))[0]??null}async _getTrackBackings(){let e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){let r=this._backingToTrack.get(e);if(r)return r;let a=e.getType()==="video"?new _r(this,e):new Rr(this,e);return this._backingToTrack.set(e,a),a}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(let e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}},xa=class extends Error{constructor(t="Input has an unsupported or unrecognizable format."){super(t),this.name="UnsupportedInputFormatError"}},ke=class extends Error{constructor(t="Input has been disposed."){super(t),this.name="InputDisposedError"}};var ei=class{constructor(t){this.source=t}get fileSize(){let t=this.source._getFileSize();if(t===void 0)throw new Error("Reading file size too early; read required first.");return t}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(t,e){if(this.source._disposed)throw new ke;if(t<0||this.fileSizeNonStrict!==null&&t+e>this.fileSizeNonStrict)return null;if(e===0){let a=new Uint8Array(0);return new xe(a,N(a),0,t,t)}let r=t+e,n=this.source._read(t,r,uu,lu);return _(n)?n.then(a=>a?new xe(a.bytes,a.view,a.offset,t,r):null):n?new xe(n.bytes,n.view,n.offset,t,r):null}requestSliceRange(t,e,r){if(this.source._disposed)throw new ke;if(t<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(t,ee(this.fileSizeNonStrict-t,e,r));{let n=this.requestSlice(t,r),a=s=>s||(g(this.fileSizeNonStrict!==null),this.requestSlice(t,ee(this.fileSizeNonStrict-t,e,r)));return _(n)?n.then(a):a(n)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let t=1024;return(async()=>{let e=[],r=0;for(;;){if(e.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let s=this.requestSliceRange(r,0,t);if(_(s)&&(s=await s),!s||s.length===0)break;let o=V(s,s.length);e.push(o),r+=s.length}let n=new Uint8Array(r),a=0;for(let s of e)n.set(s,a),a+=s.length;return new xe(n,N(n),0,0,r)})()}},xe=class i{constructor(t,e,r,n,a){this.bytes=t;this.view=e;this.offset=r;this.start=n;this.end=a;this.bufferPos=n-r}static tempFromBytes(t){return new i(t,N(t),0,0,t.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(t){this.bufferPos=t-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(t){this.bufferPos+=t}slice(t,e=this.end-t){if(tthis.end)throw new RangeError("Slicing outside of original slice.");return new i(this.bytes,this.view,this.offset,t,t+e)}},nt=(i,t)=>{if(i.filePosi.end)throw new RangeError(`Tried reading [${i.filePos}, ${i.filePos+t}), but slice is [${i.start}, ${i.end}). This is likely an internal error, please report it alongside the file that caused it.`)},V=(i,t)=>{nt(i,t);let e=i.bytes.subarray(i.bufferPos,i.bufferPos+t);return i.bufferPos+=t,e},L=i=>(nt(i,1),i.view.getUint8(i.bufferPos++)),fn=(i,t)=>{nt(i,2);let e=i.view.getUint16(i.bufferPos,t);return i.bufferPos+=2,e},he=i=>{nt(i,2);let t=i.view.getUint16(i.bufferPos,!1);return i.bufferPos+=2,t},Dt=i=>{nt(i,3);let t=gi(i.view,i.bufferPos,!1);return i.bufferPos+=3,t},ta=i=>{nt(i,2);let t=i.view.getInt16(i.bufferPos,!1);return i.bufferPos+=2,t},Ir=(i,t)=>{nt(i,4);let e=i.view.getUint32(i.bufferPos,t);return i.bufferPos+=4,e},M=i=>{nt(i,4);let t=i.view.getUint32(i.bufferPos,!1);return i.bufferPos+=4,t},Pi=i=>{nt(i,4);let t=i.view.getUint32(i.bufferPos,!0);return i.bufferPos+=4,t},Ar=i=>{nt(i,4);let t=i.view.getInt32(i.bufferPos,!1);return i.bufferPos+=4,t},hh=i=>{nt(i,4);let t=i.view.getInt32(i.bufferPos,!0);return i.bufferPos+=4,t},Lc=(i,t)=>{let e,r;return t?(e=Ir(i,!0),r=Ir(i,!0)):(r=Ir(i,!1),e=Ir(i,!1)),r*4294967296+e},We=i=>{let t=M(i),e=M(i);return t*4294967296+e},zd=i=>{let t=Ar(i),e=M(i);return t*4294967296+e},$d=i=>{let t=Pi(i);return hh(i)*4294967296+t},qd=i=>{nt(i,4);let t=i.view.getFloat32(i.bufferPos,!1);return i.bufferPos+=4,t},vs=i=>{nt(i,8);let t=i.view.getFloat64(i.bufferPos,!1);return i.bufferPos+=8,t},oe=(i,t)=>{nt(i,t);let e="";for(let r=0;rye.decode(V(i,t)).split(` +`).map(a=>a.trim()).filter(a=>a.length>0&&!e?.ignore?.(a));var aa=128,Ue=10,In=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],Gd=(i,t)=>{let e=i.filePos;t.raw??={},t.raw.TAG??=V(i,aa-3),i.filePos=e;let r=Pn(i,30);r&&(t.title??=r);let n=Pn(i,30);n&&(t.artist??=n);let a=Pn(i,30);a&&(t.album??=a);let s=Pn(i,4),o=Number.parseInt(s,10);Number.isInteger(o)&&o>0&&(t.date??=new Date(String(o)));let c=V(i,30),u;if(c[28]===0&&c[29]!==0){let d=c[29];d>0&&(t.trackNumber??=d),i.skip(-30),u=Pn(i,28),i.skip(2)}else i.skip(-30),u=Pn(i,30);u&&(t.comment??=u);let l=L(i);l{let e=V(i,t),r=ki(e.indexOf(0),e.length),n=e.subarray(0,r),a="";for(let s=0;s{let t=i.filePos,e=oe(i,3),r=L(i),n=L(i),a=L(i),s=M(i);if(e!=="ID3"||r===255||n===255||(s&2155905152)!==0)return i.filePos=t,null;let o=ks(s);return a&16&&(o+=Ue),{majorVersion:r,revision:n,flags:a,size:o}},Jr=(i,t,e)=>{if(![2,3,4].includes(t.majorVersion)){z._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}let r=t.flags&16?t.size-Ue:t.size,n=V(i,r),a=new Du(t,n);if(t.flags&128&&t.majorVersion===3&&a.ununsynchronizeAll(),t.flags&64){let s=a.readU32();t.majorVersion===3?a.pos+=s:a.pos+=s-4}for(;a.pos<=a.bytes.length-a.frameHeaderSize();){let s=a.readId3V2Frame();if(!s)break;let o=a.pos,c=a.pos+s.size,u=!1,l=!1,d=!1;if(t.majorVersion===3?(u=!!(s.flags&64),l=!!(s.flags&128)):t.majorVersion===4&&(u=!!(s.flags&4),l=!!(s.flags&8),d=!!(s.flags&2)||!!(t.flags&128)),u){z._warn(`Skipping encrypted ID3v2 frame ${s.id}`),a.pos=c;continue}if(l){z._warn(`Skipping compressed ID3v2 frame ${s.id}`),a.pos=c;continue}if(d&&a.ununsynchronizeRegion(a.pos,c),e.raw??={},s.id==="TXXX"){let m=e.raw.TXXX??={},f=a.readId3V2TextEncoding(),p=a.readId3V2Text(f,c),b=a.readId3V2Text(f,c);m[p]??=b}else s.id[0]==="T"?e.raw[s.id]??=a.readId3V2EncodingAndText(c):e.raw[s.id]??=a.readBytes(s.size);switch(a.pos=o,s.id){case"TIT2":case"TT2":e.title??=a.readId3V2EncodingAndText(c);break;case"TIT3":case"TT3":e.description??=a.readId3V2EncodingAndText(c);break;case"TPE1":case"TP1":e.artist??=a.readId3V2EncodingAndText(c);break;case"TALB":case"TAL":e.album??=a.readId3V2EncodingAndText(c);break;case"TPE2":case"TP2":e.albumArtist??=a.readId3V2EncodingAndText(c);break;case"TRCK":case"TRK":{let f=a.readId3V2EncodingAndText(c).split("/"),p=Number.parseInt(f[0],10),b=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.trackNumber??=p),b&&Number.isInteger(b)&&b>0&&(e.tracksTotal??=b)}break;case"TPOS":case"TPA":{let f=a.readId3V2EncodingAndText(c).split("/"),p=Number.parseInt(f[0],10),b=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(e.discNumber??=p),b&&Number.isInteger(b)&&b>0&&(e.discsTotal??=b)}break;case"TCON":case"TCO":{let m=a.readId3V2EncodingAndText(c),f=/^\((\d+)\)/.exec(m);if(f){let p=Number.parseInt(f[1]);if(In[p]!==void 0){e.genre??=In[p];break}}if(f=/^\d+$/.exec(m),f){let p=Number.parseInt(f[0]);if(In[p]!==void 0){e.genre??=In[p];break}}e.genre??=m}break;case"TDRC":case"TDAT":{let m=a.readId3V2EncodingAndText(c),f=new Date(m);Number.isNaN(f.getTime())||(e.date??=f)}break;case"TYER":case"TYE":{let m=a.readId3V2EncodingAndText(c),f=Number.parseInt(m,10);Number.isInteger(f)&&(e.date??=new Date(String(f)))}break;case"TBPM":case"TBP":{let m=a.readId3V2EncodingAndText(c),f=Number.parseInt(m,10);Number.isInteger(f)&&(e.beatsPerMinute??=f)}break;case"USLT":case"ULT":{let m=a.readU8();a.pos+=3,a.readId3V2Text(m,c),e.lyrics??=a.readId3V2Text(m,c)}break;case"COMM":case"COM":{let m=a.readU8();a.pos+=3,a.readId3V2Text(m,c),e.comment??=a.readId3V2Text(m,c)}break;case"APIC":case"PIC":{let m=a.readId3V2TextEncoding(),f;if(t.majorVersion===2){let y=a.readAscii(3);f=y==="PNG"?"image/png":y==="JPG"?"image/jpeg":"image/*"}else f=a.readId3V2Text(m,c);let p=a.readU8(),b=a.readId3V2Text(m,c).trimEnd(),h=c-a.pos;if(h>=0){let y=a.readBytes(h);e.images||(e.images=[]),e.images.push({data:y,mimeType:f,kind:p===3?"coverFront":p===4?"coverBack":"unknown",description:b})}}break;default:a.pos+=s.size;break}a.pos=c}},Du=class{constructor(t,e){this.header=t;this.bytes=e;this.pos=0;this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let t=[];for(let e=0;e{let c=this.pos+o;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=o;let u=this.readAscii(4);if(u!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(u))return!1}return!0};if(!s(r)){let o=this.header.majorVersion===4?e:ks(e);s(o)&&(r=o)}return this.pos=a,{id:t,size:r,flags:n}}}readId3V2TextEncoding(){let t=this.readU8();if(t>3)throw new Error(`Unsupported text encoding: ${t}`);return t}readId3V2Text(t,e){let r=this.pos,n=this.readBytes(e-this.pos);switch(t){case 0:{let a="";for(let s=0;so===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=r+Math.min(s+2,n.length),a.decode(n.subarray(2,s))}else if(n[0]===254&&n[1]===255){let a=new hi("utf-16be"),s=ki(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=r+Math.min(s+2,n.length),a.decode(n.subarray(2,s))}else{let a=ki(n.findIndex(s=>s===0),n.length);return this.pos=r+Math.min(a+1,n.length),ye.decode(n.subarray(0,a))}case 2:{let a=new hi("utf-16be"),s=ki(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=r+Math.min(s+2,n.length),a.decode(n.subarray(0,s))}case 3:{let a=ki(n.findIndex(s=>s===0),n.length);return this.pos=r+Math.min(a+1,n.length),ye.decode(n.subarray(0,a))}}}readId3V2EncodingAndText(t){if(this.pos>=t)return"";let e=this.readId3V2TextEncoding();return this.readId3V2Text(e,t)}},oi=class{constructor(t){this.helper=new Uint8Array(8);this.helperView=N(this.helper);this.writer=t}writeId3V2Tag(t){let e=this.writer.getPos();this.writeAscii("ID3"),this.writeU8(4),this.writeU8(0),this.writeU8(0),this.writeSynchsafeU32(0);let r=this.writer.getPos(),n=new Set;for(let{key:o,value:c}of vt(t))switch(o){case"title":this.writeId3V2TextFrame("TIT2",c),n.add("TIT2");break;case"description":this.writeId3V2TextFrame("TIT3",c),n.add("TIT3");break;case"artist":this.writeId3V2TextFrame("TPE1",c),n.add("TPE1");break;case"album":this.writeId3V2TextFrame("TALB",c),n.add("TALB");break;case"albumArtist":this.writeId3V2TextFrame("TPE2",c),n.add("TPE2");break;case"trackNumber":{let u=t.tracksTotal!==void 0?`${c}/${t.tracksTotal}`:c.toString();this.writeId3V2TextFrame("TRCK",u),n.add("TRCK")}break;case"discNumber":{let u=t.discsTotal!==void 0?`${c}/${t.discsTotal}`:c.toString();this.writeId3V2TextFrame("TPOS",u),n.add("TPOS")}break;case"genre":this.writeId3V2TextFrame("TCON",c),n.add("TCON");break;case"date":this.writeId3V2TextFrame("TDRC",c.toISOString().slice(0,10)),n.add("TDRC");break;case"beatsPerMinute":this.writeId3V2TextFrame("TBPM",`${c}`),n.add("TBPM");break;case"lyrics":this.writeId3V2LyricsFrame(c),n.add("USLT");break;case"comment":this.writeId3V2CommentFrame(c),n.add("COMM");break;case"images":{let u={coverFront:3,coverBack:4,unknown:0};for(let l of c){let d=u[l.kind]??0,m=l.description??"";this.writeId3V2ApicFrame(l.mimeType,d,m,l.data)}}break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ne(o)}if(t.raw)for(let o in t.raw){let c=t.raw[o];if(c==null||o.length!==4||n.has(o))continue;let u;if(typeof c=="string")if(Ct(c)){u=new Uint8Array(c.length+2),u[0]=0;for(let d=0;d=2**32)throw new Error("This muxer only supports writing up to 2 ** 32 samples");m.writeBits(4,0),m.writeBits(32,u),this.writer.write(m.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){let r=32+e.mimeType.length+(e.description?.length??0)+e.data.length,n=new Uint8Array(r),a=0,s=N(n);s.setUint32(a,e.kind==="coverFront"?3:e.kind==="coverBack"?4:0),a+=4,s.setUint32(a,e.mimeType.length),a+=4,n.set(Y.encode(e.mimeType),8),a+=e.mimeType.length,s.setUint32(a,e.description?.length??0),a+=4,n.set(Y.encode(e.description??""),a),a+=e.description?.length??0,a+=16,s.setUint32(a,e.data.length),a+=4,n.set(e.data,a),a+=e.data.length,g(a===r);let o=new H(new Uint8Array(4));o.writeBits(1,0),o.writeBits(7,6),o.writeBits(24,r),this.writer.write(o.bytes),this.writer.write(n)}writeVorbisCommentAndPictureBlock(){if(this.format._options.appendOnly||this.writer.seek(gh+Gm.byteLength),br(this.output._metadataTags)){this.metadataWritten=!0;return}let e=this.output._metadataTags.images??[];for(let a of e)this.writePictureBlock(a);let r=Qn(new Uint8Array(0),this.output._metadataTags,!1),n=new H(new Uint8Array(4));n.writeBits(1,1),n.writeBits(7,4),n.writeBits(24,r.length),this.writer.write(n.bytes),this.writer.write(r),this.metadataWritten=!0}async getMimeType(){return"audio/flac"}async addEncodedVideoPacket(){throw new Error("FLAC does not support video.")}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{this.validateTimestamp(e,r.timestamp,r.type==="key"),this.sampleRate===null&&(Se(n,e.source._codec),g(n),g(n.decoderConfig),this.applyDecoderConfig(n.decoderConfig)),this.metadataWritten||this.writeVorbisCommentAndPictureBlock();let s=xe.tempFromBytes(r.data);s.skip(2);let o=V(s,2),c=new H(o),u=Hs(c.readBits(4));if(u===null)throw new Error("Invalid FLAC frame: Invalid block size.");qs(s);let l=Ks(s,u);this.format._options.appendOnly||(this.blockSizes.push(l),this.frameSizes.push(r.data.length));let d=this.writer.getPos();this.writer.write(r.data),this.format._options.onFrame&&this.format._options.onFrame(r.data,d),await this.writer.flush()}finally{a()}}addSubtitleCue(){throw new Error("FLAC does not support subtitles.")}async finalize(){let e=await this.mutex.acquire();if(this.sampleRate===null)throw new Error("Cannot finalize an empty FLAC file: no packets were added and the track specified no decoderConfig in its metadata, so there's no telling what the file should look like.");if(this.metadataWritten||this.writeVorbisCommentAndPictureBlock(),!this.format._options.appendOnly){let r=1/0,n=0,a=1/0,s=0,o=0;for(let c=0;c\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,yh=/^WEBVTT(.|\n)*?\n{2}/,En=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Uo=class{constructor(t){this.preambleText=null;this.preambleEmitted=!1;this.options=t}parse(t){t=t.replaceAll(`\r +`,` +`).replaceAll("\r",` +`),Ca.lastIndex=0;let e;if(!this.preambleText){if(!yh.test(t))throw new Error("WebVTT preamble incorrect.");e=Ca.exec(t);let r=t.slice(0,e?.index??t.length).trimEnd();if(!r)throw new Error("No WebVTT preamble provided.");this.preambleText=r,e&&(t=t.slice(e.index),Ca.lastIndex=0)}for(;e=Ca.exec(t);){let r=t.slice(0,e.index),n=e[1],a=e.index+e[0].length,s=t.indexOf(` +`,a)+1,o=t.slice(a,s).trim(),c=t.indexOf(` + +`,a);c===-1&&(c=t.length);let u=zo(e[2]),d=zo(e[3])-u,m=t.slice(s,c).trim();t=t.slice(c).trimStart(),Ca.lastIndex=0;let f={timestamp:u/1e3,duration:d/1e3,text:m,identifier:n,settings:o,notes:r},p={};this.preambleEmitted||(p.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(f,p)}}},kh=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,zo=i=>{let t=kh.exec(i);if(!t)throw new Error("Expected match.");return 60*60*1e3*Number(t[1]||"0")+60*1e3*Number(t[2])+1e3*Number(t[3])+Number(t[4])},No=i=>{let t=Math.floor(i/36e5),e=Math.floor(i%(60*60*1e3)/(60*1e3)),r=Math.floor(i%(60*1e3)/1e3),n=i%1e3;return t.toString().padStart(2,"0")+":"+e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")};var Vi=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer);this.offsets=new WeakMap}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,Math.floor(t/2**32),!1),this.helperView.setUint32(4,t,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(t){for(let e=0;e[(i%256+256)%256],q=i=>(At.setUint16(0,i,!1),[j[0],j[1]]),Nu=i=>(At.setInt16(0,i,!1),[j[0],j[1]]),Ym=i=>(At.setUint32(0,i,!1),[j[1],j[2],j[3]]),R=i=>(At.setUint32(0,i,!1),[j[0],j[1],j[2],j[3]]),ur=i=>(At.setInt32(0,i,!1),[j[0],j[1],j[2],j[3]]),zt=i=>(At.setUint32(0,Math.floor(i/2**32),!1),At.setUint32(4,i,!1),[j[0],j[1],j[2],j[3],j[4],j[5],j[6],j[7]]),jm=i=>(At.setInt32(0,Math.floor(i/2**32),!1),At.setUint32(4,i,!1),[j[0],j[1],j[2],j[3],j[4],j[5],j[6],j[7]]),Zm=i=>(At.setInt16(0,2**8*i,!1),[j[0],j[1]]),St=i=>(At.setInt32(0,2**16*i,!1),[j[0],j[1],j[2],j[3]]),Vu=i=>(At.setInt32(0,2**30*i,!1),[j[0],j[1],j[2],j[3]]),Uu=(i,t)=>{let e=[],r=i;do{let n=r&127;r>>=7,e.length>0&&(n|=128),e.push(n),t!==void 0&&t--}while(r>0||t);return e.reverse()},ue=(i,t=!1)=>{let e=Array(i.length).fill(null).map((r,n)=>i.charCodeAt(n));return t&&e.push(0),e},Jm=i=>[St(i[0]),St(i[1]),Vu(i[2]),St(i[3]),St(i[4]),Vu(i[5]),St(i[6]),St(i[7]),Vu(i[8])],W=(i,t,e)=>({type:i,contents:t&&new Uint8Array(t.flat(10)),children:e}),te=(i,t,e,r,n)=>W(i,[be(t),Ym(e),r??[]],n),ef=i=>i.isQuickTime?W("ftyp",[ue("qt "),R(512),ue("qt ")]):i.fragmented?i.cmaf?W("ftyp",[ue("iso5"),R(512),ue("iso5"),ue("iso6"),ue("mp41"),ue("cmfc"),ue("dash")]):W("ftyp",[ue("iso5"),R(512),ue("iso5"),ue("iso6"),ue("mp41")]):W("ftyp",[ue("isom"),R(512),ue("isom"),i.holdsAvc?ue("avc1"):[],ue("mp41")]),Lu=()=>W("styp",[ue("iso5"),R(0),ue("iso5"),ue("iso6"),ue("mp41"),ue("cmfc"),ue("dash")]),Wu=(i,t)=>{let e=Math.max(0,i.minWrittenTimestamp),r=Math.max(0,i.maxWrittenEndTimestamp-e);return Number.isFinite(r)||(r=0),te("sidx",1,0,[R(1),R(at),zt(de(e,at)),zt(0),q(0),q(1),R(t&2147483647),R(de(r,at)),R(0)])},Pa=i=>({type:"mdat",largeSize:i}),tf=i=>({type:"free",size:i}),vn=i=>W("moov",void 0,[Th(i.creationTime,i.trackDatas),...i.trackDatas.map(t=>wh(t,i.creationTime)),i.isFragmented?og(i.trackDatas):null,gg(i)]),Th=(i,t)=>{let e=Math.max(0,...t.map(s=>Math.max(0,de(Ui(s),at)+de(s.startTimestampOffset??0,at)))),r=Math.max(0,...t.map(s=>s.track.id))+1,n=!Wt(i)||!Wt(e),a=n?zt:R;return te("mvhd",+n,0,[a(i),a(i),R(at),a(e),St(1),Zm(1),Array(10).fill(0),Jm(Dr),Array(24).fill(0),R(r)])},wh=(i,t)=>{let e=df(i),r=i.startTimestampOffset!==null&&i.startTimestampOffset!==0;return W("trak",void 0,[Sh(i,t),r?Ah(i):null,xh(i,t),e.name!==void 0?W("udta",void 0,[W("name",[...Y.encode(e.name)])]):null])},Sh=(i,t)=>{let e=Math.max(0,de(Ui(i),at)+de(i.startTimestampOffset??0,at)),r=!Wt(t)||!Wt(e),n=r?zt:R,a;if(i.type==="video"&&i.track.metadata.transformationMatrix)a=i.track.metadata.transformationMatrix;else if(i.type==="video"){let{rotation:c,flip:u}=i.track.metadata,l=Lt(qi(c??0),Va(u?-1:1,1));a=Da(l,i.info.width,i.info.height)}else a=Dr;let s=2;i.track.metadata.disposition?.default!==!1&&(s|=1);let o=i.type==="video"?0:i.type==="audio"?1:i.type==="subtitle"?2:ne(i);return te("tkhd",+r,s,[n(t),n(t),R(i.track.id),R(0),n(e),Array(8).fill(0),q(0),q(o),Zm(i.type==="audio"?1:0),q(0),Jm(a),St(i.type==="video"?i.info.width:0),St(i.type==="video"?i.info.height:0)])},Ah=i=>{let t=i.startTimestampOffset;if(g(t!==null),t>0){let e=de(t,at),r=de(Ui(i),at),n=!Wt(e)||!Wt(r),a=n?zt:R,s=n?jm:ur;return W("edts",void 0,[te("elst",n?1:0,0,[R(2),a(e),s(-1),St(1),a(r),s(0),St(1)])])}else{let e=de(-t,i.timescale),r=Math.max(0,de(Ui(i),at)+de(t,at)),n=!Pl(e)||!Wt(r),a=n?zt:R,s=n?jm:ur;return W("edts",void 0,[te("elst",n?1:0,0,[R(1),a(r),s(e),St(1)])])}},xh=(i,t)=>W("mdia",void 0,[Ch(i,t),Hu(!0,Ph[i.type],Ih[i.type]),Eh(i)]),Ch=(i,t)=>{let e=de(Ui(i),i.timescale),r=!Wt(t)||!Wt(e),n=r?zt:R;return te("mdhd",+r,0,[n(t),n(t),R(i.timescale),n(e),q(lf(i.track.metadata.languageCode??se)),q(0)])},Ph={video:"vide",audio:"soun",subtitle:"text"},Ih={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Hu=(i,t,e,r="\0\0\0\0")=>te("hdlr",0,0,[i?ue("mhlr"):R(0),ue(t),ue(r),R(0),R(0),ue(e,!0)]),Eh=i=>W("minf",void 0,[Fh[i.type](),Mh(),Dh(i)]),vh=()=>te("vmhd",0,1,[q(0),q(0),q(0),q(0)]),_h=()=>te("smhd",0,0,[q(0),q(0)]),Rh=()=>te("nmhd",0,0),Fh={video:vh,audio:_h,subtitle:Rh},Mh=()=>W("dinf",void 0,[Bh()]),Bh=()=>te("dref",0,0,[R(1)],[Oh()]),Oh=()=>te("url ",0,1),Dh=i=>{let t=i.compositionTimeOffsetTable.length>1||i.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return W("stbl",void 0,[Vh(i),eg(i),t?ag(i):null,t?sg(i):null,rg(i),ig(i),ng(i),tg(i)])},Vh=i=>{let t;if(i.type==="video")t=Uh(Tg(i.track.source._codec,i.info.decoderConfig.codec),i);else if(i.type==="audio"){let e=uf(i.track.source._codec,i.info.decoderConfig.codec,i.muxer.isQuickTime);g(e),t=qh(e,i)}else i.type==="subtitle"&&(t=Zh(Ag[i.track.source._codec],i));return g(t),te("stsd",0,0,[R(1)],[t])},Uh=(i,t)=>W(i,[Array(6).fill(0),q(1),q(0),q(0),Array(12).fill(0),q(t.info.width),q(t.info.height),R(4718592),R(4718592),R(0),q(1),be(yr.length),ue(yr),Array(31-yr.length).fill(0),q(t.info.hasAlphaChannel?32:24),Nu(65535)],[wg[t.track.source._codec]?.(t)??null,zh(t),za(t.info.decoderConfig.colorSpace)?null:Nh(t),qu(t)]),qu=i=>i.avgBitrate===0&&i.maxBitrate===0?null:W("btrt",[R(0),R(i.maxBitrate),R(i.avgBitrate)]),zh=i=>i.info.pixelAspectRatio.num===i.info.pixelAspectRatio.den?null:W("pasp",[R(i.info.pixelAspectRatio.num),R(i.info.pixelAspectRatio.den)]),Nh=i=>{let t=i.info.decoderConfig.colorSpace;return W("colr",[ue(i.muxer.isQuickTime?"nclc":"nclx"),q(t?.primaries!=null?Pt[t.primaries]:2),q(t?.transfer!=null?It[t.transfer]:2),q(t?.matrix!=null?Et[t.matrix]:2),i.muxer.isQuickTime?[]:be((t?.fullRange?1:0)<<7)])},Lh=i=>i.info.decoderConfig&&W("avcC",[...$(i.info.decoderConfig.description)]),Wh=i=>i.info.decoderConfig&&W("hvcC",[...$(i.info.decoderConfig.description)]),Xm=i=>{if(!i.info.decoderConfig)return null;let t=i.info.decoderConfig,e=t.codec.split("."),r=Number(e[1]),n=Number(e[2]),a=Number(e[3]),s=e[4]?Number(e[4]):1,o=e[8]?Number(e[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(s<<1)+o,u=e[5]?Number(e[5]):t.colorSpace?.primaries?Pt[t.colorSpace.primaries]:1,l=e[6]?Number(e[6]):t.colorSpace?.transfer?It[t.colorSpace.transfer]:1,d=e[7]?Number(e[7]):t.colorSpace?.matrix?Et[t.colorSpace.matrix]:1;return te("vpcC",1,0,[be(r),be(n),be(c),be(u),be(l),be(d),q(0)])},Hh=i=>W("av1C",fs(i.info.decoderConfig.codec)),qh=(i,t)=>{let e=0,r,n=16,a=ae.includes(t.track.source._codec);if(a){let s=t.track.source._codec,{sampleSize:o}=Re(s);n=8*o,n>16&&(e=1)}if(t.muxer.isQuickTime&&(e=1),e===0)r=[Array(6).fill(0),q(1),q(e),q(0),R(0),q(t.info.numberOfChannels),q(n),q(0),q(0),q(t.info.sampleRate<2**16?t.info.sampleRate:0),q(0)];else{let s=a?0:-2;r=[Array(6).fill(0),q(1),q(e),q(0),R(0),q(t.info.numberOfChannels),q(Math.min(n,16)),Nu(s),q(0),q(t.info.sampleRate<2**16?t.info.sampleRate:0),q(0),a?[R(1),R(n/8),R(t.info.numberOfChannels*n/8)]:[R(0),R(0),R(0)],R(2)]}return W(i,r,[Sg(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null,qu(t)])},zu=i=>{let t;switch(i.track.source._codec){case"aac":t=64;break;case"mp3":t=107;break;case"vorbis":t=221;break;default:throw new Error(`Unhandled audio codec: ${i.track.source._codec}`)}let e=[...be(t),...be(21),...Ym(0),...R(i.maxBitrate),...R(i.avgBitrate)];if(i.info.decoderConfig.description){let r=$(i.info.decoderConfig.description);e=[...e,...be(5),...Uu(r.byteLength),...r]}return e=[...q(1),...be(0),...be(4),...Uu(e.length),...e,...be(6),...be(1),...be(2)],e=[...be(3),...Uu(e.length),...e],te("esds",0,0,e)},ci=i=>W("wave",void 0,[Kh(i),Qh(i),W("\0\0\0\0")]),Kh=i=>W("frma",[ue(uf(i.track.source._codec,i.info.decoderConfig.codec,i.muxer.isQuickTime))]),Qh=i=>{let{littleEndian:t}=Re(i.track.source._codec);return W("enda",[q(+t)])},Gh=i=>{let t=i.info.numberOfChannels,e=3840,r=i.info.sampleRate,n=0,a=0,s=new Uint8Array(0),o=i.info.decoderConfig?.description;if(o){g(o.byteLength>=18);let c=$(o),u=Hr(c);t=u.outputChannelCount,e=u.preSkip,r=u.inputSampleRate,n=u.outputGain,a=u.channelMappingFamily,u.channelMappingTable&&(s=u.channelMappingTable)}return W("dOps",[be(0),be(t),q(e),R(r),Nu(n),be(a),...s])},jh=i=>{let t=i.info.decoderConfig?.description;g(t);let e=$(t);return te("dfLa",0,0,[...e.subarray(4)])},or=i=>{let{littleEndian:t,sampleSize:e}=Re(i.track.source._codec),r=+t;return te("pcmC",0,0,[be(r),be(8*e)])},Xh=i=>{g(i.info.primingPacket);let t=ns(i.info.primingPacket.data);if(!t)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");let e=new Uint8Array(3),r=new H(e);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),W("dac3",[...e])},$h=i=>{g(i.info.primingPacket);let t=as(i.info.primingPacket.data);if(!t)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let e=16;for(let s of t.substreams)e+=23,s.numDepSub>0?e+=9:e+=1;let r=Math.ceil(e/8),n=new Uint8Array(r),a=new H(n);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let s of t.substreams)a.writeBits(2,s.fscod),a.writeBits(5,s.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,s.bsmod),a.writeBits(3,s.acmod),a.writeBits(1,s.lfeon),a.writeBits(3,0),a.writeBits(4,s.numDepSub),s.numDepSub>0?a.writeBits(9,s.chanLoc):a.writeBits(1,0);return W("dec3",[...n])},Yh=i=>{g(i.info.primingPacket);let t=Yn(i.info.primingPacket.data);if(!t)throw new Error("Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.");return W("ddts",[...fd(t)])},Zh=(i,t)=>W(i,[Array(6).fill(0),q(1)],[xg[t.track.source._codec](t),qu(t)]),Jh=i=>W("vttC",[...Y.encode(i.info.config.description)]);var eg=i=>te("stts",0,0,[R(i.timeToSampleTable.length),i.timeToSampleTable.map(t=>[R(t.sampleCount),R(t.sampleDelta)])]),tg=i=>{if(i.samples.every(e=>e.type==="key"))return null;let t=[...i.samples.entries()].filter(([,e])=>e.type==="key");return te("stss",0,0,[R(t.length),t.map(([e])=>R(e+1))])},rg=i=>te("stsc",0,0,[R(i.compactlyCodedChunkTable.length),i.compactlyCodedChunkTable.map(t=>[R(t.firstChunk),R(t.samplesPerChunk),R(1)])]),ig=i=>{if(i.type==="audio"&&i.info.requiresPcmTransformation){let{sampleSize:t}=Re(i.track.source._codec);return te("stsz",0,0,[R(t*i.info.numberOfChannels),R(i.samples.reduce((e,r)=>e+de(r.duration,i.timescale),0))])}return te("stsz",0,0,[R(0),R(i.samples.length),i.samples.map(t=>R(t.size))])},ng=i=>i.finalizedChunks.length>0&&Z(i.finalizedChunks).offset>=2**32?te("co64",0,0,[R(i.finalizedChunks.length),i.finalizedChunks.map(t=>zt(t.offset))]):te("stco",0,0,[R(i.finalizedChunks.length),i.finalizedChunks.map(t=>R(t.offset))]),ag=i=>te("ctts",1,0,[R(i.compositionTimeOffsetTable.length),i.compositionTimeOffsetTable.map(t=>[R(t.sampleCount),ur(t.sampleCompositionTimeOffset)])]),sg=i=>{let t=1/0,e=-1/0,r=1/0,n=-1/0;g(i.compositionTimeOffsetTable.length>0),g(i.samples.length>0);for(let s=0;s=2**31?null:te("cslg",0,0,[ur(a),ur(t),ur(e),ur(r),ur(n)])},og=i=>W("mvex",void 0,i.map(cg)),cg=i=>te("trex",0,0,[R(i.track.id),R(1),R(0),R(0),R(0)]),Ku=(i,t)=>W("moof",void 0,[ug(i),...t.map(lg)]),ug=i=>te("mfhd",0,0,[R(i)]),rf=i=>{let t=0,e=0,r=0,n=0,a=i.type==="delta";return e|=+a,a?t|=1:t|=2,t<<24|e<<16|r<<8|n},lg=i=>W("traf",void 0,[dg(i),mg(i),fg(i)]),dg=i=>{g(i.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let e=i.currentChunk.samples[1]??i.currentChunk.samples[0],r={duration:e.timescaleUnitsToNextSample,size:e.size,flags:rf(e)};return te("tfhd",0,t,[R(i.track.id),R(r.duration),R(r.size),R(r.flags)])},mg=i=>(g(i.currentChunk),te("tfdt",1,0,[zt(de(i.currentChunk.startTimestamp,i.timescale))])),fg=i=>{g(i.currentChunk);let t=i.currentChunk.samples.map(b=>b.timescaleUnitsToNextSample),e=i.currentChunk.samples.map(b=>b.size),r=i.currentChunk.samples.map(rf),n=i.currentChunk.samples.map(b=>de(b.timestamp-b.decodeTimestamp,i.timescale)),a=new Set(t),s=new Set(e),o=new Set(r),c=new Set(n),u=o.size===2&&r[0]!==r[1],l=a.size>1,d=s.size>1,m=!u&&o.size>1,f=c.size>1||[...c].some(b=>b!==0),p=0;return p|=1,p|=4*+u,p|=256*+l,p|=512*+d,p|=1024*+m,p|=2048*+f,te("trun",1,p,[R(i.currentChunk.samples.length),R(i.currentChunk.offset-i.currentChunk.moofOffset||0),u?R(r[0]):[],i.currentChunk.samples.map((b,h)=>[l?R(t[h]):[],d?R(e[h]):[],m?R(r[h]):[],f?ur(n[h]):[]])])},nf=i=>W("mfra",void 0,[...i.map(pg),hg()]),pg=i=>te("tfra",1,0,[R(i.track.id),R(63),R(i.finalizedChunks.length),i.finalizedChunks.map(e=>[zt(de(e.samples[0].timestamp,i.timescale)),zt(e.moofOffset),R(e.trafIndex+1),R(1),R(1)])]),hg=()=>te("mfro",0,0,[R(0)]),af=()=>W("vtte"),sf=(i,t,e,r,n)=>W("vttc",void 0,[n!==null?W("vsid",[ur(n)]):null,e!==null?W("iden",[...Y.encode(e)]):null,t!==null?W("ctim",[...Y.encode(No(t))]):null,r!==null?W("sttg",[...Y.encode(r)]):null,W("payl",[...Y.encode(i)])]),of=i=>W("vtta",[...Y.encode(i)]),gg=i=>{let t=[],e=i.format._options.metadataFormat??"auto",r=i.output._metadataTags;if(e==="mdir"||e==="auto"&&!i.isQuickTime){let n=yg(r);n&&t.push(n)}else if(e==="mdta"){let n=kg(r);n&&t.push(n)}else(e==="udta"||e==="auto"&&i.isQuickTime)&&bg(t,i.output._metadataTags);return t.length===0?null:W("udta",void 0,t)},bg=(i,t)=>{for(let{key:e,value:r}of vt(t))switch(e){case"title":i.push(cr("\xA9nam",r));break;case"description":i.push(cr("\xA9des",r));break;case"artist":i.push(cr("\xA9ART",r));break;case"album":i.push(cr("\xA9alb",r));break;case"albumArtist":i.push(cr("albr",r));break;case"genre":i.push(cr("\xA9gen",r));break;case"date":i.push(cr("\xA9day",r.toISOString().slice(0,10)));break;case"comment":i.push(cr("\xA9cmt",r));break;case"lyrics":i.push(cr("\xA9lyr",r));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"beatsPerMinute":case"images":break;default:ne(e)}if(t.raw)for(let e in t.raw){let r=t.raw[e];r==null||e.length!==4||i.some(n=>n.type===e)||(typeof r=="string"?i.push(cr(e,r)):r instanceof Uint8Array&&i.push(W(e,Array.from(r))))}},cr=(i,t)=>{let e=Y.encode(t);return W(i,[q(e.length),q(lf("und")),Array.from(e)])},$m={"image/jpeg":13,"image/png":14,"image/bmp":27},cf=(i,t)=>{let e=[];for(let{key:r,value:n}of vt(i))switch(r){case"title":e.push({key:t?"title":"\xA9nam",value:Ut(n)});break;case"description":e.push({key:t?"description":"\xA9des",value:Ut(n)});break;case"artist":e.push({key:t?"artist":"\xA9ART",value:Ut(n)});break;case"album":e.push({key:t?"album":"\xA9alb",value:Ut(n)});break;case"albumArtist":e.push({key:t?"album_artist":"aART",value:Ut(n)});break;case"comment":e.push({key:t?"comment":"\xA9cmt",value:Ut(n)});break;case"genre":e.push({key:t?"genre":"\xA9gen",value:Ut(n)});break;case"beatsPerMinute":t||e.push({key:"tmpo",value:W("data",[R(21),R(0),q(n)])});break;case"lyrics":e.push({key:t?"lyrics":"\xA9lyr",value:Ut(n)});break;case"date":e.push({key:t?"date":"\xA9day",value:Ut(n.toISOString().slice(0,10))});break;case"images":for(let a of n)a.kind==="coverFront"&&e.push({key:"covr",value:W("data",[R($m[a.mimeType]??0),R(0),Array.from(a.data)])});break;case"trackNumber":if(t){let a=i.tracksTotal!==void 0?`${n}/${i.tracksTotal}`:n.toString();e.push({key:"track",value:Ut(a)})}else e.push({key:"trkn",value:W("data",[R(0),R(0),q(0),q(n),q(i.tracksTotal??0),q(0)])});break;case"discNumber":t||e.push({key:"disc",value:W("data",[R(0),R(0),q(0),q(n),q(i.discsTotal??0),q(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ne(r)}if(i.raw)for(let r in i.raw){let n=i.raw[r];n==null||!t&&r.length!==4||e.some(a=>a.key===r)||(typeof n=="string"?e.push({key:r,value:Ut(n)}):n instanceof Uint8Array?e.push({key:r,value:W("data",[R(0),R(0),Array.from(n)])}):n instanceof yt&&e.push({key:r,value:W("data",[R($m[n.mimeType]??0),R(0),Array.from(n.data)])}))}return e},yg=i=>{let t=cf(i,!1);return t.length===0?null:te("meta",0,0,void 0,[Hu(!1,"mdir","","appl"),W("ilst",void 0,t.map(e=>W(e.key,void 0,[e.value])))])},kg=i=>{let t=cf(i,!0);return t.length===0?null:W("meta",void 0,[Hu(!1,"mdta",""),te("keys",0,0,[R(t.length)],t.map(e=>W("mdta",[...Y.encode(e.key)]))),W("ilst",void 0,t.map((e,r)=>{let n=String.fromCharCode(...R(r+1));return W(n,void 0,[e.value])}))])},Ut=i=>W("data",[R(1),R(0),...Y.encode(i)]),Tg=(i,t)=>{switch(i){case"avc":return t.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";case"prores":return t}},wg={avc:Lh,hevc:Wh,vp8:Xm,vp9:Xm,av1:Hh,prores:null},uf=(i,t,e)=>{switch(i){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3";case"dts":return t}if(e)switch(i){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(i){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},Sg=(i,t)=>{switch(i){case"aac":return zu;case"mp3":return zu;case"opus":return Gh;case"vorbis":return zu;case"flac":return jh;case"ac3":return Xh;case"eac3":return $h;case"dts":return Yh}if(t)switch(i){case"pcm-s24":return ci;case"pcm-s24be":return ci;case"pcm-s32":return ci;case"pcm-s32be":return ci;case"pcm-f32":return ci;case"pcm-f32be":return ci;case"pcm-f64":return ci;case"pcm-f64be":return ci}else switch(i){case"pcm-s16":return or;case"pcm-s16be":return or;case"pcm-s24":return or;case"pcm-s24be":return or;case"pcm-s32":return or;case"pcm-s32be":return or;case"pcm-f32":return or;case"pcm-f32be":return or;case"pcm-f64":return or;case"pcm-f64be":return or}return null},Ag={webvtt:"wvtt"},xg={webvtt:Jh},lf=i=>{g(i.length===3);let t=0;for(let e=0;e<3;e++)t<<=5,t+=i.charCodeAt(e)-96;return t};var lr=class{constructor(t,e){this.finalized=!1;this.started=!1;this.pos=0;this.trackedWrites=null;this.trackedStart=-1;this.trackedEnd=-1;if(t._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=t,t._setMonotonicity(e),t._writerAcquired=!0}start(){g(!this.started),this.target._start(),this.started=!0}write(t){g(this.started&&!this.finalized),this.maybeTrackWrites(t),this.target._write(t,this.pos),this.pos+=t.byteLength}seek(t){this.pos=t}getPos(){return this.pos}async flush(){return g(this.started&&!this.finalized),this.target._flush()}async finalize(){g(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(t){if(!this.trackedWrites)return;let e=this.getPos();if(eGu)throw new Error(`ArrayBuffer exceeded maximum size of ${Gu} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(r);else{let n=new ArrayBuffer(r),a=new Uint8Array(n);a.set(this._bytes,0),this._buffer=n,this._bytes=a}}}_start(){}_write(e,r){this._ensureSize(r+e.byteLength),this._bytes.set(e,r),this._maxPos=Math.max(this._maxPos,r+e.byteLength),this._dispatchWrite(r,r+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,r){return this._bytes.slice(e,r)}},Cg=2**24,Pg=2,Ia=class extends ze{constructor(e,r={}){super();this._sections=[];this._lastWriteEnd=0;this._lastFlushEnd=0;this._streamWriter=null;this._writeError=null;this._chunks=[];if(!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(r!=null&&typeof r!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(r.chunked!==void 0&&typeof r.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(r.chunkSize!==void 0&&(!Number.isInteger(r.chunkSize)||r.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=r,this._chunked=r.chunked??!1,this._chunkSize=r.chunkSize??Cg}_start(){this._streamWriter=this._writable.getWriter()}_write(e,r){if(r>this._lastWriteEnd){let n=r-this._lastWriteEnd;this._write(new Uint8Array(n),this._lastWriteEnd)}this._sections.push({data:e.slice(),start:r}),this._lastWriteEnd=Math.max(this._lastWriteEnd,r+e.byteLength),this._dispatchWrite(r,r+e.byteLength)}async _flush(){if(this._writeError!==null)throw this._writeError;if(g(this._streamWriter),this._sections.length===0)return;let e=[],r=[...this._sections].sort((n,a)=>n.start-a.start);e.push({start:r[0].start,size:r[0].data.byteLength});for(let n=1;n{this._writeError??=a}),this._lastFlushEnd=n.start+n.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,r){let n=this._chunks.findIndex(u=>u.start<=r&&rPg){for(let u=0;u=e.written[s+1].start;)e.written[s].end=Math.max(e.written[s].end,e.written[s+1].end),e.written.splice(s+1,1)}_createChunk(e){let n={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(n),this._chunks.sort((a,s)=>a.start-s.start),this._chunks.indexOf(n)}_tryToFlushChunks(e=!1){g(this._streamWriter);for(let r=0;r{this._writeError??=u}),this._lastFlushEnd=n.start+a.end}this._chunks.splice(r--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;g(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _close(){return this._streamWriter?.close()}},ju=class extends ze{constructor(e){super();this._writer=null;this._nextWritePos=0;this._writable=e,this._streamTarget=new Ia(new WritableStream({start:()=>{this._writer=this._writable.getWriter()},write:r=>{if(this._monotonicity!==!0)throw new Error("AppendOnlyStreamTarget requires that data be written monotonically (always appended to the end). You must use a format that guarantees this behavior.");return g(r.position===this._nextWritePos),this._nextWritePos+=r.data.byteLength,g(this._writer),this._writer.write(r.data)},close:()=>this._writer?.close()}))}_start(){this._streamTarget._start()}_write(e,r){this._streamTarget._write(e,r),this._dispatchWrite(r,r+e.byteLength)}_flush(){return this._streamTarget._flush()}_finalize(){return this._streamTarget._finalize()}_close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}},Xu=class extends ze{constructor(e,r={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!ff.fs)throw new Error("FilePathTarget is only available in server-side environments (Node.js, Bun, Deno).");super();this._fileHandle=null;let n=new WritableStream({start:async()=>{this._fileHandle=await ff.fs.open(e,"w")},write:async a=>{g(this._fileHandle),await this._fileHandle.write(a.data,0,a.data.byteLength,a.position)},close:async()=>{this._fileHandle&&(await this._fileHandle.close(),this._fileHandle=null)}});this._streamTarget=new Ia(n,{chunked:!0,...r})}_start(){this._streamTarget._start()}_write(e,r){this._streamTarget._write(e,r),this._dispatchWrite(r,r+e.byteLength)}async _flush(){return this._streamTarget._flush()}async _finalize(){await this._streamTarget._finalize(),this._emit("finalized")}async _close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}},Ni=class extends ze{_start(){}_write(t,e){this._dispatchWrite(e,e+t.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _close(){}},Lo=class extends ze{constructor(t,e){super(),this._baseTarget=t,this._offset=e}_start(){}_write(t,e){this._baseTarget._write(t,this._offset+e),this._dispatchWrite(e,e+t.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(t){super._setMonotonicity(t),this._baseTarget._setMonotonicity(t)}},pt=class{constructor(t,e){this.rootPath=t;this.getTarget=e;if(typeof t!="string")throw new TypeError("rootPath must be a string.");if(typeof e!="function")throw new TypeError("getTarget must be a function.")}};var at=57600,Ig=2082844800,df=i=>{let t={},e=i.track;return e.metadata.name!==void 0&&(t.name=e.metadata.name),t},de=(i,t,e=!0)=>{let r=i*t;return e?Math.round(r):r},Ui=i=>{if(i.samples.length===0)return 0;let t=1/0,e=-1/0;for(let r=0;re&&(e=n.timestamp+n.duration)}return t===1/0?0:e-t},Wo=class extends Pe{constructor(e,r){super(e);this.writer=null;this.boxWriter=null;this.initWriter=null;this.initBoxWriter=null;this.auxTarget=new zi;this.auxWriter=new lr(this.auxTarget,!1);this.auxBoxWriter=new Vi(this.auxWriter);this.mdat=null;this.ftypSize=null;this.trackDatas=[];this.allTracksKnown=J();this.creationTime=Math.floor(Date.now()/1e3)+Ig;this.finalizedChunks=[];this.wroteFragmentedHeader=!1;this.nextFragmentNumber=1;this.maxWrittenTimestamp=-1/0;this.minWrittenTimestamp=1/0;this.maxWrittenEndTimestamp=-1/0;this.segmentHeaderSize=null;this.format=r,this.formatOptions={...r._options},this.isQuickTime=r instanceof Rn,this.isCmaf=r instanceof _n,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(r instanceof _n?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(n=>this.formatOptions.fastStart!==void 0?this.formatOptions.fastStart==="fragmented":n instanceof zi),this.boxWriter=new Vi(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof zi?"in-memory":!1),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");let n=await this.output._getInitTarget(),a=new lr(n,!0);a.start(),this.initWriter=a,this.initBoxWriter=new Vi(a)}let r=this.output.tracks.some(n=>n.isVideoTrack()&&n.source._codec==="avc");{let n=this.initBoxWriter??this.boxWriter;if(g(n),this.formatOptions.onFtyp&&n.writer.startTrackingWrites(),n.writeBox(ef({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:a,start:s}=n.writer.stopTrackingWrites();this.formatOptions.onFtyp(a,s)}this.ftypSize=n.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(let n of this.output.tracks)if(n.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(g(this.writer),g(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Pa(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush();for(let n of this.output.tracks)n.isVideoTrack()&&n.metadata.decoderConfig?this.getVideoTrackData(n,n.metadata.primingPacket??null,{decoderConfig:n.metadata.decoderConfig}):n.isAudioTrack()&&n.metadata.decoderConfig&&this.getAudioTrackData(n,n.metadata.primingPacket??null,{decoderConfig:n.metadata.decoderConfig});e()}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Ts({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,n){let a=this.trackDatas.find(p=>p.track===e);if(a)return a;tr(n,e.source._codec),g(n),g(n.decoderConfig);let s={...n.decoderConfig};g(s.codedWidth!==void 0),g(s.codedHeight!==void 0);let o=!1;if(e.source._codec==="avc"&&!s.description){if(!r)throw new Error("No AVC description provided; you must therefore provide a priming packet.");let p=Zt(r.data);if(!p)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=es(p),o=!0}else if(e.source._codec==="hevc"&&!s.description){if(!r)throw new Error("No HEVC description provided; you must therefore provide a priming packet.");let p=er(r.data);if(!p)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=rd(p),o=!0}let c=Vl(1/(e.metadata.frameRate??at),1e6).den,u=s.displayAspectWidth,l=s.displayAspectHeight,d=u===void 0||l===void 0?{num:1,den:1}:Gt({num:u*s.codedHeight,den:l*s.codedWidth}),m=s.codec==="ap4h"||s.codec==="ap4x",f={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:d,decoderConfig:s,requiresAnnexBTransformation:o,hasAlphaChannel:m},timescale:c,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(f),this.trackDatas.sort((p,b)=>p.track.id-b.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),f}getAudioTrackData(e,r,n){let a=this.trackDatas.find(u=>u.track===e);if(a)return a;Se(n,e.source._codec),g(n),g(n.decoderConfig);let s={...n.decoderConfig},o=!1;if(e.source._codec==="aac"&&!s.description){if(!r)throw new Error("No AAC description provided; you must therefore provide a priming packet.");let u=et(xe.tempFromBytes(r.data));if(!u)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let l=kt[u.samplingFrequencyIndex],d=Xt[u.channelConfiguration];if(l===void 0||d===void 0)throw new Error("Invalid ADTS frame header.");s.description=$i({objectType:u.objectType,outputSampleRate:l,outputNumberOfChannels:d}),o=!0}if(!r){if(e.source._codec==="ac3"||e.source._codec==="eac3")throw new Error("AC-3/E-AC-3 require a priming packet.");if(e.source._codec==="dts")throw new Error("DTS requires a priming packet.")}let c={muxer:this,track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&ae.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:r},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(c),this.trackDatas.sort((u,l)=>u.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;gs(r),g(r),g(r.config);let a={muxer:this,track:e,type:"subtitle",info:{config:r.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(a),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,n),o=r.data;if(s.info.requiresAnnexBTransformation){let u=[...Lr(o)].map(l=>o.subarray(l.offset,l.offset+l.length));if(u.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");o=Ja(u,4)}this.validateTimestamp(s.track,r.timestamp,r.type==="key");let c=this.createSampleForTrack(s,o,r.timestamp,r.duration,r.type);await this.registerSample(s,c)}finally{a()}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,r,n),o=r.data;if(s.info.requiresAdtsStripping){let d=et(xe.tempFromBytes(o));if(!d)throw new Error("Expected ADTS frame, didn't get one.");let m=d.crcCheck===null?Er:mt;o=o.subarray(m)}this.validateTimestamp(s.track,r.timestamp,r.type==="key");let c=r.timestamp,u=r.duration;if(s.info.requiresPcmTransformation){let m=Re(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(u=o.byteLength/m/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){let f=c-s.info.expectedNextPcmPacketTimestamp;if(f<.01)c=s.info.expectedNextPcmPacketTimestamp;else{let p=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,f);c=s.info.expectedNextPcmPacketTimestamp+p}}s.info.expectedNextPcmPacketTimestamp=c+u}let l=this.createSampleForTrack(s,o,c,u,r.type);await this.registerSample(s,l)}finally{a()}}async padWithSilence(e,r,n){let a=de(n,e.timescale);if(n=a/e.timescale,a>0){let{sampleSize:s,silentValue:o}=Re(e.info.decoderConfig.codec),c=a*e.info.numberOfChannels,u=new Uint8Array(s*c).fill(o),l=this.createSampleForTrack(e,new Uint8Array(u.buffer),r,n,"key");await this.registerSample(e,l)}return n}async addSubtitleCue(e,r,n){let a=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,!0),e.source._codec==="webvtt"&&(s.cueQueue.push(r),await this.processWebVTTCues(s,r.timestamp))}finally{a()}}async processWebVTTCues(e,r){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].timestamp);let n=new Set([]);for(let l of e.cueQueue)g(l.timestamp<=r),g(e.lastCueEndTimestamp<=l.timestamp+l.duration),n.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),n.add(l.timestamp+l.duration);let a=[...n].sort((l,d)=>l-d),s=a[0],o=a[1]??s;if(r=o)break;En.lastIndex=0;let m=En.test(d.text),f=d.timestamp+d.duration,p=e.cueToSourceId.get(d);if(p===void 0&&oa.timestamp).sort((a,s)=>a-s);this.isFragmented?e.startTimestampOffset??=Math.min(n[0],0):e.startTimestampOffset??=n[0];for(let a=0;a=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let d=Z(e.timeToSampleTable);if(g(d),d.sampleCount===1){d.sampleDelta=l;let f=e.timeToSampleTable[e.timeToSampleTable.length-2];f&&f.sampleDelta===l&&(f.sampleCount++,e.timeToSampleTable.pop(),d=f)}else d.sampleDelta!==l&&(d.sampleCount--,e.timeToSampleTable.push(d={sampleCount:1,sampleDelta:l}));d.sampleDelta===c?d.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:c});let m=Z(e.compositionTimeOffsetTable);g(m),m.sampleCompositionTimeOffset===o?m.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else e.lastTimescaleUnits=de(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:c}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,g(e.lastSample),g(e.lastTimescaleUnits!==null),r!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){g(r.type==="key");let a=de(r.timestamp,e.timescale,!1),s=Math.round(a-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,r){r.type==="key"&&this.processTimestamps(e,r),e.timestampProcessingQueue.push(r),this.isFragmented?(e.sampleQueue.push(r),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,r):await this.addSampleToTrack(e,r)}async addSampleToTrack(e,r){if(!this.isFragmented&&(e.samples.push(r),this.fastStart==="reserve")){let a=e.track.metadata.maximumPacketCount;if(g(a!==void 0),e.samples.length>a)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${a}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,r.timestamp);let a=r.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let s=this.trackDatas.every(o=>{if(e===o)return r.type==="key";let c=o.sampleQueue[0];return c?c.type==="key":o.closed});a>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=a>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),g(e.currentChunk),e.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,r.timestamp+r.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(e){if(g(!this.isFragmented),g(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let r=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(r=e.currentChunk.samples.reduce((n,a)=>n+de(a.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||Z(e.compactlyCodedChunkTable).samplesPerChunk!==r)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let n of e.currentChunk.samples)g(n.data),this.writer.write(n.data),n.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(g(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let r=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.closed)break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestampp.currentChunk);if(r.length===0){e&&await this.writer.flush();return}let n=this.nextFragmentNumber++,a=Ku(n,r),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(a),c=o+Mt,u=1/0;for(let p=0;p=2**32;if(d)for(let p of r)p.currentChunk.offset+=wr-Mt;this.formatOptions.onMoof&&this.writer.startTrackingWrites();let m=Ku(n,r);if(this.boxWriter.writeBox(m),this.formatOptions.onMoof){let{data:p,start:b}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(p,b,u)}g(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let f=Pa(d);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(o+(d?wr:Mt));for(let p of r)for(let b of p.currentChunk.samples)this.writer.write(b.data),b.data=null;if(this.formatOptions.onMdat){let{data:p,start:b}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(p,b)}for(let p of r)p.finalizedChunks.push(p.currentChunk),this.finalizedChunks.push(p.currentChunk),p.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,r){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,r)):e.sampleQueue.push(r)}async createFastStartReserveMdat(){g(this.writer),g(this.boxWriter),this.ensureOneEnabledTrack();let e=vn(this),n=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;g(this.ftypSize!==null),this.writer.seek(this.ftypSize+n),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Pa(!0),this.boxWriter.writeBox(this.mdat);for(let a of this.trackDatas){for(let s of a.sampleQueue)await this.addSampleToTrack(a,s);a.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){g(this.fastStart==="reserve");let e=0;for(let r of this.trackDatas){let n=r.track.metadata.maximumPacketCount;g(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0,n.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),r()}ensureOneEnabledTrack(){for(let e of["video","audio","subtitle"]){let r=this.trackDatas.filter(a=>a.type===e);if(r.length===0)continue;if(!r.some(a=>a.track.metadata.disposition?.default!==!1)){let a=r[0];a.track.metadata.disposition={...a.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){g(this.isFragmented);let e=await this.mutex.acquire();try{for(let r of this.trackDatas)r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart==="reserve"&&await this.createFastStartReserveMdat();for(let r of this.trackDatas)r.closed=!0,r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let r of this.trackDatas){await this.finalizeCurrentChunk(r);let n=Ui(r);if(n>0){let c=0;for(let u of r.samples)c+=u.size;r.avgBitrate=Math.round(8*c/n)}else r.avgBitrate=0;let a=0,s=0,o=0;for(let c=0;c=1;)s-=r.samples[a].size,a++;o=Math.max(o,s)}if(r.maxBitrate=8*o,r.startTimestampOffset!==null)for(let c=0;c=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let n=vn(this);if(this.boxWriter.writeBox(n),this.formatOptions.onMoov){let{data:a,start:s}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(a,s)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,this.boxWriter.writeBox(this.mdat);for(let a of this.finalizedChunks)for(let s of a.samples)g(s.data),this.writer.write(s.data),s.data=null;if(this.formatOptions.onMdat){let{data:a,start:s}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(a,s)}}else if(this.isFragmented)if(this.isCmaf){let r=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(Lu()),this.boxWriter.writeBox(Wu(this,r))}else{let r=this.writer.getPos(),n=nf(this.trackDatas);this.boxWriter.writeBox(n);let a=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(a)}else{g(this.mdat);let r=this.boxWriter.offsets.get(this.mdat);g(r!==void 0);let n=this.writer.getPos()-r;if(this.mdat.size=n,this.mdat.largeSize=n>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(s,o)}let a=vn(this);if(this.fastStart==="reserve"){g(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(a);let s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(tf(s))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(a);if(this.formatOptions.onMoov){let{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(s,o)}}e()}};var Eg=-(2**15),vg=2**15-1,pf=6,hf=5,_g={video:1,audio:2,subtitle:17},Ho=class extends Pe{constructor(e,r){super(e);this.trackDatas=[];this.allTracksKnown=J();this.segment=null;this.segmentInfo=null;this.seekHead=null;this.tracksElement=null;this.tagsElement=null;this.attachmentsElement=null;this.segmentDuration=null;this.cues=null;this.currentCluster=null;this.currentClusterStartMsTimestamp=null;this.currentClusterMaxMsTimestamp=null;this.trackDatasInCurrentCluster=new Map;this.startTimestamp=1/0;this.endTimestamp=-1/0;this.warnedAboutTooNegativeTimestamp=!1;this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new _s(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush();for(let r of this.output.tracks)r.isVideoTrack()&&r.metadata.decoderConfig?this.getVideoTrackData(r,r.metadata.primingPacket??null,{decoderConfig:r.metadata.decoderConfig}):r.isAudioTrack()&&r.metadata.decoderConfig&&this.getAudioTrackData(r,r.metadata.primingPacket??null,{decoderConfig:r.metadata.decoderConfig});e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();let e={id:440786851,data:[{id:17030,data:1},{id:17143,data:1},{id:17138,data:4},{id:17139,data:8},{id:17026,data:this.format instanceof Li?"webm":"matroska"},{id:17031,data:4},{id:17029,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){let{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(r,n)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;let r=new Uint8Array([28,83,187,107]),n=new Uint8Array([21,73,169,102]),a=new Uint8Array([22,84,174,107]),s=new Uint8Array([25,65,164,105]),o=new Uint8Array([18,84,195,103]),c={id:290298740,data:[{id:19899,data:[{id:21419,data:n},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:19899,data:[{id:21419,data:a},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:19899,data:[{id:21419,data:s},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:19899,data:[{id:21419,data:o},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null,{id:19899,data:[{id:21419,data:r},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]}]};this.seekHead=c}createSegmentInfo(){let e={id:17545,data:new sn(0)};this.segmentDuration=e;let r={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:yr},{id:22337,data:yr},this.format._options.appendOnly?null:e]};this.segmentInfo=r}createTracks(){let e={id:374648427,data:[]};this.tracksElement=e;for(let r of this.trackDatas){let n=Ve[r.track.source._codec];g(n),r.type==="audio"&&r.track.source._codec==="dts"&&(r.info.decoderConfig.codec==="dtse"?n="A_DTS/EXPRESS":r.info.decoderConfig.codec==="dtsl"&&(n="A_DTS/LOSSLESS"));let a=0;if(r.type==="audio"&&r.track.source._codec==="opus"){a=1e6*80;let s=r.info.decoderConfig.description;if(s){let o=$(s),c=Hr(o);a=Math.round(1e9*(c.preSkip/Ft))}}e.data.push({id:174,data:[{id:215,data:r.track.id},{id:29637,data:r.track.id},{id:131,data:_g[r.type]},r.track.metadata.disposition?.default===!1?{id:136,data:0}:null,r.track.metadata.disposition?.forced?{id:21930,data:1}:null,r.track.metadata.disposition?.hearingImpaired?{id:21931,data:1}:null,r.track.metadata.disposition?.visuallyImpaired?{id:21932,data:1}:null,r.track.metadata.disposition?.original?{id:21934,data:1}:null,r.track.metadata.disposition?.commentary?{id:21935,data:1}:null,{id:156,data:0},{id:2274716,data:r.track.metadata.languageCode??se},{id:134,data:n},r.codecPrivate?{id:25506,data:$(r.codecPrivate)}:null,a>0?{id:22203,data:a}:null,r.track.metadata.name!==void 0?{id:21358,data:new Vt(r.track.metadata.name)}:null,r.type==="video"?this.videoSpecificTrackInfo(r):null,r.type==="audio"?this.audioSpecificTrackInfo(r):null,r.type==="subtitle"?this.subtitleSpecificTrackInfo(r):null]})}}videoSpecificTrackInfo(e){let{frameRate:r,transformationMatrix:n}=e.track.metadata,a=[r?{id:2352003,data:1e9/r}:null],s,o,c;if(n){s=fi(n);let b=Lt(qi(-s),n);o=Math.sign(b[0]),c=Math.sign(b[4]),c===-1&&(c=1,o=-o,s=mr(s+180))}else s=e.track.metadata.rotation??0,o=e.track.metadata.flip?-1:1,c=1;let u=s?mr(o===-1?s:-s):0,l=Math.round(Math.acos(o)*Oa),d=Math.round(Math.acos(c)*Oa),m=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,f=e.info.decoderConfig.colorSpace,p={id:224,data:[{id:176,data:e.info.width},{id:186,data:e.info.height},m?{id:21680,data:e.info.aspectRatio.num}:null,m?{id:21690,data:e.info.aspectRatio.den}:null,m?{id:21682,data:3}:null,e.info.alphaMode?{id:21440,data:1}:null,za(f)?null:{id:21936,data:[{id:21937,data:f?.matrix!=null?Et[f.matrix]:2},{id:21946,data:f?.transfer!=null?It[f.transfer]:2},{id:21947,data:f?.primaries!=null?Pt[f.primaries]:2},{id:21945,data:f?.fullRange!=null?f.fullRange?2:1:0}]},u||l||d?{id:30320,data:[{id:30321,data:0},l?{id:30323,data:new Yr(l)}:null,d?{id:30324,data:new Yr(d)}:null,u?{id:30325,data:new Yr((u+180)%360-180)}:null]}:null]};return a.push(p),a}audioSpecificTrackInfo(e){let r=ae.includes(e.track.source._codec)?Re(e.track.source._codec):null;return[{id:225,data:[{id:181,data:new Yr(e.info.sampleRate)},{id:159,data:e.info.numberOfChannels},r?{id:25188,data:8*r.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[]}maybeCreateTags(){let e=[],r=(s,o)=>{e.push({id:26568,data:[{id:17827,data:new Vt(s)},typeof o=="string"?{id:17543,data:new Vt(o)}:{id:17541,data:o}]})},n=this.output._metadataTags,a=new Set;for(let{key:s,value:o}of vt(n))switch(s){case"title":r("TITLE",o),a.add("TITLE");break;case"description":r("DESCRIPTION",o),a.add("DESCRIPTION");break;case"artist":r("ARTIST",o),a.add("ARTIST");break;case"album":r("ALBUM",o),a.add("ALBUM");break;case"albumArtist":r("ALBUM_ARTIST",o),a.add("ALBUM_ARTIST");break;case"genre":r("GENRE",o),a.add("GENRE");break;case"beatsPerMinute":r("BPM",o.toString()),a.add("BPM");break;case"comment":r("COMMENT",o),a.add("COMMENT");break;case"lyrics":r("LYRICS",o),a.add("LYRICS");break;case"date":r("DATE",o.toISOString().slice(0,10)),a.add("DATE");break;case"trackNumber":{let c=n.tracksTotal!==void 0?`${o}/${n.tracksTotal}`:o.toString();r("PART_NUMBER",c),a.add("PART_NUMBER")}break;case"discNumber":{let c=n.discsTotal!==void 0?`${o}/${n.discsTotal}`:o.toString();r("DISC",c),a.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":break;default:ne(s)}if(n.raw)for(let s in n.raw){let o=n.raw[s];o==null||a.has(s)||(typeof o=="string"||o instanceof Uint8Array)&&r(s,o)}e.length!==0&&(this.tagsElement={id:307544935,data:[{id:29555,data:[{id:25536,data:[{id:26826,data:50},{id:25546,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){let e=this.output._metadataTags,r=[],n=new Set,a=e.images??[];for(let s of a){let o=s.name;o===void 0&&(o=(s.kind==="coverFront"?"cover":s.kind==="coverBack"?"back":"image")+(zl(s.mimeType)??""));let c;for(;;){c=0n;for(let u=0;u<8;u++)c<<=8n,c|=BigInt(Math.floor(Math.random()*256));if(c!==0n&&!n.has(c))break}n.add(c),r.push({id:24999,data:[s.description!==void 0?{id:18046,data:new Vt(s.description)}:null,{id:18030,data:new Vt(o)},{id:18016,data:s.mimeType},{id:18012,data:s.data},{id:18094,data:c}]})}for(let[s,o]of Object.entries(e.raw??{}))!(o instanceof Nr)||!/^\d+$/.test(s)||a.find(u=>u.mimeType===o.mimeType&&Ka(u.data,o.data))||r.push({id:24999,data:[o.description!==void 0?{id:18046,data:new Vt(o.description)}:null,{id:18030,data:new Vt(o.name??"")},{id:18016,data:o.mimeType??""},{id:18012,data:o.data},{id:18094,data:BigInt(s)}]});r.length!==0&&(this.attachmentsElement={id:423732329,data:r})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);let e={id:408125543,size:this.format._options.appendOnly?-1:pf,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){let{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(r,n)}}createCues(){this.cues={id:475249515,data:[]}}get segmentDataOffset(){return g(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Ms({isWebM:this.format instanceof Li,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,n){let a=this.trackDatas.find(l=>l.track===e);if(a)return a;tr(n,e.source._codec),g(n),g(n.decoderConfig),g(n.decoderConfig.codedWidth!==void 0),g(n.decoderConfig.codedHeight!==void 0);let s=n.decoderConfig.displayAspectWidth,o=n.decoderConfig.displayAspectHeight,c=s===void 0||o===void 0?null:Gt({num:s,den:o}),u={track:e,type:"video",info:{width:n.decoderConfig.codedWidth,height:n.decoderConfig.codedHeight,aspectRatio:c,decoderConfig:n.decoderConfig,alphaMode:e.metadata.canBeTransparent||(r?!!r.sideData.alpha:null)},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:n.decoderConfig.description??null,closed:!1};return e.source._codec==="vp9"?u.codecPrivate=new Uint8Array(yd(u.info.decoderConfig.codec)):e.source._codec==="av1"?u.codecPrivate=new Uint8Array(fs(u.info.decoderConfig.codec)):e.source._codec==="prores"&&(u.codecPrivate=Y.encode(n.decoderConfig.codec)),this.trackDatas.push(u),this.trackDatas.sort((l,d)=>l.track.id-d.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,r,n){let a=this.trackDatas.find(u=>u.track===e);if(a)return a;Se(n,e.source._codec),g(n),g(n.decoderConfig);let s={...n.decoderConfig},o=!1;if(e.source._codec==="aac"&&!s.description){if(!r)throw new Error("No AAC description provided; you must therefore provide a priming packet.");let u=et(xe.tempFromBytes(r.data));if(!u)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let l=kt[u.samplingFrequencyIndex],d=Xt[u.channelConfiguration];if(l===void 0||d===void 0)throw new Error("Invalid ADTS frame header.");s.description=$i({objectType:u.objectType,outputSampleRate:l,outputNumberOfChannels:d}),o=!0}let c={track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresAdtsStripping:o},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:s.description??null,closed:!1};return this.trackDatas.push(c),this.trackDatas.sort((u,l)=>u.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;gs(r),g(r),g(r.config);let a={track:e,type:"subtitle",info:{config:r.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:Y.encode(r.config.description),closed:!1};return this.trackDatas.push(a),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,n);s.info.alphaMode??=!!r.sideData.alpha;let o=r.data;if(e.source._codec==="prores"){if(o.byteLength<8)throw new Error("ProRes packet too small, expected at least 8 bytes.");o=o.subarray(8)}let c=r.type==="key";this.validateTimestamp(s.track,r.timestamp,c);let u=r.timestamp,l=r.duration;e.metadata.frameRate!==void 0&&(u=qt(u,e.metadata.frameRate),l=qt(l,e.metadata.frameRate));let d=s.info.alphaMode?r.sideData.alpha??null:null,m=this.createInternalChunk(o,u,l,r.type,d);e.source._codec==="vp9"&&this.fixVP9ColorSpace(s,m),s.chunkQueue.push(m),await this.interleaveChunks()}finally{a()}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,r,n),o=r.data;if(s.info.requiresAdtsStripping){let l=et(xe.tempFromBytes(o));if(!l)throw new Error("Expected ADTS frame, didn't get one.");let d=l.crcCheck===null?Er:mt;o=o.subarray(d)}let c=r.type==="key";this.validateTimestamp(s.track,r.timestamp,c);let u=this.createInternalChunk(o,r.timestamp,r.duration,r.type);s.chunkQueue.push(u),await this.interleaveChunks()}finally{a()}}async addSubtitleCue(e,r,n){let a=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,!0);let o=r.text,c=Math.round(r.timestamp*1e3);En.lastIndex=0,o=o.replace(En,m=>{let p=zo(m.slice(1,-1))-c;return`<${No(p)}>`});let u=Y.encode(o),l=`${r.settings??""} +${r.identifier??""} +${r.notes??""}`,d=this.createInternalChunk(u,r.timestamp,r.duration,"key",l.trim()?Y.encode(l):null);s.chunkQueue.push(d),await this.interleaveChunks()}finally{a()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){e:for(;;){let r=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.chunkQueue.length===0&&!s.closed)break e;s.chunkQueue.length>0&&s.chunkQueue[0].timestamp=2&&n.skipBits(1);let d={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];Il(r.data,n.pos,n.pos+3,d)}createInternalChunk(e,r,n,a,s=null){return{data:e,type:a,timestamp:r,duration:n,additions:s}}writeBlock(e,r){this.segment||this.createSegment();let n=Math.round(1e3*r.timestamp),a=this.trackDatas.every(m=>{if(e===m)return r.type==="key";let f=m.chunkQueue[0];return f?f.type==="key":m.closed}),s=!1;if(!this.currentCluster)s=!0;else{g(this.currentClusterStartMsTimestamp!==null),g(this.currentClusterMaxMsTimestamp!==null);let m=n-this.currentClusterStartMsTimestamp;s=a&&n>this.currentClusterMaxMsTimestamp&&m>=1e3*(this.format._options.minimumClusterDuration??1)||m>vg}s&&this.createNewCluster(n);let o=n-this.currentClusterStartMsTimestamp;if(o0?{id:155,data:l}:null]};this.ebmlWriter.writeEBML(m)}else{u.setUint8(3,+(r.type==="key")<<7);let m={id:163,data:[c,r.data]};this.ebmlWriter.writeEBML(m)}this.startTimestamp=Math.min(this.startTimestamp,n),this.endTimestamp=Math.max(this.endTimestamp,n+l),e.lastWrittenMsTimestamp=n,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:n}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,n)}createNewCluster(e){e=Math.max(0,e),this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:524531317,size:this.format._options.appendOnly?-1:hf,data:[{id:231,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(g(this.currentCluster),!this.format._options.appendOnly){let a=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),s=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(a,hf),this.writer.seek(s)}if(this.format._options.onCluster){g(this.currentClusterStartMsTimestamp!==null);let{data:a,start:s}=this.writer.stopTrackingWrites();this.format._options.onCluster(a,s,this.currentClusterStartMsTimestamp/1e3)}let e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,r=new Map;for(let[a,{firstMsTimestamp:s}]of this.trackDatasInCurrentCluster)r.has(s)||r.set(s,[]),r.get(s).push(a);let n=[...r.entries()].sort((a,s)=>a[0]-s[0]);for(let[a,s]of n)g(this.cues),this.cues.data.push({id:187,data:[{id:179,data:Math.max(0,a)},...s.map(o=>({id:183,data:[{id:247,data:o.track.id},{id:241,data:e}]}))]})}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),g(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let r=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(r,pf);let n=this.startTimestamp===1/0?0:this.endTimestamp;this.segmentDuration.data=new sn(n),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),g(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}};var qo=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer)}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(t){let e=this.writer.getPos(),r=255,n=224|t.mpegVersionId<<3|t.layer<<1,a;t.mpegVersionId&2?a=t.mpegVersionId&1?0:1:a=1;let s=0,o=155,c=-1,u=a*16*4+t.layer*16;for(let h=0;h<16;h++){let y=bs[u+h];if(ys(a,t.layer,1e3*y,t.sampleRate,s)>=o){c=h;break}}if(c===-1)throw new Error("No suitable bitrate found.");let l=c<<4|t.frequencyIndex<<2|s<<1,d=t.channel<<6|t.modeExtension<<4|t.copyright<<3|t.original<<2|t.emphasis;this.helper[0]=r,this.helper[1]=n,this.helper[2]=l,this.helper[3]=d,this.writer.write(this.helper.subarray(0,4));let m=Gr(t.mpegVersionId,t.channel);this.writer.seek(e+m),this.writeU32(Qr);let f=0;t.frameCount!==null&&(f|=1),t.fileSize!==null&&(f|=2),t.toc!==null&&(f|=4),this.writeU32(f),this.writeU32(t.frameCount??0),this.writeU32(t.fileSize??0),this.writer.write(t.toc??new Uint8Array(100));let p=bs[u+c],b=ys(a,t.layer,1e3*p,t.sampleRate,s);this.writer.write(new Uint8Array(e+b-this.writer.getPos()))}};var Ko=class extends Pe{constructor(e,r){super(e);this.xingFrameData=null;this.frameCount=0;this.framePositions=[];this.xingFramePos=null;this.format=r,this.writeXingHeader=r._options.xingHeader!==!1}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!this.writeXingHeader),this.mp3Writer=new qo(this.writer),br(this.output._metadataTags)||new oi(this.writer).writeId3V2Tag(this.output._metadataTags),e()}async getMimeType(){return"audio/mpeg"}async addEncodedVideoPacket(){throw new Error("MP3 does not support video.")}async addEncodedAudioPacket(e,r){let n=await this.mutex.acquire();try{if(!this.xingFrameData&&this.writeXingHeader){let a=N(r.data);if(a.byteLength<4)throw new Error("Invalid MP3 header in sample.");let s=a.getUint32(0,!1),o=jr(s,null).header;if(!o)throw new Error("Invalid MP3 header in sample.");let c=Gr(o.mpegVersionId,o.channel);if(a.byteLength>=c+4){let u=a.getUint32(c,!1);if(u===Qr||u===en)return}this.xingFrameData={mpegVersionId:o.mpegVersionId,layer:o.layer,frequencyIndex:o.frequencyIndex,sampleRate:o.sampleRate,channel:o.channel,modeExtension:o.modeExtension,copyright:o.copyright,original:o.original,emphasis:o.emphasis,frameCount:null,fileSize:null,toc:null},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}this.validateTimestamp(e,r.timestamp,r.type==="key"),this.writeXingHeader&&this.framePositions.push(this.writer.getPos()),this.writer.write(r.data),this.frameCount++,await this.writer.flush()}finally{n()}}async addSubtitleCue(){throw new Error("MP3 does not support subtitles.")}async finalize(){let e=await this.mutex.acquire();if(this.frameCount===0){if(!this.writeXingHeader)throw new Error("Cannot finalize an empty MP3 file: not a single packet was added and the Xing header is disabled, so there's no frame we could write.");let n=this.output.tracks[0];g(n?.isAudioTrack());let a=n.metadata.primingPacket;if(a){let s=N(a.data);if(s.byteLength<4)throw new Error("Invalid MP3 header in priming packet.");let o=s.getUint32(0,!1),c=jr(o,null).header;if(!c)throw new Error("Invalid MP3 header in priming packet.");this.xingFrameData={mpegVersionId:c.mpegVersionId,layer:c.layer,frequencyIndex:c.frequencyIndex,sampleRate:c.sampleRate,channel:c.channel,modeExtension:c.modeExtension,copyright:c.copyright,original:c.original,emphasis:c.emphasis,frameCount:null,fileSize:null,toc:null}}else if(n.metadata.decoderConfig){let{sampleRate:s,numberOfChannels:o}=n.metadata.decoderConfig,c=[3,2,0],u=null,l=-1;for(let d=0;d0){let s=new Uint8Array(100);for(let o=0;o<100;o++){let c=Math.floor(this.framePositions.length*(o/100)),u=this.framePositions[c]-this.xingFramePos;s[o]=256*(u/a)}this.xingFrameData.toc=s}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=a,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(s,o)}}e()}};var Rg=8192,Qo=class extends Pe{constructor(e,r){super(e);this.trackDatas=[];this.bosPagesWritten=!1;this.allTracksKnown=J();this.pageBytes=new Uint8Array(zs);this.pageView=new DataView(this.pageBytes.buffer);this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0);for(let r of this.output.tracks)g(r.isAudioTrack()),r.metadata.decoderConfig&&this.getTrackData(r,{decoderConfig:r.metadata.decoderConfig});e()}async getMimeType(){return await this.allTracksKnown.promise,Us({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(e,r){let n=this.trackDatas.find(o=>o.track===e);if(n)return n;let a;do a=Math.floor(2**32*Math.random());while(this.trackDatas.some(o=>o.serialNumber===a));g(e.source._codec==="vorbis"||e.source._codec==="opus"),Se(r,e.source._codec),g(r),g(r.decoderConfig);let s={track:e,serialNumber:a,internalSampleRate:e.source._codec==="opus"?Ft:r.decoderConfig.sampleRate,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],startTimestampInSamples:null,currentTimestampInSamples:0,audioPacketCount:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0,closed:!1};return this.queueHeaderPackets(s,r),this.trackDatas.push(s),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}queueHeaderPackets(e,r){if(g(r.decoderConfig),e.track.source._codec==="vorbis"){g(r.decoderConfig.description);let n=$(r.decoderConfig.description);if(n[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let a=1,s=()=>{let h=0;for(;;){let y=n[a++];if(y===void 0)throw new TypeError("Vorbis decoder description is too short.");if(h+=y,y<255)return h}},o=s(),c=s();if(n.length-a<=0)throw new TypeError("Vorbis decoder description is too short.");let l=n.subarray(a,a+=o);a+=c;let d=n.subarray(a),m=new Uint8Array(7);m[0]=3,m[1]=118,m[2]=111,m[3]=114,m[4]=98,m[5]=105,m[6]=115;let f=Qn(m,this.output._metadataTags,!0);e.packetQueue.push({data:l,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0},{data:f,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!1},{data:d,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0});let b=N(l).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(b&15),1<<(b>>4)],modeBlockflags:is(d).modeBlockflags}}else if(e.track.source._codec==="opus"){if(!r.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");let n=$(r.decoderConfig.description),a=new Uint8Array(8),s=N(a);s.setUint32(0,1332770163,!1),s.setUint32(4,1415669619,!1);let o=Qn(a,this.output._metadataTags,!0);e.packetQueue.push({data:n,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0},{data:o,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:Hr(n).preSkip}}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getTrackData(e,n);if(this.validateTimestamp(s.track,r.timestamp,r.type==="key"),s.startTimestampInSamples===null){let m=Math.round(r.timestamp*s.internalSampleRate),f=s.codecInfo.opusInfo?.preSkip??0;s.startTimestampInSamples=m>0?m+f:0,s.currentTimestampInSamples=s.startTimestampInSamples}let o=s.currentTimestampInSamples,{durationInSamples:c,vorbisBlockSize:u}=oa(r.data,s.codecInfo,s.vorbisLastBlocksize);s.currentTimestampInSamples+=c,s.vorbisLastBlocksize=u;let l=r.duration>0?ee(Math.round(r.duration*s.internalSampleRate),0,c):c,d=s.startTimestampInSamples>0&&s.audioPacketCount===1;s.audioPacketCount++,s.packetQueue.push({data:r.data,timestampInSamples:o,durationInSamples:c,trimmedDurationInSamples:l,forcePageFlush:d}),await this.interleavePages()}finally{a()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async interleavePages(e=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown()&&!e)return;for(let r of this.trackDatas)for(;r.packetQueue.length>0;){let n=r.packetQueue.shift();if(this.writePacket(r,n,!1),n.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let r=null,n=1/0;for(let o of this.trackDatas){if(!e&&o.packetQueue.length<=1&&!o.closed)break e;o.packetQueue.length>0&&o.packetQueue[0].timestampInSamples0&&a-e.currentPageStartTimestampInSamples>l&&this.writePage(e,!1)}let s=r.data.length,o=0,c=0;for(;;){e.currentLacingValues.length===0&&o>0&&(e.currentPageStartsWithFreshPacket=!1);let l=Math.min(255,s);e.currentLacingValues.push(l),e.currentPageSize++,c+=l;let d=s<255;if(e.currentLacingValues.length===255){let m=r.data.subarray(o,c);if(o=c,e.currentPageData.push(m),e.currentPageSize+=m.length,this.writePage(e,n&&d),d)return}if(d)break;s-=255}let u=r.data.subarray(o);e.currentPageData.push(u),e.currentPageSize+=u.length,e.currentGranulePosition=a,(e.currentPageSize>=Rg||r.forcePageFlush)&&this.writePage(e,n)}writePage(e,r){this.pageView.setUint32(0,sa,!0),this.pageView.setUint8(4,0);let n=0;e.currentPageStartsWithFreshPacket||(n|=1),e.pagesWritten===0&&(n|=2),r&&(n|=4),this.pageView.setUint8(5,n);let a=e.currentLacingValues.every(u=>u===255)?-1:e.currentGranulePosition;Bl(this.pageView,6,a,!0),this.pageView.setUint32(14,e.serialNumber,!0),this.pageView.setUint32(18,e.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,e.currentLacingValues.length),this.pageBytes.set(e.currentLacingValues,27);let s=27+e.currentLacingValues.length;for(let u of e.currentPageData)this.pageBytes.set(u,s),s+=u.length;let o=this.pageBytes.subarray(0,s),c=Vs(o);if(this.pageView.setUint32(22,c,!0),e.pagesWritten++,e.currentLacingValues.length=0,e.currentPageData.length=0,e.currentPageSize=27,e.currentPageStartsWithFreshPacket=!0,e.currentPageStartTimestampInSamples=e.currentGranulePosition,this.format._options.onPage&&this.writer.startTrackingWrites(),this.writer.write(o),this.format._options.onPage){let{data:u,start:l}=this.writer.stopTrackingWrites();this.format._options.onPage(u,l,e.track.source)}}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0;await this.interleavePages(!0);for(let r of this.trackDatas)r.currentLacingValues.length>0&&this.writePage(r,!0);e()}};var Fg=0,Tf=4096,gf=256,Mg=224,bf=192,yf=new Uint8Array([9,240]),kf=new Uint8Array([70,1]),Go=class extends Pe{constructor(e,r){super(e);this.trackDatas=[];this.tablesWritten=!1;this.continuityCounters=new Map;this.packetBuffer=new Uint8Array(188);this.packetView=N(this.packetBuffer);this.allTracksKnown=J();this.videoTrackIndex=0;this.audioTrackIndex=0;this.adaptationFieldBuffer=new Uint8Array(184);this.payloadBuffer=new Uint8Array(184);this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,Gs(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,r){let n=this.trackDatas.find(l=>l.track===e);if(n)return n;tr(r,e.source._codec),g(r?.decoderConfig);let a=e.source._codec;g(a==="avc"||a==="hevc");let s=a==="avc"?27:36,o=gf+this.trackDatas.length,c=Mg+this.videoTrackIndex++,u={track:e,pid:o,streamType:s,streamId:c,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(u),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,r){let n=this.trackDatas.find(l=>l.track===e);if(n)return n;Se(r,e.source._codec),g(r?.decoderConfig);let a=e.source._codec;g(a==="aac"||a==="mp3"||a==="ac3"||a==="eac3"||a==="dts");let s,o;switch(a){case"aac":s=15,o=bf+this.audioTrackIndex++;break;case"mp3":s=3,o=bf+this.audioTrackIndex++;break;case"ac3":s=129,o=189;break;case"eac3":s=135,o=189;break;case"dts":s=130,o=189;break}let c=gf+this.trackDatas.length,u={track:e,pid:c,streamType:s,streamId:o,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(u),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}async addEncodedVideoPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=this.prepareVideoPacket(s,r,n);r.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:o,presentationTimestamp:r.timestamp,decodeTimestamp:null,isKeyframe:r.type==="key"})}finally{a()}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=this.prepareAudioPacket(s,r,n);r.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:o,presentationTimestamp:r.timestamp,decodeTimestamp:null,isKeyframe:r.type==="key"})}finally{a()}}async addSubtitleCue(){throw new Error("MPEG-TS does not support subtitles.")}prepareVideoPacket(e,r,n){let a=e.track.source._codec;if(e.inputIsAnnexB===null){let s=n?.decoderConfig?.description;if(e.inputIsAnnexB=!s,!e.inputIsAnnexB){let o=$(s);a==="avc"?e.avcDecoderConfig=Wr(o):e.hevcDecoderConfig=Yi(o)}}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(r.data,a):this.prepareLengthPrefixedVideoPacket(e,r,a)}prepareAnnexBVideoPacket(e,r){let n=[];for(let s of Lr(e)){let o=e.subarray(s.offset,s.offset+s.length);(r==="avc"?Yt(o[0])===9:_t(o[0])===35)||n.push(o)}let a=r==="avc"?yf:kf;return n.unshift(a),qn(n)}prepareLengthPrefixedVideoPacket(e,r,n){let a=r.data,s=n==="avc"?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,o=[];for(let u of Ya(a,s)){let l=a.subarray(u.offset,u.offset+u.length);(n==="avc"?Yt(l[0])===9:_t(l[0])===35)||o.push(l)}if(r.type==="key")if(n==="avc"){let u=e.avcDecoderConfig;for(let l of u.pictureParameterSets)o.unshift(l);for(let l of u.sequenceParameterSets)o.unshift(l)}else{let u=e.hevcDecoderConfig;for(let l of u.arrays)if(l.nalUnitType===34)for(let d of l.nalUnits)o.unshift(d);for(let l of u.arrays)if(l.nalUnitType===33)for(let d of l.nalUnits)o.unshift(d);for(let l of u.arrays)if(l.nalUnitType===32)for(let d of l.nalUnits)o.unshift(d)}let c=n==="avc"?yf:kf;return o.unshift(c),qn(o)}prepareAudioPacket(e,r,n){let a=e.track.source._codec;if(a==="mp3"||a==="ac3"||a==="eac3"||a==="dts")return r.data;if(e.inputIsAdts===null){let u=n?.decoderConfig?.description;if(e.inputIsAdts=!u,!e.inputIsAdts){let l=$t($(u)),d=ja(l);e.adtsHeader=d.header,e.adtsHeaderBitstream=d.bitstream}}if(e.inputIsAdts)return r.data;g(e.adtsHeader),g(e.adtsHeaderBitstream);let s=e.adtsHeader,o=r.data.byteLength+s.byteLength;Xa(e.adtsHeaderBitstream,o);let c=new Uint8Array(o);return c.set(s,0),c.set(r.data,s.byteLength),c}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async flushTimestampQueue(e,r=!0){if(e.timestampProcessingQueue.length===0)return;let n=e.timestampProcessingQueue.map(a=>a.presentationTimestamp).sort((a,s)=>a-s);for(let a=0;a0&&s.packetQueue[0].presentationTimestamp0){let E=this.adaptationFieldBuffer;w===1?E[0]=0:(E[0]=w-1,E[1]=Number(k)<<7|Number(y)<<6,E.fill(255,2,w)),A=E.subarray(0,w)}let x=Math.min(184-w,h),C=this.payloadBuffer.subarray(0,x),P=0;if(f0,c=n?o?3:2:o?1:0;this.packetBuffer[0]=71,this.packetView.setUint16(1,(r?16384:0)|e&8191,!1),this.packetBuffer[3]=c<<4|s&15,o&&this.continuityCounters.set(e,s+1&15);let u=4;n&&(this.packetBuffer.set(n,u),u+=n.length),this.packetBuffer.set(a,u),u+=a.length,u<188&&this.packetBuffer.fill(255,u);let l=this.writer.getPos();this.writer.write(this.packetBuffer),this.format._options.onPacket&&this.format._options.onPacket(this.packetBuffer.slice(),l)}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0,await this.flushTimestampQueue(n,!1)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePackets(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0,await this.flushTimestampQueue(r,!1);await this.interleavePackets(!0),e()}},Bg=79764919,wf=new Uint32Array(256);for(let i=0;i<256;i++){let t=i<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^Bg:t<<1;wf[i]=t>>>0&4294967295}var Sf=i=>{let t=4294967295;for(let e=0;e>>24^r])>>>0}return t},Wi=new Uint8Array(16);{let i=N(Wi);Wi[0]=0,i.setUint16(1,45069,!1),i.setUint16(3,1,!1),Wi[5]=193,Wi[6]=0,Wi[7]=0,i.setUint16(8,1,!1),i.setUint16(10,57344|Tf&8191,!1),i.setUint32(12,Sf(Wi.subarray(0,12)),!1)}var Og=i=>{let t=0;for(let c of i)t+=5,c.streamType===129?t+=jn.length:c.streamType===135&&(t+=Xn.length);let e=9+t+4,r=new Uint8Array(3+e-4),n=N(r);r[0]=2,n.setUint16(1,45056|e&4095,!1),n.setUint16(3,1,!1),r[5]=193,r[6]=0,r[7]=0,n.setUint16(8,65535,!1),n.setUint16(10,61440,!1);let a=12;for(let c of i)r[a++]=c.streamType,n.setUint16(a,57344|c.pid&8191,!1),a+=2,c.streamType===129?(n.setUint16(a,61440|jn.length,!1),a+=2,r.set(jn,a),a+=jn.length):c.streamType===135?(n.setUint16(a,61440|Xn.length,!1),a+=2,r.set(Xn,a),a+=Xn.length):(n.setUint16(a,61440,!1),a+=2);let s=Sf(r),o=new Uint8Array(r.length+4);return o.set(r,0),N(o).setUint32(r.length,s,!1),o};var jo=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer)}writeU16(t){this.helperView.setUint16(0,t,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(t){this.helperView.setUint32(0,t,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,t,!0),this.helperView.setUint32(4,Math.floor(t/2**32),!0),this.writer.write(this.helper)}writeAscii(t){this.writer.write(Y.encode(t))}};var Xo=class extends Pe{constructor(e,r){super(e);this.headerWritten=!1;this.dataSize=0;this.sampleRate=null;this.sampleCount=0;this.riffSizePos=null;this.dataSizePos=null;this.ds64RiffSizePos=null;this.ds64DataSizePos=null;this.ds64SampleCountPos=null;this.format=r,this.isRf64=!!r._options.large}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!1),this.riffWriter=new jo(this.writer);let r=this.output.tracks[0];g(r?.isAudioTrack()),r.metadata.decoderConfig&&(Se({decoderConfig:r.metadata.decoderConfig},r.source._codec),this.writeHeader(r,r.metadata.decoderConfig),this.sampleRate=r.metadata.decoderConfig.sampleRate,this.headerWritten=!0),e()}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{if(this.headerWritten||(Se(n,e.source._codec),g(n),g(n.decoderConfig),this.writeHeader(e,n.decoderConfig),this.sampleRate=n.decoderConfig.sampleRate,this.headerWritten=!0),this.validateTimestamp(e,r.timestamp,r.type==="key"),!this.isRf64&&this.writer.getPos()+r.data.byteLength>=2**32)throw new Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(r.data),this.dataSize+=r.data.byteLength,this.sampleCount+=Math.round(r.duration*this.sampleRate),await this.writer.flush()}finally{a()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(e,r){this.format._options.onHeader&&this.writer.startTrackingWrites();let n,a=e.source._codec,s=Re(a);s.dataType==="ulaw"?n=7:s.dataType==="alaw"?n=6:s.dataType==="float"?n=3:n=1;let o=r.numberOfChannels,c=r.sampleRate,u=s.sampleSize*o;if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.ds64RiffSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64DataSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64SampleCountPos=this.writer.getPos(),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(16),this.riffWriter.writeU16(n),this.riffWriter.writeU16(o),this.riffWriter.writeU32(c),this.riffWriter.writeU32(c*u),this.riffWriter.writeU16(u),this.riffWriter.writeU16(8*s.sampleSize),!br(this.output._metadataTags)){let l=this.format._options.metadataFormat??"info";l==="info"?this.writeInfoChunk(this.output._metadataTags):l==="id3"?this.writeId3Chunk(this.output._metadataTags):ne(l)}if(this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.format._options.onHeader){let{data:l,start:d}=this.writer.stopTrackingWrites();this.format._options.onHeader(l,d)}}writeInfoChunk(e){let r=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");let n=new Set,a=(c,u)=>{if(!Ct(u)){z._warn(`Didn't write tag '${c}' because '${u}' is not ISO 8859-1-compatible.`);return}let l=u.length+1,d=new Uint8Array(l);for(let m=0;mr[n*t]:t===1&&e===4?this.channelMixer=(r,n,a)=>r[n*t]*+(a<2):t===1&&e===6?this.channelMixer=(r,n,a)=>r[n*t]*+(a===2):t===2&&e===1?this.channelMixer=(r,n)=>{let a=n*t;return .5*(r[a]+r[a+1])}:t===2&&e===4?this.channelMixer=(r,n,a)=>a<2?r[n*t+a]:0:t===2&&e===6?this.channelMixer=(r,n,a)=>a<2?r[n*t+a]:0:t===4&&e===1?this.channelMixer=(r,n)=>{let a=n*t;return .25*(r[a]+r[a+1]+r[a+2]+r[a+3])}:t===4&&e===2?this.channelMixer=(r,n,a)=>{let s=n*t;return .5*(r[s+a]+r[s+a+2])}:t===4&&e===6?this.channelMixer=(r,n,a)=>{let s=n*t;return a<2?r[s+a]:a===2||a===3?0:r[s+a-2]}:t===6&&e===1?this.channelMixer=(r,n)=>{let a=n*t;return Math.SQRT1_2*(r[a]+r[a+1])+r[a+2]+.5*(r[a+4]+r[a+5])}:t===6&&e===2?this.channelMixer=(r,n,a)=>{let s=n*t;return r[s+a]+Math.SQRT1_2*(r[s+2]+r[s+a+4])}:t===6&&e===4?this.channelMixer=(r,n,a)=>{let s=n*t;return a<2?r[s+a]+Math.SQRT1_2*r[s+2]:r[s+a+2]}:this.channelMixer=(r,n,a)=>a=this.bufferStartFrame+this.bufferCapacityInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let l=u-this.bufferStartFrame;g(l=0&&p=0&&b=this.bufferSizeInFrames?this.maxWrittenFrame-this.bufferSizeInFrames:null}async finalize(){for(;this.maxWrittenFrame!==null;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames}};var Fn=class{constructor(){this._connectedTrack=null;this._closingPromise=null;this._closed=!1;this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(t){}close(){if(this._closingPromise)return;let t=this._connectedTrack;if(!t)throw new Error("Cannot call close without connecting the source to an output track.");if(t.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(t.output.state==="finalizing"||t.output.state==="finalized")&&t.output._muxer.onTrackClose(t)})()}async _flushOrWaitForOngoingClose(t){return this._closingPromise??=(async()=>{await this._flushAndClose(t),this._closed=!0})()}},Fr=class extends Fn{constructor(t){if(super(),!le.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${le.join(", ")}.`);this._codec=t}},Ju=(i,t)=>{if(i.metadata.hasOnlyKeyPackets&&t.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},ui=class extends Fr{constructor(t){super(t)}add(t,e){if(!(t instanceof X))throw new TypeError("packet must be an EncodedPacket.");if(t.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(e!==void 0&&(!e||typeof e!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),Ju(this._connectedTrack,t),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,t,e)}},Ea=class{constructor(t,e){this.source=t;this.encodingConfig=e;this.ensureEncoderPromise=null;this.encoderInitialized=!1;this.encoder=null;this.encoderConfig=null;this.encodersReclaimed=!1;this.muxer=null;this.lastMultipleOfKeyFrameInterval=-1;this.emittedEncoderPackets=0;this.codedWidth=null;this.codedHeight=null;this.outputWidth=null;this.outputHeight=null;this.frameRateLastSample=null;this.frameRateLastTimestamp=null;this.frameRateLastEndTimestamp=null;this.preciseTimings=[];this.customEncoder=null;this.customEncoderCallSerializer=new Or;this.customEncoderQueueSize=0;this.defaultEncodeOptions={};this.alphaEncoder=null;this.splitter=null;this.splitterCreationFailed=!1;this.alphaFrameQueue=[];this.error=null;this.errorSet=!1;this.lastMuxerPromise=Promise.resolve();this.closed=!1}setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}async add(t,e,r){let n=t;try{this.checkForEncoderError(),this.source._ensureValidAdd();let a=this.encodingConfig,s=a.sizeChangeBehavior??"deny",o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((t.codedWidth!==this.codedWidth||t.codedHeight!==this.codedHeight)&&(o=!0,s==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${t.codedWidth}x${t.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight;if(a.transform?.width!==void 0||a.transform?.height!==void 0||a.transform?.rotate!==void 0||a.transform?.flip!==void 0||a.transform?.crop!==void 0||a.transform?.force===!0||o&&s!=="passThrough"){let d=a.transform?.width,m=a.transform?.height,f=a.transform?.fit??"fill";o&&s!=="passThrough"&&(g(this.outputWidth),g(this.outputHeight),g(s!=="deny"),d=this.outputWidth,m=this.outputHeight,f=s);let p=await t.transform({width:d,height:m,roundDimensionsTo:2,crop:a.transform?.crop,rotate:a.transform?.rotate,flip:a.transform?.flip,fit:f,alpha:a.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=p.displayWidth,this.outputHeight=p.displayHeight),e&&t.close(),t=p,e=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=t.codedWidth,this.outputHeight=t.codedHeight);let l=a.transform?.frameRate;if(l!==void 0){let d=t.timestamp+t.duration,m=hc(t.timestamp,l);if(this.frameRateLastSample!==null)if(m<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=t.clone(),this.frameRateLastEndTimestamp=d;return}else await this.padFrameRate(m,r);t===n&&(t=t.clone(),e=!0),t.setTimestamp(m),t.setDuration(1/l),this.frameRateLastSample?.close(),this.frameRateLastSample=t.clone(),this.frameRateLastTimestamp=m,this.frameRateLastEndTimestamp=d}await this.processAndEncode(t,r)}finally{e&&t.close()}}async processAndEncode(t,e){let r=this.encodingConfig,n;if(r.transform?.process){let a=r.transform.process(t);if(_(a)&&(a=await a),a===null)return;Array.isArray(a)||(a=[a]);let s=[];try{for(let o of a)o instanceof Xe?s.push(o):typeof VideoFrame<"u"&&o instanceof VideoFrame?s.push(new Xe(o)):s.push(new Xe(o,{timestamp:t.timestamp,duration:t.duration}))}catch(o){for(let c of s)c!==t&&c.close();for(let c of a)(c instanceof Xe&&c!==t||typeof VideoFrame<"u"&&c instanceof VideoFrame)&&c.close();throw o}n=s}else n=[t];try{for(let a of n){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(a),this.encoderInitialized||await this.ensureEncoderPromise),g(this.encoderInitialized),this.closed)break;this.encodersReclaimed&&this.recreateWebCodecsEncoders();let s=this.encodingConfig.keyFrameInterval??2,o=Math.floor(a.timestamp/s),c={...this.defaultEncodeOptions,...a.encodeOptions,...e},u={...c,keyFrame:c.keyFrame!==void 0?c.keyFrame:s===0||o!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=o,this.encodingConfig.onEncodedSample?.(a),this.customEncoder){this.customEncoderQueueSize++;let l=a.clone(),d=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(l,u)).catch(m=>this.setError(m)).finally(()=>{this.customEncoderQueueSize--,l.close()});this.customEncoderQueueSize>=4&&await d}else{g(this.encoder);let l=a.toVideoFrame(),d=Q(this.preciseTimings,l.timestamp,f=>f.microsecondTimestamp),m=d!==-1?this.preciseTimings[d]:null;if(m&&m.microsecondTimestamp===l.timestamp?(m.timestamp!==a.timestamp&&(m.timestampIsValid=!1),m.duration!==a.duration&&(m.durationIsValid=!1)):(this.preciseTimings.splice(d+1,0,{microsecondTimestamp:l.timestamp,timestamp:a.timestamp,duration:a.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(!!l.format&&!l.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(l,u)}finally{l.close()}}else{this.splitter||(this.splitter=new el);let{colorFrame:p,alphaFrame:b}=await this.splitter.split(l);this.alphaFrameQueue.push(b);try{this.encoder.encode(p,u)}finally{p.close()}}else try{this.encoder.encode(l,u)}finally{l.close()}this.encoder.encodeQueueSize>=4&&await new Promise(f=>this.encoder.addEventListener("dequeue",f,{once:!0}))}await this.lastMuxerPromise}}finally{for(let a of n)a!==t&&a.close()}}async padFrameRate(t,e){let r=this.encodingConfig.transform.frameRate;g(this.frameRateLastSample);let n=Math.round((t-this.frameRateLastTimestamp)*r);for(let u=1;u{let e=ai(this.encodingConfig.quality,this.encodingConfig.bitrate);g(e!==void 0);let r=Au({...this.encodingConfig,quality:e,width:t.codedWidth,height:t.codedHeight,squarePixelWidth:t.squarePixelWidth,squarePixelHeight:t.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate}),n=null,a;for(let o of r){let c=o.config;if(this.encodingConfig.onEncoderConfig?.(c),a=Sn.find(l=>l.supports(this.encodingConfig.codec,c)),a){n=o;break}if(typeof VideoEncoder>"u")continue;if(c.alpha="discard",this.encodingConfig.alpha==="keep"&&(c.latencyMode="quality"),(c.width%2===1||c.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${c.width}x${c.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);try{if((await VideoEncoder.isConfigSupported(c)).supported){n=o;break}}catch{}}if(!n){if(typeof VideoEncoder>"u")throw new Error(Gi("VideoEncoder"));let o=r[0].config,c=r.map(({config:u,quantizer:l})=>l!==null?`quantizer ${l}`:`${u.bitrate} bps`);throw new Error(`This specific encoder configuration (${o.codec}, ${c.join(" / ")}, ${o.width}x${o.height}, hardware acceleration: ${o.hardwareAcceleration??"no-preference"}) is not supported in this environment. Consider using another codec or changing your video parameters.`)}let s=n.config;n.quantizer!==null?this.defaultEncodeOptions=Cu(this.encodingConfig.codec,n.quantizer):this.source._nominalBitrate=s.bitrate??null,a?(this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=s,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof X))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");Ju(this.source._connectedTrack,o),this.encodingConfig.onEncodedPacket?.(o,c),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,o,c).catch(u=>{this.setError(u)})},this.customEncoder.onError=o=>{this.setError(o)},await this.customEncoder.init()):(this.encoderConfig=s,this.createWebCodecsEncoders()),g(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}createWebCodecsEncoders(){let t=this.encoderConfig;g(t);let e=[],r=[],n=0,a=0,s=(c,u)=>{if(Ul(c)){this.encodersReclaimed=!0;return}c.stack=u,this.setError(c)},o=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(c,u)=>{if(!this.alphaEncoder){this.addPacket(c,null,u);return}let l=this.alphaFrameQueue.shift();g(l!==void 0),l?(this.alphaEncoder.encode(l,{...this.defaultEncodeOptions,keyFrame:c.type==="key"}),a++,l.close(),e.push({chunk:c,meta:u})):a===0?this.addPacket(c,null,u):(r.push(n+a),e.push({chunk:c,meta:u}))},error:c=>s(c,o)}),this.encoder.configure(t),this.encodingConfig.alpha==="keep"){let c=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(u,l)=>{a--;let d=e.shift();for(g(d!==void 0),this.addPacket(d.chunk,u,d.meta),n++;r.length>0&&r[0]===n;){r.shift();let m=e.shift();g(m!==void 0),this.addPacket(m.chunk,null,m.meta)}},error:u=>s(u,c)}),this.alphaEncoder.configure(t)}}addPacket(t,e,r){let n={};if(e){let l=new Uint8Array(e.byteLength);e.copyTo(l),n.alpha=l}let a=X.fromEncodedChunk(t,n),s=this.encoderConfig;g(s),r?.decoderConfig&&(r.decoderConfig.codec=Kr({width:s.width,height:s.height,codec:this.encodingConfig.codec,codecDescription:r.decoderConfig.description?$(r.decoderConfig.description):null,colorSpace:r.decoderConfig.colorSpace??null,avcType:s.codec.includes("avc1.")?1:s.codec.includes("avc3.")?3:null,avcCodecInfo:this.encodingConfig.codec==="avc"&&!r.decoderConfig.description?Zt(a.data):null,hevcCodecInfo:this.encodingConfig.codec==="hevc"&&!r.decoderConfig.description?er(a.data):null,vp9CodecInfo:this.encodingConfig.codec==="vp9"?Zi(a.data):null,av1CodecInfo:this.encodingConfig.codec==="av1"?Ci(a.data):null,proresFormat:null}));let o=Q(this.preciseTimings,t.timestamp,l=>l.microsecondTimestamp),c=o!==-1?this.preciseTimings[o]:null,u=null;this.emittedEncoderPackets===0&&a.type==="delta"&&r?.decoderConfig&&(u=qr(this.encodingConfig.codec,r.decoderConfig,a.data)),(c&&c.microsecondTimestamp===t.timestamp||u!==null)&&(a=a.clone({timestamp:c?.timestampIsValid?c.timestamp:void 0,duration:c?.durationIsValid?c.duration:void 0,type:u??void 0})),Ju(this.source._connectedTrack,a),this.encodingConfig.onEncodedPacket?.(a,r),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,a,r).catch(l=>{this.setError(l)}),this.emittedEncoderPackets++}recreateWebCodecsEncoders(){g(this.encoder),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.alphaFrameQueue.length=0,this.encodersReclaimed=!1,this.lastMultipleOfKeyFrameInterval=-1,this.createWebCodecsEncoders()}async flushAndClose(t){try{if(!t&&(this.checkForEncoderError(),this.frameRateLastSample)){let e=this.encodingConfig.transform.frameRate,r=hc(this.frameRateLastEndTimestamp,e);await this.padFrameRate(r)}this.closed=!0,t||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&!this.encodersReclaimed&&(await this.encoder.flush(),await this.alphaEncoder?.flush(),await zr(25)))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&(this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.alphaFrameQueue.length=0,this.splitter?.close())}t||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},$u=null,el=class{constructor(){this.worker=null;this.pendingRequests=new Map;this.nextRequestId=0}split(t){if(!this.worker){if(!$u){let n=new Blob([`(${Dg.toString()})()`],{type:"application/javascript"});$u=URL.createObjectURL(n)}this.worker=new Worker($u),this.worker.addEventListener("message",n=>{let a=n.data,s=this.pendingRequests.get(a.id);s&&(this.pendingRequests.delete(a.id),"error"in a?s.reject(new Error(a.error)):s.resolve({colorFrame:a.colorFrame,alphaFrame:a.alphaFrame}))}),this.worker.addEventListener("error",n=>{let a=new Error(n.message||"Color/alpha splitter worker error.");for(let s of this.pendingRequests.values())s.reject(a);this.pendingRequests.clear()})}let e=this.nextRequestId++,r=J();return this.pendingRequests.set(e,r),this.worker.postMessage({id:e,sourceFrame:t},{transfer:[t]}),r.promise}close(){this.worker?.terminate(),this.worker=null;let t=new Error("Color/alpha splitter closed.");for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},Dg=()=>{let i=null,t=Promise.resolve();self.addEventListener("message",a=>{let{id:s,sourceFrame:o}=a.data;t=t.then(async()=>{try{let{colorFrame:c,alphaFrame:u}=await e(o);self.postMessage({id:s,colorFrame:c,alphaFrame:u},{transfer:[c,u]})}catch(c){self.postMessage({id:s,error:c.message})}finally{o.close()}})});let e=async a=>{let s=a.format;if(!s)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");let o=a.allocationSize();if((!i||i.byteLength!==o)&&(i=new Uint8Array(o)),await a.copyTo(i),s==="RGBA"||s==="BGRA")return r(i,s,a);if(s==="I420A"||s==="I420AP10"||s==="I420AP12"||s==="I422A"||s==="I422AP10"||s==="I422AP12"||s==="I444A"||s==="I444AP10"||s==="I444AP12")return n(i,s,a);throw new Error(`CPU color/alpha splitting does not support format '${s}'.`)},r=(a,s,o)=>{let c=o.visibleRect?.width??o.codedWidth,u=o.visibleRect?.height??o.codedHeight,l=c*u,d=Math.ceil(c/2),m=Math.ceil(u/2),f=l+d*m*2,p=new Uint8Array(f);for(let k=0,T=3;k{let c=o.visibleRect?.width??o.codedWidth,u=o.visibleRect?.height??o.codedHeight,l=s.includes("P10"),d=s.includes("P12"),m=l||d?2:1,f,p;s.startsWith("I420")?(f=Math.ceil(c/2),p=Math.ceil(u/2)):s.startsWith("I422")?(f=Math.ceil(c/2),p=u):(f=c,p=u);let b=c*u,h=f*p,y=b*m,k=h*m,T=b*m,w=y+k*2,A=s.replace("A",""),x=Math.ceil(c/2),C=Math.ceil(u/2),P=x*C,S=P*m,I=T+2*S,E=new Uint8Array(I),v=w;E.set(a.subarray(v,v+T),0);let F=T,O=l?512:d?2048:128;m===1?E.fill(O,F):new Uint16Array(E.buffer,F,2*P).fill(O);let D=l?"I420P10":d?"I420P12":"I420",U=new VideoFrame(a.subarray(0,w),{format:A,codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0}),K={format:D,codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[E.buffer]},ie=new VideoFrame(E,K);return{colorFrame:U,alphaFrame:ie}}},Mn=class extends Fr{constructor(t){Co(t),super(t.codec),this._encoder=new Ea(this,t)}add(t,e){if(!(t instanceof Xe))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(t,!1,e)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},tl=class extends Fr{constructor(t,e){if(!(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");Co(e),super(e.codec),this._encoder=new Ea(this,e),this._canvas=t}add(t,e=0,r){if(!Number.isFinite(t))throw new TypeError("timestamp must be a finite number.");if(!Number.isFinite(e)||e<0)throw new TypeError("duration must be a non-negative number.");let n=new Xe(this._canvas,{timestamp:t,duration:e});return this._encoder.add(n,!0,r)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},rl=class extends Fr{constructor(e,r,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");if(Co(r),typeof n!="object"||!n)throw new TypeError("options must be an object.");if(n.frameRate!=null&&(typeof n.frameRate!="number"||n.frameRate<=0))throw new TypeError("options.frameRate, when provided, must be either a positive number or null.");if(n.timestampBase!==void 0&&n.timestampBase!=="synced-zero"&&n.timestampBase!=="zero"&&n.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");r={...r,latencyMode:"realtime"};super(r.codec);this._abortController=null;this._workerTrackId=null;this._workerListener=null;this._promiseWithResolvers=J();this._errorPromiseAccessed=!1;this._paused=!1;this._lastVideoFrame=null;this._timerHandle=null;this._videoElement=null;this._options=n,this._encoder=new Ea(this,r),this._track=e}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}async _start(){this._errorPromiseAccessed||z._warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");let e=this._options.frameRate!==void 0?this._options.frameRate:this._track.getSettings().frameRate??null;this._abortController=new AbortController;let r=null,n=null,a=0,s=!1,o=null,c=0,u=()=>{if(g(e!==null),!this._lastVideoFrame)return;g(n!==null),g(r!==null);let m=performance.now();for(;m-n>1e3/e;){n+=1e3/e;let f=r+a/e,p=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*f,duration:1e6/e});d(p,m)}};e!==null&&(this._timerHandle=Kl(u,4));let l=m=>{if(e===null)d(m);else{let f=performance.now();this._lastVideoFrame?(u(),this._lastVideoFrame?.close(),this._lastVideoFrame=m):(d(m.clone(),f),n=f,this._lastVideoFrame=m)}},d=(m,f=performance.now())=>{if(s){m.close();return}a++;let p=m.timestamp/1e6;if(this._paused){if(r!==null){if(o!==null&&this._options.timestampBase!=="unix"){let y=p-o;c-=y}o=p}m.close();return}if(r===null){r=p;let h,y=this._options.timestampBase??"synced-zero";if(y==="unix")h=Date.now()/1e3;else if(y==="zero")h=0;else{let k=this._connectedTrack.output;k._firstMediaStreamTimestamp===null?(k._firstMediaStreamTimestamp=f/1e3,h=0):h=f/1e3-k._firstMediaStreamTimestamp}c=h-r}if(o=p,this._encoder.getQueueSize()>=8){m.close();return}let b=new Xe(m,{timestamp:p+c});this._encoder.add(b,!0).catch(h=>{s=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(h),this._workerTrackId!==null&&Zu({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){let m=new MediaStreamTrackProcessor({track:this._track}),f=new WritableStream({write:l});m.readable.pipeTo(f,{signal:this._abortController.signal}).catch(p=>{p instanceof DOMException&&p.name==="AbortError"||this._promiseWithResolvers.reject(p)})}else if(await Ng())this._workerTrackId=Ug++,Zu({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=f=>{let p=f.data;p.type==="videoFrame"&&p.trackId===this._workerTrackId?l(p.videoFrame):p.type==="error"&&p.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(p.error)},xt.addEventListener("message",this._workerListener);else if(e!==null){let f=document.createElement("video");f.style.position="fixed",f.style.left="-10000px",f.style.top="-10000px",f.style.width="1px",f.style.height="1px",f.style.opacity="0",f.style.pointerEvents="none",f.muted=!0,f.srcObject=new MediaStream([this._track]),document.body.appendChild(f),this._videoElement=f,f.addEventListener("loadeddata",()=>{if(s||!this._videoElement)return;let p=new VideoFrame(f,{timestamp:1e3*performance.now()});l(p),p.close()},{once:!0}),f.play().catch(p=>{s=!0,this._promiseWithResolvers.reject(p)})}else throw new Error("When no explicit frame rate is set, MediaStreamTrackProcessor is required; but it's not available in this environment.")}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&(this._abortController.abort(),this._abortController=null),this._timerHandle&&Ql(this._timerHandle),this._lastVideoFrame?.close(),this._videoElement&&(this._videoElement.srcObject=null,this._videoElement.remove(),this._videoElement=null),this._workerTrackId!==null&&(g(this._workerListener),Zu({type:"stopTrack",trackId:this._workerTrackId}),await new Promise(r=>{let n=a=>{let s=a.data;s.type==="trackStopped"&&s.trackId===this._workerTrackId&&(g(this._workerListener),xt.removeEventListener("message",this._workerListener),xt.removeEventListener("message",n),r())};xt.addEventListener("message",n)}))}finally{await this._encoder.flushAndClose(e)}}},Mr=class extends Fn{constructor(t){if(super(),!fe.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${fe.join(", ")}.`);this._codec=t}},li=class extends Mr{constructor(t){super(t)}add(t,e){if(!(t instanceof X))throw new TypeError("packet must be an EncodedPacket.");if(t.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(e!==void 0&&(!e||typeof e!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,t,e)}},va=class{constructor(t,e){this.source=t;this.encodingConfig=e;this.ensureEncoderPromise=null;this.encoderInitialized=!1;this.encoder=null;this.muxer=null;this.lastNumberOfChannels=null;this.lastSampleRate=null;this.isPcmEncoder=!1;this.outputSampleSize=null;this.writeOutputValue=null;this.customEncoder=null;this.customEncoderCallSerializer=new Or;this.customEncoderQueueSize=0;this.lastEndSampleIndex=null;this.resampler=null;this.error=null;this.errorSet=!1;this.lastMuxerPromise=Promise.resolve();this.closed=!1}setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}async add(t,e){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(t.numberOfChannels!==this.lastNumberOfChannels||t.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${t.numberOfChannels} channels at ${t.sampleRate} Hz.`)}else this.lastNumberOfChannels=t.numberOfChannels,this.lastSampleRate=t.sampleRate;let r=this.encodingConfig;r.transform?.numberOfChannels!==void 0||r.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new $o({targetNumberOfChannels:r.transform.numberOfChannels??t.numberOfChannels,targetSampleRate:r.transform.sampleRate??t.sampleRate,onSample:async a=>{await this.processAndEncode(a,!0)}})),await this.resampler.add(t)):await this.processAndEncode(t,e)}finally{e&&t.close()}}async processAndEncode(t,e){let r=this.encodingConfig;if(r.transform?.sampleFormat!==void 0&&Fm(t.format)!==r.transform.sampleFormat){let n=Mm(t,r.transform.sampleFormat);e&&t.close(),t=n,e=!0}if(r.transform?.process)try{let n=r.transform.process(t);if(_(n)&&(n=await n),n===null)return;Array.isArray(n)||(n=[n]);try{for(let a of n)if(!(a instanceof Ce))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");for(let a of n)await this.encodeSample(a,!0)}finally{for(let a of n)a instanceof Ce&&a.close()}}finally{e&&t.close()}else await this.encodeSample(t,e)}async encodeSample(t,e){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(t),this.encoderInitialized||await this.ensureEncoderPromise),g(this.encoderInitialized),this.closed)return;{let r=Math.round(t.timestamp*t.sampleRate),n=Math.round((t.timestamp+t.duration)*t.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let a=r-this.lastEndSampleIndex;if(a>=64){let s=new Ce({data:new Float32Array(a*t.numberOfChannels),format:"f32-planar",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,numberOfFrames:a,timestamp:this.lastEndSampleIndex/t.sampleRate});await this.encodeSample(s,!0)}this.lastEndSampleIndex+=t.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(t),this.customEncoder){this.customEncoderQueueSize++;let r=t.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(r)).catch(a=>this.setError(a)).finally(()=>{this.customEncoderQueueSize--,r.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(t,e);else{g(this.encoder);let r=t.toAudioData();this.encoder.encode(r),r.close(),e&&t.close(),this.encoder.encodeQueueSize>=4&&await new Promise(n=>this.encoder.addEventListener("dequeue",n,{once:!0})),await this.lastMuxerPromise}}finally{e&&t.close()}}async doPcmEncoding(t,e){g(this.outputSampleSize),g(this.writeOutputValue);let{numberOfChannels:r,numberOfFrames:n,sampleRate:a,timestamp:s}=t,o=2048,c=[];for(let b=0;b{let{numberOfChannels:e,sampleRate:r}=t,n=ai(this.encodingConfig.quality,this.encodingConfig.bitrate),a=xu({numberOfChannels:e,sampleRate:r,...this.encodingConfig,quality:n});this.encodingConfig.onEncoderConfig?.(a),this.source._nominalBitrate=a.bitrate??null;let s=An.find(o=>o.supports(this.encodingConfig.codec,a));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=a,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof X))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(o,c),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,o,c).catch(u=>{this.setError(u)})},this.customEncoder.onError=o=>{this.setError(o)},await this.customEncoder.init();else if(ae.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error(Gi("AudioEncoder"));let o;try{o=(await AudioEncoder.isConfigSupported(a)).supported??!1}catch{o=!1}if(!o)throw new Error(`This specific encoder configuration (${a.codec}, ${a.bitrate} bps, ${a.numberOfChannels} channels, ${a.sampleRate} Hz) is not supported in this environment. Consider using another codec or changing your audio parameters.`);let c=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(u,l)=>{if(this.encodingConfig.codec==="aac"&&l?.decoderConfig){let m=!1;if(!l.decoderConfig.description||l.decoderConfig.description.byteLength<2?m=!0:m=$t($(l.decoderConfig.description)).objectType===0,m){let f=Number(Z(a.codec.split(".")));l.decoderConfig.description=$i({objectType:f,outputNumberOfChannels:l.decoderConfig.numberOfChannels,outputSampleRate:l.decoderConfig.sampleRate})}}let d=X.fromEncodedChunk(u);d=d.clone({timestamp:qt(d.timestamp,a.sampleRate),duration:u.duration!=null?qt(d.duration,a.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(d,l),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,d,l).catch(m=>{this.setError(m)})},error:u=>{u.stack=c,this.setError(u)}}),this.encoder.configure(a)}g(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let t=this.encodingConfig.codec,{dataType:e,sampleSize:r,littleEndian:n}=Re(t);switch(this.outputSampleSize=r,r){case 1:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint8(s,ee(Math.round(o*128)+128,0,255)):e==="signed"?this.writeOutputValue=(a,s,o)=>{a.setInt8(s,ee(Math.round(o*128),-128,127))}:e==="ulaw"?this.writeOutputValue=(a,s,o)=>{let c=ee(Math.round(o*32768),-32768,32767);a.setUint8(s,Nm(c))}:e==="alaw"?this.writeOutputValue=(a,s,o)=>{let c=ee(Math.round(o*32768),-32768,32767);a.setUint8(s,Wm(c))}:g(!1);break;case 2:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint16(s,ee(Math.round(o*32768)+32768,0,65535),n):e==="signed"?this.writeOutputValue=(a,s,o)=>a.setInt16(s,ee(Math.round(o*32768),-32768,32767),n):g(!1);break;case 3:e==="unsigned"?this.writeOutputValue=(a,s,o)=>bi(a,s,ee(Math.round(o*8388608)+8388608,0,16777215),n):e==="signed"?this.writeOutputValue=(a,s,o)=>Ml(a,s,ee(Math.round(o*8388608),-8388608,8388607),n):g(!1);break;case 4:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint32(s,ee(Math.round(o*2147483648)+2147483648,0,4294967295),n):e==="signed"?this.writeOutputValue=(a,s,o)=>a.setInt32(s,ee(Math.round(o*2147483648),-2147483648,2147483647),n):e==="float"?this.writeOutputValue=(a,s,o)=>a.setFloat32(s,o,n):g(!1);break;case 8:e==="float"?this.writeOutputValue=(a,s,o)=>a.setFloat64(s,o,n):g(!1);break;default:ne(r),g(!1)}}async flushAndClose(t){try{t||(this.checkForEncoderError(),this.resampler&&await this.resampler.finalize()),this.closed=!0,t||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&await this.encoder.flush())}finally{this.closed=!0,this.resampler=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&this.encoder.state!=="closed"&&this.encoder.close()}t||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},_a=class extends Mr{constructor(t){Po(t),super(t.codec),this._encoder=new va(this,t)}add(t){if(!(t instanceof Ce))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(t,!1)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},il=class extends Mr{constructor(t,e={}){if(Po(t),typeof e!="object"||!e)throw new TypeError("options must be an object.");if(e.startTimestamp!==void 0&&!Number.isFinite(e.startTimestamp))throw new TypeError("options.startTimestamp, when provided, must be a finite number.");super(t.codec),this._encoder=new va(this,t),this._accumulatedTime=e.startTimestamp??0}async add(t){if(!(t instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let e=Ce._fromAudioBuffer(t,this._accumulatedTime);this._accumulatedTime+=t.duration;for(let r of e)await this._encoder.add(r,!0)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},nl=class extends Mr{constructor(e,r,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");if(Po(r),typeof n!="object"||!n)throw new TypeError("options must be an object.");if(n.timestampBase!==void 0&&n.timestampBase!=="synced-zero"&&n.timestampBase!=="zero"&&n.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");super(r.codec);this._abortController=null;this._audioContext=null;this._scriptProcessorNode=null;this._promiseWithResolvers=J();this._errorPromiseAccessed=!1;this._paused=!1;this._options=n,this._encoder=new va(this,r),this._track=e}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}async _start(){this._errorPromiseAccessed||z._warn("Make sure not to ignore the `errorPromise` field on MediaStreamAudioTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,r=!1,n=null,a=0,s=o=>{if(r){o.close();return}let c=o.timestamp;if(this._paused){if(e!==null){if(n!==null&&this._options.timestampBase!=="unix"){let l=c-n;a-=l}n=c}o.close();return}if(e===null){e=o.timestamp;let u,l=this._options.timestampBase??"synced-zero";if(l==="unix")u=Date.now()/1e3;else if(l==="zero")u=0;else{let d=this._connectedTrack.output;d._firstMediaStreamTimestamp===null?(d._firstMediaStreamTimestamp=performance.now()/1e3,u=0):u=performance.now()/1e3-d._firstMediaStreamTimestamp}a=u-e}if(n=c,this._encoder.getQueueSize()>=8){o.close();return}o.setTimestamp(c+a),this._encoder.add(o,!0).catch(u=>{r=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(u),this._audioContext?.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){let o=new MediaStreamTrackProcessor({track:this._track}),c=new WritableStream({write:u=>s(new Ce(u))});o.readable.pipeTo(c,{signal:this._abortController.signal}).catch(u=>{u instanceof DOMException&&u.name==="AbortError"||this._promiseWithResolvers.reject(u)})}else{let o=window.AudioContext||window.webkitAudioContext;this._audioContext=new o({sampleRate:this._track.getSettings().sampleRate});let c=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state==="suspended"&&await this._audioContext.resume(),c.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let u=0;this._scriptProcessorNode.onaudioprocess=l=>{let d=Ce._fromAudioBuffer(l.inputBuffer,u);u+=l.inputBuffer.duration;for(let m of d)s(m)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&(this._abortController.abort(),this._abortController=null),this._audioContext&&(g(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend())}finally{await this._encoder.flushAndClose(e)}}},Vg=()=>{let i=(r,n)=>{n?self.postMessage(r,{transfer:n}):self.postMessage(r)};i({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});let t=new Map,e=new Map;self.addEventListener("message",r=>{let n=r.data;switch(n.type){case"videoTrack":{e.set(n.trackId,n.track);let a=new MediaStreamTrackProcessor({track:n.track}),s=new WritableStream({write:c=>{if(!e.has(n.trackId)){c.close();return}i({type:"videoFrame",trackId:n.trackId,videoFrame:c},[c])}}),o=new AbortController;t.set(n.trackId,o),a.readable.pipeTo(s,{signal:o.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||i({type:"error",trackId:n.trackId,error:c})})}break;case"stopTrack":{let a=t.get(n.trackId);a&&(a.abort(),t.delete(n.trackId)),e.get(n.trackId)?.stop(),e.delete(n.trackId),i({type:"trackStopped",trackId:n.trackId})}break;default:ne(n)}})},Ug=0,xt=null,zg=()=>{let i=new Blob([`(${Vg.toString()})()`],{type:"application/javascript"}),t=URL.createObjectURL(i);xt=new Worker(t)},Yu=null,Ng=async()=>Yu!==null?Yu:(xt||zg(),new Promise(i=>{g(xt);let t=e=>{let r=e.data;r.type==="support"&&(Yu=r.supported,xt.removeEventListener("message",t),i(r.supported))};xt.addEventListener("message",t)})),Zu=(i,t)=>{g(xt),t?xt.postMessage(i,t):xt.postMessage(i)},Bn=class extends Fn{constructor(t){if(super(),!Ye.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${Ye.join(", ")}.`);this._codec=t}},al=class extends Bn{constructor(e){super(e);this._error=null;this._errorSet=!1;this._lastMuxerPromise=Promise.resolve();this._parser=new Uo({codec:e,output:(r,n)=>{this._lastMuxerPromise=this._connectedTrack.output._muxer.addSubtitleCue(this._connectedTrack,r,n).catch(a=>{this._setError(a)})}})}add(e){if(typeof e!="string")throw new TypeError("text must be a string.");return this._checkForError(),this._ensureValidAdd(),this._parser.parse(e),this._lastMuxerPromise}_setError(e){this._errorSet||(this._error=e,this._errorSet=!0)}_checkForError(){if(this._errorSet)throw this._error}async _flushAndClose(e){e||this._checkForError()}};var Af=i=>i==="opus"?"Opus":i,Zo=class extends Pe{constructor(e,r){if(!(e._target instanceof pt))throw new TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(e);this.trackDatas=[];this.isRelativeToUnixEpoch=!1;this.numWrittenMasterPlaylists=0;this.playlists=[];this.playlistDeclarations=[];this.format=r,this.targetSegmentDuration=r._options.targetDuration??2,this.singleFilePerPlaylist=r._options.singleFilePerPlaylist??!1,this.isLive=r._options.live??!1,this.maxLiveSegmentCount=r._options.maxLiveSegmentCount??1/0,this.globalTargetDuration=this.targetSegmentDuration,this.getPlaylistPath=r._options.getPlaylistPath??(({n})=>`playlist-${n}.m3u8`),this.getSegmentPath=r._options.getSegmentPath??(n=>n.isSingleFile?`segments-${n.playlist.n}${n.format.fileExtension}`:`segment-${n.playlist.n}-${n.n}${n.format.fileExtension}`),this.getInitPath=r._options.getInitPath??(n=>`init-${n.n}${n.segmentFormat.fileExtension}`)}async start(){let e=await this.mutex.acquire(),r=this.output.tracks.some(y=>y.metadata.isRelativeToUnixEpoch),n=this.output.tracks.some(y=>!y.metadata.isRelativeToUnixEpoch);if(r&&n)throw new Error("All tracks must agree on `relativeToUnixEpoch`: some tracks are relative to the Unix epoch and some are not.");this.isRelativeToUnixEpoch=r;let a=new Map,s=[],o=!1,c=!1,u=!1;for(let y of this.output.tracks){y.type==="video"&&(o=!0);let k=new Map;for(let T of this.output.tracks){if(y===T||!y.canBePairedWith(T))continue;if(y.type===T.type){c||(z._warn(`Illegal pairing of two ${y.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),c=!0);continue}if(y.isVideoTrack()&&y.metadata.hasOnlyKeyPackets||T.isVideoTrack()&&T.metadata.hasOnlyKeyPackets){u||(z._warn("A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired."),u=!0);continue}let w=k.get(T.source._codec);w||k.set(T.source._codec,w=[]),w.push(T)}for(let[,T]of k){let w=T.map(C=>C.id).join("-");s.find(C=>C.key===w)||s.push({name:T[0].type+"-"+(s.length+1),key:w,tracks:T,needsEmit:!1,firstNoUri:!1});let x=a.get(y);x||a.set(y,x=[]),x.push(w)}}let l=o?"video":"audio",d=[],m=[],f=[];for(let y of this.output.tracks){let k=a.get(y);if(k){if(g(k.length>0),y.type!==l)continue;for(let T of k){let w=s.find(A=>A.key===T);if(g(w),k.length===1&&w.tracks.length===1){let A=a.get(w.tracks[0]);if(g(A!==void 0),A.length===1){let x=s.find(C=>C.key===A[0]);if(x.tracks.length===1){g(x.tracks[0]===y),d.push({tracks:[y,w.tracks[0]],linkedGroup:null});continue}}}d.push({tracks:[y],linkedGroup:w}),w.needsEmit=!0}}else y.type==="video"?m.push(y):y.type==="audio"&&f.push(y)}let p=({metadata:y})=>{let k="";return k+=`${y.languageCode??se}-`,k+=`${y.name??""}-`,k+=`${y.disposition?.default??!0}-`,k+=`${y.disposition?.primary??!1}-`,k+=`${y.disposition?.forced??!1}-`,k};if(m.length>0)if(new Set(m.map(p)).size>1){let k={key:m.map(T=>T.id).join("-"),name:"video-"+(s.length+1),tracks:m,needsEmit:!0,firstNoUri:!0};s.push(k),d.push({tracks:[m[0]],linkedGroup:k})}else for(let k of m)d.push({tracks:[k],linkedGroup:null});if(f.length>0)if(new Set(f.map(p)).size>1){let k={key:f.map(T=>T.id).join("-"),name:"audio-"+(s.length+1),tracks:f,needsEmit:!0,firstNoUri:!0};s.push(k),d.push({tracks:[f[0]],linkedGroup:k})}else for(let k of f)d.push({tracks:[k],linkedGroup:null});let b=y=>{let k=[],T=0,w=0,A=!1,x=null,C=-1/0;for(let P of y)P.isVideoTrack()?(T++,A||=(P.metadata.rotation??0)!==0||!!P.metadata.flip||!!P.metadata.transformationMatrix):P.isAudioTrack()&&w++,k.push(P.source._codec);for(let P of jt(this.format._options.segmentFormat)){let S=P.getSupportedCodecs(),I=P.getSupportedTrackCounts();if(k.some(v=>!S.includes(v))||TI.video.max||wI.audio.max)continue;let E=0;A&&P.supportsVideoTransformationMetadata&&E++,E>C&&(x=P,C=E)}return g(x),x},h=async y=>{if(y.some(x=>this.playlists.some(C=>C.tracks.includes(x))))throw new Error("Internal error: track is already registered in a playlist.");let k=b(y),T=this.playlists.length+1,w=await this.getPlaylistPath({n:T,tracks:y,segmentFormat:k});Lg(w);let A={id:this.playlists.length+1,path:w,tracks:y,segmentFormat:k,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,nextSegmentId:1,initSegment:null,writtenSegments:[],peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,singleFile:null,mutex:new Le};return this.playlists.push(A),A};for(let y of s)if(y.needsEmit)for(let k=0;kA.tracks[0].id===T.id);w??=await h([T]),this.playlistDeclarations.push({playlist:w,groupId:y.name,noUri:y.firstNoUri&&k===0,references:[]})}for(let y of d){let k=this.playlists.find(T=>T.tracks[0].id===y.tracks[0].id);k??=await h(y.tracks),this.playlistDeclarations.push({playlist:k,groupId:null,noUri:!1,references:y.linkedGroup?this.playlistDeclarations.filter(T=>T.groupId===y.linkedGroup.name):[]})}for(let y of this.output.tracks)y.isVideoTrack()&&y.metadata.decoderConfig?this.getVideoTrackData(y,y.metadata.primingPacket??null,{decoderConfig:y.metadata.decoderConfig}):y.isAudioTrack()&&y.metadata.decoderConfig&&this.getAudioTrackData(y,y.metadata.primingPacket??null,{decoderConfig:y.metadata.decoderConfig});e()}async getMimeType(){return nr}allTracksAreKnown(e){for(let r of e.tracks)if(!r.source._closed&&!this.trackDatas.some(n=>n.track===r))return!1;return!0}async onTrackClose(e){let r=this.trackDatas.find(s=>s.track===e);r&&(r.closed=!0);let n=this.playlists.find(s=>s.tracks.includes(e));g(n);let a=await n.mutex.acquire();try{await this.advancePlaylist(n)}finally{a()}}getVideoTrackData(e,r,n){let a=this.trackDatas.find(o=>o.track===e);if(a)return a;tr(n,e.source._codec),g(n),g(n?.decoderConfig);let s=this.playlists.filter(o=>o.tracks.includes(e));return g(s.length===1),a={track:e,packets:[],playlist:s[0],closed:!1,info:{type:"video",decoderConfig:n.decoderConfig,primingPacket:r}},this.trackDatas.push(a),a}getAudioTrackData(e,r,n){let a=this.trackDatas.find(o=>o.track===e);if(a)return a;Se(n,e.source._codec),g(n),g(n?.decoderConfig);let s=this.playlists.filter(o=>o.tracks.includes(e));return g(s.length===1),a={track:e,packets:[],playlist:s[0],closed:!1,info:{type:"audio",decoderConfig:n.decoderConfig,primingPacket:r}},this.trackDatas.push(a),a}async addEncodedVideoPacket(e,r,n){let a=this.getVideoTrackData(e,r,n),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(e,r.timestamp,r.type==="key"),a.packets.push(r),s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=r.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,r.timestamp)),await this.advancePlaylist(s)}finally{o()}}async addEncodedAudioPacket(e,r,n){let a=this.getAudioTrackData(e,r,n),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(e,r.timestamp,r.type==="key"),a.packets.push(r),s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=r.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,r.timestamp)),await this.advancePlaylist(s)}finally{o()}}async addSubtitleCue(e,r,n){throw new Error("Unreachable.")}async advancePlaylist(e){if(g(!e.done),!this.allTracksAreKnown(e))return;let r=this.trackDatas.filter(s=>e.tracks.includes(s.track));if(e.currentSegmentStartTimestamp===null){r.every(s=>s.closed)&&await this.onPlaylistDone(e);return}let n=r.find(s=>s.info.type==="video"),a=r.find(s=>s.info.type==="audio");for(;;){let s=e.currentSegmentStartTimestamp+this.targetSegmentDuration,o=0,c=0;if(n&&(!n.closed||n.packets.length>0)){let x=n.packets.every(S=>S.timestamps)break;S>0&&I.type==="key"&&(C=I,P=S)}if(P!==null){if(o=P,a){let S=a.packets.findIndex(I=>I.timestamp>=C.timestamp);if(S!==-1)c=S;else if(a.closed)c=a.packets.length;else return}}else{if(!n.closed)return;o=n.packets.length;let S=Wl(n.packets,E=>E.timestamp),I=n.packets[S];if(g(I),a)if(I.timestampv.timestamp>=s);if(E!==-1)c=E;else if(a.closed)c=a.packets.length;else return}else{let E=a.packets.findIndex(v=>v.timestamp>I.timestamp);if(E!==-1)c=E;else if(a.closed)c=a.packets.length;else return}}}else if(a&&(!a.closed||a.packets.length>0))if(a.packets.every(C=>C.timestampP.timestamp<=s);c=Math.max(C,1)}if(o===0&&c===0){r.every(C=>C.closed)&&await this.onPlaylistDone(e);return}let u=null,l,d;g(this.output._target instanceof pt);let m=this.output._target;if(this.singleFilePerPlaylist)if(e.singleFile===null){let x={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:Yo(e)};l=await this.getSegmentPath(x),xf(l),d=we(we(m.rootPath,e.path),l);let C=await this.output._getTarget({path:d,isRoot:!1,mimeType:e.segmentFormat.mimeType}),P=null;if(e.segmentFormat._isFragmentedIsobmff()){P={output:new Br({format:e.segmentFormat,target:C}),videoSource:null,audioSource:null,firstMoofPosition:null,currentFileSize:0},C.on("write",({end:E})=>{P.currentFileSize=Math.max(P.currentFileSize,E)});let S=P.output._muxer;S.minimumFragmentDuration=1/0;let I=S.formatOptions.onMoof;S.formatOptions.onMoof=(E,v,F)=>{P.firstMoofPosition=v,I?.(E,v,F),S.formatOptions.onMoof=I},n&&(P.videoSource=new ui(n.track.source._codec),P.output.addVideoTrack(P.videoSource,{...n.track.metadata,decoderConfig:n.info.decoderConfig,primingPacket:n.info.primingPacket??void 0})),a&&(P.audioSource=new li(a.track.source._codec),P.output.addAudioTrack(P.audioSource,{...a.track.metadata,decoderConfig:a.info.decoderConfig,primingPacket:a.info.primingPacket??void 0})),await P.output.start()}else C._start();e.singleFile={target:C,path:l,nextOffset:0,info:x,fragmentedIsobmffOutput:P}}else l=e.singleFile.path,d=we(we(m.rootPath,e.path),l);else u={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:Yo(e)},l=await this.getSegmentPath(u),xf(l),d=we(we(m.rootPath,e.path),l),e.nextSegmentId++;let f=0,p=null,b=-1/0,h=null,y=null,k=null;try{if(e.singleFile?.fragmentedIsobmffOutput?(h=e.singleFile.fragmentedIsobmffOutput.output,y=e.singleFile.fragmentedIsobmffOutput.videoSource,k=e.singleFile.fragmentedIsobmffOutput.audioSource):(h=new Br({format:e.segmentFormat,target:new pt(d,async x=>{let C={...x,isRoot:!1};if(x.isRoot)if(e.singleFile){let P=e.singleFile.target.slice(e.singleFile.nextOffset);return P.on("write",({end:S})=>f=Math.max(f,S)),P}else{let P=await this.output._getTarget(C);return p=P,P.on("write",({end:S})=>f=Math.max(f,S)),P}return this.output._getTarget(C)}),initTarget:async()=>{if(e.initSegment)return new Ni;if(e.singleFile){e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null};let x=e.singleFile.target.slice(e.singleFile.nextOffset);return x.on("write",({end:C})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,C)}),x.on("finalized",()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),x}else{let x=Yo(e),C=await this.getInitPath(x);Wg(C),e.initSegment={path:C,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};let P=we(we(m.rootPath,e.path),C),S=await this.output._getTarget({path:P,isRoot:!1,mimeType:e.segmentFormat.mimeType});return S.on("write",({end:I})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,I)}),S.on("finalized",()=>{this.format._options.onInit?.(S,x)}),S}}}),n&&(y=new ui(n.track.source._codec),h.addVideoTrack(y,{...n.track.metadata,decoderConfig:n.info.decoderConfig,primingPacket:n.info.primingPacket??void 0})),a&&(k=new li(a.track.source._codec),h.addAudioTrack(k,{...a.track.metadata,decoderConfig:a.info.decoderConfig,primingPacket:a.info.primingPacket??void 0})),await h.start()),n){g(y);let x={decoderConfig:n.info.decoderConfig};for(let C=0;C0&&(g(n),n.packets.splice(0,o)),c>0&&(g(a),a.packets.splice(0,c));let T=1/0;n&&n.packets.length>0&&(T=n.packets[0].timestamp),a&&a.packets.length>0&&(T=Math.min(T,a.packets[0].timestamp));let w=T<1/0?T:b;g(Number.isFinite(w));let A=w-e.currentSegmentStartTimestamp;if(g(A>=0),e.writtenSegments.push({path:l,duration:A,timestamp:e.currentSegmentStartTimestamp,byteSize:f,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:u??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,A),e.currentSegmentStartTimestamp=w,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=f),this.isLive){for(;e.writtenSegments.length>this.maxLiveSegmentCount;){let x=e.writtenSegments.shift();e.mediaSequence++,this.singleFilePerPlaylist||(g(x.info),this.format._options.onSegmentPopped?.(x.path,x.info))}await this.writePlaylist(e),await this.tryWriteMasterPlaylist()}}}async onPlaylistDone(e){g(!e.done),e.done=!0,e.singleFile&&(e.singleFile.fragmentedIsobmffOutput?await e.singleFile.fragmentedIsobmffOutput.output.finalize():(await e.singleFile.target._flush(),await e.singleFile.target._finalize()),this.format._options.onSegment?.(e.singleFile.target,e.singleFile.info)),await this.writePlaylist(e),this.isLive&&e.writtenSegments.length===0&&await this.tryWriteMasterPlaylist()}updatePlaylistBitrates(e){let r=e.writtenSegments,n=0,a=0,s=0;for(let c=0;c=.5*this.globalTargetDuration&&l<=1.5*this.globalTargetDuration&&(n=Math.max(n,8*u/l)),!(l>1.5*this.globalTargetDuration));d++);}if(n===0)for(let c of r){let u=c.duration||1;n=Math.max(n,8*c.byteSize/u)}for(let c of r)a+=8*c.byteSize;let o=a/(s||1);if(r.length===0)for(let c of e.tracks){let u=this.trackDatas.find(d=>d.track===c),l=c.source._nominalBitrate??c.metadata.bitrate??0;if(o+=c.source._nominalBitrate??c.metadata.averageBitrate??0,l===0){let d=new ce("medium");if(c.isVideoTrack()){let m=u?.info.decoderConfig;l=d._toVideoBitrate(c.source._codec,m?.codedWidth??1920,m?.codedHeight??1080)}else c.isAudioTrack()&&(l=d._toAudioBitrate(c.source._codec)??0)}n+=l}e.peakBitrate=n,e.averageBitrate=o}async writePlaylist(e){g(this.output._target instanceof pt);let r=this.output._target;this.updatePlaylistBitrates(e);let n=!1;for(let m of e.writtenSegments)n||=m.byteOffset!==null;let a=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets,s=3;(a||n)&&(s=4),e.initSegment&&(s=5),e.initSegment&&!a&&(s=6);let o=this.isLive?this.targetSegmentDuration:this.globalTargetDuration,c=we(r.rootPath,e.path),u=`#EXTM3U +#EXT-X-VERSION:${s} +`+(this.isLive?"":`#EXT-X-PLAYLIST-TYPE:VOD +`)+`#EXT-X-TARGETDURATION:${Math.ceil(o)} +`+(Number.isFinite(this.maxLiveSegmentCount)?`#EXT-X-MEDIA-SEQUENCE:${e.mediaSequence} +`:"")+`#EXT-X-INDEPENDENT-SEGMENTS +`+(a?`#EXT-X-I-FRAMES-ONLY +`:"")+(e.initSegment?`#EXT-X-MAP:URI="${e.initSegment.path}"`+(e.initSegment.byteOffset!==null?`,BYTERANGE="${e.initSegment.byteSize}@${e.initSegment.byteOffset}"`:"")+` +`:"")+` +`+e.writtenSegments.map(m=>`#EXTINF:${+m.duration.toFixed(12)}, +`+(this.isRelativeToUnixEpoch?`#EXT-X-PROGRAM-DATE-TIME:${new Date(1e3*m.timestamp).toISOString()} +`:"")+(m.byteOffset!==null?`#EXT-X-BYTERANGE:${m.byteSize}@${m.byteOffset} +`:"")+`${m.path} +`).join("")+(e.done?(e.writtenSegments.length>0?` +`:"")+`#EXT-X-ENDLIST +`:"");this.format._options.onPlaylist?.(u,Yo(e));let l=await this.output._getTarget({path:c,isRoot:!1,mimeType:nr}),d=new lr(l,!0);d.start(),d.write(Y.encode(u)),await d.flush(),await d.finalize()}async writeMasterPlaylist(){g(this.output._target instanceof pt);let e=this.output._target,r=`#EXTM3U +`,n=!1,a=null,s=0,o=!1;for(let u of this.playlistDeclarations)if(u.groupId===null){let l=u.playlist.tracks[0].isVideoTrack()&&u.playlist.tracks[0].metadata.hasOnlyKeyPackets,d=[];for(let y of u.playlist.tracks){let T=this.trackDatas.find(w=>w.track===y)?.info.decoderConfig.codec??y.source._codec;d.push(Af(T))}let m=0,f=0;if(u.references.length>0){let k=u.references[0].playlist.tracks[0],w=this.trackDatas.find(A=>A.track===k)?.info.decoderConfig.codec??k.source._codec;d.push(Af(w));for(let A of u.references)g(A.playlist.peakBitrate!==null),m=Math.max(m,A.playlist.peakBitrate),f=Math.max(f,A.playlist.averageBitrate??0)}g(u.playlist.peakBitrate!==null);let p=u.playlist.peakBitrate+m,b=(u.playlist.averageBitrate??0)+f;n||(r+=` +`,n=!0),l?r+="#EXT-X-I-FRAME-STREAM-INF:":r+="#EXT-X-STREAM-INF:",r+=`BANDWIDTH=${Math.ceil(p)}`,b>0&&(r+=`,AVERAGE-BANDWIDTH=${Math.ceil(b)}`),r+=`,CODECS="${d.join(",")}"`;let h=u.playlist.tracks.find(y=>y.isVideoTrack());if(h?.isVideoTrack()){let k=this.trackDatas.find(T=>T.track===h)?.info.decoderConfig;if(k){let T=k.displayAspectWidth??k.codedWidth,w=k.displayAspectHeight??k.codedHeight;T!==void 0&&w!==void 0&&(h.metadata.rotation!==void 0&&h.metadata.rotation%180===90&&([T,w]=[w,T]),r+=`,RESOLUTION=${T}x${w}`)}!l&&h.metadata.frameRate!==void 0&&(r+=`,FRAME-RATE=${+h.metadata.frameRate.toFixed(3)}`)}if(!l){let y=new Map;for(let k of u.references){g(k.groupId!==null);let T=k.playlist.tracks[0].type;y.set(T,k.groupId)}for(let[k,T]of y)r+=`,${k.toUpperCase()}="${T}"`}l?(r+=`,URI="${u.playlist.path}"`,r+=` +`):(r+=` +`,r+=`${u.playlist.path} +`)}else{g(u.playlist.tracks.length===1);let l=u.playlist.tracks[0],d=l.type,m=l.metadata.name??null,f=l.metadata.languageCode,p=l.metadata.disposition;(a===null||u.groupId!==a)&&(s=0,r+=` +`,o=!1),a=u.groupId,s++,r+=`#EXT-X-MEDIA:TYPE=${d.toUpperCase()},GROUP-ID="${u.groupId}"`,m!==null&&/[\n\r"]/.test(m)&&(z._warn("Dropping track name since it includes a line feed, carriage return, or double quote character, which are not allowed in HLS playlist attributes."),m=null),m??=`${f??u.groupId}-${s}`,r+=`,NAME="${m}"`,f!==void 0&&(r+=`,LANGUAGE="${f}"`);let b=p?.primary??!1,h=p?.default??!0,y=p?.forced??!1;if(b&&!o&&(r+=",DEFAULT=YES",o=!0),(b||h)&&(r+=",AUTOSELECT=YES"),y&&(r+=",FORCED=YES"),d==="audio"){let T=this.trackDatas.find(w=>w.track===l)?.info.decoderConfig;T&&(r+=`,CHANNELS="${T.numberOfChannels}"`)}u.noUri||(r+=`,URI="${u.playlist.path}"`),r+=` +`}this.format._options.onMaster?.(r);let c=await this.mutex.acquire();try{let u;if(this.numWrittenMasterPlaylists===0)u=await this.output._getRootWriter(!0);else{let l=await this.output._getTarget({path:e.rootPath,isRoot:!0,mimeType:nr});u=new lr(l,!0),u.start()}u.write(Y.encode(r)),await u.flush(),await u.finalize(),this.numWrittenMasterPlaylists++}finally{c()}}async tryWriteMasterPlaylist(){g(this.isLive);for(let e of this.playlists)if(e.writtenSegments.length===0&&!e.done)return;await this.writeMasterPlaylist()}async finalize(){(await Promise.all(this.playlists.map(r=>r.mutex.acquire()))).forEach(r=>r());for(let r of this.trackDatas)r.closed=!0;await Promise.all(this.playlists.map(r=>r.done?Promise.resolve():this.advancePlaylist(r))),this.isLive||await this.writeMasterPlaylist()}},Lg=i=>{if(typeof i!="string")throw new TypeError("options.getPlaylistPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Playlist paths cannot contain line feed, carriage return, or double quote characters.")},xf=i=>{if(typeof i!="string")throw new TypeError("options.getSegmentPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Segment paths cannot contain line feed or carriage return characters.")},Wg=i=>{if(typeof i!="string")throw new TypeError("options.getInitPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Init paths cannot contain line feed, carriage return, or double quote characters.")},Yo=i=>({n:i.id,tracks:i.tracks,segmentFormat:i.segmentFormat});var Ke=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(t=>le.includes(t))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(t=>fe.includes(t))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(t=>Ye.includes(t))}_codecUnsupportedHint(t){return""}_isFragmentedIsobmff(){return!1}},On=class extends Ke{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(t.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(t.minimumFragmentDuration!==void 0&&(!ve(t.minimumFragmentDuration)||t.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(t.onFtyp!==void 0&&typeof t.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(t.onMoov!==void 0&&typeof t.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(t.onMdat!==void 0&&typeof t.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(t.onMoof!==void 0&&typeof t.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(t.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(t.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=t}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:0,max:4294967295}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"full"}_createMuxer(t){return new Wo(t,this)}_isFragmentedIsobmff(){return this._options.fastStart==="fragmented"}},Dn=class extends On{constructor(t){super(t)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...le,...Rt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Ye]}_codecUnsupportedHint(t){return new Rn().getSupportedCodecs().includes(t)?" Switching to MOV will grant support for this codec.":""}},_n=class extends On{constructor(t){super(t)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...le,...Rt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Ye]}},Rn=class extends On{constructor(t){super(t)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...le,...fe]}_codecUnsupportedHint(t){return new Dn().getSupportedCodecs().includes(t)?" Switching to MP4 will grant support for this codec.":""}},Ra=class extends Ke{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.appendOnly!==void 0&&typeof t.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(t.minimumClusterDuration!==void 0&&(!ve(t.minimumClusterDuration)||t.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(t.onEbmlHeader!==void 0&&typeof t.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(t.onSegmentHeader!==void 0&&typeof t.onSegmentHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(t.onCluster!==void 0&&typeof t.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Ho(t,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:0,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...le,...Rt,...ae.filter(t=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(t)),...Ye]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},Li=class extends Ra{constructor(t){super(t)}getSupportedCodecs(){return[...le.filter(t=>["vp8","vp9","av1"].includes(t)),...fe.filter(t=>["opus","vorbis"].includes(t)),...Ye]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(t){return new Ra().getSupportedCodecs().includes(t)?" Switching to MKV will grant support for this codec.":""}},sl=class extends Ke{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.xingHeader!==void 0&&typeof t.xingHeader!="boolean")throw new TypeError("options.xingHeader, when provided, must be a boolean.");if(t.onXingFrame!==void 0&&typeof t.onXingFrame!="function")throw new TypeError("options.onXingFrame, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Ko(t,this)}get _name(){return"MP3"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".mp3"}get mimeType(){return"audio/mpeg"}getSupportedCodecs(){return["mp3"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},ol=class extends Ke{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.large!==void 0&&typeof t.large!="boolean")throw new TypeError("options.large, when provided, must be a boolean.");if(t.metadataFormat!==void 0&&!["info","id3"].includes(t.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if(t.onHeader!==void 0&&typeof t.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Xo(t,this)}get _name(){return"WAVE"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".wav"}get mimeType(){return"audio/wav"}getSupportedCodecs(){return[...ae.filter(t=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-f64","pcm-u8","ulaw","alaw"].includes(t))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},cl=class extends Ke{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maximumPageDuration!==void 0&&(!ve(t.maximumPageDuration)||t.maximumPageDuration<=0))throw new TypeError("options.maximumPageDuration, when provided, must be a positive number.");if(t.onPage!==void 0&&typeof t.onPage!="function")throw new TypeError("options.onPage, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Qo(t,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:4294967296},subtitle:{min:0,max:0},total:{min:0,max:4294967296}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...fe.filter(t=>["vorbis","opus"].includes(t))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"none"}},ul=class extends Ke{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.onFrame!==void 0&&typeof t.onFrame!="function")throw new TypeError("options.onFrame, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Do(t,this)}get _name(){return"ADTS"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".aac"}get mimeType(){return"audio/aac"}getSupportedCodecs(){return["aac"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},ll=class extends Ke{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.appendOnly!==void 0&&typeof t.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");super(),this._options=t}_createMuxer(t){return new Vo(t,this)}get _name(){return"FLAC"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".flac"}get mimeType(){return"audio/flac"}getSupportedCodecs(){return["flac"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},dl=class extends Ke{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.onPacket!==void 0&&typeof t.onPacket!="function")throw new TypeError("options.onPacket, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Go(t,this)}get _name(){return"MPEG-TS"}getSupportedTrackCounts(){return{video:{min:0,max:16},audio:{min:0,max:32},subtitle:{min:0,max:0},total:{min:0,max:48}}}get fileExtension(){return".ts"}get mimeType(){return"video/MP2T"}getSupportedCodecs(){return[...le.filter(t=>["avc","hevc"].includes(t)),...fe.filter(t=>["aac","mp3","ac3","eac3","dts"].includes(t))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},ml=class extends Ke{constructor(t){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!(t.segmentFormat instanceof Ke)&&(!Array.isArray(t.segmentFormat)||t.segmentFormat.length===0||!t.segmentFormat.every(e=>e instanceof Ke)))throw new TypeError("options.segmentFormat must be an OutputFormat or a non-empty array of OutputFormat instances.");if(t.targetDuration!==void 0&&(typeof t.targetDuration!="number"||t.targetDuration<=0))throw new TypeError("options.targetDuration, when provided, must be a positive number.");if(t.singleFilePerPlaylist!==void 0&&typeof t.singleFilePerPlaylist!="boolean")throw new TypeError("options.singleFilePerPlaylist, when provided, must be a boolean.");if(t.live!==void 0&&typeof t.live!="boolean")throw new TypeError("options.live, when provided, must be a boolean.");if(t.maxLiveSegmentCount!==void 0&&(typeof t.maxLiveSegmentCount!="number"||t.maxLiveSegmentCount<1||Number.isFinite(t.maxLiveSegmentCount)&&!Number.isInteger(t.maxLiveSegmentCount)))throw new TypeError("options.maxLiveSegmentCount, when provided, must be a positive integer or Infinity.");if(t.getPlaylistPath!==void 0&&typeof t.getPlaylistPath!="function")throw new TypeError("options.getPlaylistPath, when provided, must be a function.");if(t.getSegmentPath!==void 0&&typeof t.getSegmentPath!="function")throw new TypeError("options.getSegmentPath, when provided, must be a function.");if(t.getInitPath!==void 0&&typeof t.getInitPath!="function")throw new TypeError("options.getInitPath, when provided, must be a function.");if(t.onMaster!==void 0&&typeof t.onMaster!="function")throw new TypeError("options.onMaster, when provided, must be a function.");if(t.onPlaylist!==void 0&&typeof t.onPlaylist!="function")throw new TypeError("options.onPlaylist, when provided, must be a function.");if(t.onSegment!==void 0&&typeof t.onSegment!="function")throw new TypeError("options.onSegment, when provided, must be a function.");if(t.onInit!==void 0&&typeof t.onInit!="function")throw new TypeError("options.onInit, when provided, must be a function.");if(t.onSegmentPopped!==void 0&&typeof t.onSegmentPopped!="function")throw new TypeError("options.onSegmentPopped, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Zo(t,this)}get _name(){return"HTTP Live Streaming (HLS)"}get fileExtension(){return".m3u8"}get mimeType(){return nr}getSupportedCodecs(){return[...new Set(jt(this._options.segmentFormat).flatMap(e=>e.getSupportedCodecs()))]}getSupportedTrackCounts(){let t=!1,e=!1,r=!1;for(let n of jt(this._options.segmentFormat)){let a=n.getSupportedTrackCounts();t||=a.video.max>0,e||=a.audio.max>0,r||=a.subtitle.max>0}return{video:{min:0,max:t?1/0:0},audio:{min:0,max:e?1/0:0},subtitle:{min:0,max:0},total:{min:0,max:1/0}}}get supportsVideoTransformationMetadata(){return jt(this._options.segmentFormat).some(t=>t.supportsVideoTransformationMetadata)}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){let t=jt(this._options.segmentFormat);return t.some(e=>e.negativeTimestampSupport==="none")?"none":t.some(e=>e.negativeTimestampSupport==="prefer-non-negative")?"prefer-non-negative":t.some(e=>e.negativeTimestampSupport==="full")?"full":null}_codecUnsupportedHint(t){return" Using different segment formats may grant support for this codec."}};var pl=["video","audio","subtitle"],Vn=class i{constructor(t,e,r,n,a){this.id=t,this.output=e,this.type=r,this.source=n,this.metadata=a}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(t){if(!(t instanceof i))throw new TypeError("other must be an OutputTrack.");if(this===t)return!1;let e=jt(this.metadata.group),r=jt(t.metadata.group);for(let n of e)if(this.type!==t.type&&r.some(o=>n===o)||r.some(o=>n._pairedGroups.has(o)))return!0;return!1}},Jo=class extends Vn{constructor(t,e,r,n){super(t,e,"video",r,n)}},ec=class extends Vn{constructor(t,e,r,n){super(t,e,"audio",r,n)}},tc=class extends Vn{constructor(t,e,r,n){super(t,e,"subtitle",r,n)}},ht=class i{constructor(){this._pairedGroups=new Set}pairWith(t){if(!(t instanceof i))throw new TypeError("other must be an OutputTrackGroup.");if(this===t)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(t),t._pairedGroups.add(this)}},fl=i=>{if(!i||typeof i!="object")throw new TypeError("metadata must be an object.");if(i.languageCode!==void 0&&!gr(i.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(i.name!==void 0&&typeof i.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(i.disposition!==void 0&&jl(i.disposition),i.maximumPacketCount!==void 0&&(!Number.isInteger(i.maximumPacketCount)||i.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(i.bitrate!==void 0&&(!Number.isFinite(i.bitrate)||i.bitrate<0))throw new TypeError("metadata.bitrate, when provided, must be a non-negative number.");if(i.averageBitrate!==void 0&&(!Number.isFinite(i.averageBitrate)||i.averageBitrate<0))throw new TypeError("metadata.averageBitrate, when provided, must be a non-negative number.");if(i.group!==void 0&&!(i.group instanceof ht)&&(!Array.isArray(i.group)||i.group.some(t=>!(t instanceof ht))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},Br=class extends ct{constructor(e){super();this.state="pending";this.defaultTrackGroup=new ht;this.tracks=[];this._onFinalize=null;this._unfinalizedTargets=new Set;this._rootWriterPromise=null;this._startPromise=null;this._cancelPromise=null;this._finalizePromise=null;this._mutex=new Le;this._metadataTags={};this._rootTarget=null;this._rootTargetPromise=null;this._firstMediaStreamTimestamp=null;if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof Ke))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof ze||e.target instanceof pt))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof ze&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof ze)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof ze&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}get target(){let e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(e);let r=this._getRootTarget();if(_(r))throw new TypeError(e);return r}_getTargetValidated(e){g(this._target instanceof pt);let r=this._target.getTarget(e),n=a=>{if(!(a instanceof ze))throw new TypeError("getTarget must return a Target.");return a};return _(r)?r.then(n):n(r)}async _getTarget(e){g(this._target instanceof pt);let r=await this._getTargetValidated(e);return this._emit("target",{target:r,request:e,isRoot:e.isRoot}),this.state==="canceled"?await r._close():this._rememberTarget(r),r}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(g(this._initTarget!==null),this._initTarget instanceof ze)return this._initTarget;let e=await this._initTarget();return this.state==="canceled"?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof ze)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},r=this._getTargetValidated(e),n=a=>(this.state==="canceled"?a._close():this._rememberTarget(a),this._emit("target",{target:a,request:e,isRoot:!0}),this._rootTarget=a,a);return _(r)?this._rootTargetPromise=r.then(n):n(r)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let r=await this._getRootTarget(),n=new lr(r,typeof e=="boolean"?e:e(r));return n.start(),n})()}addVideoTrack(e,r={}){if(!(e instanceof Fr))throw new TypeError("source must be a VideoSource.");if(fl(r),r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError(`Invalid video rotation: ${r.rotation}. Has to be 0, 90, 180 or 270.`);if(r.flip!==void 0&&typeof r.flip!="boolean")throw new TypeError("metadata.flip, when provided, must be a boolean.");if(r.transformationMatrix!==void 0&&(!Array.isArray(r.transformationMatrix)||r.transformationMatrix.length!==9||!r.transformationMatrix.every(a=>Number.isFinite(a))))throw new TypeError("metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.");if(r.frameRate!==void 0&&(!Number.isFinite(r.frameRate)||r.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${r.frameRate}. Must be a positive number.`);if(r.hasOnlyKeyPackets!==void 0&&typeof r.hasOnlyKeyPackets!="boolean")throw new TypeError("metadata.hasOnlyKeyPackets, when provided, must be a boolean.");if(r.canBeTransparent!==void 0&&typeof r.canBeTransparent!="boolean")throw new TypeError("metadata.canBeTransparent, when provided, must be a boolean.");if(r.decoderConfig!==void 0&&tr({decoderConfig:r.decoderConfig},e._codec),r.primingPacket!==void 0){if(!(r.primingPacket instanceof X))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(r.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}let n={...r};return n.group??=this.defaultTrackGroup,this._addTrack(new Jo(this.tracks.length+1,this,e,n))}addAudioTrack(e,r={}){if(!(e instanceof Mr))throw new TypeError("source must be an AudioSource.");if(fl(r),r.decoderConfig!==void 0&&Se({decoderConfig:r.decoderConfig},e._codec),r.primingPacket!==void 0){if(!(r.primingPacket instanceof X))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(r.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}let n={...r};return n.group??=this.defaultTrackGroup,this._addTrack(new ec(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,r={}){if(!(e instanceof Bn))throw new TypeError("source must be a SubtitleSource.");fl(r);let n={...r};return n.group??=this.defaultTrackGroup,this._addTrack(new tc(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(Ln(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");let r=this.format.getSupportedTrackCounts(),n=this.tracks.reduce((o,c)=>o+(c.type===e.type?1:0),0),a=r[e.type].max;if(n===a)throw new Error(a===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${a} ${e.type} track${a===1?"":"s"}.`);let s=r.total.max;if(this.tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} tracks${s===1?"":"s"} in total.`);if(e.isVideoTrack()){let o=this.format.getSupportedVideoCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${o.map(c=>`'${c}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let o=this.format.getSupportedAudioCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${o.map(c=>`'${c}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let o=this.format.getSupportedSubtitleCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${o.map(c=>`'${c}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){let e=this.format.getSupportedTrackCounts();for(let n of pl){let a=this.tracks.reduce((o,c)=>o+(c.type===n?1:0),0),s=e[n].min;if(ao+(c.type===n?1:0),0),s=e[n].min;if(a{this.state="started";let n=this._mutex.acquire();try{await this._muxer.start();let a=this.tracks.map(s=>s.source._start());await Promise.all(a)}finally{(await n)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this.state==="canceled")return this._cancelPromise??void 0;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&z._warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let e=await this._mutex.acquire();try{let r=this.tracks.map(n=>n.source._flushOrWaitForOngoingClose(!0));await Promise.all(r),await Promise.all([...this._unfinalizedTargets].map(n=>n._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(z._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";let e=await this._mutex.acquire();try{let r=this.tracks.map(n=>n.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(r),await this._muxer.finalize(),this._rootWriterPromise){let n=await this._rootWriterPromise;n.finalized||(await n.flush(),await n.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}catch(r){throw this.state="canceled",r}finally{await Promise.all([...this._unfinalizedTargets].map(r=>r._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}};var rc=i=>{if(!i||typeof i!="object")throw new TypeError("options.video, when provided, must be an object.");if(i?.discard!==void 0&&typeof i.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if(i?.forceTranscode!==void 0&&typeof i.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(i?.codec!==void 0&&!le.includes(i.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${le.join(", ")}.`);let t=i?.bitrate;if(i?.quality!==void 0&&!(i.quality instanceof ce))throw new TypeError("options.video.quality, when provided, must be a Quality.");if(i?.quality!==void 0&&t!==void 0)throw new TypeError("options.video.quality and options.video.bitrate cannot both be provided.");if(t!==void 0&&!(t instanceof ce)&&(!Number.isInteger(t)||t<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if(i?.width!==void 0&&(!Number.isInteger(i.width)||i.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if(i?.height!==void 0&&(!Number.isInteger(i.height)||i.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if(i?.fit!==void 0&&!["fill","contain","cover"].includes(i.fit))throw new TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");if(i?.width!==void 0&&i.height!==void 0&&i.fit===void 0)throw new TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if(i?.rotate!==void 0&&![0,90,180,270].includes(i.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if(i?.flip!==void 0&&typeof i.flip!="boolean")throw new TypeError("options.video.flip, when provided, must be a boolean.");if(i?.allowTransformationMetadata!==void 0&&typeof i.allowTransformationMetadata!="boolean")throw new TypeError("options.video.allowTransformationMetadata, when provided, must be a boolean.");if(i?.allowRotationMetadata!==void 0&&typeof i.allowRotationMetadata!="boolean")throw new TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if(i?.crop!==void 0&&ni(i.crop,"options.video."),i?.frameRate!==void 0&&(!Number.isFinite(i.frameRate)||i.frameRate<=0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.");if(i?.alpha!==void 0&&!["discard","keep"].includes(i.alpha))throw new TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if(i?.keyFrameInterval!==void 0&&(!Number.isFinite(i.keyFrameInterval)||i.keyFrameInterval<0))throw new TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if(i?.process!==void 0&&typeof i.process!="function")throw new TypeError("options.video.process, when provided, must be a function.");if(i?.processedWidth!==void 0&&(!Number.isInteger(i.processedWidth)||i.processedWidth<=0))throw new TypeError("options.video.processedWidth, when provided, must be a positive integer.");if(i?.processedHeight!==void 0&&(!Number.isInteger(i.processedHeight)||i.processedHeight<=0))throw new TypeError("options.video.processedHeight, when provided, must be a positive integer.");if(i?.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(i.hardwareAcceleration))throw new TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(i?.group!==void 0&&!(i.group instanceof ht||Array.isArray(i.group)&&i.group.every(e=>e instanceof ht)))throw new TypeError("options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},ic=i=>{if(!i||typeof i!="object")throw new TypeError("options.audio, when provided, must be an object.");if(i?.discard!==void 0&&typeof i.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if(i?.forceTranscode!==void 0&&typeof i.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(i?.codec!==void 0&&!fe.includes(i.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${fe.join(", ")}.`);let t=i?.bitrate;if(i?.quality!==void 0&&!(i.quality instanceof ce))throw new TypeError("options.audio.quality, when provided, must be a Quality.");if(i?.quality!==void 0&&t!==void 0)throw new TypeError("options.audio.quality and options.audio.bitrate cannot both be provided.");if(t!==void 0&&!(t instanceof ce)&&(!Number.isInteger(t)||t<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if(i?.numberOfChannels!==void 0&&(!Number.isInteger(i.numberOfChannels)||i.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if(i?.sampleRate!==void 0&&(!Number.isInteger(i.sampleRate)||i.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if(i?.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(i.sampleFormat))throw new TypeError("options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(i?.process!==void 0&&typeof i.process!="function")throw new TypeError("options.audio.process, when provided, must be a function.");if(i?.processedNumberOfChannels!==void 0&&(!Number.isInteger(i.processedNumberOfChannels)||i.processedNumberOfChannels<=0))throw new TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if(i?.processedSampleRate!==void 0&&(!Number.isInteger(i.processedSampleRate)||i.processedSampleRate<=0))throw new TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.");if(i?.group!==void 0&&!(i.group instanceof ht||Array.isArray(i.group)&&i.group.every(e=>e instanceof ht)))throw new TypeError("options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},hl=2,gl=48e3,bl=class i{constructor(t){this._state="idle";this._timestampOffset=0;this._timestampOffsetAdjusted=!1;this._copyTimestampPossible=new Map;this._copyStartPackets=new Map;this._nextOutputTrackId=0;this._outputTrackIds=[];this._outputOwnTrackGroups=[];this._trackPumps=[];this._composable=!1;this._executed=!1;this._executionUntil=1/0;this._pauseRequested=!1;this._synchronizer=new yl(this);this._totalDuration=null;this._maxTimestamps=new Map;this.onProgress=void 0;this._computeProgress=!1;this._lastProgress=0;this.isValid=!1;this.utilizedTracks=[];this.discardedTracks=[];if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!(t.input instanceof Ri))throw new TypeError("options.input must be an Input.");if(!(t.output instanceof Br))throw new TypeError("options.output must be an Output.");if(t.tracks!==void 0&&t.tracks!=="all"&&t.tracks!=="primary")throw new TypeError("options.tracks, when provided, must be either 'all' or 'primary'.");if(t.composable!==void 0&&typeof t.composable!="boolean")throw new TypeError("options.composable, when provided, must be a boolean.");if(t.copy!==void 0&&t.copy!==!1){if(!t.copy||typeof t.copy!="object")throw new TypeError("options.copy, when provided, must be an object or false.");if(t.copy.mode!==void 0&&!["forced","preferred"].includes(t.copy.mode))throw new TypeError("options.copy.mode, when provided, must be 'forced' or 'preferred'.");if(t.copy.shiftTolerance!==void 0&&(!ve(t.copy.shiftTolerance)||t.copy.shiftTolerance<0))throw new TypeError("options.copy.shiftTolerance, when provided, must be a non-negative number.");if(t.copy.boundaryPolicy!==void 0&&!["expand","shrink"].includes(t.copy.boundaryPolicy))throw new TypeError("options.copy.boundaryPolicy, when provided, must be 'expand' or 'shrink'.");if(t.copy.boundaryTolerance!==void 0&&(!ve(t.copy.boundaryTolerance)||t.copy.boundaryTolerance<0))throw new TypeError("options.copy.boundaryTolerance, when provided, must be a non-negative number.")}let e=t.composable??!1;if(e){if(t.tags!==void 0)throw new TypeError("options.tags cannot be set by a composable conversion; set metadata directly on the output instead.");if(t.output.state!=="pending")throw new TypeError("options.output must not have been started yet.")}else if(t.output.tracks.length>0||Object.keys(t.output._metadataTags).length>0||t.output.state!=="pending")throw new TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if(t.video!==void 0&&typeof t.video!="function")if(Array.isArray(t.video))for(let r of t.video)rc(r);else rc(t.video);if(t.audio!==void 0&&typeof t.audio!="function")if(Array.isArray(t.audio))for(let r of t.audio)ic(r);else ic(t.audio);if(t.trim!==void 0&&(!t.trim||typeof t.trim!="object"))throw new TypeError("options.trim, when provided, must be an object.");if(t.trim?.start!==void 0&&!Number.isFinite(t.trim.start))throw new TypeError("options.trim.start, when provided, must be a finite number.");if(t.trim?.end!==void 0&&!ve(t.trim.end))throw new TypeError("options.trim.end, when provided, must be a number.");if(t.trim?.start!==void 0&&t.trim.end!==void 0&&t.trim.start>=t.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");if(t.tags!==void 0&&(typeof t.tags!="object"||!t.tags)&&typeof t.tags!="function")throw new TypeError("options.tags, when provided, must be an object or a function.");if(typeof t.tags=="object"&&Ln(t.tags),t.showWarnings!==void 0&&typeof t.showWarnings!="boolean")throw new TypeError("options.showWarnings, when provided, must be a boolean.");this._options=t,this._copyMode=t.copy===!1?!1:t.copy?.mode??"preferred",this._copyTimestampShiftTolerance=t.copy===!1?0:t.copy?.shiftTolerance??0,this._copyBoundaryPolicy=t.copy===!1?"expand":t.copy?.boundaryPolicy??"expand",this._copyBoundaryTolerance=t.copy===!1?1/0:t.copy?.boundaryTolerance??1/0,this._composable=e,this.input=t.input,this.output=t.output}get state(){return this._state}static async init(t){let e=new i(t);return await e._init(),e}async _init(){let t=await this.input.getFormat(),e,r=this._options.tracks;if(r===void 0&&(r=t.name.includes("(HLS)")?"primary":"all"),r==="all")e=await this.input.getTracks();else if(r==="primary"){let u=await this.input.getPrimaryVideoTrack(),l=await this.input.getPrimaryAudioTrack();e=[u,l].filter(d=>d!==null)}else ne(r),g(!1);let n=this.output.format.getSupportedTrackCounts(),a=1,s=1,o=[],c=[];for(let u of e){let l;if(u.isVideoTrack())if(this._options.video)if(typeof this._options.video=="function"){let f=await this._options.video(u,a)??{};if(Array.isArray(f))for(let p of f)rc(p);else rc(f);l=Array.isArray(f)?f:[f],a++}else l=Array.isArray(this._options.video)?this._options.video:[this._options.video];else l=[{}];else if(u.isAudioTrack())if(this._options.audio)if(typeof this._options.audio=="function"){let f=await this._options.audio(u,s)??{};if(Array.isArray(f))for(let p of f)ic(p);else ic(f);l=Array.isArray(f)?f:[f],s++}else l=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else l=[{}];else g(!1);let d=l.filter(f=>f.discard);for(let f of d)this.discardedTracks.push({track:u,reason:"discarded_by_user",trackOptions:f});if(l.length===d.length){l.length===0&&this.discardedTracks.push({track:u,reason:"discarded_by_user",trackOptions:{}});continue}let m=l.filter(f=>!f.discard);o.push(u),c.push(m)}this._options.trim?.start!==void 0?this._startTimestamp=this._options.trim.start:this._startTimestamp=Math.max(await this.input.getFirstTimestamp(o),0),this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp),this._timestampOffset=-this._startTimestamp;for(let u=0;ub+(h.type===l.type?1:0),0)===n[l.type].max){this.discardedTracks.push({track:l,reason:"max_track_count_of_type_reached",trackOptions:m});continue}let p=this._nextOutputTrackId++;l.isVideoTrack()?await this._processVideoTrack(l,m,p):l.isAudioTrack()?await this._processAudioTrack(l,m,p):g(!1)}}for(let u=0;u0,this._options.showWarnings??!0){let u=[],l=this.discardedTracks.filter(d=>d.reason!=="discarded_by_user");l.length>0&&u.push("Some tracks had to be discarded from the conversion:",l),this.isValid||(u.length>0&&u.push(` + +`),u.push(this._getInvalidityExplanation().join(""))),u.length>0&&z._warn(...u)}}_getInvalidityExplanation(){let t=[];if(this.discardedTracks.length===0)t.push("Due to missing tracks, this conversion cannot be executed.");else{let e=this.discardedTracks.every(r=>r.reason==="discarded_by_user"||r.reason==="no_encodable_target_codec")&&this.discardedTracks.some(r=>r.reason==="no_encodable_target_codec");if(t.push("Due to discarded tracks, this conversion cannot be executed."),e){let r=this.discardedTracks.flatMap(a=>{if(a.reason==="discarded_by_user")return[];let s;return a.track.type==="video"?s=this.output.format.getSupportedVideoCodecs():a.track.type==="audio"?s=this.output.format.getSupportedAudioCodecs():s=this.output.format.getSupportedSubtitleCodecs(),s.filter(o=>!a.trackOptions.codec||o===a.trackOptions.codec)}),n=[...new Set(r)];n.length===1?t.push(` +Tracks were discarded because your environment is not able to encode '${n[0]}' with the provided parameters.`):t.push(` +Tracks were discarded because your environment is not able to encode any of the codecs ${n.map(a=>`'${a}'`).join(", ")} with the provided parameters.`),n.includes("mp3")&&t.push(` +The @mediabunny/mp3-encoder extension package provides support for encoding MP3.`),n.includes("aac")&&t.push(` +The @mediabunny/aac-encoder extension package provides support for encoding AAC.`),(n.includes("ac3")||n.includes("eac3"))&&t.push(` +The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),n.includes("flac")&&t.push(` +The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else t.push(` +Check the discardedTracks field for more info.`)}return t}async execute(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.until!==void 0&&(typeof t.until!="number"||Number.isNaN(t.until)))throw new TypeError("options.until, when provided, must be a number.");if(t.pauseSignal!==void 0&&!(t.pauseSignal instanceof AbortSignal))throw new TypeError("options.pauseSignal, when provided, must be an AbortSignal.");if(!this.isValid)throw new Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion. +`+this._getInvalidityExplanation().join(""));if(this._state==="executing")throw new Error("Cannot call execute() while a previous call to execute() is still running.");if(this._state==="canceled")throw new Fa;if(this._state==="done")return;if(this._composable&&this.output.state==="pending")throw new Error("A composable conversion requires the output to be started. Call start() on the output before executing the conversion.");this._state="executing",this._executionUntil=t.until??1/0,this._pauseRequested=t.pauseSignal?.aborted??!1;let e=()=>{this._state==="executing"&&(this._pauseRequested=!0,this._synchronizer.resolveAll())};t.pauseSignal?.addEventListener("abort",e);for(let n of this._trackPumps)n.done||(n.resolvers=J());if(this._executed)for(let n of this._trackPumps)n.wake?.();else{this._executed=!0;for(let n of this._outputTrackIds)this._synchronizer.declareTrack(n);if(this.onProgress){let a=[...new Set(this.utilizedTracks)].map(async o=>await o.isLive()?1/0:await o.getDurationFromMetadata()??await o.computeDuration()),s=Math.max(0,...await Promise.all(a));this._computeProgress=!0,this._totalDuration=Math.min(s-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let o of this._outputTrackIds)this._maxTimestamps.set(o,0);this.onProgress?.(0,0)}this._composable||await this.output.start();for(let n of this._trackPumps)n.start()}try{await Promise.all(this._trackPumps.map(n=>n.resolvers.promise))}catch(n){throw this._state!=="canceled"&&this.cancel(),n}finally{t.pauseSignal?.removeEventListener("abort",e)}if(this._state==="canceled")throw new Fa;let r=this._trackPumps.every(n=>n.done);if(this._state=r?"done":"idle",r&&(this._composable||await this.output.finalize(),this._computeProgress)){let n=Math.min(...this._maxTimestamps.values());this.onProgress?.(1,n)}}async cancel(){if(this._state!=="done"){if(this._state==="canceled"){z._warn("Conversion already canceled.");return}this._state="canceled";for(let t of this._trackPumps)t.wake?.();this._synchronizer.resolveAll(),this._composable||await this.output.cancel()}}async _processVideoTrack(t,e,r){let n=await t.getCodec();if(!n){this.discardedTracks.push({track:t,reason:"unknown_source_codec",trackOptions:e});return}let a,s=await t.getRotation(),o=await t.getFlip(),{rotation:c,flip:u}=Ua(s,o,e.rotate??0,e.flip??!1),l=c,d=u,m=e.rotate||e.flip?null:await t.getTransformationMatrix(),f=this.output.format.supportsVideoTransformationMetadata&&(e.allowTransformationMetadata??e.allowRotationMetadata??!0),p=await t.getSquarePixelWidth(),b=await t.getSquarePixelHeight(),[h,y]=c%180===0?[p,b]:[b,p],k=e.crop;k&&(k=wn(k,h,y));let[T,w]=k?[k.width,k.height]:[h,y],A=T,x=w,C=A/x;e.width!==void 0&&e.height===void 0?(A=Si(e.width),x=Si(Math.round(A/C))):e.width===void 0&&e.height!==void 0?(x=Si(e.height),A=Si(Math.round(x*C))):e.width!==void 0&&e.height!==void 0&&(A=Si(e.width),x=Si(e.height));let P=this.output.format.getSupportedVideoCodecs(),S=e.alpha??"discard",I=!this._copyMode||!!e.forceTranscode||!!e.frameRate||e.keyFrameInterval!==void 0||e.process!==void 0||e.quality!==void 0||e.bitrate!==void 0||!P.includes(n)||e.codec&&e.codec!==n||A!==T||x!==w||c!==0&&!f||u&&!f||!!k,E=null;if(!I){let Qe=new ft(t),Fe=await Qe.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await Qe.getFirstKeyPacket({verifyKeyPackets:!0});if(Fe&&Fe.timestampthis._copyBoundaryTolerance)I=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&Ne=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+Me):I=!0}}else if(this._timestampOffsetAdjusted)Ne+this._timestampOffset===0||(I=!0);else{let Me=ee(this._startTimestamp-Ne,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);Ne+Me===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+Me,this._timestampOffsetAdjusted=!0):I=!0}}}if(I&&this._copyMode==="forced"){this.discardedTracks.push({track:t,reason:"cannot_copy",trackOptions:e});return}if(I){if(!await t.canDecode()){this.discardedTracks.push({track:t,reason:"undecodable_source_codec",trackOptions:e});return}e.codec&&(P=P.filter(me=>me===e.codec));let Fe=ai(e.quality,e.bitrate)??new ce("high"),Ne=await Pu(P,{width:e.process&&e.processedWidth?e.processedWidth:A,height:e.process&&e.processedHeight?e.processedHeight:x,quality:Fe});if(!Ne){this.discardedTracks.push({track:t,reason:"no_encodable_target_codec",trackOptions:e});return}let re={codec:Ne,quality:Fe,keyFrameInterval:e.keyFrameInterval,sizeChangeBehavior:e.fit??"passThrough",alpha:S,hardwareAcceleration:e.hardwareAcceleration,transform:{}};g(re.transform);let Me=A!==T||x!==w||c!==0&&(!f||e.process!==void 0)||u&&(!f||e.process!==void 0)||!!k||p!==await t.getCodedWidth()||b!==await t.getCodedHeight();if(!Me){var pe=[];try{let me=new Br({format:new Dn,target:new Ni});let Oe=new Mn(re);me.addVideoTrack(Oe);await me.start();let di=new Bi(t);let Ge=st(pe,await di.getSample(await t.getFirstTimestamp()));if(Ge)try{await Oe.add(Ge),Ge.close(),await me.finalize()}catch(dr){z._warn("An error occurred when probing encoder support. Falling back to rerender path.",dr),me.cancel(),Me=!0,re.transform.force=!0}else await me.cancel()}catch(Ie){var Nt=Ie,gt=!0}finally{ot(pe,Nt,gt)}}e.frameRate&&(re.transform.frameRate=e.frameRate),e.process&&(re.transform.process=e.process),Me&&(l=0,d=!1,m=null,re.transform.width=A,re.transform.height=x,re.transform.fit=e.fit??"fill",re.transform.rotate=e.rotate,re.transform.flip=e.flip,re.transform.crop=k,re.transform.alpha=S);let Be=null;re.onEncodedSample=me=>{Be=me.timestamp};let Ee=new Mn(re);a=Ee,this._registerTrackPump(async me=>{let Oe=new Bi(t);for await(var di of Oe.samples(this._startTimestamp,this._endTimestamp)){var Ge=[];try{let bt=st(Ge,di);if(this._state==="canceled")break;let mi=Math.max(this._startTimestamp,bt.timestamp),kl=Math.min(this._endTimestamp,bt.timestamp+bt.duration);mi>=kl||(bt.setTimestamp(mi+this._timestampOffset),bt.setDuration(kl-mi),this._reportProgress(r,bt.timestamp+bt.duration),await Ee.add(bt),bt.close(),Be!==null&&(this._synchronizer.shouldWait(r,Be)&&await this._synchronizer.wait(Be),await this._checkpoint(me,Be)))}catch(dr){var Hi=dr,nc=!0}finally{ot(Ge,Hi,nc)}}Ee.close(),this._synchronizer.closeTrack(r)})}else{let Qe=new ui(n);a=Qe,this._registerTrackPump(async Fe=>{let Ne=new ft(t),Me={decoderConfig:await t.getDecoderConfig()??void 0},Be=null;if(E)for await(let Ee of Ne.packets(E,void 0,{verifyKeyPackets:!0})){if(this._state==="canceled")break;if(Ee.timestamp>=this._endTimestamp){if(this._copyBoundaryPolicy==="shrink")break;{let dr=Ee,Hi=!1,nc=6;for(let bt=0;btthis._copyBoundaryTolerance)d=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&w.timestamp=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+C):d=!0}}else if(this._timestampOffsetAdjusted)w.timestamp+this._timestampOffset===0||(d=!0);else{let C=ee(this._startTimestamp-w.timestamp,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);w.timestamp+C===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+C,this._timestampOffsetAdjusted=!0):d=!0}}if(d&&this._copyMode==="forced"){this.discardedTracks.push({track:t,reason:"cannot_copy",trackOptions:e});return}if(d){if(!await t.canDecode()){this.discardedTracks.push({track:t,reason:"undecodable_source_codec",trackOptions:e});return}let w=null;e.codec&&(l=l.filter(I=>I===e.codec));let A=ai(e.quality,e.bitrate)??new ce("high"),x=await wa(l,{numberOfChannels:e.process&&e.processedNumberOfChannels?e.processedNumberOfChannels:c,sampleRate:e.process&&e.processedSampleRate?e.processedSampleRate:u,quality:A});if(!x.some(I=>Rt.includes(I))&&l.some(I=>Rt.includes(I))&&(c!==hl||u!==gl)){let E=(await wa(l,{numberOfChannels:hl,sampleRate:gl,quality:A})).find(v=>Rt.includes(v));E&&(w=E,c=hl,u=gl)}else w=x[0]??null;if(w===null){this.discardedTracks.push({track:t,reason:"no_encodable_target_codec",trackOptions:e});return}let C={codec:w,quality:A,transform:{sampleFormat:e.sampleFormat,process:e.process}};g(C.transform),c!==s&&(C.transform.numberOfChannels=c),u!==o&&(C.transform.sampleRate=u);let P=null;C.onEncodedSample=I=>{P=I.timestamp};let S=new _a(C);a=S,this._registerTrackPump(async I=>{let E=null,v=new xn(t);for await(var Nt of v.samples(this._startTimestamp,this._endTimestamp)){var gt=[];try{let re=st(gt,Nt);var K=[];try{if(this._state==="canceled")break;let Me=0;let Be=re.numberOfFrames;re.timestampthis._endTimestamp&&(Be=Math.round((this._endTimestamp-re.timestamp)*re.sampleRate));if(Me>=Be){re.close();continue}let Ee;if(Me>0||Be0&&!this.output.format.supportsTimestampedMediaData);if(E){var F=[];try{let Oe=me.timestamp;let di=Math.round(Oe*o);let Ge=sr(re.format);let dr=new Uint8Array(Ge*di*s);(re.format==="u8"||re.format==="u8-planar")&&dr.fill(2**7);let Hi=st(F,new Ce({data:dr,format:re.format,numberOfChannels:s,sampleRate:o,timestamp:0}));await this._registerAudioSample(I,Hi,S,r,()=>P);E=!1}catch(O){var D=O,U=!0}finally{ot(F,D,U)}}await this._registerAudioSample(I,me,S,r,()=>P)}catch(ie){var pe=ie,Ie=!0}finally{ot(K,pe,Ie)}}catch(Qe){var Fe=Qe,Ne=!0}finally{ot(gt,Fe,Ne)}}S.close(),this._synchronizer.closeTrack(r)})}else{let T=new li(n);a=T,this._registerTrackPump(async w=>{let A=new ft(t),C={decoderConfig:await t.getDecoderConfig()??void 0},P=null;if(m)for await(let S of A.packets(m)){if(this._state==="canceled"||S.timestamp>=this._endTimestamp||this._copyBoundaryPolicy==="shrink"&&S.timestamp+S.duration>this._endTimestamp)break;let I=S.timestamp+this._timestampOffset;if(P!==null&&I{t(e).then(()=>{e.done=!0,e.resolvers.resolve()},r=>{e.resolvers.reject(r)})}};this._trackPumps.push(e)}async _checkpoint(t,e){for(;this._state!=="canceled"&&(e>=this._executionUntil||this._pauseRequested);){t.resolvers.resolve();let{promise:r,resolve:n}=J();t.wake=n,await r}}_reportProgress(t,e){if(!this._computeProgress)return;g(this._totalDuration!==null),this._maxTimestamps.set(t,Math.max(e,this._maxTimestamps.get(t)));let r=Math.min(...this._maxTimestamps.values()),n=ee(r/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n,r))}},Fa=class extends Error{constructor(t="Conversion has been canceled."){super(t),this.name="ConversionCanceledError"}},Cf=1,yl=class{constructor(t){this.maxTimestamps=new Map;this.resolvers=[];this.conversion=t}declareTrack(t){this.maxTimestamps.set(t,-1/0)}shouldWait(t,e){let r=this.maxTimestamps.get(t);g(r!==void 0),this.maxTimestamps.set(t,Math.max(e,r));let n=this.computeMinAndMaybeResolve();return this.conversion._state==="canceled"||this.conversion._pauseRequested||e>=this.conversion._executionUntil?!1:e-n>Cf}wait(t){let{promise:e,resolve:r}=J();return this.resolvers.push({timestamp:t,resolve:r}),e}closeTrack(t){this.maxTimestamps.delete(t),this.computeMinAndMaybeResolve()}resolveAll(){for(let t of this.resolvers)t.resolve();this.resolvers.length=0}computeMinAndMaybeResolve(){let t=1/0;for(let[,e]of this.maxTimestamps)t=Math.min(t,e);for(let e=0;e