Skip to content

🎥 Make videos programmatically with React

extract samples

Jonny Burger3e835263f787
diff --git a/packages/media/src/extract-frame-and-audio.ts b/packages/media/src/extract-frame-and-audio.ts
new file mode 100644
index 0000000000..96a6931976
--- /dev/null
+++ b/packages/media/src/extract-frame-and-audio.ts
@@ -0,0 +1,48 @@
+import type {LogLevel} from 'remotion';
+import type {PcmS16AudioData} from './convert-audiodata/convert-audiodata';
+import {extractFrame} from './extract-frame';
+import {extractAudio} from './extrct-audio';
+
+export const extractFrameAndAudio = async ({
+ src,
+ timeInSeconds,
+ logLevel,
+ durationInSeconds,
+ includeAudio,
+ includeVideo,
+ volume,
+}: {
+ src: string;
+ timeInSeconds: number;
+ logLevel: LogLevel;
+ durationInSeconds: number;
+ includeAudio: boolean;
+ includeVideo: boolean;
+ volume: number;
+}): Promise<{
+ frame: VideoFrame | null;
+ audio: PcmS16AudioData | null;
+}> => {
+ const [frame, audio] = await Promise.all([
+ includeVideo
+ ? extractFrame({
+ src,
+ timeInSeconds,
+ logLevel,
+ })
+ : null,
+ includeAudio
+ ? extractAudio({
+ src,
+ timeInSeconds,
+ durationInSeconds,
+ volume,
+ })
+ : null,
+ ]);
+
+ return {
+ frame: frame?.toVideoFrame() ?? null,
+ audio,
+ };
+};
diff --git a/packages/media/src/extract-frame-via-broadcast-channel.ts b/packages/media/src/extract-frame-via-broadcast-channel.ts
index 11bf5d204b..72be829df8 100644
--- a/packages/media/src/extract-frame-via-broadcast-channel.ts
+++ b/packages/media/src/extract-frame-via-broadcast-channel.ts
@@ -1,5 +1,5 @@
import type {PcmS16AudioData} from './convert-audiodata/convert-audiodata';
-import {extractFrameAndAudio} from './extract-frame';
+import {extractFrameAndAudio} from './extract-frame-and-audio';
import type {LogLevel} from './log';
type ExtractFrameRequest = {
diff --git a/packages/media/src/extract-frame.ts b/packages/media/src/extract-frame.ts
index 7bb350e0b6..f815f8f7a3 100644
--- a/packages/media/src/extract-frame.ts
+++ b/packages/media/src/extract-frame.ts
@@ -1,17 +1,9 @@
-import type {AudioSample} from 'mediabunny';
-import {combineAudioDataAndClosePrevious} from './convert-audiodata/combine-audiodata';
-import type {PcmS16AudioData} from './convert-audiodata/convert-audiodata';
-import {convertAudioData} from './convert-audiodata/convert-audiodata';
-import {
- TARGET_NUMBER_OF_CHANNELS,
- TARGET_SAMPLE_RATE,
-} from './convert-audiodata/resample-audiodata';
import {getSinks, type GetSink} from './get-frames-since-keyframe';
import {makeKeyframeManager} from './keyframe-manager';
import type {LogLevel} from './log';
export const keyframeManager = makeKeyframeManager();
-const sinkPromise: Record<string, Promise<GetSink>> = {};
+export const sinkPromises: Record<string, Promise<GetSink>> = {};
export const extractFrame = async ({
src,
@@ -22,11 +14,11 @@ export const extractFrame = async ({
timeInSeconds: number;
logLevel: LogLevel;
}) => {
- if (!sinkPromise[src]) {
- sinkPromise[src] = getSinks(src);
+ if (!sinkPromises[src]) {
+ sinkPromises[src] = getSinks(src);
}
- const {video} = await sinkPromise[src];
+ const {video} = await sinkPromises[src];
const keyframeBank = await keyframeManager.requestKeyframeBank({
packetSink: video.packetSink,
@@ -40,187 +32,3 @@ export const extractFrame = async ({
return frame;
};
-
-export const extractAudio = async ({
- src,
- timeInSeconds,
- durationInSeconds,
- volume,
-}: {
- src: string;
- timeInSeconds: number;
- durationInSeconds: number;
- volume: number;
-}): Promise<PcmS16AudioData | null> => {
- if (!sinkPromise[src]) {
- sinkPromise[src] = getSinks(src);
- }
-
- const {audio, actualMatroskaTimestamps, isMatroska} = await sinkPromise[src];
-
- if (audio === null) {
- return null;
- }
-
- // https://discord.com/channels/@me/1409810025844838481/1415028953093111870
- // Audio frames might have dependencies on previous and next frames so we need to decode a bit more
- // and then discard it.
- // The worst case seems to be FLAC files with a 65'535 sample window, which would be 1486.0ms at 44.1Khz.
- // So let's set a threshold of 1.5 seconds.
-
- const extraThreshold = 1.5;
-
- // Matroska timestamps are not accurate unless we start from the beginning
- // So for matroska, we need to decode all samples :(
-
- // https://github.com/Vanilagy/mediabunny/issues/105
- const sampleIterator = audio.sampleSink.samples(
- isMatroska ? 0 : Math.max(0, timeInSeconds - extraThreshold),
- timeInSeconds + durationInSeconds,
- );
- const samples: AudioSample[] = [];
-
- for await (const sample of sampleIterator) {
- const realTimestamp = actualMatroskaTimestamps.getRealTimestamp(
- sample.timestamp,
- );
-
- if (realTimestamp !== null && realTimestamp !== sample.timestamp) {
- sample.setTimestamp(realTimestamp);
- }
-
- actualMatroskaTimestamps.observeTimestamp(sample.timestamp);
- actualMatroskaTimestamps.observeTimestamp(
- sample.timestamp + sample.duration,
- );
- if (sample.timestamp + sample.duration - 0.0000000001 <= timeInSeconds) {
- continue;
- }
-
- if (sample.timestamp >= timeInSeconds + durationInSeconds - 0.0000000001) {
- continue;
- }
-
- samples.push(sample);
- }
-
- const audioDataArray: PcmS16AudioData[] = [];
- for (let i = 0; i < samples.length; i++) {
- const sample = samples[i];
-
- // Less than 1 sample would be included - we did not need it after all!
- if (
- Math.abs(sample.timestamp - (timeInSeconds + durationInSeconds)) *
- 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;
- }
-
- const isFirstSample = i === 0;
- const isLastSample = i === samples.length - 1;
-
- const audioDataRaw = sample.toAudioData();
-
- // amount of samples to shave from start and end
- let trimStartInSeconds = 0;
- let trimEndInSeconds = 0;
-
- // TODO: Apply playback rate
- // TODO: Apply tone frequency
-
- if (isFirstSample) {
- trimStartInSeconds = timeInSeconds - sample.timestamp;
- }
-
- if (isLastSample) {
- trimEndInSeconds =
- // clamp to 0 in case the audio ends early
- Math.max(
- 0,
- sample.timestamp +
- sample.duration -
- (timeInSeconds + durationInSeconds),
- );
- }
-
- const audioData = convertAudioData({
- audioData: audioDataRaw,
- newSampleRate: TARGET_SAMPLE_RATE,
- trimStartInSeconds,
- trimEndInSeconds,
- targetNumberOfChannels: TARGET_NUMBER_OF_CHANNELS,
- volume,
- });
- audioDataRaw.close();
-
- if (audioData.numberOfFrames === 0) {
- sample.close();
-
- continue;
- }
-
- audioDataArray.push(audioData);
-
- sample.close();
- }
-
- if (audioDataArray.length === 0) {
- return null;
- }
-
- const combined = combineAudioDataAndClosePrevious(audioDataArray);
-
- return combined;
-};
-
-export const extractFrameAndAudio = async ({
- src,
- timeInSeconds,
- logLevel,
- durationInSeconds,
- includeAudio,
- includeVideo,
- volume,
-}: {
- src: string;
- timeInSeconds: number;
- logLevel: LogLevel;
- durationInSeconds: number;
- includeAudio: boolean;
- includeVideo: boolean;
- volume: number;
-}): Promise<{
- frame: VideoFrame | null;
- audio: PcmS16AudioData | null;
-}> => {
- const [frame, audio] = await Promise.all([
- includeVideo
- ? extractFrame({
- src,
- timeInSeconds,
- logLevel,
- })
- : null,
- includeAudio
- ? extractAudio({
- src,
- timeInSeconds,
- durationInSeconds,
- volume,
- })
- : null,
- ]);
-
- return {
- frame: frame?.toVideoFrame() ?? null,
- audio,
- };
-};
diff --git a/packages/media/src/extrct-audio.ts b/packages/media/src/extrct-audio.ts
new file mode 100644
index 0000000000..cf9ece4979
--- /dev/null
+++ b/packages/media/src/extrct-audio.ts
@@ -0,0 +1,150 @@
+import type {AudioSample} from 'mediabunny';
+import {combineAudioDataAndClosePrevious} from './convert-audiodata/combine-audiodata';
+import type {PcmS16AudioData} from './convert-audiodata/convert-audiodata';
+import {convertAudioData} from './convert-audiodata/convert-audiodata';
+import {
+ TARGET_NUMBER_OF_CHANNELS,
+ TARGET_SAMPLE_RATE,
+} from './convert-audiodata/resample-audiodata';
+import {sinkPromises} from './extract-frame';
+import {getSinks} from './get-frames-since-keyframe';
+
+export const extractAudio = async ({
+ src,
+ timeInSeconds,
+ durationInSeconds,
+ volume,
+}: {
+ src: string;
+ timeInSeconds: number;
+ durationInSeconds: number;
+ volume: number;
+}): Promise<PcmS16AudioData | null> => {
+ if (!sinkPromises[src]) {
+ sinkPromises[src] = getSinks(src);
+ }
+
+ const {audio, actualMatroskaTimestamps, isMatroska} = await sinkPromises[src];
+
+ if (audio === null) {
+ return null;
+ }
+
+ // https://discord.com/channels/@me/1409810025844838481/1415028953093111870
+ // Audio frames might have dependencies on previous and next frames so we need to decode a bit more
+ // and then discard it.
+ // The worst case seems to be FLAC files with a 65'535 sample window, which would be 1486.0ms at 44.1Khz.
+ // So let's set a threshold of 1.5 seconds.
+
+ const extraThreshold = 1.5;
+
+ // Matroska timestamps are not accurate unless we start from the beginning
+ // So for matroska, we need to decode all samples :(
+
+ // https://github.com/Vanilagy/mediabunny/issues/105
+ const sampleIterator = audio.sampleSink.samples(
+ isMatroska ? 0 : Math.max(0, timeInSeconds - extraThreshold),
+ timeInSeconds + durationInSeconds,
+ );
+ const samples: AudioSample[] = [];
+
+ for await (const sample of sampleIterator) {
+ const realTimestamp = actualMatroskaTimestamps.getRealTimestamp(
+ sample.timestamp,
+ );
+
+ if (realTimestamp !== null && realTimestamp !== sample.timestamp) {
+ sample.setTimestamp(realTimestamp);
+ }
+
+ actualMatroskaTimestamps.observeTimestamp(sample.timestamp);
+ actualMatroskaTimestamps.observeTimestamp(
+ sample.timestamp + sample.duration,
+ );
+ if (sample.timestamp + sample.duration - 0.0000000001 <= timeInSeconds) {
+ continue;
+ }
+
+ if (sample.timestamp >= timeInSeconds + durationInSeconds - 0.0000000001) {
+ continue;
+ }
+
+ samples.push(sample);
+ }
+
+ const audioDataArray: PcmS16AudioData[] = [];
+ for (let i = 0; i < samples.length; i++) {
+ const sample = samples[i];
+
+ // Less than 1 sample would be included - we did not need it after all!
+ if (
+ Math.abs(sample.timestamp - (timeInSeconds + durationInSeconds)) *
+ 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;
+ }
+
+ const isFirstSample = i === 0;
+ const isLastSample = i === samples.length - 1;
+
+ const audioDataRaw = sample.toAudioData();
+
+ // amount of samples to shave from start and end
+ let trimStartInSeconds = 0;
+ let trimEndInSeconds = 0;
+
+ // TODO: Apply playback rate
+ // TODO: Apply tone frequency
+
+ if (isFirstSample) {
+ trimStartInSeconds = timeInSeconds - sample.timestamp;
+ }
+
+ if (isLastSample) {
+ trimEndInSeconds =
+ // clamp to 0 in case the audio ends early
+ Math.max(
+ 0,
+ sample.timestamp +
+ sample.duration -
+ (timeInSeconds + durationInSeconds),
+ );
+ }
+
+ const audioData = convertAudioData({
+ audioData: audioDataRaw,
+ newSampleRate: TARGET_SAMPLE_RATE,
+ trimStartInSeconds,
+ trimEndInSeconds,
+ targetNumberOfChannels: TARGET_NUMBER_OF_CHANNELS,
+ volume,
+ });
+ audioDataRaw.close();
+
+ if (audioData.numberOfFrames === 0) {
+ sample.close();
+
+ continue;
+ }
+
+ audioDataArray.push(audioData);
+
+ sample.close();
+ }
+
+ if (audioDataArray.length === 0) {
+ return null;
+ }
+
+ const combined = combineAudioDataAndClosePrevious(audioDataArray);
+
+ return combined;
+};
diff --git a/packages/media/src/test/browser.test.ts b/packages/media/src/test/browser.test.ts
index d7a15e79d0..5a5447c0a5 100644
--- a/packages/media/src/test/browser.test.ts
+++ b/packages/media/src/test/browser.test.ts
@@ -1,5 +1,6 @@
import {assert, expect, test} from 'vitest';
-import {extractFrameAndAudio, keyframeManager} from '../extract-frame';
+import {keyframeManager} from '../extract-frame';
+import {extractFrameAndAudio} from '../extract-frame-and-audio';
test('Should be able to extract a frame', async () => {
await keyframeManager.clearAll();