Skip to content

🎥 Make videos programmatically with React

works handsomely

JonnyBurger3aa29275a32d
diff --git a/packages/video/src/get-sink.ts b/packages/video/src/get-frames-since-keyframe.ts
similarity index 55%
rename from packages/video/src/get-sink.ts
rename to packages/video/src/get-frames-since-keyframe.ts
index a6fd5eefd8..58da906c41 100644
--- a/packages/video/src/get-sink.ts
+++ b/packages/video/src/get-frames-since-keyframe.ts
@@ -1,3 +1,4 @@
+import type {EncodedPacket} from 'mediabunny';
import {
ALL_FORMATS,
EncodedPacketSink,
@@ -5,6 +6,7 @@ import {
UrlSource,
VideoSampleSink,
} from 'mediabunny';
+import {makeKeyframeBank} from './keyframe-bank';
export const getVideoSink = async (src: string) => {
const input = new Input({
@@ -28,27 +30,29 @@ export type GetSink = Awaited<ReturnType<typeof getVideoSink>>;
export const getFramesSinceKeyframe = async ({
packetSink,
videoSampleSink,
- timestamp,
+ startPacket,
}: {
packetSink: EncodedPacketSink;
videoSampleSink: VideoSampleSink;
- timestamp: number;
+ startPacket: EncodedPacket;
}) => {
- const packet = await packetSink.getKeyPacket(timestamp, {
- verifyKeyPackets: true,
+ const packet2 = await packetSink.getNextKeyPacket(startPacket, {
+ verifyKeyPackets: false,
});
- if (!packet) {
- throw new Error('No packet found');
- }
- const packet2 = await packetSink.getNextKeyPacket(packet, {
- verifyKeyPackets: true,
+ const samples = videoSampleSink.samples(
+ startPacket.timestamp,
+ packet2 ? packet2.timestamp : Infinity,
+ );
+
+ const keyframeBank = makeKeyframeBank({
+ startTimestamp: startPacket.timestamp,
+ endTimestamp: packet2 ? packet2.timestamp : Infinity,
});
- if (!packet2) {
- throw new Error('No packet found');
- }
- const samples = videoSampleSink.samples(packet.timestamp, packet2.timestamp);
+ for await (const sample of samples) {
+ keyframeBank.frames.push(sample.toVideoFrame());
+ }
- return samples;
+ return keyframeBank;
};
diff --git a/packages/video/src/keyframe-bank.ts b/packages/video/src/keyframe-bank.ts
new file mode 100644
index 0000000000..9f533dd49d
--- /dev/null
+++ b/packages/video/src/keyframe-bank.ts
@@ -0,0 +1,41 @@
+export type KeyframeBank = {
+ frames: VideoFrame[];
+ startTimestamp: number;
+ endTimestamp: number;
+ getFrameFromTimestamp: (timestamp: number) => VideoFrame;
+};
+
+export const makeKeyframeBank = ({
+ startTimestamp,
+ endTimestamp,
+}: {
+ startTimestamp: number;
+ endTimestamp: number;
+}) => {
+ const frames: VideoFrame[] = [];
+ const keyframeBank: KeyframeBank = {
+ frames,
+ startTimestamp,
+ endTimestamp,
+ getFrameFromTimestamp: (timestampInSeconds) => {
+ if (timestampInSeconds < startTimestamp * 1_000_000) {
+ throw new Error('Timestamp is before start timestamp');
+ }
+
+ if (timestampInSeconds > endTimestamp * 1_000_000) {
+ throw new Error('Timestamp is after end timestamp');
+ }
+
+ for (let i = frames.length - 1; i >= 0; i--) {
+ const frame = frames[i];
+ if (frame.timestamp <= timestampInSeconds * 1_000_000) {
+ return frame;
+ }
+ }
+
+ throw new Error('No frame found for timestamp ' + timestampInSeconds);
+ },
+ };
+
+ return keyframeBank;
+};
diff --git a/packages/video/src/keyframe-manager.ts b/packages/video/src/keyframe-manager.ts
new file mode 100644
index 0000000000..87c961634b
--- /dev/null
+++ b/packages/video/src/keyframe-manager.ts
@@ -0,0 +1,54 @@
+import type {EncodedPacketSink, VideoSampleSink} from 'mediabunny';
+import {getFramesSinceKeyframe} from './get-frames-since-keyframe';
+import {type KeyframeBank} from './keyframe-bank';
+
+export const makeKeyframeManager = () => {
+ // src => {[startTimestamp]: KeyframeBank
+ const sources: Record<string, Record<number, KeyframeBank>> = {};
+
+ const addKeyframeBank = ({src, bank}: {src: string; bank: KeyframeBank}) => {
+ sources[src] = sources[src] ?? {};
+ sources[src][bank.startTimestamp] = bank;
+ };
+
+ const requestKeyframeBank = async ({
+ packetSink,
+ timestamp,
+ videoSampleSink,
+ src,
+ }: {
+ timestamp: number;
+ packetSink: EncodedPacketSink;
+ videoSampleSink: VideoSampleSink;
+ src: string;
+ }) => {
+ const packet = await packetSink.getKeyPacket(timestamp, {
+ verifyKeyPackets: true,
+ });
+ if (!packet) {
+ throw new Error('No key packet found for timestamp ' + timestamp);
+ }
+
+ const startTimestamp = packet.timestamp;
+ if (sources[src]?.[startTimestamp]) {
+ return sources[src][startTimestamp];
+ }
+
+ const keyframeBank = await getFramesSinceKeyframe({
+ packetSink,
+ videoSampleSink,
+ startPacket: packet,
+ });
+
+ addKeyframeBank({src, bank: keyframeBank});
+
+ return keyframeBank;
+ };
+
+ return {
+ requestKeyframeBank,
+ addKeyframeBank,
+ };
+};
+
+export type KeyframeManager = Awaited<ReturnType<typeof makeKeyframeManager>>;
diff --git a/packages/video/src/new-video-for-rendering.tsx b/packages/video/src/new-video-for-rendering.tsx
index e7fe02bacc..be73fb9382 100644
--- a/packages/video/src/new-video-for-rendering.tsx
+++ b/packages/video/src/new-video-for-rendering.tsx
@@ -12,8 +12,10 @@ import {
random,
useCurrentFrame,
} from 'remotion';
-import type {GetSink} from './get-sink';
-import {getFramesSinceKeyframe, getVideoSink} from './get-sink';
+import type {GetSink} from './get-frames-since-keyframe';
+import {getVideoSink} from './get-frames-since-keyframe';
+import type {KeyframeManager} from './keyframe-manager';
+import {makeKeyframeManager} from './keyframe-manager';
import type {NewVideoProps} from './props';
const {
@@ -126,6 +128,7 @@ export const NewVideoForRendering: React.FC<NewVideoProps> = ({
const {fps} = videoConfig;
const sinkPromise = useRef<Promise<GetSink> | null>(null);
+ const keyframeManager = useRef<KeyframeManager | null>(null);
useLayoutEffect(() => {
if (!canvasRef.current) {
@@ -136,32 +139,35 @@ export const NewVideoForRendering: React.FC<NewVideoProps> = ({
sinkPromise.current = getVideoSink(src);
}
+ if (!keyframeManager.current) {
+ keyframeManager.current = makeKeyframeManager();
+ }
+
const actualFPS = playbackRate ? fps / playbackRate : fps;
const timestamp = frame / actualFPS;
- sinkPromise.current.then(({packetSink, videoSampleSink}) => {
- console.time('getFramesSinceKeyframe');
- getFramesSinceKeyframe({packetSink, videoSampleSink, timestamp}).then(
- async (samples) => {
- let size = 0;
- for await (const sample of samples) {
- console.log(sample.timestamp, sample.allocationSize());
- sample.toVideoFrame();
- size += sample.allocationSize();
- }
-
- console.timeEnd('getFramesSinceKeyframe');
-
- console.log(size);
- },
- );
- });
-
const newHandle = delayRender(`extracting frame number ${frame}`, {
retries: delayRenderRetries ?? undefined,
timeoutInMilliseconds: delayRenderTimeoutInMilliseconds ?? undefined,
});
+ sinkPromise.current?.then(({packetSink, videoSampleSink}) => {
+ const keyframeBank = keyframeManager.current?.requestKeyframeBank({
+ packetSink,
+ videoSampleSink,
+ timestamp,
+ src,
+ });
+ keyframeBank?.then((bank) => {
+ const videoFrame = bank.getFrameFromTimestamp(timestamp);
+ console.log('got frame', videoFrame.timestamp, timestamp);
+ onVideoFrame?.(videoFrame);
+ canvasRef.current?.getContext('2d')?.drawImage(videoFrame, 0, 0);
+
+ continueRender(newHandle);
+ });
+ });
+
return () => {
continueRender(newHandle);
};