🎥 Make videos programmatically with React
still buggy but getting there
Jonny Burger863b9db5ac98
diff --git a/packages/example/public/demo_smpte_h264_pcm.mkv b/packages/example/public/demo_smpte_h264_pcm.mkvnew file mode 100644index 0000000000..58d3969a07Binary files /dev/null and b/packages/example/public/demo_smpte_h264_pcm.mkv differdiff --git a/packages/example/src/NewVideo/NewVideo.tsx b/packages/example/src/NewVideo/NewVideo.tsxindex 5c0b4cc208..82cd5b1d10 100644--- a/packages/example/src/NewVideo/NewVideo.tsx+++ b/packages/example/src/NewVideo/NewVideo.tsx@@ -24,7 +24,7 @@ export const NewVideoExample: React.FC = () => {No Flickering</h1></div>- <NewVideo src={staticFile('long-video.mp4')} />+ <NewVideo src={staticFile('demo_smpte_h264_pcm.mkv')} /></AbsoluteFill></>);diff --git a/packages/renderer/src/assets/download-map.ts b/packages/renderer/src/assets/download-map.tsindex abab0133d1..1b19c32ed9 100644--- a/packages/renderer/src/assets/download-map.ts+++ b/packages/renderer/src/assets/download-map.ts@@ -1,4 +1,4 @@-import {mkdirSync} from 'node:fs';+import {cpSync, mkdirSync} from 'node:fs';import path from 'node:path';import {VERSION} from 'remotion/version';import {deleteDirectory} from '../delete-directory';@@ -6,6 +6,10 @@ import {OffthreadVideoServerEmitter} from '../offthread-video-server';import type {FrameAndAssets} from '../render-frames';import {tmpDir} from '../tmp-dir';import type {RenderMediaOnDownload} from './download-and-map-assets-to-file';+import {+ makeInlineAudioMixing,+ type InlineAudioMixing,+} from './inline-audio-mixing';export type AudioChannelsAndDurationResultCache = {channels: number;@@ -44,6 +48,7 @@ export type DownloadMap = {preventCleanup: () => void;allowCleanup: () => void;isPreventedFromCleanup: () => boolean;+ inlineAudioMixing: InlineAudioMixing;};export type RenderAssetInfo = {@@ -57,7 +62,7 @@ export type RenderAssetInfo = {forSeamlessAacConcatenation: boolean;};-const makeAndReturn = (dir: string, name: string) => {+export const makeAndReturn = (dir: string, name: string) => {const p = path.join(dir, name);mkdirSync(p);return p;@@ -93,6 +98,7 @@ export const makeDownloadMap = (): DownloadMap => {isPreventedFromCleanup: () => {return prevented;},+ inlineAudioMixing: makeInlineAudioMixing(dir),};};@@ -104,6 +110,16 @@ export const cleanDownloadMap = (downloadMap: DownloadMap) => {deleteDirectory(downloadMap.downloadDir);deleteDirectory(downloadMap.complexFilter);deleteDirectory(downloadMap.compositingDir);+ // TODO: Cleanup inline audio mixing+ const backupDir = path.join(+ downloadMap.assetDir,+ '..',+ 'remotion-inline-audio-mixing',+ );+ cpSync(downloadMap.inlineAudioMixing.folder, backupDir, {recursive: true});+ console.log('Copied inline audio mixing to', backupDir);+ // downloadMap.inlineAudioMixing.cleanup();+// Assets dir must be last since the others are containeddeleteDirectory(downloadMap.assetDir);};diff --git a/packages/renderer/src/assets/inline-audio-mixing.ts b/packages/renderer/src/assets/inline-audio-mixing.tsnew file mode 100644index 0000000000..102770e7e4--- /dev/null+++ b/packages/renderer/src/assets/inline-audio-mixing.ts@@ -0,0 +1,159 @@+import fs, {writeSync} from 'node:fs';+import path from 'node:path';+import type {InlineAudioAsset} from 'remotion/no-react';+import {deleteDirectory} from '../delete-directory';+import {DEFAULT_SAMPLE_RATE} from '../sample-rate';+import {makeAndReturn} from './download-map';++const numberTo32BiIntLittleEndian = (num: number) => {+ return new Uint8Array([+ num & 0xff,+ (num >> 8) & 0xff,+ (num >> 16) & 0xff,+ (num >> 24) & 0xff,+ ]);+};++const numberTo16BitLittleEndian = (num: number) => {+ return new Uint8Array([num & 0xff, (num >> 8) & 0xff]);+};++const BIT_DEPTH = 16;+const BYTES_PER_SAMPLE = BIT_DEPTH / 8;++export const makeInlineAudioMixing = (dir: string) => {+ const folderToAdd = makeAndReturn(dir, 'remotion-inline-audio-mixing');+ // asset id -> file descriptor+ const openFiles: Record<string, number> = {};++ const cleanup = () => {+ for (const fd of Object.values(openFiles)) {+ fs.closeSync(fd);+ }++ deleteDirectory(folderToAdd);+ };++ const ensureAsset = (+ asset: InlineAudioAsset,+ fps: number,+ totalNumberOfFrames: number,+ ) => {+ const filePath = path.join(folderToAdd, `${asset.id}.wav`);+ if (!openFiles[asset.id]) {+ openFiles[asset.id] = fs.openSync(filePath, 'w');+ }++ const expectedDataSize = Math.round(+ (totalNumberOfFrames / fps) *+ asset.numberOfChannels *+ DEFAULT_SAMPLE_RATE *+ BYTES_PER_SAMPLE,+ );+ console.log({totalNumberOfFrames, fps});+ const expectedSize = 40 + expectedDataSize;++ const {numberOfChannels} = asset;++ const fd = openFiles[asset.id];+ writeSync(fd, new Uint8Array([0x52, 0x49, 0x46, 0x46]), 0, 4, 0); // "RIFF"+ writeSync(+ fd,+ new Uint8Array(numberTo32BiIntLittleEndian(expectedSize)),+ 0,+ 4,+ 4,+ ); // Remaining size+ writeSync(fd, new Uint8Array([0x57, 0x41, 0x56, 0x45]), 0, 4, 8); // "WAVE"+ writeSync(fd, new Uint8Array([0x66, 0x6d, 0x74, 0x20]), 0, 4, 12); // "fmt "+ writeSync(fd, new Uint8Array([BIT_DEPTH, 0x00, 0x00, 0x00]), 0, 4, 16); // fmt chunk size = 16+ writeSync(fd, new Uint8Array([0x01, 0x00]), 0, 2, 20); // Audio format (PCM) = 1, set 3 if float32 would be true+ writeSync(fd, new Uint8Array([numberOfChannels, 0x00]), 0, 2, 22); // Number of channels+ writeSync(+ fd,+ new Uint8Array(numberTo32BiIntLittleEndian(DEFAULT_SAMPLE_RATE)),+ 0,+ 4,+ 24,+ ); // Sample rate+ writeSync(+ fd,+ new Uint8Array(+ numberTo32BiIntLittleEndian(+ DEFAULT_SAMPLE_RATE * numberOfChannels * BYTES_PER_SAMPLE,+ ),+ ),+ 0,+ 4,+ 28,+ ); // Byte rate+ writeSync(+ fd,+ new Uint8Array(+ numberTo16BitLittleEndian(numberOfChannels * BYTES_PER_SAMPLE),+ ),+ 0,+ 2,+ 32,+ ); // Block align+ writeSync(fd, numberTo16BitLittleEndian(BIT_DEPTH), 0, 2, 34); // Bits per sample+ writeSync(fd, new Uint8Array([0x64, 0x61, 0x74, 0x61]), 0, 4, 36); // "data"+ writeSync(+ fd,+ new Uint8Array(numberTo32BiIntLittleEndian(expectedDataSize)),+ 0,+ 4,+ 40,+ ); // Remaining size+ };++ const addAsset = (+ asset: InlineAudioAsset,+ fps: number,+ totalNumberOfFrames: number,+ ) => {+ ensureAsset(asset, fps, totalNumberOfFrames);+ const fileDescriptor = openFiles[asset.id];++ const arr = new Int16Array(asset.audio);+ writeSync(+ // fs+ fileDescriptor,+ // data+ arr,+ // offset of dats+ 0,+ // length+ arr.byteLength,+ // position+ 44 ++ Math.round(+ (asset.frame / fps) *+ asset.numberOfChannels *+ DEFAULT_SAMPLE_RATE *+ BYTES_PER_SAMPLE,+ ),+ );++ console.log(+ 'wrote',+ arr.byteLength,+ 'bytes to',+ path.join(folderToAdd, `${asset.id}.wav`),+ Math.round(+ (asset.frame / fps) *+ asset.numberOfChannels *+ DEFAULT_SAMPLE_RATE *+ BYTES_PER_SAMPLE,+ ),+ );+ };++ return {+ cleanup,+ addAsset,+ folder: folderToAdd,+ };+};++export type InlineAudioMixing = ReturnType<typeof makeInlineAudioMixing>;diff --git a/packages/renderer/src/render-frame-with-option-to-reject.ts b/packages/renderer/src/render-frame-with-option-to-reject.tsindex 56a60d44e0..fd1526b3f7 100644--- a/packages/renderer/src/render-frame-with-option-to-reject.ts+++ b/packages/renderer/src/render-frame-with-option-to-reject.ts@@ -253,6 +253,15 @@ export const renderFrameWithOptionToReject = async ({});}+ for (const renderAsset of inlineAudioAssets) {+ // TODO: Hardcoded FPS+ downloadMap.inlineAudioMixing.addAsset(+ renderAsset,+ 30,+ framesToRender.length,+ );+ }+cleanupPageError();page.off('error', errorCallbackOnFrame);diff --git a/packages/video/src/convert-audiodata/combine-audiodata.ts b/packages/video/src/convert-audiodata/combine-audiodata.tsindex 49411a8239..d287979781 100644--- a/packages/video/src/convert-audiodata/combine-audiodata.ts+++ b/packages/video/src/convert-audiodata/combine-audiodata.ts@@ -61,21 +61,25 @@ export const combineAudioDataAndClosePrevious = (audioDataIndex++) {const audioData = audioDataArray[audioDataIndex];- if (audioDataIndex === 0) {- audioData.clone().copyTo(channel, {- planeIndex: 0,- });- } else {- const intermediateChannel = new DataType(- audioData.numberOfFrames * numberOfChannels,- );- audioData.clone().copyTo(intermediateChannel, {- planeIndex: 0,- });- channel.set(intermediateChannel, framesWritten);- }- framesWritten += audioData.numberOfFrames;+ const intermediateChannel = new DataType(+ audioData.numberOfFrames * numberOfChannels,+ );+ audioData.copyTo(intermediateChannel, {+ planeIndex: 0,+ });+ channel.set(intermediateChannel, framesWritten);+ console.log(+ 'wrote',+ intermediateChannel.byteLength,+ 'bytes to channel at offset',+ framesWritten,+ audioData.format,+ DataType,+ audioData.allocationSize({planeIndex: 0}),+ );++ framesWritten += audioData.numberOfFrames * numberOfChannels;audioData.close();}diff --git a/packages/video/src/convert-audiodata/convert-audiodata.ts b/packages/video/src/convert-audiodata/convert-audiodata.tsindex 2d5a029849..112ce9f587 100644--- a/packages/video/src/convert-audiodata/convert-audiodata.ts+++ b/packages/video/src/convert-audiodata/convert-audiodata.ts@@ -38,6 +38,7 @@ export const convertAudioData = ({const frameCount =numberOfFrames -Math.round((trimEndInSeconds + trimStartInSeconds) * audioData.sampleRate);+ console.log({frameCount, trimEndInSeconds, trimStartInSeconds});const newNumberOfFrames = Math.floor(frameCount / ratio);@@ -59,8 +60,9 @@ export const convertAudioData = ({format === audioData.format &&newNumberOfFrames === numberOfFrames &&trimStartInSeconds === 0 &&- trimEndInSeconds === null+ trimEndInSeconds === 0) {+ console.log('cloning');return audioData.clone();}@@ -74,7 +76,9 @@ export const convertAudioData = ({.map(() => new DataType((isPlanar ? 1 : numberOfChannels) * frameCount));for (let i = 0; i < planes; i++) {- audioData.clone().copyTo(srcChannels[i], {+ console.log('copying');++ audioData.copyTo(srcChannels[i], {planeIndex: i,format,frameOffset,@@ -84,6 +88,25 @@ export const convertAudioData = ({const data = new DataType(newNumberOfFrames * numberOfChannels);const chunkSize = frameCount / newNumberOfFrames;+ console.log('resampling', chunkSize, frameCount, newNumberOfFrames);++ if (newNumberOfFrames === frameCount) {+ console.log('not resampling, copying');+ let offset = 0;+ for (let i = 0; i < planes; i++) {+ data.set(srcChannels[i], offset);+ offset += srcChannels[i].length;+ }++ return new AudioData({+ data,+ format,+ numberOfChannels,+ numberOfFrames: newNumberOfFrames,+ sampleRate: newSampleRate,+ timestamp: audioData.timestamp,+ });+ }for (let newFrameIndex = 0;diff --git a/packages/video/src/extract-frame.ts b/packages/video/src/extract-frame.tsindex d0f77a6fac..db5a231a63 100644--- a/packages/video/src/extract-frame.ts+++ b/packages/video/src/extract-frame.ts@@ -79,11 +79,30 @@ export const extractAudio = async ({continue;}+ // Less than 1 sample would be included - we did not need it after all!+ if (sample.timestamp + sample.duration <= timeInSeconds) {+ sample.close();+ continue;+ }++ console.log(+ sample.timestamp,+ sample.duration,+ timeInSeconds + durationInSeconds,+ );+const isFirstSample = i === 0;const isLastSample = i === samples.length - 1;const audioDataRaw = sample.toAudioData();+ console.log(+ audioDataRaw.numberOfChannels,+ audioDataRaw.format,+ audioDataRaw.numberOfFrames,+ audioDataRaw.sampleRate,+ );+// amount of samples to shave from start and endlet trimStartInSeconds = 0;let trimEndInSeconds = 0;@@ -98,25 +117,39 @@ export const extractAudio = async ({if (isLastSample) {trimEndInSeconds =- sample.timestamp +- sample.duration -- (timeInSeconds + durationInSeconds);+ // clamp to 0 in case the audio ends early+ Math.max(+ 0,+ sample.timestamp ++ sample.duration -+ (timeInSeconds + durationInSeconds),+ );}const audioData = convertAudioData({audioData: audioDataRaw,newSampleRate: 48000,- // todo: planar or not?format: 's16',trimStartInSeconds,trimEndInSeconds,});+ if (audioData.numberOfFrames === 0) {+ audioData.close();+ sample.close();++ continue;+ }+audioDataArray.push(audioData);sample.close();}+ if (audioDataArray.length === 0) {+ return null;+ }+const combined = combineAudioDataAndClosePrevious(audioDataArray);return combined;diff --git a/packages/video/src/new-video-for-rendering.tsx b/packages/video/src/new-video-for-rendering.tsxindex a9480e863b..46700f111b 100644--- a/packages/video/src/new-video-for-rendering.tsx+++ b/packages/video/src/new-video-for-rendering.tsx@@ -1,4 +1,10 @@-import React, {useContext, useLayoutEffect, useMemo, useRef} from 'react';+import React, {+ useContext,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from 'react';import {cancelRender,continueRender,@@ -39,7 +45,7 @@ export const NewVideoForRendering: React.FC<NewVideoProps> = ({loopVolumeCurveBehavior ?? 'repeat',);- const id = useMemo(() => `${Math.random()}`, []);+ const [id] = useState(() => `${Math.random()}`.replace('0.', ''));if (!videoConfig) {throw new Error('No video config found');diff --git a/reference.mp4 b/reference.mp4new file mode 100644index 0000000000..e69de29bb2diff --git a/reference.wav b/reference.wavnew file mode 100644index 0000000000..71a0fa073aBinary files /dev/null and b/reference.wav differdiff --git a/reference2channel.wav b/reference2channel.wavnew file mode 100644index 0000000000..c97373026dBinary files /dev/null and b/reference2channel.wav differ