Skip to content

Open source CapCut alternative.

TypeScript

fix(site): keep MP3 and proxy audio on picture [rebuild]

David Le921f5629b471
diff --git a/site/patches/mediabunny+1.61.0.patch b/site/patches/mediabunny+1.61.0.patch
index aa7989ba..d36f5962 100644
--- a/site/patches/mediabunny+1.61.0.patch
+++ b/site/patches/mediabunny+1.61.0.patch
@@ -1,8 +1,30 @@
diff --git a/node_modules/mediabunny/dist/bundles/mediabunny.cjs b/node_modules/mediabunny/dist/bundles/mediabunny.cjs
-index f984c84..39c0530 100644
+index f984c84..9c9d93a 100644
--- a/node_modules/mediabunny/dist/bundles/mediabunny.cjs
+++ b/node_modules/mediabunny/dist/bundles/mediabunny.cjs
-@@ -24644,11 +24644,13 @@ var Mediabunny = (() => {
+@@ -12381,6 +12381,21 @@ var Mediabunny = (() => {
+ frameCount: flags & 1 /* FrameCount */ ? view2.getUint32(4, false) : null,
+ fileSize: flags & 2 /* FileSize */ ? view2.getUint32(8, false) : null
+ };
++ // Gapless start (Donkey patch): the LAME/Lavc tag after the Xing fields
++ // holds the encoder delay, and the decoder adds 529 samples of priming on
++ // top. The audio starts after both, as ffmpeg plays it, so the first
++ // frames carry negative timestamps.
++ const tagAt = result.startPos + xingOffset + 8 + (flags & 1 ? 4 : 0) + (flags & 2 ? 4 : 0) + (flags & 4 ? 100 : 0) + (flags & 8 ? 4 : 0);
++ let tagSlice = this.reader.requestSlice(tagAt, 24);
++ if (isThenable(tagSlice)) tagSlice = await tagSlice;
++ if (tagSlice && this.nextTimestampInSamples === 0) {
++ const tag = readBytes(tagSlice, 24);
++ const id = String.fromCharCode(tag[0], tag[1], tag[2], tag[3]);
++ if (id === "LAME" || id === "Lavf" || id === "Lavc") {
++ const delay = (tag[21] << 4) | (tag[22] >> 4);
++ this.nextTimestampInSamples = -(delay + 529);
++ }
++ }
+ }
+ }
+ return;
+@@ -24644,11 +24659,13 @@ var Mediabunny = (() => {
}
};
var computeMaxQueueSize = (decodedSampleQueueSize) => {
@@ -18,7 +40,7 @@ index f984c84..39c0530 100644
this.codec = codec;
this.decoderConfig = decoderConfig;
this.rotation = rotation;
-@@ -24658,6 +24660,13 @@ var Mediabunny = (() => {
+@@ -24658,6 +24675,13 @@ var Mediabunny = (() => {
this.customDecoder = null;
this.customDecoderCallSerializer = new CallSerializer();
this.customDecoderQueueSize = 0;
@@ -32,7 +54,7 @@ index f984c84..39c0530 100644
this.inputTimestamps = [];
// Timestamps input into the decoder, sorted.
this.sampleQueue = [];
-@@ -24689,6 +24698,17 @@ var Mediabunny = (() => {
+@@ -24689,6 +24713,17 @@ var Mediabunny = (() => {
if (!(sample instanceof VideoSample)) {
throw new TypeError("The argument passed to onSample must be a VideoSample.");
}
@@ -50,7 +72,7 @@ index f984c84..39c0530 100644
this.finalizeAndEmitSample(sample);
};
this.customDecoder.onError = (error) => {
-@@ -24744,6 +24764,7 @@ var Mediabunny = (() => {
+@@ -24744,6 +24779,7 @@ var Mediabunny = (() => {
const stack = new Error("Decoding error").stack;
this.decoder = new VideoDecoder({
output: (frame) => {
@@ -58,7 +80,7 @@ index f984c84..39c0530 100644
try {
colorHandler(frame);
} catch (error) {
-@@ -24760,13 +24781,10 @@ var Mediabunny = (() => {
+@@ -24760,13 +24796,10 @@ var Mediabunny = (() => {
}
getDecodeQueueSize() {
if (this.customDecoder) {
@@ -74,7 +96,7 @@ index f984c84..39c0530 100644
}
}
decode(packet) {
-@@ -24824,6 +24842,13 @@ var Mediabunny = (() => {
+@@ -24824,6 +24857,13 @@ var Mediabunny = (() => {
}
}
}
@@ -88,7 +110,7 @@ index f984c84..39c0530 100644
this.decoder.decode(packet.toEncodedVideoChunk());
this.decodeAlphaData(packet);
}
-@@ -24940,6 +24965,49 @@ var Mediabunny = (() => {
+@@ -24940,6 +24980,49 @@ var Mediabunny = (() => {
sample.setFlip(this.flip);
this.onSample(sample);
}
@@ -138,7 +160,7 @@ index f984c84..39c0530 100644
async mergeAlpha(color, alpha) {
const resolver = promiseWithResolvers();
this.mergeAlphaPromises.push(resolver.promise);
-@@ -24968,6 +25036,11 @@ var Mediabunny = (() => {
+@@ -24968,6 +25051,11 @@ var Mediabunny = (() => {
async flush() {
if (this.customDecoder) {
await this.customDecoderCallSerializer.call(() => this.customDecoder.flush());
@@ -150,7 +172,7 @@ index f984c84..39c0530 100644
} else {
assert(this.decoder);
await Promise.all([
-@@ -24992,6 +25065,7 @@ var Mediabunny = (() => {
+@@ -24992,6 +25080,7 @@ var Mediabunny = (() => {
}
this.sampleQueue.length = 0;
}
@@ -158,7 +180,7 @@ index f984c84..39c0530 100644
this.currentPacketIndex = 0;
this.raslSkipped = false;
}
-@@ -25248,6 +25322,18 @@ var Mediabunny = (() => {
+@@ -25248,6 +25337,18 @@ var Mediabunny = (() => {
if (decoderOptions.optimizeForLatency !== void 0 && typeof decoderOptions.optimizeForLatency !== "boolean") {
throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.");
}
@@ -177,7 +199,7 @@ index f984c84..39c0530 100644
};
var VideoSampleSink = class extends BaseMediaSampleSink {
/** Creates a new {@link VideoSampleSink} for the given {@link InputVideoTrack}. */
-@@ -25276,12 +25362,19 @@ var Mediabunny = (() => {
+@@ -25276,12 +25377,19 @@ var Mediabunny = (() => {
let decoderConfig = await this._track.getDecoderConfig();
const timeResolution = await this._track.getTimeResolution();
assert(codec && decoderConfig);
@@ -200,10 +222,32 @@ index f984c84..39c0530 100644
/** @internal */
_createPacketSink() {
diff --git a/node_modules/mediabunny/dist/bundles/mediabunny.mjs b/node_modules/mediabunny/dist/bundles/mediabunny.mjs
-index e675b1f..fc4477d 100644
+index e675b1f..5a114ed 100644
--- a/node_modules/mediabunny/dist/bundles/mediabunny.mjs
+++ b/node_modules/mediabunny/dist/bundles/mediabunny.mjs
-@@ -24487,11 +24487,13 @@ var BaseMediaSampleSink = class {
+@@ -12224,6 +12224,21 @@ var Mp3Demuxer = class extends Demuxer {
+ frameCount: flags & 1 /* FrameCount */ ? view2.getUint32(4, false) : null,
+ fileSize: flags & 2 /* FileSize */ ? view2.getUint32(8, false) : null
+ };
++ // Gapless start (Donkey patch): the LAME/Lavc tag after the Xing fields
++ // holds the encoder delay, and the decoder adds 529 samples of priming on
++ // top. The audio starts after both, as ffmpeg plays it, so the first
++ // frames carry negative timestamps.
++ const tagAt = result.startPos + xingOffset + 8 + (flags & 1 ? 4 : 0) + (flags & 2 ? 4 : 0) + (flags & 4 ? 100 : 0) + (flags & 8 ? 4 : 0);
++ let tagSlice = this.reader.requestSlice(tagAt, 24);
++ if (isThenable(tagSlice)) tagSlice = await tagSlice;
++ if (tagSlice && this.nextTimestampInSamples === 0) {
++ const tag = readBytes(tagSlice, 24);
++ const id = String.fromCharCode(tag[0], tag[1], tag[2], tag[3]);
++ if (id === "LAME" || id === "Lavf" || id === "Lavc") {
++ const delay = (tag[21] << 4) | (tag[22] >> 4);
++ this.nextTimestampInSamples = -(delay + 529);
++ }
++ }
+ }
+ }
+ return;
+@@ -24487,11 +24502,13 @@ var BaseMediaSampleSink = class {
}
};
var computeMaxQueueSize = (decodedSampleQueueSize) => {
@@ -219,7 +263,7 @@ index e675b1f..fc4477d 100644
this.codec = codec;
this.decoderConfig = decoderConfig;
this.rotation = rotation;
-@@ -24501,6 +24503,13 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
+@@ -24501,6 +24518,13 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
this.customDecoder = null;
this.customDecoderCallSerializer = new CallSerializer();
this.customDecoderQueueSize = 0;
@@ -233,7 +277,7 @@ index e675b1f..fc4477d 100644
this.inputTimestamps = [];
// Timestamps input into the decoder, sorted.
this.sampleQueue = [];
-@@ -24532,6 +24541,17 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
+@@ -24532,6 +24556,17 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
if (!(sample instanceof VideoSample)) {
throw new TypeError("The argument passed to onSample must be a VideoSample.");
}
@@ -251,7 +295,7 @@ index e675b1f..fc4477d 100644
this.finalizeAndEmitSample(sample);
};
this.customDecoder.onError = (error) => {
-@@ -24587,6 +24607,7 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
+@@ -24587,6 +24622,7 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
const stack = new Error("Decoding error").stack;
this.decoder = new VideoDecoder({
output: (frame) => {
@@ -259,7 +303,7 @@ index e675b1f..fc4477d 100644
try {
colorHandler(frame);
} catch (error) {
-@@ -24603,13 +24624,10 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
+@@ -24603,13 +24639,10 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
}
getDecodeQueueSize() {
if (this.customDecoder) {
@@ -275,7 +319,7 @@ index e675b1f..fc4477d 100644
}
}
decode(packet) {
-@@ -24667,6 +24685,13 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
+@@ -24667,6 +24700,13 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
}
}
}
@@ -289,7 +333,7 @@ index e675b1f..fc4477d 100644
this.decoder.decode(packet.toEncodedVideoChunk());
this.decodeAlphaData(packet);
}
-@@ -24783,6 +24808,49 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
+@@ -24783,6 +24823,49 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
sample.setFlip(this.flip);
this.onSample(sample);
}
@@ -339,7 +383,7 @@ index e675b1f..fc4477d 100644
async mergeAlpha(color, alpha) {
const resolver = promiseWithResolvers();
this.mergeAlphaPromises.push(resolver.promise);
-@@ -24811,6 +24879,11 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
+@@ -24811,6 +24894,11 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
async flush() {
if (this.customDecoder) {
await this.customDecoderCallSerializer.call(() => this.customDecoder.flush());
@@ -351,7 +395,7 @@ index e675b1f..fc4477d 100644
} else {
assert(this.decoder);
await Promise.all([
-@@ -24835,6 +24908,7 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
+@@ -24835,6 +24923,7 @@ var VideoDecoderWrapper = class extends DecoderWrapper {
}
this.sampleQueue.length = 0;
}
@@ -359,7 +403,7 @@ index e675b1f..fc4477d 100644
this.currentPacketIndex = 0;
this.raslSkipped = false;
}
-@@ -25091,6 +25165,18 @@ var validateVideoSinkDecoderOptions = (decoderOptions) => {
+@@ -25091,6 +25180,18 @@ var validateVideoSinkDecoderOptions = (decoderOptions) => {
if (decoderOptions.optimizeForLatency !== void 0 && typeof decoderOptions.optimizeForLatency !== "boolean") {
throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.");
}
@@ -378,7 +422,7 @@ index e675b1f..fc4477d 100644
};
var VideoSampleSink = class extends BaseMediaSampleSink {
/** Creates a new {@link VideoSampleSink} for the given {@link InputVideoTrack}. */
-@@ -25119,12 +25205,19 @@ var VideoSampleSink = class extends BaseMediaSampleSink {
+@@ -25119,12 +25220,19 @@ var VideoSampleSink = class extends BaseMediaSampleSink {
let decoderConfig = await this._track.getDecoderConfig();
const timeResolution = await this._track.getTimeResolution();
assert(codec && decoderConfig);
@@ -401,10 +445,32 @@ index e675b1f..fc4477d 100644
/** @internal */
_createPacketSink() {
diff --git a/node_modules/mediabunny/dist/bundles/mediabunny.node.cjs b/node_modules/mediabunny/dist/bundles/mediabunny.node.cjs
-index c828e19..ecf530c 100644
+index c828e19..d0af8d1 100644
--- a/node_modules/mediabunny/dist/bundles/mediabunny.node.cjs
+++ b/node_modules/mediabunny/dist/bundles/mediabunny.node.cjs
-@@ -24650,8 +24650,10 @@ var Mediabunny = (() => {
+@@ -12378,6 +12378,21 @@ var Mediabunny = (() => {
+ frameCount: flags & 1 /* FrameCount */ ? view2.getUint32(4, false) : null,
+ fileSize: flags & 2 /* FileSize */ ? view2.getUint32(8, false) : null
+ };
++ // Gapless start (Donkey patch): the LAME/Lavc tag after the Xing fields
++ // holds the encoder delay, and the decoder adds 529 samples of priming on
++ // top. The audio starts after both, as ffmpeg plays it, so the first
++ // frames carry negative timestamps.
++ const tagAt = result.startPos + xingOffset + 8 + (flags & 1 ? 4 : 0) + (flags & 2 ? 4 : 0) + (flags & 4 ? 100 : 0) + (flags & 8 ? 4 : 0);
++ let tagSlice = this.reader.requestSlice(tagAt, 24);
++ if (isThenable(tagSlice)) tagSlice = await tagSlice;
++ if (tagSlice && this.nextTimestampInSamples === 0) {
++ const tag = readBytes(tagSlice, 24);
++ const id = String.fromCharCode(tag[0], tag[1], tag[2], tag[3]);
++ if (id === "LAME" || id === "Lavf" || id === "Lavc") {
++ const delay = (tag[21] << 4) | (tag[22] >> 4);
++ this.nextTimestampInSamples = -(delay + 529);
++ }
++ }
+ }
+ }
+ return;
+@@ -24650,8 +24665,10 @@ var Mediabunny = (() => {
return decodedSampleQueueSize === 0 ? 40 : 8;
};
var VideoDecoderWrapper = class extends DecoderWrapper {
@@ -416,7 +482,7 @@ index c828e19..ecf530c 100644
this.codec = codec;
this.decoderConfig = decoderConfig;
this.rotation = rotation;
-@@ -24661,6 +24663,12 @@ var Mediabunny = (() => {
+@@ -24661,6 +24678,12 @@ var Mediabunny = (() => {
this.customDecoder = null;
this.customDecoderCallSerializer = new CallSerializer();
this.customDecoderQueueSize = 0;
@@ -429,7 +495,7 @@ index c828e19..ecf530c 100644
this.inputTimestamps = [];
// Timestamps input into the decoder, sorted.
this.sampleQueue = [];
-@@ -24692,6 +24700,17 @@ var Mediabunny = (() => {
+@@ -24692,6 +24715,17 @@ var Mediabunny = (() => {
if (!(sample instanceof VideoSample)) {
throw new TypeError("The argument passed to onSample must be a VideoSample.");
}
@@ -447,7 +513,7 @@ index c828e19..ecf530c 100644
this.finalizeAndEmitSample(sample);
};
this.customDecoder.onError = (error) => {
-@@ -24763,7 +24782,7 @@ var Mediabunny = (() => {
+@@ -24763,7 +24797,7 @@ var Mediabunny = (() => {
}
getDecodeQueueSize() {
if (this.customDecoder) {
@@ -456,7 +522,7 @@ index c828e19..ecf530c 100644
} else {
assert(this.decoder);
return Math.max(
-@@ -24827,6 +24846,12 @@ var Mediabunny = (() => {
+@@ -24827,6 +24861,12 @@ var Mediabunny = (() => {
}
}
}
@@ -469,7 +535,7 @@ index c828e19..ecf530c 100644
this.decoder.decode(packet.toEncodedVideoChunk());
this.decodeAlphaData(packet);
}
-@@ -24943,6 +24968,49 @@ var Mediabunny = (() => {
+@@ -24943,6 +24983,49 @@ var Mediabunny = (() => {
sample.setFlip(this.flip);
this.onSample(sample);
}
@@ -519,7 +585,7 @@ index c828e19..ecf530c 100644
async mergeAlpha(color, alpha) {
const resolver = promiseWithResolvers();
this.mergeAlphaPromises.push(resolver.promise);
-@@ -24971,6 +25039,11 @@ var Mediabunny = (() => {
+@@ -24971,6 +25054,11 @@ var Mediabunny = (() => {
async flush() {
if (this.customDecoder) {
await this.customDecoderCallSerializer.call(() => this.customDecoder.flush());
@@ -531,7 +597,7 @@ index c828e19..ecf530c 100644
} else {
assert(this.decoder);
await Promise.all([
-@@ -25251,6 +25324,18 @@ var Mediabunny = (() => {
+@@ -25251,6 +25339,18 @@ var Mediabunny = (() => {
if (decoderOptions.optimizeForLatency !== void 0 && typeof decoderOptions.optimizeForLatency !== "boolean") {
throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.");
}
@@ -550,7 +616,7 @@ index c828e19..ecf530c 100644
};
var VideoSampleSink = class extends BaseMediaSampleSink {
/** Creates a new {@link VideoSampleSink} for the given {@link InputVideoTrack}. */
-@@ -25279,12 +25364,19 @@ var Mediabunny = (() => {
+@@ -25279,12 +25379,19 @@ var Mediabunny = (() => {
let decoderConfig = await this._track.getDecoderConfig();
const timeResolution = await this._track.getTimeResolution();
assert(codec && decoderConfig);
@@ -841,3 +907,29 @@ index 9465e3b..4af78f2 100644
}
/** @internal */
_createPacketSink() {
+diff --git a/node_modules/mediabunny/dist/modules/src/mp3/mp3-demuxer.js b/node_modules/mediabunny/dist/modules/src/mp3/mp3-demuxer.js
+index a7b3aa6..7cd67f4 100644
+--- a/node_modules/mediabunny/dist/modules/src/mp3/mp3-demuxer.js
++++ b/node_modules/mediabunny/dist/modules/src/mp3/mp3-demuxer.js
+@@ -103,6 +103,21 @@ export class Mp3Demuxer extends Demuxer {
+ ? view.getUint32(8, false)
+ : null,
+ };
++ // Gapless start (Donkey patch): the LAME/Lavc tag after the Xing fields
++ // holds the encoder delay, and the decoder adds 529 samples of priming on
++ // top. The audio starts after both, as ffmpeg plays it, so the first
++ // frames carry negative timestamps.
++ const tagAt = result.startPos + xingOffset + 8 + (flags & 1 ? 4 : 0) + (flags & 2 ? 4 : 0) + (flags & 4 ? 100 : 0) + (flags & 8 ? 4 : 0);
++ let tagSlice = this.reader.requestSlice(tagAt, 24);
++ if (isThenable(tagSlice)) tagSlice = await tagSlice;
++ if (tagSlice && this.nextTimestampInSamples === 0) {
++ const tag = readBytes(tagSlice, 24);
++ const id = String.fromCharCode(tag[0], tag[1], tag[2], tag[3]);
++ if (id === "LAME" || id === "Lavf" || id === "Lavc") {
++ const delay = (tag[21] << 4) | (tag[22] >> 4);
++ this.nextTimestampInSamples = -(delay + 529);
++ }
++ }
+ }
+ }
+ return;
diff --git a/site/scripts/check-mediabunny-patch.mjs b/site/scripts/check-mediabunny-patch.mjs
index abe464a5..99e1500e 100644
--- a/site/scripts/check-mediabunny-patch.mjs
+++ b/site/scripts/check-mediabunny-patch.mjs
@@ -1,7 +1,8 @@
// Runs in postinstall, after patch-package. The patch in patches/ bounds how
-// many decoded frames mediabunny's decode pump keeps in flight; it belongs to
-// one mediabunny version and retires when upstream carries the fix. A bump
-// stops the install here until someone has looked.
+// many decoded frames mediabunny's decode pump keeps in flight, and starts an
+// MP3's audio after the priming its LAME tag names; it belongs to one
+// mediabunny version and retires as upstream carries each fix. A bump stops
+// the install here until someone has looked.
import { readdirSync, readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
@@ -10,12 +11,13 @@ const site = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const patches = readdirSync(path.join(site, "patches")).filter((f) => /^mediabunny\+.*\.patch$/.test(f));
const installed = JSON.parse(readFileSync(path.join(site, "node_modules/mediabunny/package.json"), "utf8")).version;
const sink = readFileSync(path.join(site, "node_modules/mediabunny/dist/modules/src/media-sink.js"), "utf8");
+const mp3 = readFileSync(path.join(site, "node_modules/mediabunny/dist/modules/src/mp3/mp3-demuxer.js"), "utf8");
const patched = patches.map((f) => f.slice("mediabunny+".length, -".patch".length));
-if (patched.length === 1 && patched[0] === installed && sink.includes("this.inFlight++")) process.exit(0);
+if (patched.length === 1 && patched[0] === installed && sink.includes("this.inFlight++") && mp3.includes("delay + 529")) process.exit(0);
console.error(`
-mediabunny is ${installed}; the decode-pump patch in site/patches/ is for ${patched.join(", ") || "no version"}.
+mediabunny is ${installed}; the patch in site/patches/ is for ${patched.join(", ") || "no version"}.
Open node_modules/mediabunny/dist/modules/src/media-sink.js and read computeMaxQueueSize and
the pump loops that call getDecodeQueueSize().
@@ -25,5 +27,9 @@ the pump loops that call getDecodeQueueSize().
Upstream still throttles on decodeQueueSize with a 40-packet head start: re-apply the
patch's six edits to the module and both bundles, run \`npx patch-package mediabunny\`,
and commit the new patch file.
+
+Then open node_modules/mediabunny/dist/modules/src/mp3/mp3-demuxer.js. If it reads the
+encoder delay from the LAME tag, drop the patch's gapless block; if not, carry it over.
+src/cut/lib/mp3Gapless.test.ts says which.
`);
process.exit(1);
diff --git a/site/src/cut/lib/encoderLead.ts b/site/src/cut/lib/encoderLead.ts
new file mode 100644
index 00000000..fc307dd3
--- /dev/null
+++ b/site/src/cut/lib/encoderLead.ts
@@ -0,0 +1,80 @@
+/**
+ * How far an audio encoder's output runs behind its input.
+ *
+ * An AAC encoder opens its stream with priming — 2112 samples from the one
+ * this Mac's browser uses — and stamps that first packet 0, so the sound plays
+ * that much late against the picture unless the file says to skip it. A file
+ * says so with an edit list, and the muxer writes one when the audio starts
+ * before zero: start the track at minus the lead, and the edit list trims
+ * exactly the priming. The lead is the encoder's own, so it is measured here
+ * once per format — a click encoded and decoded back — rather than assumed.
+ */
+
+import {
+ AudioBufferSink,
+ AudioBufferSource,
+ BufferSource,
+ BufferTarget,
+ Input,
+ MP4,
+ Mp4OutputFormat,
+ Output,
+ type AudioCodec,
+} from "mediabunny";
+
+/** Where the probe's click sits, far enough in that any lead stays inside. */
+const PROBE_CLICK_S = 0.1;
+const PROBE_LENGTH_S = 0.4;
+
+const leads = new Map<string, Promise<number>>();
+
+/** Seconds the encoder's output trails its input; 0 for codecs with no
+ * priming. Measured once per codec, rate and channel count. */
+export function encoderLead(codec: AudioCodec, sampleRate: number, channels: number): Promise<number> {
+ if (codec.startsWith("pcm")) return Promise.resolve(0);
+ const key = `${codec}/${sampleRate}/${channels}`;
+ let lead = leads.get(key);
+ if (!lead) {
+ lead = measureLead(codec, sampleRate, channels);
+ // A probe that failed is asked again next time, not remembered.
+ lead.catch(() => leads.delete(key));
+ leads.set(key, lead);
+ }
+ return lead;
+}
+
+async function measureLead(codec: AudioCodec, sampleRate: number, channels: number): Promise<number> {
+ // One sample of click in silence, through the same encoder the export uses.
+ const length = Math.round(PROBE_LENGTH_S * sampleRate);
+ const at = Math.round(PROBE_CLICK_S * sampleRate);
+ const probe = new AudioBuffer({ length, numberOfChannels: channels, sampleRate });
+ for (let ch = 0; ch < channels; ch++) probe.getChannelData(ch)[at] = 0.9;
+
+ const target = new BufferTarget();
+ const output = new Output({ format: new Mp4OutputFormat(), target });
+ const source = new AudioBufferSource({ codec, bitrate: 192_000 });
+ output.addAudioTrack(source);
+ await output.start();
+ await source.add(probe);
+ await output.finalize();
+
+ // Decode it back and find where the click came out.
+ const input = new Input({ formats: [MP4], source: new BufferSource(target.buffer!) });
+ try {
+ const track = await input.getPrimaryAudioTrack();
+ if (!track) throw new Error("The encoder probe wrote no audio.");
+ let peak = 0;
+ let peakAt = 0;
+ for await (const { buffer, timestamp } of new AudioBufferSink(track).buffers()) {
+ const data = buffer.getChannelData(0);
+ for (let i = 0; i < data.length; i++) {
+ if (Math.abs(data[i]) <= peak) continue;
+ peak = Math.abs(data[i]);
+ peakAt = timestamp + i / buffer.sampleRate;
+ }
+ }
+ return Math.max(0, peakAt - at / sampleRate);
+ } finally {
+ input.dispose();
+ }
+}
diff --git a/site/src/cut/lib/fixtures/sine-quarter-second.mp3 b/site/src/cut/lib/fixtures/sine-quarter-second.mp3
new file mode 100644
index 00000000..59eb2731
Binary files /dev/null and b/site/src/cut/lib/fixtures/sine-quarter-second.mp3 differ
diff --git a/site/src/cut/lib/mediaProxy.ts b/site/src/cut/lib/mediaProxy.ts
index 925a9c97..08836e45 100644
--- a/site/src/cut/lib/mediaProxy.ts
+++ b/site/src/cut/lib/mediaProxy.ts
@@ -41,6 +41,7 @@ import { pollCloudJob } from "./cloudJob";
import { cutColor } from "./colorSettings";
import { uploadProjectMediaTo } from "./media";
import { audioTrackOf, frameSinkIsCustom, openMedia, probeMediaFile, videoTrackOf } from "./mediaRead";
+import { encoderLead } from "./encoderLead";
import { forgetLocalMediaUrl, storedMediaUrl } from "./mediaSync";
import { ensureProresDecoder } from "./proresDecoder";
import { convertPlanes, isPlanarFormat, planesPassThrough, proxySize } from "./proxyPlanes";
@@ -336,9 +337,13 @@ export async function proxyInPage(
}
}
if (audio && audioSource) {
+ // Each sample goes in early by the encoder's priming, so the edit list
+ // trims it and the proxy's sound stays on its picture.
+ const lead = await encoderLead("aac", await audio.getSampleRate(), await audio.getNumberOfChannels());
const sounds = new AudioSampleSink(audio);
for await (const sample of sounds.samples()) {
try {
+ sample.setTimestamp(sample.timestamp - lead);
await audioSource.add(sample);
} finally {
sample.close();
diff --git a/site/src/cut/lib/mp3Gapless.test.ts b/site/src/cut/lib/mp3Gapless.test.ts
new file mode 100644
index 00000000..9e543922
--- /dev/null
+++ b/site/src/cut/lib/mp3Gapless.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { BufferSource, EncodedPacketSink, Input, MP3 } from "mediabunny";
+
+// An MP3 opens with the encoder's delay plus the decoder's 529 samples of
+// filter priming, and the LAME/Lavc tag in its Info frame says how many. The
+// demuxer has to start the audio after them, the way ffmpeg does, or every MP3
+// (the whole stock sound library) plays late in the tab and early in the
+// engine's ffmpeg export. The fixture is 0.25 s of sine with delay 576.
+const FIXTURE = new URL("./fixtures/sine-quarter-second.mp3", import.meta.url);
+const RATE = 44_100;
+const SKIP_SAMPLES = 576 + 529;
+
+async function openFixture() {
+ const bytes = readFileSync(FIXTURE);
+ const input = new Input({ source: new BufferSource(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length)), formats: [MP3] });
+ const track = await input.getPrimaryAudioTrack();
+ if (!track) throw new Error("fixture has no audio");
+ return { input, track };
+}
+
+describe("mp3 gapless start", () => {
+ test("the first packet sits before zero by the tag's delay", async () => {
+ const { input, track } = await openFixture();
+ const first = await new EncodedPacketSink(track).getFirstPacket();
+ expect(first?.timestamp).toBeCloseTo(-SKIP_SAMPLES / RATE, 6);
+ input.dispose();
+ });
+
+ test("a packet looked up at zero is the one holding the first real sample", async () => {
+ const { input, track } = await openFixture();
+ const at = await new EncodedPacketSink(track).getPacket(0);
+ expect(at).not.toBeNull();
+ expect(at!.timestamp).toBeLessThanOrEqual(0);
+ expect(at!.timestamp + at!.duration).toBeGreaterThan(0);
+ input.dispose();
+ });
+});