@mediabunny/server 1.62.1 → 1.64.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 Logging2,
13
- registerDecoder,
12
+ Logging as Logging3,
13
+ registerDecoder as registerDecoder2,
14
14
  registerEncoder,
15
15
  registerVideoSampleTransformer,
16
- VideoSample as VideoSample4
16
+ VideoSample as VideoSample5
17
17
  } from "mediabunny";
18
18
  import * as NodeAv8 from "node-av";
19
19
 
@@ -37,7 +37,8 @@ var CODEC_TO_CODEC_ID = {
37
37
  flac: NodeAv.AV_CODEC_ID_FLAC,
38
38
  ac3: NodeAv.AV_CODEC_ID_AC3,
39
39
  eac3: NodeAv.AV_CODEC_ID_EAC3,
40
- dts: NodeAv.AV_CODEC_ID_DTS
40
+ dts: NodeAv.AV_CODEC_ID_DTS,
41
+ truehd: NodeAv.AV_CODEC_ID_TRUEHD
41
42
  };
42
43
  var cachedHardwareContext = void 0;
43
44
  var getHardwareContext = () => {
@@ -366,6 +367,24 @@ var getDtsChannelLayout = (numChannels) => {
366
367
  return { nbChannels: numChannels, order: NodeAv.AV_CHANNEL_ORDER_UNSPEC, mask: 0n };
367
368
  }
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
+ };
369
388
 
370
389
  // src/logging.ts
371
390
  var _Logging = class _Logging {
@@ -663,6 +682,14 @@ var assertNever = (x) => {
663
682
  throw new Error(`Unexpected value: ${x}`);
664
683
  };
665
684
  var SECOND_TO_MICROSECOND_FACTOR = 1e6 * (1 + Number.EPSILON);
685
+ var isWebKitCache = null;
686
+ var isWebKit = () => {
687
+ if (isWebKitCache !== null) {
688
+ return isWebKitCache;
689
+ }
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
+ };
666
693
  var NativePromiseConstructor = (async () => {
667
694
  })().constructor;
668
695
  var simplifyRational = (rational) => {
@@ -1191,6 +1218,7 @@ var aacFrequencyTable = [
1191
1218
  7350
1192
1219
  ];
1193
1220
  var aacChannelMap = [-1, 1, 2, 3, 4, 5, 6, 8];
1221
+ var generalAudioObjectTypes = [1, 2, 3, 4, 6, 7, 17, 19, 20, 21, 22];
1194
1222
  var parseAacAudioSpecificConfig = (bytes) => {
1195
1223
  if (!bytes || bytes.byteLength < 2) {
1196
1224
  throw new TypeError("AAC description must be at least 2 bytes long.");
@@ -1213,7 +1241,12 @@ var parseAacAudioSpecificConfig = (bytes) => {
1213
1241
  if (coreObjectType === 22) {
1214
1242
  bitstream.skipBits(4);
1215
1243
  }
1216
- } else {
1244
+ }
1245
+ let frameLength = 1024;
1246
+ if (generalAudioObjectTypes.includes(coreObjectType)) {
1247
+ frameLength = bitstream.readBits(1) ? 960 : 1024;
1248
+ }
1249
+ if (objectType !== 5 && objectType !== 29) {
1217
1250
  while (bitstream.getBitsLeft() > 15) {
1218
1251
  const searchStart = bitstream.pos;
1219
1252
  if (bitstream.readBits(11) !== 695) {
@@ -1237,8 +1270,10 @@ var parseAacAudioSpecificConfig = (bytes) => {
1237
1270
  coreObjectType,
1238
1271
  frequencyIndex,
1239
1272
  channelConfiguration,
1273
+ coreSampleRate: sampleRate,
1240
1274
  outputSampleRate,
1241
- outputNumberOfChannels: psPresent && numberOfChannels === 1 ? 2 : numberOfChannels
1275
+ outputNumberOfChannels: psPresent && numberOfChannels === 1 ? 2 : numberOfChannels,
1276
+ frameLength
1242
1277
  };
1243
1278
  };
1244
1279
  var readAacObjectType = (bitstream) => {
@@ -1307,7 +1342,8 @@ var NON_PCM_AUDIO_CODECS = [
1307
1342
  "flac",
1308
1343
  "ac3",
1309
1344
  "eac3",
1310
- "dts"
1345
+ "dts",
1346
+ "truehd"
1311
1347
  ];
1312
1348
  var AUDIO_CODECS = [
1313
1349
  ...NON_PCM_AUDIO_CODECS,
@@ -1549,6 +1585,11 @@ var extractVideoCodecString = (trackInfo) => {
1549
1585
  };
1550
1586
  var VALID_VIDEO_CODEC_STRING_PREFIXES = ["avc1", "avc3", "hev1", "hvc1", "vp8", "vp09", "av01", ...PRORES_FOURCCS];
1551
1587
 
1588
+ // shared/truehd-misc.ts
1589
+ var TRUEHD_MAJOR_SYNC_WORD = 4168249274;
1590
+ var TRUEHD_SAMPLE_RATES = [44100, 48e3, 88200, 96e3, 176400, 192e3];
1591
+ var TRUEHD_CHANNEL_COUNTS = [1, 2, 3, 4, 5, 6];
1592
+
1552
1593
  // src/codec-data.ts
1553
1594
  var iterateNalUnitsInAnnexB = function* (packetData) {
1554
1595
  let i = 0;
@@ -2796,6 +2837,14 @@ var extractAv1CodecInfoFromPacket = (packet) => {
2796
2837
  var av1CodecInfoHasColorInfo = (info) => {
2797
2838
  return info.colourPrimaries !== 2 || info.transferCharacteristics !== 2 || info.matrixCoefficients !== 2;
2798
2839
  };
2840
+ var determineAudioPacketType = (codec, packetData) => {
2841
+ if (codec === "truehd") {
2842
+ const syncWord = packetData.byteLength >= 8 ? toDataView(packetData).getUint32(4) : null;
2843
+ return syncWord === TRUEHD_MAJOR_SYNC_WORD ? "key" : "delta";
2844
+ } else {
2845
+ return "key";
2846
+ }
2847
+ };
2799
2848
  var AC3_FRAME_SIZES = [
2800
2849
  // frmsizecod, [48kHz, 44.1kHz, 32kHz] in bytes
2801
2850
  64 * 2,
@@ -3528,7 +3577,7 @@ var NodeAvAudioDecoder = class extends CustomAudioDecoder {
3528
3577
  }
3529
3578
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
3530
3579
  static supports(codec, config) {
3531
- return codec === "aac" || codec === "opus" || codec === "mp3" || codec === "vorbis" || codec === "flac" || codec === "ac3" || codec === "eac3" || codec === "dts";
3580
+ return codec === "aac" || codec === "opus" || codec === "mp3" || codec === "vorbis" || codec === "flac" || codec === "ac3" || codec === "eac3" || codec === "dts" || codec === "truehd";
3532
3581
  }
3533
3582
  async init() {
3534
3583
  this.frame = new NodeAv6.Frame();
@@ -3546,6 +3595,7 @@ var NodeAvAudioDecoder = class extends CustomAudioDecoder {
3546
3595
  codecContext.sampleRate = this.config.sampleRate;
3547
3596
  codecContext.channelLayout = getChannelLayout(this.config.numberOfChannels);
3548
3597
  codecContext.timeBase = new NodeAv6.Rational(1, this.config.sampleRate);
3598
+ codecContext.pktTimebase = new NodeAv6.Rational(1, this.config.sampleRate);
3549
3599
  codecContext.codecType = NodeAv6.AVMEDIA_TYPE_AUDIO;
3550
3600
  codecContext.codecId = codecId;
3551
3601
  codecContext.extraData = this.config.description ? Buffer.from(toUint8Array(this.config.description)) : null;
@@ -3636,8 +3686,6 @@ var NodeAvAudioEncoder = class extends CustomAudioEncoder {
3636
3686
  this.codecContext = null;
3637
3687
  this.resampler = null;
3638
3688
  this.dstFrame = null;
3639
- this.firstExpectedTimestamp = null;
3640
- this.outputTimestampOffset = 0;
3641
3689
  this.inputParametersKey = null;
3642
3690
  this.resamplerInputSampleRate = null;
3643
3691
  this.nextResamplerPts = null;
@@ -3646,7 +3694,7 @@ var NodeAvAudioEncoder = class extends CustomAudioEncoder {
3646
3694
  }
3647
3695
  static supports(codec, config) {
3648
3696
  const { numberOfChannels, sampleRate } = config;
3649
- 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);
3697
+ 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);
3650
3698
  }
3651
3699
  async init() {
3652
3700
  this.frame = new NodeAv7.Frame();
@@ -3667,11 +3715,19 @@ var NodeAvAudioEncoder = class extends CustomAudioEncoder {
3667
3715
  const codecContext = new NodeAv7.CodecContext();
3668
3716
  codecContext.allocContext3(this.avCodec);
3669
3717
  let sampleFormat = NodeAv7.AV_SAMPLE_FMT_FLTP;
3670
- if (this.avCodec.sampleFormats && !this.avCodec.sampleFormats.includes(NodeAv7.AV_SAMPLE_FMT_FLTP)) {
3718
+ if (this.codec === "truehd") {
3719
+ sampleFormat = NodeAv7.AV_SAMPLE_FMT_S32P;
3720
+ } else if (this.avCodec.sampleFormats && !this.avCodec.sampleFormats.includes(NodeAv7.AV_SAMPLE_FMT_FLTP)) {
3671
3721
  sampleFormat = this.avCodec.sampleFormats[0];
3672
3722
  }
3673
3723
  codecContext.sampleRate = this.config.sampleRate;
3674
- codecContext.channelLayout = this.codec === "dts" ? getDtsChannelLayout(this.config.numberOfChannels) : getChannelLayout(this.config.numberOfChannels);
3724
+ if (this.codec === "dts") {
3725
+ codecContext.channelLayout = getDtsChannelLayout(this.config.numberOfChannels);
3726
+ } else if (this.codec === "truehd") {
3727
+ codecContext.channelLayout = getTrueHdChannelLayout(this.config.numberOfChannels);
3728
+ } else {
3729
+ codecContext.channelLayout = getChannelLayout(this.config.numberOfChannels);
3730
+ }
3675
3731
  codecContext.codecType = NodeAv7.AVMEDIA_TYPE_AUDIO;
3676
3732
  codecContext.codecId = CODEC_TO_CODEC_ID[this.codec];
3677
3733
  codecContext.sampleFormat = sampleFormat;
@@ -3681,7 +3737,7 @@ var NodeAvAudioEncoder = class extends CustomAudioEncoder {
3681
3737
  codecContext.rcMinRate = codecContext.bitRate;
3682
3738
  codecContext.rcMaxRate = codecContext.bitRate;
3683
3739
  }
3684
- const options = this.codec === "dts" ? NodeAv7.Dictionary.fromObject({ strict: -2 }) : null;
3740
+ const options = this.codec === "dts" || this.codec === "truehd" ? NodeAv7.Dictionary.fromObject({ strict: -2 }) : null;
3685
3741
  const ret = await codecContext.open2(this.avCodec, options);
3686
3742
  NodeAv7.FFmpegError.throwIfError(ret, "Open codec context");
3687
3743
  this.codecContext = codecContext;
@@ -3691,7 +3747,6 @@ var NodeAvAudioEncoder = class extends CustomAudioEncoder {
3691
3747
  await this.createCodecContext();
3692
3748
  assert(this.codecContext);
3693
3749
  }
3694
- this.firstExpectedTimestamp ??= audioSample.timestamp;
3695
3750
  if (audioSample._data instanceof AvFrameAudioSampleResource) {
3696
3751
  this.frame.unref();
3697
3752
  this.frame.ref(audioSample._data.frame);
@@ -3777,19 +3832,17 @@ var NodeAvAudioEncoder = class extends CustomAudioEncoder {
3777
3832
  }
3778
3833
  receivePacket(ret) {
3779
3834
  assert(this.codecContext);
3780
- assert(this.firstExpectedTimestamp !== null);
3781
3835
  NodeAv7.FFmpegError.throwIfError(ret, "Receive packet");
3782
3836
  if (!this.packet.data) {
3783
3837
  return;
3784
3838
  }
3785
- let timestamp = Number(this.packet.pts) / this.codecContext.sampleRate;
3839
+ const timestamp = Number(this.packet.pts) / this.codecContext.sampleRate;
3786
3840
  const duration = Number(this.packet.duration) / this.codecContext.sampleRate;
3787
3841
  let data = this.packet.data;
3788
3842
  let metadata;
3789
3843
  if (this.packetEmitted) {
3790
3844
  metadata = {};
3791
3845
  } else {
3792
- this.outputTimestampOffset = Math.max(this.firstExpectedTimestamp - timestamp, 0);
3793
3846
  const codecString = this.config.codec;
3794
3847
  let description = this.codecContext.extraData ? toUint8Array(this.codecContext.extraData) : void 0;
3795
3848
  if (this.codec === "aac") {
@@ -3845,10 +3898,9 @@ var NodeAvAudioEncoder = class extends CustomAudioEncoder {
3845
3898
  final.set(data, this.adtsHeaderTemplate.header.byteLength);
3846
3899
  data = final;
3847
3900
  }
3848
- timestamp += this.outputTimestampOffset;
3849
3901
  const packet = new EncodedPacket4(
3850
3902
  data,
3851
- "key",
3903
+ determineAudioPacketType(this.codec, data),
3852
3904
  timestamp,
3853
3905
  duration
3854
3906
  );
@@ -3878,8 +3930,6 @@ var NodeAvAudioEncoder = class extends CustomAudioEncoder {
3878
3930
  this.codecContext.freeContext();
3879
3931
  this.codecContext = null;
3880
3932
  this.packetEmitted = false;
3881
- this.firstExpectedTimestamp = null;
3882
- this.outputTimestampOffset = 0;
3883
3933
  this.adtsHeaderTemplate = null;
3884
3934
  this.resampler?.free();
3885
3935
  this.resampler = null;
@@ -3901,16 +3951,204 @@ var resolveBitrate = (config, codec) => {
3901
3951
  return config.bitrate ?? new Quality2("medium")._toAudioBitrate(codec) ?? 0;
3902
3952
  };
3903
3953
 
3954
+ // packages/prores/src/index.ts
3955
+ import { CustomVideoDecoder as CustomVideoDecoder2, Logging as Logging2, registerDecoder, VideoSample as VideoSample4 } from "mediabunny";
3956
+ import { Decoder, Frame as Frame7, PIXEL_FORMATS } from "turbores";
3957
+ var PRORES_LOADED_SYMBOL = Symbol.for("@mediabunny/prores loaded");
3958
+ if (globalThis[PRORES_LOADED_SYMBOL]) {
3959
+ Logging2._error(
3960
+ "[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."
3961
+ );
3962
+ }
3963
+ globalThis[PRORES_LOADED_SYMBOL] = true;
3964
+ var _ProresDecoder = class _ProresDecoder extends CustomVideoDecoder2 {
3965
+ constructor() {
3966
+ super(...arguments);
3967
+ this.decoder = null;
3968
+ this.framePool = [];
3969
+ }
3970
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
3971
+ static supports(codec, config) {
3972
+ return codec === "prores";
3973
+ }
3974
+ /** @internal */
3975
+ static _determineSupportedVideoFrameFormats() {
3976
+ const result = [];
3977
+ const data = new Uint8Array(32);
3978
+ for (const format of PIXEL_FORMATS) {
3979
+ try {
3980
+ const frame = new VideoFrame(data, {
3981
+ format,
3982
+ codedWidth: 2,
3983
+ codedHeight: 2,
3984
+ timestamp: 0,
3985
+ duration: 0
3986
+ });
3987
+ frame.close();
3988
+ result.push(format);
3989
+ } catch {
3990
+ }
3991
+ }
3992
+ return result;
3993
+ }
3994
+ async init() {
3995
+ if (typeof VideoFrame !== "undefined") {
3996
+ _ProresDecoder._supportedVideoFrameFormats ??= _ProresDecoder._determineSupportedVideoFrameFormats();
3997
+ }
3998
+ const decoder = await Decoder.create({
3999
+ proresFourCc: this.config.codec,
4000
+ useSharedMemory: Decoder.canUseSharedMemory(),
4001
+ allowedOutputFormats: _ProresDecoder._supportedVideoFrameFormats ?? void 0
4002
+ });
4003
+ if (decoder instanceof Error) {
4004
+ throw decoder;
4005
+ }
4006
+ this.decoder = decoder;
4007
+ }
4008
+ async decode(packet) {
4009
+ assert(this.decoder);
4010
+ while (this.decoder.desiredSize <= 0) {
4011
+ await this.decoder.dequeued;
4012
+ }
4013
+ void this.runDecode(packet).catch((error) => this.onError(error));
4014
+ }
4015
+ async runDecode(packet) {
4016
+ assert(this.decoder);
4017
+ let frame;
4018
+ if (this.framePool.length > 0) {
4019
+ frame = this.framePool.shift();
4020
+ } else {
4021
+ frame = new Frame7();
4022
+ }
4023
+ const result = await this.decoder.decode(packet.data, frame);
4024
+ this.framePool.push(frame);
4025
+ if (result instanceof Error) {
4026
+ throw result;
4027
+ }
4028
+ if (result.visibleHeight < result.codedHeight && isWebKit()) {
4029
+ this.trimCodedHeightToVisibleHeight(result);
4030
+ }
4031
+ const colorSpaceInit = {
4032
+ primaries: result.colorPrimariesString,
4033
+ matrix: result.colorMatrixString,
4034
+ transfer: result.colorTransferString,
4035
+ fullRange: result.colorRangeFull
4036
+ };
4037
+ let displayWidth = result.visibleWidth;
4038
+ let displayHeight = result.visibleHeight;
4039
+ if (result.pixelAspectRatio.num > result.pixelAspectRatio.den) {
4040
+ displayWidth = Math.round(
4041
+ result.visibleWidth * result.pixelAspectRatio.num / result.pixelAspectRatio.den
4042
+ );
4043
+ } else {
4044
+ displayHeight = Math.round(
4045
+ result.visibleHeight * result.pixelAspectRatio.den / result.pixelAspectRatio.num
4046
+ );
4047
+ }
4048
+ let sample;
4049
+ if (typeof VideoFrame !== "undefined") {
4050
+ const frame2 = new VideoFrame(result.frameData, {
4051
+ format: result.pixelFormat,
4052
+ codedWidth: result.codedWidth,
4053
+ codedHeight: result.codedHeight,
4054
+ displayWidth,
4055
+ displayHeight,
4056
+ visibleRect: {
4057
+ x: 0,
4058
+ y: 0,
4059
+ width: result.visibleWidth,
4060
+ height: result.visibleHeight
4061
+ },
4062
+ timestamp: packet.microsecondTimestamp,
4063
+ duration: packet.microsecondDuration,
4064
+ colorSpace: colorSpaceInit
4065
+ });
4066
+ sample = new VideoSample4(frame2, {
4067
+ timestamp: packet.timestamp,
4068
+ duration: packet.duration
4069
+ });
4070
+ } else {
4071
+ sample = new VideoSample4(result.frameData, {
4072
+ format: result.pixelFormat,
4073
+ codedWidth: result.codedWidth,
4074
+ codedHeight: result.codedHeight,
4075
+ displayWidth,
4076
+ displayHeight,
4077
+ visibleRect: {
4078
+ left: 0,
4079
+ top: 0,
4080
+ width: result.visibleWidth,
4081
+ height: result.visibleHeight
4082
+ },
4083
+ timestamp: packet.timestamp,
4084
+ duration: packet.duration,
4085
+ colorSpace: colorSpaceInit
4086
+ });
4087
+ }
4088
+ this.onSample(sample);
4089
+ }
4090
+ trimCodedHeightToVisibleHeight(result) {
4091
+ const bytesPerSample = result.pixelFormat.includes("P") ? 2 : 1;
4092
+ const subWidth = result.pixelFormat.includes("444") ? 1 : 2;
4093
+ const subHeight = result.pixelFormat.includes("420") ? 2 : 1;
4094
+ const chromaCodedWidth = result.codedWidth / subWidth;
4095
+ const chromaCodedHeight = result.codedHeight / subHeight;
4096
+ const chromaVisibleHeight = Math.ceil(result.visibleHeight / subHeight);
4097
+ const lumaCodedPixels = result.codedWidth * result.codedHeight;
4098
+ const lumaVisiblePixels = result.codedWidth * result.visibleHeight;
4099
+ const chromaCodedPixels = chromaCodedWidth * chromaCodedHeight;
4100
+ const chromaVisiblePixels = chromaCodedWidth * chromaVisibleHeight;
4101
+ result.frameData.set(
4102
+ result.frameData.subarray(
4103
+ bytesPerSample * lumaCodedPixels,
4104
+ bytesPerSample * (lumaCodedPixels + chromaCodedPixels)
4105
+ ),
4106
+ bytesPerSample * lumaVisiblePixels
4107
+ );
4108
+ result.frameData.set(
4109
+ result.frameData.subarray(
4110
+ bytesPerSample * (lumaCodedPixels + chromaCodedPixels),
4111
+ bytesPerSample * (lumaCodedPixels + 2 * chromaCodedPixels)
4112
+ ),
4113
+ bytesPerSample * (lumaVisiblePixels + chromaVisiblePixels)
4114
+ );
4115
+ result.codedHeight = result.visibleHeight;
4116
+ }
4117
+ async flush() {
4118
+ assert(this.decoder);
4119
+ while (this.decoder.decodeQueueSize > 0) {
4120
+ await this.decoder.dequeued;
4121
+ }
4122
+ }
4123
+ async close() {
4124
+ assert(this.decoder);
4125
+ await this.decoder.close();
4126
+ for (const frame of this.framePool) {
4127
+ frame.clear();
4128
+ }
4129
+ }
4130
+ };
4131
+ /** @internal */
4132
+ _ProresDecoder._supportedVideoFrameFormats = null;
4133
+ var ProresDecoder = _ProresDecoder;
4134
+ var registered = false;
4135
+ var registerProresDecoder = () => {
4136
+ if (registered) {
4137
+ return;
4138
+ }
4139
+ registered = true;
4140
+ registerDecoder(ProresDecoder);
4141
+ };
4142
+
3904
4143
  // packages/server/src/index.ts
3905
- import { registerProresDecoder } from "@mediabunny/prores";
3906
4144
  var SERVER_LOADED_SYMBOL = Symbol.for("@mediabunny/server loaded");
3907
4145
  if (globalThis[SERVER_LOADED_SYMBOL]) {
3908
- Logging2._error(
4146
+ Logging3._error(
3909
4147
  "[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."
3910
4148
  );
3911
4149
  }
3912
4150
  globalThis[SERVER_LOADED_SYMBOL] = true;
3913
- var registered = false;
4151
+ var registered2 = false;
3914
4152
  var _serverOptions = {};
3915
4153
  var registerMediabunnyServer = (options = {}) => {
3916
4154
  if (typeof options !== "object" || !options) {
@@ -3921,27 +4159,27 @@ var registerMediabunnyServer = (options = {}) => {
3921
4159
  "options.hardwareContext, when provided, must be a NodeAv.HardwareContext, a function, or null."
3922
4160
  );
3923
4161
  }
3924
- if (registered) {
4162
+ if (registered2) {
3925
4163
  return;
3926
4164
  }
3927
- registered = true;
4165
+ registered2 = true;
3928
4166
  _serverOptions = options;
3929
4167
  NodeAv8.Log.setLevel(NodeAv8.AV_LOG_ERROR);
3930
- registerDecoder(NodeAvVideoDecoder);
4168
+ registerDecoder2(NodeAvVideoDecoder);
3931
4169
  registerProresDecoder();
3932
4170
  registerEncoder(NodeAvVideoEncoder);
3933
- registerDecoder(NodeAvAudioDecoder);
4171
+ registerDecoder2(NodeAvAudioDecoder);
3934
4172
  registerEncoder(NodeAvAudioEncoder);
3935
4173
  registerVideoSampleTransformer(transformVideoSample);
3936
4174
  };
3937
4175
  var toAvFrame = async (sample, frame) => {
3938
- if (!(sample instanceof VideoSample4) && !(sample instanceof AudioSample4)) {
4176
+ if (!(sample instanceof VideoSample5) && !(sample instanceof AudioSample4)) {
3939
4177
  throw new TypeError("sample must be a VideoSample or an AudioSample.");
3940
4178
  }
3941
4179
  if (!(frame instanceof NodeAv8.Frame)) {
3942
4180
  throw new TypeError("frame must be a NodeAv.Frame.");
3943
4181
  }
3944
- if (sample instanceof VideoSample4) {
4182
+ if (sample instanceof VideoSample5) {
3945
4183
  if (sample._data instanceof AvFrameVideoSampleResource) {
3946
4184
  frame.unref();
3947
4185
  frame.ref(sample._data.frame);
@@ -1 +1 @@
1
- {"version":3,"file":"audio-decoder.d.ts","sourceRoot":"","sources":["../../../src/audio-decoder.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,UAAU,EAAe,kBAAkB,EAAE,aAAa,EAAE,KAAK,YAAY,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O,CAAC,IAAI,CAAC;IAqB5B,KAAK,IAAI,YAAY,CAAC,IAAI,CAAC;CAK3B"}
@@ -60,7 +60,8 @@ class NodeAvAudioDecoder extends mediabunny_1.CustomAudioDecoder {
60
60
  || codec === 'flac'
61
61
  || codec === 'ac3'
62
62
  || codec === 'eac3'
63
- || codec === 'dts';
63
+ || codec === 'dts'
64
+ || codec === 'truehd';
64
65
  }
65
66
  async init() {
66
67
  this.frame = new NodeAv.Frame();
@@ -78,6 +79,8 @@ class NodeAvAudioDecoder extends mediabunny_1.CustomAudioDecoder {
78
79
  codecContext.sampleRate = this.config.sampleRate;
79
80
  codecContext.channelLayout = (0, misc_1.getChannelLayout)(this.config.numberOfChannels);
80
81
  codecContext.timeBase = new NodeAv.Rational(1, this.config.sampleRate);
82
+ // Without this, leading samples are discarded (like Opus pre-skip) without advancing the frame timestamp
83
+ codecContext.pktTimebase = new NodeAv.Rational(1, this.config.sampleRate);
81
84
  codecContext.codecType = NodeAv.AVMEDIA_TYPE_AUDIO;
82
85
  codecContext.codecId = codecId;
83
86
  codecContext.extraData = this.config.description
@@ -15,8 +15,6 @@ export declare class NodeAvAudioEncoder extends CustomAudioEncoder {
15
15
  resampler: NodeAv.SoftwareResampleContext | null;
16
16
  dstFrame: NodeAv.Frame | null;
17
17
  avCodec: NodeAv.Codec;
18
- firstExpectedTimestamp: number | null;
19
- outputTimestampOffset: number;
20
18
  inputParametersKey: string | null;
21
19
  resamplerInputSampleRate: number | null;
22
20
  nextResamplerPts: bigint | null;
@@ -1 +1 @@
1
- {"version":3,"file":"audio-encoder.d.ts","sourceRoot":"","sources":["../../../src/audio-encoder.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EACN,UAAU,EACV,WAAW,EACX,kBAAkB,EAClB,KAAK,YAAY,EAGjB,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,MAAM,MAAM,SAAS,CAAC;AAIlC,OAAO,EACN,kBAAkB,EAGlB,MAAM,0BAA0B,CA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O,KAAK,MAAM,MAAM,SAAS,CAAC;AAKlC,OAAO,EACN,kBAAkB,EAGlB,MAAM,0BAA0B,CAAC;AAYlC,qBAAa,kBAAmB,SAAQ,kBAAkB;IACzD,KAAK,EAAG,MAAM,CAAC,KAAK,CAAC;IACrB,MAAM,EAAG,MAAM,CAAC,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC,YAAY,GAAG,IAAI,CAAQ;IAChD,SAAS,EAAE,MAAM,CAAC,uBAAuB,GAAG,IAAI,CAAQ;IACxD,QAAQ,EAAE,MAAM,CAAC,KAAK,GAAG,IAAI,CAAQ;IACrC,OAAO,EAAG,MAAM,CAAC,KAAK,CAAC;IAEvB,kBAAkB,EAAE,MAAM,GAAG,IAAI,CAAQ;IACzC,wBAAwB,EAAE,MAAM,GAAG,IAAI,CAAQ;IAC/C,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAQ;IACvC,aAAa,UAAS;IACtB,kBAAkB,EAAE,kBAAkB,GAAG,IAAI,CAAQ;WAErC,QAAQ,CAAC,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,kBAAkB,GAAG,OAAO;IAkC1E,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAmBrB,kBAAkB;IA8ClB,MAAM,CAAC,WAAW,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IAiF/C,mBAAmB;IAuBnB,0BAA0B,CAAC,KAAK,EAAE,MAAM,CAAC,KAAK,GAAG,IAAI;IAgB3D,aAAa,CAAC,GAAG,EAAE,MAAM;IA8FnB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAyC5B,KAAK,IAAI,YAAY,CAAC,IAAI,CAAC;CAO3B"}
@@ -45,9 +45,11 @@ const mediabunny_1 = require("mediabunny");
45
45
  const NodeAv = __importStar(require("node-av"));
46
46
  const misc_1 = require("./misc");
47
47
  const misc_2 = require("../../../src/misc");
48
+ const codec_data_1 = require("../../../src/codec-data");
48
49
  const audio_sample_1 = require("./audio-sample");
49
50
  const aac_misc_1 = require("../../../shared/aac-misc");
50
51
  const dts_misc_1 = require("../../../shared/dts-misc");
52
+ const truehd_misc_1 = require("../../../shared/truehd-misc");
51
53
  const AAC_SAMPLE_RATES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
52
54
  const OPUS_SAMPLE_RATES = [8000, 12000, 16000, 24000, 48000];
53
55
  const MP3_SAMPLE_RATES = [8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000];
@@ -59,8 +61,6 @@ class NodeAvAudioEncoder extends mediabunny_1.CustomAudioEncoder {
59
61
  this.codecContext = null;
60
62
  this.resampler = null;
61
63
  this.dstFrame = null;
62
- this.firstExpectedTimestamp = null;
63
- this.outputTimestampOffset = 0;
64
64
  this.inputParametersKey = null;
65
65
  this.resamplerInputSampleRate = null;
66
66
  this.nextResamplerPts = null;
@@ -78,7 +78,8 @@ class NodeAvAudioEncoder extends mediabunny_1.CustomAudioEncoder {
78
78
  && AC3_SAMPLE_RATES.includes(sampleRate)) || (codec === 'eac3' && numberOfChannels >= 1 && numberOfChannels <= 16
79
79
  && AC3_SAMPLE_RATES.includes(sampleRate)) || (codec === 'dts' && dts_misc_1.DTS_CHANNEL_COUNTS.includes(numberOfChannels)
80
80
  && dts_misc_1.DTS_SAMPLE_RATES.includes(sampleRate)
81
- && (0, dts_misc_1.dtsBitrateFits)(resolveBitrate(config, codec), sampleRate, numberOfChannels));
81
+ && (0, dts_misc_1.dtsBitrateFits)(resolveBitrate(config, codec), sampleRate, numberOfChannels)) || (codec === 'truehd' && truehd_misc_1.TRUEHD_CHANNEL_COUNTS.includes(numberOfChannels)
82
+ && truehd_misc_1.TRUEHD_SAMPLE_RATES.includes(sampleRate));
82
83
  }
83
84
  async init() {
84
85
  this.frame = new NodeAv.Frame();
@@ -99,14 +100,24 @@ class NodeAvAudioEncoder extends mediabunny_1.CustomAudioEncoder {
99
100
  const codecContext = new NodeAv.CodecContext();
100
101
  codecContext.allocContext3(this.avCodec);
101
102
  let sampleFormat = NodeAv.AV_SAMPLE_FMT_FLTP;
102
- if (this.avCodec.sampleFormats && !this.avCodec.sampleFormats.includes(NodeAv.AV_SAMPLE_FMT_FLTP)) {
103
+ if (this.codec === 'truehd') {
104
+ // The first listed format is 16-bit, which would needlessly truncate what's supposed to be lossless
105
+ sampleFormat = NodeAv.AV_SAMPLE_FMT_S32P;
106
+ }
107
+ else if (this.avCodec.sampleFormats && !this.avCodec.sampleFormats.includes(NodeAv.AV_SAMPLE_FMT_FLTP)) {
103
108
  // Use a format that's supported
104
109
  sampleFormat = this.avCodec.sampleFormats[0];
105
110
  }
106
111
  codecContext.sampleRate = this.config.sampleRate;
107
- codecContext.channelLayout = this.codec === 'dts'
108
- ? (0, misc_1.getDtsChannelLayout)(this.config.numberOfChannels)
109
- : (0, misc_1.getChannelLayout)(this.config.numberOfChannels);
112
+ if (this.codec === 'dts') {
113
+ codecContext.channelLayout = (0, misc_1.getDtsChannelLayout)(this.config.numberOfChannels);
114
+ }
115
+ else if (this.codec === 'truehd') {
116
+ codecContext.channelLayout = (0, misc_1.getTrueHdChannelLayout)(this.config.numberOfChannels);
117
+ }
118
+ else {
119
+ codecContext.channelLayout = (0, misc_1.getChannelLayout)(this.config.numberOfChannels);
120
+ }
110
121
  codecContext.codecType = NodeAv.AVMEDIA_TYPE_AUDIO;
111
122
  codecContext.codecId = misc_1.CODEC_TO_CODEC_ID[this.codec];
112
123
  codecContext.sampleFormat = sampleFormat;
@@ -116,8 +127,9 @@ class NodeAvAudioEncoder extends mediabunny_1.CustomAudioEncoder {
116
127
  codecContext.rcMinRate = codecContext.bitRate;
117
128
  codecContext.rcMaxRate = codecContext.bitRate;
118
129
  }
119
- // libav's DTS encoder is marked experimental, so it refuses to open at the default compliance level
120
- const options = this.codec === 'dts'
130
+ // libav's DTS and TrueHD encoders are marked experimental, so they refuse to open at the default compliance
131
+ // level
132
+ const options = this.codec === 'dts' || this.codec === 'truehd'
121
133
  ? NodeAv.Dictionary.fromObject({ strict: -2 })
122
134
  : null;
123
135
  const ret = await codecContext.open2(this.avCodec, options);
@@ -129,7 +141,6 @@ class NodeAvAudioEncoder extends mediabunny_1.CustomAudioEncoder {
129
141
  await this.createCodecContext();
130
142
  (0, misc_2.assert)(this.codecContext);
131
143
  }
132
- this.firstExpectedTimestamp ??= audioSample.timestamp;
133
144
  if (audioSample._data instanceof audio_sample_1.AvFrameAudioSampleResource) {
134
145
  // Release any buffers still referenced from the previous encode before reffing the new frame, otherwise
135
146
  // av_frame_ref leaks them
@@ -220,12 +231,11 @@ class NodeAvAudioEncoder extends mediabunny_1.CustomAudioEncoder {
220
231
  }
221
232
  receivePacket(ret) {
222
233
  (0, misc_2.assert)(this.codecContext);
223
- (0, misc_2.assert)(this.firstExpectedTimestamp !== null);
224
234
  NodeAv.FFmpegError.throwIfError(ret, 'Receive packet');
225
235
  if (!this.packet.data) {
226
236
  return;
227
237
  }
228
- let timestamp = Number(this.packet.pts) / this.codecContext.sampleRate;
238
+ const timestamp = Number(this.packet.pts) / this.codecContext.sampleRate;
229
239
  const duration = Number(this.packet.duration) / this.codecContext.sampleRate;
230
240
  let data = this.packet.data;
231
241
  let metadata;
@@ -233,10 +243,6 @@ class NodeAvAudioEncoder extends mediabunny_1.CustomAudioEncoder {
233
243
  metadata = {};
234
244
  }
235
245
  else {
236
- // To compensate for any negative timestamp things that FFmpeg might do. It does these for a reason, to
237
- // indicate encoder delay, but the notion of this is not yet supported in Mediabunny. Yes, this technically
238
- // introduces audio sync drift.
239
- this.outputTimestampOffset = Math.max(this.firstExpectedTimestamp - timestamp, 0);
240
246
  const codecString = this.config.codec;
241
247
  let description = this.codecContext.extraData
242
248
  ? (0, misc_2.toUint8Array)(this.codecContext.extraData)
@@ -297,8 +303,7 @@ class NodeAvAudioEncoder extends mediabunny_1.CustomAudioEncoder {
297
303
  final.set(data, this.adtsHeaderTemplate.header.byteLength);
298
304
  data = final;
299
305
  }
300
- timestamp += this.outputTimestampOffset;
301
- const packet = new mediabunny_1.EncodedPacket(data, 'key', timestamp, duration);
306
+ const packet = new mediabunny_1.EncodedPacket(data, (0, codec_data_1.determineAudioPacketType)(this.codec, data), timestamp, duration);
302
307
  this.packetEmitted = true;
303
308
  this.onPacket(packet, metadata);
304
309
  }
@@ -322,8 +327,6 @@ class NodeAvAudioEncoder extends mediabunny_1.CustomAudioEncoder {
322
327
  this.codecContext.freeContext();
323
328
  this.codecContext = null;
324
329
  this.packetEmitted = false;
325
- this.firstExpectedTimestamp = null;
326
- this.outputTimestampOffset = 0;
327
330
  this.adtsHeaderTemplate = null;
328
331
  this.resampler?.free();
329
332
  this.resampler = null;
@@ -28,4 +28,6 @@ export declare const getChannelLayout: (numChannels: number) => NodeAv.ChannelLa
28
28
  * hands out, so it gets its own mapping.
29
29
  */
30
30
  export declare const getDtsChannelLayout: (numChannels: number) => NodeAv.ChannelLayout;
31
+ /** The TrueHD encoder only accepts a fixed set of layouts, so it gets its own mapping. */
32
+ export declare const getTrueHdChannelLayout: (numChannels: number) => NodeAv.ChannelLayout;
31
33
  //# sourceMappingURL=misc.d.ts.map