@mediabunny/server 1.65.1 → 1.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,11 +9,11 @@
9
9
  // packages/server/src/index.ts
10
10
  import {
11
11
  AudioSample as AudioSample4,
12
- Logging as Logging3,
13
- registerDecoder as registerDecoder2,
12
+ Logging as Logging2,
13
+ registerDecoder,
14
14
  registerEncoder,
15
15
  registerVideoSampleTransformer,
16
- VideoSample as VideoSample5
16
+ VideoSample as VideoSample4
17
17
  } from "mediabunny";
18
18
  import * as NodeAv8 from "node-av";
19
19
 
@@ -23,6 +23,227 @@ import * as NodeAv3 from "node-av";
23
23
 
24
24
  // packages/server/src/misc.ts
25
25
  import * as NodeAv from "node-av";
26
+
27
+ // src/logging.ts
28
+ var _Logging = class _Logging {
29
+ constructor() {
30
+ }
31
+ /** The current log level. Defaults to {@link LogLevel.Info}. */
32
+ static get level() {
33
+ return _Logging._level;
34
+ }
35
+ static set level(value) {
36
+ if (value !== 0 /* Silent */ && value !== 1 /* Errors */ && value !== 2 /* Warnings */ && value !== 3 /* Info */) {
37
+ throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");
38
+ }
39
+ _Logging._level = value;
40
+ }
41
+ /** @internal */
42
+ static get _emitter() {
43
+ return _Logging._emitterInstance ??= new EventEmitter();
44
+ }
45
+ /** Registers a listener for a log event. Returns a function that, when called, removes the listener again. */
46
+ static on(event, listener, options) {
47
+ return _Logging._emitter.on(event, listener, options);
48
+ }
49
+ /** @internal */
50
+ static _error(...args) {
51
+ _Logging._emitter._emit("error", args);
52
+ if (_Logging._level >= 1 /* Errors */) {
53
+ console.error(...args);
54
+ }
55
+ }
56
+ /** @internal */
57
+ static _warn(...args) {
58
+ _Logging._emitter._emit("warn", args);
59
+ if (_Logging._level >= 2 /* Warnings */) {
60
+ console.warn(...args);
61
+ }
62
+ }
63
+ /** @internal */
64
+ static _info(...args) {
65
+ _Logging._emitter._emit("info", args);
66
+ if (_Logging._level >= 3 /* Info */) {
67
+ console.info(...args);
68
+ }
69
+ }
70
+ };
71
+ /** @internal */
72
+ _Logging._level = 3 /* Info */;
73
+ /** @internal */
74
+ _Logging._emitterInstance = null;
75
+ var Logging = _Logging;
76
+
77
+ // src/misc.ts
78
+ function assert(x) {
79
+ if (!x) {
80
+ throw new Error("Assertion failed.");
81
+ }
82
+ }
83
+ var DEG_TO_RAD = Math.PI / 180;
84
+ var RAD_TO_DEG = 180 / Math.PI;
85
+ var last = (arr) => {
86
+ return arr && arr[arr.length - 1];
87
+ };
88
+ var readExpGolomb = (bitstream) => {
89
+ let leadingZeroBits = 0;
90
+ while (bitstream.readBits(1) === 0 && leadingZeroBits < 32) {
91
+ leadingZeroBits++;
92
+ }
93
+ if (leadingZeroBits >= 32) {
94
+ throw new Error("Invalid exponential-Golomb code.");
95
+ }
96
+ const result = 2 ** leadingZeroBits - 1 + bitstream.readBits(leadingZeroBits);
97
+ return result;
98
+ };
99
+ var readSignedExpGolomb = (bitstream) => {
100
+ const codeNum = readExpGolomb(bitstream);
101
+ return codeNum % 2 === 0 ? -(codeNum / 2) : (codeNum + 1) / 2;
102
+ };
103
+ var toUint8Array = (source) => {
104
+ if (source.constructor === Uint8Array) {
105
+ return source;
106
+ } else if (ArrayBuffer.isView(source)) {
107
+ return new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
108
+ } else {
109
+ return new Uint8Array(source);
110
+ }
111
+ };
112
+ var toDataView = (source) => {
113
+ if (source.constructor === DataView) {
114
+ return source;
115
+ } else if (ArrayBuffer.isView(source)) {
116
+ return new DataView(source.buffer, source.byteOffset, source.byteLength);
117
+ } else {
118
+ return new DataView(source);
119
+ }
120
+ };
121
+ var COLOR_PRIMARIES_MAP = {
122
+ bt709: 1,
123
+ // ITU-R BT.709
124
+ bt470bg: 5,
125
+ // ITU-R BT.470BG
126
+ smpte170m: 6,
127
+ // ITU-R BT.601 525 - SMPTE 170M
128
+ bt2020: 9,
129
+ // ITU-R BT.202
130
+ smpte432: 12
131
+ // SMPTE EG 432-1
132
+ };
133
+ var TRANSFER_CHARACTERISTICS_MAP = {
134
+ "bt709": 1,
135
+ // ITU-R BT.709
136
+ "smpte170m": 6,
137
+ // SMPTE 170M
138
+ "linear": 8,
139
+ // Linear transfer characteristics
140
+ "iec61966-2-1": 13,
141
+ // IEC 61966-2-1
142
+ "pq": 16,
143
+ // Rec. ITU-R BT.2100-2 perceptual quantization (PQ) system
144
+ "hlg": 18
145
+ // Rec. ITU-R BT.2100-2 hybrid loggamma (HLG) system
146
+ };
147
+ var MATRIX_COEFFICIENTS_MAP = {
148
+ "rgb": 0,
149
+ // Identity
150
+ "bt709": 1,
151
+ // ITU-R BT.709
152
+ "bt470bg": 5,
153
+ // ITU-R BT.470BG
154
+ "smpte170m": 6,
155
+ // SMPTE 170M
156
+ "bt2020-ncl": 9
157
+ // ITU-R BT.2020-2 (non-constant luminance)
158
+ };
159
+ var bytesToHexString = (bytes) => {
160
+ return [...bytes].map((x) => x.toString(16).padStart(2, "0")).join("");
161
+ };
162
+ var reverseBitsU32 = (x) => {
163
+ x = x >> 1 & 1431655765 | (x & 1431655765) << 1;
164
+ x = x >> 2 & 858993459 | (x & 858993459) << 2;
165
+ x = x >> 4 & 252645135 | (x & 252645135) << 4;
166
+ x = x >> 8 & 16711935 | (x & 16711935) << 8;
167
+ x = x >> 16 & 65535 | (x & 65535) << 16;
168
+ return x >>> 0;
169
+ };
170
+ var binarySearchLessOrEqual = (arr, key, valueGetter) => {
171
+ let low = 0;
172
+ let high = arr.length - 1;
173
+ let ans = -1;
174
+ while (low <= high) {
175
+ const mid = low + (high - low + 1) / 2 | 0;
176
+ const midVal = valueGetter(arr[mid]);
177
+ if (midVal <= key) {
178
+ ans = mid;
179
+ low = mid + 1;
180
+ } else {
181
+ high = mid - 1;
182
+ }
183
+ }
184
+ return ans;
185
+ };
186
+ var assertNever = (x) => {
187
+ throw new Error(`Unexpected value: ${x}`);
188
+ };
189
+ var SECOND_TO_MICROSECOND_FACTOR = 1e6 * (1 + Number.EPSILON);
190
+ var simplifyRational = (rational) => {
191
+ assert(Number.isInteger(rational.num));
192
+ assert(Number.isInteger(rational.den));
193
+ assert(rational.den !== 0);
194
+ let a = Math.abs(rational.num);
195
+ let b = Math.abs(rational.den);
196
+ while (b !== 0) {
197
+ const t = a % b;
198
+ a = b;
199
+ b = t;
200
+ }
201
+ const gcd = a || 1;
202
+ return {
203
+ num: rational.num / gcd,
204
+ den: rational.den / gcd
205
+ };
206
+ };
207
+ var EventEmitter = class {
208
+ constructor() {
209
+ /** @internal */
210
+ this._listeners = /* @__PURE__ */ new Map();
211
+ }
212
+ /** Registers a listener for the given event. Returns a function that, when called, removes the listener again. */
213
+ on(event, listener, options) {
214
+ if (!this._listeners.has(event)) {
215
+ this._listeners.set(event, /* @__PURE__ */ new Set());
216
+ }
217
+ const entry = { fn: listener, once: options?.once ?? false };
218
+ this._listeners.get(event).add(entry);
219
+ return () => {
220
+ this._listeners.get(event)?.delete(entry);
221
+ };
222
+ }
223
+ /** @internal */
224
+ _emit(...args) {
225
+ const [event, data] = args;
226
+ const listeners = this._listeners.get(event);
227
+ if (!listeners) {
228
+ return;
229
+ }
230
+ for (const entry of [...listeners]) {
231
+ if (!listeners.has(entry)) {
232
+ continue;
233
+ }
234
+ if (entry.once) {
235
+ listeners.delete(entry);
236
+ }
237
+ try {
238
+ entry.fn(data);
239
+ } catch (error) {
240
+ console.error(error);
241
+ }
242
+ }
243
+ }
244
+ };
245
+
246
+ // packages/server/src/misc.ts
26
247
  var CODEC_TO_CODEC_ID = {
27
248
  avc: NodeAv.AV_CODEC_ID_H264,
28
249
  hevc: NodeAv.AV_CODEC_ID_HEVC,
@@ -252,6 +473,9 @@ var fromPixelFormat = (pixelFormat) => {
252
473
  return NodeAv.AV_PIX_FMT_YUVA420P;
253
474
  case "I420AP10":
254
475
  return NodeAv.AV_PIX_FMT_YUVA420P10LE;
476
+ case "I420AP12":
477
+ return NodeAv.AV_PIX_FMT_NONE;
478
+ // FFmpeg has no 12-bit 4:2:0 format with alpha :(
255
479
  case "I422":
256
480
  return NodeAv.AV_PIX_FMT_YUV422P;
257
481
  case "I422P10":
@@ -287,7 +511,7 @@ var fromPixelFormat = (pixelFormat) => {
287
511
  case "BGRX":
288
512
  return NodeAv.AV_PIX_FMT_BGR0;
289
513
  default:
290
- return NodeAv.AV_PIX_FMT_NONE;
514
+ return assertNever(pixelFormat);
291
515
  }
292
516
  };
293
517
  var toAudioSampleFormat = (ffmpegSampleFormat) => {
@@ -312,436 +536,77 @@ var toAudioSampleFormat = (ffmpegSampleFormat) => {
312
536
  return null;
313
537
  }
314
538
  };
315
- var fromAudioSampleFormat = (sampleFormat) => {
316
- switch (sampleFormat) {
317
- case "u8":
318
- return NodeAv.AV_SAMPLE_FMT_U8;
319
- case "s16":
320
- return NodeAv.AV_SAMPLE_FMT_S16;
321
- case "s32":
322
- return NodeAv.AV_SAMPLE_FMT_S32;
323
- case "f32":
324
- return NodeAv.AV_SAMPLE_FMT_FLT;
325
- case "u8-planar":
326
- return NodeAv.AV_SAMPLE_FMT_U8P;
327
- case "s16-planar":
328
- return NodeAv.AV_SAMPLE_FMT_S16P;
329
- case "s32-planar":
330
- return NodeAv.AV_SAMPLE_FMT_S32P;
331
- case "f32-planar":
332
- return NodeAv.AV_SAMPLE_FMT_FLTP;
333
- default:
334
- return NodeAv.AV_SAMPLE_FMT_NONE;
335
- }
336
- };
337
- var getChannelLayout = (numChannels) => {
338
- switch (numChannels) {
339
- case 1:
340
- return NodeAv.AV_CHANNEL_LAYOUT_MONO;
341
- case 2:
342
- return NodeAv.AV_CHANNEL_LAYOUT_STEREO;
343
- case 4:
344
- return NodeAv.AV_CHANNEL_LAYOUT_QUAD;
345
- case 6:
346
- return NodeAv.AV_CHANNEL_LAYOUT_5POINT1_BACK;
347
- case 8:
348
- return NodeAv.AV_CHANNEL_LAYOUT_7POINT1;
349
- default:
350
- return { nbChannels: numChannels, order: NodeAv.AV_CHANNEL_ORDER_UNSPEC, mask: 0n };
351
- }
352
- };
353
- var QUAD_SIDE_MASK = 0x603n;
354
- var getDtsChannelLayout = (numChannels) => {
355
- switch (numChannels) {
356
- case 1:
357
- return NodeAv.AV_CHANNEL_LAYOUT_MONO;
358
- case 2:
359
- return NodeAv.AV_CHANNEL_LAYOUT_STEREO;
360
- case 4:
361
- return { nbChannels: 4, order: NodeAv.AV_CHANNEL_ORDER_NATIVE, mask: QUAD_SIDE_MASK };
362
- case 5:
363
- return NodeAv.AV_CHANNEL_LAYOUT_5POINT0;
364
- case 6:
365
- return NodeAv.AV_CHANNEL_LAYOUT_5POINT1;
366
- default:
367
- return { nbChannels: numChannels, order: NodeAv.AV_CHANNEL_ORDER_UNSPEC, mask: 0n };
368
- }
369
- };
370
- var getTrueHdChannelLayout = (numChannels) => {
371
- switch (numChannels) {
372
- case 1:
373
- return NodeAv.AV_CHANNEL_LAYOUT_MONO;
374
- case 2:
375
- return NodeAv.AV_CHANNEL_LAYOUT_STEREO;
376
- case 3:
377
- return NodeAv.AV_CHANNEL_LAYOUT_SURROUND;
378
- case 4:
379
- return NodeAv.AV_CHANNEL_LAYOUT_4POINT0;
380
- case 5:
381
- return NodeAv.AV_CHANNEL_LAYOUT_5POINT0;
382
- case 6:
383
- return NodeAv.AV_CHANNEL_LAYOUT_5POINT1;
384
- default:
385
- return { nbChannels: numChannels, order: NodeAv.AV_CHANNEL_ORDER_UNSPEC, mask: 0n };
386
- }
387
- };
388
-
389
- // src/logging.ts
390
- var _Logging = class _Logging {
391
- constructor() {
392
- }
393
- /** The current log level. Defaults to {@link LogLevel.Info}. */
394
- static get level() {
395
- return _Logging._level;
396
- }
397
- static set level(value) {
398
- if (value !== 0 /* Silent */ && value !== 1 /* Errors */ && value !== 2 /* Warnings */ && value !== 3 /* Info */) {
399
- throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");
400
- }
401
- _Logging._level = value;
402
- }
403
- /** @internal */
404
- static get _emitter() {
405
- return _Logging._emitterInstance ??= new EventEmitter();
406
- }
407
- /** Registers a listener for a log event. Returns a function that, when called, removes the listener again. */
408
- static on(event, listener, options) {
409
- return _Logging._emitter.on(event, listener, options);
410
- }
411
- /** @internal */
412
- static _error(...args) {
413
- _Logging._emitter._emit("error", args);
414
- if (_Logging._level >= 1 /* Errors */) {
415
- console.error(...args);
416
- }
417
- }
418
- /** @internal */
419
- static _warn(...args) {
420
- _Logging._emitter._emit("warn", args);
421
- if (_Logging._level >= 2 /* Warnings */) {
422
- console.warn(...args);
423
- }
424
- }
425
- /** @internal */
426
- static _info(...args) {
427
- _Logging._emitter._emit("info", args);
428
- if (_Logging._level >= 3 /* Info */) {
429
- console.info(...args);
430
- }
431
- }
432
- };
433
- /** @internal */
434
- _Logging._level = 3 /* Info */;
435
- /** @internal */
436
- _Logging._emitterInstance = null;
437
- var Logging = _Logging;
438
-
439
- // src/misc.ts
440
- function assert(x) {
441
- if (!x) {
442
- throw new Error("Assertion failed.");
443
- }
444
- }
445
- var DEG_TO_RAD = Math.PI / 180;
446
- var RAD_TO_DEG = 180 / Math.PI;
447
- var last = (arr) => {
448
- return arr && arr[arr.length - 1];
449
- };
450
- var readExpGolomb = (bitstream) => {
451
- let leadingZeroBits = 0;
452
- while (bitstream.readBits(1) === 0 && leadingZeroBits < 32) {
453
- leadingZeroBits++;
454
- }
455
- if (leadingZeroBits >= 32) {
456
- throw new Error("Invalid exponential-Golomb code.");
457
- }
458
- const result = 2 ** leadingZeroBits - 1 + bitstream.readBits(leadingZeroBits);
459
- return result;
460
- };
461
- var readSignedExpGolomb = (bitstream) => {
462
- const codeNum = readExpGolomb(bitstream);
463
- return codeNum % 2 === 0 ? -(codeNum / 2) : (codeNum + 1) / 2;
464
- };
465
- var toUint8Array = (source) => {
466
- if (source.constructor === Uint8Array) {
467
- return source;
468
- } else if (ArrayBuffer.isView(source)) {
469
- return new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
470
- } else {
471
- return new Uint8Array(source);
472
- }
473
- };
474
- var toDataView = (source) => {
475
- if (source.constructor === DataView) {
476
- return source;
477
- } else if (ArrayBuffer.isView(source)) {
478
- return new DataView(source.buffer, source.byteOffset, source.byteLength);
479
- } else {
480
- return new DataView(source);
481
- }
482
- };
483
- var TextEncoder = typeof globalThis.TextEncoder !== "undefined" ? globalThis.TextEncoder : class TextEncoder2 {
484
- constructor() {
485
- this.encoding = "utf-8";
486
- }
487
- encode(input = "") {
488
- const bytes = new Uint8Array(3 * input.length);
489
- let n = 0;
490
- for (let i = 0; i < input.length; i++) {
491
- let c = input.charCodeAt(i);
492
- if (c < 128) {
493
- bytes[n++] = c;
494
- } else if (c < 2048) {
495
- bytes[n++] = 192 | c >> 6;
496
- bytes[n++] = 128 | c & 63;
497
- } else if (c < 55296 || c > 57343) {
498
- bytes[n++] = 224 | c >> 12;
499
- bytes[n++] = 128 | c >> 6 & 63;
500
- bytes[n++] = 128 | c & 63;
501
- } else {
502
- const next = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
503
- if (c < 56320 && next >= 56320 && next <= 57343) {
504
- c = 65536 + (c - 55296 << 10) + (next - 56320);
505
- i++;
506
- bytes[n++] = 240 | c >> 18;
507
- bytes[n++] = 128 | c >> 12 & 63;
508
- bytes[n++] = 128 | c >> 6 & 63;
509
- bytes[n++] = 128 | c & 63;
510
- } else {
511
- bytes[n++] = 239;
512
- bytes[n++] = 191;
513
- bytes[n++] = 189;
514
- }
515
- }
516
- }
517
- return bytes.slice(0, n);
518
- }
519
- };
520
- var TextDecoder = typeof globalThis.TextDecoder !== "undefined" ? globalThis.TextDecoder : class TextDecoder2 {
521
- constructor(label = "utf-8") {
522
- const normalized = label.trim().toLowerCase();
523
- if (normalized === "utf-8" || normalized === "utf8" || normalized === "unicode-1-1-utf-8") {
524
- this.encoding = "utf-8";
525
- } else if (normalized === "utf-16le" || normalized === "utf-16") {
526
- this.encoding = "utf-16le";
527
- } else if (normalized === "utf-16be") {
528
- this.encoding = "utf-16be";
529
- } else {
530
- throw new RangeError(`The encoding label provided ('${label}') is invalid.`);
531
- }
532
- }
533
- decode(input) {
534
- const bytes = input ? toUint8Array(input) : new Uint8Array(0);
535
- const units = [];
536
- if (this.encoding === "utf-8") {
537
- let i = bytes.length >= 3 && bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191 ? 3 : 0;
538
- while (i < bytes.length) {
539
- const lead = bytes[i];
540
- if (lead < 128) {
541
- units.push(lead);
542
- i++;
543
- continue;
544
- }
545
- let continuationCount;
546
- let codePoint;
547
- if (lead >= 194 && lead < 224) {
548
- continuationCount = 1;
549
- codePoint = lead & 31;
550
- } else if (lead >= 224 && lead < 240) {
551
- continuationCount = 2;
552
- codePoint = lead & 15;
553
- } else if (lead >= 240 && lead < 245) {
554
- continuationCount = 3;
555
- codePoint = lead & 7;
556
- } else {
557
- units.push(65533);
558
- i++;
559
- continue;
560
- }
561
- let lowerBound = lead === 224 ? 160 : lead === 240 ? 144 : 128;
562
- let upperBound = lead === 237 ? 159 : lead === 244 ? 143 : 191;
563
- let j = 1;
564
- for (; j <= continuationCount; j++) {
565
- const byte = i + j < bytes.length ? bytes[i + j] : 0;
566
- if (byte < lowerBound || byte > upperBound) {
567
- break;
568
- }
569
- codePoint = codePoint << 6 | byte & 63;
570
- lowerBound = 128;
571
- upperBound = 191;
572
- }
573
- i += j;
574
- if (j <= continuationCount) {
575
- units.push(65533);
576
- } else if (codePoint >= 65536) {
577
- codePoint -= 65536;
578
- units.push(55296 | codePoint >> 10, 56320 | codePoint & 1023);
579
- } else {
580
- units.push(codePoint);
581
- }
582
- }
583
- } else {
584
- const littleEndian = this.encoding === "utf-16le";
585
- const bomLow = littleEndian ? 255 : 254;
586
- const bomHigh = littleEndian ? 254 : 255;
587
- let i = bytes.length >= 2 && bytes[0] === bomLow && bytes[1] === bomHigh ? 2 : 0;
588
- while (i + 1 < bytes.length) {
589
- const unit = littleEndian ? bytes[i] | bytes[i + 1] << 8 : bytes[i] << 8 | bytes[i + 1];
590
- i += 2;
591
- if (unit >= 55296 && unit <= 56319) {
592
- const next = i + 1 < bytes.length ? littleEndian ? bytes[i] | bytes[i + 1] << 8 : bytes[i] << 8 | bytes[i + 1] : -1;
593
- if (next >= 56320 && next <= 57343) {
594
- units.push(unit, next);
595
- i += 2;
596
- } else {
597
- units.push(65533);
598
- }
599
- } else if (unit >= 56320 && unit <= 57343) {
600
- units.push(65533);
601
- } else {
602
- units.push(unit);
603
- }
604
- }
605
- if (i < bytes.length) {
606
- units.push(65533);
607
- }
608
- }
609
- let result = "";
610
- for (let i = 0; i < units.length; i += 8192) {
611
- result += String.fromCharCode(...units.slice(i, i + 8192));
612
- }
613
- return result;
614
- }
615
- };
616
- var COLOR_PRIMARIES_MAP = {
617
- bt709: 1,
618
- // ITU-R BT.709
619
- bt470bg: 5,
620
- // ITU-R BT.470BG
621
- smpte170m: 6,
622
- // ITU-R BT.601 525 - SMPTE 170M
623
- bt2020: 9,
624
- // ITU-R BT.202
625
- smpte432: 12
626
- // SMPTE EG 432-1
627
- };
628
- var TRANSFER_CHARACTERISTICS_MAP = {
629
- "bt709": 1,
630
- // ITU-R BT.709
631
- "smpte170m": 6,
632
- // SMPTE 170M
633
- "linear": 8,
634
- // Linear transfer characteristics
635
- "iec61966-2-1": 13,
636
- // IEC 61966-2-1
637
- "pq": 16,
638
- // Rec. ITU-R BT.2100-2 perceptual quantization (PQ) system
639
- "hlg": 18
640
- // Rec. ITU-R BT.2100-2 hybrid loggamma (HLG) system
641
- };
642
- var MATRIX_COEFFICIENTS_MAP = {
643
- "rgb": 0,
644
- // Identity
645
- "bt709": 1,
646
- // ITU-R BT.709
647
- "bt470bg": 5,
648
- // ITU-R BT.470BG
649
- "smpte170m": 6,
650
- // SMPTE 170M
651
- "bt2020-ncl": 9
652
- // ITU-R BT.2020-2 (non-constant luminance)
653
- };
654
- var bytesToHexString = (bytes) => {
655
- return [...bytes].map((x) => x.toString(16).padStart(2, "0")).join("");
656
- };
657
- var reverseBitsU32 = (x) => {
658
- x = x >> 1 & 1431655765 | (x & 1431655765) << 1;
659
- x = x >> 2 & 858993459 | (x & 858993459) << 2;
660
- x = x >> 4 & 252645135 | (x & 252645135) << 4;
661
- x = x >> 8 & 16711935 | (x & 16711935) << 8;
662
- x = x >> 16 & 65535 | (x & 65535) << 16;
663
- return x >>> 0;
664
- };
665
- var binarySearchLessOrEqual = (arr, key, valueGetter) => {
666
- let low = 0;
667
- let high = arr.length - 1;
668
- let ans = -1;
669
- while (low <= high) {
670
- const mid = low + (high - low + 1) / 2 | 0;
671
- const midVal = valueGetter(arr[mid]);
672
- if (midVal <= key) {
673
- ans = mid;
674
- low = mid + 1;
675
- } else {
676
- high = mid - 1;
677
- }
678
- }
679
- return ans;
680
- };
681
- var assertNever = (x) => {
682
- throw new Error(`Unexpected value: ${x}`);
683
- };
684
- var SECOND_TO_MICROSECOND_FACTOR = 1e6 * (1 + Number.EPSILON);
685
- var isWebKitCache = null;
686
- var isWebKit = () => {
687
- if (isWebKitCache !== null) {
688
- return isWebKitCache;
539
+ var fromAudioSampleFormat = (sampleFormat) => {
540
+ switch (sampleFormat) {
541
+ case "u8":
542
+ return NodeAv.AV_SAMPLE_FMT_U8;
543
+ case "s16":
544
+ return NodeAv.AV_SAMPLE_FMT_S16;
545
+ case "s32":
546
+ return NodeAv.AV_SAMPLE_FMT_S32;
547
+ case "f32":
548
+ return NodeAv.AV_SAMPLE_FMT_FLT;
549
+ case "u8-planar":
550
+ return NodeAv.AV_SAMPLE_FMT_U8P;
551
+ case "s16-planar":
552
+ return NodeAv.AV_SAMPLE_FMT_S16P;
553
+ case "s32-planar":
554
+ return NodeAv.AV_SAMPLE_FMT_S32P;
555
+ case "f32-planar":
556
+ return NodeAv.AV_SAMPLE_FMT_FLTP;
557
+ default:
558
+ return NodeAv.AV_SAMPLE_FMT_NONE;
689
559
  }
690
- return isWebKitCache = !!(typeof navigator !== "undefined" && // eslint-disable-next-line @typescript-eslint/no-deprecated
691
- (navigator.vendor?.match(/apple/i) || /AppleWebKit/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) || /\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));
692
560
  };
693
- var NativePromiseConstructor = (async () => {
694
- })().constructor;
695
- var simplifyRational = (rational) => {
696
- assert(Number.isInteger(rational.num));
697
- assert(Number.isInteger(rational.den));
698
- assert(rational.den !== 0);
699
- let a = Math.abs(rational.num);
700
- let b = Math.abs(rational.den);
701
- while (b !== 0) {
702
- const t = a % b;
703
- a = b;
704
- b = t;
561
+ var getChannelLayout = (numChannels) => {
562
+ switch (numChannels) {
563
+ case 1:
564
+ return NodeAv.AV_CHANNEL_LAYOUT_MONO;
565
+ case 2:
566
+ return NodeAv.AV_CHANNEL_LAYOUT_STEREO;
567
+ case 4:
568
+ return NodeAv.AV_CHANNEL_LAYOUT_QUAD;
569
+ case 6:
570
+ return NodeAv.AV_CHANNEL_LAYOUT_5POINT1_BACK;
571
+ case 8:
572
+ return NodeAv.AV_CHANNEL_LAYOUT_7POINT1;
573
+ default:
574
+ return { nbChannels: numChannels, order: NodeAv.AV_CHANNEL_ORDER_UNSPEC, mask: 0n };
705
575
  }
706
- const gcd = a || 1;
707
- return {
708
- num: rational.num / gcd,
709
- den: rational.den / gcd
710
- };
711
576
  };
712
- var EventEmitter = class {
713
- constructor() {
714
- /** @internal */
715
- this._listeners = /* @__PURE__ */ new Map();
716
- }
717
- /** Registers a listener for the given event. Returns a function that, when called, removes the listener again. */
718
- on(event, listener, options) {
719
- if (!this._listeners.has(event)) {
720
- this._listeners.set(event, /* @__PURE__ */ new Set());
721
- }
722
- const entry = { fn: listener, once: options?.once ?? false };
723
- this._listeners.get(event).add(entry);
724
- return () => {
725
- this._listeners.get(event)?.delete(entry);
726
- };
577
+ var QUAD_SIDE_MASK = 0x603n;
578
+ var getDtsChannelLayout = (numChannels) => {
579
+ switch (numChannels) {
580
+ case 1:
581
+ return NodeAv.AV_CHANNEL_LAYOUT_MONO;
582
+ case 2:
583
+ return NodeAv.AV_CHANNEL_LAYOUT_STEREO;
584
+ case 4:
585
+ return { nbChannels: 4, order: NodeAv.AV_CHANNEL_ORDER_NATIVE, mask: QUAD_SIDE_MASK };
586
+ case 5:
587
+ return NodeAv.AV_CHANNEL_LAYOUT_5POINT0;
588
+ case 6:
589
+ return NodeAv.AV_CHANNEL_LAYOUT_5POINT1;
590
+ default:
591
+ return { nbChannels: numChannels, order: NodeAv.AV_CHANNEL_ORDER_UNSPEC, mask: 0n };
727
592
  }
728
- /** @internal */
729
- _emit(...args) {
730
- const [event, data] = args;
731
- const listeners = this._listeners.get(event);
732
- if (!listeners) {
733
- return;
734
- }
735
- for (const entry of listeners) {
736
- try {
737
- entry.fn(data);
738
- } catch (error) {
739
- console.error(error);
740
- }
741
- if (entry.once) {
742
- listeners.delete(entry);
743
- }
744
- }
593
+ };
594
+ var getTrueHdChannelLayout = (numChannels) => {
595
+ switch (numChannels) {
596
+ case 1:
597
+ return NodeAv.AV_CHANNEL_LAYOUT_MONO;
598
+ case 2:
599
+ return NodeAv.AV_CHANNEL_LAYOUT_STEREO;
600
+ case 3:
601
+ return NodeAv.AV_CHANNEL_LAYOUT_SURROUND;
602
+ case 4:
603
+ return NodeAv.AV_CHANNEL_LAYOUT_4POINT0;
604
+ case 5:
605
+ return NodeAv.AV_CHANNEL_LAYOUT_5POINT0;
606
+ case 6:
607
+ return NodeAv.AV_CHANNEL_LAYOUT_5POINT1;
608
+ default:
609
+ return { nbChannels: numChannels, order: NodeAv.AV_CHANNEL_ORDER_UNSPEC, mask: 0n };
745
610
  }
746
611
  };
747
612
 
@@ -797,7 +662,7 @@ var AvFrameVideoSampleResource = class _AvFrameVideoSampleResource extends Video
797
662
  }
798
663
  }
799
664
  getSquarePixelHeight() {
800
- if (this.frame.sampleAspectRatio.num > this.frame.sampleAspectRatio.den) {
665
+ if (this.frame.sampleAspectRatio.num > this.frame.sampleAspectRatio.den || this.frame.sampleAspectRatio.num === 0) {
801
666
  return this.frame.height;
802
667
  } else {
803
668
  return Math.round(this.frame.height * this.frame.sampleAspectRatio.den / this.frame.sampleAspectRatio.num);
@@ -868,7 +733,8 @@ var AvFrameVideoSampleResource = class _AvFrameVideoSampleResource extends Video
868
733
  var copyVideoSampleToAvFrame = async (sample, frame, lastBuffer) => {
869
734
  assert(sample.format !== null);
870
735
  frame.unref();
871
- frame.format = fromPixelFormat(sample.format);
736
+ const widenFrom12To16Bit = sample.format === "I420AP12";
737
+ frame.format = widenFrom12To16Bit ? NodeAv2.AV_PIX_FMT_YUVA420P16LE : fromPixelFormat(sample.format);
872
738
  frame.width = sample.codedWidth;
873
739
  frame.height = sample.codedHeight;
874
740
  frame.sampleAspectRatio = new NodeAv2.Rational(
@@ -884,6 +750,12 @@ var copyVideoSampleToAvFrame = async (sample, frame, lastBuffer) => {
884
750
  lastBuffer = Buffer.from({ length: size });
885
751
  }
886
752
  await sample.copyTo(lastBuffer);
753
+ if (widenFrom12To16Bit) {
754
+ const values = new Uint16Array(lastBuffer.buffer, lastBuffer.byteOffset, lastBuffer.byteLength / 2);
755
+ for (let i = 0; i < values.length; i++) {
756
+ values[i] = values[i] << 4 | values[i] >> 8;
757
+ }
758
+ }
887
759
  frame.fromBuffer(lastBuffer);
888
760
  return lastBuffer;
889
761
  };
@@ -899,7 +771,6 @@ var transformVideoSample = async (sample, description) => {
899
771
  srcFrame = new NodeAv2.Frame();
900
772
  srcFrame.alloc();
901
773
  srcFrameOwned = true;
902
- await copyVideoSampleToAvFrame(sample, srcFrame, null);
903
774
  }
904
775
  const chain = [];
905
776
  if (sample.squarePixelWidth !== sample.codedWidth || sample.squarePixelHeight !== sample.codedHeight) {
@@ -930,7 +801,19 @@ var transformVideoSample = async (sample, description) => {
930
801
  const graph = new NodeAv2.FilterGraph();
931
802
  graph.alloc();
932
803
  try {
933
- const srcArgs = `video_size=${srcFrame.width}x${srcFrame.height}:pix_fmt=${srcFrame.format}:time_base=1/1000000:pixel_aspect=${sample.pixelAspectRatio.num}/${sample.pixelAspectRatio.den}`;
804
+ if (srcFrameOwned) {
805
+ await copyVideoSampleToAvFrame(sample, srcFrame, null);
806
+ }
807
+ if (description.alpha === "discard") {
808
+ const formatName = NodeAv2.avGetPixFmtName(srcFrame.format);
809
+ assert(formatName);
810
+ const opaqueFormatName = formatName.replace(/^yuva/, "yuv").replace(/^gbrap/, "gbrp").replace(/^ya8$/, "gray").replace(/^ya16/, "gray16").replace(/^(rgb|bgr)a64/, "$148").replace(/^(rgb|bgr)a/, "$10").replace(/^a(rgb|bgr)/, "0$1");
811
+ if (opaqueFormatName !== formatName) {
812
+ assert(NodeAv2.avGetPixFmtFromName(opaqueFormatName) !== NodeAv2.AV_PIX_FMT_NONE);
813
+ chain.splice(-1, 0, "premultiply=inplace=1", `format=${opaqueFormatName}`);
814
+ }
815
+ }
816
+ const srcArgs = `video_size=${srcFrame.width}x${srcFrame.height}:pix_fmt=${srcFrame.format}:time_base=1/1000000:pixel_aspect=${sample.pixelAspectRatio.num}/${sample.pixelAspectRatio.den}:colorspace=${srcFrame.colorSpace}:range=${srcFrame.colorRange}`;
934
817
  const bufferSrc = graph.createFilter(NodeAv2.Filter.getByName("buffer"), "src", srcArgs);
935
818
  const bufferSink = graph.createFilter(NodeAv2.Filter.getByName("buffersink"), "sink");
936
819
  assert(bufferSrc && bufferSink);
@@ -940,7 +823,7 @@ var transformVideoSample = async (sample, description) => {
940
823
  NodeAv2.FFmpegError.throwIfError(parseRet, "FilterGraph.parsePtr");
941
824
  const configRet = await graph.config();
942
825
  NodeAv2.FFmpegError.throwIfError(configRet, "FilterGraph.config");
943
- const addRet = await bufferSrc.buffersrcAddFrame(srcFrame);
826
+ const addRet = await bufferSrc.buffersrcAddFrame(srcFrame, NodeAv2.AV_BUFFERSRC_FLAG_KEEP_REF);
944
827
  NodeAv2.FFmpegError.throwIfError(addRet, "buffersrcAddFrame");
945
828
  await bufferSrc.buffersrcAddFrame(null);
946
829
  const dstFrame = new NodeAv2.Frame();
@@ -952,7 +835,8 @@ var transformVideoSample = async (sample, description) => {
952
835
  duration: sample.duration,
953
836
  // Baked in by the filter graph:
954
837
  rotation: 0,
955
- flip: false
838
+ flip: false,
839
+ encodeOptions: sample.encodeOptions
956
840
  });
957
841
  } finally {
958
842
  graph.free();
@@ -1003,6 +887,7 @@ var NodeAvVideoDecoder = class extends CustomVideoDecoder {
1003
887
  }
1004
888
  const codecContext = new NodeAv3.CodecContext();
1005
889
  codecContext.allocContext3(codec);
890
+ codecContext.threadCount = 0;
1006
891
  this.pixelAspectRatio = simplifyRational({
1007
892
  num: (this.config.displayAspectWidth ?? this.config.codedWidth ?? 0) * (this.config.codedHeight ?? 0),
1008
893
  den: (this.config.displayAspectHeight ?? this.config.codedHeight ?? 0) * (this.config.codedWidth ?? 0) || 1
@@ -1013,7 +898,7 @@ var NodeAvVideoDecoder = class extends CustomVideoDecoder {
1013
898
  codecContext.codecId = codecId;
1014
899
  codecContext.extraData = this.config.description ? Buffer.from(toUint8Array(this.config.description)) : null;
1015
900
  codecContext.sampleAspectRatio = new NodeAv3.Rational(this.pixelAspectRatio.num, this.pixelAspectRatio.den);
1016
- const options = NodeAv3.Dictionary.fromObject({ strict: NodeAv3.FF_COMPLIANCE_STRICT });
901
+ const options = this.codec === "avc" ? NodeAv3.Dictionary.fromObject({ strict: NodeAv3.FF_COMPLIANCE_STRICT }) : null;
1017
902
  const ret = await codecContext.open2(codec, options);
1018
903
  NodeAv3.FFmpegError.throwIfError(ret, "Open codec context");
1019
904
  this.codecContext = codecContext;
@@ -1074,6 +959,19 @@ var NodeAvVideoDecoder = class extends CustomVideoDecoder {
1074
959
  receiveFrame(ret) {
1075
960
  NodeAv3.FFmpegError.throwIfError(ret, "Receive frame");
1076
961
  this.frame.sampleAspectRatio = new NodeAv3.Rational(this.pixelAspectRatio.num, this.pixelAspectRatio.den);
962
+ const colorSpace = this.config.colorSpace;
963
+ if (colorSpace?.primaries) {
964
+ this.frame.colorPrimaries = mapColorPrimaries(colorSpace.primaries) ?? this.frame.colorPrimaries;
965
+ }
966
+ if (colorSpace?.transfer) {
967
+ this.frame.colorTrc = mapTransferCharacteristics(colorSpace.transfer) ?? this.frame.colorTrc;
968
+ }
969
+ if (colorSpace?.matrix) {
970
+ this.frame.colorSpace = mapMatrixCoefficients(colorSpace.matrix) ?? this.frame.colorSpace;
971
+ }
972
+ if (typeof colorSpace?.fullRange === "boolean") {
973
+ this.frame.colorRange = colorSpace.fullRange ? NodeAv3.AVCOL_RANGE_JPEG : NodeAv3.AVCOL_RANGE_MPEG;
974
+ }
1077
975
  let timestamp = Number(this.frame.pts) / 1e6;
1078
976
  let duration = Number(this.frame.duration) / 1e6;
1079
977
  const preciseTimingIndex = binarySearchLessOrEqual(
@@ -1113,6 +1011,7 @@ var NodeAvVideoDecoder = class extends CustomVideoDecoder {
1113
1011
  this.receiveFrame(receiveRet);
1114
1012
  }
1115
1013
  this.codecContext.flushBuffers();
1014
+ this.preciseTimings.length = 0;
1116
1015
  }
1117
1016
  close() {
1118
1017
  this.codecContext?.freeContext();
@@ -1153,8 +1052,7 @@ var Bitstream = class _Bitstream {
1153
1052
  }
1154
1053
  let result = 0;
1155
1054
  for (let i = 0; i < n; i++) {
1156
- result <<= 1;
1157
- result |= this.readBit();
1055
+ result = 2 * result + this.readBit();
1158
1056
  }
1159
1057
  return result;
1160
1058
  }
@@ -1164,8 +1062,9 @@ var Bitstream = class _Bitstream {
1164
1062
  const byteIndex = Math.floor(i / 8);
1165
1063
  let byte = this.bytes[byteIndex];
1166
1064
  const bitIndex = 7 - (i & 7);
1065
+ const bit = Math.floor(value / 2 ** (end - i - 1)) & 1;
1167
1066
  byte &= ~(1 << bitIndex);
1168
- byte |= (value & 1 << end - i - 1) >> end - i - 1 << bitIndex;
1067
+ byte |= bit << bitIndex;
1169
1068
  this.bytes[byteIndex] = byte;
1170
1069
  }
1171
1070
  this.pos = end;
@@ -1244,8 +1143,17 @@ var parseAacAudioSpecificConfig = (bytes) => {
1244
1143
  }
1245
1144
  }
1246
1145
  let frameLength = 1024;
1146
+ let programConfigElement = null;
1247
1147
  if (generalAudioObjectTypes.includes(coreObjectType)) {
1248
1148
  frameLength = bitstream.readBits(1) ? 960 : 1024;
1149
+ if (channelConfiguration === 0) {
1150
+ if (bitstream.readBits(1)) {
1151
+ bitstream.skipBits(14);
1152
+ }
1153
+ bitstream.skipBits(1);
1154
+ programConfigElement = readAacProgramConfigElement(bitstream);
1155
+ numberOfChannels = getAacProgramConfigElementChannelCount(programConfigElement);
1156
+ }
1249
1157
  }
1250
1158
  if (objectType !== 5 && objectType !== 29) {
1251
1159
  while (bitstream.getBitsLeft() > 15) {
@@ -1274,7 +1182,8 @@ var parseAacAudioSpecificConfig = (bytes) => {
1274
1182
  coreSampleRate: sampleRate,
1275
1183
  outputSampleRate,
1276
1184
  outputNumberOfChannels: psPresent && numberOfChannels === 1 ? 2 : numberOfChannels,
1277
- frameLength
1185
+ frameLength,
1186
+ programConfigElement
1278
1187
  };
1279
1188
  };
1280
1189
  var readAacObjectType = (bitstream) => {
@@ -1295,9 +1204,62 @@ var readAacSamplingFrequency = (bitstream) => {
1295
1204
  };
1296
1205
  };
1297
1206
  var buildAdtsHeaderTemplate = (config) => {
1298
- const header = new Uint8Array(7);
1207
+ const { coreObjectType, frequencyIndex, frameLength } = config;
1208
+ let { channelConfiguration, programConfigElement } = config;
1209
+ if (coreObjectType < 1 || coreObjectType > 4) {
1210
+ throw new Error(`AAC object type ${coreObjectType} can't be stored in ADTS.`);
1211
+ }
1212
+ if (frequencyIndex >= aacFrequencyTable.length) {
1213
+ throw new Error(`AAC sampling frequency index ${frequencyIndex} can't be stored in ADTS.`);
1214
+ }
1215
+ if (channelConfiguration === 11 || channelConfiguration === 12) {
1216
+ const surroundPair = {
1217
+ isCpe: true,
1218
+ tagSelect: 1
1219
+ };
1220
+ programConfigElement = {
1221
+ elementInstanceTag: 0,
1222
+ objectType: coreObjectType - 1,
1223
+ samplingFrequencyIndex: frequencyIndex,
1224
+ frontElements: [
1225
+ {
1226
+ isCpe: false,
1227
+ tagSelect: 0
1228
+ },
1229
+ {
1230
+ isCpe: true,
1231
+ tagSelect: 0
1232
+ }
1233
+ ],
1234
+ sideElements: channelConfiguration === 12 ? [surroundPair] : [],
1235
+ backElements: channelConfiguration === 11 ? [
1236
+ surroundPair,
1237
+ {
1238
+ isCpe: false,
1239
+ tagSelect: 1
1240
+ }
1241
+ ] : [{
1242
+ isCpe: true,
1243
+ tagSelect: 2
1244
+ }],
1245
+ lfeElementTags: [0],
1246
+ assocDataElementTags: [],
1247
+ ccElements: [],
1248
+ monoMixdownElementNumber: null,
1249
+ stereoMixdownElementNumber: null,
1250
+ matrixMixdown: null,
1251
+ comment: new Uint8Array(0)
1252
+ };
1253
+ channelConfiguration = 0;
1254
+ }
1255
+ if (channelConfiguration > 7) {
1256
+ throw new Error(`AAC channel configuration ${channelConfiguration} can't be stored in ADTS.`);
1257
+ }
1258
+ if (frameLength !== 1024) {
1259
+ throw new Error(`AAC frame length ${frameLength} can't be stored in ADTS.`);
1260
+ }
1261
+ let header = new Uint8Array(7 + (programConfigElement ? getMaxPceByteLength(programConfigElement) : 0));
1299
1262
  const bitstream = new Bitstream(header);
1300
- const { coreObjectType, frequencyIndex, channelConfiguration } = config;
1301
1263
  const profile = coreObjectType - 1;
1302
1264
  bitstream.writeBits(12, 4095);
1303
1265
  bitstream.writeBits(1, 0);
@@ -1314,8 +1276,109 @@ var buildAdtsHeaderTemplate = (config) => {
1314
1276
  bitstream.skipBits(13);
1315
1277
  bitstream.writeBits(11, 2047);
1316
1278
  bitstream.writeBits(2, 0);
1279
+ if (programConfigElement) {
1280
+ bitstream.pos = 8 * 7;
1281
+ bitstream.writeBits(3, 5);
1282
+ writeAacProgramConfigElement(bitstream, programConfigElement);
1283
+ header = header.subarray(0, bitstream.pos / 8);
1284
+ }
1317
1285
  return { header, bitstream };
1318
1286
  };
1287
+ var getMaxPceByteLength = (programConfigElement) => {
1288
+ return 64 + programConfigElement.comment.byteLength;
1289
+ };
1290
+ var writeAacProgramConfigElement = (bitstream, pce) => {
1291
+ bitstream.writeBits(4, pce.elementInstanceTag);
1292
+ bitstream.writeBits(2, pce.objectType);
1293
+ bitstream.writeBits(4, pce.samplingFrequencyIndex);
1294
+ bitstream.writeBits(4, pce.frontElements.length);
1295
+ bitstream.writeBits(4, pce.sideElements.length);
1296
+ bitstream.writeBits(4, pce.backElements.length);
1297
+ bitstream.writeBits(2, pce.lfeElementTags.length);
1298
+ bitstream.writeBits(3, pce.assocDataElementTags.length);
1299
+ bitstream.writeBits(4, pce.ccElements.length);
1300
+ bitstream.writeBits(1, +(pce.monoMixdownElementNumber !== null));
1301
+ if (pce.monoMixdownElementNumber !== null) {
1302
+ bitstream.writeBits(4, pce.monoMixdownElementNumber);
1303
+ }
1304
+ bitstream.writeBits(1, +(pce.stereoMixdownElementNumber !== null));
1305
+ if (pce.stereoMixdownElementNumber !== null) {
1306
+ bitstream.writeBits(4, pce.stereoMixdownElementNumber);
1307
+ }
1308
+ bitstream.writeBits(1, +(pce.matrixMixdown !== null));
1309
+ if (pce.matrixMixdown) {
1310
+ bitstream.writeBits(2, pce.matrixMixdown.index);
1311
+ bitstream.writeBits(1, +pce.matrixMixdown.pseudoSurroundEnabled);
1312
+ }
1313
+ for (const element of [...pce.frontElements, ...pce.sideElements, ...pce.backElements]) {
1314
+ bitstream.writeBits(1, +element.isCpe);
1315
+ bitstream.writeBits(4, element.tagSelect);
1316
+ }
1317
+ for (const tag of [...pce.lfeElementTags, ...pce.assocDataElementTags]) {
1318
+ bitstream.writeBits(4, tag);
1319
+ }
1320
+ for (const element of pce.ccElements) {
1321
+ bitstream.writeBits(1, +element.isIndependentlySwitched);
1322
+ bitstream.writeBits(4, element.tagSelect);
1323
+ }
1324
+ bitstream.pos = 8 * Math.ceil(bitstream.pos / 8);
1325
+ bitstream.writeBits(8, pce.comment.byteLength);
1326
+ bitstream.bytes.set(pce.comment, bitstream.pos / 8);
1327
+ bitstream.pos += 8 * pce.comment.byteLength;
1328
+ };
1329
+ var readAacProgramConfigElement = (bitstream) => {
1330
+ const elementInstanceTag = bitstream.readBits(4);
1331
+ const objectType = bitstream.readBits(2);
1332
+ const samplingFrequencyIndex = bitstream.readBits(4);
1333
+ const frontElementCount = bitstream.readBits(4);
1334
+ const sideElementCount = bitstream.readBits(4);
1335
+ const backElementCount = bitstream.readBits(4);
1336
+ const lfeElementCount = bitstream.readBits(2);
1337
+ const assocDataElementCount = bitstream.readBits(3);
1338
+ const ccElementCount = bitstream.readBits(4);
1339
+ const monoMixdownElementNumber = bitstream.readBits(1) ? bitstream.readBits(4) : null;
1340
+ const stereoMixdownElementNumber = bitstream.readBits(1) ? bitstream.readBits(4) : null;
1341
+ const matrixMixdown = bitstream.readBits(1) ? {
1342
+ index: bitstream.readBits(2),
1343
+ pseudoSurroundEnabled: !!bitstream.readBits(1)
1344
+ } : null;
1345
+ const readChannelElements = (count) => Array.from({ length: count }, () => ({
1346
+ isCpe: !!bitstream.readBits(1),
1347
+ tagSelect: bitstream.readBits(4)
1348
+ }));
1349
+ const frontElements = readChannelElements(frontElementCount);
1350
+ const sideElements = readChannelElements(sideElementCount);
1351
+ const backElements = readChannelElements(backElementCount);
1352
+ const lfeElementTags = Array.from({ length: lfeElementCount }, () => bitstream.readBits(4));
1353
+ const assocDataElementTags = Array.from({ length: assocDataElementCount }, () => bitstream.readBits(4));
1354
+ const ccElements = Array.from({ length: ccElementCount }, () => ({
1355
+ isIndependentlySwitched: !!bitstream.readBits(1),
1356
+ tagSelect: bitstream.readBits(4)
1357
+ }));
1358
+ bitstream.pos = 8 * Math.ceil(bitstream.pos / 8);
1359
+ const commentLength = bitstream.readBits(8);
1360
+ const comment = bitstream.bytes.slice(bitstream.pos / 8, bitstream.pos / 8 + commentLength);
1361
+ bitstream.pos += 8 * commentLength;
1362
+ return {
1363
+ elementInstanceTag,
1364
+ objectType,
1365
+ samplingFrequencyIndex,
1366
+ frontElements,
1367
+ sideElements,
1368
+ backElements,
1369
+ lfeElementTags,
1370
+ assocDataElementTags,
1371
+ ccElements,
1372
+ monoMixdownElementNumber,
1373
+ stereoMixdownElementNumber,
1374
+ matrixMixdown,
1375
+ comment
1376
+ };
1377
+ };
1378
+ var getAacProgramConfigElementChannelCount = (pce) => {
1379
+ const elements = [...pce.frontElements, ...pce.sideElements, ...pce.backElements];
1380
+ return elements.reduce((count, element) => count + (element.isCpe ? 2 : 1), pce.lfeElementTags.length);
1381
+ };
1319
1382
 
1320
1383
  // src/codec.ts
1321
1384
  var PCM_AUDIO_CODECS = [
@@ -1420,6 +1483,56 @@ var VP9_LEVEL_TABLE = [
1420
1483
  { maxPictureSize: 35651584, maxBitrate: 48e7, level: 62 }
1421
1484
  // Level 6.2
1422
1485
  ];
1486
+ var AV1_LEVEL_TABLE = [
1487
+ // Level 2.0 (Main Tier)
1488
+ { maxPictureSize: 147456, maxHSize: 2048, maxVSize: 1152, maxBitrate: 15e5, tier: "M", level: 0 },
1489
+ // Level 2.1 (Main Tier)
1490
+ { maxPictureSize: 278784, maxHSize: 2816, maxVSize: 1584, maxBitrate: 3e6, tier: "M", level: 1 },
1491
+ // Level 3.0 (Main Tier)
1492
+ { maxPictureSize: 665856, maxHSize: 4352, maxVSize: 2448, maxBitrate: 6e6, tier: "M", level: 4 },
1493
+ // Level 3.1 (Main Tier)
1494
+ { maxPictureSize: 1065024, maxHSize: 5504, maxVSize: 3096, maxBitrate: 1e7, tier: "M", level: 5 },
1495
+ // Level 4.0 (Main Tier)
1496
+ { maxPictureSize: 2359296, maxHSize: 6144, maxVSize: 3456, maxBitrate: 12e6, tier: "M", level: 8 },
1497
+ // Level 4.0 (High Tier)
1498
+ { maxPictureSize: 2359296, maxHSize: 6144, maxVSize: 3456, maxBitrate: 3e7, tier: "H", level: 8 },
1499
+ // Level 4.1 (Main Tier)
1500
+ { maxPictureSize: 2359296, maxHSize: 6144, maxVSize: 3456, maxBitrate: 2e7, tier: "M", level: 9 },
1501
+ // Level 4.1 (High Tier)
1502
+ { maxPictureSize: 2359296, maxHSize: 6144, maxVSize: 3456, maxBitrate: 5e7, tier: "H", level: 9 },
1503
+ // Level 5.0 (Main Tier)
1504
+ { maxPictureSize: 8912896, maxHSize: 8192, maxVSize: 4352, maxBitrate: 3e7, tier: "M", level: 12 },
1505
+ // Level 5.0 (High Tier)
1506
+ { maxPictureSize: 8912896, maxHSize: 8192, maxVSize: 4352, maxBitrate: 1e8, tier: "H", level: 12 },
1507
+ // Level 5.1 (Main Tier)
1508
+ { maxPictureSize: 8912896, maxHSize: 8192, maxVSize: 4352, maxBitrate: 4e7, tier: "M", level: 13 },
1509
+ // Level 5.1 (High Tier)
1510
+ { maxPictureSize: 8912896, maxHSize: 8192, maxVSize: 4352, maxBitrate: 16e7, tier: "H", level: 13 },
1511
+ // Level 5.2 (Main Tier)
1512
+ { maxPictureSize: 8912896, maxHSize: 8192, maxVSize: 4352, maxBitrate: 6e7, tier: "M", level: 14 },
1513
+ // Level 5.2 (High Tier)
1514
+ { maxPictureSize: 8912896, maxHSize: 8192, maxVSize: 4352, maxBitrate: 24e7, tier: "H", level: 14 },
1515
+ // Level 5.3 (Main Tier)
1516
+ { maxPictureSize: 8912896, maxHSize: 8192, maxVSize: 4352, maxBitrate: 6e7, tier: "M", level: 15 },
1517
+ // Level 5.3 (High Tier)
1518
+ { maxPictureSize: 8912896, maxHSize: 8192, maxVSize: 4352, maxBitrate: 24e7, tier: "H", level: 15 },
1519
+ // Level 6.0 (Main Tier)
1520
+ { maxPictureSize: 35651584, maxHSize: 16384, maxVSize: 8704, maxBitrate: 6e7, tier: "M", level: 16 },
1521
+ // Level 6.0 (High Tier)
1522
+ { maxPictureSize: 35651584, maxHSize: 16384, maxVSize: 8704, maxBitrate: 24e7, tier: "H", level: 16 },
1523
+ // Level 6.1 (Main Tier)
1524
+ { maxPictureSize: 35651584, maxHSize: 16384, maxVSize: 8704, maxBitrate: 1e8, tier: "M", level: 17 },
1525
+ // Level 6.1 (High Tier)
1526
+ { maxPictureSize: 35651584, maxHSize: 16384, maxVSize: 8704, maxBitrate: 48e7, tier: "H", level: 17 },
1527
+ // Level 6.2 (Main Tier)
1528
+ { maxPictureSize: 35651584, maxHSize: 16384, maxVSize: 8704, maxBitrate: 16e7, tier: "M", level: 18 },
1529
+ // Level 6.2 (High Tier)
1530
+ { maxPictureSize: 35651584, maxHSize: 16384, maxVSize: 8704, maxBitrate: 8e8, tier: "H", level: 18 },
1531
+ // Level 6.3 (Main Tier)
1532
+ { maxPictureSize: 35651584, maxHSize: 16384, maxVSize: 8704, maxBitrate: 16e7, tier: "M", level: 19 },
1533
+ // Level 6.3 (High Tier)
1534
+ { maxPictureSize: 35651584, maxHSize: 16384, maxVSize: 8704, maxBitrate: 8e8, tier: "H", level: 19 }
1535
+ ];
1423
1536
  var VP9_DEFAULT_SUFFIX = ".01.01.01.01.00";
1424
1537
  var AV1_DEFAULT_SUFFIX = ".0.110.01.01.01.0";
1425
1538
  var PRORES_FOURCCS = [
@@ -1462,6 +1575,7 @@ var extractVideoCodecString = (trackInfo) => {
1462
1575
  }
1463
1576
  return `avc${trackInfo.avcType}.${bytesToHexString(codecDescription.subarray(1, 4))}`;
1464
1577
  } else if (codec === "hevc") {
1578
+ assert(trackInfo.hevcType !== null);
1465
1579
  let generalProfileSpace;
1466
1580
  let generalProfileIdc;
1467
1581
  let compatibilityFlags;
@@ -1491,7 +1605,7 @@ var extractVideoCodecString = (trackInfo) => {
1491
1605
  constraintFlags.push(view.getUint8(6 + i));
1492
1606
  }
1493
1607
  }
1494
- let codecString = "hev1.";
1608
+ let codecString = `${trackInfo.hevcType}.`;
1495
1609
  codecString += ["", "A", "B", "C"][generalProfileSpace] + generalProfileIdc;
1496
1610
  codecString += ".";
1497
1611
  codecString += compatibilityFlags.toString(16).toUpperCase();
@@ -1509,19 +1623,19 @@ var extractVideoCodecString = (trackInfo) => {
1509
1623
  } else if (codec === "vp8") {
1510
1624
  return "vp8";
1511
1625
  } else if (codec === "vp9") {
1512
- if (!vp9CodecInfo) {
1513
- const pictureSize = trackInfo.width * trackInfo.height;
1514
- let level2 = last(VP9_LEVEL_TABLE).level;
1515
- for (const entry of VP9_LEVEL_TABLE) {
1516
- if (pictureSize <= entry.maxPictureSize) {
1517
- level2 = entry.level;
1518
- break;
1519
- }
1626
+ const pictureSize = trackInfo.width * trackInfo.height;
1627
+ let levelFromSize = last(VP9_LEVEL_TABLE).level;
1628
+ for (const entry of VP9_LEVEL_TABLE) {
1629
+ if (pictureSize <= entry.maxPictureSize) {
1630
+ levelFromSize = entry.level;
1631
+ break;
1520
1632
  }
1521
- return `vp09.00.${level2.toString().padStart(2, "0")}.08`;
1633
+ }
1634
+ if (!vp9CodecInfo) {
1635
+ return `vp09.00.${levelFromSize.toString().padStart(2, "0")}.08`;
1522
1636
  }
1523
1637
  const profile = vp9CodecInfo.profile.toString().padStart(2, "0");
1524
- const level = vp9CodecInfo.level.toString().padStart(2, "0");
1638
+ const level = (vp9CodecInfo.level === 0 ? levelFromSize : vp9CodecInfo.level).toString().padStart(2, "0");
1525
1639
  const bitDepth = vp9CodecInfo.bitDepth.toString().padStart(2, "0");
1526
1640
  const chromaSubsampling = vp9CodecInfo.chromaSubsampling.toString().padStart(2, "0");
1527
1641
  const colourPrimaries = vp9CodecInfo.colourPrimaries.toString().padStart(2, "0");
@@ -1537,9 +1651,9 @@ var extractVideoCodecString = (trackInfo) => {
1537
1651
  } else if (codec === "av1") {
1538
1652
  if (!av1CodecInfo) {
1539
1653
  const pictureSize = trackInfo.width * trackInfo.height;
1540
- let level2 = last(VP9_LEVEL_TABLE).level;
1541
- for (const entry of VP9_LEVEL_TABLE) {
1542
- if (pictureSize <= entry.maxPictureSize) {
1654
+ let level2 = last(AV1_LEVEL_TABLE).level;
1655
+ for (const entry of AV1_LEVEL_TABLE) {
1656
+ if (pictureSize <= entry.maxPictureSize && trackInfo.width <= entry.maxHSize && trackInfo.height <= entry.maxVSize) {
1543
1657
  level2 = entry.level;
1544
1658
  break;
1545
1659
  }
@@ -1673,7 +1787,7 @@ var extractAvcDecoderConfigurationRecord = (packetData) => {
1673
1787
  if (!spsInfo) {
1674
1788
  return null;
1675
1789
  }
1676
- const hasExtendedData = spsInfo.profileIdc === 100 || spsInfo.profileIdc === 110 || spsInfo.profileIdc === 122 || spsInfo.profileIdc === 144;
1790
+ const hasExtendedData = avcProfileHasExtendedConfigurationData(spsInfo.profileIdc);
1677
1791
  return {
1678
1792
  configurationVersion: 1,
1679
1793
  avcProfileIndication: spsInfo.profileIdc,
@@ -1718,7 +1832,7 @@ var serializeAvcDecoderConfigurationRecord = (record) => {
1718
1832
  bytes.push(pps[i]);
1719
1833
  }
1720
1834
  }
1721
- if ((record.avcProfileIndication === 100 || record.avcProfileIndication === 110 || record.avcProfileIndication === 122 || record.avcProfileIndication === 144) && record.chromaFormat !== null) {
1835
+ if (avcProfileHasExtendedConfigurationData(record.avcProfileIndication) && record.chromaFormat !== null) {
1722
1836
  assert(record.bitDepthLumaMinus8 !== null);
1723
1837
  assert(record.bitDepthChromaMinus8 !== null);
1724
1838
  assert(record.sequenceParameterSetExt !== null);
@@ -1737,6 +1851,9 @@ var serializeAvcDecoderConfigurationRecord = (record) => {
1737
1851
  }
1738
1852
  return new Uint8Array(bytes);
1739
1853
  };
1854
+ var avcProfileHasExtendedConfigurationData = (profileIdc) => {
1855
+ return profileIdc !== 66 && profileIdc !== 77 && profileIdc !== 88;
1856
+ };
1740
1857
  var AVC_HEVC_ASPECT_RATIO_IDC_TABLE = {
1741
1858
  1: { num: 1, den: 1 },
1742
1859
  2: { num: 12, den: 11 },
@@ -1773,7 +1890,7 @@ var parseAvcSps = (sps) => {
1773
1890
  let bitDepthLumaMinus8 = 0;
1774
1891
  let bitDepthChromaMinus8 = 0;
1775
1892
  let separateColourPlaneFlag = 0;
1776
- if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
1893
+ if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128 || profileIdc === 138 || profileIdc === 139 || profileIdc === 134 || profileIdc === 135 || profileIdc === 144) {
1777
1894
  chromaFormatIdc = readExpGolomb(bitstream);
1778
1895
  if (chromaFormatIdc === 3) {
1779
1896
  separateColourPlaneFlag = bitstream.readBits(1);
@@ -1813,18 +1930,18 @@ var parseAvcSps = (sps) => {
1813
1930
  readSignedExpGolomb(bitstream);
1814
1931
  }
1815
1932
  }
1816
- readExpGolomb(bitstream);
1933
+ const maxNumRefFrames = readExpGolomb(bitstream);
1817
1934
  bitstream.skipBits(1);
1818
1935
  const picWidthInMbsMinus1 = readExpGolomb(bitstream);
1819
1936
  const picHeightInMapUnitsMinus1 = readExpGolomb(bitstream);
1820
- const codedWidth = 16 * (picWidthInMbsMinus1 + 1);
1821
- const codedHeight = 16 * (picHeightInMapUnitsMinus1 + 1);
1822
- let displayWidth = codedWidth;
1823
- let displayHeight = codedHeight;
1824
1937
  const frameMbsOnlyFlag = bitstream.readBits(1);
1825
1938
  if (!frameMbsOnlyFlag) {
1826
1939
  bitstream.skipBits(1);
1827
1940
  }
1941
+ const codedWidth = 16 * (picWidthInMbsMinus1 + 1);
1942
+ const codedHeight = 16 * (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1);
1943
+ let displayWidth = codedWidth;
1944
+ let displayHeight = codedHeight;
1828
1945
  bitstream.skipBits(1);
1829
1946
  const frameCroppingFlag = bitstream.readBits(1);
1830
1947
  if (frameCroppingFlag) {
@@ -1937,15 +2054,16 @@ var parseAvcSps = (sps) => {
1937
2054
  const picWidthInMbs = picWidthInMbsMinus1 + 1;
1938
2055
  const picHeightInMapUnits = picHeightInMapUnitsMinus1 + 1;
1939
2056
  const frameHeightInMbs = (2 - frameMbsOnlyFlag) * picHeightInMapUnits;
2057
+ const isLevel1b = levelIdc === 11 && constraintSet3Flag && (profileIdc === 66 || profileIdc === 77 || profileIdc === 88);
1940
2058
  const levelInfo = AVC_LEVEL_TABLE.find(
1941
- (x) => x.level >= levelIdc
2059
+ (x) => x.level >= (isLevel1b ? 10 : levelIdc)
1942
2060
  ) ?? last(AVC_LEVEL_TABLE);
1943
2061
  const maxDpbFrames = Math.min(
1944
2062
  Math.floor(levelInfo.maxDpbMbs / (picWidthInMbs * frameHeightInMbs)),
1945
2063
  16
1946
2064
  );
1947
2065
  numReorderFrames = maxDpbFrames;
1948
- maxDecFrameBuffering = maxDpbFrames;
2066
+ maxDecFrameBuffering = Math.min(Math.max(maxDpbFrames, maxNumRefFrames), 16);
1949
2067
  }
1950
2068
  }
1951
2069
  assert(maxDecFrameBuffering !== null);
@@ -2043,7 +2161,7 @@ var parseHevcSps = (sps) => {
2043
2161
  }
2044
2162
  const bitDepthLumaMinus8 = readExpGolomb(bitstream);
2045
2163
  const bitDepthChromaMinus8 = readExpGolomb(bitstream);
2046
- readExpGolomb(bitstream);
2164
+ const log2MaxPicOrderCntLsbMinus4 = readExpGolomb(bitstream);
2047
2165
  const spsSubLayerOrderingInfoPresentFlag = bitstream.readBits(1);
2048
2166
  const startI = spsSubLayerOrderingInfoPresentFlag ? 0 : spsMaxSubLayersMinus1;
2049
2167
  let spsMaxNumReorderPics = 0;
@@ -2077,7 +2195,7 @@ var parseHevcSps = (sps) => {
2077
2195
  if (bitstream.readBits(1)) {
2078
2196
  const numLongTermRefPicsSps = readExpGolomb(bitstream);
2079
2197
  for (let i = 0; i < numLongTermRefPicsSps; i++) {
2080
- readExpGolomb(bitstream);
2198
+ bitstream.skipBits(log2MaxPicOrderCntLsbMinus4 + 4);
2081
2199
  bitstream.skipBits(1);
2082
2200
  }
2083
2201
  }
@@ -2132,7 +2250,8 @@ var extractHevcDecoderConfigurationRecord = (packetData) => {
2132
2250
  const vpsUnits = [];
2133
2251
  const spsUnits = [];
2134
2252
  const ppsUnits = [];
2135
- const seiUnits = [];
2253
+ const prefixSeiUnits = [];
2254
+ const suffixSeiUnits = [];
2136
2255
  const MAX_NAL_UNITS_PER_ARRAY = 65535;
2137
2256
  for (const loc of iterateNalUnitsInAnnexB(packetData)) {
2138
2257
  const nalUnit = packetData.subarray(loc.offset, loc.offset + loc.length);
@@ -2143,8 +2262,10 @@ var extractHevcDecoderConfigurationRecord = (packetData) => {
2143
2262
  spsUnits.push(nalUnit);
2144
2263
  } else if (type === 34 /* PPS_NUT */ && ppsUnits.length < MAX_NAL_UNITS_PER_ARRAY) {
2145
2264
  ppsUnits.push(nalUnit);
2146
- } else if ((type === 39 /* PREFIX_SEI_NUT */ || type === 40 /* SUFFIX_SEI_NUT */) && seiUnits.length < MAX_NAL_UNITS_PER_ARRAY) {
2147
- seiUnits.push(nalUnit);
2265
+ } else if (type === 39 /* PREFIX_SEI_NUT */ && prefixSeiUnits.length < MAX_NAL_UNITS_PER_ARRAY) {
2266
+ prefixSeiUnits.push(nalUnit);
2267
+ } else if (type === 40 /* SUFFIX_SEI_NUT */ && suffixSeiUnits.length < MAX_NAL_UNITS_PER_ARRAY) {
2268
+ suffixSeiUnits.push(nalUnit);
2148
2269
  }
2149
2270
  }
2150
2271
  if (spsUnits.length === 0 || ppsUnits.length === 0) return null;
@@ -2205,11 +2326,19 @@ var extractHevcDecoderConfigurationRecord = (packetData) => {
2205
2326
  nalUnits: ppsUnits
2206
2327
  }
2207
2328
  ] : [],
2208
- ...seiUnits.length ? [
2329
+ // "array_completeness is 1 for arrays of all types of parameter sets, and 0 for all other arrays"
2330
+ ...prefixSeiUnits.length ? [
2209
2331
  {
2210
- arrayCompleteness: 1,
2211
- nalUnitType: extractNalUnitTypeForHevc(seiUnits[0][0]),
2212
- nalUnits: seiUnits
2332
+ arrayCompleteness: 0,
2333
+ nalUnitType: 39 /* PREFIX_SEI_NUT */,
2334
+ nalUnits: prefixSeiUnits
2335
+ }
2336
+ ] : [],
2337
+ ...suffixSeiUnits.length ? [
2338
+ {
2339
+ arrayCompleteness: 0,
2340
+ nalUnitType: 40 /* SUFFIX_SEI_NUT */,
2341
+ nalUnits: suffixSeiUnits
2213
2342
  }
2214
2343
  ] : []
2215
2344
  ];
@@ -2319,11 +2448,11 @@ var skipStRefPicSet = (bitstream, stRpsIdx, num_short_term_ref_pic_sets, NumDelt
2319
2448
  const numDelta = NumDeltaPocs[RefRpsIdx] ?? 0;
2320
2449
  for (let j = 0; j <= numDelta; j++) {
2321
2450
  const used_by_curr_pic_flag = bitstream.readBits(1);
2322
- if (!used_by_curr_pic_flag) {
2323
- bitstream.readBits(1);
2451
+ const use_delta_flag = used_by_curr_pic_flag || bitstream.readBits(1);
2452
+ if (use_delta_flag) {
2453
+ NumDeltaPocsThis++;
2324
2454
  }
2325
2455
  }
2326
- NumDeltaPocsThis = NumDeltaPocs[RefRpsIdx];
2327
2456
  } else {
2328
2457
  const num_negative_pics = readExpGolomb(bitstream);
2329
2458
  const num_positive_pics = readExpGolomb(bitstream);
@@ -2576,6 +2705,9 @@ var extractVp9CodecInfoFromPacket = (packet) => {
2576
2705
  } else {
2577
2706
  chromaSubsampling = 3;
2578
2707
  videoFullRangeFlag = 1;
2708
+ if (profile === 1 || profile === 3) {
2709
+ bitstream.skipBits(1);
2710
+ }
2579
2711
  }
2580
2712
  const widthMinusOne = bitstream.readBits(16);
2581
2713
  const heightMinusOne = bitstream.readBits(16);
@@ -3031,6 +3163,7 @@ var NodeAvVideoEncoder = class extends CustomVideoEncoder {
3031
3163
  assert(this.codecContext === null);
3032
3164
  const codecContext = new NodeAv4.CodecContext();
3033
3165
  codecContext.allocContext3(this.avCodec);
3166
+ codecContext.threadCount = 0;
3034
3167
  let pixelFormat = NodeAv4.AV_PIX_FMT_YUV420P;
3035
3168
  if (this.avCodec.pixelFormats) {
3036
3169
  if (!this.avCodec.pixelFormats.includes(NodeAv4.AV_PIX_FMT_YUV420P)) {
@@ -3045,6 +3178,8 @@ var NodeAvVideoEncoder = class extends CustomVideoEncoder {
3045
3178
  NodeAv4.AV_PIX_FMT_YUVA444P12LE
3046
3179
  );
3047
3180
  }
3181
+ } else if ((this.config.codec === "ap4h" || this.config.codec === "ap4x") && this.avCodec.pixelFormats.includes(NodeAv4.AV_PIX_FMT_YUV444P10LE)) {
3182
+ pixelFormat = NodeAv4.AV_PIX_FMT_YUV444P10LE;
3048
3183
  }
3049
3184
  }
3050
3185
  const pixelAspectRatio = simplifyRational({
@@ -3073,6 +3208,7 @@ var NodeAvVideoEncoder = class extends CustomVideoEncoder {
3073
3208
  }
3074
3209
  } else if (this.avCodec.name === "libx265") {
3075
3210
  codecContext.setOption("x265-params", "log-level=error");
3211
+ codecContext.setOption("forced-idr", "1");
3076
3212
  if (isRealtime) {
3077
3213
  codecContext.setOption("tune", "zerolatency");
3078
3214
  codecContext.setOption("preset", "ultrafast");
@@ -3084,6 +3220,9 @@ var NodeAvVideoEncoder = class extends CustomVideoEncoder {
3084
3220
  } else {
3085
3221
  codecContext.setOption("cpu-used", "8");
3086
3222
  }
3223
+ if (this.config.alpha === "keep") {
3224
+ codecContext.setOption("auto-alt-ref", "0");
3225
+ }
3087
3226
  } else if (this.avCodec.name === "libvpx-vp9") {
3088
3227
  codecContext.setOption("deadline", "realtime");
3089
3228
  if (isRealtime) {
@@ -3106,6 +3245,8 @@ var NodeAvVideoEncoder = class extends CustomVideoEncoder {
3106
3245
  let mapped;
3107
3246
  if (this.avCodec.name === "libaom-av1" || this.avCodec.name === "libsvtav1" || this.avCodec.name === "libvpx-vp9") {
3108
3247
  mapped = Math.round(this.quantizer / 4);
3248
+ } else if (this.avCodec.name === "libx264") {
3249
+ mapped = Math.max(this.quantizer, 1);
3109
3250
  } else {
3110
3251
  mapped = this.quantizer;
3111
3252
  }
@@ -3330,6 +3471,7 @@ var NodeAvVideoEncoder = class extends CustomVideoEncoder {
3330
3471
  colorSpace: null,
3331
3472
  avcType: 1,
3332
3473
  avcCodecInfo: null,
3474
+ hevcType: this.config.codec.startsWith("hev1.") ? "hev1" : "hvc1",
3333
3475
  hevcCodecInfo: null,
3334
3476
  vp9CodecInfo: null,
3335
3477
  av1CodecInfo: null,
@@ -3384,6 +3526,7 @@ var NodeAvVideoEncoder = class extends CustomVideoEncoder {
3384
3526
  colorSpace: null,
3385
3527
  avcType: null,
3386
3528
  avcCodecInfo: null,
3529
+ hevcType: null,
3387
3530
  hevcCodecInfo: null,
3388
3531
  vp9CodecInfo: null,
3389
3532
  av1CodecInfo: null,
@@ -3401,6 +3544,7 @@ var NodeAvVideoEncoder = class extends CustomVideoEncoder {
3401
3544
  colorSpace: null,
3402
3545
  avcType: null,
3403
3546
  avcCodecInfo: null,
3547
+ hevcType: null,
3404
3548
  hevcCodecInfo: null,
3405
3549
  vp9CodecInfo,
3406
3550
  av1CodecInfo: null,
@@ -3418,6 +3562,7 @@ var NodeAvVideoEncoder = class extends CustomVideoEncoder {
3418
3562
  colorSpace: null,
3419
3563
  avcType: null,
3420
3564
  avcCodecInfo: null,
3565
+ hevcType: null,
3421
3566
  hevcCodecInfo: null,
3422
3567
  vp9CodecInfo: null,
3423
3568
  av1CodecInfo,
@@ -3434,6 +3579,7 @@ var NodeAvVideoEncoder = class extends CustomVideoEncoder {
3434
3579
  colorSpace: null,
3435
3580
  avcType: null,
3436
3581
  avcCodecInfo: null,
3582
+ hevcType: null,
3437
3583
  hevcCodecInfo: null,
3438
3584
  vp9CodecInfo: null,
3439
3585
  av1CodecInfo: null,
@@ -3491,6 +3637,7 @@ var NodeAvVideoEncoder = class extends CustomVideoEncoder {
3491
3637
  this.codecContext = null;
3492
3638
  }
3493
3639
  this.packetEmitted = false;
3640
+ this.preciseTimings.length = 0;
3494
3641
  }
3495
3642
  close() {
3496
3643
  this.codecContext?.freeContext();
@@ -3547,15 +3694,16 @@ var AvFrameAudioSampleResource = class extends AudioSampleResource {
3547
3694
  return this.frame.nbSamples;
3548
3695
  }
3549
3696
  getTimestamp() {
3550
- return Number(this.frame.pts) / this.frame.timeBase.den;
3697
+ return Number(this.frame.pts) * this.frame.timeBase.num / this.frame.timeBase.den;
3551
3698
  }
3552
3699
  close() {
3553
3700
  this.frame.free();
3554
3701
  this._frame = null;
3555
3702
  }
3556
3703
  getDataPlane(planeIndex) {
3557
- assert(this.frame.data && planeIndex < this.frame.data.length);
3558
- return toUint8Array(this.frame.data[planeIndex]);
3704
+ const planes = this.frame.extendedData;
3705
+ assert(planes && planeIndex < planes.length);
3706
+ return toUint8Array(planes[planeIndex]);
3559
3707
  }
3560
3708
  };
3561
3709
  var copyAudioSampleToAvFrame = (sample, frame) => {
@@ -3565,9 +3713,10 @@ var copyAudioSampleToAvFrame = (sample, frame) => {
3565
3713
  frame.sampleRate = sample.sampleRate;
3566
3714
  frame.channelLayout = getChannelLayout(sample.numberOfChannels);
3567
3715
  frame.allocBuffer();
3568
- assert(frame.data);
3569
- for (let i = 0; i < frame.data.length; i++) {
3570
- sample.copyTo(frame.data[i], { planeIndex: i });
3716
+ const planes = frame.extendedData;
3717
+ assert(planes);
3718
+ for (let i = 0; i < planes.length; i++) {
3719
+ sample.copyTo(planes[i], { planeIndex: i });
3571
3720
  }
3572
3721
  };
3573
3722
 
@@ -3594,6 +3743,7 @@ var NodeAvAudioDecoder = class extends CustomAudioDecoder {
3594
3743
  }
3595
3744
  const codecContext = new NodeAv6.CodecContext();
3596
3745
  codecContext.allocContext3(codec);
3746
+ codecContext.threadCount = 0;
3597
3747
  codecContext.sampleRate = this.config.sampleRate;
3598
3748
  codecContext.channelLayout = getChannelLayout(this.config.numberOfChannels);
3599
3749
  codecContext.timeBase = new NodeAv6.Rational(1, this.config.sampleRate);
@@ -3665,15 +3815,16 @@ import * as NodeAv7 from "node-av";
3665
3815
  var DTS_SAMPLE_RATES = [8e3, 11025, 12e3, 16e3, 22050, 24e3, 32e3, 44100, 48e3];
3666
3816
  var DTS_CHANNEL_COUNTS = [1, 2, 4, 5, 6];
3667
3817
  var DTS_MAX_FRAME_SIZE = 16384;
3668
- var dtsBitrateFits = (bitrate, sampleRate, numberOfChannels) => {
3669
- if (bitrate < 32e3 || bitrate > 384e4) {
3670
- return false;
3671
- }
3818
+ var clampDtsBitrate = (bitrate, sampleRate, numberOfChannels) => {
3672
3819
  const hasLfe = numberOfChannels === 6;
3673
3820
  const fullbandChannels = numberOfChannels - (hasLfe ? 1 : 0);
3674
- const frameBits = 32 * Math.ceil(Math.ceil(bitrate * 512 / sampleRate) / 32);
3675
3821
  const minFrameBits = 132 + (493 + 28 * 32) * fullbandChannels + (hasLfe ? 72 : 0);
3676
- return frameBits >= minFrameBits && frameBits <= 8 * DTS_MAX_FRAME_SIZE;
3822
+ const minBitrate = Math.max(
3823
+ 32e3,
3824
+ Math.floor(32 * (Math.ceil(minFrameBits / 32) - 1) * sampleRate / 512) + 1
3825
+ );
3826
+ const maxBitrate = Math.min(384e4, Math.floor(8 * DTS_MAX_FRAME_SIZE * sampleRate / 512));
3827
+ return Math.min(Math.max(bitrate, minBitrate), maxBitrate);
3677
3828
  };
3678
3829
 
3679
3830
  // packages/server/src/audio-encoder.ts
@@ -3681,7 +3832,14 @@ var AAC_SAMPLE_RATES = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3,
3681
3832
  var OPUS_SAMPLE_RATES = [8e3, 12e3, 16e3, 24e3, 48e3];
3682
3833
  var MP3_SAMPLE_RATES = [8e3, 11025, 12e3, 16e3, 22050, 24e3, 32e3, 44100, 48e3];
3683
3834
  var AC3_SAMPLE_RATES = [32e3, 44100, 48e3];
3835
+ var SUPPORTED_AAC_CHANNEL_COUNTS = [1, 2, 3, 4, 5, 6, 8];
3684
3836
  var FRAME_SIZE_FALLBACK = 1024;
3837
+ var DTS_ENCODER_DELAY = 512;
3838
+ var UNFLUSHED_ENCODER_DELAYS = {
3839
+ ac3: 256,
3840
+ eac3: 256,
3841
+ dts: DTS_ENCODER_DELAY
3842
+ };
3685
3843
  var NodeAvAudioEncoder = class extends CustomAudioEncoder {
3686
3844
  constructor() {
3687
3845
  super(...arguments);
@@ -3696,7 +3854,8 @@ var NodeAvAudioEncoder = class extends CustomAudioEncoder {
3696
3854
  }
3697
3855
  static supports(codec, config) {
3698
3856
  const { numberOfChannels, sampleRate } = config;
3699
- return codec === "aac" && numberOfChannels >= 1 && numberOfChannels <= 48 && AAC_SAMPLE_RATES.includes(sampleRate) || codec === "opus" && numberOfChannels >= 1 && numberOfChannels <= 255 && OPUS_SAMPLE_RATES.includes(sampleRate) || codec === "mp3" && numberOfChannels >= 1 && numberOfChannels <= 2 && MP3_SAMPLE_RATES.includes(sampleRate) || codec === "vorbis" && numberOfChannels >= 1 && numberOfChannels <= 255 && sampleRate <= 2e5 || codec === "flac" && numberOfChannels >= 1 && numberOfChannels <= 8 && sampleRate <= 655350 || codec === "ac3" && numberOfChannels >= 1 && numberOfChannels <= 6 && AC3_SAMPLE_RATES.includes(sampleRate) || codec === "eac3" && numberOfChannels >= 1 && numberOfChannels <= 16 && AC3_SAMPLE_RATES.includes(sampleRate) || codec === "dts" && DTS_CHANNEL_COUNTS.includes(numberOfChannels) && DTS_SAMPLE_RATES.includes(sampleRate) && dtsBitrateFits(resolveBitrate(config, codec), sampleRate, numberOfChannels) || codec === "truehd" && TRUEHD_CHANNEL_COUNTS.includes(numberOfChannels) && TRUEHD_SAMPLE_RATES.includes(sampleRate);
3857
+ return codec === "aac" && SUPPORTED_AAC_CHANNEL_COUNTS.includes(numberOfChannels) && AAC_SAMPLE_RATES.includes(sampleRate) || // Without an explicit mapping family, libopus only does up to 8 channels
3858
+ codec === "opus" && numberOfChannels >= 1 && numberOfChannels <= 8 && OPUS_SAMPLE_RATES.includes(sampleRate) || codec === "mp3" && numberOfChannels >= 1 && numberOfChannels <= 2 && MP3_SAMPLE_RATES.includes(sampleRate) || codec === "vorbis" && numberOfChannels >= 1 && numberOfChannels <= 8 && sampleRate <= 5e4 || codec === "flac" && numberOfChannels >= 1 && numberOfChannels <= 8 && sampleRate <= 655350 || codec === "ac3" && numberOfChannels >= 1 && numberOfChannels <= 6 && AC3_SAMPLE_RATES.includes(sampleRate) || codec === "eac3" && numberOfChannels >= 1 && numberOfChannels <= 6 && AC3_SAMPLE_RATES.includes(sampleRate) || codec === "dts" && DTS_CHANNEL_COUNTS.includes(numberOfChannels) && DTS_SAMPLE_RATES.includes(sampleRate) || codec === "truehd" && TRUEHD_CHANNEL_COUNTS.includes(numberOfChannels) && TRUEHD_SAMPLE_RATES.includes(sampleRate);
3700
3859
  }
3701
3860
  async init() {
3702
3861
  this.frame = new NodeAv7.Frame();
@@ -3710,23 +3869,39 @@ var NodeAvAudioEncoder = class extends CustomAudioEncoder {
3710
3869
  throw new Error(`Unable to obtain libav codec for '${this.codec}'.`);
3711
3870
  }
3712
3871
  this.avCodec = codec;
3713
- await this.createCodecContext();
3872
+ if (this.codec !== "flac") {
3873
+ await this.createCodecContext(null);
3874
+ }
3714
3875
  }
3715
- async createCodecContext() {
3876
+ async createCodecContext(firstSample) {
3716
3877
  assert(this.codecContext === null);
3717
3878
  const codecContext = new NodeAv7.CodecContext();
3718
3879
  codecContext.allocContext3(this.avCodec);
3880
+ codecContext.threadCount = 0;
3719
3881
  let sampleFormat = NodeAv7.AV_SAMPLE_FMT_FLTP;
3720
3882
  if (this.codec === "truehd") {
3721
3883
  sampleFormat = NodeAv7.AV_SAMPLE_FMT_S32P;
3884
+ } else if (this.codec === "flac") {
3885
+ assert(firstSample);
3886
+ if (firstSample.format.startsWith("u8") || firstSample.format.startsWith("s16")) {
3887
+ sampleFormat = NodeAv7.AV_SAMPLE_FMT_S16;
3888
+ } else {
3889
+ sampleFormat = NodeAv7.AV_SAMPLE_FMT_S32;
3890
+ codecContext.bitsPerRawSample = 24;
3891
+ }
3722
3892
  } else if (this.avCodec.sampleFormats && !this.avCodec.sampleFormats.includes(NodeAv7.AV_SAMPLE_FMT_FLTP)) {
3723
3893
  sampleFormat = this.avCodec.sampleFormats[0];
3724
3894
  }
3895
+ const isAacOrAc3 = this.codec === "aac" || this.codec === "ac3" || this.codec === "eac3";
3725
3896
  codecContext.sampleRate = this.config.sampleRate;
3726
3897
  if (this.codec === "dts") {
3727
3898
  codecContext.channelLayout = getDtsChannelLayout(this.config.numberOfChannels);
3728
3899
  } else if (this.codec === "truehd") {
3729
3900
  codecContext.channelLayout = getTrueHdChannelLayout(this.config.numberOfChannels);
3901
+ } else if (isAacOrAc3 && this.config.numberOfChannels === 3) {
3902
+ codecContext.channelLayout = NodeAv7.AV_CHANNEL_LAYOUT_SURROUND;
3903
+ } else if (isAacOrAc3 && this.config.numberOfChannels === 5) {
3904
+ codecContext.channelLayout = NodeAv7.AV_CHANNEL_LAYOUT_5POINT0_BACK;
3730
3905
  } else {
3731
3906
  codecContext.channelLayout = getChannelLayout(this.config.numberOfChannels);
3732
3907
  }
@@ -3746,7 +3921,7 @@ var NodeAvAudioEncoder = class extends CustomAudioEncoder {
3746
3921
  }
3747
3922
  async encode(audioSample) {
3748
3923
  if (this.codecContext === null) {
3749
- await this.createCodecContext();
3924
+ await this.createCodecContext(audioSample);
3750
3925
  assert(this.codecContext);
3751
3926
  }
3752
3927
  if (audioSample._data instanceof AvFrameAudioSampleResource) {
@@ -3771,7 +3946,7 @@ var NodeAvAudioEncoder = class extends CustomAudioEncoder {
3771
3946
  this.resampler = new NodeAv7.SoftwareResampleContext();
3772
3947
  this.resamplerInputSampleRate = this.frame.sampleRate;
3773
3948
  const outLayout = this.codecContext.channelLayout;
3774
- const inLayout = getChannelLayout(this.frame.channels);
3949
+ const inLayout = this.frame.channels === this.codecContext.channels ? outLayout : getChannelLayout(this.frame.channels);
3775
3950
  const ret = this.resampler.allocSetOpts2(
3776
3951
  outLayout,
3777
3952
  this.codecContext.sampleFormat,
@@ -3838,7 +4013,8 @@ var NodeAvAudioEncoder = class extends CustomAudioEncoder {
3838
4013
  if (!this.packet.data) {
3839
4014
  return;
3840
4015
  }
3841
- const timestamp = Number(this.packet.pts) / this.codecContext.sampleRate;
4016
+ const delay = this.codec === "dts" ? DTS_ENCODER_DELAY : 0;
4017
+ const timestamp = (Number(this.packet.pts) - delay) / this.codecContext.sampleRate;
3842
4018
  const duration = Number(this.packet.duration) / this.codecContext.sampleRate;
3843
4019
  let data = this.packet.data;
3844
4020
  let metadata;
@@ -3916,12 +4092,29 @@ var NodeAvAudioEncoder = class extends CustomAudioEncoder {
3916
4092
  outer:
3917
4093
  if (this.resampler) {
3918
4094
  assert(this.resamplerInputSampleRate !== null);
4095
+ const unflushedDelay = UNFLUSHED_ENCODER_DELAYS[this.codec];
4096
+ if (unflushedDelay !== void 0) {
4097
+ this.resampler.injectSilence(
4098
+ Math.ceil(unflushedDelay / this.codecContext.sampleRate * this.resamplerInputSampleRate)
4099
+ );
4100
+ await this.pullResampledFrames();
4101
+ }
3919
4102
  const currentOutSamples = this.resampler.getOutSamples(0);
3920
4103
  if (currentOutSamples === 0) {
3921
4104
  break outer;
3922
4105
  }
3923
4106
  const frameSize = this.codecContext.frameSize || FRAME_SIZE_FALLBACK;
3924
4107
  assert(currentOutSamples < frameSize);
4108
+ if (this.codec === "flac" || this.codec === "truehd") {
4109
+ assert(this.dstFrame);
4110
+ assert(this.nextResamplerPts !== null);
4111
+ const samples = await this.resampler.convert(this.dstFrame.data, frameSize, null, 0);
4112
+ this.dstFrame.nbSamples = samples;
4113
+ this.dstFrame.duration = BigInt(samples);
4114
+ this.dstFrame.pts = this.nextResamplerPts;
4115
+ await this.sendFrameAndReceivePackets(this.dstFrame);
4116
+ break outer;
4117
+ }
3925
4118
  const inputSamplesNeeded = Math.ceil(
3926
4119
  (frameSize - currentOutSamples) / this.codecContext.sampleRate * this.resamplerInputSampleRate
3927
4120
  );
@@ -3950,207 +4143,20 @@ var NodeAvAudioEncoder = class extends CustomAudioEncoder {
3950
4143
  }
3951
4144
  };
3952
4145
  var resolveBitrate = (config, codec) => {
3953
- return config.bitrate ?? new Quality2("medium")._toAudioBitrate(codec) ?? 0;
3954
- };
3955
-
3956
- // packages/prores/src/index.ts
3957
- import { CustomVideoDecoder as CustomVideoDecoder2, Logging as Logging2, registerDecoder, VideoSample as VideoSample4 } from "mediabunny";
3958
- import { Decoder, Frame as Frame7, PIXEL_FORMATS } from "turbores";
3959
- var PRORES_LOADED_SYMBOL = Symbol.for("@mediabunny/prores loaded");
3960
- if (globalThis[PRORES_LOADED_SYMBOL]) {
3961
- Logging2._error(
3962
- "[WARNING]\n@mediabunny/prores was loaded twice. This will likely cause the decoder not to work correctly. Check if multiple dependencies are importing different versions of @mediabunny/prores, or if something is being bundled incorrectly."
3963
- );
3964
- }
3965
- globalThis[PRORES_LOADED_SYMBOL] = true;
3966
- var _ProresDecoder = class _ProresDecoder extends CustomVideoDecoder2 {
3967
- constructor() {
3968
- super(...arguments);
3969
- this.decoder = null;
3970
- this.framePool = [];
3971
- }
3972
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
3973
- static supports(codec, config) {
3974
- return codec === "prores";
3975
- }
3976
- /** @internal */
3977
- static _determineSupportedVideoFrameFormats() {
3978
- const result = [];
3979
- const data = new Uint8Array(32);
3980
- for (const format of PIXEL_FORMATS) {
3981
- try {
3982
- const frame = new VideoFrame(data, {
3983
- format,
3984
- codedWidth: 2,
3985
- codedHeight: 2,
3986
- timestamp: 0,
3987
- duration: 0
3988
- });
3989
- frame.close();
3990
- result.push(format);
3991
- } catch {
3992
- }
3993
- }
3994
- return result;
3995
- }
3996
- async init() {
3997
- if (typeof VideoFrame !== "undefined") {
3998
- _ProresDecoder._supportedVideoFrameFormats ??= _ProresDecoder._determineSupportedVideoFrameFormats();
3999
- }
4000
- const decoder = await Decoder.create({
4001
- proresFourCc: this.config.codec,
4002
- useSharedMemory: Decoder.canUseSharedMemory(),
4003
- allowedOutputFormats: _ProresDecoder._supportedVideoFrameFormats ?? void 0
4004
- });
4005
- if (decoder instanceof Error) {
4006
- throw decoder;
4007
- }
4008
- this.decoder = decoder;
4009
- }
4010
- async decode(packet) {
4011
- assert(this.decoder);
4012
- while (this.decoder.desiredSize <= 0) {
4013
- await this.decoder.dequeued;
4014
- }
4015
- void this.runDecode(packet).catch((error) => this.onError(error));
4016
- }
4017
- async runDecode(packet) {
4018
- assert(this.decoder);
4019
- let frame;
4020
- if (this.framePool.length > 0) {
4021
- frame = this.framePool.shift();
4022
- } else {
4023
- frame = new Frame7();
4024
- }
4025
- const result = await this.decoder.decode(packet.data, frame);
4026
- this.framePool.push(frame);
4027
- if (result instanceof Error) {
4028
- throw result;
4029
- }
4030
- if (result.visibleHeight < result.codedHeight && isWebKit()) {
4031
- this.trimCodedHeightToVisibleHeight(result);
4032
- }
4033
- const colorSpaceInit = {
4034
- primaries: result.colorPrimariesString,
4035
- matrix: result.colorMatrixString,
4036
- transfer: result.colorTransferString,
4037
- fullRange: result.colorRangeFull
4038
- };
4039
- let displayWidth = result.visibleWidth;
4040
- let displayHeight = result.visibleHeight;
4041
- if (result.pixelAspectRatio.num > result.pixelAspectRatio.den) {
4042
- displayWidth = Math.round(
4043
- result.visibleWidth * result.pixelAspectRatio.num / result.pixelAspectRatio.den
4044
- );
4045
- } else {
4046
- displayHeight = Math.round(
4047
- result.visibleHeight * result.pixelAspectRatio.den / result.pixelAspectRatio.num
4048
- );
4049
- }
4050
- let sample;
4051
- if (typeof VideoFrame !== "undefined") {
4052
- const frame2 = new VideoFrame(result.frameData, {
4053
- format: result.pixelFormat,
4054
- codedWidth: result.codedWidth,
4055
- codedHeight: result.codedHeight,
4056
- displayWidth,
4057
- displayHeight,
4058
- visibleRect: {
4059
- x: 0,
4060
- y: 0,
4061
- width: result.visibleWidth,
4062
- height: result.visibleHeight
4063
- },
4064
- timestamp: packet.microsecondTimestamp,
4065
- duration: packet.microsecondDuration,
4066
- colorSpace: colorSpaceInit
4067
- });
4068
- sample = new VideoSample4(frame2, {
4069
- timestamp: packet.timestamp,
4070
- duration: packet.duration
4071
- });
4072
- } else {
4073
- sample = new VideoSample4(result.frameData, {
4074
- format: result.pixelFormat,
4075
- codedWidth: result.codedWidth,
4076
- codedHeight: result.codedHeight,
4077
- displayWidth,
4078
- displayHeight,
4079
- visibleRect: {
4080
- left: 0,
4081
- top: 0,
4082
- width: result.visibleWidth,
4083
- height: result.visibleHeight
4084
- },
4085
- timestamp: packet.timestamp,
4086
- duration: packet.duration,
4087
- colorSpace: colorSpaceInit
4088
- });
4089
- }
4090
- this.onSample(sample);
4091
- }
4092
- trimCodedHeightToVisibleHeight(result) {
4093
- const bytesPerSample = result.pixelFormat.includes("P") ? 2 : 1;
4094
- const subWidth = result.pixelFormat.includes("444") ? 1 : 2;
4095
- const subHeight = result.pixelFormat.includes("420") ? 2 : 1;
4096
- const chromaCodedWidth = result.codedWidth / subWidth;
4097
- const chromaCodedHeight = result.codedHeight / subHeight;
4098
- const chromaVisibleHeight = Math.ceil(result.visibleHeight / subHeight);
4099
- const lumaCodedPixels = result.codedWidth * result.codedHeight;
4100
- const lumaVisiblePixels = result.codedWidth * result.visibleHeight;
4101
- const chromaCodedPixels = chromaCodedWidth * chromaCodedHeight;
4102
- const chromaVisiblePixels = chromaCodedWidth * chromaVisibleHeight;
4103
- result.frameData.set(
4104
- result.frameData.subarray(
4105
- bytesPerSample * lumaCodedPixels,
4106
- bytesPerSample * (lumaCodedPixels + chromaCodedPixels)
4107
- ),
4108
- bytesPerSample * lumaVisiblePixels
4109
- );
4110
- result.frameData.set(
4111
- result.frameData.subarray(
4112
- bytesPerSample * (lumaCodedPixels + chromaCodedPixels),
4113
- bytesPerSample * (lumaCodedPixels + 2 * chromaCodedPixels)
4114
- ),
4115
- bytesPerSample * (lumaVisiblePixels + chromaVisiblePixels)
4116
- );
4117
- result.codedHeight = result.visibleHeight;
4118
- }
4119
- async flush() {
4120
- assert(this.decoder);
4121
- while (this.decoder.decodeQueueSize > 0) {
4122
- await this.decoder.dequeued;
4123
- }
4124
- }
4125
- async close() {
4126
- assert(this.decoder);
4127
- await this.decoder.close();
4128
- for (const frame of this.framePool) {
4129
- frame.clear();
4130
- }
4131
- }
4132
- };
4133
- /** @internal */
4134
- _ProresDecoder._supportedVideoFrameFormats = null;
4135
- var ProresDecoder = _ProresDecoder;
4136
- var registered = false;
4137
- var registerProresDecoder = () => {
4138
- if (registered) {
4139
- return;
4140
- }
4141
- registered = true;
4142
- registerDecoder(ProresDecoder);
4146
+ const bitrate = config.bitrate ?? new Quality2("medium")._toAudioBitrate(codec, config.numberOfChannels) ?? 0;
4147
+ return codec === "dts" ? clampDtsBitrate(bitrate, config.sampleRate, config.numberOfChannels) : bitrate;
4143
4148
  };
4144
4149
 
4145
4150
  // packages/server/src/index.ts
4151
+ import { registerProresDecoder } from "@mediabunny/prores";
4146
4152
  var SERVER_LOADED_SYMBOL = Symbol.for("@mediabunny/server loaded");
4147
4153
  if (globalThis[SERVER_LOADED_SYMBOL]) {
4148
- Logging3._error(
4154
+ Logging2._error(
4149
4155
  "[WARNING]\n@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."
4150
4156
  );
4151
4157
  }
4152
4158
  globalThis[SERVER_LOADED_SYMBOL] = true;
4153
- var registered2 = false;
4159
+ var registered = false;
4154
4160
  var _serverOptions = {};
4155
4161
  var registerMediabunnyServer = (options = {}) => {
4156
4162
  if (typeof options !== "object" || !options) {
@@ -4161,27 +4167,27 @@ var registerMediabunnyServer = (options = {}) => {
4161
4167
  "options.hardwareContext, when provided, must be a NodeAv.HardwareContext, a function, or null."
4162
4168
  );
4163
4169
  }
4164
- if (registered2) {
4170
+ if (registered) {
4165
4171
  return;
4166
4172
  }
4167
- registered2 = true;
4173
+ registered = true;
4168
4174
  _serverOptions = options;
4169
4175
  NodeAv8.Log.setLevel(NodeAv8.AV_LOG_ERROR);
4170
- registerDecoder2(NodeAvVideoDecoder);
4176
+ registerDecoder(NodeAvVideoDecoder);
4171
4177
  registerProresDecoder();
4172
4178
  registerEncoder(NodeAvVideoEncoder);
4173
- registerDecoder2(NodeAvAudioDecoder);
4179
+ registerDecoder(NodeAvAudioDecoder);
4174
4180
  registerEncoder(NodeAvAudioEncoder);
4175
4181
  registerVideoSampleTransformer(transformVideoSample);
4176
4182
  };
4177
4183
  var toAvFrame = async (sample, frame) => {
4178
- if (!(sample instanceof VideoSample5) && !(sample instanceof AudioSample4)) {
4184
+ if (!(sample instanceof VideoSample4) && !(sample instanceof AudioSample4)) {
4179
4185
  throw new TypeError("sample must be a VideoSample or an AudioSample.");
4180
4186
  }
4181
4187
  if (!(frame instanceof NodeAv8.Frame)) {
4182
4188
  throw new TypeError("frame must be a NodeAv.Frame.");
4183
4189
  }
4184
- if (sample instanceof VideoSample5) {
4190
+ if (sample instanceof VideoSample4) {
4185
4191
  if (sample._data instanceof AvFrameVideoSampleResource) {
4186
4192
  frame.unref();
4187
4193
  frame.ref(sample._data.frame);