Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 111 additions & 18 deletions src/lib/exporter/audioMediaProcessor.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,29 @@
import { afterEach, expect, it, vi } from "vitest";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { AudioMediaProcessor } from "./audioMediaProcessor";
import { DECODE_BACKPRESSURE_LIMIT } from "./audioProcessorShared";

const packetCount = DECODE_BACKPRESSURE_LIMIT + 2;
const closeFrame = vi.fn();
const destroyDemuxer = vi.fn();

type DemuxedSource = {
packets: number;
firstPacketUs: number;
packetUs: number;
/** The audio streams getMediaInfo() lists, and the index of the one read("audio") decodes. */
streams: { index: number; codec_type_string: "audio"; start_time: number }[];
decoded: number;
};

const opusSource: DemuxedSource = {
packets: packetCount,
firstPacketUs: 0,
packetUs: 20_000,
streams: [{ index: 0, codec_type_string: "audio", start_time: 0 }],
decoded: 0,
};
let demuxed = opusSource;

vi.mock("web-demuxer", () => ({
WebDemuxer: class {
async load() {}
Expand All @@ -14,11 +32,21 @@ vi.mock("web-demuxer", () => ({
return { codec: "opus", numberOfChannels: 1, sampleRate: 48_000 };
}

async getMediaInfo() {
return { streams: demuxed.streams };
}

async getMediaStream() {
return demuxed.streams[demuxed.decoded];
}

read() {
return new ReadableStream({
start(controller) {
for (let index = 0; index < packetCount; index++) {
controller.enqueue({ timestamp: index * 20_000 });
for (let index = 0; index < demuxed.packets; index++) {
controller.enqueue({
timestamp: demuxed.firstPacketUs + index * demuxed.packetUs,
});
}
controller.close();
},
Expand All @@ -35,6 +63,18 @@ class TestAudioMediaProcessor extends AudioMediaProcessor {
streamDecode = this.streamDecodeFromUrl;
}

class TestAudioBuffer {
private readonly samples: Float32Array;

constructor({ length }: AudioBufferOptions) {
this.samples = new Float32Array(length);
}

getChannelData() {
return this.samples;
}
}

class BufferedAudioDecoder {
state: CodecState = "unconfigured";
decodeQueueSize = 0;
Expand Down Expand Up @@ -74,25 +114,54 @@ class BufferedAudioDecoder {
}
}

/** Decodes each packet into 1024 frames whose samples hold their frame number. */
class NumberedAudioDecoder {
state: CodecState = "unconfigured";
decodeQueueSize = 0;
ondequeue: (() => void) | null = null;
private decodedFrames = 0;

constructor(private readonly callbacks: AudioDecoderInit) {}

configure() {
this.state = "configured";
}

decode() {
const firstFrame = this.decodedFrames;
this.decodedFrames += 1024;
this.callbacks.output({
numberOfFrames: 1024,
numberOfChannels: 1,
format: "f32-planar",
allocationSize: () => 1024 * Float32Array.BYTES_PER_ELEMENT,
copyTo: (bytes: ArrayBuffer) => {
const samples = new Float32Array(bytes);
for (let frame = 0; frame < samples.length; frame++) {
samples[frame] = firstFrame + frame;
}
},
close: () => {},
} as unknown as AudioData);
}

async flush() {}

close() {
this.state = "closed";
}
}

beforeEach(() => {
demuxed = opusSource;
vi.stubGlobal("window", { location: { href: "https://recordly.example/editor" } });
vi.stubGlobal("AudioBuffer", TestAudioBuffer);
});

afterEach(() => vi.unstubAllGlobals());

it("drains the source audio decoder when input capacity changes before output", async () => {
vi.stubGlobal("window", { location: { href: "https://recordly.example/editor" } });
vi.stubGlobal("AudioDecoder", BufferedAudioDecoder);
vi.stubGlobal(
"AudioBuffer",
class {
private readonly samples: Float32Array;

constructor({ length }: AudioBufferOptions) {
this.samples = new Float32Array(length);
}

getChannelData() {
return this.samples;
}
},
);

const result = await new TestAudioMediaProcessor().streamDecode(
"https://recordly.example/source.opus",
Expand All @@ -102,3 +171,27 @@ it("drains the source audio decoder when input capacity changes before output",
expect(closeFrame).toHaveBeenCalledOnce();
expect(destroyDemuxer).toHaveBeenCalledOnce();
}, 1500);

it("trims AAC priming by the start of the track it decodes, not the first audio track", async () => {
// The first track starts 100 ms late. The second is the default, which read("audio")
// decodes, and its first packet holds the 1024 priming frames before 0.
demuxed = {
packets: 6,
firstPacketUs: -21_333,
packetUs: 21_333,
streams: [
{ index: 0, codec_type_string: "audio", start_time: 0.078 },
{ index: 1, codec_type_string: "audio", start_time: 0 },
],
decoded: 1,
};
vi.stubGlobal("AudioDecoder", NumberedAudioDecoder);

const result = await new TestAudioMediaProcessor().streamDecode(
"https://recordly.example/two-tracks.m4a",
);

const samples = result?.getChannelData(0);
expect(samples?.length).toBe(5 * 1024);
expect(samples?.[0]).toBe(1024);
});
33 changes: 27 additions & 6 deletions src/lib/exporter/audioMediaProcessor.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import type { WebDemuxer } from "web-demuxer";
import { DECODE_BACKPRESSURE_LIMIT, OFFLINE_AUDIO_SAMPLE_RATE } from "./audioProcessorShared";
import {
countPrimingFrames,
DECODE_BACKPRESSURE_LIMIT,
OFFLINE_AUDIO_SAMPLE_RATE,
} from "./audioProcessorShared";
import { AudioTimelineProcessor } from "./audioTimelineProcessor";
import { resolveMediaElementSource } from "./localMediaSource";
import { createWebDemuxer } from "./webDemuxerFactory";
Expand Down Expand Up @@ -39,6 +43,15 @@ export class AudioMediaProcessor extends AudioTimelineProcessor {

const sampleRate = audioConfig.sampleRate || 48_000;
const numChannels = Math.min(audioConfig.numberOfChannels || 2, 2);
// The start time of the stream read("audio") decodes. A file can hold several
// audio tracks, and the first one listed is not always the one decoded.
let streamStartTimeSec: number | undefined;
try {
streamStartTimeSec = (await demuxer.getMediaStream("audio")).start_time;
} catch {
streamStartTimeSec = undefined;
}
let firstChunkTimestampUs: number | null = null;

// Accumulate decoded PCM per channel
const channelChunks: Float32Array[][] = Array.from({ length: numChannels }, () => []);
Expand Down Expand Up @@ -130,6 +143,7 @@ export class AudioMediaProcessor extends AudioTimelineProcessor {
const { done, value: chunk } = await reader.read();
if (done || !chunk) break;

firstChunkTimestampUs ??= chunk.timestamp;
decoder.decode(chunk);

while (decoder.decodeQueueSize > DECODE_BACKPRESSURE_LIMIT && !this.cancelled) {
Expand All @@ -155,20 +169,27 @@ export class AudioMediaProcessor extends AudioTimelineProcessor {
}
}

if (totalFrames === 0) return null;
const primingFrames = Math.min(
totalFrames,
countPrimingFrames(streamStartTimeSec, firstChunkTimestampUs, sampleRate),
);
if (totalFrames - primingFrames === 0) return null;

// Build AudioBuffer from accumulated chunks
// Build AudioBuffer from accumulated chunks, without the priming frames
const audioBuffer = new AudioBuffer({
length: totalFrames,
length: totalFrames - primingFrames,
numberOfChannels: numChannels,
sampleRate,
});
for (let ch = 0; ch < numChannels; ch++) {
const channelData = audioBuffer.getChannelData(ch);
let framesToSkip = primingFrames;
let writeOffset = 0;
for (const chunk of channelChunks[ch]) {
channelData.set(chunk, writeOffset);
writeOffset += chunk.length;
const skipped = Math.min(framesToSkip, chunk.length);
framesToSkip -= skipped;
channelData.set(chunk.subarray(skipped), writeOffset);
writeOffset += chunk.length - skipped;
}
}

Expand Down
19 changes: 19 additions & 0 deletions src/lib/exporter/audioProcessorShared.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { describe, expect, it } from "vitest";
import { countPrimingFrames } from "./audioProcessorShared";

describe("countPrimingFrames", () => {
it("drops the AAC priming that an iTunSMPB tag puts before the start time", () => {
expect(countPrimingFrames(0.044, 0, 48_000)).toBe(2112);
});

it("drops the AAC priming that an edit list gives negative timestamps", () => {
expect(countPrimingFrames(0, -44_000, 48_000)).toBe(2112);
});

it("keeps everything when the stream starts at its first packet or is unknown", () => {
expect(countPrimingFrames(0, 0, 48_000)).toBe(0);
expect(countPrimingFrames(2.5, 2_500_000, 48_000)).toBe(0);
expect(countPrimingFrames(undefined, 0, 48_000)).toBe(0);
expect(countPrimingFrames(0.044, null, 48_000)).toBe(0);
});
});
24 changes: 24 additions & 0 deletions src/lib/exporter/audioProcessorShared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,30 @@ export function resolveAudioTimestampOffsetUs(firstChunkTimestampUs: number): nu
return 0;
}

/**
* Counts the frames a decoder emits before a stream's first presented sample. AAC
* starts with encoder priming, which containers place before the stream's start
* time: an edit list gives the first packets negative timestamps, and an iTunSMPB
* tag moves the start time later. Kept, it delays the audio by about 44 ms.
*/
export function countPrimingFrames(
streamStartTimeSec: number | undefined,
firstChunkTimestampUs: number | null,
sampleRate: number,
): number {
if (
typeof streamStartTimeSec !== "number" ||
!Number.isFinite(streamStartTimeSec) ||
firstChunkTimestampUs === null
) {
return 0;
}
return Math.max(
0,
Math.round((streamStartTimeSec - firstChunkTimestampUs / 1_000_000) * sampleRate),
);
}

const OFFLINE_MIX_SOFT_LIMITER_THRESHOLD = 0.9;
const OFFLINE_MIX_SOFT_LIMITER_CEILING = 0.985;

Expand Down
Loading