🎥 Make videos programmatically with React
`@remotion/webcodecs`: Dynamically calculate how big the MP4 header should be
Jonny Burgerbc78131e0e54
diff --git a/packages/convert/app/components/ConvertUi.tsx b/packages/convert/app/components/ConvertUi.tsxindex cb7e36def5..6f6bfc37ca 100644--- a/packages/convert/app/components/ConvertUi.tsx+++ b/packages/convert/app/components/ConvertUi.tsx@@ -58,7 +58,7 @@ const ConvertUI = ({currentVideoCodec,tracks,setSrc,- duration,+ durationInSeconds,logLevel,action,enableRotateOrMirror,@@ -84,7 +84,7 @@ const ConvertUI = ({readonly videoThumbnailRef: React.RefObject<VideoThumbnailRef | null>;readonly unrotatedDimensions: Dimensions | null;readonly dimensions: Dimensions | null | undefined;- readonly duration: number | null;+ readonly durationInSeconds: number | null;readonly rotation: number | null;readonly inputContainer: MediaParserContainer | null;readonly logLevel: LogLevel;@@ -184,8 +184,8 @@ const ConvertUI = ({const waveform = makeWaveformVisualizer({onWaveformBars,});- if (duration) {- waveform.setDuration(duration);+ if (durationInSeconds) {+ waveform.setDuration(durationInSeconds);}convertMedia({@@ -207,6 +207,7 @@ const ConvertUI = ({waveform.add(audioData);return audioData;},+ expectedDurationInSeconds: durationInSeconds,rotate: userRotation,logLevel,onProgress: (s) => {@@ -307,7 +308,7 @@ const ConvertUI = ({};}, [onWaveformBars,- duration,+ durationInSeconds,src,userRotation,logLevel,@@ -409,7 +410,7 @@ const ConvertUI = ({name={name}container={outputContainer}done={false}- duration={duration}+ duration={durationInSeconds}isReencoding={supportedConfigs !== null &&isReencoding({@@ -435,7 +436,7 @@ const ConvertUI = ({state={state.state}name={name}container={outputContainer}- duration={duration}+ duration={durationInSeconds}isReencoding={supportedConfigs !== null &&isReencoding({diff --git a/packages/convert/app/components/FileAvailable.tsx b/packages/convert/app/components/FileAvailable.tsxindex 01539eb421..8ef2ed8630 100644--- a/packages/convert/app/components/FileAvailable.tsx+++ b/packages/convert/app/components/FileAvailable.tsx@@ -102,7 +102,7 @@ export const FileAvailable: React.FC<{setSrc={setSrc}unrotatedDimensions={probeResult.unrotatedDimensions}dimensions={probeResult.dimensions}- duration={probeResult.durationInSeconds ?? null}+ durationInSeconds={probeResult.durationInSeconds ?? null}logLevel="verbose"action={routeAction}enableRotateOrMirror={enableRotateOrMirrow}diff --git a/packages/docs/docs/webcodecs/convert-media.mdx b/packages/docs/docs/webcodecs/convert-media.mdxindex 5f3c4672fb..81f2453104 100644--- a/packages/docs/docs/webcodecs/convert-media.mdx+++ b/packages/docs/docs/webcodecs/convert-media.mdx@@ -47,6 +47,14 @@ _string_ <TsType type="ConvertMediaContainer" source="@remotion/webcodecs"/>The container format to convert to. Currently, `"mp4"`, `"webm"` and `"wav"` is supported.+### `expectedDurationInSeconds?`++_number_++Pass the expected duration of the output video in seconds, so that the size of the MP4 metadata section can be estimated well. If the value is not passed, 2MB will be allocated for the MP4 metadata section.++If the size is exceeded (for videos which are around 1 hour or longer), the render may fail in the end.+### `videoCodec?`_string_ <TsType type="ConvertMediaVideoCodec" source="@remotion/webcodecs"/>diff --git a/packages/webcodecs/src/convert-media.ts b/packages/webcodecs/src/convert-media.tsindex 741f69c806..e3ec82e2cc 100644--- a/packages/webcodecs/src/convert-media.ts+++ b/packages/webcodecs/src/convert-media.ts@@ -129,6 +129,7 @@ export const convertMedia = async function <onM3uStreams,selectM3uStream,selectM3uAssociatedPlaylists,+ expectedDurationInSeconds,...more}: {src: ParseMediaOptions<F>['src'];@@ -143,6 +144,7 @@ export const convertMedia = async function <onVideoTrack?: ConvertMediaOnVideoTrackHandler;selectM3uStream?: ParseMediaOptions<F>['selectM3uStream'];selectM3uAssociatedPlaylists?: ParseMediaOptions<F>['selectM3uAssociatedPlaylists'];+ expectedDurationInSeconds?: number | null;reader?: ParseMediaOptions<F>['reader'];logLevel?: LogLevel;writer?: WriterInterface;@@ -228,6 +230,7 @@ export const convertMedia = async function <},logLevel,progressTracker,+ expectedDurationInSeconds: expectedDurationInSeconds ?? null,});const onVideoTrack: OnVideoTrack = makeVideoTrackHandler({diff --git a/packages/webcodecs/src/create/iso-base-media/create-iso-base-media.ts b/packages/webcodecs/src/create/iso-base-media/create-iso-base-media.tsindex e6d1567fdb..61031bc8e4 100644--- a/packages/webcodecs/src/create/iso-base-media/create-iso-base-media.ts+++ b/packages/webcodecs/src/create/iso-base-media/create-iso-base-media.ts@@ -19,6 +19,7 @@ export const createIsoBaseMedia = async ({logLevel,filename,progressTracker,+ expectedDurationInSeconds,}: MediaFnGeneratorInput): Promise<MediaFn> => {const header = createIsoBaseMediaFtyp({compatibleBrands: ['isom', 'iso2', 'avc1', 'mp42'],@@ -54,6 +55,8 @@ export const createIsoBaseMedia = async ({};}),timescale: CONTAINER_TIMESCALE,+ expectedDurationInSeconds,+ logLevel,});};diff --git a/packages/webcodecs/src/create/iso-base-media/header-length.ts b/packages/webcodecs/src/create/iso-base-media/header-length.tsnew file mode 100644index 0000000000..63e047691b--- /dev/null+++ b/packages/webcodecs/src/create/iso-base-media/header-length.ts@@ -0,0 +1,27 @@+export const calculateAReasonableMp4HeaderLength = (+ expectedDurationInSeconds: number | null,+) => {+ if (expectedDurationInSeconds === null) {+ return 2048_000;+ }++ /**+ * we had a video that was 1 hour 40 minutes long and the header ended up being 3.7MB. the header approximately grows linearly to the video length in seconds, but we should reserve enough, like at least 50KB in any case.+ * it's better to be safe than to fail, so let's add a 30% safety margin+ */++ // 1h40m = 6000 seconds resulted in 3.7MB header+ // So bytes per second = 3.7MB / 6000 = ~616 bytes/second+ const bytesPerSecond = (3.7 * 1024 * 1024) / 6000;++ // Add 20% safety margin+ const bytesWithSafetyMargin = bytesPerSecond * 1.2;++ // Calculate based on duration, with minimum 50KB+ const calculatedBytes = Math.max(+ 50 * 1024,+ Math.ceil(expectedDurationInSeconds * bytesWithSafetyMargin),+ );++ return calculatedBytes;+};diff --git a/packages/webcodecs/src/create/iso-base-media/mp4-header.ts b/packages/webcodecs/src/create/iso-base-media/mp4-header.tsindex af08629bbe..6322995a98 100644--- a/packages/webcodecs/src/create/iso-base-media/mp4-header.ts+++ b/packages/webcodecs/src/create/iso-base-media/mp4-header.ts@@ -1,8 +1,11 @@+import type {LogLevel} from '@remotion/media-parser';import {VERSION} from '@remotion/media-parser';+import {Log} from '../../log';import {createIlst} from './create-ilst';import {createMoov} from './create-moov';import {createMvhd} from './create-mvhd';import {createUdta} from './create-udta';+import {calculateAReasonableMp4HeaderLength} from './header-length';import {createCmt} from './ilst/create-cmt';import {createToo} from './ilst/create-too';import {IDENTITY_MATRIX, padIsoBaseMediaBytes} from './primitives';@@ -11,18 +14,34 @@ import {serializeTrack} from './serialize-track';import {createMeta} from './udta/create-meta';import {createHdlr} from './udta/meta/create-hdlr';-// TODO: Creates a header that is way too large-const HEADER_LENGTH = 2048_000;-export const createPaddedMoovAtom = ({durationInUnits,trackInfo,timescale,+ expectedDurationInSeconds,+ logLevel,}: {durationInUnits: number;trackInfo: IsoBaseMediaTrackData[];timescale: number;+ expectedDurationInSeconds: number | null;+ logLevel: LogLevel;}) => {+ const headerLength = calculateAReasonableMp4HeaderLength(+ expectedDurationInSeconds,+ );+ if (expectedDurationInSeconds !== null) {+ Log.verbose(+ logLevel,+ `Expecting duration of the video to be ${expectedDurationInSeconds} seconds, allocating ${headerLength} bytes for the MP4 header.`,+ );+ } else {+ Log.verbose(+ logLevel,+ `No duration was provided, allocating ${headerLength} bytes for the MP4 header.`,+ );+ }+return padIsoBaseMediaBytes(createMoov({mvhd: createMvhd({@@ -56,6 +75,6 @@ export const createPaddedMoovAtom = ({}),),}),- HEADER_LENGTH,+ headerLength,);};diff --git a/packages/webcodecs/src/create/iso-base-media/primitives.ts b/packages/webcodecs/src/create/iso-base-media/primitives.tsindex 49c0b344e9..71a21e11c8 100644--- a/packages/webcodecs/src/create/iso-base-media/primitives.ts+++ b/packages/webcodecs/src/create/iso-base-media/primitives.ts@@ -125,7 +125,7 @@ export const stringToPascalString = (str: string) => {export const padIsoBaseMediaBytes = (data: Uint8Array, totalLength: number) => {if (data.length - 8 > totalLength) {throw new Error(- `Data is longer than the total length: ${data.length - 8} > ${totalLength}`,+ `Data is longer than the total length: ${data.length - 8} > ${totalLength}. Set the 'expectedDurationInSeconds' value to avoid this problem: https://www.remotion.dev/docs/webcodecs/convert-media#expecteddurationinseconds`,);}diff --git a/packages/webcodecs/src/create/media-fn.ts b/packages/webcodecs/src/create/media-fn.tsindex fb7c453115..45176649cb 100644--- a/packages/webcodecs/src/create/media-fn.ts+++ b/packages/webcodecs/src/create/media-fn.ts@@ -32,4 +32,5 @@ export type MediaFnGeneratorInput = {logLevel: LogLevel;filename: string;progressTracker: ProgressTracker;+ expectedDurationInSeconds: number | null;};diff --git a/packages/webcodecs/src/test/mp4-header-length.test.ts b/packages/webcodecs/src/test/mp4-header-length.test.tsnew file mode 100644index 0000000000..f1a478970b--- /dev/null+++ b/packages/webcodecs/src/test/mp4-header-length.test.ts@@ -0,0 +1,12 @@+import {expect, test} from 'bun:test';+import {calculateAReasonableMp4HeaderLength} from '../create/iso-base-media/header-length';++test('should calculate good header length', () => {+ const result = calculateAReasonableMp4HeaderLength(60 * 110);+ expect(result).toBe(5121246);+});++test('should calculate good header length for null', () => {+ const result = calculateAReasonableMp4HeaderLength(0);+ expect(result).toBe(51200);+});