Skip to content

🎥 Make videos programmatically with React

average color

Jonny Burger8a5daab1c2b5
diff --git a/packages/convert/app/components/FileAvailable.tsx b/packages/convert/app/components/FileAvailable.tsx
index 8ba948d259..c39188e0a2 100644
--- a/packages/convert/app/components/FileAvailable.tsx
+++ b/packages/convert/app/components/FileAvailable.tsx
@@ -41,7 +41,7 @@ export const FileAvailable: React.FC<{
/>
{probeDetails ? null : (
<>
- <div className="h-8 lg:h-0 lg:w-6" />
+ <div className="h-8 lg:h-0 lg:w-8" />
<ConvertUI src={src} />
</>
)}
diff --git a/packages/convert/app/components/Probe.tsx b/packages/convert/app/components/Probe.tsx
index a17089acba..797c5f89ab 100644
--- a/packages/convert/app/components/Probe.tsx
+++ b/packages/convert/app/components/Probe.tsx
@@ -1,14 +1,4 @@
-import type {
- Dimensions,
- MediaParserAudioCodec,
- MediaParserVideoCodec,
- ParseMediaContainer,
- TracksField,
-} from '@remotion/media-parser';
-import {parseMedia} from '@remotion/media-parser';
-import {fetchReader} from '@remotion/media-parser/fetch';
-import {webFileReader} from '@remotion/media-parser/web-file';
-import React, {useCallback, useEffect, useMemo, useState} from 'react';
+import React, {useCallback, useMemo, useState} from 'react';
import {Source} from '~/lib/convert-state';
import {AudioTrackOverview} from './AudioTrackOverview';
import {ContainerOverview} from './ContainerOverview';
@@ -27,188 +17,25 @@ import {
import {ScrollArea} from './ui/scroll-area';
import {Separator} from './ui/separator';
import {Skeleton} from './ui/skeleton';
+import {useProbe} from './use-probe';
export const Probe: React.FC<{
readonly src: Source;
readonly setProbeDetails: React.Dispatch<React.SetStateAction<boolean>>;
readonly probeDetails: boolean;
}> = ({src, probeDetails, setProbeDetails}) => {
- const [audioCodec, setAudioCodec] = useState<MediaParserAudioCodec | null>(
- null,
- );
- const [fps, setFps] = useState<number | null | undefined>(undefined);
- const [durationInSeconds, setDurationInSeconds] = useState<number | null>(
- null,
- );
- const [dimensions, setDimensions] = useState<Dimensions | null>(null);
- const [name, setName] = useState<string | null>(null);
- const [videoCodec, setVideoCodec] = useState<MediaParserVideoCodec | null>(
- null,
- );
- const [size, setSize] = useState<number | null>(null);
- const [tracks, setTracks] = useState<TracksField | null>(null);
- const [container, setContainer] = useState<ParseMediaContainer | null>(null);
- const [thumbnail, setThumbnail] = useState<VideoFrame | null>(null);
-
- const getStart = useCallback(() => {
- const controller = new AbortController();
- let hasFps = false;
- let hasDuration = false;
- let hasDimensions = false;
- let hasVideoCodec = false;
- let hasAudioCodec = false;
- let hasSize = false;
- let hasName = false;
- let hasFrame = false;
- let hasContainer = false;
- let hasTracks = false;
-
- const cancelIfDone = () => {
- if (
- hasFps &&
- hasDuration &&
- hasDimensions &&
- hasVideoCodec &&
- hasAudioCodec &&
- hasSize &&
- hasName &&
- hasFrame &&
- hasContainer &&
- hasTracks
- ) {
- controller.abort(new Error('Cancelled (all info)'));
- }
- };
-
- parseMedia({
- src: src.type === 'file' ? src.file : src.url,
- fields: {
- dimensions: true,
- videoCodec: true,
- size: true,
- durationInSeconds: true,
- audioCodec: true,
- fps: true,
- name: true,
- tracks: true,
- container: true,
- },
- reader: src.type === 'file' ? webFileReader : fetchReader,
- signal: controller.signal,
- onVideoTrack: async (track) => {
- if (typeof VideoDecoder === 'undefined') {
- return null;
- }
-
- let frames = 0;
-
- const decoder = new VideoDecoder({
- error: (error) => {
- // eslint-disable-next-line no-console
- console.log(error);
- },
- output(frame) {
- frames++;
- if (frames < 30) {
- frame.close();
- return;
- }
-
- setThumbnail((f) => {
- if (f) {
- frame.close();
- return f;
- }
-
- return frame;
- });
- hasFrame = true;
- cancelIfDone();
- },
- });
-
- if (!(await VideoDecoder.isConfigSupported(track)).supported) {
- return null;
- }
-
- // TODO: See if possible
- decoder.configure(track);
- return (sample) => {
- if (hasFrame) {
- return;
- }
-
- decoder.decode(new EncodedVideoChunk(sample));
- };
- },
- onContainer(c) {
- hasContainer = true;
- setContainer(c);
- cancelIfDone();
- },
- onAudioCodec: (codec) => {
- hasAudioCodec = true;
- setAudioCodec(codec);
- cancelIfDone();
- },
- onFps: (f) => {
- hasFps = true;
- setFps(f);
- cancelIfDone();
- },
- onDurationInSeconds: (d) => {
- hasDuration = true;
- setDurationInSeconds(d);
- cancelIfDone();
- },
- onName: (n) => {
- hasName = true;
- setName(n);
- cancelIfDone();
- },
- onDimensions(dim) {
- hasDimensions = true;
- setDimensions(dim);
- cancelIfDone();
- },
- onVideoCodec: (codec) => {
- hasVideoCodec = true;
- setVideoCodec(codec);
- cancelIfDone();
- },
- onTracks: (trx) => {
- hasTracks = true;
- setTracks(trx);
- cancelIfDone();
- },
- onSize(s) {
- hasSize = true;
- setSize(s);
- cancelIfDone();
- },
- })
- .then(() => {})
- .catch((err) => {
- if ((err as Error).stack?.includes('Cancelled')) {
- return;
- }
- if ((err as Error).stack?.toLowerCase()?.includes('aborted')) {
- return;
- }
-
- // eslint-disable-next-line no-console
- console.log(err);
- });
-
- return controller;
- }, [src]);
-
- useEffect(() => {
- const start = getStart();
- return () => {
- start.abort(new Error('Cancelled (strict mode)'));
- };
- }, [getStart]);
+ const {
+ audioCodec,
+ fps,
+ tracks,
+ name,
+ thumbnail,
+ container,
+ dimensions,
+ size,
+ videoCodec,
+ durationInSeconds,
+ } = useProbe(src);
const onClick = useCallback(() => {
setProbeDetails((p) => !p);
diff --git a/packages/convert/app/components/VideoThumbnail.tsx b/packages/convert/app/components/VideoThumbnail.tsx
index 5c41e6918f..819265099c 100644
--- a/packages/convert/app/components/VideoThumbnail.tsx
+++ b/packages/convert/app/components/VideoThumbnail.tsx
@@ -1,20 +1,25 @@
-import {useEffect, useRef} from 'react';
+import {FastAverageColor} from 'fast-average-color';
+import {useEffect, useRef, useState} from 'react';
-const THUMBNAIL_WIDTH = 350;
-const THUMBNAIL_HEIGHT = Math.round((THUMBNAIL_WIDTH / 16) * 9);
+const THUMBNAIL_HEIGHT = Math.round((350 / 16) * 9);
export const VideoThumbnail: React.FC<{
readonly thumbnail: VideoFrame | null;
}> = ({thumbnail}) => {
const ref = useRef<HTMLCanvasElement>(null);
+ const scaleRatio = thumbnail ? THUMBNAIL_HEIGHT / thumbnail.displayHeight : 0;
+ const width = thumbnail ? Math.round(thumbnail.displayWidth * scaleRatio) : 0;
+
+ const [color, setColor] = useState<string>('transparent');
+
useEffect(() => {
if (!thumbnail) {
return;
}
createImageBitmap(thumbnail, {
- resizeWidth: THUMBNAIL_WIDTH,
+ resizeWidth: width,
resizeHeight: THUMBNAIL_HEIGHT,
}).then((bitmap) => {
const twoDContext = ref.current?.getContext('2d');
@@ -23,21 +28,25 @@ export const VideoThumbnail: React.FC<{
}
twoDContext.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height);
- thumbnail.close();
+ const color = new FastAverageColor().getColor(ref.current);
+ setColor(color.hex);
});
- }, [thumbnail]);
+ }, [scaleRatio, thumbnail, width]);
return (
- <canvas
- ref={ref}
- width={THUMBNAIL_WIDTH}
- height={THUMBNAIL_HEIGHT}
- style={{
- maxHeight: THUMBNAIL_HEIGHT,
- width: THUMBNAIL_WIDTH,
- aspectRatio: '16 / 9',
- }}
- className="border-b-2 border-black"
- />
+ <div
+ className="border-b-2 border-black flex justify-center"
+ style={{height: THUMBNAIL_HEIGHT, background: color}}
+ >
+ <canvas
+ ref={ref}
+ width={width}
+ height={THUMBNAIL_HEIGHT}
+ style={{
+ maxHeight: THUMBNAIL_HEIGHT,
+ width,
+ }}
+ />
+ </div>
);
};
diff --git a/packages/convert/app/components/use-probe.ts b/packages/convert/app/components/use-probe.ts
new file mode 100644
index 0000000000..96585bc8e8
--- /dev/null
+++ b/packages/convert/app/components/use-probe.ts
@@ -0,0 +1,216 @@
+import {
+ Dimensions,
+ MediaParserAudioCodec,
+ MediaParserVideoCodec,
+ parseMedia,
+ ParseMediaContainer,
+ TracksField,
+} from '@remotion/media-parser';
+import {fetchReader} from '@remotion/media-parser/fetch';
+import {webFileReader} from '@remotion/media-parser/web-file';
+import {useCallback, useEffect, useMemo, useState} from 'react';
+import {Source} from '~/lib/convert-state';
+
+export const useProbe = (src: Source) => {
+ const [audioCodec, setAudioCodec] = useState<MediaParserAudioCodec | null>(
+ null,
+ );
+ const [fps, setFps] = useState<number | null | undefined>(undefined);
+ const [durationInSeconds, setDurationInSeconds] = useState<number | null>(
+ null,
+ );
+ const [dimensions, setDimensions] = useState<Dimensions | null>(null);
+ const [name, setName] = useState<string | null>(null);
+ const [videoCodec, setVideoCodec] = useState<MediaParserVideoCodec | null>(
+ null,
+ );
+ const [size, setSize] = useState<number | null>(null);
+ const [tracks, setTracks] = useState<TracksField | null>(null);
+ const [container, setContainer] = useState<ParseMediaContainer | null>(null);
+ const [thumbnail, setThumbnail] = useState<VideoFrame | null>(null);
+
+ const getStart = useCallback(() => {
+ const controller = new AbortController();
+ let hasFps = false;
+ let hasDuration = false;
+ let hasDimensions = false;
+ let hasVideoCodec = false;
+ let hasAudioCodec = false;
+ let hasSize = false;
+ let hasName = false;
+ let hasFrame = false;
+ let hasContainer = false;
+ let hasTracks = false;
+
+ const cancelIfDone = () => {
+ if (
+ hasFps &&
+ hasDuration &&
+ hasDimensions &&
+ hasVideoCodec &&
+ hasAudioCodec &&
+ hasSize &&
+ hasName &&
+ hasFrame &&
+ hasContainer &&
+ hasTracks
+ ) {
+ controller.abort(new Error('Cancelled (all info)'));
+ }
+ };
+
+ parseMedia({
+ src: src.type === 'file' ? src.file : src.url,
+ fields: {
+ dimensions: true,
+ videoCodec: true,
+ size: true,
+ durationInSeconds: true,
+ audioCodec: true,
+ fps: true,
+ name: true,
+ tracks: true,
+ container: true,
+ },
+ reader: src.type === 'file' ? webFileReader : fetchReader,
+ signal: controller.signal,
+ onVideoTrack: async (track) => {
+ if (typeof VideoDecoder === 'undefined') {
+ return null;
+ }
+
+ let frames = 0;
+
+ const decoder = new VideoDecoder({
+ error: (error) => {
+ // eslint-disable-next-line no-console
+ console.log(error);
+ },
+ output(frame) {
+ frames++;
+ if (frames < 30) {
+ frame.close();
+ return;
+ }
+ if (hasFrame) {
+ cancelIfDone();
+ frame.close();
+ return;
+ }
+
+ setThumbnail(frame.clone());
+ frame.clone();
+ hasFrame = true;
+ cancelIfDone();
+ },
+ });
+
+ if (!(await VideoDecoder.isConfigSupported(track)).supported) {
+ return null;
+ }
+
+ // TODO: See if possible
+ decoder.configure(track);
+ return (sample) => {
+ if (hasFrame) {
+ return;
+ }
+
+ decoder.decode(new EncodedVideoChunk(sample));
+ };
+ },
+ onContainer(c) {
+ hasContainer = true;
+ setContainer(c);
+ cancelIfDone();
+ },
+ onAudioCodec: (codec) => {
+ hasAudioCodec = true;
+ setAudioCodec(codec);
+ cancelIfDone();
+ },
+ onFps: (f) => {
+ hasFps = true;
+ setFps(f);
+ cancelIfDone();
+ },
+ onDurationInSeconds: (d) => {
+ hasDuration = true;
+ setDurationInSeconds(d);
+ cancelIfDone();
+ },
+ onName: (n) => {
+ hasName = true;
+ setName(n);
+ cancelIfDone();
+ },
+ onDimensions(dim) {
+ hasDimensions = true;
+ setDimensions(dim);
+ cancelIfDone();
+ },
+ onVideoCodec: (codec) => {
+ hasVideoCodec = true;
+ setVideoCodec(codec);
+ cancelIfDone();
+ },
+ onTracks: (trx) => {
+ hasTracks = true;
+ setTracks(trx);
+ cancelIfDone();
+ },
+ onSize(s) {
+ hasSize = true;
+ setSize(s);
+ cancelIfDone();
+ },
+ })
+ .then(() => {})
+ .catch((err) => {
+ if ((err as Error).stack?.includes('Cancelled')) {
+ return;
+ }
+ if ((err as Error).stack?.toLowerCase()?.includes('aborted')) {
+ return;
+ }
+
+ // eslint-disable-next-line no-console
+ console.log(err);
+ });
+
+ return controller;
+ }, [src]);
+
+ useEffect(() => {
+ const start = getStart();
+ return () => {
+ start.abort(new Error('Cancelled (strict mode)'));
+ };
+ }, [getStart]);
+
+ return useMemo(() => {
+ return {
+ tracks,
+ audioCodec,
+ fps,
+ thumbnail,
+ name,
+ container,
+ dimensions,
+ videoCodec,
+ size,
+ durationInSeconds,
+ };
+ }, [
+ audioCodec,
+ container,
+ dimensions,
+ fps,
+ name,
+ size,
+ thumbnail,
+ tracks,
+ videoCodec,
+ durationInSeconds,
+ ]);
+};
diff --git a/packages/convert/package.json b/packages/convert/package.json
index 87fcf3a1dc..74e61ccc9c 100644
--- a/packages/convert/package.json
+++ b/packages/convert/package.json
@@ -30,7 +30,8 @@
"react": "18.3.1",
"react-dom": "18.3.1",
"tailwind-merge": "2.5.2",
- "tailwindcss-animate": "^1.0.7"
+ "tailwindcss-animate": "^1.0.7",
+ "fast-average-color": "9.4.0"
},
"devDependencies": {
"@remix-run/dev": "^2.11.2",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 779bb942c4..368d0bb0b2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -406,6 +406,9 @@ importers:
clsx:
specifier: 2.1.1
version: 2.1.1
+ fast-average-color:
+ specifier: 9.4.0
+ version: 9.4.0
isbot:
specifier: 4.1.0
version: 4.1.0
@@ -19401,6 +19404,11 @@ packages:
- supports-color
dev: false
+ resolution: {integrity: sha512-bvM8vV6YwK07dPbzFz77zJaBcfF6ABVfgNwaxVgXc2G+o0e/tzLCF9WU8Ryp1r0Nkk6JuJNsWCzbb4cLOMlB+Q==}
+ engines: {node: '>= 12'}
+ dev: false
+
resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}