@mediabunny/server 1.49.0 → 1.50.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,7 +12,7 @@
12
12
  By default, Mediabunny requires a browser environment for full access to decoders, encoders, and video processing features. `@mediabunny/server` uses [NodeAV](https://github.com/seydx/node-av) to polyfill this functionality for server-side environments such as Node, Bun, or Deno, enabling the usage of all Mediabunny features on the server. The result is a server-side media processing API that integrates naturally with TypeScript as opposed to the awkwardness and inefficiencies of calling out to the FFmpeg CLI.
13
13
 
14
14
  Features added by this package include:
15
- - Video decoders and encoders for AVC (H.264), HEVC (H.265), VP8, VP9, and AV1. Supports both length-prefixed and Annex B AVC/HEVC as well as transparent video via VP9.
15
+ - Video decoders and encoders for AVC (H.264), HEVC (H.265), VP8, VP9, AV1, and ProRes. Supports both length-prefixed and Annex B AVC/HEVC as well as transparent video via VP9 and ProRes.
16
16
  - Audio decoders and encoders for AAC, MP3, Vorbis, Opus, FLAC, AC-3 and E-AC-3. Supports AAC in both AAC and ADTS formats.
17
17
  - Video frame transformation support (resize, rotate, crop)
18
18
  - Automatic hardware acceleration on all platforms (macOS, Linux, Windows)
@@ -321,6 +321,8 @@ For encoding, video frames and audio samples are transferred to FFmpeg by conver
321
321
 
322
322
  Whenever possible, `AVFrame`s are never copied over to JavaScript unless explicitly needed. This enables zero-copy decode -> transformation -> encode paths.
323
323
 
324
+ ProRes decoding support is provided by [TurboRes](https://github.com/Vanilagy/turbores), as it is often faster than FFmpeg.
325
+
324
326
  ## License
325
327
 
326
328
  `@mediabunny/server` uses the same MPL-2.0 license as Mediabunny.
@@ -65,6 +65,7 @@ var MediabunnyServer = (() => {
65
65
  vp8: NodeAv.AV_CODEC_ID_VP8,
66
66
  vp9: NodeAv.AV_CODEC_ID_VP9,
67
67
  av1: NodeAv.AV_CODEC_ID_AV1,
68
+ prores: NodeAv.AV_CODEC_ID_PRORES,
68
69
  aac: NodeAv.AV_CODEC_ID_AAC,
69
70
  opus: NodeAv.AV_CODEC_ID_OPUS,
70
71
  mp3: NodeAv.AV_CODEC_ID_MP3,
@@ -537,6 +538,9 @@ var MediabunnyServer = (() => {
537
538
  }
538
539
  return ans;
539
540
  };
541
+ var assertNever = (x) => {
542
+ throw new Error(`Unexpected value: ${x}`);
543
+ };
540
544
  var SECOND_TO_MICROSECOND_FACTOR = 1e6 * (1 + Number.EPSILON);
541
545
  var simplifyRational = (rational) => {
542
546
  assert(Number.isInteger(rational.num));
@@ -1186,8 +1190,31 @@ var MediabunnyServer = (() => {
1186
1190
  ];
1187
1191
  var VP9_DEFAULT_SUFFIX = ".01.01.01.01.00";
1188
1192
  var AV1_DEFAULT_SUFFIX = ".0.110.01.01.01.0";
1193
+ var PRORES_FOURCCS = [
1194
+ "ap4x",
1195
+ // ProRes 4444 XQ
1196
+ "ap4h",
1197
+ // ProRes 4444
1198
+ "apch",
1199
+ // ProRes 422 High Quality
1200
+ "apcn",
1201
+ // ProRes 422 Standard Definition
1202
+ "apcs",
1203
+ // ProRes 422 LT
1204
+ "apco"
1205
+ // ProRes 422 Proxy
1206
+ ];
1189
1207
  var extractVideoCodecString = (trackInfo) => {
1190
- const { codec, codecDescription, colorSpace, avcCodecInfo, hevcCodecInfo, vp9CodecInfo, av1CodecInfo } = trackInfo;
1208
+ const {
1209
+ codec,
1210
+ codecDescription,
1211
+ colorSpace,
1212
+ avcCodecInfo,
1213
+ hevcCodecInfo,
1214
+ vp9CodecInfo,
1215
+ av1CodecInfo,
1216
+ proresFormat
1217
+ } = trackInfo;
1191
1218
  if (codec === "avc") {
1192
1219
  assert(trackInfo.avcType !== null);
1193
1220
  if (avcCodecInfo) {
@@ -1307,9 +1334,14 @@ var MediabunnyServer = (() => {
1307
1334
  string = string.slice(0, -AV1_DEFAULT_SUFFIX.length);
1308
1335
  }
1309
1336
  return string;
1337
+ } else if (codec === "prores") {
1338
+ return proresFormat ?? "apch";
1339
+ } else if (codec !== null) {
1340
+ assertNever(codec);
1310
1341
  }
1311
1342
  throw new TypeError(`Unhandled codec '${codec}'.`);
1312
1343
  };
1344
+ var VALID_VIDEO_CODEC_STRING_PREFIXES = ["avc1", "avc3", "hev1", "hvc1", "vp8", "vp09", "av01", ...PRORES_FOURCCS];
1313
1345
 
1314
1346
  // src/codec-data.ts
1315
1347
  var iterateNalUnitsInAnnexB = function* (packetData) {
@@ -2608,6 +2640,14 @@ var MediabunnyServer = (() => {
2608
2640
  var EAC3_REGISTRATION_DESCRIPTOR = new Uint8Array([5, 4, 69, 65, 67, 51]);
2609
2641
 
2610
2642
  // packages/server/src/video-encoder.ts
2643
+ var PRORES_FOURCC_TO_PROFILE = {
2644
+ apco: NodeAv4.AV_PROFILE_PRORES_PROXY,
2645
+ apcs: NodeAv4.AV_PROFILE_PRORES_LT,
2646
+ apcn: NodeAv4.AV_PROFILE_PRORES_STANDARD,
2647
+ apch: NodeAv4.AV_PROFILE_PRORES_HQ,
2648
+ ap4h: NodeAv4.AV_PROFILE_PRORES_4444,
2649
+ ap4x: NodeAv4.AV_PROFILE_PRORES_XQ
2650
+ };
2611
2651
  var NodeAvVideoEncoder = class extends import_mediabunny3.CustomVideoEncoder {
2612
2652
  constructor() {
2613
2653
  super(...arguments);
@@ -2621,7 +2661,7 @@ var MediabunnyServer = (() => {
2621
2661
  this.preciseTimings = [];
2622
2662
  }
2623
2663
  static supports(codec, config) {
2624
- return (codec === "avc" || codec === "hevc" || codec === "vp8" || codec === "vp9" || codec === "av1") && config.bitrateMode !== "quantizer";
2664
+ return (codec === "avc" || codec === "hevc" || codec === "vp8" || codec === "vp9" || codec === "av1" || codec === "prores") && config.bitrateMode !== "quantizer";
2625
2665
  }
2626
2666
  async init() {
2627
2667
  this.frame = new NodeAv4.Frame();
@@ -2631,13 +2671,22 @@ var MediabunnyServer = (() => {
2631
2671
  this.packet.alloc();
2632
2672
  const codecId = CODEC_TO_CODEC_ID[this.codec];
2633
2673
  assert(codecId !== void 0);
2674
+ const getSoftwareCodec = () => {
2675
+ if (this.codec === "prores") {
2676
+ const proresKs = NodeAv4.Codec.findEncoderByName(NodeAv4.FF_ENCODER_PRORES_KS);
2677
+ if (proresKs) {
2678
+ return proresKs;
2679
+ }
2680
+ }
2681
+ return NodeAv4.Codec.findEncoder(codecId);
2682
+ };
2634
2683
  let codec = null;
2635
2684
  if (this.codec === "vp9" && this.config.alpha === "keep") {
2636
2685
  codec = NodeAv4.Codec.findEncoderByName(NodeAv4.FF_ENCODER_LIBVPX_VP9) ?? NodeAv4.Codec.findEncoder(codecId);
2637
2686
  } else if (this.config.hardwareAcceleration === "prefer-software") {
2638
- codec = NodeAv4.Codec.findEncoder(codecId);
2687
+ codec = getSoftwareCodec();
2639
2688
  } else {
2640
- codec = await getHardwareEncoderCodec(codecId) ?? NodeAv4.Codec.findEncoder(codecId);
2689
+ codec = await getHardwareEncoderCodec(codecId) ?? getSoftwareCodec();
2641
2690
  }
2642
2691
  if (!codec) {
2643
2692
  throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);
@@ -2654,8 +2703,15 @@ var MediabunnyServer = (() => {
2654
2703
  if (!this.avCodec.pixelFormats.includes(NodeAv4.AV_PIX_FMT_YUV420P)) {
2655
2704
  pixelFormat = this.avCodec.pixelFormats[0];
2656
2705
  }
2657
- if (this.config.alpha === "keep" && this.avCodec.pixelFormats.includes(NodeAv4.AV_PIX_FMT_YUVA420P)) {
2658
- pixelFormat = NodeAv4.AV_PIX_FMT_YUVA420P;
2706
+ if (this.config.alpha === "keep") {
2707
+ if (this.avCodec.pixelFormats.includes(NodeAv4.AV_PIX_FMT_YUVA420P)) {
2708
+ pixelFormat = NodeAv4.AV_PIX_FMT_YUVA420P;
2709
+ } else {
2710
+ pixelFormat = NodeAv4.avcodecFindBestPixFmtOfList(
2711
+ this.avCodec.pixelFormats,
2712
+ NodeAv4.AV_PIX_FMT_YUVA444P12LE
2713
+ );
2714
+ }
2659
2715
  }
2660
2716
  }
2661
2717
  const pixelAspectRatio = simplifyRational({
@@ -2708,6 +2764,11 @@ var MediabunnyServer = (() => {
2708
2764
  codecContext.setOption("preset", "12");
2709
2765
  }
2710
2766
  }
2767
+ if (this.codec === "prores") {
2768
+ const profile = PRORES_FOURCC_TO_PROFILE[this.config.codec];
2769
+ assert(profile !== void 0);
2770
+ codecContext.setOption("profile", String(profile));
2771
+ }
2711
2772
  const ret = await codecContext.open2();
2712
2773
  NodeAv4.FFmpegError.throwIfError(ret, "Open codec context");
2713
2774
  this.codecContext = codecContext;
@@ -2858,7 +2919,8 @@ var MediabunnyServer = (() => {
2858
2919
  avcCodecInfo: null,
2859
2920
  hevcCodecInfo: null,
2860
2921
  vp9CodecInfo: null,
2861
- av1CodecInfo: null
2922
+ av1CodecInfo: null,
2923
+ proresFormat: null
2862
2924
  });
2863
2925
  if (!expectsAnnexB) {
2864
2926
  decoderConfigDescription = serializedRecord;
@@ -2911,7 +2973,8 @@ var MediabunnyServer = (() => {
2911
2973
  avcCodecInfo: null,
2912
2974
  hevcCodecInfo: null,
2913
2975
  vp9CodecInfo: null,
2914
- av1CodecInfo: null
2976
+ av1CodecInfo: null,
2977
+ proresFormat: null
2915
2978
  });
2916
2979
  }
2917
2980
  } else if (this.codec === "vp9") {
@@ -2927,7 +2990,8 @@ var MediabunnyServer = (() => {
2927
2990
  avcCodecInfo: null,
2928
2991
  hevcCodecInfo: null,
2929
2992
  vp9CodecInfo,
2930
- av1CodecInfo: null
2993
+ av1CodecInfo: null,
2994
+ proresFormat: null
2931
2995
  });
2932
2996
  }
2933
2997
  } else if (this.codec === "av1") {
@@ -2943,7 +3007,24 @@ var MediabunnyServer = (() => {
2943
3007
  avcCodecInfo: null,
2944
3008
  hevcCodecInfo: null,
2945
3009
  vp9CodecInfo: null,
2946
- av1CodecInfo
3010
+ av1CodecInfo,
3011
+ proresFormat: null
3012
+ });
3013
+ }
3014
+ } else if (this.codec === "prores") {
3015
+ if (!this.packetEmitted) {
3016
+ decoderConfigCodecString = extractVideoCodecString({
3017
+ width: this.config.width,
3018
+ height: this.config.height,
3019
+ codec: "prores",
3020
+ codecDescription: null,
3021
+ colorSpace: null,
3022
+ avcType: null,
3023
+ avcCodecInfo: null,
3024
+ hevcCodecInfo: null,
3025
+ vp9CodecInfo: null,
3026
+ av1CodecInfo: null,
3027
+ proresFormat: this.config.codec
2947
3028
  });
2948
3029
  }
2949
3030
  } else {
@@ -3433,6 +3514,7 @@ var MediabunnyServer = (() => {
3433
3514
  };
3434
3515
 
3435
3516
  // packages/server/src/index.ts
3517
+ var import_prores = __require("@mediabunny/prores");
3436
3518
  var SERVER_LOADED_SYMBOL = Symbol.for("@mediabunny/server loaded");
3437
3519
  if (globalThis[SERVER_LOADED_SYMBOL]) {
3438
3520
  import_mediabunny7.Logging._error(
@@ -3458,6 +3540,7 @@ var MediabunnyServer = (() => {
3458
3540
  _serverOptions = options;
3459
3541
  NodeAv8.Log.setLevel(NodeAv8.AV_LOG_ERROR);
3460
3542
  (0, import_mediabunny7.registerDecoder)(NodeAvVideoDecoder);
3543
+ (0, import_prores.registerProresDecoder)();
3461
3544
  (0, import_mediabunny7.registerEncoder)(NodeAvVideoEncoder);
3462
3545
  (0, import_mediabunny7.registerDecoder)(NodeAvAudioDecoder);
3463
3546
  (0, import_mediabunny7.registerEncoder)(NodeAvAudioEncoder);
@@ -5,6 +5,6 @@
5
5
  * License, v. 2.0. If a copy of the MPL was not distributed with this
6
6
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
7
  */
8
- "use strict";var MediabunnyServer=(()=>{var bt=Object.create;var me=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var yt=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var M=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var _t=(t,e)=>{for(var r in e)me(t,r,{get:e[r],enumerable:!0})},Oe=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of vt(e))!Et.call(t,n)&&n!==r&&me(t,n,{get:()=>e[n],enumerable:!(i=xt(e,n))||i.enumerable});return t};var $=(t,e,r)=>(r=t!=null?bt(yt(t)):{},Oe(e||!t||!t.__esModule?me(r,"default",{value:t,enumerable:!0}):r,t)),wt=t=>Oe(me({},"__esModule",{value:!0}),t);var Gt={};_t(Gt,{AvFrameAudioSampleResource:()=>Q,AvFrameVideoSampleResource:()=>q,_serverOptions:()=>Y,registerMediabunnyServer:()=>qt,toAvFrame:()=>Wt});var k=M("mediabunny"),G=$(M("node-av"));var xe=M("mediabunny"),b=$(M("node-av"));var o=$(M("node-av"));var J={avc:o.AV_CODEC_ID_H264,hevc:o.AV_CODEC_ID_HEVC,vp8:o.AV_CODEC_ID_VP8,vp9:o.AV_CODEC_ID_VP9,av1:o.AV_CODEC_ID_AV1,aac:o.AV_CODEC_ID_AAC,opus:o.AV_CODEC_ID_OPUS,mp3:o.AV_CODEC_ID_MP3,vorbis:o.AV_CODEC_ID_VORBIS,flac:o.AV_CODEC_ID_FLAC,ac3:o.AV_CODEC_ID_AC3,eac3:o.AV_CODEC_ID_EAC3},Be,He=()=>Y.hardwareContext!==void 0&&typeof Y.hardwareContext!="function"?Y.hardwareContext:(Be===void 0&&(Be=o.HardwareContext.auto()),Be),ze=t=>{if(t!==null&&!(t instanceof o.HardwareContext))throw new TypeError("When serverOptions.hardwareContext is a function, it must return or resolve to a NodeAv.HardwareContext or null.")},Te=new Map,qe=async t=>{if(typeof Y.hardwareContext=="function"){let e=await Y.hardwareContext(t);return ze(e),e?.getDecoderCodec(t)??null}if(!Te.has(t)){let e=He();Te.set(t,e?.getDecoderCodec(t)??null)}return Te.get(t)},Pe=new Map,We=async t=>{if(typeof Y.hardwareContext=="function"){let e=await Y.hardwareContext(t);return ze(e),e?.getEncoderCodec(t)??null}if(!Pe.has(t)){let e=He();Pe.set(t,e?.getEncoderCodec(t)??null)}return Pe.get(t)},Ge=t=>{switch(t){case"bt709":return o.AVCOL_PRI_BT709;case"bt470bg":return o.AVCOL_PRI_BT470BG;case"smpte170m":return o.AVCOL_PRI_SMPTE170M;case"bt2020":return o.AVCOL_PRI_BT2020;case"smpte432":return o.AVCOL_PRI_SMPTE432}return null},fe=t=>{switch(t){case o.AVCOL_PRI_BT709:return"bt709";case o.AVCOL_PRI_BT470BG:return"bt470bg";case o.AVCOL_PRI_SMPTE170M:return"smpte170m";case o.AVCOL_PRI_BT2020:return"bt2020";case o.AVCOL_PRI_SMPTE432:return"smpte432"}return null},Xe=t=>{switch(t){case"bt709":return o.AVCOL_TRC_BT709;case"smpte170m":return o.AVCOL_TRC_SMPTE170M;case"iec61966-2-1":return o.AVCOL_TRC_IEC61966_2_1;case"linear":return o.AVCOL_TRC_LINEAR;case"pq":return o.AVCOL_TRC_SMPTE2084;case"hlg":return o.AVCOL_TRC_ARIB_STD_B67}return null},pe=t=>{switch(t){case o.AVCOL_TRC_BT709:return"bt709";case o.AVCOL_TRC_SMPTE170M:return"smpte170m";case o.AVCOL_TRC_IEC61966_2_1:return"iec61966-2-1";case o.AVCOL_TRC_LINEAR:return"linear";case o.AVCOL_TRC_SMPTE2084:return"pq";case o.AVCOL_TRC_ARIB_STD_B67:return"hlg"}return null},Ye=t=>{switch(t){case"rgb":return o.AVCOL_SPC_RGB;case"bt709":return o.AVCOL_SPC_BT709;case"bt470bg":return o.AVCOL_SPC_BT470BG;case"smpte170m":return o.AVCOL_SPC_SMPTE170M;case"bt2020-ncl":return o.AVCOL_SPC_BT2020_NCL}return null},he=t=>{switch(t){case o.AVCOL_SPC_RGB:return"rgb";case o.AVCOL_SPC_BT709:return"bt709";case o.AVCOL_SPC_BT470BG:return"bt470bg";case o.AVCOL_SPC_SMPTE170M:return"smpte170m";case o.AVCOL_SPC_BT2020_NCL:return"bt2020-ncl"}return null},Ke=t=>{switch(t){case o.AV_PIX_FMT_YUV420P:return"I420";case o.AV_PIX_FMT_YUVJ420P:return"I420";case o.AV_PIX_FMT_YUV420P10LE:return"I420P10";case o.AV_PIX_FMT_YUV420P12LE:return"I420P12";case o.AV_PIX_FMT_YUVA420P:return"I420A";case o.AV_PIX_FMT_YUVA420P10LE:return"I420AP10";case o.AV_PIX_FMT_YUV422P:return"I422";case o.AV_PIX_FMT_YUVJ422P:return"I422";case o.AV_PIX_FMT_YUV422P10LE:return"I422P10";case o.AV_PIX_FMT_YUV422P12LE:return"I422P12";case o.AV_PIX_FMT_YUVA422P:return"I422A";case o.AV_PIX_FMT_YUVA422P10LE:return"I422AP10";case o.AV_PIX_FMT_YUVA422P12LE:return"I422AP12";case o.AV_PIX_FMT_YUV444P:return"I444";case o.AV_PIX_FMT_YUVJ444P:return"I444";case o.AV_PIX_FMT_YUV444P10LE:return"I444P10";case o.AV_PIX_FMT_YUV444P12LE:return"I444P12";case o.AV_PIX_FMT_YUVA444P:return"I444A";case o.AV_PIX_FMT_YUVA444P10LE:return"I444AP10";case o.AV_PIX_FMT_YUVA444P12LE:return"I444AP12";case o.AV_PIX_FMT_NV12:return"NV12";case o.AV_PIX_FMT_RGBA:return"RGBA";case o.AV_PIX_FMT_RGB0:return"RGBX";case o.AV_PIX_FMT_BGRA:return"BGRA";case o.AV_PIX_FMT_BGR0:return"BGRX";default:return null}},Fe=t=>{switch(t){case"I420":return o.AV_PIX_FMT_YUV420P;case"I420P10":return o.AV_PIX_FMT_YUV420P10LE;case"I420P12":return o.AV_PIX_FMT_YUV420P12LE;case"I420A":return o.AV_PIX_FMT_YUVA420P;case"I420AP10":return o.AV_PIX_FMT_YUVA420P10LE;case"I422":return o.AV_PIX_FMT_YUV422P;case"I422P10":return o.AV_PIX_FMT_YUV422P10LE;case"I422P12":return o.AV_PIX_FMT_YUV422P12LE;case"I422A":return o.AV_PIX_FMT_YUVA422P;case"I422AP10":return o.AV_PIX_FMT_YUVA422P10LE;case"I422AP12":return o.AV_PIX_FMT_YUVA422P12LE;case"I444":return o.AV_PIX_FMT_YUV444P;case"I444P10":return o.AV_PIX_FMT_YUV444P10LE;case"I444P12":return o.AV_PIX_FMT_YUV444P12LE;case"I444A":return o.AV_PIX_FMT_YUVA444P;case"I444AP10":return o.AV_PIX_FMT_YUVA444P10LE;case"I444AP12":return o.AV_PIX_FMT_YUVA444P12LE;case"NV12":return o.AV_PIX_FMT_NV12;case"RGBA":return o.AV_PIX_FMT_RGBA;case"RGBX":return o.AV_PIX_FMT_RGB0;case"BGRA":return o.AV_PIX_FMT_BGRA;case"BGRX":return o.AV_PIX_FMT_BGR0;default:return o.AV_PIX_FMT_NONE}},Qe=t=>{switch(t){case o.AV_SAMPLE_FMT_U8:return"u8";case o.AV_SAMPLE_FMT_S16:return"s16";case o.AV_SAMPLE_FMT_S32:return"s32";case o.AV_SAMPLE_FMT_FLT:return"f32";case o.AV_SAMPLE_FMT_U8P:return"u8-planar";case o.AV_SAMPLE_FMT_S16P:return"s16-planar";case o.AV_SAMPLE_FMT_S32P:return"s32-planar";case o.AV_SAMPLE_FMT_FLTP:return"f32-planar";default:return null}},Je=t=>{switch(t){case"u8":return o.AV_SAMPLE_FMT_U8;case"s16":return o.AV_SAMPLE_FMT_S16;case"s32":return o.AV_SAMPLE_FMT_S32;case"f32":return o.AV_SAMPLE_FMT_FLT;case"u8-planar":return o.AV_SAMPLE_FMT_U8P;case"s16-planar":return o.AV_SAMPLE_FMT_S16P;case"s32-planar":return o.AV_SAMPLE_FMT_S32P;case"f32-planar":return o.AV_SAMPLE_FMT_FLTP;default:return o.AV_SAMPLE_FMT_NONE}},Z=t=>{switch(t){case 1:return o.AV_CHANNEL_LAYOUT_MONO;case 2:return o.AV_CHANNEL_LAYOUT_STEREO;case 4:return o.AV_CHANNEL_LAYOUT_QUAD;case 6:return o.AV_CHANNEL_LAYOUT_5POINT1_BACK;case 8:return o.AV_CHANNEL_LAYOUT_7POINT1;default:return{nbChannels:t,order:o.AV_CHANNEL_ORDER_UNSPEC,mask:0n}}};var U=class U{constructor(){}static get level(){return U._level}static set level(e){if(e!==0&&e!==1&&e!==2&&e!==3)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");U._level=e}static get _emitter(){return U._emitterInstance??=new ge}static on(e,r,i){return U._emitter.on(e,r,i)}static _error(...e){U._emitter._emit("error",e),U._level>=1&&console.error(...e)}static _warn(...e){U._emitter._emit("warn",e),U._level>=2&&console.warn(...e)}static _info(...e){U._emitter._emit("info",e),U._level>=3&&console.info(...e)}};U._level=3,U._emitterInstance=null;var te=U;function p(t){if(!t)throw new Error("Assertion failed.")}var ne=t=>t&&t[t.length-1];var l=t=>{let e=0;for(;t.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},K=t=>{let e=l(t);return(e&1)===0?-(e>>1):e+1>>1};var L=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),Re=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t);var je={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12};var $e={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18};var Ze={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9};var Ve=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join("");var Ne=t=>(t=t>>1&1431655765|(t&1431655765)<<1,t=t>>2&858993459|(t&858993459)<<2,t=t>>4&252645135|(t&252645135)<<4,t=t>>8&16711935|(t&16711935)<<8,t=t>>16&65535|(t&65535)<<16,t>>>0);var oe=(t,e,r)=>{let i=0,n=t.length-1,s=-1;for(;i<=n;){let a=i+(n-i+1)/2|0;r(t[a])<=e?(s=a,i=a+1):n=a-1}return s};var jt=1e6*(1+Number.EPSILON);var Ce=t=>{p(Number.isInteger(t.num)),p(Number.isInteger(t.den)),p(t.den!==0);let e=Math.abs(t.num),r=Math.abs(t.den);for(;r!==0;){let n=e%r;e=r,r=n}let i=e||1;return{num:t.num/i,den:t.den/i}};var ge=class{constructor(){this._listeners=new Map}on(e,r,i){this._listeners.has(e)||this._listeners.set(e,new Set);let n={fn:r,once:i?.once??!1};return this._listeners.get(e).add(n),()=>{this._listeners.get(e)?.delete(n)}}_emit(...e){let[r,i]=e,n=this._listeners.get(r);if(n)for(let s of n){try{s.fn(i)}catch(a){console.error(a)}s.once&&n.delete(s)}}};var re=M("mediabunny"),f=$(M("node-av"));var St=new Set([f.AV_PIX_FMT_YUVJ411P,f.AV_PIX_FMT_YUVJ420P,f.AV_PIX_FMT_YUVJ422P,f.AV_PIX_FMT_YUVJ440P,f.AV_PIX_FMT_YUVJ444P]),q=class t extends re.VideoSampleResource{get frame(){if(!this._frame)throw new Error("AvFrameVideoSampleResource has been closed.");return this._frame}constructor(e){if(super(),!(e instanceof f.Frame))throw new TypeError("frame must be a NodeAv.Frame.");if(e.getMediaType()!==f.AVMEDIA_TYPE_VIDEO)throw new Error("AvFrameVideoSampleResource must be initialized with a video frame.");this._frame=e}getFormat(){return Ke(this.frame.format)}getCodedWidth(){return this.frame.width}getCodedHeight(){return this.frame.height}getSquarePixelWidth(){return this.frame.sampleAspectRatio.num>this.frame.sampleAspectRatio.den?Math.round(this.frame.width*this.frame.sampleAspectRatio.num/this.frame.sampleAspectRatio.den):this.frame.width}getSquarePixelHeight(){return this.frame.sampleAspectRatio.num>this.frame.sampleAspectRatio.den?this.frame.height:Math.round(this.frame.height*this.frame.sampleAspectRatio.den/this.frame.sampleAspectRatio.num)}getColorSpace(){return new re.VideoSampleColorSpace({primaries:fe(this.frame.colorPrimaries),transfer:pe(this.frame.colorTrc),matrix:he(this.frame.colorSpace),fullRange:this.frame.colorRange===f.AVCOL_RANGE_JPEG||St.has(this.frame.format)?!0:this.frame.colorRange===f.AVCOL_RANGE_MPEG?!1:null})}close(){this.frame.free(),this._frame=null}getDataPlanes(){return p(this.frame.data),this.frame.data.map((e,r)=>({data:L(e),stride:this.frame.linesize[r]}))}async toRgbSample(e,r){let i=this.frame.width,n=this.frame.height,s=new f.SoftwareScaleContext,a=this.frame.format,A=Fe("RGBA");s.getContext(i,n,a,i,n,A,f.SWS_BILINEAR);let u=new f.Frame;u.width=i,u.height=n,u.format=A,u.alloc(),u.allocBuffer();let d=this.frame;try{await s.scaleFrame(u,d)}finally{s.freeContext()}return u.sampleAspectRatio=d.sampleAspectRatio,new re.VideoSample(new t(u),e)}},de=async(t,e,r)=>{p(t.format!==null),e.format=Fe(t.format),e.width=t.codedWidth,e.height=t.codedHeight,e.sampleAspectRatio=new f.Rational(t.pixelAspectRatio.num,t.pixelAspectRatio.den),e.colorPrimaries=Ge(t.colorSpace.primaries??"unknown")??f.AVCOL_PRI_UNSPECIFIED,e.colorSpace=Ye(t.colorSpace.matrix??"unknown")??f.AVCOL_SPC_UNSPECIFIED,e.colorTrc=Xe(t.colorSpace.transfer??"unknown")??f.AVCOL_TRC_UNSPECIFIED,e.colorRange=t.colorSpace.fullRange===!1?f.AVCOL_RANGE_MPEG:t.colorSpace.fullRange===!0?f.AVCOL_RANGE_JPEG:f.AVCOL_RANGE_UNSPECIFIED;let i=t.allocationSize();return(!r||r.byteLength!==i)&&(r=Buffer.from({length:i})),await t.copyTo(r),e.fromBuffer(r),r},et=async(t,e)=>{let r,i=!1;if(t._data instanceof q)r=t._data.frame;else{if(t.format===null)return null;r=new f.Frame,r.alloc(),i=!0,await de(t,r,null)}let n=[];(t.squarePixelWidth!==t.codedWidth||t.squarePixelHeight!==t.codedHeight)&&(n.push(`scale=${t.squarePixelWidth}:${t.squarePixelHeight}`),n.push("setsar=1")),e.rotation===90?n.push("transpose=1"):e.rotation===180?n.push("transpose=1,transpose=1"):e.rotation===270&&n.push("transpose=2"),n.push(`crop=${Math.round(e.crop.width)}:${Math.round(e.crop.height)}:${Math.round(e.crop.left)}:${Math.round(e.crop.top)}`),e.fit==="fill"?n.push(`scale=${e.width}:${e.height}`):e.fit==="contain"?(n.push(`scale=${e.width}:${e.height}:force_original_aspect_ratio=decrease`),n.push(`pad=${e.width}:${e.height}:(ow-iw)/2:(oh-ih)/2:color=black@0`)):e.fit==="cover"&&(n.push(`scale=${e.width}:${e.height}:force_original_aspect_ratio=increase`),n.push(`crop=${e.width}:${e.height}`)),n.push("setsar=1");let s=new f.FilterGraph;s.alloc();try{let a=`video_size=${r.width}x${r.height}:pix_fmt=${r.format}:time_base=1/1000000:pixel_aspect=${t.pixelAspectRatio.num}/${t.pixelAspectRatio.den}`,A=s.createFilter(f.Filter.getByName("buffer"),"src",a),u=s.createFilter(f.Filter.getByName("buffersink"),"sink");p(A&&u);let d=f.FilterInOut.createList([{name:"in",filterCtx:A,padIdx:0}]),c=f.FilterInOut.createList([{name:"out",filterCtx:u,padIdx:0}]),h=s.parsePtr(`[in]${n.join(",")}[out]`,c,d);f.FFmpegError.throwIfError(h,"FilterGraph.parsePtr");let _=await s.config();f.FFmpegError.throwIfError(_,"FilterGraph.config");let w=await A.buffersrcAddFrame(r);f.FFmpegError.throwIfError(w,"buffersrcAddFrame"),await A.buffersrcAddFrame(null);let g=new f.Frame;g.alloc();let x=await u.buffersinkGetFrame(g);return f.FFmpegError.throwIfError(x,"buffersinkGetFrame"),new re.VideoSample(new q(g),{timestamp:t.timestamp,duration:t.duration,rotation:0})}finally{s.free(),i&&r.free()}};var be=class extends xe.CustomVideoDecoder{constructor(){super(...arguments);this.codecContext=null;this.preciseTimings=[]}static supports(r,i){return r==="avc"||r==="hevc"||r==="vp8"||r==="vp9"||r==="av1"}async init(){this.frame=new b.Frame,this.frame.alloc(),this.packet=new b.Packet,this.packet.alloc()}async initCodecContext(r){p(this.codecContext===null);let i=J[this.codec];p(i!==void 0);let n;if(this.codec==="vp9"&&r.sideData.alpha?n=b.Codec.findDecoderByName(b.FF_DECODER_LIBVPX_VP9)??b.Codec.findDecoder(i):this.config.hardwareAcceleration==="prefer-software"||this.codec==="av1"?n=b.Codec.findDecoder(i):n=await qe(i)??b.Codec.findDecoder(i),!n)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);let s=new b.CodecContext;s.allocContext3(n),this.pixelAspectRatio=Ce({num:(this.config.displayAspectWidth??this.config.codedWidth??0)*(this.config.codedHeight??0),den:(this.config.displayAspectHeight??this.config.codedHeight??0)*(this.config.codedWidth??0)||1}),s.width=this.config.codedWidth??0,s.height=this.config.codedHeight??0,s.codecType=b.AVMEDIA_TYPE_VIDEO,s.codecId=i,s.extraData=this.config.description?Buffer.from(L(this.config.description)):null,s.sampleAspectRatio=new b.Rational(this.pixelAspectRatio.num,this.pixelAspectRatio.den);let a=await s.open2();b.FFmpegError.throwIfError(a,"Open codec context"),this.codecContext=s}async decode(r){if(this.codecContext===null&&await this.initCodecContext(r),p(this.codecContext),this.packet.isKeyframe=r.type==="key",this.packet.data=Buffer.from(r.data),this.packet.timeBase={num:1,den:1e6},this.packet.pts=BigInt(r.microsecondTimestamp),this.packet.dts=b.AV_NOPTS_VALUE,this.packet.duration=BigInt(r.microsecondDuration),r.sideData.alpha){let a=Buffer.alloc(8+r.sideData.alpha.byteLength);a[7]=1,a.set(r.sideData.alpha,8),this.packet.addSideData(b.AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,a)}let i=oe(this.preciseTimings,r.microsecondTimestamp,a=>a.microsecondTimestamp),n=i!==-1?this.preciseTimings[i]:null;n&&n.microsecondTimestamp===r.microsecondTimestamp?(n.timestamp!==r.timestamp&&(n.timestampIsValid=!1),n.duration!==r.duration&&(n.durationIsValid=!1)):(this.preciseTimings.splice(i+1,0,{microsecondTimestamp:r.microsecondTimestamp,timestamp:r.timestamp,duration:r.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift());let s=await this.codecContext.sendPacket(this.packet);for(b.FFmpegError.throwIfError(s,"Send packet"),this.packet.unref();;){let a=await this.codecContext.receiveFrame(this.frame);if(a===b.AVERROR_EAGAIN||a===b.AVERROR_EOF)break;this.receiveFrame(a)}}receiveFrame(r){b.FFmpegError.throwIfError(r,"Receive frame"),this.frame.sampleAspectRatio=new b.Rational(this.pixelAspectRatio.num,this.pixelAspectRatio.den);let i=Number(this.frame.pts)/1e6,n=Number(this.frame.duration)/1e6,s=oe(this.preciseTimings,Number(this.frame.pts),u=>u.microsecondTimestamp),a=s!==-1?this.preciseTimings[s]:null;a&&a.microsecondTimestamp===Number(this.frame.pts)&&(a.timestampIsValid&&(i=a.timestamp),a.durationIsValid&&(n=a.duration));let A=this.frame.clone();if(!A)throw new Error("Frame clone allocation failed.");this.onSample(new xe.VideoSample(new q(A),{timestamp:i,duration:n}))}async flush(){if(!this.codecContext)return;let r=await this.codecContext.sendPacket(null);for(b.FFmpegError.throwIfError(r,"Flush decoder");;){let i=await this.codecContext.receiveFrame(this.frame);if(i===b.AVERROR_EAGAIN||i===b.AVERROR_EOF)break;this.receiveFrame(i)}this.codecContext.flushBuffers()}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free()}};var se=M("mediabunny"),m=$(M("node-av"));var W=class t{constructor(e){this.bytes=e;this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),r=this.bytes[e]??0,i=7-(this.pos&7),n=(r&1<<i)>>i;return this.pos++,n}readBits(e){if(e===1)return this.readBit();let r=0;for(let i=0;i<e;i++)r<<=1,r|=this.readBit();return r}writeBits(e,r){let i=this.pos+e;for(let n=this.pos;n<i;n++){let s=Math.floor(n/8),a=this.bytes[s],A=7-(n&7);a&=~(1<<A),a|=(r&1<<i-n-1)>>i-n-1<<A,this.bytes[s]=a}this.pos=i}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,r=this.bytes[e]??0;return this.pos+=8,r}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new t(this.bytes);return e.pos=this.pos,e}};var tt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],It=[-1,1,2,3,4,5,6,8],rt=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new W(t),r=e.readBits(5);r===31&&(r=32+e.readBits(6));let i=e.readBits(4),n=null;i===15?n=e.readBits(24):i<tt.length&&(n=tt[i]);let s=e.readBits(4),a=null;return s>=1&&s<=7&&(a=It[s]),{objectType:r,frequencyIndex:i,sampleRate:n,channelConfiguration:s,numberOfChannels:a}};var it=t=>{let e=new Uint8Array(7),r=new W(e),{objectType:i,frequencyIndex:n,channelConfiguration:s}=t,a=i-1;return r.writeBits(12,4095),r.writeBits(1,0),r.writeBits(2,0),r.writeBits(1,1),r.writeBits(2,a),r.writeBits(4,n),r.writeBits(1,0),r.writeBits(3,s),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.skipBits(13),r.writeBits(11,2047),r.writeBits(2,0),{header:e,bitstream:r}};var Tt=["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"],Pt=["aac","opus","mp3","vorbis","flac","ac3","eac3"],br=[...Pt,...Tt];var Me=[{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}];var ie=[{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}];var nt=".01.01.01.01.00",ot=".0.110.01.01.01.0";var Ae=t=>{let{codec:e,codecDescription:r,colorSpace:i,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:A}=t;if(e==="avc"){if(p(t.avcType!==null),n){let u=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${t.avcType}.${Ve(u)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${t.avcType}.${Ve(r.subarray(1,4))}`}else if(e==="hevc"){let u,d,c,h,_,w;if(s)u=s.generalProfileSpace,d=s.generalProfileIdc,c=Ne(s.generalProfileCompatibilityFlags),h=s.generalTierFlag,_=s.generalLevelIdc,w=[...s.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let x=Re(r),C=x.getUint8(1);u=C>>6&3,d=C&31,c=Ne(x.getUint32(2)),h=C>>5&1,_=x.getUint8(12),w=[];for(let T=0;T<6;T++)w.push(x.getUint8(6+T))}let g="hev1.";for(g+=["","A","B","C"][u]+d,g+=".",g+=c.toString(16).toUpperCase(),g+=".",g+=h===0?"L":"H",g+=_;w.length>0&&w[w.length-1]===0;)w.pop();return w.length>0&&(g+=".",g+=w.map(x=>x.toString(16).toUpperCase()).join(".")),g}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){let T=t.width*t.height,y=ne(ie).level;for(let P of ie)if(T<=P.maxPictureSize){y=P.level;break}return`vp09.00.${y.toString().padStart(2,"0")}.08`}let u=a.profile.toString().padStart(2,"0"),d=a.level.toString().padStart(2,"0"),c=a.bitDepth.toString().padStart(2,"0"),h=a.chromaSubsampling.toString().padStart(2,"0"),_=a.colourPrimaries.toString().padStart(2,"0"),w=a.transferCharacteristics.toString().padStart(2,"0"),g=a.matrixCoefficients.toString().padStart(2,"0"),x=a.videoFullRangeFlag.toString().padStart(2,"0"),C=`vp09.${u}.${d}.${c}.${h}`;return C+=`.${_}.${w}.${g}.${x}`,C.endsWith(nt)&&(C=C.slice(0,-nt.length)),C}else if(e==="av1"){if(!A){let P=t.width*t.height,V=ne(ie).level;for(let S of ie)if(P<=S.maxPictureSize){V=S.level;break}return`av01.0.${V.toString().padStart(2,"0")}M.08`}let u=A.profile,d=A.level.toString().padStart(2,"0"),c=A.tier?"H":"M",h=A.bitDepth.toString().padStart(2,"0"),_=A.monochrome?"1":"0",w=100*A.chromaSubsamplingX+10*A.chromaSubsamplingY+1*(A.chromaSubsamplingX&&A.chromaSubsamplingY?A.chromaSamplePosition:0),g=i?.primaries?je[i.primaries]:1,x=i?.transfer?$e[i.transfer]:1,C=i?.matrix?Ze[i.matrix]:1,T=i?.fullRange?1:0,y=`av01.${u}.${d}${c}.${h}`;return y+=`.${_}.${w.toString().padStart(3,"0")}`,y+=`.${g.toString().padStart(2,"0")}`,y+=`.${x.toString().padStart(2,"0")}`,y+=`.${C.toString().padStart(2,"0")}`,y+=`.${T}`,y.endsWith(ot)&&(y=y.slice(0,-ot.length)),y}}throw new TypeError(`Unhandled codec '${e}'.`)};var ye=function*(t){let e=0,r=-1;for(;e<t.length-2;){let i=t.indexOf(0,e);if(i===-1||i>=t.length-2)break;e=i;let n=0;if(e+3<t.length&&t[e+1]===0&&t[e+2]===0&&t[e+3]===1?n=4:t[e+1]===0&&t[e+2]===1&&(n=3),n===0){e++;continue}r!==-1&&e>r&&(yield{offset:r,length:e-r}),r=e+n,e=r}r!==-1&&r<t.length&&(yield{offset:r,length:t.length-r})};var ke=t=>t&31,Ue=t=>{let e=[],r=t.length;for(let i=0;i<r;i++)i+2<r&&t[i]===0&&t[i+1]===0&&t[i+2]===3?(e.push(0,0),i+=2):e.push(t[i]);return new Uint8Array(e)},kr=new Uint8Array([0,0,0,1]);var ct=t=>{try{let e=[],r=[],i=[];for(let A of ye(t)){let u=t.subarray(A.offset,A.offset+A.length),d=ke(u[0]);d===7?e.push(u):d===8?r.push(u):d===13&&i.push(u)}if(e.length===0||r.length===0)return null;let n=e[0],s=Ft(n);p(s!==null);let a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:r,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?i:null}}catch(e){return te._error("Error building AVC Decoder Configuration Record:",e),null}},lt=t=>{let e=[];e.push(t.configurationVersion),e.push(t.avcProfileIndication),e.push(t.profileCompatibility),e.push(t.avcLevelIndication),e.push(252|t.lengthSizeMinusOne&3),e.push(224|t.sequenceParameterSets.length&31);for(let r of t.sequenceParameterSets){let i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}e.push(t.pictureParameterSets.length);for(let r of t.pictureParameterSets){let i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}if(t.avcProfileIndication===100||t.avcProfileIndication===110||t.avcProfileIndication===122||t.avcProfileIndication===144){p(t.chromaFormat!==null),p(t.bitDepthLumaMinus8!==null),p(t.bitDepthChromaMinus8!==null),p(t.sequenceParameterSetExt!==null),e.push(252|t.chromaFormat&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.sequenceParameterSetExt.length);for(let r of t.sequenceParameterSetExt){let i=r.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(r[n])}}return new Uint8Array(e)};var dt={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Ft=t=>{try{let e=new W(Ue(t));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let i=e.readAlignedByte(),n=e.readAlignedByte(),s=e.readAlignedByte();l(e);let a=1,A=0,u=0,d=0;if((i===100||i===110||i===122||i===244||i===44||i===83||i===86||i===118||i===128)&&(a=l(e),a===3&&(d=e.readBits(1)),A=l(e),u=l(e),e.skipBits(1),e.readBits(1))){for(let E=0;E<(a!==3?8:12);E++)if(e.readBits(1)){let j=E<6?16:64,H=8,R=8;for(let z=0;z<j;z++){if(R!==0){let ee=K(e);R=(H+ee+256)%256}H=R===0?H:R}}}l(e);let c=l(e);if(c===0)l(e);else if(c===1){e.skipBits(1),K(e),K(e);let D=l(e);for(let E=0;E<D;E++)K(e)}l(e),e.skipBits(1);let h=l(e),_=l(e),w=16*(h+1),g=16*(_+1),x=w,C=g,T=e.readBits(1);if(T||e.skipBits(1),e.skipBits(1),e.readBits(1)){let D=l(e),E=l(e),X=l(e),j=l(e),H,R;if((d===0?a:0)===0)H=1,R=2-T;else{let ee=a===3?1:2,le=a===1?2:1;H=ee,R=le*(2-T)}x-=H*(D+E),C-=R*(X+j)}let P=2,V=2,S=2,B=0,N={num:1,den:1},F=null,O=null;if(e.readBits(1)){if(e.readBits(1)){let le=e.readBits(8);if(le===255)N={num:e.readBits(16),den:e.readBits(16)};else{let De=dt[le];De&&(N=De)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),B=e.readBits(1),e.readBits(1)&&(P=e.readBits(8),V=e.readBits(8),S=e.readBits(8))),e.readBits(1)&&(l(e),l(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));let R=e.readBits(1);R&&st(e);let z=e.readBits(1);z&&st(e),(R||z)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),l(e),l(e),l(e),l(e),F=l(e),O=l(e))}if(F===null){p(O===null);let D=n&16;if((i===44||i===86||i===100||i===110||i===122||i===244)&&D)F=0,O=0;else{let E=h+1,X=_+1,j=(2-T)*X,H=Me.find(z=>z.level>=s)??ne(Me),R=Math.min(Math.floor(H.maxDpbMbs/(E*j)),16);F=R,O=R}}return p(O!==null),{profileIdc:i,constraintFlags:n,levelIdc:s,frameMbsOnlyFlag:T,chromaFormatIdc:a,bitDepthLumaMinus8:A,bitDepthChromaMinus8:u,codedWidth:w,codedHeight:g,displayWidth:x,displayHeight:C,pixelAspectRatio:N,colourPrimaries:P,matrixCoefficients:S,transferCharacteristics:V,fullRangeFlag:B,numReorderFrames:F,maxDecFrameBuffering:O}}catch(e){return te._error("Error parsing AVC SPS:",e),null}},st=t=>{let e=l(t);t.skipBits(4),t.skipBits(4);for(let r=0;r<=e;r++)l(t),l(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)};var ve=t=>t>>1&63,Rt=t=>{try{let e=new W(Ue(t));e.skipBits(16),e.readBits(4);let r=e.readBits(3),i=e.readBits(1),{general_profile_space:n,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:A,general_constraint_indicator_flags:u,general_level_idc:d}=Vt(e,r);l(e);let c=l(e),h=0;c===3&&(h=e.readBits(1));let _=l(e),w=l(e),g=_,x=w;if(e.readBits(1)){let E=l(e),X=l(e),j=l(e),H=l(e),R=1,z=1,ee=h===0?c:0;ee===1?(R=2,z=2):ee===2&&(R=2,z=1),g-=(E+X)*R,x-=(j+H)*z}let C=l(e),T=l(e);l(e);let P=e.readBits(1)?0:r,V=0;for(let E=P;E<=r;E++)l(e),V=l(e),l(e);l(e),l(e),l(e),l(e),l(e),l(e),e.readBits(1)&&e.readBits(1)&&Nt(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),l(e),l(e),e.skipBits(1));let S=l(e);if(Mt(e,S),e.readBits(1)){let E=l(e);for(let X=0;X<E;X++)l(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let B=2,N=2,F=2,O=0,ue=0,D={num:1,den:1};if(e.readBits(1)){let E=Ut(e,r);D=E.pixelAspectRatio,B=E.colourPrimaries,N=E.transferCharacteristics,F=E.matrixCoefficients,O=E.fullRangeFlag,ue=E.minSpatialSegmentationIdc}return{displayWidth:g,displayHeight:x,pixelAspectRatio:D,colourPrimaries:B,transferCharacteristics:N,matrixCoefficients:F,fullRangeFlag:O,maxDecFrameBuffering:V+1,spsMaxSubLayersMinus1:r,spsTemporalIdNestingFlag:i,generalProfileSpace:n,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:A,generalConstraintIndicatorFlags:u,generalLevelIdc:d,chromaFormatIdc:c,bitDepthLumaMinus8:C,bitDepthChromaMinus8:T,minSpatialSegmentationIdc:ue}}catch(e){return te._error("Error parsing HEVC SPS:",e),null}},At=t=>{try{let e=[],r=[],i=[],n=[];for(let d of ye(t)){let c=t.subarray(d.offset,d.offset+d.length),h=ve(c[0]);h===32?e.push(c):h===33?r.push(c):h===34?i.push(c):(h===39||h===40)&&n.push(c)}if(r.length===0||i.length===0)return null;let s=Rt(r[0]);if(!s)return null;let a=0;if(i.length>0){let d=i[0],c=new W(Ue(d));c.skipBits(16),l(c),l(c),c.skipBits(1),c.skipBits(1),c.skipBits(3),c.skipBits(1),c.skipBits(1),l(c),l(c),K(c),c.skipBits(1),c.skipBits(1),c.readBits(1)&&l(c),K(c),K(c),c.skipBits(1),c.skipBits(1),c.skipBits(1),c.skipBits(1);let h=c.readBits(1),_=c.readBits(1);!h&&!_?a=0:h&&!_?a=2:!h&&_?a=3:a=0}let A=[...e.length?[{arrayCompleteness:1,nalUnitType:32,nalUnits:e}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:33,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:34,nalUnits:i}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:ve(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:A}}catch(e){return te._error("Error building HEVC Decoder Configuration Record:",e),null}},Vt=(t,e)=>{let r=t.readBits(2),i=t.readBits(1),n=t.readBits(5),s=0;for(let c=0;c<32;c++)s=s<<1|t.readBits(1);let a=new Uint8Array(6);for(let c=0;c<6;c++)a[c]=t.readBits(8);let A=t.readBits(8),u=[],d=[];for(let c=0;c<e;c++)u.push(t.readBits(1)),d.push(t.readBits(1));if(e>0)for(let c=e;c<8;c++)t.skipBits(2);for(let c=0;c<e;c++)u[c]&&t.skipBits(88),d[c]&&t.skipBits(8);return{general_profile_space:r,general_tier_flag:i,general_profile_idc:n,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:A}},Nt=t=>{for(let e=0;e<4;e++)for(let r=0;r<(e===3?2:6);r++)if(!t.readBits(1))l(t);else{let n=Math.min(64,1<<4+(e<<1));e>1&&K(t);for(let s=0;s<n;s++)K(t)}},Mt=(t,e)=>{let r=[];for(let i=0;i<e;i++)r[i]=kt(t,i,e,r)},kt=(t,e,r,i)=>{let n=0,s=0,a=0;if(e!==0&&(s=t.readBits(1)),s){if(e===r){let u=l(t);a=e-(u+1)}else a=e-1;t.readBits(1),l(t);let A=i[a]??0;for(let u=0;u<=A;u++)t.readBits(1)||t.readBits(1);n=i[a]}else{let A=l(t),u=l(t);for(let d=0;d<A;d++)l(t),t.readBits(1);for(let d=0;d<u;d++)l(t),t.readBits(1);n=A+u}return n},Ut=(t,e)=>{let r=2,i=2,n=2,s=0,a=0,A={num:1,den:1};if(t.readBits(1)){let u=t.readBits(8);if(u===255)A={num:t.readBits(16),den:t.readBits(16)};else{let d=dt[u];d&&(A=d)}}return t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),s=t.readBits(1),t.readBits(1)&&(r=t.readBits(8),i=t.readBits(8),n=t.readBits(8))),t.readBits(1)&&(l(t),l(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(l(t),l(t),l(t),l(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&l(t),t.readBits(1)&&Lt(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),a=l(t),l(t),l(t),l(t),l(t)),{pixelAspectRatio:A,colourPrimaries:r,transferCharacteristics:i,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},Lt=(t,e,r)=>{let i=!1,n=!1,s=!1;e&&(i=t.readBits(1)===1,n=t.readBits(1)===1,(i||n)&&(s=t.readBits(1)===1,s&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),s&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5)));for(let a=0;a<=r;a++){let A=t.readBits(1)===1,u=!0;A||(u=t.readBits(1)===1);let d=!1;u?l(t):d=t.readBits(1)===1;let c=1;d||(c=l(t)+1),i&&at(t,c,s),n&&at(t,c,s)}},at=(t,e,r)=>{for(let i=0;i<e;i++)l(t),l(t),r&&(l(t),l(t)),t.readBits(1)},ut=t=>{let e=[];e.push(t.configurationVersion),e.push((t.generalProfileSpace&3)<<6|(t.generalTierFlag&1)<<5|t.generalProfileIdc&31),e.push(t.generalProfileCompatibilityFlags>>>24&255),e.push(t.generalProfileCompatibilityFlags>>>16&255),e.push(t.generalProfileCompatibilityFlags>>>8&255),e.push(t.generalProfileCompatibilityFlags&255),e.push(...t.generalConstraintIndicatorFlags),e.push(t.generalLevelIdc&255),e.push(240|t.minSpatialSegmentationIdc>>8&15),e.push(t.minSpatialSegmentationIdc&255),e.push(252|t.parallelismType&3),e.push(252|t.chromaFormatIdc&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.avgFrameRate>>8&255),e.push(t.avgFrameRate&255),e.push((t.constantFrameRate&3)<<6|(t.numTemporalLayers&7)<<3|(t.temporalIdNested&1)<<2|t.lengthSizeMinusOne&3),e.push(t.arrays.length&255);for(let r of t.arrays){e.push((r.arrayCompleteness&1)<<7|0|r.nalUnitType&63),e.push(r.nalUnits.length>>8&255),e.push(r.nalUnits.length&255);for(let i of r.nalUnits){e.push(i.length>>8&255),e.push(i.length&255);for(let n=0;n<i.length;n++)e.push(i[n])}}return new Uint8Array(e)};var mt=t=>{let e=new W(t);if(e.readBits(2)!==2)return null;let i=e.readBits(1),s=(e.readBits(1)<<1)+i;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let d=8;s>=2&&(d=e.readBits(1)?12:10);let c=e.readBits(3),h=0,_=0;if(c!==7)if(_=e.readBits(1),s===1||s===3){let N=e.readBits(1),F=e.readBits(1);h=!N&&!F?3:N&&!F?2:1,e.skipBits(1)}else h=1;else h=3,_=1;let w=e.readBits(16),g=e.readBits(16),x=w+1,C=g+1,T=x*C,y=ne(ie).level;for(let B of ie)if(T<=B.maxPictureSize){y=B.level;break}return{profile:s,level:y,bitDepth:d,chromaSubsampling:h,videoFullRangeFlag:_,colourPrimaries:c===2?1:c===1?6:2,transferCharacteristics:c===2?1:c===1?6:2,matrixCoefficients:c===7?0:c===2?1:c===1?6:2}},Dt=function*(t){let e=new W(t),r=()=>{let i=0;for(let n=0;n<8;n++){let s=e.readAlignedByte();if(i|=(s&127)<<n*7,!(s&128))break;if(n===7&&s&128)return null}return i>=2**32-1?null:i};for(;e.getBitsLeft()>=8;){e.skipBits(1);let i=e.readBits(4),n=e.readBits(1),s=e.readBits(1);e.skipBits(1),n&&e.skipBits(8);let a;if(s){let A=r();if(A===null)return;a=A}else a=Math.floor(e.getBitsLeft()/8);p(e.pos%8===0),yield{type:i,data:t.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},ft=t=>{for(let{type:e,data:r}of Dt(t)){if(e!==1)continue;let i=new W(r),n=i.readBits(3),s=i.readBits(1),a=i.readBits(1),A=0,u=0,d=0;if(a)A=i.readBits(5);else{if(i.readBits(1)&&(i.skipBits(32),i.skipBits(32),i.readBits(1)))return null;let B=i.readBits(1);B&&(d=i.readBits(5),i.skipBits(32),i.skipBits(5),i.skipBits(5));let N=i.readBits(5);for(let F=0;F<=N;F++){i.skipBits(12);let O=i.readBits(5);if(F===0&&(A=O),O>7){let D=i.readBits(1);F===0&&(u=D)}if(B&&i.readBits(1)){let E=d+1;i.skipBits(E),i.skipBits(E),i.skipBits(1)}i.readBits(1)&&i.skipBits(4)}}let c=i.readBits(4),h=i.readBits(4),_=c+1;i.skipBits(_);let w=h+1;i.skipBits(w);let g=0;if(a?g=0:g=i.readBits(1),g&&(i.skipBits(4),i.skipBits(3)),i.skipBits(1),i.skipBits(1),i.skipBits(1),!a){i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);let S=i.readBits(1);S&&(i.skipBits(1),i.skipBits(1));let B=i.readBits(1),N=0;B?N=2:N=i.readBits(1),N>0&&(i.readBits(1)||i.skipBits(1)),S&&i.skipBits(3)}i.skipBits(1),i.skipBits(1),i.skipBits(1);let x=i.readBits(1),C=8;n===2&&x?C=i.readBits(1)?12:10:n<=2&&(C=x?10:8);let T=0;n!==1&&(T=i.readBits(1));let y=1,P=1,V=0;return T||(n===0?(y=1,P=1):n===1?(y=0,P=0):C===12&&(y=i.readBits(1),y&&(P=i.readBits(1))),y&&P&&(V=i.readBits(2))),{profile:n,level:A,tier:u,bitDepth:C,monochrome:T,chromaSubsamplingX:y,chromaSubsamplingY:P,chromaSamplePosition:V}}return null};var Ur=[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];var Lr=new Uint8Array([5,4,65,67,45,51]),Dr=new Uint8Array([5,4,69,65,67,51]);var Ee=class extends se.CustomVideoEncoder{constructor(){super(...arguments);this.codecContext=null;this.scaler=null;this.dstFrame=null;this.lastBuffer=null;this.packetEmitted=!1;this.lastScalerKey=null;this.preciseTimings=[]}static supports(r,i){return(r==="avc"||r==="hevc"||r==="vp8"||r==="vp9"||r==="av1")&&i.bitrateMode!=="quantizer"}async init(){this.frame=new m.Frame,this.frame.alloc(),this.frame.timeBase=new m.Rational(1,1e6),this.packet=new m.Packet,this.packet.alloc();let r=J[this.codec];p(r!==void 0);let i=null;if(this.codec==="vp9"&&this.config.alpha==="keep"?i=m.Codec.findEncoderByName(m.FF_ENCODER_LIBVPX_VP9)??m.Codec.findEncoder(r):this.config.hardwareAcceleration==="prefer-software"?i=m.Codec.findEncoder(r):i=await We(r)??m.Codec.findEncoder(r),!i)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);this.avCodec=i,await this.createCodecContext()}async createCodecContext(){p(this.codecContext===null);let r=new m.CodecContext;r.allocContext3(this.avCodec);let i=m.AV_PIX_FMT_YUV420P;this.avCodec.pixelFormats&&(this.avCodec.pixelFormats.includes(m.AV_PIX_FMT_YUV420P)||(i=this.avCodec.pixelFormats[0]),this.config.alpha==="keep"&&this.avCodec.pixelFormats.includes(m.AV_PIX_FMT_YUVA420P)&&(i=m.AV_PIX_FMT_YUVA420P));let n=Ce({num:(this.config.displayWidth??this.config.width)*this.config.height,den:(this.config.displayHeight??this.config.height)*this.config.width});r.width=this.config.width,r.height=this.config.height,r.pixelFormat=i,r.timeBase=new m.Rational(1,1e6),r.gopSize=60,r.framerate=new m.Rational(Math.round(this.config.framerate??0)||30,1),r.bitRate=BigInt(this.config.bitrate??se.QUALITY_MEDIUM._toVideoBitrate(this.codec,this.config.width,this.config.height)),r.sampleAspectRatio=new m.Rational(n.num,n.den),this.config.bitrateMode==="constant"&&(r.rcMinRate=r.bitRate,r.rcMaxRate=r.bitRate);let s=this.config.latencyMode==="realtime";this.avCodec.name==="libx264"?s&&(r.setOption("tune","zerolatency"),r.setOption("preset","ultrafast")):this.avCodec.name==="libx265"?(r.setOption("x265-params","log-level=error"),s&&(r.setOption("tune","zerolatency"),r.setOption("preset","ultrafast"))):this.avCodec.name==="libvpx"?(s&&r.setOption("deadline","realtime"),r.setOption("cpu-used","8")):this.avCodec.name==="libvpx-vp9"?(r.setOption("deadline","realtime"),s?r.setOption("cpu-used","8"):r.setOption("cpu-used","5")):this.avCodec.name==="libsvtav1"&&(process.env.SVT_LOG="1",s&&r.setOption("preset","12"));let a=await r.open2();m.FFmpegError.throwIfError(a,"Open codec context"),this.codecContext=r}async encode(r,i){if(this.codecContext===null&&await this.createCodecContext(),p(this.codecContext),r._data instanceof q)this.frame.unref(),this.frame.ref(r._data.frame);else{if(r.format===null)throw new Error("Cannot encode foreign VideoSample with unknown (null) format.");this.lastBuffer=await de(r,this.frame,this.lastBuffer)}let n=this.frame;if(this.codecContext.pixelFormat!==this.frame.format||this.codecContext.width!==this.frame.width||this.codecContext.height!==this.frame.height){this.scaler||(this.scaler=new m.SoftwareScaleContext);let d=`${this.frame.width}x${this.frame.height}:${this.frame.format}`;if(d!==this.lastScalerKey){this.scaler.getContext(this.frame.width,this.frame.height,this.frame.format,this.codecContext.width,this.codecContext.height,this.codecContext.pixelFormat,m.SWS_FAST_BILINEAR),this.lastScalerKey=d;let h=this.scaler.initContext();m.FFmpegError.throwIfError(h,"initContext")}this.dstFrame||(this.dstFrame=new m.Frame,this.dstFrame.alloc(),this.dstFrame.width=this.codecContext.width,this.dstFrame.height=this.codecContext.height,this.dstFrame.format=this.codecContext.pixelFormat,this.dstFrame.allocBuffer()),await this.scaler.scaleFrame(this.dstFrame,this.frame),this.dstFrame.copyProps(this.frame),n=this.dstFrame}n.pts=BigInt(r.microsecondTimestamp),n.duration=BigInt(r.microsecondDuration),n.timeBase=new m.Rational(1,1e6),n.pictType=i?.keyFrame?m.AV_PICTURE_TYPE_I:m.AV_PICTURE_TYPE_NONE,n.keyFrame=i?.keyFrame?1:0;let a=oe(this.preciseTimings,r.microsecondTimestamp,d=>d.microsecondTimestamp),A=a!==-1?this.preciseTimings[a]:null;A&&A.microsecondTimestamp===r.microsecondTimestamp?(A.timestamp!==r.timestamp&&(A.timestampIsValid=!1),A.duration!==r.duration&&(A.durationIsValid=!1)):(this.preciseTimings.splice(a+1,0,{microsecondTimestamp:r.microsecondTimestamp,timestamp:r.timestamp,duration:r.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift());let u=await this.codecContext.sendFrame(n);for(m.FFmpegError.throwIfError(u,"Send frame");;){let d=await this.codecContext.receivePacket(this.packet);if(d===m.AVERROR_EAGAIN||d===m.AVERROR_EOF)break;this.receivePacket(d)}}receivePacket(r){if(p(this.codecContext),m.FFmpegError.throwIfError(r,"Receive packet"),!this.packet.data)return;let i=L(this.packet.data),n=Number(this.packet.pts)/1e6,s=Number(this.packet.duration)/1e6,a=oe(this.preciseTimings,Number(this.packet.pts),g=>g.microsecondTimestamp),A=a!==-1?this.preciseTimings[a]:null;A&&A.microsecondTimestamp===Number(this.packet.pts)&&(A.timestampIsValid&&(n=A.timestamp),A.durationIsValid&&(s=A.duration));let u={},d=null,c=null;if(this.codec==="avc"||this.codec==="hevc"){let g=!1;if(this.codec==="avc"?g=this.config.avc?.format==="annexb":g=this.config.hevc?.format==="annexb",!this.packetEmitted){let x;if(this.codec==="avc"){let C=ct(this.packet.data);if(!C)throw new Error("Invalid AVC data, could not extract decoder configuration record.");x=lt(C)}else{let C=At(this.packet.data);if(!C)throw new Error("Invalid HEVC data, could not extract decoder configuration record.");x=ut(C)}d=Ae({width:this.config.width,height:this.config.height,codec:this.codec,codecDescription:x,colorSpace:null,avcType:1,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}),g||(c=x)}if(!g){let C=[];for(let S of ye(i))if(this.codec==="avc"){let B=ke(i[S.offset]);B!==7&&B!==8&&B!==13&&C.push(S)}else{let B=ve(i[S.offset]);B!==33&&B!==34&&B!==32&&C.push(S)}let T=0;for(let S of C)T+=4+S.length;let y=new Uint8Array(T),P=new DataView(y.buffer),V=0;for(let S of C){let B=S.length;P.setUint32(V,B,!1),V+=4,y.set(i.subarray(S.offset,S.offset+S.length),V),V+=S.length}i=y}}else if(this.codec==="vp8")this.packetEmitted||(d=Ae({width:this.config.width,height:this.config.height,codec:"vp8",codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}));else if(this.codec==="vp9"){if(!this.packetEmitted){let g=mt(i);d=Ae({width:this.config.width,height:this.config.height,codec:"vp9",codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:g,av1CodecInfo:null})}}else if(this.codec==="av1"){if(!this.packetEmitted){let g=ft(i);d=Ae({width:this.config.width,height:this.config.height,codec:"av1",codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:g})}}else throw new Error("Unreachable.");let h={},_=this.packet.getSideData(m.AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL);_&&(h.alpha=L(_).subarray(8));let w=new se.EncodedPacket(i,this.packet.isKeyframe?"key":"delta",n,s,void 0,void 0,h);d!==null&&(u.decoderConfig={codec:d,codedWidth:this.codecContext.width,codedHeight:this.codecContext.height,displayAspectWidth:this.config.displayWidth??this.codecContext.width,displayAspectHeight:this.config.displayHeight??this.codecContext.height,description:c??void 0,colorSpace:{primaries:fe(this.codecContext.colorPrimaries),matrix:he(this.codecContext.colorSpace),transfer:pe(this.codecContext.colorTrc),fullRange:this.codecContext.colorRange===m.AVCOL_RANGE_JPEG?!0:this.codecContext.colorRange===m.AVCOL_RANGE_MPEG?!1:void 0}}),this.packetEmitted=!0,this.onPacket(w,u)}async flush(){if(this.codecContext){let r=await this.codecContext.sendFrame(null);for(m.FFmpegError.throwIfError(r,"Send frame");;){let i=await this.codecContext.receivePacket(this.packet);if(i===m.AVERROR_EAGAIN||i===m.AVERROR_EOF)break;this.receivePacket(i)}this.codecContext.freeContext(),this.codecContext=null}this.packetEmitted=!1}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free(),this.scaler?.freeContext(),this.dstFrame?.free()}};var Se=M("mediabunny"),I=$(M("node-av"));var pt=M("mediabunny"),ae=$(M("node-av"));var Q=class extends pt.AudioSampleResource{get frame(){if(!this._frame)throw new Error("AvFrameAudioSampleResource has been closed.");return this._frame}constructor(e){if(super(),!(e instanceof ae.Frame))throw new TypeError("frame must be a NodeAv.Frame.");if(e.getMediaType()!==ae.AVMEDIA_TYPE_AUDIO)throw new Error("AvFrameAudioSampleResource must be initialized with an audio frame.");this._frame=e}getFormat(){let e=Qe(this.frame.format);if(e===null){let r=ae.avGetSampleFmtName(this.frame.format);throw new TypeError(`Unsupported audio sample format: ${r} (${this.frame.format})`)}return e}getSampleRate(){return this.frame.sampleRate}getNumberOfChannels(){return this.frame.channels}getNumberOfFrames(){return this.frame.nbSamples}getTimestamp(){return Number(this.frame.pts)/this.frame.timeBase.den}close(){this.frame.free(),this._frame=null}getDataPlane(e){return p(this.frame.data&&e<this.frame.data.length),L(this.frame.data[e])}},_e=(t,e)=>{e.format=Je(t.format),e.nbSamples=t.numberOfFrames,e.sampleRate=t.sampleRate,e.channelLayout=Z(t.numberOfChannels),e.allocBuffer(),p(e.data);for(let r=0;r<e.data.length;r++)t.copyTo(e.data[r],{planeIndex:r})};var we=class extends Se.CustomAudioDecoder{constructor(){super(...arguments);this.codecContext=null}static supports(r,i){return r==="aac"||r==="opus"||r==="mp3"||r==="vorbis"||r==="flac"||r==="ac3"||r==="eac3"}async init(){this.frame=new I.Frame,this.frame.alloc(),this.packet=new I.Packet,this.packet.alloc();let r=J[this.codec];p(r!==void 0);let i=I.Codec.findDecoder(r);if(i===null)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);let n=new I.CodecContext;n.allocContext3(i),n.sampleRate=this.config.sampleRate,n.channelLayout=Z(this.config.numberOfChannels),n.timeBase=new I.Rational(1,this.config.sampleRate),n.codecType=I.AVMEDIA_TYPE_AUDIO,n.codecId=r,n.extraData=this.config.description?Buffer.from(L(this.config.description)):null;let s=await n.open2();I.FFmpegError.throwIfError(s,"Open codec context"),this.codecContext=n}async decode(r){p(this.codecContext),this.packet.isKeyframe=r.type==="key",this.packet.data=Buffer.from(r.data),this.packet.timeBase={num:1,den:this.config.sampleRate},this.packet.pts=BigInt(Math.round(r.timestamp*this.config.sampleRate)),this.packet.dts=I.AV_NOPTS_VALUE,this.packet.duration=BigInt(Math.round(r.duration*this.config.sampleRate));let i=await this.codecContext.sendPacket(this.packet);for(I.FFmpegError.throwIfError(i,"Send packet"),this.packet.unref();;){let n=await this.codecContext.receiveFrame(this.frame);if(n===I.AVERROR_EAGAIN||n===I.AVERROR_EOF)break;this.receiveFrame(n)}}receiveFrame(r){I.FFmpegError.throwIfError(r,"Receive frame");let i=this.frame.clone();if(!i)throw new Error("Allocation failure during frame clone.");i.timeBase=new I.Rational(1,this.config.sampleRate),this.onSample(new Se.AudioSample(new Q(i)))}async flush(){p(this.codecContext);let r=await this.codecContext.sendPacket(null);for(I.FFmpegError.throwIfError(r,"Flush decoder");;){let i=await this.codecContext.receiveFrame(this.frame);if(i===I.AVERROR_EAGAIN||i===I.AVERROR_EOF)break;this.receiveFrame(i)}this.codecContext.flushBuffers()}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free()}};var ce=M("mediabunny"),v=$(M("node-av"));var Ot=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Ht=[8e3,12e3,16e3,24e3,48e3],zt=[8e3,11025,12e3,16e3,22050,24e3,32e3,44100,48e3],ht=[32e3,44100,48e3],Le=1024,Ie=class extends ce.CustomAudioEncoder{constructor(){super(...arguments);this.codecContext=null;this.resampler=null;this.dstFrame=null;this.firstExpectedTimestamp=null;this.outputTimestampOffset=0;this.inputParametersKey=null;this.resamplerInputSampleRate=null;this.nextResamplerPts=null;this.packetEmitted=!1;this.adtsHeaderTemplate=null}static supports(r,i){let{numberOfChannels:n,sampleRate:s}=i;return r==="aac"&&n>=1&&n<=48&&Ot.includes(s)||r==="opus"&&n>=1&&n<=255&&Ht.includes(s)||r==="mp3"&&n>=1&&n<=2&&zt.includes(s)||r==="vorbis"&&n>=1&&n<=255&&s<=2e5||r==="flac"&&n>=1&&n<=8&&s<=655350||r==="ac3"&&n>=1&&n<=6&&ht.includes(s)||r==="eac3"&&n>=1&&n<=16&&ht.includes(s)}async init(){this.frame=new v.Frame,this.frame.alloc(),this.packet=new v.Packet,this.packet.alloc();let r=J[this.codec];p(r!==void 0);let i=v.Codec.findEncoder(r);if(!i)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);this.avCodec=i,await this.createCodecContext()}async createCodecContext(){p(this.codecContext===null);let r=new v.CodecContext;r.allocContext3(this.avCodec);let i=v.AV_SAMPLE_FMT_FLTP;this.avCodec.sampleFormats&&!this.avCodec.sampleFormats.includes(v.AV_SAMPLE_FMT_FLTP)&&(i=this.avCodec.sampleFormats[0]),r.sampleRate=this.config.sampleRate,r.channelLayout=Z(this.config.numberOfChannels),r.codecType=v.AVMEDIA_TYPE_AUDIO,r.codecId=J[this.codec],r.sampleFormat=i,r.timeBase=new v.Rational(1,this.config.sampleRate),r.bitRate=BigInt(this.config.bitrate??ce.QUALITY_MEDIUM._toAudioBitrate(this.codec)??0),this.config.bitrateMode==="constant"&&(r.rcMinRate=r.bitRate,r.rcMaxRate=r.bitRate);let n=await r.open2();v.FFmpegError.throwIfError(n,"Open codec context"),this.codecContext=r}async encode(r){this.codecContext===null&&(await this.createCodecContext(),p(this.codecContext)),this.firstExpectedTimestamp??=r.timestamp,r._data instanceof Q?(this.frame.unref(),this.frame.ref(r._data.frame)):_e(r,this.frame),this.frame.pts=BigInt(Math.round(r.timestamp*this.config.sampleRate)),this.frame.duration=BigInt(Math.round(r.duration*this.config.sampleRate)),this.frame.timeBase=new v.Rational(1,this.config.sampleRate);let i=`${this.frame.sampleRate}:${this.frame.channels}:${this.frame.format}`;if(this.inputParametersKey!==null&&this.inputParametersKey!==i)throw new Error("Input audio parameters changed. For this audio encoder, you cannot change the input audio parameters over time.");if(this.inputParametersKey=i,this.codecContext.frameSize>0||this.codecContext.sampleFormat!==this.frame.format||this.codecContext.sampleRate!==this.frame.sampleRate||this.codecContext.channels!==this.frame.channels){if(!this.resampler){this.resampler=new v.SoftwareResampleContext,this.resamplerInputSampleRate=this.frame.sampleRate;let a=Z(this.codecContext.channels),A=Z(this.frame.channels),u=this.resampler.allocSetOpts2(a,this.codecContext.sampleFormat,this.codecContext.sampleRate,A,this.frame.format,this.frame.sampleRate);v.FFmpegError.throwIfError(u,"allocSetOpts2");let d=this.resampler.init();v.FFmpegError.throwIfError(d,"init"),this.dstFrame=new v.Frame,this.dstFrame.alloc(),this.dstFrame.channelLayout=a,this.dstFrame.sampleRate=this.codecContext.sampleRate,this.dstFrame.format=this.codecContext.sampleFormat,this.dstFrame.nbSamples=this.codecContext.frameSize||Le,this.dstFrame.duration=BigInt(this.dstFrame.nbSamples),this.dstFrame.allocBuffer(),this.nextResamplerPts=this.frame.pts}let s=this.frame.data;if(!s)throw new DOMException("Frame has no data","EncodingError");await this.resampler.convert(null,0,s,this.frame.nbSamples),await this.pullResampledFrames()}else await this.sendFrameAndReceivePackets(this.frame)}async pullResampledFrames(){p(this.codecContext),p(this.resampler),p(this.dstFrame),p(this.nextResamplerPts!==null);let r=this.codecContext.frameSize||Le;for(;!(this.resampler.getOutSamples(0)<r);)await this.resampler.convert(this.dstFrame.data,r,null,0),this.dstFrame.pts=this.nextResamplerPts,await this.sendFrameAndReceivePackets(this.dstFrame),this.nextResamplerPts+=BigInt(r)}async sendFrameAndReceivePackets(r){p(this.codecContext);let i=await this.codecContext.sendFrame(r);for(v.FFmpegError.throwIfError(i,"Send frame");;){let n=await this.codecContext.receivePacket(this.packet);if(n===v.AVERROR_EAGAIN||n===v.AVERROR_EOF)break;this.receivePacket(n)}}receivePacket(r){if(p(this.codecContext),p(this.firstExpectedTimestamp!==null),v.FFmpegError.throwIfError(r,"Receive packet"),!this.packet.data)return;let i=Number(this.packet.pts)/this.codecContext.sampleRate,n=Number(this.packet.duration)/this.codecContext.sampleRate,s=this.packet.data,a;if(this.packetEmitted)a={};else{this.outputTimestampOffset=Math.max(this.firstExpectedTimestamp-i,0);let u=this.config.codec,d=this.codecContext.extraData?L(this.codecContext.extraData):void 0;if(this.codec==="aac"){if(!d)throw new Error("Extradata expected for AAC.");if(this.config.aac?.format==="adts"){let h=rt(d);this.adtsHeaderTemplate=it(h),d=void 0}}else if(this.codec==="opus"){if(!d)throw new Error("Extradata expected for Opus.")}else if(this.codec==="vorbis"){if(!d)throw new Error("Extradata expected for Vorbis.")}else if(this.codec==="flac"){if(!d)throw new Error("Extradata expected for FLAC.");d=new Uint8Array([102,76,97,67,128,0,0,d.byteLength,...d])}a={decoderConfig:{codec:u,sampleRate:this.codecContext.sampleRate,numberOfChannels:this.codecContext.channels,description:d}}}if(this.adtsHeaderTemplate){let u=s.byteLength+this.adtsHeaderTemplate.header.byteLength;this.adtsHeaderTemplate.bitstream.pos=30,this.adtsHeaderTemplate.bitstream.writeBits(13,u);let d=new Uint8Array(this.adtsHeaderTemplate.header.byteLength+s.byteLength);d.set(this.adtsHeaderTemplate.header,0),d.set(s,this.adtsHeaderTemplate.header.byteLength),s=d}i+=this.outputTimestampOffset;let A=new ce.EncodedPacket(s,"key",i,n);this.packetEmitted=!0,this.onPacket(A,a)}async flush(){if(this.codecContext){e:if(this.resampler){p(this.resamplerInputSampleRate!==null);let r=this.resampler.getOutSamples(0);if(r===0)break e;let i=this.codecContext.frameSize||Le;p(r<i);let n=Math.ceil((i-r)/this.codecContext.sampleRate*this.resamplerInputSampleRate);this.resampler.injectSilence(n),await this.pullResampledFrames()}await this.sendFrameAndReceivePackets(null),this.codecContext.freeContext(),this.codecContext=null,this.packetEmitted=!1,this.firstExpectedTimestamp=null,this.outputTimestampOffset=0,this.adtsHeaderTemplate=null,this.resampler?.free(),this.resampler=null,this.inputParametersKey=null,this.resamplerInputSampleRate=null,this.nextResamplerPts=null,this.dstFrame?.free(),this.dstFrame=null}}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free(),this.dstFrame?.free(),this.resampler?.free()}};var Ct=Symbol.for("@mediabunny/server loaded");globalThis[Ct]&&k.Logging._error(`[WARNING]
9
- @mediabunny/server was loaded twice. This will likely cause the package not to work correctly. Check if multiple dependencies are importing different versions of @mediabunny/server, or if something is being bundled incorrectly.`);globalThis[Ct]=!0;var gt=!1,Y={},qt=(t={})=>{if(typeof t!="object"||!t)throw new TypeError("options must be an object.");if(t.hardwareContext!=null&&!(t.hardwareContext instanceof G.HardwareContext||typeof t.hardwareContext=="function"))throw new TypeError("options.hardwareContext, when provided, must be a NodeAv.HardwareContext, a function, or null.");gt||(gt=!0,Y=t,G.Log.setLevel(G.AV_LOG_ERROR),(0,k.registerDecoder)(be),(0,k.registerEncoder)(Ee),(0,k.registerDecoder)(we),(0,k.registerEncoder)(Ie),(0,k.registerVideoSampleTransformer)(et))},Wt=async(t,e)=>{if(!(t instanceof k.VideoSample)&&!(t instanceof k.AudioSample))throw new TypeError("sample must be a VideoSample or an AudioSample.");if(!(e instanceof G.Frame))throw new TypeError("frame must be a NodeAv.Frame.");if(t instanceof k.VideoSample){if(t._data instanceof q)e.unref(),e.ref(t._data.frame);else{if(t.format===null)throw new Error("Cannot convert foreign VideoSample with unknown (null) format.");await de(t,e,null)}e.pts=BigInt(t.microsecondTimestamp),e.duration=BigInt(t.microsecondDuration),e.timeBase=new G.Rational(1,1e6)}else t._data instanceof Q?(e.unref(),e.ref(t._data.frame)):_e(t,e),e.timeBase=new G.Rational(1,t.sampleRate),e.pts=BigInt(Math.round(t.timestamp*t.sampleRate)),e.duration=BigInt(t.numberOfFrames)};return wt(Gt);})();
8
+ "use strict";var MediabunnyServer=(()=>{var vt=Object.create;var me=Object.defineProperty;var _t=Object.getOwnPropertyDescriptor;var yt=Object.getOwnPropertyNames;var Et=Object.getPrototypeOf,St=Object.prototype.hasOwnProperty;var N=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var It=(t,e)=>{for(var r in e)me(t,r,{get:e[r],enumerable:!0})},He=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of yt(e))!St.call(t,n)&&n!==r&&me(t,n,{get:()=>e[n],enumerable:!(o=_t(e,n))||o.enumerable});return t};var $=(t,e,r)=>(r=t!=null?vt(Et(t)):{},He(e||!t||!t.__esModule?me(r,"default",{value:t,enumerable:!0}):r,t)),wt=t=>He(me({},"__esModule",{value:!0}),t);var Qt={};It(Qt,{AvFrameAudioSampleResource:()=>Q,AvFrameVideoSampleResource:()=>q,_serverOptions:()=>Y,registerMediabunnyServer:()=>Yt,toAvFrame:()=>Kt});var k=N("mediabunny"),G=$(N("node-av"));var xe=N("mediabunny"),b=$(N("node-av"));var i=$(N("node-av"));var J={avc:i.AV_CODEC_ID_H264,hevc:i.AV_CODEC_ID_HEVC,vp8:i.AV_CODEC_ID_VP8,vp9:i.AV_CODEC_ID_VP9,av1:i.AV_CODEC_ID_AV1,prores:i.AV_CODEC_ID_PRORES,aac:i.AV_CODEC_ID_AAC,opus:i.AV_CODEC_ID_OPUS,mp3:i.AV_CODEC_ID_MP3,vorbis:i.AV_CODEC_ID_VORBIS,flac:i.AV_CODEC_ID_FLAC,ac3:i.AV_CODEC_ID_AC3,eac3:i.AV_CODEC_ID_EAC3},Be,ze=()=>Y.hardwareContext!==void 0&&typeof Y.hardwareContext!="function"?Y.hardwareContext:(Be===void 0&&(Be=i.HardwareContext.auto()),Be),qe=t=>{if(t!==null&&!(t instanceof i.HardwareContext))throw new TypeError("When serverOptions.hardwareContext is a function, it must return or resolve to a NodeAv.HardwareContext or null.")},Pe=new Map,We=async t=>{if(typeof Y.hardwareContext=="function"){let e=await Y.hardwareContext(t);return qe(e),e?.getDecoderCodec(t)??null}if(!Pe.has(t)){let e=ze();Pe.set(t,e?.getDecoderCodec(t)??null)}return Pe.get(t)},Te=new Map,Ge=async t=>{if(typeof Y.hardwareContext=="function"){let e=await Y.hardwareContext(t);return qe(e),e?.getEncoderCodec(t)??null}if(!Te.has(t)){let e=ze();Te.set(t,e?.getEncoderCodec(t)??null)}return Te.get(t)},Xe=t=>{switch(t){case"bt709":return i.AVCOL_PRI_BT709;case"bt470bg":return i.AVCOL_PRI_BT470BG;case"smpte170m":return i.AVCOL_PRI_SMPTE170M;case"bt2020":return i.AVCOL_PRI_BT2020;case"smpte432":return i.AVCOL_PRI_SMPTE432}return null},fe=t=>{switch(t){case i.AVCOL_PRI_BT709:return"bt709";case i.AVCOL_PRI_BT470BG:return"bt470bg";case i.AVCOL_PRI_SMPTE170M:return"smpte170m";case i.AVCOL_PRI_BT2020:return"bt2020";case i.AVCOL_PRI_SMPTE432:return"smpte432"}return null},Ye=t=>{switch(t){case"bt709":return i.AVCOL_TRC_BT709;case"smpte170m":return i.AVCOL_TRC_SMPTE170M;case"iec61966-2-1":return i.AVCOL_TRC_IEC61966_2_1;case"linear":return i.AVCOL_TRC_LINEAR;case"pq":return i.AVCOL_TRC_SMPTE2084;case"hlg":return i.AVCOL_TRC_ARIB_STD_B67}return null},pe=t=>{switch(t){case i.AVCOL_TRC_BT709:return"bt709";case i.AVCOL_TRC_SMPTE170M:return"smpte170m";case i.AVCOL_TRC_IEC61966_2_1:return"iec61966-2-1";case i.AVCOL_TRC_LINEAR:return"linear";case i.AVCOL_TRC_SMPTE2084:return"pq";case i.AVCOL_TRC_ARIB_STD_B67:return"hlg"}return null},Ke=t=>{switch(t){case"rgb":return i.AVCOL_SPC_RGB;case"bt709":return i.AVCOL_SPC_BT709;case"bt470bg":return i.AVCOL_SPC_BT470BG;case"smpte170m":return i.AVCOL_SPC_SMPTE170M;case"bt2020-ncl":return i.AVCOL_SPC_BT2020_NCL}return null},he=t=>{switch(t){case i.AVCOL_SPC_RGB:return"rgb";case i.AVCOL_SPC_BT709:return"bt709";case i.AVCOL_SPC_BT470BG:return"bt470bg";case i.AVCOL_SPC_SMPTE170M:return"smpte170m";case i.AVCOL_SPC_BT2020_NCL:return"bt2020-ncl"}return null},Qe=t=>{switch(t){case i.AV_PIX_FMT_YUV420P:return"I420";case i.AV_PIX_FMT_YUVJ420P:return"I420";case i.AV_PIX_FMT_YUV420P10LE:return"I420P10";case i.AV_PIX_FMT_YUV420P12LE:return"I420P12";case i.AV_PIX_FMT_YUVA420P:return"I420A";case i.AV_PIX_FMT_YUVA420P10LE:return"I420AP10";case i.AV_PIX_FMT_YUV422P:return"I422";case i.AV_PIX_FMT_YUVJ422P:return"I422";case i.AV_PIX_FMT_YUV422P10LE:return"I422P10";case i.AV_PIX_FMT_YUV422P12LE:return"I422P12";case i.AV_PIX_FMT_YUVA422P:return"I422A";case i.AV_PIX_FMT_YUVA422P10LE:return"I422AP10";case i.AV_PIX_FMT_YUVA422P12LE:return"I422AP12";case i.AV_PIX_FMT_YUV444P:return"I444";case i.AV_PIX_FMT_YUVJ444P:return"I444";case i.AV_PIX_FMT_YUV444P10LE:return"I444P10";case i.AV_PIX_FMT_YUV444P12LE:return"I444P12";case i.AV_PIX_FMT_YUVA444P:return"I444A";case i.AV_PIX_FMT_YUVA444P10LE:return"I444AP10";case i.AV_PIX_FMT_YUVA444P12LE:return"I444AP12";case i.AV_PIX_FMT_NV12:return"NV12";case i.AV_PIX_FMT_RGBA:return"RGBA";case i.AV_PIX_FMT_RGB0:return"RGBX";case i.AV_PIX_FMT_BGRA:return"BGRA";case i.AV_PIX_FMT_BGR0:return"BGRX";default:return null}},Fe=t=>{switch(t){case"I420":return i.AV_PIX_FMT_YUV420P;case"I420P10":return i.AV_PIX_FMT_YUV420P10LE;case"I420P12":return i.AV_PIX_FMT_YUV420P12LE;case"I420A":return i.AV_PIX_FMT_YUVA420P;case"I420AP10":return i.AV_PIX_FMT_YUVA420P10LE;case"I422":return i.AV_PIX_FMT_YUV422P;case"I422P10":return i.AV_PIX_FMT_YUV422P10LE;case"I422P12":return i.AV_PIX_FMT_YUV422P12LE;case"I422A":return i.AV_PIX_FMT_YUVA422P;case"I422AP10":return i.AV_PIX_FMT_YUVA422P10LE;case"I422AP12":return i.AV_PIX_FMT_YUVA422P12LE;case"I444":return i.AV_PIX_FMT_YUV444P;case"I444P10":return i.AV_PIX_FMT_YUV444P10LE;case"I444P12":return i.AV_PIX_FMT_YUV444P12LE;case"I444A":return i.AV_PIX_FMT_YUVA444P;case"I444AP10":return i.AV_PIX_FMT_YUVA444P10LE;case"I444AP12":return i.AV_PIX_FMT_YUVA444P12LE;case"NV12":return i.AV_PIX_FMT_NV12;case"RGBA":return i.AV_PIX_FMT_RGBA;case"RGBX":return i.AV_PIX_FMT_RGB0;case"BGRA":return i.AV_PIX_FMT_BGRA;case"BGRX":return i.AV_PIX_FMT_BGR0;default:return i.AV_PIX_FMT_NONE}},Je=t=>{switch(t){case i.AV_SAMPLE_FMT_U8:return"u8";case i.AV_SAMPLE_FMT_S16:return"s16";case i.AV_SAMPLE_FMT_S32:return"s32";case i.AV_SAMPLE_FMT_FLT:return"f32";case i.AV_SAMPLE_FMT_U8P:return"u8-planar";case i.AV_SAMPLE_FMT_S16P:return"s16-planar";case i.AV_SAMPLE_FMT_S32P:return"s32-planar";case i.AV_SAMPLE_FMT_FLTP:return"f32-planar";default:return null}},je=t=>{switch(t){case"u8":return i.AV_SAMPLE_FMT_U8;case"s16":return i.AV_SAMPLE_FMT_S16;case"s32":return i.AV_SAMPLE_FMT_S32;case"f32":return i.AV_SAMPLE_FMT_FLT;case"u8-planar":return i.AV_SAMPLE_FMT_U8P;case"s16-planar":return i.AV_SAMPLE_FMT_S16P;case"s32-planar":return i.AV_SAMPLE_FMT_S32P;case"f32-planar":return i.AV_SAMPLE_FMT_FLTP;default:return i.AV_SAMPLE_FMT_NONE}},Z=t=>{switch(t){case 1:return i.AV_CHANNEL_LAYOUT_MONO;case 2:return i.AV_CHANNEL_LAYOUT_STEREO;case 4:return i.AV_CHANNEL_LAYOUT_QUAD;case 6:return i.AV_CHANNEL_LAYOUT_5POINT1_BACK;case 8:return i.AV_CHANNEL_LAYOUT_7POINT1;default:return{nbChannels:t,order:i.AV_CHANNEL_ORDER_UNSPEC,mask:0n}}};var U=class U{constructor(){}static get level(){return U._level}static set level(e){if(e!==0&&e!==1&&e!==2&&e!==3)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");U._level=e}static get _emitter(){return U._emitterInstance??=new ge}static on(e,r,o){return U._emitter.on(e,r,o)}static _error(...e){U._emitter._emit("error",e),U._level>=1&&console.error(...e)}static _warn(...e){U._emitter._emit("warn",e),U._level>=2&&console.warn(...e)}static _info(...e){U._emitter._emit("info",e),U._level>=3&&console.info(...e)}};U._level=3,U._emitterInstance=null;var te=U;function p(t){if(!t)throw new Error("Assertion failed.")}var ne=t=>t&&t[t.length-1];var d=t=>{let e=0;for(;t.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},K=t=>{let e=d(t);return(e&1)===0?-(e>>1):e+1>>1};var L=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),Re=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t);var $e={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12};var Ze={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18};var et={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9};var Ve=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join("");var Ne=t=>(t=t>>1&1431655765|(t&1431655765)<<1,t=t>>2&858993459|(t&858993459)<<2,t=t>>4&252645135|(t&252645135)<<4,t=t>>8&16711935|(t&16711935)<<8,t=t>>16&65535|(t&65535)<<16,t>>>0);var ie=(t,e,r)=>{let o=0,n=t.length-1,s=-1;for(;o<=n;){let a=o+(n-o+1)/2|0;r(t[a])<=e?(s=a,o=a+1):n=a-1}return s};var Me=t=>{throw new Error(`Unexpected value: ${t}`)};var tr=1e6*(1+Number.EPSILON);var Ce=t=>{p(Number.isInteger(t.num)),p(Number.isInteger(t.den)),p(t.den!==0);let e=Math.abs(t.num),r=Math.abs(t.den);for(;r!==0;){let n=e%r;e=r,r=n}let o=e||1;return{num:t.num/o,den:t.den/o}};var ge=class{constructor(){this._listeners=new Map}on(e,r,o){this._listeners.has(e)||this._listeners.set(e,new Set);let n={fn:r,once:o?.once??!1};return this._listeners.get(e).add(n),()=>{this._listeners.get(e)?.delete(n)}}_emit(...e){let[r,o]=e,n=this._listeners.get(r);if(n)for(let s of n){try{s.fn(o)}catch(a){console.error(a)}s.once&&n.delete(s)}}};var re=N("mediabunny"),f=$(N("node-av"));var Bt=new Set([f.AV_PIX_FMT_YUVJ411P,f.AV_PIX_FMT_YUVJ420P,f.AV_PIX_FMT_YUVJ422P,f.AV_PIX_FMT_YUVJ440P,f.AV_PIX_FMT_YUVJ444P]),q=class t extends re.VideoSampleResource{get frame(){if(!this._frame)throw new Error("AvFrameVideoSampleResource has been closed.");return this._frame}constructor(e){if(super(),!(e instanceof f.Frame))throw new TypeError("frame must be a NodeAv.Frame.");if(e.getMediaType()!==f.AVMEDIA_TYPE_VIDEO)throw new Error("AvFrameVideoSampleResource must be initialized with a video frame.");this._frame=e}getFormat(){return Qe(this.frame.format)}getCodedWidth(){return this.frame.width}getCodedHeight(){return this.frame.height}getSquarePixelWidth(){return this.frame.sampleAspectRatio.num>this.frame.sampleAspectRatio.den?Math.round(this.frame.width*this.frame.sampleAspectRatio.num/this.frame.sampleAspectRatio.den):this.frame.width}getSquarePixelHeight(){return this.frame.sampleAspectRatio.num>this.frame.sampleAspectRatio.den?this.frame.height:Math.round(this.frame.height*this.frame.sampleAspectRatio.den/this.frame.sampleAspectRatio.num)}getColorSpace(){return new re.VideoSampleColorSpace({primaries:fe(this.frame.colorPrimaries),transfer:pe(this.frame.colorTrc),matrix:he(this.frame.colorSpace),fullRange:this.frame.colorRange===f.AVCOL_RANGE_JPEG||Bt.has(this.frame.format)?!0:this.frame.colorRange===f.AVCOL_RANGE_MPEG?!1:null})}close(){this.frame.free(),this._frame=null}getDataPlanes(){return p(this.frame.data),this.frame.data.map((e,r)=>({data:L(e),stride:this.frame.linesize[r]}))}async toRgbSample(e,r){let o=this.frame.width,n=this.frame.height,s=new f.SoftwareScaleContext,a=this.frame.format,A=Fe("RGBA");s.getContext(o,n,a,o,n,A,f.SWS_BILINEAR);let m=new f.Frame;m.width=o,m.height=n,m.format=A,m.alloc(),m.allocBuffer();let c=this.frame;try{await s.scaleFrame(m,c)}finally{s.freeContext()}return m.sampleAspectRatio=c.sampleAspectRatio,new re.VideoSample(new t(m),e)}},Ae=async(t,e,r)=>{p(t.format!==null),e.format=Fe(t.format),e.width=t.codedWidth,e.height=t.codedHeight,e.sampleAspectRatio=new f.Rational(t.pixelAspectRatio.num,t.pixelAspectRatio.den),e.colorPrimaries=Xe(t.colorSpace.primaries??"unknown")??f.AVCOL_PRI_UNSPECIFIED,e.colorSpace=Ke(t.colorSpace.matrix??"unknown")??f.AVCOL_SPC_UNSPECIFIED,e.colorTrc=Ye(t.colorSpace.transfer??"unknown")??f.AVCOL_TRC_UNSPECIFIED,e.colorRange=t.colorSpace.fullRange===!1?f.AVCOL_RANGE_MPEG:t.colorSpace.fullRange===!0?f.AVCOL_RANGE_JPEG:f.AVCOL_RANGE_UNSPECIFIED;let o=t.allocationSize();return(!r||r.byteLength!==o)&&(r=Buffer.from({length:o})),await t.copyTo(r),e.fromBuffer(r),r},tt=async(t,e)=>{let r,o=!1;if(t._data instanceof q)r=t._data.frame;else{if(t.format===null)return null;r=new f.Frame,r.alloc(),o=!0,await Ae(t,r,null)}let n=[];(t.squarePixelWidth!==t.codedWidth||t.squarePixelHeight!==t.codedHeight)&&(n.push(`scale=${t.squarePixelWidth}:${t.squarePixelHeight}`),n.push("setsar=1")),e.rotation===90?n.push("transpose=1"):e.rotation===180?n.push("transpose=1,transpose=1"):e.rotation===270&&n.push("transpose=2"),n.push(`crop=${Math.round(e.crop.width)}:${Math.round(e.crop.height)}:${Math.round(e.crop.left)}:${Math.round(e.crop.top)}`),e.fit==="fill"?n.push(`scale=${e.width}:${e.height}`):e.fit==="contain"?(n.push(`scale=${e.width}:${e.height}:force_original_aspect_ratio=decrease`),n.push(`pad=${e.width}:${e.height}:(ow-iw)/2:(oh-ih)/2:color=black@0`)):e.fit==="cover"&&(n.push(`scale=${e.width}:${e.height}:force_original_aspect_ratio=increase`),n.push(`crop=${e.width}:${e.height}`)),n.push("setsar=1");let s=new f.FilterGraph;s.alloc();try{let a=`video_size=${r.width}x${r.height}:pix_fmt=${r.format}:time_base=1/1000000:pixel_aspect=${t.pixelAspectRatio.num}/${t.pixelAspectRatio.den}`,A=s.createFilter(f.Filter.getByName("buffer"),"src",a),m=s.createFilter(f.Filter.getByName("buffersink"),"sink");p(A&&m);let c=f.FilterInOut.createList([{name:"in",filterCtx:A,padIdx:0}]),l=f.FilterInOut.createList([{name:"out",filterCtx:m,padIdx:0}]),h=s.parsePtr(`[in]${n.join(",")}[out]`,l,c);f.FFmpegError.throwIfError(h,"FilterGraph.parsePtr");let S=await s.config();f.FFmpegError.throwIfError(S,"FilterGraph.config");let T=await A.buffersrcAddFrame(r);f.FFmpegError.throwIfError(T,"buffersrcAddFrame"),await A.buffersrcAddFrame(null);let g=new f.Frame;g.alloc();let x=await m.buffersinkGetFrame(g);return f.FFmpegError.throwIfError(x,"buffersinkGetFrame"),new re.VideoSample(new q(g),{timestamp:t.timestamp,duration:t.duration,rotation:0})}finally{s.free(),o&&r.free()}};var be=class extends xe.CustomVideoDecoder{constructor(){super(...arguments);this.codecContext=null;this.preciseTimings=[]}static supports(r,o){return r==="avc"||r==="hevc"||r==="vp8"||r==="vp9"||r==="av1"}async init(){this.frame=new b.Frame,this.frame.alloc(),this.packet=new b.Packet,this.packet.alloc()}async initCodecContext(r){p(this.codecContext===null);let o=J[this.codec];p(o!==void 0);let n;if(this.codec==="vp9"&&r.sideData.alpha?n=b.Codec.findDecoderByName(b.FF_DECODER_LIBVPX_VP9)??b.Codec.findDecoder(o):this.config.hardwareAcceleration==="prefer-software"||this.codec==="av1"?n=b.Codec.findDecoder(o):n=await We(o)??b.Codec.findDecoder(o),!n)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);let s=new b.CodecContext;s.allocContext3(n),this.pixelAspectRatio=Ce({num:(this.config.displayAspectWidth??this.config.codedWidth??0)*(this.config.codedHeight??0),den:(this.config.displayAspectHeight??this.config.codedHeight??0)*(this.config.codedWidth??0)||1}),s.width=this.config.codedWidth??0,s.height=this.config.codedHeight??0,s.codecType=b.AVMEDIA_TYPE_VIDEO,s.codecId=o,s.extraData=this.config.description?Buffer.from(L(this.config.description)):null,s.sampleAspectRatio=new b.Rational(this.pixelAspectRatio.num,this.pixelAspectRatio.den);let a=await s.open2();b.FFmpegError.throwIfError(a,"Open codec context"),this.codecContext=s}async decode(r){if(this.codecContext===null&&await this.initCodecContext(r),p(this.codecContext),this.packet.isKeyframe=r.type==="key",this.packet.data=Buffer.from(r.data),this.packet.timeBase={num:1,den:1e6},this.packet.pts=BigInt(r.microsecondTimestamp),this.packet.dts=b.AV_NOPTS_VALUE,this.packet.duration=BigInt(r.microsecondDuration),r.sideData.alpha){let a=Buffer.alloc(8+r.sideData.alpha.byteLength);a[7]=1,a.set(r.sideData.alpha,8),this.packet.addSideData(b.AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,a)}let o=ie(this.preciseTimings,r.microsecondTimestamp,a=>a.microsecondTimestamp),n=o!==-1?this.preciseTimings[o]:null;n&&n.microsecondTimestamp===r.microsecondTimestamp?(n.timestamp!==r.timestamp&&(n.timestampIsValid=!1),n.duration!==r.duration&&(n.durationIsValid=!1)):(this.preciseTimings.splice(o+1,0,{microsecondTimestamp:r.microsecondTimestamp,timestamp:r.timestamp,duration:r.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift());let s=await this.codecContext.sendPacket(this.packet);for(b.FFmpegError.throwIfError(s,"Send packet"),this.packet.unref();;){let a=await this.codecContext.receiveFrame(this.frame);if(a===b.AVERROR_EAGAIN||a===b.AVERROR_EOF)break;this.receiveFrame(a)}}receiveFrame(r){b.FFmpegError.throwIfError(r,"Receive frame"),this.frame.sampleAspectRatio=new b.Rational(this.pixelAspectRatio.num,this.pixelAspectRatio.den);let o=Number(this.frame.pts)/1e6,n=Number(this.frame.duration)/1e6,s=ie(this.preciseTimings,Number(this.frame.pts),m=>m.microsecondTimestamp),a=s!==-1?this.preciseTimings[s]:null;a&&a.microsecondTimestamp===Number(this.frame.pts)&&(a.timestampIsValid&&(o=a.timestamp),a.durationIsValid&&(n=a.duration));let A=this.frame.clone();if(!A)throw new Error("Frame clone allocation failed.");this.onSample(new xe.VideoSample(new q(A),{timestamp:o,duration:n}))}async flush(){if(!this.codecContext)return;let r=await this.codecContext.sendPacket(null);for(b.FFmpegError.throwIfError(r,"Flush decoder");;){let o=await this.codecContext.receiveFrame(this.frame);if(o===b.AVERROR_EAGAIN||o===b.AVERROR_EOF)break;this.receiveFrame(o)}this.codecContext.flushBuffers()}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free()}};var ae=N("mediabunny"),u=$(N("node-av"));var W=class t{constructor(e){this.bytes=e;this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),r=this.bytes[e]??0,o=7-(this.pos&7),n=(r&1<<o)>>o;return this.pos++,n}readBits(e){if(e===1)return this.readBit();let r=0;for(let o=0;o<e;o++)r<<=1,r|=this.readBit();return r}writeBits(e,r){let o=this.pos+e;for(let n=this.pos;n<o;n++){let s=Math.floor(n/8),a=this.bytes[s],A=7-(n&7);a&=~(1<<A),a|=(r&1<<o-n-1)>>o-n-1<<A,this.bytes[s]=a}this.pos=o}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let e=this.pos/8,r=this.bytes[e]??0;return this.pos+=8,r}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let e=new t(this.bytes);return e.pos=this.pos,e}};var rt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Pt=[-1,1,2,3,4,5,6,8],ot=t=>{if(!t||t.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let e=new W(t),r=e.readBits(5);r===31&&(r=32+e.readBits(6));let o=e.readBits(4),n=null;o===15?n=e.readBits(24):o<rt.length&&(n=rt[o]);let s=e.readBits(4),a=null;return s>=1&&s<=7&&(a=Pt[s]),{objectType:r,frequencyIndex:o,sampleRate:n,channelConfiguration:s,numberOfChannels:a}};var nt=t=>{let e=new Uint8Array(7),r=new W(e),{objectType:o,frequencyIndex:n,channelConfiguration:s}=t,a=o-1;return r.writeBits(12,4095),r.writeBits(1,0),r.writeBits(2,0),r.writeBits(1,1),r.writeBits(2,a),r.writeBits(4,n),r.writeBits(1,0),r.writeBits(3,s),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.skipBits(13),r.writeBits(11,2047),r.writeBits(2,0),{header:e,bitstream:r}};var Ft=["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"],yr=[...Rt,...Ft];var ke=[{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}];var oe=[{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}];var it=".01.01.01.01.00",st=".0.110.01.01.01.0",Vt=["ap4x","ap4h","apch","apcn","apcs","apco"];var se=t=>{let{codec:e,codecDescription:r,colorSpace:o,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:A,proresFormat:m}=t;if(e==="avc"){if(p(t.avcType!==null),n){let c=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${t.avcType}.${Ve(c)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${t.avcType}.${Ve(r.subarray(1,4))}`}else if(e==="hevc"){let c,l,h,S,T,g;if(s)c=s.generalProfileSpace,l=s.generalProfileIdc,h=Ne(s.generalProfileCompatibilityFlags),S=s.generalTierFlag,T=s.generalLevelIdc,g=[...s.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let C=Re(r),_=C.getUint8(1);c=_>>6&3,l=_&31,h=Ne(C.getUint32(2)),S=_>>5&1,T=C.getUint8(12),g=[];for(let P=0;P<6;P++)g.push(C.getUint8(6+P))}let x="hev1.";for(x+=["","A","B","C"][c]+l,x+=".",x+=h.toString(16).toUpperCase(),x+=".",x+=S===0?"L":"H",x+=T;g.length>0&&g[g.length-1]===0;)g.pop();return g.length>0&&(x+=".",x+=g.map(C=>C.toString(16).toUpperCase()).join(".")),x}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){let P=t.width*t.height,I=ne(oe).level;for(let F of oe)if(P<=F.maxPictureSize){I=F.level;break}return`vp09.00.${I.toString().padStart(2,"0")}.08`}let c=a.profile.toString().padStart(2,"0"),l=a.level.toString().padStart(2,"0"),h=a.bitDepth.toString().padStart(2,"0"),S=a.chromaSubsampling.toString().padStart(2,"0"),T=a.colourPrimaries.toString().padStart(2,"0"),g=a.transferCharacteristics.toString().padStart(2,"0"),x=a.matrixCoefficients.toString().padStart(2,"0"),C=a.videoFullRangeFlag.toString().padStart(2,"0"),_=`vp09.${c}.${l}.${h}.${S}`;return _+=`.${T}.${g}.${x}.${C}`,_.endsWith(it)&&(_=_.slice(0,-it.length)),_}else if(e==="av1"){if(!A){let F=t.width*t.height,w=ne(oe).level;for(let y of oe)if(F<=y.maxPictureSize){w=y.level;break}return`av01.0.${w.toString().padStart(2,"0")}M.08`}let c=A.profile,l=A.level.toString().padStart(2,"0"),h=A.tier?"H":"M",S=A.bitDepth.toString().padStart(2,"0"),T=A.monochrome?"1":"0",g=100*A.chromaSubsamplingX+10*A.chromaSubsamplingY+1*(A.chromaSubsamplingX&&A.chromaSubsamplingY?A.chromaSamplePosition:0),x=o?.primaries?$e[o.primaries]:1,C=o?.transfer?Ze[o.transfer]:1,_=o?.matrix?et[o.matrix]:1,P=o?.fullRange?1:0,I=`av01.${c}.${l}${h}.${S}`;return I+=`.${T}.${g.toString().padStart(3,"0")}`,I+=`.${x.toString().padStart(2,"0")}`,I+=`.${C.toString().padStart(2,"0")}`,I+=`.${_.toString().padStart(2,"0")}`,I+=`.${P}`,I.endsWith(st)&&(I=I.slice(0,-st.length)),I}else{if(e==="prores")return m??"apch";e!==null&&Me(e)}}throw new TypeError(`Unhandled codec '${e}'.`)};var Er=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Vt];var _e=function*(t){let e=0,r=-1;for(;e<t.length-2;){let o=t.indexOf(0,e);if(o===-1||o>=t.length-2)break;e=o;let n=0;if(e+3<t.length&&t[e+1]===0&&t[e+2]===0&&t[e+3]===1?n=4:t[e+1]===0&&t[e+2]===1&&(n=3),n===0){e++;continue}r!==-1&&e>r&&(yield{offset:r,length:e-r}),r=e+n,e=r}r!==-1&&r<t.length&&(yield{offset:r,length:t.length-r})};var Ue=t=>t&31,Le=t=>{let e=[],r=t.length;for(let o=0;o<r;o++)o+2<r&&t[o]===0&&t[o+1]===0&&t[o+2]===3?(e.push(0,0),o+=2):e.push(t[o]);return new Uint8Array(e)},Dr=new Uint8Array([0,0,0,1]);var lt=t=>{try{let e=[],r=[],o=[];for(let A of _e(t)){let m=t.subarray(A.offset,A.offset+A.length),c=Ue(m[0]);c===7?e.push(m):c===8?r.push(m):c===13&&o.push(m)}if(e.length===0||r.length===0)return null;let n=e[0],s=Nt(n);p(s!==null);let a=s.profileIdc===100||s.profileIdc===110||s.profileIdc===122||s.profileIdc===144;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:r,chromaFormat:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?o:null}}catch(e){return te._error("Error building AVC Decoder Configuration Record:",e),null}},dt=t=>{let e=[];e.push(t.configurationVersion),e.push(t.avcProfileIndication),e.push(t.profileCompatibility),e.push(t.avcLevelIndication),e.push(252|t.lengthSizeMinusOne&3),e.push(224|t.sequenceParameterSets.length&31);for(let r of t.sequenceParameterSets){let o=r.byteLength;e.push(o>>8),e.push(o&255);for(let n=0;n<o;n++)e.push(r[n])}e.push(t.pictureParameterSets.length);for(let r of t.pictureParameterSets){let o=r.byteLength;e.push(o>>8),e.push(o&255);for(let n=0;n<o;n++)e.push(r[n])}if(t.avcProfileIndication===100||t.avcProfileIndication===110||t.avcProfileIndication===122||t.avcProfileIndication===144){p(t.chromaFormat!==null),p(t.bitDepthLumaMinus8!==null),p(t.bitDepthChromaMinus8!==null),p(t.sequenceParameterSetExt!==null),e.push(252|t.chromaFormat&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.sequenceParameterSetExt.length);for(let r of t.sequenceParameterSetExt){let o=r.byteLength;e.push(o>>8),e.push(o&255);for(let n=0;n<o;n++)e.push(r[n])}}return new Uint8Array(e)};var At={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Nt=t=>{try{let e=new W(Le(t));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let o=e.readAlignedByte(),n=e.readAlignedByte(),s=e.readAlignedByte();d(e);let a=1,A=0,m=0,c=0;if((o===100||o===110||o===122||o===244||o===44||o===83||o===86||o===118||o===128)&&(a=d(e),a===3&&(c=e.readBits(1)),A=d(e),m=d(e),e.skipBits(1),e.readBits(1))){for(let E=0;E<(a!==3?8:12);E++)if(e.readBits(1)){let j=E<6?16:64,H=8,V=8;for(let z=0;z<j;z++){if(V!==0){let ee=K(e);V=(H+ee+256)%256}H=V===0?H:V}}}d(e);let l=d(e);if(l===0)d(e);else if(l===1){e.skipBits(1),K(e),K(e);let O=d(e);for(let E=0;E<O;E++)K(e)}d(e),e.skipBits(1);let h=d(e),S=d(e),T=16*(h+1),g=16*(S+1),x=T,C=g,_=e.readBits(1);if(_||e.skipBits(1),e.skipBits(1),e.readBits(1)){let O=d(e),E=d(e),X=d(e),j=d(e),H,V;if((c===0?a:0)===0)H=1,V=2-_;else{let ee=a===3?1:2,de=a===1?2:1;H=ee,V=de*(2-_)}x-=H*(O+E),C-=V*(X+j)}let I=2,F=2,w=2,y=0,M={num:1,den:1},R=null,D=null;if(e.readBits(1)){if(e.readBits(1)){let de=e.readBits(8);if(de===255)M={num:e.readBits(16),den:e.readBits(16)};else{let De=At[de];De&&(M=De)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),y=e.readBits(1),e.readBits(1)&&(I=e.readBits(8),F=e.readBits(8),w=e.readBits(8))),e.readBits(1)&&(d(e),d(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));let V=e.readBits(1);V&&at(e);let z=e.readBits(1);z&&at(e),(V||z)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),d(e),d(e),d(e),d(e),R=d(e),D=d(e))}if(R===null){p(D===null);let O=n&16;if((o===44||o===86||o===100||o===110||o===122||o===244)&&O)R=0,D=0;else{let E=h+1,X=S+1,j=(2-_)*X,H=ke.find(z=>z.level>=s)??ne(ke),V=Math.min(Math.floor(H.maxDpbMbs/(E*j)),16);R=V,D=V}}return p(D!==null),{profileIdc:o,constraintFlags:n,levelIdc:s,frameMbsOnlyFlag:_,chromaFormatIdc:a,bitDepthLumaMinus8:A,bitDepthChromaMinus8:m,codedWidth:T,codedHeight:g,displayWidth:x,displayHeight:C,pixelAspectRatio:M,colourPrimaries:I,matrixCoefficients:w,transferCharacteristics:F,fullRangeFlag:y,numReorderFrames:R,maxDecFrameBuffering:D}}catch(e){return te._error("Error parsing AVC SPS:",e),null}},at=t=>{let e=d(t);t.skipBits(4),t.skipBits(4);for(let r=0;r<=e;r++)d(t),d(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)};var ve=t=>t>>1&63,Mt=t=>{try{let e=new W(Le(t));e.skipBits(16),e.readBits(4);let r=e.readBits(3),o=e.readBits(1),{general_profile_space:n,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:A,general_constraint_indicator_flags:m,general_level_idc:c}=kt(e,r);d(e);let l=d(e),h=0;l===3&&(h=e.readBits(1));let S=d(e),T=d(e),g=S,x=T;if(e.readBits(1)){let E=d(e),X=d(e),j=d(e),H=d(e),V=1,z=1,ee=h===0?l:0;ee===1?(V=2,z=2):ee===2&&(V=2,z=1),g-=(E+X)*V,x-=(j+H)*z}let C=d(e),_=d(e);d(e);let I=e.readBits(1)?0:r,F=0;for(let E=I;E<=r;E++)d(e),F=d(e),d(e);d(e),d(e),d(e),d(e),d(e),d(e),e.readBits(1)&&e.readBits(1)&&Ut(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),d(e),d(e),e.skipBits(1));let w=d(e);if(Lt(e,w),e.readBits(1)){let E=d(e);for(let X=0;X<E;X++)d(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let y=2,M=2,R=2,D=0,ue=0,O={num:1,den:1};if(e.readBits(1)){let E=Dt(e,r);O=E.pixelAspectRatio,y=E.colourPrimaries,M=E.transferCharacteristics,R=E.matrixCoefficients,D=E.fullRangeFlag,ue=E.minSpatialSegmentationIdc}return{displayWidth:g,displayHeight:x,pixelAspectRatio:O,colourPrimaries:y,transferCharacteristics:M,matrixCoefficients:R,fullRangeFlag:D,maxDecFrameBuffering:F+1,spsMaxSubLayersMinus1:r,spsTemporalIdNestingFlag:o,generalProfileSpace:n,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:A,generalConstraintIndicatorFlags:m,generalLevelIdc:c,chromaFormatIdc:l,bitDepthLumaMinus8:C,bitDepthChromaMinus8:_,minSpatialSegmentationIdc:ue}}catch(e){return te._error("Error parsing HEVC SPS:",e),null}},ut=t=>{try{let e=[],r=[],o=[],n=[];for(let c of _e(t)){let l=t.subarray(c.offset,c.offset+c.length),h=ve(l[0]);h===32?e.push(l):h===33?r.push(l):h===34?o.push(l):(h===39||h===40)&&n.push(l)}if(r.length===0||o.length===0)return null;let s=Mt(r[0]);if(!s)return null;let a=0;if(o.length>0){let c=o[0],l=new W(Le(c));l.skipBits(16),d(l),d(l),l.skipBits(1),l.skipBits(1),l.skipBits(3),l.skipBits(1),l.skipBits(1),d(l),d(l),K(l),l.skipBits(1),l.skipBits(1),l.readBits(1)&&d(l),K(l),K(l),l.skipBits(1),l.skipBits(1),l.skipBits(1),l.skipBits(1);let h=l.readBits(1),S=l.readBits(1);!h&&!S?a=0:h&&!S?a=2:!h&&S?a=3:a=0}let A=[...e.length?[{arrayCompleteness:1,nalUnitType:32,nalUnits:e}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:33,nalUnits:r}]:[],...o.length?[{arrayCompleteness:1,nalUnitType:34,nalUnits:o}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:ve(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:A}}catch(e){return te._error("Error building HEVC Decoder Configuration Record:",e),null}},kt=(t,e)=>{let r=t.readBits(2),o=t.readBits(1),n=t.readBits(5),s=0;for(let l=0;l<32;l++)s=s<<1|t.readBits(1);let a=new Uint8Array(6);for(let l=0;l<6;l++)a[l]=t.readBits(8);let A=t.readBits(8),m=[],c=[];for(let l=0;l<e;l++)m.push(t.readBits(1)),c.push(t.readBits(1));if(e>0)for(let l=e;l<8;l++)t.skipBits(2);for(let l=0;l<e;l++)m[l]&&t.skipBits(88),c[l]&&t.skipBits(8);return{general_profile_space:r,general_tier_flag:o,general_profile_idc:n,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:A}},Ut=t=>{for(let e=0;e<4;e++)for(let r=0;r<(e===3?2:6);r++)if(!t.readBits(1))d(t);else{let n=Math.min(64,1<<4+(e<<1));e>1&&K(t);for(let s=0;s<n;s++)K(t)}},Lt=(t,e)=>{let r=[];for(let o=0;o<e;o++)r[o]=Ot(t,o,e,r)},Ot=(t,e,r,o)=>{let n=0,s=0,a=0;if(e!==0&&(s=t.readBits(1)),s){if(e===r){let m=d(t);a=e-(m+1)}else a=e-1;t.readBits(1),d(t);let A=o[a]??0;for(let m=0;m<=A;m++)t.readBits(1)||t.readBits(1);n=o[a]}else{let A=d(t),m=d(t);for(let c=0;c<A;c++)d(t),t.readBits(1);for(let c=0;c<m;c++)d(t),t.readBits(1);n=A+m}return n},Dt=(t,e)=>{let r=2,o=2,n=2,s=0,a=0,A={num:1,den:1};if(t.readBits(1)){let m=t.readBits(8);if(m===255)A={num:t.readBits(16),den:t.readBits(16)};else{let c=At[m];c&&(A=c)}}return t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),s=t.readBits(1),t.readBits(1)&&(r=t.readBits(8),o=t.readBits(8),n=t.readBits(8))),t.readBits(1)&&(d(t),d(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(d(t),d(t),d(t),d(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&d(t),t.readBits(1)&&Ht(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),a=d(t),d(t),d(t),d(t),d(t)),{pixelAspectRatio:A,colourPrimaries:r,transferCharacteristics:o,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},Ht=(t,e,r)=>{let o=!1,n=!1,s=!1;e&&(o=t.readBits(1)===1,n=t.readBits(1)===1,(o||n)&&(s=t.readBits(1)===1,s&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),s&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5)));for(let a=0;a<=r;a++){let A=t.readBits(1)===1,m=!0;A||(m=t.readBits(1)===1);let c=!1;m?d(t):c=t.readBits(1)===1;let l=1;c||(l=d(t)+1),o&&ct(t,l,s),n&&ct(t,l,s)}},ct=(t,e,r)=>{for(let o=0;o<e;o++)d(t),d(t),r&&(d(t),d(t)),t.readBits(1)},mt=t=>{let e=[];e.push(t.configurationVersion),e.push((t.generalProfileSpace&3)<<6|(t.generalTierFlag&1)<<5|t.generalProfileIdc&31),e.push(t.generalProfileCompatibilityFlags>>>24&255),e.push(t.generalProfileCompatibilityFlags>>>16&255),e.push(t.generalProfileCompatibilityFlags>>>8&255),e.push(t.generalProfileCompatibilityFlags&255),e.push(...t.generalConstraintIndicatorFlags),e.push(t.generalLevelIdc&255),e.push(240|t.minSpatialSegmentationIdc>>8&15),e.push(t.minSpatialSegmentationIdc&255),e.push(252|t.parallelismType&3),e.push(252|t.chromaFormatIdc&3),e.push(248|t.bitDepthLumaMinus8&7),e.push(248|t.bitDepthChromaMinus8&7),e.push(t.avgFrameRate>>8&255),e.push(t.avgFrameRate&255),e.push((t.constantFrameRate&3)<<6|(t.numTemporalLayers&7)<<3|(t.temporalIdNested&1)<<2|t.lengthSizeMinusOne&3),e.push(t.arrays.length&255);for(let r of t.arrays){e.push((r.arrayCompleteness&1)<<7|0|r.nalUnitType&63),e.push(r.nalUnits.length>>8&255),e.push(r.nalUnits.length&255);for(let o of r.nalUnits){e.push(o.length>>8&255),e.push(o.length&255);for(let n=0;n<o.length;n++)e.push(o[n])}}return new Uint8Array(e)};var ft=t=>{let e=new W(t);if(e.readBits(2)!==2)return null;let o=e.readBits(1),s=(e.readBits(1)<<1)+o;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let c=8;s>=2&&(c=e.readBits(1)?12:10);let l=e.readBits(3),h=0,S=0;if(l!==7)if(S=e.readBits(1),s===1||s===3){let M=e.readBits(1),R=e.readBits(1);h=!M&&!R?3:M&&!R?2:1,e.skipBits(1)}else h=1;else h=3,S=1;let T=e.readBits(16),g=e.readBits(16),x=T+1,C=g+1,_=x*C,P=ne(oe).level;for(let y of oe)if(_<=y.maxPictureSize){P=y.level;break}return{profile:s,level:P,bitDepth:c,chromaSubsampling:h,videoFullRangeFlag:S,colourPrimaries:l===2?1:l===1?6:2,transferCharacteristics:l===2?1:l===1?6:2,matrixCoefficients:l===7?0:l===2?1:l===1?6:2}},zt=function*(t){let e=new W(t),r=()=>{let o=0;for(let n=0;n<8;n++){let s=e.readAlignedByte();if(o|=(s&127)<<n*7,!(s&128))break;if(n===7&&s&128)return null}return o>=2**32-1?null:o};for(;e.getBitsLeft()>=8;){e.skipBits(1);let o=e.readBits(4),n=e.readBits(1),s=e.readBits(1);e.skipBits(1),n&&e.skipBits(8);let a;if(s){let A=r();if(A===null)return;a=A}else a=Math.floor(e.getBitsLeft()/8);p(e.pos%8===0),yield{type:o,data:t.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},pt=t=>{for(let{type:e,data:r}of zt(t)){if(e!==1)continue;let o=new W(r),n=o.readBits(3),s=o.readBits(1),a=o.readBits(1),A=0,m=0,c=0;if(a)A=o.readBits(5);else{if(o.readBits(1)&&(o.skipBits(32),o.skipBits(32),o.readBits(1)))return null;let y=o.readBits(1);y&&(c=o.readBits(5),o.skipBits(32),o.skipBits(5),o.skipBits(5));let M=o.readBits(5);for(let R=0;R<=M;R++){o.skipBits(12);let D=o.readBits(5);if(R===0&&(A=D),D>7){let O=o.readBits(1);R===0&&(m=O)}if(y&&o.readBits(1)){let E=c+1;o.skipBits(E),o.skipBits(E),o.skipBits(1)}o.readBits(1)&&o.skipBits(4)}}let l=o.readBits(4),h=o.readBits(4),S=l+1;o.skipBits(S);let T=h+1;o.skipBits(T);let g=0;if(a?g=0:g=o.readBits(1),g&&(o.skipBits(4),o.skipBits(3)),o.skipBits(1),o.skipBits(1),o.skipBits(1),!a){o.skipBits(1),o.skipBits(1),o.skipBits(1),o.skipBits(1);let w=o.readBits(1);w&&(o.skipBits(1),o.skipBits(1));let y=o.readBits(1),M=0;y?M=2:M=o.readBits(1),M>0&&(o.readBits(1)||o.skipBits(1)),w&&o.skipBits(3)}o.skipBits(1),o.skipBits(1),o.skipBits(1);let x=o.readBits(1),C=8;n===2&&x?C=o.readBits(1)?12:10:n<=2&&(C=x?10:8);let _=0;n!==1&&(_=o.readBits(1));let P=1,I=1,F=0;return _||(n===0?(P=1,I=1):n===1?(P=0,I=0):C===12&&(P=o.readBits(1),P&&(I=o.readBits(1))),P&&I&&(F=o.readBits(2))),{profile:n,level:A,tier:m,bitDepth:C,monochrome:_,chromaSubsamplingX:P,chromaSubsamplingY:I,chromaSamplePosition:F}}return null};var Hr=[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];var zr=new Uint8Array([5,4,65,67,45,51]),qr=new Uint8Array([5,4,69,65,67,51]);var qt={apco:u.AV_PROFILE_PRORES_PROXY,apcs:u.AV_PROFILE_PRORES_LT,apcn:u.AV_PROFILE_PRORES_STANDARD,apch:u.AV_PROFILE_PRORES_HQ,ap4h:u.AV_PROFILE_PRORES_4444,ap4x:u.AV_PROFILE_PRORES_XQ},ye=class extends ae.CustomVideoEncoder{constructor(){super(...arguments);this.codecContext=null;this.scaler=null;this.dstFrame=null;this.lastBuffer=null;this.packetEmitted=!1;this.lastScalerKey=null;this.preciseTimings=[]}static supports(r,o){return(r==="avc"||r==="hevc"||r==="vp8"||r==="vp9"||r==="av1"||r==="prores")&&o.bitrateMode!=="quantizer"}async init(){this.frame=new u.Frame,this.frame.alloc(),this.frame.timeBase=new u.Rational(1,1e6),this.packet=new u.Packet,this.packet.alloc();let r=J[this.codec];p(r!==void 0);let o=()=>{if(this.codec==="prores"){let s=u.Codec.findEncoderByName(u.FF_ENCODER_PRORES_KS);if(s)return s}return u.Codec.findEncoder(r)},n=null;if(this.codec==="vp9"&&this.config.alpha==="keep"?n=u.Codec.findEncoderByName(u.FF_ENCODER_LIBVPX_VP9)??u.Codec.findEncoder(r):this.config.hardwareAcceleration==="prefer-software"?n=o():n=await Ge(r)??o(),!n)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);this.avCodec=n,await this.createCodecContext()}async createCodecContext(){p(this.codecContext===null);let r=new u.CodecContext;r.allocContext3(this.avCodec);let o=u.AV_PIX_FMT_YUV420P;this.avCodec.pixelFormats&&(this.avCodec.pixelFormats.includes(u.AV_PIX_FMT_YUV420P)||(o=this.avCodec.pixelFormats[0]),this.config.alpha==="keep"&&(this.avCodec.pixelFormats.includes(u.AV_PIX_FMT_YUVA420P)?o=u.AV_PIX_FMT_YUVA420P:o=u.avcodecFindBestPixFmtOfList(this.avCodec.pixelFormats,u.AV_PIX_FMT_YUVA444P12LE)));let n=Ce({num:(this.config.displayWidth??this.config.width)*this.config.height,den:(this.config.displayHeight??this.config.height)*this.config.width});r.width=this.config.width,r.height=this.config.height,r.pixelFormat=o,r.timeBase=new u.Rational(1,1e6),r.gopSize=60,r.framerate=new u.Rational(Math.round(this.config.framerate??0)||30,1),r.bitRate=BigInt(this.config.bitrate??ae.QUALITY_MEDIUM._toVideoBitrate(this.codec,this.config.width,this.config.height)),r.sampleAspectRatio=new u.Rational(n.num,n.den),this.config.bitrateMode==="constant"&&(r.rcMinRate=r.bitRate,r.rcMaxRate=r.bitRate);let s=this.config.latencyMode==="realtime";if(this.avCodec.name==="libx264"?s&&(r.setOption("tune","zerolatency"),r.setOption("preset","ultrafast")):this.avCodec.name==="libx265"?(r.setOption("x265-params","log-level=error"),s&&(r.setOption("tune","zerolatency"),r.setOption("preset","ultrafast"))):this.avCodec.name==="libvpx"?(s&&r.setOption("deadline","realtime"),r.setOption("cpu-used","8")):this.avCodec.name==="libvpx-vp9"?(r.setOption("deadline","realtime"),s?r.setOption("cpu-used","8"):r.setOption("cpu-used","5")):this.avCodec.name==="libsvtav1"&&(process.env.SVT_LOG="1",s&&r.setOption("preset","12")),this.codec==="prores"){let A=qt[this.config.codec];p(A!==void 0),r.setOption("profile",String(A))}let a=await r.open2();u.FFmpegError.throwIfError(a,"Open codec context"),this.codecContext=r}async encode(r,o){if(this.codecContext===null&&await this.createCodecContext(),p(this.codecContext),r._data instanceof q)this.frame.unref(),this.frame.ref(r._data.frame);else{if(r.format===null)throw new Error("Cannot encode foreign VideoSample with unknown (null) format.");this.lastBuffer=await Ae(r,this.frame,this.lastBuffer)}let n=this.frame;if(this.codecContext.pixelFormat!==this.frame.format||this.codecContext.width!==this.frame.width||this.codecContext.height!==this.frame.height){this.scaler||(this.scaler=new u.SoftwareScaleContext);let c=`${this.frame.width}x${this.frame.height}:${this.frame.format}`;if(c!==this.lastScalerKey){this.scaler.getContext(this.frame.width,this.frame.height,this.frame.format,this.codecContext.width,this.codecContext.height,this.codecContext.pixelFormat,u.SWS_FAST_BILINEAR),this.lastScalerKey=c;let h=this.scaler.initContext();u.FFmpegError.throwIfError(h,"initContext")}this.dstFrame||(this.dstFrame=new u.Frame,this.dstFrame.alloc(),this.dstFrame.width=this.codecContext.width,this.dstFrame.height=this.codecContext.height,this.dstFrame.format=this.codecContext.pixelFormat,this.dstFrame.allocBuffer()),await this.scaler.scaleFrame(this.dstFrame,this.frame),this.dstFrame.copyProps(this.frame),n=this.dstFrame}n.pts=BigInt(r.microsecondTimestamp),n.duration=BigInt(r.microsecondDuration),n.timeBase=new u.Rational(1,1e6),n.pictType=o?.keyFrame?u.AV_PICTURE_TYPE_I:u.AV_PICTURE_TYPE_NONE,n.keyFrame=o?.keyFrame?1:0;let a=ie(this.preciseTimings,r.microsecondTimestamp,c=>c.microsecondTimestamp),A=a!==-1?this.preciseTimings[a]:null;A&&A.microsecondTimestamp===r.microsecondTimestamp?(A.timestamp!==r.timestamp&&(A.timestampIsValid=!1),A.duration!==r.duration&&(A.durationIsValid=!1)):(this.preciseTimings.splice(a+1,0,{microsecondTimestamp:r.microsecondTimestamp,timestamp:r.timestamp,duration:r.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift());let m=await this.codecContext.sendFrame(n);for(u.FFmpegError.throwIfError(m,"Send frame");;){let c=await this.codecContext.receivePacket(this.packet);if(c===u.AVERROR_EAGAIN||c===u.AVERROR_EOF)break;this.receivePacket(c)}}receivePacket(r){if(p(this.codecContext),u.FFmpegError.throwIfError(r,"Receive packet"),!this.packet.data)return;let o=L(this.packet.data),n=Number(this.packet.pts)/1e6,s=Number(this.packet.duration)/1e6,a=ie(this.preciseTimings,Number(this.packet.pts),g=>g.microsecondTimestamp),A=a!==-1?this.preciseTimings[a]:null;A&&A.microsecondTimestamp===Number(this.packet.pts)&&(A.timestampIsValid&&(n=A.timestamp),A.durationIsValid&&(s=A.duration));let m={},c=null,l=null;if(this.codec==="avc"||this.codec==="hevc"){let g=!1;if(this.codec==="avc"?g=this.config.avc?.format==="annexb":g=this.config.hevc?.format==="annexb",!this.packetEmitted){let x;if(this.codec==="avc"){let C=lt(this.packet.data);if(!C)throw new Error("Invalid AVC data, could not extract decoder configuration record.");x=dt(C)}else{let C=ut(this.packet.data);if(!C)throw new Error("Invalid HEVC data, could not extract decoder configuration record.");x=mt(C)}c=se({width:this.config.width,height:this.config.height,codec:this.codec,codecDescription:x,colorSpace:null,avcType:1,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),g||(l=x)}if(!g){let C=[];for(let w of _e(o))if(this.codec==="avc"){let y=Ue(o[w.offset]);y!==7&&y!==8&&y!==13&&C.push(w)}else{let y=ve(o[w.offset]);y!==33&&y!==34&&y!==32&&C.push(w)}let _=0;for(let w of C)_+=4+w.length;let P=new Uint8Array(_),I=new DataView(P.buffer),F=0;for(let w of C){let y=w.length;I.setUint32(F,y,!1),F+=4,P.set(o.subarray(w.offset,w.offset+w.length),F),F+=w.length}o=P}}else if(this.codec==="vp8")this.packetEmitted||(c=se({width:this.config.width,height:this.config.height,codec:"vp8",codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}));else if(this.codec==="vp9"){if(!this.packetEmitted){let g=ft(o);c=se({width:this.config.width,height:this.config.height,codec:"vp9",codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:g,av1CodecInfo:null,proresFormat:null})}}else if(this.codec==="av1"){if(!this.packetEmitted){let g=pt(o);c=se({width:this.config.width,height:this.config.height,codec:"av1",codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:g,proresFormat:null})}}else if(this.codec==="prores")this.packetEmitted||(c=se({width:this.config.width,height:this.config.height,codec:"prores",codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:this.config.codec}));else throw new Error("Unreachable.");let h={},S=this.packet.getSideData(u.AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL);S&&(h.alpha=L(S).subarray(8));let T=new ae.EncodedPacket(o,this.packet.isKeyframe?"key":"delta",n,s,void 0,void 0,h);c!==null&&(m.decoderConfig={codec:c,codedWidth:this.codecContext.width,codedHeight:this.codecContext.height,displayAspectWidth:this.config.displayWidth??this.codecContext.width,displayAspectHeight:this.config.displayHeight??this.codecContext.height,description:l??void 0,colorSpace:{primaries:fe(this.codecContext.colorPrimaries),matrix:he(this.codecContext.colorSpace),transfer:pe(this.codecContext.colorTrc),fullRange:this.codecContext.colorRange===u.AVCOL_RANGE_JPEG?!0:this.codecContext.colorRange===u.AVCOL_RANGE_MPEG?!1:void 0}}),this.packetEmitted=!0,this.onPacket(T,m)}async flush(){if(this.codecContext){let r=await this.codecContext.sendFrame(null);for(u.FFmpegError.throwIfError(r,"Send frame");;){let o=await this.codecContext.receivePacket(this.packet);if(o===u.AVERROR_EAGAIN||o===u.AVERROR_EOF)break;this.receivePacket(o)}this.codecContext.freeContext(),this.codecContext=null}this.packetEmitted=!1}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free(),this.scaler?.freeContext(),this.dstFrame?.free()}};var Ie=N("mediabunny"),B=$(N("node-av"));var ht=N("mediabunny"),ce=$(N("node-av"));var Q=class extends ht.AudioSampleResource{get frame(){if(!this._frame)throw new Error("AvFrameAudioSampleResource has been closed.");return this._frame}constructor(e){if(super(),!(e instanceof ce.Frame))throw new TypeError("frame must be a NodeAv.Frame.");if(e.getMediaType()!==ce.AVMEDIA_TYPE_AUDIO)throw new Error("AvFrameAudioSampleResource must be initialized with an audio frame.");this._frame=e}getFormat(){let e=Je(this.frame.format);if(e===null){let r=ce.avGetSampleFmtName(this.frame.format);throw new TypeError(`Unsupported audio sample format: ${r} (${this.frame.format})`)}return e}getSampleRate(){return this.frame.sampleRate}getNumberOfChannels(){return this.frame.channels}getNumberOfFrames(){return this.frame.nbSamples}getTimestamp(){return Number(this.frame.pts)/this.frame.timeBase.den}close(){this.frame.free(),this._frame=null}getDataPlane(e){return p(this.frame.data&&e<this.frame.data.length),L(this.frame.data[e])}},Ee=(t,e)=>{e.format=je(t.format),e.nbSamples=t.numberOfFrames,e.sampleRate=t.sampleRate,e.channelLayout=Z(t.numberOfChannels),e.allocBuffer(),p(e.data);for(let r=0;r<e.data.length;r++)t.copyTo(e.data[r],{planeIndex:r})};var Se=class extends Ie.CustomAudioDecoder{constructor(){super(...arguments);this.codecContext=null}static supports(r,o){return r==="aac"||r==="opus"||r==="mp3"||r==="vorbis"||r==="flac"||r==="ac3"||r==="eac3"}async init(){this.frame=new B.Frame,this.frame.alloc(),this.packet=new B.Packet,this.packet.alloc();let r=J[this.codec];p(r!==void 0);let o=B.Codec.findDecoder(r);if(o===null)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);let n=new B.CodecContext;n.allocContext3(o),n.sampleRate=this.config.sampleRate,n.channelLayout=Z(this.config.numberOfChannels),n.timeBase=new B.Rational(1,this.config.sampleRate),n.codecType=B.AVMEDIA_TYPE_AUDIO,n.codecId=r,n.extraData=this.config.description?Buffer.from(L(this.config.description)):null;let s=await n.open2();B.FFmpegError.throwIfError(s,"Open codec context"),this.codecContext=n}async decode(r){p(this.codecContext),this.packet.isKeyframe=r.type==="key",this.packet.data=Buffer.from(r.data),this.packet.timeBase={num:1,den:this.config.sampleRate},this.packet.pts=BigInt(Math.round(r.timestamp*this.config.sampleRate)),this.packet.dts=B.AV_NOPTS_VALUE,this.packet.duration=BigInt(Math.round(r.duration*this.config.sampleRate));let o=await this.codecContext.sendPacket(this.packet);for(B.FFmpegError.throwIfError(o,"Send packet"),this.packet.unref();;){let n=await this.codecContext.receiveFrame(this.frame);if(n===B.AVERROR_EAGAIN||n===B.AVERROR_EOF)break;this.receiveFrame(n)}}receiveFrame(r){B.FFmpegError.throwIfError(r,"Receive frame");let o=this.frame.clone();if(!o)throw new Error("Allocation failure during frame clone.");o.timeBase=new B.Rational(1,this.config.sampleRate),this.onSample(new Ie.AudioSample(new Q(o)))}async flush(){p(this.codecContext);let r=await this.codecContext.sendPacket(null);for(B.FFmpegError.throwIfError(r,"Flush decoder");;){let o=await this.codecContext.receiveFrame(this.frame);if(o===B.AVERROR_EAGAIN||o===B.AVERROR_EOF)break;this.receiveFrame(o)}this.codecContext.flushBuffers()}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free()}};var le=N("mediabunny"),v=$(N("node-av"));var Wt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Gt=[8e3,12e3,16e3,24e3,48e3],Xt=[8e3,11025,12e3,16e3,22050,24e3,32e3,44100,48e3],gt=[32e3,44100,48e3],Oe=1024,we=class extends le.CustomAudioEncoder{constructor(){super(...arguments);this.codecContext=null;this.resampler=null;this.dstFrame=null;this.firstExpectedTimestamp=null;this.outputTimestampOffset=0;this.inputParametersKey=null;this.resamplerInputSampleRate=null;this.nextResamplerPts=null;this.packetEmitted=!1;this.adtsHeaderTemplate=null}static supports(r,o){let{numberOfChannels:n,sampleRate:s}=o;return r==="aac"&&n>=1&&n<=48&&Wt.includes(s)||r==="opus"&&n>=1&&n<=255&&Gt.includes(s)||r==="mp3"&&n>=1&&n<=2&&Xt.includes(s)||r==="vorbis"&&n>=1&&n<=255&&s<=2e5||r==="flac"&&n>=1&&n<=8&&s<=655350||r==="ac3"&&n>=1&&n<=6&&gt.includes(s)||r==="eac3"&&n>=1&&n<=16&&gt.includes(s)}async init(){this.frame=new v.Frame,this.frame.alloc(),this.packet=new v.Packet,this.packet.alloc();let r=J[this.codec];p(r!==void 0);let o=v.Codec.findEncoder(r);if(!o)throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);this.avCodec=o,await this.createCodecContext()}async createCodecContext(){p(this.codecContext===null);let r=new v.CodecContext;r.allocContext3(this.avCodec);let o=v.AV_SAMPLE_FMT_FLTP;this.avCodec.sampleFormats&&!this.avCodec.sampleFormats.includes(v.AV_SAMPLE_FMT_FLTP)&&(o=this.avCodec.sampleFormats[0]),r.sampleRate=this.config.sampleRate,r.channelLayout=Z(this.config.numberOfChannels),r.codecType=v.AVMEDIA_TYPE_AUDIO,r.codecId=J[this.codec],r.sampleFormat=o,r.timeBase=new v.Rational(1,this.config.sampleRate),r.bitRate=BigInt(this.config.bitrate??le.QUALITY_MEDIUM._toAudioBitrate(this.codec)??0),this.config.bitrateMode==="constant"&&(r.rcMinRate=r.bitRate,r.rcMaxRate=r.bitRate);let n=await r.open2();v.FFmpegError.throwIfError(n,"Open codec context"),this.codecContext=r}async encode(r){this.codecContext===null&&(await this.createCodecContext(),p(this.codecContext)),this.firstExpectedTimestamp??=r.timestamp,r._data instanceof Q?(this.frame.unref(),this.frame.ref(r._data.frame)):Ee(r,this.frame),this.frame.pts=BigInt(Math.round(r.timestamp*this.config.sampleRate)),this.frame.duration=BigInt(Math.round(r.duration*this.config.sampleRate)),this.frame.timeBase=new v.Rational(1,this.config.sampleRate);let o=`${this.frame.sampleRate}:${this.frame.channels}:${this.frame.format}`;if(this.inputParametersKey!==null&&this.inputParametersKey!==o)throw new Error("Input audio parameters changed. For this audio encoder, you cannot change the input audio parameters over time.");if(this.inputParametersKey=o,this.codecContext.frameSize>0||this.codecContext.sampleFormat!==this.frame.format||this.codecContext.sampleRate!==this.frame.sampleRate||this.codecContext.channels!==this.frame.channels){if(!this.resampler){this.resampler=new v.SoftwareResampleContext,this.resamplerInputSampleRate=this.frame.sampleRate;let a=Z(this.codecContext.channels),A=Z(this.frame.channels),m=this.resampler.allocSetOpts2(a,this.codecContext.sampleFormat,this.codecContext.sampleRate,A,this.frame.format,this.frame.sampleRate);v.FFmpegError.throwIfError(m,"allocSetOpts2");let c=this.resampler.init();v.FFmpegError.throwIfError(c,"init"),this.dstFrame=new v.Frame,this.dstFrame.alloc(),this.dstFrame.channelLayout=a,this.dstFrame.sampleRate=this.codecContext.sampleRate,this.dstFrame.format=this.codecContext.sampleFormat,this.dstFrame.nbSamples=this.codecContext.frameSize||Oe,this.dstFrame.duration=BigInt(this.dstFrame.nbSamples),this.dstFrame.allocBuffer(),this.nextResamplerPts=this.frame.pts}let s=this.frame.data;if(!s)throw new DOMException("Frame has no data","EncodingError");await this.resampler.convert(null,0,s,this.frame.nbSamples),await this.pullResampledFrames()}else await this.sendFrameAndReceivePackets(this.frame)}async pullResampledFrames(){p(this.codecContext),p(this.resampler),p(this.dstFrame),p(this.nextResamplerPts!==null);let r=this.codecContext.frameSize||Oe;for(;!(this.resampler.getOutSamples(0)<r);)await this.resampler.convert(this.dstFrame.data,r,null,0),this.dstFrame.pts=this.nextResamplerPts,await this.sendFrameAndReceivePackets(this.dstFrame),this.nextResamplerPts+=BigInt(r)}async sendFrameAndReceivePackets(r){p(this.codecContext);let o=await this.codecContext.sendFrame(r);for(v.FFmpegError.throwIfError(o,"Send frame");;){let n=await this.codecContext.receivePacket(this.packet);if(n===v.AVERROR_EAGAIN||n===v.AVERROR_EOF)break;this.receivePacket(n)}}receivePacket(r){if(p(this.codecContext),p(this.firstExpectedTimestamp!==null),v.FFmpegError.throwIfError(r,"Receive packet"),!this.packet.data)return;let o=Number(this.packet.pts)/this.codecContext.sampleRate,n=Number(this.packet.duration)/this.codecContext.sampleRate,s=this.packet.data,a;if(this.packetEmitted)a={};else{this.outputTimestampOffset=Math.max(this.firstExpectedTimestamp-o,0);let m=this.config.codec,c=this.codecContext.extraData?L(this.codecContext.extraData):void 0;if(this.codec==="aac"){if(!c)throw new Error("Extradata expected for AAC.");if(this.config.aac?.format==="adts"){let h=ot(c);this.adtsHeaderTemplate=nt(h),c=void 0}}else if(this.codec==="opus"){if(!c)throw new Error("Extradata expected for Opus.")}else if(this.codec==="vorbis"){if(!c)throw new Error("Extradata expected for Vorbis.")}else if(this.codec==="flac"){if(!c)throw new Error("Extradata expected for FLAC.");c=new Uint8Array([102,76,97,67,128,0,0,c.byteLength,...c])}a={decoderConfig:{codec:m,sampleRate:this.codecContext.sampleRate,numberOfChannels:this.codecContext.channels,description:c}}}if(this.adtsHeaderTemplate){let m=s.byteLength+this.adtsHeaderTemplate.header.byteLength;this.adtsHeaderTemplate.bitstream.pos=30,this.adtsHeaderTemplate.bitstream.writeBits(13,m);let c=new Uint8Array(this.adtsHeaderTemplate.header.byteLength+s.byteLength);c.set(this.adtsHeaderTemplate.header,0),c.set(s,this.adtsHeaderTemplate.header.byteLength),s=c}o+=this.outputTimestampOffset;let A=new le.EncodedPacket(s,"key",o,n);this.packetEmitted=!0,this.onPacket(A,a)}async flush(){if(this.codecContext){e:if(this.resampler){p(this.resamplerInputSampleRate!==null);let r=this.resampler.getOutSamples(0);if(r===0)break e;let o=this.codecContext.frameSize||Oe;p(r<o);let n=Math.ceil((o-r)/this.codecContext.sampleRate*this.resamplerInputSampleRate);this.resampler.injectSilence(n),await this.pullResampledFrames()}await this.sendFrameAndReceivePackets(null),this.codecContext.freeContext(),this.codecContext=null,this.packetEmitted=!1,this.firstExpectedTimestamp=null,this.outputTimestampOffset=0,this.adtsHeaderTemplate=null,this.resampler?.free(),this.resampler=null,this.inputParametersKey=null,this.resamplerInputSampleRate=null,this.nextResamplerPts=null,this.dstFrame?.free(),this.dstFrame=null}}close(){this.codecContext?.freeContext(),this.frame.free(),this.packet.free(),this.dstFrame?.free(),this.resampler?.free()}};var bt=N("@mediabunny/prores");var xt=Symbol.for("@mediabunny/server loaded");globalThis[xt]&&k.Logging._error(`[WARNING]
9
+ @mediabunny/server was loaded twice. This will likely cause the package not to work correctly. Check if multiple dependencies are importing different versions of @mediabunny/server, or if something is being bundled incorrectly.`);globalThis[xt]=!0;var Ct=!1,Y={},Yt=(t={})=>{if(typeof t!="object"||!t)throw new TypeError("options must be an object.");if(t.hardwareContext!=null&&!(t.hardwareContext instanceof G.HardwareContext||typeof t.hardwareContext=="function"))throw new TypeError("options.hardwareContext, when provided, must be a NodeAv.HardwareContext, a function, or null.");Ct||(Ct=!0,Y=t,G.Log.setLevel(G.AV_LOG_ERROR),(0,k.registerDecoder)(be),(0,bt.registerProresDecoder)(),(0,k.registerEncoder)(ye),(0,k.registerDecoder)(Se),(0,k.registerEncoder)(we),(0,k.registerVideoSampleTransformer)(tt))},Kt=async(t,e)=>{if(!(t instanceof k.VideoSample)&&!(t instanceof k.AudioSample))throw new TypeError("sample must be a VideoSample or an AudioSample.");if(!(e instanceof G.Frame))throw new TypeError("frame must be a NodeAv.Frame.");if(t instanceof k.VideoSample){if(t._data instanceof q)e.unref(),e.ref(t._data.frame);else{if(t.format===null)throw new Error("Cannot convert foreign VideoSample with unknown (null) format.");await Ae(t,e,null)}e.pts=BigInt(t.microsecondTimestamp),e.duration=BigInt(t.microsecondDuration),e.timeBase=new G.Rational(1,1e6)}else t._data instanceof Q?(e.unref(),e.ref(t._data.frame)):Ee(t,e),e.timeBase=new G.Rational(1,t.sampleRate),e.pts=BigInt(Math.round(t.timestamp*t.sampleRate)),e.duration=BigInt(t.numberOfFrames)};return wt(Qt);})();
10
10
  if (typeof module === "object" && typeof module.exports === "object") Object.assign(module.exports, MediabunnyServer)