Skip to content

🎥 Make videos programmatically with React

hmm

Jonny Burger102180da86f5
diff --git a/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx b/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx
index 8348424e4c..c96236a8ed 100644
--- a/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx
+++ b/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx
@@ -17,6 +17,32 @@ const containerStyle: React.CSSProperties = {
fontFamily: 'Arial, Helvetica',
};
+const calculateTimestampSlots = ({
+ visualizationWidth,
+ fromSeconds,
+ segmentDuration,
+ aspectRatio,
+}: {
+ visualizationWidth: number;
+ fromSeconds: number;
+ segmentDuration: number;
+ aspectRatio: number;
+}) => {
+ const framesFitInWidth = Math.ceil(
+ visualizationWidth / (HEIGHT * aspectRatio),
+ );
+ const timestampTargets: number[] = [];
+ for (let i = 0; i < framesFitInWidth; i++) {
+ timestampTargets.push(
+ fromSeconds +
+ ((segmentDuration * WEBCODECS_TIMESCALE) / framesFitInWidth) *
+ (i + 0.5),
+ );
+ }
+
+ return timestampTargets;
+};
+
const fillWithCachedFrames = ({
ctx,
frameDatabase,
@@ -38,20 +64,15 @@ const fillWithCachedFrames = ({
const segmentDuration = toSeconds - fromSeconds;
const aspectRatio = anyFrame.displayWidth / anyFrame.displayHeight;
- const framesFitInWidth = Math.ceil(
- visualizationWidth / (HEIGHT * aspectRatio),
- );
- const timestampTargets: number[] = [];
- for (let i = 0; i < framesFitInWidth; i++) {
- timestampTargets.push(
- fromSeconds +
- ((segmentDuration * WEBCODECS_TIMESCALE) / framesFitInWidth) *
- (i + 0.5),
- );
- }
+ const timestampTargets = calculateTimestampSlots({
+ visualizationWidth,
+ fromSeconds,
+ segmentDuration,
+ aspectRatio,
+ });
const keys = Array.from(frameDatabase.keys());
- for (let i = 0; i < framesFitInWidth; i++) {
+ for (let i = 0; i < timestampTargets.length; i++) {
const timestamp = timestampTargets[i];
let bestKey: number | undefined;
let bestDistance = Infinity;
@@ -69,14 +90,13 @@ const fillWithCachedFrames = ({
const frame = frameDatabase.get(bestKey);
if (frame) {
- console.log('drawing from cache ', bestKey, bestDistance, frame);
- ctx.drawImage(frame, (i / framesFitInWidth) * visualizationWidth, 0);
- } else {
- console.log('frame not found', bestKey, bestDistance);
+ ctx.drawImage(
+ frame,
+ (i / timestampTargets.length) * visualizationWidth,
+ 0,
+ );
}
}
-
- console.log(framesFitInWidth);
};
export const TimelineVideoInfo: React.FC<{
diff --git a/packages/webcodecs/src/extract-frames.ts b/packages/webcodecs/src/extract-frames.ts
index 8036ccbfdc..7d3572fc2e 100644
--- a/packages/webcodecs/src/extract-frames.ts
+++ b/packages/webcodecs/src/extract-frames.ts
@@ -1,13 +1,15 @@
import type {MediaParserVideoSample} from '@remotion/media-parser';
import {
hasBeenAborted,
+ MediaParserAbortError,
mediaParserController,
WEBCODECS_TIMESCALE,
} from '@remotion/media-parser';
import {parseMediaOnWebWorker} from '@remotion/media-parser/worker';
import {createVideoDecoder} from './create-video-decoder';
+import {withResolvers} from './create/with-resolvers';
-export const extractFrames = async ({
+export const extractFrames = ({
fromSeconds,
toSeconds,
width,
@@ -31,79 +33,94 @@ export const extractFrames = async ({
const expectedFrames: number[] = [];
+ const resolvers = withResolvers<void>();
+
const abortListener = () => {
controller.abort();
+ resolvers.reject(new MediaParserAbortError('Aborted by user'));
};
signal.addEventListener('abort', abortListener, {once: true});
- try {
- await parseMediaOnWebWorker({
- src: new URL(src, window.location.href).toString(),
- acknowledgeRemotionLicense: true,
- controller,
- onVideoTrack: ({track}) => {
- const aspectRatio = track.width / track.height;
- const framesFitInWidth = Math.ceil(width / (height * aspectRatio));
- const timestampTargets: number[] = [];
- for (let i = 0; i < framesFitInWidth; i++) {
- timestampTargets.push(
- fromSeconds +
- ((segmentDuration * WEBCODECS_TIMESCALE) / framesFitInWidth) *
- (i + 0.5),
- );
- }
+ parseMediaOnWebWorker({
+ src: new URL(src, window.location.href),
+ acknowledgeRemotionLicense: true,
+ controller,
+ onVideoTrack: ({track}) => {
+ const aspectRatio = track.width / track.height;
+ const framesFitInWidth = Math.ceil(width / (height * aspectRatio));
+ const timestampTargets: number[] = [];
+ for (let i = 0; i < framesFitInWidth; i++) {
+ timestampTargets.push(
+ fromSeconds +
+ ((segmentDuration * WEBCODECS_TIMESCALE) / framesFitInWidth) *
+ (i + 0.5),
+ );
+ }
- const decoder = createVideoDecoder({
- onFrame: (frame) => {
- if (frame.timestamp >= expectedFrames[0] - 1) {
- expectedFrames.shift();
- onFrame(frame);
- } else {
- frame.close();
- }
- },
- onError: console.error,
- track,
- });
-
- const queued: MediaParserVideoSample[] = [];
-
- return async (sample) => {
- const nextTimestampWeWant = timestampTargets[0];
-
- if (nextTimestampWeWant === undefined) {
- throw new Error('this should not happen');
+ const decoder = createVideoDecoder({
+ onFrame: (frame) => {
+ if (frame.timestamp >= expectedFrames[0] - 1) {
+ expectedFrames.shift();
+ onFrame(frame);
+ } else {
+ frame.close();
}
+ },
+ onError: (e) => {
+ controller.abort();
+ try {
+ decoder.close();
+ } catch {}
- if (sample.type === 'key') {
- queued.length = 0;
- }
+ resolvers.reject(e);
+ },
+ track,
+ });
+
+ const queued: MediaParserVideoSample[] = [];
+
+ return async (sample) => {
+ const nextTimestampWeWant = timestampTargets[0];
+
+ if (nextTimestampWeWant === undefined) {
+ throw new Error('this should not happen');
+ }
+
+ if (sample.type === 'key') {
+ queued.length = 0;
+ }
- queued.push(sample);
+ queued.push(sample);
- if (sample.timestamp > nextTimestampWeWant) {
- expectedFrames.push(timestampTargets.shift() as number);
+ if (sample.timestamp > nextTimestampWeWant) {
+ expectedFrames.push(timestampTargets.shift() as number);
- while (queued.length > 0) {
- const sam = queued.shift();
- await decoder.waitForQueueToBeLessThan(10);
- await decoder.decode(sam as MediaParserVideoSample);
- }
+ while (queued.length > 0) {
+ const sam = queued.shift();
+ await decoder.waitForQueueToBeLessThan(10);
+ await decoder.decode(sam as MediaParserVideoSample);
+ }
- if (timestampTargets.length === 0) {
- await decoder.flush();
- controller.abort();
- }
+ if (timestampTargets.length === 0) {
+ await decoder.flush();
+ controller.abort();
}
- };
- },
+ }
+ };
+ },
+ })
+ .then(() => {
+ resolvers.resolve();
+ })
+ .catch((e) => {
+ if (!hasBeenAborted(e)) {
+ resolvers.reject(3);
+ }
+ })
+ .finally(() => {
+ signal.removeEventListener('abort', abortListener);
});
- } catch (e) {
- if (!hasBeenAborted(e)) {
- throw e;
- }
- } finally {
- signal.removeEventListener('abort', abortListener);
- }
+
+ return resolvers.promise;
};
diff --git a/packages/webcodecs/src/on-frame.ts b/packages/webcodecs/src/on-frame.ts
index d305f6285e..6a60f51c9e 100644
--- a/packages/webcodecs/src/on-frame.ts
+++ b/packages/webcodecs/src/on-frame.ts
@@ -25,7 +25,7 @@ export const onFrame = async ({
rotation,
frame: unrotatedFrame,
resizeOperation,
- videoCodec: outputCodec,
+ needsToBeMultipleOfTwo: outputCodec === 'h264',
});
if (unrotatedFrame !== rotated) {
unrotatedFrame.close();