Skip to content

🎥 Make videos programmatically with React

Add internal `@remotion/timeline-utils` package (#7320)

Jonny Burgerd53b535924b5
diff --git a/bun.lock b/bun.lock
index dd6954831a..1b91850205 100644
--- a/bun.lock
+++ b/bun.lock
@@ -1503,6 +1503,7 @@
"@remotion/player": "workspace:*",
"@remotion/renderer": "workspace:*",
"@remotion/studio-shared": "workspace:*",
+ "@remotion/timeline-utils": "workspace:*",
"@remotion/web-renderer": "workspace:*",
"@remotion/zod-types": "workspace:*",
"mediabunny": "catalog:",
@@ -2363,6 +2364,18 @@
"three": ">=0.137.0",
},
},
+ "packages/timeline-utils": {
+ "name": "@remotion/timeline-utils",
+ "version": "4.0.459",
+ "dependencies": {
+ "mediabunny": "catalog:",
+ },
+ "devDependencies": {
+ "@remotion/eslint-config-internal": "workspace:*",
+ "@typescript/native-preview": "catalog:",
+ "eslint": "catalog:",
+ },
+ },
"packages/transitions": {
"name": "@remotion/transitions",
"version": "4.0.459",
@@ -3948,6 +3961,8 @@
"@remotion/three": ["@remotion/three@workspace:packages/three"],
+ "@remotion/timeline-utils": ["@remotion/timeline-utils@workspace:packages/timeline-utils"],
+
"@remotion/transitions": ["@remotion/transitions@workspace:packages/transitions"],
"@remotion/vercel": ["@remotion/vercel@workspace:packages/vercel"],
diff --git a/packages/STATS.md b/packages/STATS.md
index 38ab007bce..963db3d7f7 100644
--- a/packages/STATS.md
+++ b/packages/STATS.md
@@ -61,6 +61,7 @@ Monthly downloads of Remotion packages
[![NPM Downloads](https://img.shields.io/npm/dm/@remotion/tailwind.svg?style=flat&color=black&label=@remotion/tailwind)](https://npmcharts.com/compare/@remotion/tailwind?minimal=true)
[![NPM Downloads](https://img.shields.io/npm/dm/@remotion/tailwind-v4.svg?style=flat&color=black&label=@remotion/tailwind-v4)](https://npmcharts.com/compare/@remotion/tailwind-v4?minimal=true)
[![NPM Downloads](https://img.shields.io/npm/dm/@remotion/three.svg?style=flat&color=black&label=@remotion/three)](https://npmcharts.com/compare/@remotion/three?minimal=true)
+[![NPM Downloads](https://img.shields.io/npm/dm/@remotion/timeline-utils.svg?style=flat&color=black&label=@remotion/timeline-utils)](https://npmcharts.com/compare/@remotion/timeline-utils?minimal=true)
[![NPM Downloads](https://img.shields.io/npm/dm/@remotion/transitions.svg?style=flat&color=black&label=@remotion/transitions)](https://npmcharts.com/compare/@remotion/transitions?minimal=true)
[![NPM Downloads](https://img.shields.io/npm/dm/@remotion/vercel.svg?style=flat&color=black&label=@remotion/vercel)](https://npmcharts.com/compare/@remotion/vercel?minimal=true)
[![NPM Downloads](https://img.shields.io/npm/dm/@remotion/web-renderer.svg?style=flat&color=black&label=@remotion/web-renderer)](https://npmcharts.com/compare/@remotion/web-renderer?minimal=true)
diff --git a/packages/cli/src/list-of-remotion-packages.ts b/packages/cli/src/list-of-remotion-packages.ts
index f48335388a..888aebbff9 100644
--- a/packages/cli/src/list-of-remotion-packages.ts
+++ b/packages/cli/src/list-of-remotion-packages.ts
@@ -70,6 +70,7 @@ export const listOfRemotionPackages = [
'@remotion/studio',
'@remotion/tailwind',
'@remotion/tailwind-v4',
+ '@remotion/timeline-utils',
'@remotion/test-utils',
'@remotion/three',
'@remotion/transitions',
diff --git a/packages/create-video/src/list-of-remotion-packages.ts b/packages/create-video/src/list-of-remotion-packages.ts
index f48335388a..888aebbff9 100644
--- a/packages/create-video/src/list-of-remotion-packages.ts
+++ b/packages/create-video/src/list-of-remotion-packages.ts
@@ -70,6 +70,7 @@ export const listOfRemotionPackages = [
'@remotion/studio',
'@remotion/tailwind',
'@remotion/tailwind-v4',
+ '@remotion/timeline-utils',
'@remotion/test-utils',
'@remotion/three',
'@remotion/transitions',
diff --git a/packages/studio-shared/src/package-info.ts b/packages/studio-shared/src/package-info.ts
index 9a16f23de5..32e20b8d40 100644
--- a/packages/studio-shared/src/package-info.ts
+++ b/packages/studio-shared/src/package-info.ts
@@ -69,6 +69,7 @@ export const packages = [
'studio',
'tailwind',
'tailwind-v4',
+ 'timeline-utils',
'test-utils',
'three',
'transitions',
@@ -170,6 +171,7 @@ export const descriptions: {[key in Pkgs]: string | null} = {
'create-video': 'Create a new Remotion project',
'studio-shared':
'Internal package for shared objects between the Studio backend and frontend',
+ 'timeline-utils': 'Internal utilities for rendering Remotion timelines',
tailwind: 'Enable TailwindCSS support in Remotion (TailwindCSS v3)',
'tailwind-v4': 'Enable TailwindCSS support in Remotion (TailwindCSS v4)',
streaming: 'Utilities for streaming data between programs',
@@ -295,6 +297,7 @@ export const installableMap: {[key in Pkgs]: boolean} = {
studio: true,
tailwind: true,
'tailwind-v4': true,
+ 'timeline-utils': false,
'test-utils': false,
three: true,
transitions: true,
@@ -394,6 +397,7 @@ export const apiDocs: {[key in Pkgs]: string | null} = {
serverless: null,
skills: null,
studio: 'https://www.remotion.dev/docs/studio/api',
+ 'timeline-utils': null,
transitions: 'https://www.remotion.dev/transitions',
'animated-emoji': 'https://www.remotion.dev/docs/animated-emoji',
webcodecs: 'https://remotion.dev/webcodecs',
diff --git a/packages/studio/bundle.ts b/packages/studio/bundle.ts
index c214bd70c1..55d86e908e 100644
--- a/packages/studio/bundle.ts
+++ b/packages/studio/bundle.ts
@@ -7,6 +7,7 @@ const external = [
'react',
'@remotion/media-utils',
'@remotion/studio-shared',
+ '@remotion/timeline-utils',
'@remotion/zod-types',
'@remotion/renderer',
'@remotion/player',
diff --git a/packages/studio/package.json b/packages/studio/package.json
index 9982b61d38..a2af3b0d74 100644
--- a/packages/studio/package.json
+++ b/packages/studio/package.json
@@ -32,6 +32,7 @@
"@remotion/renderer": "workspace:*",
"@remotion/web-renderer": "workspace:*",
"@remotion/studio-shared": "workspace:*",
+ "@remotion/timeline-utils": "workspace:*",
"@remotion/zod-types": "workspace:*",
"mediabunny": "catalog:",
"memfs": "3.4.3",
diff --git a/packages/studio/src/audio-waveform-worker.ts b/packages/studio/src/audio-waveform-worker.ts
index 2e3709a558..3f059d6d48 100644
--- a/packages/studio/src/audio-waveform-worker.ts
+++ b/packages/studio/src/audio-waveform-worker.ts
@@ -1,5 +1,9 @@
/// <reference lib="webworker" />
+import {
+ getLoopDisplayWidth,
+ shouldTileLoopDisplay,
+} from '@remotion/timeline-utils';
import type {
AudioWaveformWorkerIncomingMessage,
AudioWaveformWorkerOutgoingMessage,
@@ -7,10 +11,6 @@ import type {
} from './components/audio-waveform-worker-types';
import {drawBars} from './components/draw-peaks';
import {loadWaveformPeaks} from './components/load-waveform-peaks';
-import {
- getLoopDisplayWidth,
- shouldTileLoopDisplay,
-} from './components/looped-media-timeline';
import {sliceWaveformPeaks} from './components/slice-waveform-peaks';
declare const self: DedicatedWorkerGlobalScope;
diff --git a/packages/studio/src/components/AudioWaveform.tsx b/packages/studio/src/components/AudioWaveform.tsx
index 49bc574c72..523d78cbe1 100644
--- a/packages/studio/src/components/AudioWaveform.tsx
+++ b/packages/studio/src/components/AudioWaveform.tsx
@@ -1,3 +1,7 @@
+import {
+ getLoopDisplayWidth,
+ shouldTileLoopDisplay,
+} from '@remotion/timeline-utils';
import React, {useEffect, useMemo, useRef, useState} from 'react';
import type {LoopDisplay} from 'remotion';
import {Internals} from 'remotion';
@@ -10,10 +14,6 @@ import type {
} from './audio-waveform-worker-types';
import {drawBars} from './draw-peaks';
import {loadWaveformPeaks} from './load-waveform-peaks';
-import {
- getLoopDisplayWidth,
- shouldTileLoopDisplay,
-} from './looped-media-timeline';
import {sliceWaveformPeaks} from './slice-waveform-peaks';
const EMPTY_PEAKS = new Float32Array(0);
diff --git a/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx b/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx
index 634688cc14..5ea92acce4 100644
--- a/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx
+++ b/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx
@@ -1,27 +1,25 @@
-import React, {useEffect, useMemo, useRef, useState} from 'react';
-import type {LoopDisplay} from 'remotion';
-import {useVideoConfig} from 'remotion';
-import {extractFrames} from '../../helpers/extract-frames';
-import type {FrameDatabaseKey} from '../../helpers/frame-database';
import {
addFrameToCache,
aspectRatioCache,
- frameDatabase,
+ ensureSlots,
+ extractFrames,
+ fillFrameWhereItFits,
+ fillWithCachedFrames,
+ getLoopDisplayWidth,
getAspectRatioFromCache,
- getFrameDatabaseKeyPrefix,
- getTimestampFromFrameDatabaseKey,
makeFrameDatabaseKey,
-} from '../../helpers/frame-database';
-import {resizeVideoFrame} from '../../helpers/resize-video-frame';
+ resizeVideoFrame,
+ shouldTileLoopDisplay,
+ WEBCODECS_TIMESCALE,
+} from '@remotion/timeline-utils';
+import React, {useEffect, useMemo, useRef, useState} from 'react';
+import type {LoopDisplay} from 'remotion';
+import {useVideoConfig} from 'remotion';
import {
TIMELINE_LAYER_HEIGHT_AUDIO,
TIMELINE_LAYER_HEIGHT_IMAGE,
} from '../../helpers/timeline-layout';
import {AudioWaveform} from '../AudioWaveform';
-import {
- getLoopDisplayWidth,
- shouldTileLoopDisplay,
-} from '../looped-media-timeline';
const FILMSTRIP_HEIGHT = TIMELINE_LAYER_HEIGHT_IMAGE - 2;
@@ -42,245 +40,6 @@ const filmstripContainerStyle: React.CSSProperties = {
fontFamily: 'Arial, Helvetica',
};
-const WEBCODECS_TIMESCALE = 1_000_000;
-const MAX_TIME_DEVIATION = WEBCODECS_TIMESCALE * 0.05;
-
-const getDurationOfOneFrame = ({
- visualizationWidth,
- aspectRatio,
- segmentDuration,
-}: {
- visualizationWidth: number;
- aspectRatio: number;
- segmentDuration: number;
-}) => {
- const framesFitInWidthUnrounded =
- visualizationWidth / (FILMSTRIP_HEIGHT * aspectRatio);
- return (segmentDuration / framesFitInWidthUnrounded) * WEBCODECS_TIMESCALE;
-};
-
-const fixRounding = (value: number) => {
- if (value % 1 >= 0.49999999) {
- return Math.ceil(value);
- }
-
- return Math.floor(value);
-};
-
-const calculateTimestampSlots = ({
- visualizationWidth,
- fromSeconds,
- segmentDuration,
- aspectRatio,
-}: {
- visualizationWidth: number;
- fromSeconds: number;
- segmentDuration: number;
- aspectRatio: number;
-}) => {
- const framesFitInWidthUnrounded =
- visualizationWidth / (FILMSTRIP_HEIGHT * aspectRatio);
- const framesFitInWidth = Math.ceil(framesFitInWidthUnrounded);
- const durationOfOneFrame = getDurationOfOneFrame({
- visualizationWidth,
- aspectRatio,
- segmentDuration,
- });
-
- const timestampTargets: number[] = [];
- for (let i = 0; i < framesFitInWidth + 1; i++) {
- const target =
- fromSeconds * WEBCODECS_TIMESCALE + durationOfOneFrame * (i + 0.5);
- const snappedToDuration =
- (Math.round(fixRounding(target / durationOfOneFrame)) - 1) *
- durationOfOneFrame;
-
- timestampTargets.push(snappedToDuration);
- }
-
- return timestampTargets;
-};
-
-const ensureSlots = ({
- filledSlots,
- naturalWidth,
- fromSeconds,
- toSeconds,
- aspectRatio,
-}: {
- filledSlots: Map<number, number | undefined>;
- naturalWidth: number;
- fromSeconds: number;
- toSeconds: number;
- aspectRatio: number;
-}) => {
- const segmentDuration = toSeconds - fromSeconds;
-
- const timestampTargets = calculateTimestampSlots({
- visualizationWidth: naturalWidth,
- fromSeconds,
- segmentDuration,
- aspectRatio,
- });
-
- for (const timestamp of timestampTargets) {
- if (!filledSlots.has(timestamp)) {
- filledSlots.set(timestamp, undefined);
- }
- }
-};
-
-const drawSlot = ({
- frame,
- ctx,
- filledSlots,
- visualizationWidth,
- timestamp,
- segmentDuration,
- fromSeconds,
-}: {
- frame: VideoFrame;
- ctx: CanvasRenderingContext2D;
- filledSlots: Map<number, number | undefined>;
- visualizationWidth: number;
- timestamp: number;
- segmentDuration: number;
- fromSeconds: number;
-}) => {
- const durationOfOneFrame = getDurationOfOneFrame({
- visualizationWidth,
- aspectRatio: frame.displayWidth / frame.displayHeight,
- segmentDuration,
- });
-
- const relativeTimestamp = timestamp - fromSeconds * WEBCODECS_TIMESCALE;
- const frameIndex = relativeTimestamp / durationOfOneFrame;
- const thumbnailWidth = frame.displayWidth / window.devicePixelRatio;
- const left = Math.floor(frameIndex * thumbnailWidth);
- const right = Math.ceil((frameIndex + 1) * thumbnailWidth);
-
- ctx.drawImage(
- frame,
- left,
- 0,
- right - left,
- frame.displayHeight / window.devicePixelRatio,
- );
- filledSlots.set(timestamp, frame.timestamp);
-};
-
-const fillWithCachedFrames = ({
- ctx,
- naturalWidth,
- filledSlots,
- src,
- segmentDuration,
- fromSeconds,
-}: {
- ctx: CanvasRenderingContext2D;
- naturalWidth: number;
- filledSlots: Map<number, number | undefined>;
- src: string;
- segmentDuration: number;
- fromSeconds: number;
-}) => {
- const prefix = getFrameDatabaseKeyPrefix(src);
- const keys = Array.from(frameDatabase.keys()).filter((k) =>
- k.startsWith(prefix),
- );
- const targets = Array.from(filledSlots.keys());
-
- for (const timestamp of targets) {
- let bestKey: FrameDatabaseKey | undefined;
- let bestDistance = Infinity;
- for (const key of keys) {
- const distance = Math.abs(
- getTimestampFromFrameDatabaseKey(key) - timestamp,
- );
- if (distance < bestDistance) {
- bestDistance = distance;
- bestKey = key;
- }
- }
-
- if (!bestKey) {
- continue;
- }
-
- const frame = frameDatabase.get(bestKey);
- if (!frame) {
- continue;
- }
-
- const alreadyFilled = filledSlots.get(timestamp);
-
- // Don't fill if a closer frame was already drawn
- if (
- alreadyFilled &&
- Math.abs(alreadyFilled - timestamp) <=
- Math.abs(frame.frame.timestamp - timestamp)
- ) {
- continue;
- }
-
- frame.lastUsed = Date.now();
-
- drawSlot({
- ctx,
- frame: frame.frame,
- filledSlots,
- visualizationWidth: naturalWidth,
- timestamp,
- segmentDuration,
- fromSeconds,
- });
- }
-};
-
-const fillFrameWhereItFits = ({
- frame,
- filledSlots,
- ctx,
- visualizationWidth,
- segmentDuration,
- fromSeconds,
-}: {
- frame: VideoFrame;
- filledSlots: Map<number, number | undefined>;
- ctx: CanvasRenderingContext2D;
- visualizationWidth: number;
- segmentDuration: number;
- fromSeconds: number;
-}) => {
- const slots = Array.from(filledSlots.keys());
-
- for (let i = 0; i < slots.length; i++) {
- const slot = slots[i];
- if (Math.abs(slot - frame.timestamp) > MAX_TIME_DEVIATION) {
- continue;
- }
-
- const filled = filledSlots.get(slot);
- // Don't fill if a better timestamp was already filled
- if (
- filled &&
- Math.abs(filled - slot) <= Math.abs(filled - frame.timestamp)
- ) {
- continue;
- }
-
- drawSlot({
- ctx,
- frame,
- filledSlots,
- visualizationWidth,
- timestamp: slot,
- segmentDuration,
- fromSeconds,
- });
- }
-};
-
export const TimelineVideoInfo: React.FC<{
readonly src: string;
readonly visualizationWidth: number;
@@ -391,6 +150,7 @@ export const TimelineVideoInfo: React.FC<{
fromSeconds,
toSeconds,
aspectRatio: aspectRatio.current,
+ frameHeight: FILMSTRIP_HEIGHT,
});
fillWithCachedFrames({
@@ -400,6 +160,8 @@ export const TimelineVideoInfo: React.FC<{
src,
segmentDuration: toSeconds - fromSeconds,
fromSeconds,
+ devicePixelRatio: window.devicePixelRatio,
+ frameHeight: FILMSTRIP_HEIGHT,
});
repeatTarget();
@@ -430,6 +192,7 @@ export const TimelineVideoInfo: React.FC<{
toSeconds,
naturalWidth: targetWidth,
aspectRatio: aspectRatio.current,
+ frameHeight: FILMSTRIP_HEIGHT,
});
return Array.from(filledSlots.keys()).map(
@@ -468,6 +231,7 @@ export const TimelineVideoInfo: React.FC<{
toSeconds,
naturalWidth: targetWidth,
aspectRatio: aspectRatio.current,
+ frameHeight: FILMSTRIP_HEIGHT,
});
fillFrameWhereItFits({
ctx: targetCtx,
@@ -476,6 +240,8 @@ export const TimelineVideoInfo: React.FC<{
frame: transformed,
segmentDuration: toSeconds - fromSeconds,
fromSeconds,
+ devicePixelRatio: window.devicePixelRatio,
+ frameHeight: FILMSTRIP_HEIGHT,
});
repeatTarget();
} catch (e) {
@@ -502,6 +268,8 @@ export const TimelineVideoInfo: React.FC<{
src,
segmentDuration: toSeconds - fromSeconds,
fromSeconds,
+ devicePixelRatio: window.devicePixelRatio,
+ frameHeight: FILMSTRIP_HEIGHT,
});
repeatTarget();
})
diff --git a/packages/studio/src/test/looped-audio-waveform.test.ts b/packages/studio/src/test/looped-audio-waveform.test.ts
index 877e19bd65..d559b33afa 100644
--- a/packages/studio/src/test/looped-audio-waveform.test.ts
+++ b/packages/studio/src/test/looped-audio-waveform.test.ts
@@ -2,7 +2,7 @@ import {expect, test} from 'bun:test';
import {
getLoopDisplayWidth,
shouldTileLoopDisplay,
-} from '../components/looped-media-timeline';
+} from '@remotion/timeline-utils';
test('Should only tile media if more than one loop is visible', () => {
expect(shouldTileLoopDisplay(undefined)).toBe(false);
diff --git a/packages/studio/tsconfig.json b/packages/studio/tsconfig.json
index 279d4129d1..f392c429cf 100644
--- a/packages/studio/tsconfig.json
+++ b/packages/studio/tsconfig.json
@@ -17,6 +17,9 @@
{
"path": "../studio-shared"
},
+ {
+ "path": "../timeline-utils"
+ },
{
"path": "../zod-types"
},
diff --git a/packages/timeline-utils/.npmignore b/packages/timeline-utils/.npmignore
new file mode 100644
index 0000000000..b151432254
--- /dev/null
+++ b/packages/timeline-utils/.npmignore
@@ -0,0 +1,9 @@
+dist/test/**
+src
+tsconfig.tsbuildinfo
+*.tgz
+.turbo
+tsconfig.json
+.prettierrc.js
+bundle.ts
+eslint.config.mjs
diff --git a/packages/timeline-utils/README.md b/packages/timeline-utils/README.md
new file mode 100644
index 0000000000..dcb8bc21c0
--- /dev/null
+++ b/packages/timeline-utils/README.md
@@ -0,0 +1,7 @@
+# @remotion/timeline-utils
+
+Internal utilities for rendering Remotion timelines
+
+## Usage
+
+This is an internal package and has no documentation.
diff --git a/packages/timeline-utils/bundle.ts b/packages/timeline-utils/bundle.ts
new file mode 100644
index 0000000000..0771f1c59f
--- /dev/null
+++ b/packages/timeline-utils/bundle.ts
@@ -0,0 +1,18 @@
+import {build} from 'bun';
+
+if (process.env.NODE_ENV !== 'production') {
+ throw new Error('This script must be run using NODE_ENV=production');
+}
+
+const output = await build({
+ entrypoints: ['src/index.ts'],
+ naming: '[name].mjs',
+ external: ['mediabunny'],
+});
+
+const [file] = output.outputs;
+const text = await file.text();
+
+await Bun.write('dist/esm/index.mjs', text);
+
+export {};
diff --git a/packages/timeline-utils/eslint.config.mjs b/packages/timeline-utils/eslint.config.mjs
new file mode 100644
index 0000000000..04fd4fac11
--- /dev/null
+++ b/packages/timeline-utils/eslint.config.mjs
@@ -0,0 +1,7 @@
+import {remotionFlatConfig} from '@remotion/eslint-config-internal';
+
+const config = remotionFlatConfig({react: false});
+
+export default {
+ ...config,
+};
diff --git a/packages/timeline-utils/package.json b/packages/timeline-utils/package.json
new file mode 100644
index 0000000000..3e27c1e89a
--- /dev/null
+++ b/packages/timeline-utils/package.json
@@ -0,0 +1,43 @@
+{
+ "repository": {
+ "url": "https://github.com/remotion-dev/remotion/tree/main/packages/timeline-utils"
+ },
+ "name": "@remotion/timeline-utils",
+ "version": "4.0.459",
+ "description": "Internal utilities for rendering Remotion timelines",
+ "main": "dist/index.js",
+ "sideEffects": false,
+ "scripts": {
+ "formatting": "oxfmt src --check",
+ "format": "oxfmt src",
+ "lint": "eslint src",
+ "make": "tsgo -d && bun --env-file=../.env.bundle bundle.ts"
+ },
+ "types": "dist/index.d.ts",
+ "module": "dist/esm/index.mjs",
+ "author": "Jonny Burger <[email protected]>",
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/remotion-dev/remotion/issues"
+ },
+ "dependencies": {
+ "mediabunny": "catalog:"
+ },
+ "devDependencies": {
+ "@remotion/eslint-config-internal": "workspace:*",
+ "eslint": "catalog:",
+ "@typescript/native-preview": "catalog:"
+ },
+ "publishConfig": {
+ "access": "public"
+ },
+ "exports": {
+ "./package.json": "./package.json",
+ ".": {
+ "types": "./dist/index.d.ts",
+ "module": "./dist/esm/index.mjs",
+ "import": "./dist/esm/index.mjs",
+ "require": "./dist/index.js"
+ }
+ }
+}
diff --git a/packages/studio/src/helpers/extract-frames.ts b/packages/timeline-utils/src/extract-frames.ts
similarity index 90%
rename from packages/studio/src/helpers/extract-frames.ts
rename to packages/timeline-utils/src/extract-frames.ts
index ad891b06fe..6e44711554 100644
--- a/packages/studio/src/helpers/extract-frames.ts
+++ b/packages/timeline-utils/src/extract-frames.ts
@@ -101,10 +101,8 @@ export async function extractFrames({
onVideoSample(videoSample);
}
} finally {
- // When input.dispose() causes the iterator to throw
- // InputDisposedError, for-await does not call .return() on the
- // iterator (it only does so on `break`). Explicitly call it so
- // the iterator can close any internally buffered VideoSamples.
+ // When input.dispose() causes the iterator to throw InputDisposedError,
+ // for-await does not call .return() on the iterator.
try {
await sampleIterator.return?.();
} catch {
diff --git a/packages/studio/src/helpers/frame-database.ts b/packages/timeline-utils/src/frame-database.ts
similarity index 94%
rename from packages/studio/src/helpers/frame-database.ts
rename to packages/timeline-utils/src/frame-database.ts
index ec861d7f03..6a6569efbb 100644
--- a/packages/studio/src/helpers/frame-database.ts
+++ b/packages/timeline-utils/src/frame-database.ts
@@ -1,5 +1,3 @@
-// Cache the thumbnails of the timeline
-
export type FrameDatabaseKey = string & {__brand: 'FrameDatabaseKey'};
const KEY_SEPARATOR = '|';
@@ -19,7 +17,7 @@ type VideoFrameAndLastUsed = {
size: number;
};
-const MAX_CACHE_SIZE_BYTES = 10 * 1024 * 1024; // 10 MB
+const MAX_CACHE_SIZE_BYTES = 10 * 1024 * 1024;
let totalCacheSize = 0;
diff --git a/packages/timeline-utils/src/get-duration-or-compute.ts b/packages/timeline-utils/src/get-duration-or-compute.ts
new file mode 100644
index 0000000000..7436fb448c
--- /dev/null
+++ b/packages/timeline-utils/src/get-duration-or-compute.ts
@@ -0,0 +1,9 @@
+import type {Input} from 'mediabunny';
+
+export const getDurationOrCompute = async (input: Input) => {
+ return (
+ (await input.getDurationFromMetadata(undefined, {
+ skipLiveWait: true,
+ })) ?? input.computeDuration(undefined, {skipLiveWait: true})
+ );
+};
diff --git a/packages/timeline-utils/src/index.ts b/packages/timeline-utils/src/index.ts
new file mode 100644
index 0000000000..8a088a9580
--- /dev/null
+++ b/packages/timeline-utils/src/index.ts
@@ -0,0 +1,27 @@
+export {extractFrames} from './extract-frames';
+export type {
+ ExtractFramesProps,
+ ExtractFramesTimestampsInSecondsFn,
+} from './extract-frames';
+export {
+ addFrameToCache,
+ aspectRatioCache,
+ frameDatabase,
+ getAspectRatioFromCache,
+ getFrameDatabaseKeyPrefix,
+ getTimestampFromFrameDatabaseKey,
+ makeFrameDatabaseKey,
+} from './frame-database';
+export type {FrameDatabaseKey} from './frame-database';
+export {getLoopDisplayWidth, shouldTileLoopDisplay} from './loop-display';
+export type {TimelineLoopDisplay} from './loop-display';
+export {
+ calculateTimestampSlots,
+ drawSlot,
+ ensureSlots,
+ fillFrameWhereItFits,
+ fillWithCachedFrames,
+ getDurationOfOneFrame,
+ WEBCODECS_TIMESCALE,
+} from './render-frame-strip';
+export {resizeVideoFrame} from './resize-video-frame';
diff --git a/packages/studio/src/components/looped-media-timeline.ts b/packages/timeline-utils/src/loop-display.ts
similarity index 59%
rename from packages/studio/src/components/looped-media-timeline.ts
rename to packages/timeline-utils/src/loop-display.ts
index fb429ce52d..bfcdb0066e 100644
--- a/packages/studio/src/components/looped-media-timeline.ts
+++ b/packages/timeline-utils/src/loop-display.ts
@@ -1,8 +1,12 @@
-import type {LoopDisplay} from 'remotion';
+export type TimelineLoopDisplay = {
+ durationInFrames: number;
+ numberOfTimes: number;
+ startOffset: number;
+};
export const shouldTileLoopDisplay = (
- loopDisplay: LoopDisplay | undefined,
-): loopDisplay is LoopDisplay => {
+ loopDisplay: TimelineLoopDisplay | undefined,
+): loopDisplay is TimelineLoopDisplay => {
return loopDisplay !== undefined && loopDisplay.numberOfTimes > 1;
};
@@ -11,7 +15,7 @@ export const getLoopDisplayWidth = ({
loopDisplay,
}: {
visualizationWidth: number;
- loopDisplay: LoopDisplay | undefined;
+ loopDisplay: TimelineLoopDisplay | undefined;
}) => {
if (!shouldTileLoopDisplay(loopDisplay)) {
return visualizationWidth;
diff --git a/packages/timeline-utils/src/render-frame-strip.ts b/packages/timeline-utils/src/render-frame-strip.ts
new file mode 100644
index 0000000000..b71cd81f93
--- /dev/null
+++ b/packages/timeline-utils/src/render-frame-strip.ts
@@ -0,0 +1,267 @@
+import type {FrameDatabaseKey} from './frame-database';
+import {
+ frameDatabase,
+ getFrameDatabaseKeyPrefix,
+ getTimestampFromFrameDatabaseKey,
+} from './frame-database';
+
+export const WEBCODECS_TIMESCALE = 1_000_000;
+const MAX_TIME_DEVIATION = WEBCODECS_TIMESCALE * 0.05;
+
+export const getDurationOfOneFrame = ({
+ visualizationWidth,
+ aspectRatio,
+ segmentDuration,
+ frameHeight,
+}: {
+ visualizationWidth: number;
+ aspectRatio: number;
+ segmentDuration: number;
+ frameHeight: number;
+}) => {
+ const framesFitInWidthUnrounded =
+ visualizationWidth / (frameHeight * aspectRatio);
+ return (segmentDuration / framesFitInWidthUnrounded) * WEBCODECS_TIMESCALE;
+};
+
+const fixRounding = (value: number) => {
+ if (value % 1 >= 0.49999999) {
+ return Math.ceil(value);
+ }
+
+ return Math.floor(value);
+};
+
+export const calculateTimestampSlots = ({
+ visualizationWidth,
+ fromSeconds,
+ segmentDuration,
+ aspectRatio,
+ frameHeight,
+}: {
+ visualizationWidth: number;
+ fromSeconds: number;
+ segmentDuration: number;
+ aspectRatio: number;
+ frameHeight: number;
+}) => {
+ const framesFitInWidthUnrounded =
+ visualizationWidth / (frameHeight * aspectRatio);
+ const framesFitInWidth = Math.ceil(framesFitInWidthUnrounded);
+ const durationOfOneFrame = getDurationOfOneFrame({
+ visualizationWidth,
+ aspectRatio,
+ segmentDuration,
+ frameHeight,
+ });
+
+ const timestampTargets: number[] = [];
+ for (let i = 0; i < framesFitInWidth + 1; i++) {
+ const target =
+ fromSeconds * WEBCODECS_TIMESCALE + durationOfOneFrame * (i + 0.5);
+ const snappedToDuration =
+ (Math.round(fixRounding(target / durationOfOneFrame)) - 1) *
+ durationOfOneFrame;
+
+ timestampTargets.push(snappedToDuration);
+ }
+
+ return timestampTargets;
+};
+
+export const ensureSlots = ({
+ filledSlots,
+ naturalWidth,
+ fromSeconds,
+ toSeconds,
+ aspectRatio,
+ frameHeight,
+}: {
+ filledSlots: Map<number, number | undefined>;
+ naturalWidth: number;
+ fromSeconds: number;
+ toSeconds: number;
+ aspectRatio: number;
+ frameHeight: number;
+}) => {
+ const segmentDuration = toSeconds - fromSeconds;
+
+ const timestampTargets = calculateTimestampSlots({
+ visualizationWidth: naturalWidth,
+ fromSeconds,
+ segmentDuration,
+ aspectRatio,
+ frameHeight,
+ });
+
+ for (const timestamp of timestampTargets) {
+ if (!filledSlots.has(timestamp)) {
+ filledSlots.set(timestamp, undefined);
+ }
+ }
+};
+
+export const drawSlot = ({
+ frame,
+ ctx,
+ filledSlots,
+ visualizationWidth,
+ timestamp,
+ segmentDuration,
+ fromSeconds,
+ devicePixelRatio,
+ frameHeight,
+}: {
+ frame: VideoFrame;
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
+ filledSlots: Map<number, number | undefined>;
+ visualizationWidth: number;
+ timestamp: number;
+ segmentDuration: number;
+ fromSeconds: number;
+ devicePixelRatio: number;
+ frameHeight: number;
+}) => {
+ const durationOfOneFrame = getDurationOfOneFrame({
+ visualizationWidth,
+ aspectRatio: frame.displayWidth / frame.displayHeight,
+ segmentDuration,
+ frameHeight,
+ });
+
+ const relativeTimestamp = timestamp - fromSeconds * WEBCODECS_TIMESCALE;
+ const frameIndex = relativeTimestamp / durationOfOneFrame;
+ const thumbnailWidth = frame.displayWidth / devicePixelRatio;
+ const left = Math.floor(frameIndex * thumbnailWidth);
+ const right = Math.ceil((frameIndex + 1) * thumbnailWidth);
+
+ ctx.drawImage(
+ frame,
+ left,
+ 0,
+ right - left,
+ frame.displayHeight / devicePixelRatio,
+ );
+ filledSlots.set(timestamp, frame.timestamp);
+};
+
+export const fillWithCachedFrames = ({
+ ctx,
+ naturalWidth,
+ filledSlots,
+ src,
+ segmentDuration,
+ fromSeconds,
+ devicePixelRatio,
+ frameHeight,
+}: {
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
+ naturalWidth: number;
+ filledSlots: Map<number, number | undefined>;
+ src: string;
+ segmentDuration: number;
+ fromSeconds: number;
+ devicePixelRatio: number;
+ frameHeight: number;
+}) => {
+ const prefix = getFrameDatabaseKeyPrefix(src);
+ const keys = Array.from(frameDatabase.keys()).filter((k) =>
+ k.startsWith(prefix),
+ );
+ const targets = Array.from(filledSlots.keys());
+
+ for (const timestamp of targets) {
+ let bestKey: FrameDatabaseKey | undefined;
+ let bestDistance = Infinity;
+ for (const key of keys) {
+ const distance = Math.abs(
+ getTimestampFromFrameDatabaseKey(key) - timestamp,
+ );
+ if (distance < bestDistance) {
+ bestDistance = distance;
+ bestKey = key;
+ }
+ }
+
+ if (!bestKey) {
+ continue;
+ }
+
+ const frame = frameDatabase.get(bestKey);
+ if (!frame) {
+ continue;
+ }
+
+ const alreadyFilled = filledSlots.get(timestamp);
+ if (
+ alreadyFilled &&
+ Math.abs(alreadyFilled - timestamp) <=
+ Math.abs(frame.frame.timestamp - timestamp)
+ ) {
+ continue;
+ }
+
+ frame.lastUsed = Date.now();
+
+ drawSlot({
+ ctx,
+ frame: frame.frame,
+ filledSlots,
+ visualizationWidth: naturalWidth,
+ timestamp,
+ segmentDuration,
+ fromSeconds,
+ devicePixelRatio,
+ frameHeight,
+ });
+ }
+};
+
+export const fillFrameWhereItFits = ({
+ frame,
+ filledSlots,
+ ctx,
+ visualizationWidth,
+ segmentDuration,
+ fromSeconds,
+ devicePixelRatio,
+ frameHeight,
+}: {
+ frame: VideoFrame;
+ filledSlots: Map<number, number | undefined>;
+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
+ visualizationWidth: number;
+ segmentDuration: number;
+ fromSeconds: number;
+ devicePixelRatio: number;
+ frameHeight: number;
+}) => {
+ const slots = Array.from(filledSlots.keys());
+
+ for (let i = 0; i < slots.length; i++) {
+ const slot = slots[i];
+ if (Math.abs(slot - frame.timestamp) > MAX_TIME_DEVIATION) {
+ continue;
+ }
+
+ const filled = filledSlots.get(slot);
+ if (
+ filled &&
+ Math.abs(filled - slot) <= Math.abs(filled - frame.timestamp)
+ ) {
+ continue;
+ }
+
+ drawSlot({
+ ctx,
+ frame,
+ filledSlots,
+ visualizationWidth,
+ timestamp: slot,
+ segmentDuration,
+ fromSeconds,
+ devicePixelRatio,
+ frameHeight,
+ });
+ }
+};
diff --git a/packages/studio/src/helpers/resize-video-frame.ts b/packages/timeline-utils/src/resize-video-frame.ts
similarity index 97%
rename from packages/studio/src/helpers/resize-video-frame.ts
rename to packages/timeline-utils/src/resize-video-frame.ts
index 6fc5879414..4f5133c43b 100644
--- a/packages/studio/src/helpers/resize-video-frame.ts
+++ b/packages/timeline-utils/src/resize-video-frame.ts
@@ -22,7 +22,6 @@ export const resizeVideoFrame = ({
frame: VideoFrame;
scale: number;
}) => {
- // No resize, no rotation
if (scale === 1) {
return frame;
}
@@ -43,7 +42,6 @@ export const resizeVideoFrame = ({
canvas.height = height;
ctx.scale(scale, scale);
-
ctx.drawImage(frame, 0, 0);
return new VideoFrame(canvas, {
diff --git a/packages/timeline-utils/tsconfig.json b/packages/timeline-utils/tsconfig.json
new file mode 100644
index 0000000000..c80d66921c
--- /dev/null
+++ b/packages/timeline-utils/tsconfig.json
@@ -0,0 +1,8 @@
+{
+ "extends": "../tsconfig.settings.json",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "dist"
+ },
+ "include": ["src"]
+}