Skip to content

🎥 Make videos programmatically with React

not race condition prone anymore

Jonny Burger1e5375a103c4
diff --git a/packages/media/src/audio-extraction/audio-cache.ts b/packages/media/src/audio-extraction/audio-cache.ts
index 17c3ebbc72..dc80599ed4 100644
--- a/packages/media/src/audio-extraction/audio-cache.ts
+++ b/packages/media/src/audio-extraction/audio-cache.ts
@@ -14,6 +14,7 @@ export const makeAudioCache = () => {
const endTimestamp = timestamp + samples[timestamp].duration;
if (endTimestamp < threshold) {
+ samples[timestamp].close();
delete samples[timestamp];
timestamps.splice(timestamps.indexOf(timestamp), 1);
}
@@ -28,10 +29,47 @@ export const makeAudioCache = () => {
timestamps.length = 0;
};
+ const getSamples = (timestamp: number, durationInSeconds: number) => {
+ const selected: AudioSample[] = [];
+ for (let i = 0; i < timestamps.length; i++) {
+ const sampleTimestamp = timestamps[i];
+ const sample = samples[sampleTimestamp];
+
+ if (sample.timestamp + sample.duration - 0.0000000001 <= timestamp) {
+ continue;
+ }
+
+ if (sample.timestamp >= timestamp + durationInSeconds - 0.0000000001) {
+ break;
+ }
+
+ selected.push(sample);
+ }
+
+ return selected;
+ };
+
+ const getOpenTimestamps = () => {
+ return timestamps;
+ };
+
+ const getOldestTimestamp = () => {
+ return timestamps[0];
+ };
+
+ const getNewestTimestamp = () => {
+ const sample = samples[timestamps[timestamps.length - 1]];
+ return sample.timestamp + sample.duration;
+ };
+
return {
addFrame,
clearBeforeThreshold,
deleteAll,
+ getSamples,
+ getOldestTimestamp,
+ getNewestTimestamp,
+ getOpenTimestamps,
};
};
diff --git a/packages/media/src/audio-extraction/audio-iterator.ts b/packages/media/src/audio-extraction/audio-iterator.ts
index e851259cb4..8dd5dac3fb 100644
--- a/packages/media/src/audio-extraction/audio-iterator.ts
+++ b/packages/media/src/audio-extraction/audio-iterator.ts
@@ -1,4 +1,6 @@
import type {AudioSample, AudioSampleSink} from 'mediabunny';
+import type {LogLevel} from '../log';
+import {Log} from '../log';
import type {RememberActualMatroskaTimestamps} from '../video-extraction/remember-actual-matroska-timestamps';
import {makeAudioCache} from './audio-cache';
@@ -13,13 +15,13 @@ const extraThreshold = 1.5;
export const makeAudioIterator = ({
audioSampleSink,
isMatroska,
- timeInSeconds,
+ startTimestamp,
src,
actualMatroskaTimestamps,
}: {
audioSampleSink: AudioSampleSink;
isMatroska: boolean;
- timeInSeconds: number;
+ startTimestamp: number;
src: string;
actualMatroskaTimestamps: RememberActualMatroskaTimestamps;
}) => {
@@ -29,16 +31,17 @@ export const makeAudioIterator = ({
// https://github.com/Vanilagy/mediabunny/issues/105
const sampleIterator = audioSampleSink.samples(
- isMatroska ? 0 : Math.max(0, timeInSeconds - extraThreshold),
+ isMatroska ? 0 : Math.max(0, startTimestamp - extraThreshold),
);
- const cache = makeAudioCache();
+ let fullDuration: number | null = null;
- let currentTimestamp = timeInSeconds;
+ const cache = makeAudioCache();
const getNextSample = async () => {
const {value: sample, done} = await sampleIterator.next();
if (done) {
+ fullDuration = cache.getNewestTimestamp() ?? null;
return null;
}
@@ -56,16 +59,23 @@ export const makeAudioIterator = ({
);
cache.addFrame(sample);
- currentTimestamp = sample.timestamp;
return sample;
};
const getSamples = async (timestamp: number, durationInSeconds: number) => {
+ if (fullDuration !== null && timestamp > fullDuration) {
+ return [];
+ }
+
// Clear all samples before the timestamp
+ // Do this in the while loop because samples might start from 0
cache.clearBeforeThreshold(timestamp - 1);
- const samples: AudioSample[] = [];
+ const samples: AudioSample[] = cache.getSamples(
+ timestamp,
+ durationInSeconds,
+ );
while (true) {
const sample = await getNextSample();
@@ -87,11 +97,43 @@ export const makeAudioIterator = ({
return samples;
};
+ const logOpenFrames = (logLevel: LogLevel) => {
+ Log.verbose(
+ logLevel,
+ 'Open audio samples for src',
+ src,
+ cache
+ .getOpenTimestamps()
+ .map((t) => t.toFixed(3))
+ .join(', '),
+ );
+ };
+
+ const canSatisfyRequestedTime = (timestamp: number) => {
+ const oldestTimestamp = cache.getOldestTimestamp() ?? startTimestamp;
+ if (fullDuration !== null && timestamp > fullDuration) {
+ return true;
+ }
+
+ return (
+ oldestTimestamp < timestamp && Math.abs(oldestTimestamp - timestamp) < 10
+ );
+ };
+
+ let op = Promise.resolve<AudioSample[]>([]);
+
return {
src,
- getNextSample,
- getCurrentTimestamp: () => currentTimestamp,
- getSamples,
+ getSamples: (ts: number, dur: number) => {
+ op = op.then(() => getSamples(ts, dur));
+ return op;
+ },
+ waitForCompletion: async () => {
+ await op;
+ return true;
+ },
+ canSatisfyRequestedTime,
+ logOpenFrames,
};
};
diff --git a/packages/media/src/audio-extraction/audio-manager.ts b/packages/media/src/audio-extraction/audio-manager.ts
index c25966f7f2..4d029b256f 100644
--- a/packages/media/src/audio-extraction/audio-manager.ts
+++ b/packages/media/src/audio-extraction/audio-manager.ts
@@ -22,7 +22,7 @@ export const makeAudioManager = () => {
const iterator = makeAudioIterator({
audioSampleSink,
isMatroska,
- timeInSeconds,
+ startTimestamp: timeInSeconds,
src,
actualMatroskaTimestamps,
});
@@ -32,7 +32,7 @@ export const makeAudioManager = () => {
return iterator;
};
- const getIterator = ({
+ const getIterator = async ({
src,
timeInSeconds,
audioSampleSink,
@@ -45,6 +45,16 @@ export const makeAudioManager = () => {
isMatroska: boolean;
actualMatroskaTimestamps: RememberActualMatroskaTimestamps;
}) => {
+ for (const iterator of iterators) {
+ if (
+ iterator.src === src &&
+ (await iterator.waitForCompletion()) &&
+ iterator.canSatisfyRequestedTime(timeInSeconds)
+ ) {
+ return iterator;
+ }
+ }
+
return makeIterator({
src,
timeInSeconds,
diff --git a/packages/media/src/audio-extraction/extract-audio.ts b/packages/media/src/audio-extraction/extract-audio.ts
index 8d1e9b8fca..830afe235d 100644
--- a/packages/media/src/audio-extraction/extract-audio.ts
+++ b/packages/media/src/audio-extraction/extract-audio.ts
@@ -5,6 +5,7 @@ import {
TARGET_NUMBER_OF_CHANNELS,
TARGET_SAMPLE_RATE,
} from '../convert-audiodata/resample-audiodata';
+import type {LogLevel} from '../log';
import {sinkPromises} from '../video-extraction/extract-frame';
import {getSinks} from '../video-extraction/get-frames-since-keyframe';
import {makeAudioManager} from './audio-manager';
@@ -16,13 +17,14 @@ export const extractAudio = async ({
timeInSeconds,
durationInSeconds,
volume,
+ logLevel,
}: {
src: string;
timeInSeconds: number;
durationInSeconds: number;
volume: number;
+ logLevel: LogLevel;
}): Promise<PcmS16AudioData | null> => {
- console.time('extractAudio');
if (!sinkPromises[src]) {
sinkPromises[src] = getSinks(src);
}
@@ -30,12 +32,10 @@ export const extractAudio = async ({
const {audio, actualMatroskaTimestamps, isMatroska} = await sinkPromises[src];
if (audio === null) {
- console.timeEnd('extractAudio');
-
return null;
}
- const sampleIterator = audioManager.getIterator({
+ const sampleIterator = await audioManager.getIterator({
src,
timeInSeconds,
audioSampleSink: audio.sampleSink,
@@ -48,6 +48,8 @@ export const extractAudio = async ({
durationInSeconds,
);
+ sampleIterator.logOpenFrames(logLevel);
+
const audioDataArray: PcmS16AudioData[] = [];
for (let i = 0; i < samples.length; i++) {
const sample = samples[i];
@@ -58,13 +60,11 @@ export const extractAudio = async ({
sample.sampleRate <
1
) {
- sample.close();
continue;
}
// Less than 1 sample would be included - we did not need it after all!
if (sample.timestamp + sample.duration <= timeInSeconds) {
- sample.close();
continue;
}
@@ -106,25 +106,17 @@ export const extractAudio = async ({
audioDataRaw.close();
if (audioData.numberOfFrames === 0) {
- sample.close();
-
continue;
}
audioDataArray.push(audioData);
-
- sample.close();
}
if (audioDataArray.length === 0) {
- console.timeEnd('extractAudio');
-
return null;
}
const combined = combineAudioDataAndClosePrevious(audioDataArray);
- console.timeEnd('extractAudio');
-
return combined;
};
diff --git a/packages/media/src/extract-frame-and-audio.ts b/packages/media/src/extract-frame-and-audio.ts
index 10e4072d1a..5df7673d81 100644
--- a/packages/media/src/extract-frame-and-audio.ts
+++ b/packages/media/src/extract-frame-and-audio.ts
@@ -37,6 +37,7 @@ export const extractFrameAndAudio = async ({
timeInSeconds,
durationInSeconds,
volume,
+ logLevel,
})
: null,
]);
diff --git a/packages/media/src/video-extraction/extract-frame.ts b/packages/media/src/video-extraction/extract-frame.ts
index 1bb364578b..5578ca9e66 100644
--- a/packages/media/src/video-extraction/extract-frame.ts
+++ b/packages/media/src/video-extraction/extract-frame.ts
@@ -14,7 +14,6 @@ export const extractFrame = async ({
timeInSeconds: number;
logLevel: LogLevel;
}) => {
- console.time('extractFrame');
if (!sinkPromises[src]) {
sinkPromises[src] = getSinks(src);
}
@@ -31,6 +30,5 @@ export const extractFrame = async ({
const frame = await keyframeBank.getFrameFromTimestamp(timeInSeconds);
- console.timeEnd('extractFrame');
return frame;
};