🎥 Make videos programmatically with React
Docs: Use Mediabunny frame rate metrics (#10692)
Jonny Burger9e7bd22084a5
diff --git a/packages/docs/docs/dynamic-metadata.mdx b/packages/docs/docs/dynamic-metadata.mdxindex d7237537c9..96cfd95425 100644--- a/packages/docs/docs/dynamic-metadata.mdx+++ b/packages/docs/docs/dynamic-metadata.mdx@@ -15,24 +15,9 @@ Consider a scenario where a video is dynamically specified as a background and tPass a [`calculateMetadata`](/docs/composition#calculatemetadata) callback function to a [`<Composition>`](/docs/composition). This function should take the [combined props](/docs/props-resolution) and calculate the metadata.-```twoslash include dynamic-metadata-frame-rate-helper-// @filename: get-video-frame-rate.ts-import type {Input} from 'mediabunny';--export type VideoFrameRate =- | {type: 'constant'; rate: number}- | {type: 'variable'; max: number; average: number};--export declare const getVideoFrameRate: (- input: Input,-) => Promise<VideoFrameRate | null>;-```-```tsx twoslash title="src/Root.tsx"-// @include: dynamic-metadata-frame-rate-helper// @filename: get-media-metadata.tsimport {Input, ALL_FORMATS, UrlSource} from 'mediabunny';-import {getVideoFrameRate} from './get-video-frame-rate';export const getMediaMetadata = async (src: string) => {const input = new Input({@@ -50,13 +35,13 @@ export const getMediaMetadata = async (src: string) => {height: videoTrack.displayHeight,}: null;- const frameRate = await getVideoFrameRate(input);+ const frameRateMetrics = videoTrack+ ? await videoTrack.computeFrameRateMetrics()+ : null;const fps =- frameRate === null+ frameRateMetrics === null || frameRateMetrics.probedPacketCount < 2? null- : frameRate.type === 'constant'- ? frameRate.rate- : frameRate.max;+ : frameRateMetrics.bestGuessFrameRate;return {durationInSeconds,@@ -110,7 +95,7 @@ export const Root: React.FC = () => {:::noteSee [Getting metadata using Mediabunny](/docs/mediabunny/metadata) for the snippet for `get-media-metadata.ts`.-It uses the [`getVideoFrameRate()` helper](/docs/mediabunny/frame-rate) to match the composition FPS to the source video.+It uses Mediabunny's [`computeFrameRateMetrics()`](https://mediabunny.dev/api/InputVideoTrack#computeframeratemetrics) method to match the composition FPS to the source video.:::The `props` defaults to the `defaultProps` specified, but may be overriden by [passing input props to the render](/docs/props-resolution).@@ -127,10 +112,8 @@ In the following example, Remotion is instructed to wait for the [`getMediaMetadBy calling [`delayRender()`](/docs/delay-render), Remotion will be blocked from proceeding until [`continueRender()`](/docs/continue-render) is called.```tsx twoslash title="src/Root.tsx"-// @include: dynamic-metadata-frame-rate-helper// @filename: get-media-metadata.tsimport {Input, ALL_FORMATS, UrlSource} from 'mediabunny';-import {getVideoFrameRate} from './get-video-frame-rate';export const getMediaMetadata = async (src: string) => {const input = new Input({@@ -148,13 +131,13 @@ export const getMediaMetadata = async (src: string) => {height: videoTrack.displayHeight,}: null;- const frameRate = await getVideoFrameRate(input);+ const frameRateMetrics = videoTrack+ ? await videoTrack.computeFrameRateMetrics()+ : null;const fps =- frameRate === null+ frameRateMetrics === null || frameRateMetrics.probedPacketCount < 2? null- : frameRate.type === 'constant'- ? frameRate.rate- : frameRate.max;+ : frameRateMetrics.bestGuessFrameRate;return {durationInSeconds,@@ -238,10 +221,8 @@ The [`<Player>`](/docs/player) will react if the metadata being passed to it cha</p>```tsx twoslash title="MyApp.tsx"-// @include: dynamic-metadata-frame-rate-helper// @filename: get-media-metadata.tsimport {Input, ALL_FORMATS, UrlSource} from 'mediabunny';-import {getVideoFrameRate} from './get-video-frame-rate';export const getMediaMetadata = async (src: string) => {const input = new Input({@@ -259,13 +240,13 @@ export const getMediaMetadata = async (src: string) => {height: videoTrack.displayHeight,}: null;- const frameRate = await getVideoFrameRate(input);+ const frameRateMetrics = videoTrack+ ? await videoTrack.computeFrameRateMetrics()+ : null;const fps =- frameRate === null+ frameRateMetrics === null || frameRateMetrics.probedPacketCount < 2? null- : frameRate.type === 'constant'- ? frameRate.rate- : frameRate.max;+ : frameRateMetrics.bestGuessFrameRate;return {durationInSeconds,diff --git a/packages/docs/docs/lambda/cost-example.mdx b/packages/docs/docs/lambda/cost-example.mdxindex d2ea37e553..d1ede6c75c 100644--- a/packages/docs/docs/lambda/cost-example.mdx+++ b/packages/docs/docs/lambda/cost-example.mdx@@ -27,26 +27,11 @@ Rendering the [`HelloWorld`](https://github.com/remotion-dev/template-helloworld## Rendering a 1 minute Video in the same S3 bucket-The video examples use the [`getVideoFrameRate()` helper](/docs/mediabunny/frame-rate) to account for constant and variable frame rate videos.--```twoslash include lambda-frame-rate-helper-// @filename: get-video-frame-rate.ts-import type {Input} from 'mediabunny';--export type VideoFrameRate =- | {type: 'constant'; rate: number}- | {type: 'variable'; max: number; average: number};--export declare const getVideoFrameRate: (- input: Input,-) => Promise<VideoFrameRate | null>;-```+The video examples use Mediabunny's [`computeFrameRateMetrics()`](https://mediabunny.dev/api/InputVideoTrack#computeframeratemetrics) method to account for constant and variable frame rate videos.```tsx twoslash title="OffthreadRemoteVideo.tsx"-// @include: lambda-frame-rate-helper// @filename: get-media-metadata.tsimport {Input, ALL_FORMATS, UrlSource} from 'mediabunny';-import {getVideoFrameRate} from './get-video-frame-rate';export const getMediaMetadata = async (src: string) => {const input = new Input({@@ -64,13 +49,13 @@ export const getMediaMetadata = async (src: string) => {height: videoTrack.displayHeight,}: null;- const frameRate = await getVideoFrameRate(input);+ const frameRateMetrics = videoTrack+ ? await videoTrack.computeFrameRateMetrics()+ : null;const fps =- frameRate === null+ frameRateMetrics === null || frameRateMetrics.probedPacketCount < 2? null- : frameRate.type === 'constant'- ? frameRate.rate- : frameRate.max;+ : frameRateMetrics.bestGuessFrameRate;return {durationInSeconds,@@ -123,10 +108,8 @@ Rendering a video inside your video increases the cost significantly.## Rendering a 10 minute Remote HD Video```tsx twoslash title="OffthreadRemoteVideo.tsx"-// @include: lambda-frame-rate-helper// @filename: get-media-metadata.tsimport {Input, ALL_FORMATS, UrlSource} from 'mediabunny';-import {getVideoFrameRate} from './get-video-frame-rate';export const getMediaMetadata = async (src: string) => {const input = new Input({@@ -144,13 +127,13 @@ export const getMediaMetadata = async (src: string) => {height: videoTrack.displayHeight,}: null;- const frameRate = await getVideoFrameRate(input);+ const frameRateMetrics = videoTrack+ ? await videoTrack.computeFrameRateMetrics()+ : null;const fps =- frameRate === null+ frameRateMetrics === null || frameRateMetrics.probedPacketCount < 2? null- : frameRate.type === 'constant'- ? frameRate.rate- : frameRate.max;+ : frameRateMetrics.bestGuessFrameRate;return {durationInSeconds,@@ -199,10 +182,8 @@ export const NewVideoComp = () => {## Rendering a 10 second Remote 4K Video```tsx twoslash title="OffthreadRemoteVideo.tsx"-// @include: lambda-frame-rate-helper// @filename: get-media-metadata.tsimport {Input, ALL_FORMATS, UrlSource} from 'mediabunny';-import {getVideoFrameRate} from './get-video-frame-rate';export const getMediaMetadata = async (src: string) => {const input = new Input({@@ -220,13 +201,13 @@ export const getMediaMetadata = async (src: string) => {height: videoTrack.displayHeight,}: null;- const frameRate = await getVideoFrameRate(input);+ const frameRateMetrics = videoTrack+ ? await videoTrack.computeFrameRateMetrics()+ : null;const fps =- frameRate === null+ frameRateMetrics === null || frameRateMetrics.probedPacketCount < 2? null- : frameRate.type === 'constant'- ? frameRate.rate- : frameRate.max;+ : frameRateMetrics.bestGuessFrameRate;return {durationInSeconds,diff --git a/packages/docs/docs/mediabunny/frame-rate.mdx b/packages/docs/docs/mediabunny/frame-rate.mdxindex e9d8c7d85b..bc1cc0b8c2 100644--- a/packages/docs/docs/mediabunny/frame-rate.mdx+++ b/packages/docs/docs/mediabunny/frame-rate.mdx@@ -14,122 +14,30 @@ Videos can have one of two types of frame rates:## Getting the frame rate using Mediabunny-Use [Mediabunny](https://mediabunny.dev) to determine the frame rate of a video.--There is no native method to determine whether a video has a variable frame rate, but you can probe it by reading some packets without causing expensive decoding work.--```ts twoslash title="get-video-frame-rate.ts"-import {EncodedPacketSink, Input} from 'mediabunny';--export type VideoFrameRate =- | {- type: 'constant';- rate: number;- }- | {- type: 'variable';- max: number;- average: number;- };--const commonFpsValues = [- 24000 / 1001,- 24,- 25,- 30000 / 1001,- 30,- 50,- 60000 / 1001,- 60,- 120,-];--const snapToCommonFps = (fps: number) => {- return commonFpsValues.find(- (commonFps) => Math.abs(fps - commonFps) < 0.01,- ) ?? fps;-};+Use Mediabunny's [`computeFrameRateMetrics()`](https://mediabunny.dev/api/InputVideoTrack#computeframeratemetrics) method to estimate the frame rate from the video's frame timestamps:-export const getVideoFrameRate = async (- input: Input,-): Promise<VideoFrameRate | null> => {- const videoTrack = await input.getPrimaryVideoTrack();- if (!videoTrack) {- return null;- }+```ts twoslash title="get-frame-rate.ts"+import type {InputVideoTrack} from 'mediabunny';- const packetSampleCount = 121;- const timestamps = new Set<number>();- const sink = new EncodedPacketSink(videoTrack);- let endTimestamp = -Infinity;-- for await (const packet of sink.packets(undefined, undefined, {- metadataOnly: true,- })) {- if (- timestamps.size >= packetSampleCount &&- packet.timestamp >= endTimestamp- ) {- break;- }-- timestamps.add(packet.timestamp);- endTimestamp = Math.max(- endTimestamp,- packet.timestamp + packet.duration,- );- }+const getFrameRate = async (videoTrack: InputVideoTrack) => {+ const metrics = await videoTrack.computeFrameRateMetrics();+ // ^?- if (timestamps.size < 2) {+ if (metrics.probedPacketCount < 2) {return null;}- const sortedTimestamps = [...timestamps].sort((a, b) => a - b);- sortedTimestamps.splice(packetSampleCount);-- const intervals = sortedTimestamps.slice(1).map((timestamp, index) => {- return timestamp - sortedTimestamps[index];- });- const averageInterval =- intervals.reduce((sum, interval) => sum + interval, 0) / intervals.length;- const toleranceInSeconds = 1.01 / 1000;- const intervalSpread = Math.max(...intervals) - Math.min(...intervals);- const isConstant = intervalSpread <= toleranceInSeconds;-- if (isConstant) {- return {- type: 'constant',- rate: snapToCommonFps(1 / averageInterval),- };- }-- return {- type: 'variable',- max: 1 / Math.min(...intervals),- average: 1 / averageInterval,- };+ return metrics.bestGuessFrameRate;};```-Note that:+With [`metrics.frameRateIsConstant`](https://mediabunny.dev/api/FrameRateMetrics#framerateisconstant) you can determine whether the frame rate is constant or variable.-- Video timestamps have limited precision. For example, Matroska timestamps commonly have millisecond precision, leading to uneven timestamps such as `33 ms`, `67 ms`, and `100 ms`.- We still consider this a constant frame rate video, so we allow the intervals to vary by slightly more than one millisecond (also allowing for floating point inaccuracies).-- For the same reason, we snap constant frame rates to common values because the calculation may be slightly off depending on how many packets are read.- You still want a 30 FPS timeline if the calculation returns, for example, 30.003 FPS.-- With too few packet timestamps, some frame rates cannot be distinguished, such as 29.97 and 30 FPS or 59.94 and 60 FPS. We sample 121 packet timestamps to reliably detect these fractional frame rates.-- Mediabunny returns encoded packets in decode order, which may differ from presentation order when a video uses B-frames. The loop may read a few additional packet timestamps to finish the current group before sorting them and keeping the first 121.+[`bestGuessFrameRate`](https://mediabunny.dev/api/FrameRateMetrics#bestguessframerate) is Mediabunny's estimate of the intended frame rate and recommendation for your timeline.<br />+If Mediabunny detects a consistent underlying frame rate, this value is snapped to it.-## Matching a Remotion composition to the frame rate--For constant frame rate videos, it is recommended to align Remotion's timeline frame rate to the source videos you are importing.--Remotion and pretty much every other video editor do not support variable frame rate timelines or outputting variable frame rate videos.-You must specify a constant frame rate for your composition.--Changing the frame rate can be lossy.--To minimize frame loss, set the composition frame rate based on the smallest interval between two frames of the source video.+If [`underlyingFrameRate`](https://mediabunny.dev/api/FrameRateMetrics#underlyingframerate) is `null`, the video has no consistent underlying frame rate.<br />+In this case, [`maxFrameRate`](https://mediabunny.dev/api/FrameRateMetrics#maxframerate) is the highest frame rate measured between two consecutive frames.<details><summary>@@ -141,36 +49,31 @@ Consider a 10-second screen recording where:- For the first 5 seconds there is no movement on the screen- For the next 5 seconds, as the mouse cursor starts moving, frames are written with up to 120 FPS.-A naive implementation would look at Mediabunny's [`averagePacketRate`](https://mediabunny.dev/api/PacketStats#averagepacketrate) and determine that the average FPS is 60.--However, by setting the timeline to 60 FPS, every second frame in the second half of the video will be dropped.+The average frame rate is 60 FPS.<br />+Setting the timeline to 60 FPS would drop every second frame in the second half of the video.</details>-### Usage example+By default, `computeFrameRateMetrics()` probes the first 256 packets. You can change the number using the [`targetPacketCount`](https://mediabunny.dev/api/FrameRateMetricsOptions#targetpacketcount) option. A larger sample can be more representative, but requires reading more of the file.-Use [`calculateMetadata()`](/docs/calculate-metadata) to match the composition FPS to the source video:+## Matching a Remotion composition to the frame rate++Align Remotion's timeline frame rate to the source video's [`bestGuessFrameRate`](https://mediabunny.dev/api/FrameRateMetrics#bestguessframerate).-```twoslash include frame-rate-helper-// @filename: get-video-frame-rate.ts-import type {Input} from 'mediabunny';+Remotion and most other video editors do not support variable frame rate timelines or outputting variable frame rate videos.+You must specify a constant frame rate for your composition.-export type VideoFrameRate =- | {type: 'constant'; rate: number}- | {type: 'variable'; max: number; average: number};+Changing the frame rate is a lossy process.<br />+While `bestGuessFrameRate` does its best to recommend a good frame rate, it may lead to dropped frames.<br />+`maxFrameRate` is an alternative to consider, but may lead to some seriously high frame rate videos if there are just 2 samples which are very close to each other.-export declare const getVideoFrameRate: (- input: Input,-) => Promise<VideoFrameRate | null>;-```+### Usage example++Use [`calculateMetadata()`](/docs/calculate-metadata) to match the composition FPS to the source video:```ts twoslash title="calculate-metadata.ts"-// @include: frame-rate-helper-// @filename: calculate-metadata.ts-// ---cut---import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';import type {CalculateMetadataFunction} from 'remotion';-import {getVideoFrameRate} from './get-video-frame-rate';type Props = {src: string;@@ -186,16 +89,15 @@ export const calculateMetadata: CalculateMetadataFunction<Props> = async ({}),});- const [frameRate, durationInSeconds] = await Promise.all([- getVideoFrameRate(input),+ const videoTrack = await input.getPrimaryVideoTrack();+ const [frameRateMetrics, durationInSeconds] = await Promise.all([+ videoTrack?.computeFrameRateMetrics() ?? null,input.computeDuration(),]);const fps =- frameRate === null+ frameRateMetrics === null || frameRateMetrics.probedPacketCount < 2? 30 // Fallback if none or not enough video frames are available- : frameRate.type === 'constant'- ? frameRate.rate- : frameRate.max;+ : frameRateMetrics.bestGuessFrameRate;return {fps,@@ -204,7 +106,8 @@ export const calculateMetadata: CalculateMetadataFunction<Props> = async ({};```-If the frame rate cannot be determined, the composition uses 30 FPS.+If the frame rate cannot be determined, decide which frame rate you want to fall back to, in this example 30.+The `durationInFrames` is adjusted to preserve the duration of the source video.## See alsodiff --git a/packages/docs/docs/mediabunny/metadata.mdx b/packages/docs/docs/mediabunny/metadata.mdxindex d0b2d55199..33b9c3a55a 100644--- a/packages/docs/docs/mediabunny/metadata.mdx+++ b/packages/docs/docs/mediabunny/metadata.mdx@@ -13,13 +13,12 @@ If you would like to obtain metadata from a video or audio in JavaScript, such athen [Mediabunny](https://mediabunny.dev) is the ideal library for doing so.-The example uses the [`getVideoFrameRate()` code snippet](/docs/mediabunny/frame-rate) to determine whether the frame rate is constant or variable.+The example uses Mediabunny's [`computeFrameRateMetrics()`](https://mediabunny.dev/api/InputVideoTrack#computeframeratemetrics) method to determine whether the frame rate is constant or variable.## Getting metadata from a URL```tsx title="get-media-metadata.ts"import {Input, ALL_FORMATS, UrlSource} from 'mediabunny';-import {getVideoFrameRate} from './get-video-frame-rate';export const getMediaMetadata = async (src: string) => {const input = new Input({@@ -37,13 +36,13 @@ export const getMediaMetadata = async (src: string) => {height: await videoTrack.getDisplayHeight(),}: null;- const frameRate = await getVideoFrameRate(input);+ const frameRateMetrics = videoTrack+ ? await videoTrack.computeFrameRateMetrics()+ : null;const fps =- frameRate === null+ frameRateMetrics === null || frameRateMetrics.probedPacketCount < 2? null- : frameRate.type === 'constant'- ? frameRate.rate- : frameRate.max;+ : frameRateMetrics.bestGuessFrameRate;return {durationInSeconds,@@ -90,4 +89,4 @@ In that case, you are better off using the [`getVideoMetadata()`](/docs/get-vide## See also-- [`getVideoFrameRate()`](/docs/mediabunny/frame-rate)+- [Getting the frame rate of a video](/docs/mediabunny/frame-rate)diff --git a/packages/docs/src/css/custom.css b/packages/docs/src/css/custom.cssindex 4e1607579f..04920d0944 100644--- a/packages/docs/src/css/custom.css+++ b/packages/docs/src/css/custom.css@@ -30,6 +30,7 @@ h6 {word-spacing: -0.025em;font-family: 'GTPlanar';font-feature-settings: 'ss03' on;+ text-wrap: balance;}@font-face {