Skip to content

🎥 Make videos programmatically with React

handle rotation

Jonny Burger1bb7e08db43c
diff --git a/packages/convert/app/components/ConvertProgress.tsx b/packages/convert/app/components/ConvertProgress.tsx
index c305c30eb3..b8f8813449 100644
--- a/packages/convert/app/components/ConvertProgress.tsx
+++ b/packages/convert/app/components/ConvertProgress.tsx
@@ -25,8 +25,8 @@ export const ConvertProgress: React.FC<{
<VideoThumbnail
ref={convertProgressRef}
smallThumbOnMobile={false}
+ rotation={0}
/>
- <div className="border-b-2 border-black" />
</>
) : null}
<div className="h-5 overflow-hidden">
diff --git a/packages/convert/app/components/ConvertUi.tsx b/packages/convert/app/components/ConvertUi.tsx
index aad3ace390..af529070c7 100644
--- a/packages/convert/app/components/ConvertUi.tsx
+++ b/packages/convert/app/components/ConvertUi.tsx
@@ -13,7 +13,6 @@ import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {ConvertState, Source} from '~/lib/convert-state';
import {
ConvertSections,
- defaultRotateOrMirorState,
getOrderOfSections,
isConvertEnabledByDefault,
RotateOrMirrorState,
@@ -40,6 +39,10 @@ export default function ConvertUI({
duration,
logLevel,
action,
+ enableRotateOrMirrow,
+ setEnableRotateOrMirror,
+ userRotation,
+ setRotation,
}: {
readonly src: Source;
readonly setSrc: React.Dispatch<React.SetStateAction<Source | null>>;
@@ -49,6 +52,12 @@ export default function ConvertUI({
readonly duration: number | null;
readonly logLevel: LogLevel;
readonly action: RouteAction;
+ readonly enableRotateOrMirrow: RotateOrMirrorState;
+ readonly setEnableRotateOrMirror: React.Dispatch<
+ React.SetStateAction<RotateOrMirrorState | null>
+ >;
+ readonly userRotation: number;
+ readonly setRotation: React.Dispatch<React.SetStateAction<number>>;
}) {
const [container, setContainer] = useState<ConvertMediaContainer>(() =>
getDefaultContainerForConversion(src),
@@ -66,8 +75,6 @@ export default function ConvertUI({
const [enableConvert, setEnableConvert] = useState(() =>
isConvertEnabledByDefault(action),
);
- const [enableRotateOrMirrow, setEnableRotateOrMirror] =
- useState<RotateOrMirrorState>(() => defaultRotateOrMirorState(action));
const order = useMemo(() => {
return Object.entries(getOrderOfSections(action))
@@ -77,17 +84,6 @@ export default function ConvertUI({
.map(([section]) => section as ConvertSections);
}, [action]);
- const [rotation, setRotation] = useState(90);
-
- const actualRotation = useMemo(() => {
- if (enableRotateOrMirrow !== 'rotate') {
- // TODO: Native rotation
- return 0;
- }
-
- return rotation;
- }, [enableRotateOrMirrow, rotation]);
-
const supportedConfigs = useSupportedConfigs({container, tracks, logLevel});
const setVideoConfigIndex = useCallback((trackId: number, i: number) => {
@@ -122,13 +118,14 @@ export default function ConvertUI({
vertical: flipVertical && enableRotateOrMirrow === 'mirror',
});
if (videoFrames % 15 === 0) {
+ // TODO: Pass rotation that was applied
convertProgressRef.current?.draw(flipped);
}
videoFrames++;
return flipped;
},
- rotate: actualRotation,
+ rotate: userRotation,
logLevel,
onProgress: (s) => {
setState({
@@ -214,7 +211,7 @@ export default function ConvertUI({
};
}, [
src,
- actualRotation,
+ userRotation,
container,
flipHorizontal,
flipVertical,
@@ -253,7 +250,7 @@ export default function ConvertUI({
}
return null;
});
- }, []);
+ }, [setEnableRotateOrMirror]);
const onRotateClick = useCallback(() => {
setEnableRotateOrMirror((m) => {
@@ -262,7 +259,7 @@ export default function ConvertUI({
}
return null;
});
- }, []);
+ }, [setEnableRotateOrMirror]);
if (state.type === 'error') {
return (
@@ -289,6 +286,7 @@ export default function ConvertUI({
supportedConfigs !== null &&
isReencoding({supportedConfigs, videoConfigIndex})
}
+ userRotation={userRotation}
/>
<div className="h-2" />
<Button className="block w-full" type="button" onClick={cancel}>
@@ -311,6 +309,7 @@ export default function ConvertUI({
supportedConfigs !== null &&
isReencoding({supportedConfigs, videoConfigIndex})
}
+ userRotation={userRotation}
/>
<div className="h-2" />
<ConversionDone {...{container, name, setState, state, setSrc}} />
@@ -336,7 +335,7 @@ export default function ConvertUI({
{order.map((section) => {
if (section === 'convert') {
return (
- <div>
+ <div key="convert">
<ConvertUiSection
active={enableConvert}
setActive={setEnableConvert}
@@ -371,7 +370,7 @@ export default function ConvertUI({
if (section === 'mirror') {
return (
- <>
+ <div key="mirror">
<ConvertUiSection
active={enableRotateOrMirrow === 'mirror'}
setActive={onMirrorClick}
@@ -387,14 +386,13 @@ export default function ConvertUI({
setFlipVertical={setFlipVertical}
/>
) : null}
- </>
+ </div>
);
}
if (section === 'rotate') {
return (
- <>
- {' '}
+ <div key="rotate">
<ConvertUiSection
active={enableRotateOrMirrow === 'rotate'}
setActive={onRotateClick}
@@ -404,11 +402,11 @@ export default function ConvertUI({
{enableRotateOrMirrow === 'rotate' ? (
<RotateComponents
canPixelManipulate={canPixelManipulate}
- rotation={rotation}
+ rotation={userRotation}
setRotation={setRotation}
/>
) : null}
- </>
+ </div>
);
}
diff --git a/packages/convert/app/components/FileAvailable.tsx b/packages/convert/app/components/FileAvailable.tsx
index f05a592870..869952b7f2 100644
--- a/packages/convert/app/components/FileAvailable.tsx
+++ b/packages/convert/app/components/FileAvailable.tsx
@@ -1,6 +1,8 @@
import {ParseMediaOnProgress} from '@remotion/media-parser';
-import React, {useCallback, useRef, useState} from 'react';
+import {WebCodecsInternals} from '@remotion/webcodecs';
+import React, {useCallback, useMemo, useRef, useState} from 'react';
import {Source} from '~/lib/convert-state';
+import {defaultRotateOrMirorState, RotateOrMirrorState} from '~/lib/default-ui';
import {formatBytes} from '~/lib/format-bytes';
import {RouteAction} from '~/seo';
import ConvertUI from './ConvertUi';
@@ -23,12 +25,9 @@ export const FileAvailable: React.FC<{
const videoThumbnailRef = useRef<VideoThumbnailRef>(null);
- const onVideoThumbnail = useCallback(
- (frame: VideoFrame, rotation: number) => {
- videoThumbnailRef.current?.draw(frame, rotation);
- },
- [],
- );
+ const onVideoThumbnail = useCallback((frame: VideoFrame) => {
+ videoThumbnailRef.current?.draw(frame);
+ }, []);
const onProgress: ParseMediaOnProgress = useCallback(
async ({bytes, percentage}) => {
@@ -49,6 +48,9 @@ export const FileAvailable: React.FC<{
[],
);
+ const [enableRotateOrMirrow, setEnableRotateOrMirror] =
+ useState<RotateOrMirrorState>(() => defaultRotateOrMirorState(routeAction));
+
const probeResult = useProbe({
src,
logLevel: 'verbose',
@@ -56,6 +58,16 @@ export const FileAvailable: React.FC<{
onVideoThumbnail,
});
+ const [userRotation, setRotation] = useState(90);
+
+ const actualUserRotation = useMemo(() => {
+ if (enableRotateOrMirrow !== 'rotate') {
+ return 0;
+ }
+
+ return WebCodecsInternals.normalizeVideoRotation(userRotation);
+ }, [enableRotateOrMirrow, userRotation]);
+
return (
<div>
<div className="overflow-y-auto w-full lg:flex lg:justify-center pt-6 pb-10 px-4 bg-slate-50 min-h-[100vh]">
@@ -83,6 +95,7 @@ export const FileAvailable: React.FC<{
setProbeDetails={setProbeDetails}
probeResult={probeResult}
videoThumbnailRef={videoThumbnailRef}
+ userRotation={actualUserRotation}
/>
<div className="h-8 lg:h-0 lg:w-8" />
<div
@@ -99,6 +112,10 @@ export const FileAvailable: React.FC<{
duration={probeResult.durationInSeconds ?? null}
logLevel="verbose"
action={routeAction}
+ enableRotateOrMirrow={enableRotateOrMirrow}
+ setEnableRotateOrMirror={setEnableRotateOrMirror}
+ userRotation={actualUserRotation}
+ setRotation={setRotation}
/>
</div>
</div>
diff --git a/packages/convert/app/components/Probe.tsx b/packages/convert/app/components/Probe.tsx
index a64d9f1c66..db94d23a1f 100644
--- a/packages/convert/app/components/Probe.tsx
+++ b/packages/convert/app/components/Probe.tsx
@@ -20,7 +20,15 @@ export const Probe: React.FC<{
readonly probeDetails: boolean;
readonly probeResult: ProbeResult;
readonly videoThumbnailRef: React.RefObject<VideoThumbnailRef>;
-}> = ({src, probeDetails, setProbeDetails, probeResult, videoThumbnailRef}) => {
+ readonly userRotation: number;
+}> = ({
+ src,
+ probeDetails,
+ setProbeDetails,
+ probeResult,
+ videoThumbnailRef,
+ userRotation,
+}) => {
const {
audioCodec,
fps,
@@ -32,6 +40,7 @@ export const Probe: React.FC<{
videoCodec,
durationInSeconds,
isHdr,
+ rotation,
done,
error,
} = probeResult;
@@ -67,7 +76,11 @@ export const Probe: React.FC<{
<Card className="w-full lg:w-[350px] overflow-hidden">
<div className="flex flex-row lg:flex-col w-full border-b-2 border-black">
{error ? null : (
- <VideoThumbnail ref={videoThumbnailRef} smallThumbOnMobile />
+ <VideoThumbnail
+ ref={videoThumbnailRef}
+ smallThumbOnMobile
+ rotation={userRotation - (rotation ?? 0)}
+ />
)}
<CardHeader className="p-3 lg:p-4 w-full">
<CardTitle title={name ?? undefined}>
diff --git a/packages/convert/app/components/VideoThumbnail.tsx b/packages/convert/app/components/VideoThumbnail.tsx
index 02be7ddd66..0511b24fcd 100644
--- a/packages/convert/app/components/VideoThumbnail.tsx
+++ b/packages/convert/app/components/VideoThumbnail.tsx
@@ -1,4 +1,3 @@
-import {WebCodecsInternals} from '@remotion/webcodecs';
import {FastAverageColor} from 'fast-average-color';
import React, {useCallback, useImperativeHandle, useRef, useState} from 'react';
import {useIsNarrow} from '~/lib/is-narrow';
@@ -7,53 +6,46 @@ const THUMBNAIL_HEIGHT = Math.round((350 / 16) * 9);
type Props = {
readonly smallThumbOnMobile: boolean;
+ readonly rotation: number;
};
export type VideoThumbnailRef = {
- draw: (videoFrame: VideoFrame, rotation: number) => void;
+ draw: (videoFrame: VideoFrame) => void;
};
const VideoThumbnailRefForward: React.ForwardRefRenderFunction<
VideoThumbnailRef,
Props
-> = ({smallThumbOnMobile}, forwardedRef) => {
+> = ({smallThumbOnMobile, rotation}, forwardedRef) => {
const ref = useRef<HTMLCanvasElement>(null);
const [color, setColor] = useState<string>('transparent');
- const [width, setWidth] = useState<number>(0);
+ const [dimensions, setDimensions] = useState<{width: number}>({width: 0});
- const drawThumbnail = useCallback(
- (unrotatedVideoFrame: VideoFrame, rotation: number) => {
- const videoFrame = WebCodecsInternals.rotateVideoFrame({
- frame: unrotatedVideoFrame,
- rotation: 0 - rotation,
- });
+ const drawThumbnail = useCallback((unrotatedVideoFrame: VideoFrame) => {
+ const scaleRatio = THUMBNAIL_HEIGHT / unrotatedVideoFrame.displayHeight;
+ const w = Math.round(unrotatedVideoFrame.displayWidth * scaleRatio);
+ setDimensions({width: w});
- const scaleRatio = THUMBNAIL_HEIGHT / videoFrame.displayHeight;
- const w = Math.round(videoFrame.displayWidth * scaleRatio);
- setWidth(w);
+ const canvas = ref.current;
+ if (!canvas) {
+ return;
+ }
+ canvas.width = w;
+ const twoDContext = canvas.getContext('2d');
+ if (!twoDContext) {
+ return;
+ }
- const canvas = ref.current;
- if (!canvas) {
- return;
+ twoDContext.drawImage(unrotatedVideoFrame, 0, 0, w, THUMBNAIL_HEIGHT);
+ setColor((c) => {
+ if (c !== 'transparent') {
+ return c;
}
- canvas.width = w;
- const twoDContext = canvas.getContext('2d');
- if (!twoDContext) {
- return;
- }
-
- twoDContext.drawImage(videoFrame, 0, 0, w, THUMBNAIL_HEIGHT);
- setColor((c) => {
- if (c !== 'transparent') {
- return c;
- }
- return new FastAverageColor().getColor(canvas).hex;
- });
- },
- [],
- );
+ return new FastAverageColor().getColor(canvas).hex;
+ });
+ }, []);
useImperativeHandle(
forwardedRef,
@@ -66,10 +58,14 @@ const VideoThumbnailRefForward: React.ForwardRefRenderFunction<
const isNarrow = useIsNarrow();
const scale = isNarrow && smallThumbOnMobile ? 0.5 : 1;
+ const scaleTransform =
+ rotation % 90 === 0 && rotation % 180 !== 0
+ ? THUMBNAIL_HEIGHT / dimensions.width
+ : 1;
return (
<div
- className="border-b-2 border-black"
+ className="border-b-2 border-black overflow-hidden"
// +2 to account for border
style={{height: THUMBNAIL_HEIGHT * scale + 2}}
>
@@ -79,7 +75,10 @@ const VideoThumbnailRefForward: React.ForwardRefRenderFunction<
height={THUMBNAIL_HEIGHT}
style={{
maxHeight: THUMBNAIL_HEIGHT * scale,
- width: width * scale,
+ width: dimensions.width * scale,
+ rotate: `${String(rotation)}deg`,
+ scale: String(scaleTransform),
+ transition: 'rotate 0.3s, scale 0.3s',
}}
/>
</div>
diff --git a/packages/convert/app/components/use-probe.ts b/packages/convert/app/components/use-probe.ts
index 187b750ebd..e2896efabe 100644
--- a/packages/convert/app/components/use-probe.ts
+++ b/packages/convert/app/components/use-probe.ts
@@ -39,6 +39,7 @@ export const useProbe = ({
const [videoCodec, setVideoCodec] = useState<MediaParserVideoCodec | null>(
null,
);
+ const [rotation, setRotation] = useState<number | null>(null);
const [size, setSize] = useState<number | null>(null);
const [tracks, setTracks] = useState<TracksField | null>(null);
const [container, setContainer] = useState<ParseMediaContainer | null>(null);
@@ -58,6 +59,7 @@ export const useProbe = ({
let hasContainer = false;
let hasTracks = false;
let hasHdr = false;
+ let hasRotation = false;
const cancelIfDone = () => {
if (
@@ -71,7 +73,8 @@ export const useProbe = ({
hasFrame &&
hasContainer &&
hasTracks &&
- hasHdr
+ hasHdr &&
+ hasRotation
) {
controller.abort(new Error('Cancelled (all info)'));
}
@@ -91,11 +94,11 @@ export const useProbe = ({
tracks: true,
container: true,
isHdr: true,
+ rotation: true,
},
onParseProgress: onProgress,
reader: src.type === 'file' ? webFileReader : fetchReader,
signal: controller.signal,
-
onVideoTrack: async (track) => {
if (typeof VideoDecoder === 'undefined') {
return null;
@@ -160,6 +163,11 @@ export const useProbe = ({
setDurationInSeconds(d);
cancelIfDone();
},
+ onRotation(rotation) {
+ hasRotation = true;
+ setRotation(rotation);
+ cancelIfDone();
+ },
onName: (n) => {
hasName = true;
setName(n);
@@ -227,6 +235,7 @@ export const useProbe = ({
isHdr,
done,
error,
+ rotation,
};
}, [
audioCodec,
@@ -241,5 +250,6 @@ export const useProbe = ({
done,
error,
isHdr,
+ rotation,
]);
};
diff --git a/packages/webcodecs/src/index.ts b/packages/webcodecs/src/index.ts
index 43aad1ece2..87431a9bf1 100644
--- a/packages/webcodecs/src/index.ts
+++ b/packages/webcodecs/src/index.ts
@@ -1,4 +1,4 @@
-import {rotateVideoFrame} from './rotate-video-frame';
+import {normalizeVideoRotation, rotateVideoFrame} from './rotate-video-frame';
import {setRemotionImported} from './set-remotion-imported';
export {createAudioDecoder, WebCodecsAudioDecoder} from './audio-decoder';
@@ -43,6 +43,7 @@ export {createVideoEncoder, WebCodecsVideoEncoder} from './video-encoder';
export const WebCodecsInternals = {
rotateVideoFrame,
+ normalizeVideoRotation,
};
setRemotionImported();
diff --git a/packages/webcodecs/src/on-video-track.ts b/packages/webcodecs/src/on-video-track.ts
index e1bb196adc..550d69e026 100644
--- a/packages/webcodecs/src/on-video-track.ts
+++ b/packages/webcodecs/src/on-video-track.ts
@@ -109,7 +109,7 @@ export const makeVideoTrackHandler =
);
}
- const rotation = videoOperation.rotation ?? rotate;
+ const rotation = videoOperation.rotation ?? -track.rotation + rotate;
const {height: newHeight, width: newWidth} =
calculateNewDimensionsFromDimensions({
diff --git a/packages/webcodecs/src/rotate-video-frame.ts b/packages/webcodecs/src/rotate-video-frame.ts
index e46e129890..443cbce701 100644
--- a/packages/webcodecs/src/rotate-video-frame.ts
+++ b/packages/webcodecs/src/rotate-video-frame.ts
@@ -1,5 +1,9 @@
import {calculateNewDimensionsFromDimensions} from './rotation';
+export const normalizeVideoRotation = (rotation: number) => {
+ return ((rotation % 360) + 360) % 360;
+};
+
export const rotateVideoFrame = ({
frame,
rotation,