Make sure that samples are always closed in the Conversion API, even on error cases

This commit is contained in:
Vanilagy
2026-07-18 22:54:24 +02:00
parent 45c34f9dcd
commit 794b84884f
3 changed files with 81 additions and 18 deletions
+17 -14
View File
@@ -1321,7 +1321,7 @@ export class Conversion {
await tempOutput.start();
const sink = new VideoSampleSink(track);
const firstSample = await sink.getSample(firstTimestamp); // Let's just use the first sample
using firstSample = await sink.getSample(firstTimestamp); // Let's just use the first sample
if (firstSample) {
try {
@@ -1375,9 +1375,8 @@ export class Conversion {
const sink = new VideoSampleSink(track);
for await (const sample of sink.samples(this._startTimestamp, this._endTimestamp)) {
for await (using sample of sink.samples(this._startTimestamp, this._endTimestamp)) {
if (this._canceled) {
sample.close();
return;
}
@@ -1386,14 +1385,13 @@ export class Conversion {
this._reportProgress(outputTrackId, sample.timestamp + sample.duration);
await source.add(sample);
sample.close();
if (lastSampleTimestamp !== null) {
if (this._synchronizer.shouldWait(outputTrackId, lastSampleTimestamp)) {
await this._synchronizer.wait(lastSampleTimestamp);
}
}
sample.close();
}
source.close();
@@ -1595,9 +1593,8 @@ export class Conversion {
await this._started;
const sink = new AudioSampleSink(track);
for await (let sample of sink.samples(this._startTimestamp, this._endTimestamp)) {
for await (using sample of sink.samples(this._startTimestamp, this._endTimestamp)) {
if (this._canceled) {
sample.close();
return;
}
@@ -1612,7 +1609,7 @@ export class Conversion {
data.fill(2 ** 7); // Fill it with the silent value
}
const silentSample = new AudioSample({
using silentSample = new AudioSample({
data,
// Use the same format the decoder is spitting out. This avoids feeding changing sample
// formats to the audio encoder.
@@ -1636,22 +1633,28 @@ export class Conversion {
endFrame = Math.round((this._endTimestamp - sample.timestamp) * sample.sampleRate);
}
// Can't assign to "using" identifiers so we gotta do this
let finalSampleLet: AudioSample;
if (startFrame > 0 || endFrame < sample.numberOfFrames) {
// Trim the sample if it sticks out of the trim region on either end
const trimmedSample = sample.trim(startFrame, endFrame);
sample.close();
sample = trimmedSample;
finalSampleLet = trimmedSample;
if (sample.numberOfFrames === 0) {
sample.close();
if (trimmedSample.numberOfFrames === 0) {
trimmedSample.close();
continue;
}
} else {
finalSampleLet = sample;
}
// Offset the timestamp as needed
sample.setTimestamp(sample.timestamp - this._startTimestamp);
using finalSample = finalSampleLet;
await this._registerAudioSample(sample, source, outputTrackId, () => lastSampleTimestamp);
// Offset the timestamp as needed
finalSample.setTimestamp(finalSample.timestamp - this._startTimestamp);
await this._registerAudioSample(finalSample, source, outputTrackId, () => lastSampleTimestamp);
}
source.close();