Skip to content

🎥 Make videos programmatically with React

remotion.dev/convert: Make preview smoother

Jonny Burgerb98068ece80c
diff --git a/packages/convert/app/components/ContainerOverview.tsx b/packages/convert/app/components/ContainerOverview.tsx
index 1a6320ccdd..ae7b324718 100644
--- a/packages/convert/app/components/ContainerOverview.tsx
+++ b/packages/convert/app/components/ContainerOverview.tsx
@@ -45,22 +45,22 @@ export const ContainerOverview: React.FC<{
<Table className="table-fixed">
<TableBody>
<TableRow>
- <TableCell className="font-brand">Size</TableCell>
+ <TableCell className="font-brand">Container</TableCell>
<TableCell className="text-right">
- {size === null ? (
- <Skeleton className="h-3 w-[100px] inline-block" />
+ {container ? (
+ <>{renderHumanReadableContainer(container)}</>
) : (
- <>{formatBytes(size)}</>
+ <Skeleton className="h-3 w-[100px] inline-block" />
)}
</TableCell>
</TableRow>
<TableRow>
- <TableCell className="font-brand">Container</TableCell>
+ <TableCell className="font-brand">Size</TableCell>
<TableCell className="text-right">
- {container ? (
- <>{renderHumanReadableContainer(container)}</>
- ) : (
+ {size === null ? (
<Skeleton className="h-3 w-[100px] inline-block" />
+ ) : (
+ <>{formatBytes(size)}</>
)}
</TableCell>
</TableRow>
diff --git a/packages/convert/app/components/ConvertProgress.tsx b/packages/convert/app/components/ConvertProgress.tsx
index 72d870bd58..8e12f2c6ce 100644
--- a/packages/convert/app/components/ConvertProgress.tsx
+++ b/packages/convert/app/components/ConvertProgress.tsx
@@ -24,6 +24,7 @@ export const ConvertProgress: React.FC<{
<>
<VideoThumbnail
ref={convertProgressRef}
+ initialReveal
smallThumbOnMobile={false}
rotation={0}
mirrorHorizontal={false}
diff --git a/packages/convert/app/components/FileAvailable.tsx b/packages/convert/app/components/FileAvailable.tsx
index 9334aa77aa..0811cb3fd5 100644
--- a/packages/convert/app/components/FileAvailable.tsx
+++ b/packages/convert/app/components/FileAvailable.tsx
@@ -10,9 +10,12 @@ import ConvertUI from './ConvertUi';
import {Footer} from './Footer';
import {Probe} from './Probe';
import {VideoThumbnailRef} from './VideoThumbnail';
+import {getBrightnessOfFrame} from './get-brightness-of-frame';
import {Button} from './ui/button';
import {useProbe} from './use-probe';
+const idealBrightness = 0.8;
+
export const FileAvailable: React.FC<{
readonly src: Source;
readonly setSrc: React.Dispatch<React.SetStateAction<Source | null>>;
@@ -26,10 +29,24 @@ export const FileAvailable: React.FC<{
setSrc(null);
}, [setSrc]);
+ const bestBrightness = useRef<number | null>(null);
+
const videoThumbnailRef = useRef<VideoThumbnailRef>(null);
- const onVideoThumbnail = useCallback((frame: VideoFrame) => {
- videoThumbnailRef.current?.draw(frame);
+ const onVideoThumbnail = useCallback(async (frame: VideoFrame) => {
+ const brightness = await getBrightnessOfFrame(frame);
+ const differenceToIdeal = Math.abs(brightness - idealBrightness);
+ if (
+ bestBrightness.current === null ||
+ differenceToIdeal < bestBrightness.current
+ ) {
+ bestBrightness.current = differenceToIdeal;
+ videoThumbnailRef.current?.draw(frame);
+ }
+ }, []);
+
+ const onDone = useCallback(() => {
+ videoThumbnailRef.current?.reveal();
}, []);
const onProgress: ParseMediaOnProgress = useCallback(
@@ -54,7 +71,12 @@ export const FileAvailable: React.FC<{
const [enableRotateOrMirrow, setEnableRotateOrMirror] =
useState<RotateOrMirrorState>(() => defaultRotateOrMirorState(routeAction));
- const {err} = useThumbnail({src, logLevel: 'verbose', onVideoThumbnail});
+ const {err} = useThumbnail({
+ src,
+ logLevel: 'verbose',
+ onVideoThumbnail,
+ onDone,
+ });
const probeResult = useProbe({
src,
logLevel: 'verbose',
diff --git a/packages/convert/app/components/Main.tsx b/packages/convert/app/components/Main.tsx
index 23c64f328b..18e0655198 100644
--- a/packages/convert/app/components/Main.tsx
+++ b/packages/convert/app/components/Main.tsx
@@ -20,7 +20,7 @@ export const Main: React.FC<{
}, [routeAction]);
return (
- <div className="font-sans min-h-screen ">
+ <div className="font-sans min-h-screen">
{src ? (
<FileAvailable
key={src.type === 'url' ? src.url : src.file.name}
diff --git a/packages/convert/app/components/Probe.tsx b/packages/convert/app/components/Probe.tsx
index 48845d21e7..04ec6fe65b 100644
--- a/packages/convert/app/components/Probe.tsx
+++ b/packages/convert/app/components/Probe.tsx
@@ -80,8 +80,6 @@ export const Probe: React.FC<{
return sortedTracks[trackDetails];
}, [probeDetails, sortedTracks, trackDetails]);
- const isCompact = isNarrow && !probeDetails;
-
return (
<Card className="w-full lg:w-[350px] overflow-hidden">
<div className="flex flex-row lg:flex-col w-full border-b-2 border-black">
@@ -92,6 +90,7 @@ export const Probe: React.FC<{
rotation={userRotation - (rotation ?? 0)}
mirrorHorizontal={mirrorHorizontal}
mirrorVertical={mirrorVertical}
+ initialReveal={false}
/>
)}
<CardHeader className="p-3 lg:p-4 w-full">
@@ -107,13 +106,13 @@ export const Probe: React.FC<{
</p>
</CardDescription>
) : null}
- {done ? (
- <CardDescription className="!mt-0">
+ <CardDescription className="!mt-0 overflow-hidden whitespace-nowrap text-ellipsis">
+ {done ? (
<SourceLabel src={src} />
- </CardDescription>
- ) : (
- <div id="not-done" />
- )}
+ ) : (
+ <span id="not-done">0% read</span>
+ )}
+ </CardDescription>
</CardHeader>
</div>
{sortedTracks.length && probeDetails ? (
@@ -127,7 +126,7 @@ export const Probe: React.FC<{
/>
</div>
) : null}
- {isCompact ? null : (
+ {isNarrow ? null : (
<>
<ScrollArea height={300} className="flex-1">
{selectedTrack === null ? (
diff --git a/packages/convert/app/components/SourceLabel.tsx b/packages/convert/app/components/SourceLabel.tsx
index 39a44e2155..c76877a9bf 100644
--- a/packages/convert/app/components/SourceLabel.tsx
+++ b/packages/convert/app/components/SourceLabel.tsx
@@ -15,7 +15,7 @@ export const SourceLabel: React.FC<{
.replace(/^http:\/\//, '');
return (
- <span className="font-brand">
+ <span className="font-brand white ">
From{' '}
<a
href={src.url}
diff --git a/packages/convert/app/components/VideoThumbnail.tsx b/packages/convert/app/components/VideoThumbnail.tsx
index 7cc087e4f7..2c05539cd8 100644
--- a/packages/convert/app/components/VideoThumbnail.tsx
+++ b/packages/convert/app/components/VideoThumbnail.tsx
@@ -9,23 +9,32 @@ type Props = {
readonly rotation: number;
readonly mirrorHorizontal: boolean;
readonly mirrorVertical: boolean;
+ readonly initialReveal: boolean;
};
export type VideoThumbnailRef = {
draw: (videoFrame: VideoFrame) => void;
+ reveal: () => void;
};
const VideoThumbnailRefForward: React.ForwardRefRenderFunction<
VideoThumbnailRef,
Props
> = (
- {smallThumbOnMobile, rotation, mirrorHorizontal, mirrorVertical},
+ {
+ smallThumbOnMobile,
+ rotation,
+ mirrorHorizontal,
+ mirrorVertical,
+ initialReveal,
+ },
forwardedRef,
) => {
const ref = useRef<HTMLCanvasElement>(null);
const [color, setColor] = useState<string>('transparent');
const [dimensions, setDimensions] = useState<{width: number}>({width: 0});
+ const [reveal, setReveal] = useState(initialReveal);
const drawThumbnail = useCallback((unrotatedVideoFrame: VideoFrame) => {
const scaleRatio = THUMBNAIL_HEIGHT / unrotatedVideoFrame.displayHeight;
@@ -56,6 +65,7 @@ const VideoThumbnailRefForward: React.ForwardRefRenderFunction<
forwardedRef,
() => ({
draw: drawThumbnail,
+ reveal: () => setReveal(true),
}),
[drawThumbnail],
);
@@ -74,7 +84,10 @@ const VideoThumbnailRefForward: React.ForwardRefRenderFunction<
// +2 to account for border
style={{height: THUMBNAIL_HEIGHT * scale + 2}}
>
- <div className="flex justify-center" style={{backgroundColor: color}}>
+ <div
+ className="flex justify-center transition-opacity"
+ style={{backgroundColor: color, opacity: reveal ? 1 : 0}}
+ >
<canvas
ref={ref}
height={THUMBNAIL_HEIGHT}
diff --git a/packages/convert/app/components/get-brightness-of-frame.ts b/packages/convert/app/components/get-brightness-of-frame.ts
new file mode 100644
index 0000000000..8e92eb751c
--- /dev/null
+++ b/packages/convert/app/components/get-brightness-of-frame.ts
@@ -0,0 +1,20 @@
+export const getBrightnessOfFrame = async (frame: VideoFrame) => {
+ const bitmap = await createImageBitmap(frame);
+ const canvas = document.createElement('canvas');
+ canvas.width = bitmap.width;
+ canvas.height = bitmap.height;
+ const context = canvas.getContext('2d');
+ if (context === null) {
+ throw new Error('Could not get 2d context');
+ }
+ context.drawImage(bitmap, 0, 0);
+ const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
+ let sum = 0;
+ for (let i = 0; i < imageData.data.length; i += 4) {
+ sum +=
+ imageData.data[i] * 0.299 +
+ imageData.data[i + 1] * 0.587 +
+ imageData.data[i + 2] * 0.114;
+ }
+ return sum / (imageData.data.length / 4) / 255;
+};
diff --git a/packages/convert/app/lib/is-narrow.ts b/packages/convert/app/lib/is-narrow.ts
index 755656e46f..cd6269350e 100644
--- a/packages/convert/app/lib/is-narrow.ts
+++ b/packages/convert/app/lib/is-narrow.ts
@@ -3,7 +3,9 @@ import {useEffect, useState} from 'react';
const query = '(min-width: 1024px)';
export function useIsNarrow() {
- const [matches, setMatches] = useState(false);
+ const [matches, setMatches] = useState(() =>
+ typeof window === 'undefined' ? true : window.matchMedia(query).matches,
+ );
useEffect(() => {
const mediaQuery = window.matchMedia(query);
diff --git a/packages/convert/app/lib/use-thumbnail.ts b/packages/convert/app/lib/use-thumbnail.ts
index f9a1699cb0..0d5dad6453 100644
--- a/packages/convert/app/lib/use-thumbnail.ts
+++ b/packages/convert/app/lib/use-thumbnail.ts
@@ -8,10 +8,12 @@ export const useThumbnail = ({
src,
logLevel,
onVideoThumbnail,
+ onDone,
}: {
src: Source;
logLevel: LogLevel;
- onVideoThumbnail: (videoFrame: VideoFrame) => void;
+ onVideoThumbnail: (videoFrame: VideoFrame) => Promise<void>;
+ onDone: () => void;
}) => {
const [err, setError] = useState<Error | null>(null);
@@ -37,8 +39,9 @@ export const useThumbnail = ({
abortController.abort();
},
output(frame) {
- onVideoThumbnail(frame);
- frame.close();
+ onVideoThumbnail(frame).then(() => {
+ frame.close();
+ });
},
});
@@ -51,32 +54,42 @@ export const useThumbnail = ({
decoder.configure(track);
return (sample) => {
- frames++;
- if (frames >= 10) {
+ if (sample.type !== 'key') {
+ return;
+ }
+
+ if (frames >= 3) {
abortController.abort();
+ return;
}
+ frames++;
+ decoder.flush();
decoder.decode(new EncodedVideoChunk(sample));
};
},
- }).catch((err) => {
- if ((err as Error).stack?.includes('Cancelled')) {
- return;
- }
- if ((err as Error).stack?.toLowerCase()?.includes('aborted')) {
- return;
- }
- // firefox
- if ((err as Error).message?.toLowerCase()?.includes('aborted')) {
- return;
- }
+ })
+ .catch((err) => {
+ if ((err as Error).stack?.includes('Cancelled')) {
+ return;
+ }
+ if ((err as Error).stack?.toLowerCase()?.includes('aborted')) {
+ return;
+ }
+ // firefox
+ if ((err as Error).message?.toLowerCase()?.includes('aborted')) {
+ return;
+ }
- console.log(err);
- setError(err as Error);
- });
+ console.log(err);
+ setError(err as Error);
+ })
+ .finally(() => {
+ onDone();
+ });
return abortController;
- }, [logLevel, onVideoThumbnail, src]);
+ }, [logLevel, onDone, onVideoThumbnail, src]);
useEffect(() => {
const task = execute();
diff --git a/packages/media-parser/src/parse-media.ts b/packages/media-parser/src/parse-media.ts
index 69461d0265..32bea1d8be 100644
--- a/packages/media-parser/src/parse-media.ts
+++ b/packages/media-parser/src/parse-media.ts
@@ -142,7 +142,7 @@ export const parseMedia: ParseMedia = async function <
});
triggerInfoEmit();
if (parseResult && parseResult.status === 'incomplete') {
- Log.verbose(
+ Log.trace(
logLevel,
'Continuing parsing of file, currently at position',
iterator.counter.getOffset(),