🎥 Make videos programmatically with React
separate audio and video when combining
Jonny Burger3c6ef1a3e6bd
diff --git a/packages/renderer/src/combine-audio.ts b/packages/renderer/src/combine-audio.tsnew file mode 100644index 0000000000..eff5c7748c--- /dev/null+++ b/packages/renderer/src/combine-audio.ts@@ -0,0 +1,212 @@+import {rmSync, writeFileSync} from 'fs';+import {join} from 'path';+import type {AudioCodec} from './audio-codec';+import {mapAudioCodecToFfmpegAudioCodecName} from './audio-codec';+import {callFf} from './call-ffmpeg';+import type {LogLevel} from './log-level';+import {Log} from './logger';+import {parseFfmpegProgress} from './parse-ffmpeg-progress';+import {DEFAULT_SAMPLE_RATE} from './sample-rate';+import {truthy} from './truthy';++const durationOf1Frame = (1024 / DEFAULT_SAMPLE_RATE) * 1_000_000;++const getClosestAlignedTime = (targetTime: number) => {+ const decimalFramesToTargetTime = targetTime / durationOf1Frame;+ const nearestFrameIndexForTargetTime = Math.round(decimalFramesToTargetTime);+ return nearestFrameIndexForTargetTime * durationOf1Frame;+};++const encodeAudio = async ({+ files,+ resolvedAudioCodec,+ audioBitrate,+ filelistDir,+ output,+ indent,+ logLevel,+}: {+ files: string[];+ resolvedAudioCodec: AudioCodec;+ audioBitrate: string | null;+ filelistDir: string;+ output: string;+ indent: boolean;+ logLevel: LogLevel;+}) => {+ const fileList = files.map((p) => `file '${p}'`).join('\n');+ const fileListTxt = join(filelistDir, 'audio-files.txt');+ writeFileSync(fileListTxt, fileList);++ const command = [+ '-i',+ '-f',+ 'concat',+ '-safe',+ '0',+ fileListTxt,+ '-c:a',+ mapAudioCodecToFfmpegAudioCodecName(resolvedAudioCodec),+ resolvedAudioCodec === 'aac' ? '-cutoff' : null,+ resolvedAudioCodec === 'aac' ? '18000' : null,+ '-b:a',+ audioBitrate ? audioBitrate : '320k',+ '-vn',+ '-y',+ output,+ ];++ try {+ const task = callFf({+ args: command,+ bin: 'ffmpeg',+ indent,+ logLevel,+ });+ task.stderr?.on('data', (data: Buffer) => {+ const parsed = parseFfmpegProgress(data.toString('utf8'));+ if (parsed === undefined) {+ Log.verbose({indent, logLevel}, data.toString('utf8'));+ } else {+ Log.verbose({indent, logLevel}, `Encoded ${parsed} audio frames`);+ }+ });+ await task;+ return output;+ } catch (e) {+ rmSync(filelistDir, {recursive: true});+ throw e;+ }+};++const combineAudioSeamlessly = async ({+ files,+ filelistDir,+ indent,+ logLevel,+ output,+ chunkDurationInSeconds,+}: {+ files: string[];+ filelistDir: string;+ indent: boolean;+ logLevel: LogLevel;+ output: string;+ chunkDurationInSeconds: number;+}) => {+ const fileList = files+ .map((p, i) => {+ const isLast = i === files.length - 1;++ const targetStart = i * chunkDurationInSeconds;+ const endStart = (i + 1) * chunkDurationInSeconds;++ const startTime = getClosestAlignedTime(targetStart);+ const endTime = getClosestAlignedTime(endStart);++ const realDuration = endTime - startTime;++ let inpoint = 0;+ if (i > 0) {+ // Although we only asked for two frames of padding, ffmpeg will add an+ // additional 2 frames of silence at the start of the segment. When we slice out+ // our real data with inpoint and outpoint, we'll want remove both the silence+ // and the extra frames we asked for.+ inpoint = durationOf1Frame * 4;+ }++ // inpoint is inclusive and outpoint is exclusive. To avoid overlap, we subtract+ // the duration of one frame from the outpoint.+ // we don't have to subtract a frame if this is the last segment.+ const outpoint = realDuration + inpoint - durationOf1Frame;++ return [+ `file '${p}'`,+ `inpoint ${inpoint}us`,+ isLast ? null : `outpoint ${outpoint}us`,+ ].filter(truthy);+ })+ .join('\n');++ const fileListTxt = join(filelistDir, 'audio-files.txt');+ writeFileSync(fileListTxt, fileList);++ const command = [+ '-f',+ 'concat',+ '-safe',+ '0',+ '-i',+ fileListTxt,+ '-c',+ 'copy',+ '-vn',+ '-y',+ output,+ ];++ try {+ const task = callFf({+ args: command,+ bin: 'ffmpeg',+ indent,+ logLevel,+ });+ task.stderr?.on('data', (data: Buffer) => {+ const parsed = parseFfmpegProgress(data.toString('utf8'));+ if (parsed === undefined) {+ Log.verbose({indent, logLevel}, data.toString('utf8'));+ } else {+ Log.verbose({indent, logLevel}, `Encoded ${parsed} audio frames`);+ }+ });+ await task;+ return output;+ } catch (e) {+ rmSync(filelistDir, {recursive: true});+ throw e;+ }+};++export const createCombinedAudio = ({+ seamless,+ filelistDir,+ files,+ indent,+ logLevel,+ audioBitrate,+ resolvedAudioCodec,+ output,+ chunkDurationInSeconds,+}: {+ seamless: boolean;+ filelistDir: string;+ files: string[];+ indent: boolean;+ logLevel: LogLevel;+ audioBitrate: string | null;+ resolvedAudioCodec: AudioCodec;+ output: string;+ chunkDurationInSeconds: number;+}): Promise<string> => {+ if (seamless) {+ return combineAudioSeamlessly({+ filelistDir,+ files,+ indent,+ logLevel,+ output,+ chunkDurationInSeconds,+ });+ }++ return encodeAudio({+ filelistDir,+ files,+ resolvedAudioCodec,+ audioBitrate,+ output,+ indent,+ logLevel,+ });+};diff --git a/packages/renderer/src/combine-video-streams.ts b/packages/renderer/src/combine-video-streams.tsnew file mode 100644index 0000000000..1db0df7576--- /dev/null+++ b/packages/renderer/src/combine-video-streams.ts@@ -0,0 +1,84 @@+import {rmSync, writeFileSync} from 'fs';+import {join} from 'path';+import {VERSION} from 'remotion/version';+import {callFf} from './call-ffmpeg';+import type {Codec} from './codec';+import {convertNumberOfGifLoopsToFfmpegSyntax} from './convert-number-of-gif-loops-to-ffmpeg';+import type {LogLevel} from './log-level';+import {Log} from './logger';+import {parseFfmpegProgress} from './parse-ffmpeg-progress';+import {truthy} from './truthy';++export const combineVideoStreams = async ({+ fps,+ codec,+ filelistDir,+ numberOfGifLoops,+ output,+ indent,+ logLevel,+ onProgress,+ files,+}: {+ fps: number;+ codec: Codec;+ filelistDir: string;+ numberOfGifLoops: number | null;+ output: string;+ indent: boolean;+ logLevel: LogLevel;+ onProgress: (p: number) => void;+ files: string[];+}) => {+ const fileList = files.map((p) => `file '${p}'`).join('\n');++ const fileListTxt = join(filelistDir, 'video-files.txt');+ writeFileSync(fileListTxt, fileList);++ const command = [+ '-r',+ String(fps),+ '-f',+ 'concat',+ '-safe',+ '0',+ '-i',+ fileListTxt,+ numberOfGifLoops === null ? null : '-loop',+ numberOfGifLoops === null+ ? null+ : convertNumberOfGifLoopsToFfmpegSyntax(numberOfGifLoops),+ '-an',+ '-c:v',+ codec === 'gif' ? 'gif' : 'copy',+ codec === 'h264' ? '-movflags' : null,+ codec === 'h264' ? 'faststart' : null,+ `-metadata`,+ `comment=Made with Remotion ${VERSION}`,+ '-y',+ output,+ ].filter(truthy);++ try {+ const task = callFf({+ args: command,+ bin: 'ffmpeg',+ indent,+ logLevel,+ });+ task.stderr?.on('data', (data: Buffer) => {+ const parsed = parseFfmpegProgress(data.toString('utf8'));+ if (parsed === undefined) {+ Log.verbose({indent, logLevel}, data.toString('utf8'));+ } else {+ Log.verbose({indent, logLevel}, `Encoded ${parsed} video frames`);+ onProgress(parsed);+ }+ });+ await task;+ return output;+ } catch (e) {+ rmSync(filelistDir, {recursive: true});+ throw e;+ }+};diff --git a/packages/renderer/src/combine-videos.ts b/packages/renderer/src/combine-videos.tsindex 936e328487..fc5d920f9a 100644--- a/packages/renderer/src/combine-videos.ts+++ b/packages/renderer/src/combine-videos.ts@@ -1,16 +1,14 @@// Combine multiple video chunks, useful for decentralized rendering-import {rmSync, writeFileSync} from 'node:fs';+import {rmSync} from 'node:fs';import {join} from 'node:path';import {VERSION} from 'remotion/version';import type {AudioCodec} from './audio-codec';-import {- getDefaultAudioCodec,- mapAudioCodecToFfmpegAudioCodecName,-} from './audio-codec';+import {getDefaultAudioCodec} from './audio-codec';import {callFf} from './call-ffmpeg';import type {Codec} from './codec';-import {convertNumberOfGifLoopsToFfmpegSyntax} from './convert-number-of-gif-loops-to-ffmpeg';+import {createCombinedAudio} from './combine-audio';+import {combineVideoStreams} from './combine-video-streams';import {isAudioCodec} from './is-audio-codec';import type {LogLevel} from './log-level';import {Log} from './logger';@@ -30,6 +28,7 @@ type Options = {audioBitrate: string | null;indent: boolean;logLevel: LogLevel;+ chunkDurationInSeconds: number;};export const combineVideos = async (options: Options) => {@@ -46,40 +45,55 @@ export const combineVideos = async (options: Options) => {audioBitrate,indent,logLevel,+ chunkDurationInSeconds,} = options;- const fileList = files.map((p) => `file '${p}'`).join('\n');- const fileListTxt = join(filelistDir, 'files.txt');- writeFileSync(fileListTxt, fileList);+ const audioOutput = join(filelistDir, 'audio');+ const videoOutput = join(filelistDir, 'video');const resolvedAudioCodec =audioCodec ?? getDefaultAudioCodec({codec, preferLossless: false});+ const shouldCreateAudio = resolvedAudioCodec !== null;+ const shouldCreateVideo = !isAudioCodec(codec);++ if (shouldCreateAudio) {+ await createCombinedAudio({+ audioBitrate,+ filelistDir,+ files,+ indent,+ logLevel,+ output: audioOutput,+ resolvedAudioCodec,+ seamless: resolvedAudioCodec === 'aac',+ chunkDurationInSeconds,+ });+ }++ if (shouldCreateVideo) {+ await combineVideoStreams({+ codec,+ filelistDir,+ fps,+ indent,+ logLevel,+ numberOfGifLoops,+ onProgress,+ output: videoOutput,+ files,+ });+ }+const command = [- isAudioCodec(codec) ? null : '-r',- isAudioCodec(codec) ? null : String(fps),- '-f',- 'concat',- '-safe',- '0','-i',- fileListTxt,- numberOfGifLoops === null ? null : '-loop',- numberOfGifLoops === null- ? null- : convertNumberOfGifLoopsToFfmpegSyntax(numberOfGifLoops),- isAudioCodec(codec) ? null : '-c:v',- isAudioCodec(codec) ? null : codec === 'gif' ? 'gif' : 'copy',- resolvedAudioCodec ? '-c:a' : null,- resolvedAudioCodec- ? mapAudioCodecToFfmpegAudioCodecName(resolvedAudioCodec)- : null,- resolvedAudioCodec === 'aac' ? '-cutoff' : null,- resolvedAudioCodec === 'aac' ? '18000' : null,- '-b:a',- audioBitrate ? audioBitrate : '320k',- codec === 'h264' ? '-movflags' : null,- codec === 'h264' ? 'faststart' : null,+ videoOutput,+ '-i',+ audioOutput,+ '-c:v',+ 'copy',+ '-c:a',+ 'copy',`-metadata`,`comment=Made with Remotion ${VERSION}`,'-y',@@ -96,14 +110,12 @@ export const combineVideos = async (options: Options) => {logLevel: options.logLevel,});task.stderr?.on('data', (data: Buffer) => {- if (onProgress) {- const parsed = parseFfmpegProgress(data.toString('utf8'));- if (parsed === undefined) {- Log.verbose({indent, logLevel}, data.toString('utf8'));- } else {- Log.verbose({indent, logLevel}, `Combined ${parsed} frames`);- onProgress(parsed);- }+ const parsed = parseFfmpegProgress(data.toString('utf8'));+ if (parsed === undefined) {+ Log.verbose({indent, logLevel}, data.toString('utf8'));+ } else {+ Log.verbose({indent, logLevel}, `Combined ${parsed} frames`);+ onProgress(parsed);}});