Skip to content

🎥 Make videos programmatically with React

`@remotion/webcodecs`: Better estimate MP4 header section based on expected frame rate

Jonny Burger47418902d6c1
diff --git a/packages/convert/app/components/ConvertUi.tsx b/packages/convert/app/components/ConvertUi.tsx
index e63102f464..6effc6b092 100644
--- a/packages/convert/app/components/ConvertUi.tsx
+++ b/packages/convert/app/components/ConvertUi.tsx
@@ -61,6 +61,7 @@ const ConvertUI = ({
tracks,
setSrc,
durationInSeconds,
+ fps,
logLevel,
action,
enableRotateOrMirror,
@@ -88,6 +89,7 @@ const ConvertUI = ({
readonly unrotatedDimensions: Dimensions | null;
readonly dimensions: Dimensions | null | undefined;
readonly durationInSeconds: number | null;
+ readonly fps: number | null;
readonly rotation: number | null;
readonly inputContainer: MediaParserContainer | null;
readonly logLevel: LogLevel;
@@ -237,6 +239,7 @@ const ConvertUI = ({
return audioData;
},
expectedDurationInSeconds: durationInSeconds,
+ expectedFrameRate: fps,
rotate: userRotation,
logLevel,
onProgress: (s) => {
@@ -339,6 +342,7 @@ const ConvertUI = ({
}, [
onWaveformBars,
durationInSeconds,
+ fps,
src,
userRotation,
logLevel,
diff --git a/packages/convert/app/components/FileAvailable.tsx b/packages/convert/app/components/FileAvailable.tsx
index 2c670d4d39..95cb81c3d3 100644
--- a/packages/convert/app/components/FileAvailable.tsx
+++ b/packages/convert/app/components/FileAvailable.tsx
@@ -103,6 +103,7 @@ export const FileAvailable: React.FC<{
unrotatedDimensions={probeResult.unrotatedDimensions}
dimensions={probeResult.dimensions}
durationInSeconds={probeResult.durationInSeconds ?? null}
+ fps={probeResult.fps ?? null}
logLevel="verbose"
action={routeAction}
enableRotateOrMirror={enableRotateOrMirrow}
diff --git a/packages/convert/app/components/LoadFromUrl.tsx b/packages/convert/app/components/LoadFromUrl.tsx
index afc8b6f39b..220c736b37 100644
--- a/packages/convert/app/components/LoadFromUrl.tsx
+++ b/packages/convert/app/components/LoadFromUrl.tsx
@@ -32,7 +32,10 @@ export const LoadFromUrl: React.FC = () => {
}, []);
const set = useCallback(() => {
- const currentUrl = new URL(window.location.href);
+ const currentUrl = new URL(
+ window.location.pathname === '/' ? '/convert' : window.location.pathname,
+ window.location.href,
+ );
currentUrl.searchParams.set('url', value);
window.location.href = currentUrl.toString();
}, [value]);
diff --git a/packages/convert/app/components/VideoOperationOption.tsx b/packages/convert/app/components/VideoOperationOption.tsx
index 15edf2e9e4..8e31b51f1f 100644
--- a/packages/convert/app/components/VideoOperationOption.tsx
+++ b/packages/convert/app/components/VideoOperationOption.tsx
@@ -12,7 +12,7 @@ export const VideoOperationOption: React.FC<{
if (operation.type === 'copy') {
if (!currentVideoCodec) {
- throw new Error('No current video codec');
+ return `Copy without re-encoding`;
}
return `Copy ${renderHumanReadableVideoCodec(currentVideoCodec)} without re-encoding`;
diff --git a/packages/docs/docs/webcodecs/convert-media.mdx b/packages/docs/docs/webcodecs/convert-media.mdx
index 67a016f5f7..43e97a829b 100644
--- a/packages/docs/docs/webcodecs/convert-media.mdx
+++ b/packages/docs/docs/webcodecs/convert-media.mdx
@@ -55,6 +55,12 @@ Pass the expected duration of the output video in seconds, so that the size of t
If the size is exceeded (for videos which are around 1 hour or longer), the render may fail in the end.
+### `expectedFrameRate?`
+
+_number_
+
+Pass the expected frame rate of the output video, so that the size of the MP4 metadata section can be estimated well. If the value is not passed, 60 will be used as a conservative fallback.
+
### `videoCodec?`
_string_ <TsType type="ConvertMediaVideoCodec" source="@remotion/webcodecs"/>
diff --git a/packages/webcodecs/src/can-reencode-video-track.ts b/packages/webcodecs/src/can-reencode-video-track.ts
index e9082783f1..057e7f94b4 100644
--- a/packages/webcodecs/src/can-reencode-video-track.ts
+++ b/packages/webcodecs/src/can-reencode-video-track.ts
@@ -31,6 +31,7 @@ export const canReencodeVideoTrack = async ({
});
const videoDecoderConfig =
await getVideoDecoderConfigWithHardwareAcceleration(track);
+ console.log({videoEncoderConfig, videoDecoderConfig});
return Boolean(videoDecoderConfig && videoEncoderConfig);
};
diff --git a/packages/webcodecs/src/convert-media.ts b/packages/webcodecs/src/convert-media.ts
index 152a1304ea..0c6eff4d8a 100644
--- a/packages/webcodecs/src/convert-media.ts
+++ b/packages/webcodecs/src/convert-media.ts
@@ -130,6 +130,7 @@ export const convertMedia = async function <
selectM3uStream,
selectM3uAssociatedPlaylists,
expectedDurationInSeconds,
+ expectedFrameRate,
seekingHints,
...more
}: {
@@ -146,6 +147,7 @@ export const convertMedia = async function <
selectM3uStream?: ParseMediaOptions<F>['selectM3uStream'];
selectM3uAssociatedPlaylists?: ParseMediaOptions<F>['selectM3uAssociatedPlaylists'];
expectedDurationInSeconds?: number | null;
+ expectedFrameRate?: number | null;
reader?: ParseMediaOptions<F>['reader'];
logLevel?: LogLevel;
writer?: WriterInterface;
@@ -233,6 +235,7 @@ export const convertMedia = async function <
logLevel,
progressTracker,
expectedDurationInSeconds: expectedDurationInSeconds ?? null,
+ expectedFrameRate: expectedFrameRate ?? 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.ts
index 67767dc1b5..54e57737cd 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
@@ -20,6 +20,7 @@ export const createIsoBaseMedia = async ({
filename,
progressTracker,
expectedDurationInSeconds,
+ expectedFrameRate,
}: MediaFnGeneratorInput): Promise<MediaFn> => {
const header = createIsoBaseMediaFtyp({
compatibleBrands: ['isom', 'iso2', 'avc1', 'mp42'],
@@ -57,6 +58,7 @@ export const createIsoBaseMedia = async ({
timescale: CONTAINER_TIMESCALE,
expectedDurationInSeconds,
logLevel,
+ expectedFrameRate,
});
};
diff --git a/packages/webcodecs/src/create/iso-base-media/header-length.ts b/packages/webcodecs/src/create/iso-base-media/header-length.ts
index 63e047691b..a6bd24f520 100644
--- a/packages/webcodecs/src/create/iso-base-media/header-length.ts
+++ b/packages/webcodecs/src/create/iso-base-media/header-length.ts
@@ -1,6 +1,10 @@
-export const calculateAReasonableMp4HeaderLength = (
- expectedDurationInSeconds: number | null,
-) => {
+export const calculateAReasonableMp4HeaderLength = ({
+ expectedDurationInSeconds,
+ expectedFrameRate,
+}: {
+ expectedDurationInSeconds: number | null;
+ expectedFrameRate: number | null;
+}) => {
if (expectedDurationInSeconds === null) {
return 2048_000;
}
@@ -10,12 +14,17 @@ export const calculateAReasonableMp4HeaderLength = (
* it's better to be safe than to fail, so let's add a 30% safety margin
*/
+ // This was however with 30fps, and there can also be 60fps videos, so let's
+ // estimate even more conservatively and estimate 60fps
+ const assumedFrameRate = expectedFrameRate ?? 60;
+ const frameRateMultiplier = assumedFrameRate / 30;
+
// 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;
+ // Add 20% safety margin and multiply by frame rate multiplier
+ const bytesWithSafetyMargin = bytesPerSecond * 1.2 * frameRateMultiplier;
// Calculate based on duration, with minimum 50KB
const calculatedBytes = Math.max(
diff --git a/packages/webcodecs/src/create/iso-base-media/mp4-header.ts b/packages/webcodecs/src/create/iso-base-media/mp4-header.ts
index 6322995a98..72a6c45255 100644
--- a/packages/webcodecs/src/create/iso-base-media/mp4-header.ts
+++ b/packages/webcodecs/src/create/iso-base-media/mp4-header.ts
@@ -20,16 +20,19 @@ export const createPaddedMoovAtom = ({
timescale,
expectedDurationInSeconds,
logLevel,
+ expectedFrameRate,
}: {
durationInUnits: number;
trackInfo: IsoBaseMediaTrackData[];
timescale: number;
expectedDurationInSeconds: number | null;
logLevel: LogLevel;
+ expectedFrameRate: number | null;
}) => {
- const headerLength = calculateAReasonableMp4HeaderLength(
+ const headerLength = calculateAReasonableMp4HeaderLength({
expectedDurationInSeconds,
- );
+ expectedFrameRate,
+ });
if (expectedDurationInSeconds !== null) {
Log.verbose(
logLevel,
diff --git a/packages/webcodecs/src/create/media-fn.ts b/packages/webcodecs/src/create/media-fn.ts
index 45176649cb..380b29796a 100644
--- a/packages/webcodecs/src/create/media-fn.ts
+++ b/packages/webcodecs/src/create/media-fn.ts
@@ -33,4 +33,5 @@ export type MediaFnGeneratorInput = {
filename: string;
progressTracker: ProgressTracker;
expectedDurationInSeconds: number | null;
+ expectedFrameRate: number | null;
};
diff --git a/packages/webcodecs/src/get-codec-string.ts b/packages/webcodecs/src/get-codec-string.ts
index 45a9fb958c..829cad8ad8 100644
--- a/packages/webcodecs/src/get-codec-string.ts
+++ b/packages/webcodecs/src/get-codec-string.ts
@@ -13,8 +13,10 @@ export const getCodecStringForEncoder = ({
height: number;
width: number;
}) => {
+ console.log(chooseCorrectAvc1Profile({fps, height, width}));
if (codec === 'h264') {
- return chooseCorrectAvc1Profile({fps, height, width});
+ return 'avc1.640033';
+ // return chooseCorrectAvc1Profile({fps, height, width});
}
if (codec === 'h265') {
diff --git a/packages/webcodecs/src/test/mp4-header-length.test.ts b/packages/webcodecs/src/test/mp4-header-length.test.ts
index f1a478970b..4024044cf0 100644
--- a/packages/webcodecs/src/test/mp4-header-length.test.ts
+++ b/packages/webcodecs/src/test/mp4-header-length.test.ts
@@ -2,11 +2,25 @@ 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);
+ const result = calculateAReasonableMp4HeaderLength({
+ expectedDurationInSeconds: 60 * 110,
+ expectedFrameRate: 30,
+ });
expect(result).toBe(5121246);
});
+test('should calculate good header length if no fps is provided', () => {
+ const result = calculateAReasonableMp4HeaderLength({
+ expectedDurationInSeconds: 60 * 110,
+ expectedFrameRate: null,
+ });
+ expect(result).toBe(5121246 * 2 - 1);
+});
+
test('should calculate good header length for null', () => {
- const result = calculateAReasonableMp4HeaderLength(0);
+ const result = calculateAReasonableMp4HeaderLength({
+ expectedDurationInSeconds: 0,
+ expectedFrameRate: 60,
+ });
expect(result).toBe(51200);
});