Skip to content

🎥 Make videos programmatically with React

remotion.dev/convert: Combine crop, rotate, and mirror (#10085)

Jonny Burger45be30bb29d0
diff --git a/packages/convert/app/components/ConvertUi.tsx b/packages/convert/app/components/ConvertUi.tsx
index 9edec37f1e..3162e0dc64 100644
--- a/packages/convert/app/components/ConvertUi.tsx
+++ b/packages/convert/app/components/ConvertUi.tsx
@@ -11,13 +11,13 @@ import {Conversion, Output, StreamTarget} from 'mediabunny';
import React, {useCallback, useMemo, useState} from 'react';
import {applyCrop} from '~/lib/apply-crop';
import type {Dimensions} from '~/lib/calculate-new-dimensions-from-dimensions';
-import {calculateNewDimensionsFromRotateAndScale} from '~/lib/calculate-new-dimensions-from-dimensions';
+import {
+ calculateNewDimensionsFromRotate,
+ calculateNewSizeAfterResizing,
+} from '~/lib/calculate-new-dimensions-from-dimensions';
import {canRotateOrMirror} from '~/lib/can-rotate-or-mirror';
import type {ConvertState, Source} from '~/lib/convert-state';
-import type {
- ConvertSections,
- RotateOrMirrorOrCropState,
-} from '~/lib/default-ui';
+import type {ConvertSections, VideoEditState} from '~/lib/default-ui';
import {
getOrderOfSections,
isConvertEnabledByDefault,
@@ -69,8 +69,6 @@ const ConvertUI = ({
setTrim,
trimInFrame,
trimOutFrame,
- enableRotateOrMirror,
- setEnableRotateOrMirror,
userRotation,
setRotation,
flipHorizontal,
@@ -79,12 +77,12 @@ const ConvertUI = ({
setFlipVertical,
inputContainer,
videoThumbnailRef,
- rotation,
dimensions,
sampleRate,
name,
input,
- crop,
+ videoEditState,
+ setVideoEditState,
cropRect,
}: {
readonly setSrc: React.Dispatch<React.SetStateAction<Source | null>>;
@@ -94,7 +92,6 @@ const ConvertUI = ({
readonly dimensions: Dimensions | null | undefined;
readonly durationInSeconds: number | null;
readonly fps: number | null | undefined;
- readonly rotation: number | null;
readonly inputContainer: InputFormat;
readonly action: RouteAction;
readonly trim: boolean;
@@ -103,9 +100,9 @@ const ConvertUI = ({
readonly trimOutFrame: number | null;
readonly name: string;
readonly input: Input;
- readonly enableRotateOrMirror: RotateOrMirrorOrCropState;
- readonly setEnableRotateOrMirror: React.Dispatch<
- React.SetStateAction<RotateOrMirrorOrCropState | null>
+ readonly videoEditState: VideoEditState;
+ readonly setVideoEditState: React.Dispatch<
+ React.SetStateAction<VideoEditState>
>;
readonly userRotation: number;
readonly setRotation: React.Dispatch<React.SetStateAction<number>>;
@@ -113,10 +110,10 @@ const ConvertUI = ({
readonly flipVertical: boolean;
readonly setFlipHorizontal: React.Dispatch<React.SetStateAction<boolean>>;
readonly setFlipVertical: React.Dispatch<React.SetStateAction<boolean>>;
- readonly crop: boolean;
readonly sampleRate: number | null;
readonly cropRect: CropRectangle;
}) => {
+ const {crop, mirror, rotate} = videoEditState;
const [enableConvert, setEnableConvert] = useState(() =>
isConvertEnabledByDefault(action),
);
@@ -177,7 +174,7 @@ const ConvertUI = ({
}, [resampleRate, canResample, resampleUserPreferenceActive]);
const disableVideoCopy =
- enableRotateOrMirror !== null || trim || resizeOperation !== null;
+ crop || mirror || rotate || trim || resizeOperation !== null;
const supportedConfigs = useSupportedConfigs({
outputContainer: actualOutputContainer,
@@ -200,6 +197,37 @@ const ConvertUI = ({
return operation.type === 'reencode' && operation.videoCodec === 'avc';
});
+ const dimensionsAfterRotation = useMemo(() => {
+ if (!dimensions) {
+ return null;
+ }
+
+ return calculateNewDimensionsFromRotate({
+ ...dimensions,
+ rotation: userRotation,
+ });
+ }, [dimensions, userRotation]);
+
+ const dimensionsAfterCrop = useMemo(() => {
+ if (dimensionsAfterRotation === null || !crop) {
+ return dimensionsAfterRotation;
+ }
+
+ return applyCrop(dimensionsAfterRotation, cropRect);
+ }, [crop, cropRect, dimensionsAfterRotation]);
+
+ const newDimensions = useMemo(() => {
+ if (dimensionsAfterCrop === null) {
+ return null;
+ }
+
+ return calculateNewSizeAfterResizing({
+ dimensions: dimensionsAfterCrop,
+ resizeOperation,
+ needsToBeMultipleOfTwo: isH264Reencode ?? false,
+ });
+ }, [dimensionsAfterCrop, isH264Reencode, resizeOperation]);
+
const setVideoConfigIndex = useCallback((trackId: number, key: string) => {
setVideoOperationKey((prev) => ({
...prev,
@@ -311,16 +339,12 @@ const ConvertUI = ({
progress.hasVideo = true;
- const dimensionsAfterCrop =
- dimensions && crop ? applyCrop(dimensions, cropRect) : dimensions;
-
return {
process(sample) {
const flipped = flipVideoFrame({
frame: sample.toVideoFrame(),
- horizontal:
- flipHorizontal && enableRotateOrMirror === 'mirror',
- vertical: flipVertical && enableRotateOrMirror === 'mirror',
+ horizontal: flipHorizontal && mirror,
+ vertical: flipVertical && mirror,
});
if (videoFrames % 15 === 0) {
convertProgressRef.current?.draw(flipped);
@@ -334,7 +358,9 @@ const ConvertUI = ({
crop: crop
? makeCrop({
cropRect,
- dimensions: dimensions!,
+ dimensions: dimensionsAfterRotation!,
+ mirrorHorizontal: flipHorizontal && mirror,
+ mirrorVertical: flipVertical && mirror,
videoCodec: operation.videoCodec,
})
: undefined,
@@ -446,9 +472,7 @@ const ConvertUI = ({
}, [
audioOperationSelection,
actualOutputContainer,
- dimensions,
enableConvert,
- enableRotateOrMirror,
flipHorizontal,
flipVertical,
input,
@@ -464,6 +488,9 @@ const ConvertUI = ({
videoOperationSelection,
crop,
cropRect,
+ dimensionsAfterCrop,
+ dimensionsAfterRotation,
+ mirror,
]);
const dimissError = useCallback(() => {
@@ -471,39 +498,31 @@ const ConvertUI = ({
}, []);
const onMirrorClick = useCallback(() => {
- setEnableRotateOrMirror((m) => {
- if (m !== 'mirror') {
- return 'mirror';
- }
-
- return null;
- });
- }, [setEnableRotateOrMirror]);
+ setVideoEditState((editState) => ({
+ ...editState,
+ mirror: !editState.mirror,
+ }));
+ }, [setVideoEditState]);
const onRotateClick = useCallback(() => {
- setEnableRotateOrMirror((m) => {
- if (m !== 'rotate') {
- return 'rotate';
- }
-
- return null;
- });
- }, [setEnableRotateOrMirror]);
+ setVideoEditState((editState) => ({
+ ...editState,
+ rotate: !editState.rotate,
+ }));
+ }, [setVideoEditState]);
const onCropClick = useCallback(() => {
- setEnableRotateOrMirror((m) => {
- if (m !== 'crop') {
+ setVideoEditState((editState) => {
+ if (!editState.crop) {
// Scroll to top of the page when crop is activated
if (typeof window !== 'undefined') {
window.scrollTo({top: 0, behavior: 'smooth'});
}
-
- return 'crop';
}
- return null;
+ return {...editState, crop: !editState.crop};
});
- }, [setEnableRotateOrMirror]);
+ }, [setVideoEditState]);
const onResizeClick = useCallback(() => {
setResizeOperation((r) => {
@@ -519,37 +538,6 @@ const ConvertUI = ({
return (tracks?.filter((t) => t.isVideoTrack()).length ?? 0) === 0;
}, [tracks]);
- const unrotatedDimensions = useMemo(() => {
- if (!dimensions) {
- return null;
- }
-
- if (enableRotateOrMirror !== 'crop') {
- return dimensions;
- }
-
- return applyCrop(dimensions, cropRect);
- }, [dimensions, cropRect, enableRotateOrMirror]);
-
- const newDimensions = useMemo(() => {
- if (unrotatedDimensions === null) {
- return null;
- }
-
- return calculateNewDimensionsFromRotateAndScale({
- ...unrotatedDimensions,
- rotation: userRotation - (rotation ?? 0),
- resizeOperation,
- needsToBeMultipleOfTwo: isH264Reencode ?? false,
- });
- }, [
- unrotatedDimensions,
- isH264Reencode,
- resizeOperation,
- rotation,
- userRotation,
- ]);
-
if (state.type === 'error') {
return (
<>
@@ -622,8 +610,9 @@ const ConvertUI = ({
supportedConfigs,
videoConfigIndexSelection: videoOperationSelection,
enableConvert,
- enableRotateOrMirror,
+ videoEditState,
enableTrim: trim,
+ enableResize: resizeOperation !== null,
});
const canPixelManipulate = canRotateOrMirror({
@@ -687,13 +676,10 @@ const ConvertUI = ({
if (section === 'mirror') {
return (
<div key="mirror">
- <ConvertUiSection
- active={enableRotateOrMirror === 'mirror'}
- setActive={onMirrorClick}
- >
+ <ConvertUiSection active={mirror} setActive={onMirrorClick}>
Mirror
</ConvertUiSection>
- {enableRotateOrMirror === 'mirror' ? (
+ {mirror ? (
<MirrorComponents
canPixelManipulate={canPixelManipulate}
flipHorizontal={flipHorizontal}
@@ -709,13 +695,10 @@ const ConvertUI = ({
if (section === 'rotate') {
return (
<div key="rotate">
- <ConvertUiSection
- active={enableRotateOrMirror === 'rotate'}
- setActive={onRotateClick}
- >
+ <ConvertUiSection active={rotate} setActive={onRotateClick}>
Rotate
</ConvertUiSection>
- {enableRotateOrMirror === 'rotate' ? (
+ {rotate ? (
<RotateComponents
canPixelManipulate={canPixelManipulate}
rotation={userRotation}
@@ -792,21 +775,25 @@ const ConvertUI = ({
</ConvertUiSection>
{resizeOperation !== null &&
newDimensions !== null &&
- unrotatedDimensions !== null &&
+ dimensionsAfterCrop !== null &&
+ dimensionsAfterRotation !== null &&
dimensions !== null &&
dimensions !== undefined ? (
<>
<div className="h-2" />
<ResizeUi
- originalDimensions={unrotatedDimensions}
+ originalDimensions={dimensionsAfterCrop}
dimensions={newDimensions}
thumbnailRef={videoThumbnailRef}
- rotation={userRotation - (rotation ?? 0)}
+ rotation={userRotation}
setResizeMode={setResizeOperation}
requireTwoStep={Boolean(isH264Reencode)}
- crop={enableRotateOrMirror === 'crop'}
+ crop={crop}
cropRect={cropRect}
- dimensionsBeforeCrop={dimensions}
+ dimensionsBeforeCrop={dimensionsAfterRotation}
+ sourceDimensions={dimensions}
+ mirrorHorizontal={flipHorizontal && mirror}
+ mirrorVertical={flipVertical && mirror}
/>
</>
) : null}
diff --git a/packages/convert/app/components/FileAvailable.tsx b/packages/convert/app/components/FileAvailable.tsx
index 48d0618d09..439c568fdc 100644
--- a/packages/convert/app/components/FileAvailable.tsx
+++ b/packages/convert/app/components/FileAvailable.tsx
@@ -2,8 +2,7 @@ import type {CropRectangle} from 'mediabunny';
import React, {useCallback, useMemo, useRef, useState} from 'react';
import {normalizeVideoRotation} from '~/lib/calculate-new-dimensions-from-dimensions';
import type {Source} from '~/lib/convert-state';
-import type {RotateOrMirrorOrCropState} from '~/lib/default-ui';
-import {defaultRotateOrMirorState} from '~/lib/default-ui';
+import {getDefaultVideoEditState} from '~/lib/default-ui';
import {isAudioOnly} from '~/lib/is-audio-container';
import type {RouteAction} from '~/seo';
import {BackButton} from './BackButton';
@@ -27,10 +26,9 @@ export const FileAvailable: React.FC<{
const videoThumbnailRef = useRef<VideoThumbnailRef>(null);
- const [enableRotateOrMirrow, setEnableRotateOrMirror] =
- useState<RotateOrMirrorOrCropState>(() =>
- defaultRotateOrMirorState(routeAction),
- );
+ const [videoEditState, setVideoEditState] = useState(() =>
+ getDefaultVideoEditState(routeAction),
+ );
const [enableTrim, setEnableTrim] = useState(
() =>
routeAction.type === 'generic-trim' || routeAction.type === 'trim-format',
@@ -57,12 +55,12 @@ export const FileAvailable: React.FC<{
const [waveform, setWaveform] = useState<number[]>([]);
const actualUserRotation = useMemo(() => {
- if (enableRotateOrMirrow !== 'rotate') {
+ if (!videoEditState.rotate) {
return 0;
}
return normalizeVideoRotation(userRotation);
- }, [enableRotateOrMirrow, userRotation]);
+ }, [videoEditState.rotate, userRotation]);
const onWaveformBars = useCallback((bars: number[]) => {
setWaveform(bars);
@@ -81,7 +79,7 @@ export const FileAvailable: React.FC<{
src={src}
isAudio={isAudio}
waveform={waveform}
- crop={enableRotateOrMirrow === 'crop'}
+ crop={videoEditState.crop}
trim={enableTrim}
trimInFrame={trimInFrame}
trimOutFrame={trimOutFrame}
@@ -93,10 +91,8 @@ export const FileAvailable: React.FC<{
durationInSeconds={probeResult.durationInSeconds}
fps={probeResult.fps}
rotation={actualUserRotation}
- mirrorHorizontal={
- flipHorizontal && enableRotateOrMirrow === 'mirror'
- }
- mirrorVertical={flipVertical && enableRotateOrMirrow === 'mirror'}
+ mirrorHorizontal={flipHorizontal && videoEditState.mirror}
+ mirrorVertical={flipVertical && videoEditState.mirror}
onPlaybackTimeChange={setPlaybackTime}
/>
<div className="h-8" />
@@ -111,10 +107,8 @@ export const FileAvailable: React.FC<{
probeResult={probeResult}
videoThumbnailRef={videoThumbnailRef}
userRotation={actualUserRotation}
- mirrorHorizontal={
- flipHorizontal && enableRotateOrMirrow === 'mirror'
- }
- mirrorVertical={flipVertical && enableRotateOrMirrow === 'mirror'}
+ mirrorHorizontal={flipHorizontal && videoEditState.mirror}
+ mirrorVertical={flipVertical && videoEditState.mirror}
onWaveformBars={onWaveformBars}
/>
{routeAction.type !== 'generic-probe' &&
@@ -132,7 +126,7 @@ export const FileAvailable: React.FC<{
data-hidden={probeDetails}
>
<ConvertUI
- crop={enableRotateOrMirrow === 'crop'}
+ videoEditState={videoEditState}
inputContainer={probeResult.container}
currentVideoCodec={probeResult.videoCodec ?? null}
tracks={probeResult.tracks}
@@ -145,8 +139,7 @@ export const FileAvailable: React.FC<{
trimInFrame={trimInFrame}
trimOutFrame={trimOutFrame}
fps={probeResult.fps}
- enableRotateOrMirror={enableRotateOrMirrow}
- setEnableRotateOrMirror={setEnableRotateOrMirror}
+ setVideoEditState={setVideoEditState}
userRotation={actualUserRotation}
setRotation={setRotation}
flipHorizontal={flipHorizontal}
@@ -154,7 +147,6 @@ export const FileAvailable: React.FC<{
flipVertical={flipVertical}
setFlipVertical={setFlipVertical}
videoThumbnailRef={videoThumbnailRef}
- rotation={probeResult.rotation}
sampleRate={probeResult.sampleRate}
name={probeResult.name}
input={probeResult.input}
diff --git a/packages/convert/app/components/MediaPlayer.tsx b/packages/convert/app/components/MediaPlayer.tsx
index 45a9efd4ba..9015c76472 100644
--- a/packages/convert/app/components/MediaPlayer.tsx
+++ b/packages/convert/app/components/MediaPlayer.tsx
@@ -108,7 +108,7 @@ export const getVideoPreviewStyle = ({
top: '50%',
width: switchesDimensions ? height : width,
height: switchesDimensions ? width : height,
- transform: `translate(-50%, -50%) rotate(${normalizedRotation}deg) scale(${mirrorHorizontal ? -1 : 1}, ${mirrorVertical ? -1 : 1})`,
+ transform: `translate(-50%, -50%) scale(${mirrorHorizontal ? -1 : 1}, ${mirrorVertical ? -1 : 1}) rotate(${normalizedRotation}deg)`,
};
};
@@ -318,11 +318,11 @@ export function VideoPlayer({
Loading preview...
</div>
)}
- {!isAudio && crop && dimensions ? (
+ {!isAudio && crop && playerDimensions ? (
<CropUI
setUnclampedRect={setUnclampedRect}
unclampedRect={unclampedRect}
- dimensions={dimensions}
+ dimensions={playerDimensions}
/>
) : null}
</div>
diff --git a/packages/convert/app/components/ResizeThumbnail.tsx b/packages/convert/app/components/ResizeThumbnail.tsx
index 59e1910582..edff70ee82 100644
--- a/packages/convert/app/components/ResizeThumbnail.tsx
+++ b/packages/convert/app/components/ResizeThumbnail.tsx
@@ -28,10 +28,12 @@ export const getThumbnailDimensions = (dimensions: Dimensions) => {
export const ResizeThumbnail: React.FC<{
readonly dimensions: Dimensions;
- readonly unrotatedDimensions: Dimensions;
readonly dimensionsBeforeCrop: Dimensions;
+ readonly sourceDimensions: Dimensions;
readonly thumbnailRef: React.RefObject<VideoThumbnailRef | null>;
readonly rotation: number;
+ readonly mirrorHorizontal: boolean;
+ readonly mirrorVertical: boolean;
readonly scale: number;
readonly setResizeMode: React.Dispatch<
React.SetStateAction<MediabunnyResize | null>
@@ -45,21 +47,19 @@ export const ResizeThumbnail: React.FC<{
scale,
setResizeMode,
rotation,
- unrotatedDimensions,
inputFocused,
cropRect,
crop,
dimensionsBeforeCrop,
+ sourceDimensions,
+ mirrorHorizontal,
+ mirrorVertical,
}) => {
const ref = useRef<HTMLCanvasElement>(null);
const thumbnailDimensions = useMemo(() => {
return getThumbnailDimensions(dimensions);
}, [dimensions]);
- const unrotatedThumbnailDimensions = useMemo(() => {
- return getThumbnailDimensions(unrotatedDimensions);
- }, [unrotatedDimensions]);
-
const inner = useMemo(() => {
return {
height: thumbnailDimensions.height * scale,
@@ -82,10 +82,14 @@ export const ResizeThumbnail: React.FC<{
const drawn = useThumbnailCopy({
sourceRef: thumbnailRef,
targetRef: ref,
- dimensions: unrotatedThumbnailDimensions,
+ dimensions: thumbnailDimensions,
cropRect,
crop,
fullDimensionsBeforeCrop: dimensionsBeforeCrop,
+ sourceDimensions,
+ rotation,
+ mirrorHorizontal,
+ mirrorVertical,
});
return (
@@ -105,23 +109,22 @@ export const ResizeThumbnail: React.FC<{
ref={ref}
style={{
position: 'absolute',
- width: Math.ceil(unrotatedThumbnailDimensions.width * scale),
- height: Math.ceil(unrotatedThumbnailDimensions.height * scale),
- transform: `rotate(${rotation}deg)`,
+ width: Math.ceil(thumbnailDimensions.width * scale),
+ height: Math.ceil(thumbnailDimensions.height * scale),
transitionProperty: animate ? 'all' : 'none',
transitionTimingFunction: 'cubic-bezier(0.4, 0, 0.2, 1)',
transitionDuration: '150ms',
opacity: drawn ? 1 : 0,
}}
data-animate={animate}
- width={unrotatedThumbnailDimensions.width}
- height={unrotatedThumbnailDimensions.height}
+ width={thumbnailDimensions.width}
+ height={thumbnailDimensions.height}
/>
<ResizeCorner
outerDimensions={thumbnailDimensions}
innerDimensions={inner}
setResizeMode={setResizeMode}
- videoDimensions={unrotatedDimensions}
+ videoDimensions={dimensions}
onEnd={onEnd}
onStart={onStart}
/>
diff --git a/packages/convert/app/components/ResizeUi.tsx b/packages/convert/app/components/ResizeUi.tsx
index e0814e469a..0cc06efac1 100644
--- a/packages/convert/app/components/ResizeUi.tsx
+++ b/packages/convert/app/components/ResizeUi.tsx
@@ -40,8 +40,11 @@ export const ResizeUi: React.FC<{
readonly dimensions: Dimensions;
readonly originalDimensions: Dimensions;
readonly dimensionsBeforeCrop: Dimensions;
+ readonly sourceDimensions: Dimensions;
readonly thumbnailRef: React.RefObject<VideoThumbnailRef | null>;
readonly rotation: number;
+ readonly mirrorHorizontal: boolean;
+ readonly mirrorVertical: boolean;
readonly setResizeMode: React.Dispatch<
React.SetStateAction<MediabunnyResize | null>
>;
@@ -58,25 +61,14 @@ export const ResizeUi: React.FC<{
cropRect,
crop,
dimensionsBeforeCrop,
+ sourceDimensions,
+ mirrorHorizontal,
+ mirrorVertical,
}) => {
const outer: React.CSSProperties = useMemo(() => {
return {...getThumbnailDimensions(dimensions), outlineStyle: 'solid'};
}, [dimensions]);
- const rotatedDimensions = useMemo(() => {
- if (rotation % 360 === 90 || rotation % 360 === 270) {
- return {
- height: originalDimensions.width,
- width: originalDimensions.height,
- };
- }
-
- return {
- height: originalDimensions.height,
- width: originalDimensions.width,
- };
- }, [originalDimensions, rotation]);
-
const onChangeHeight = useCallback(
(height: number) => {
setResizeMode(() => {
@@ -107,7 +99,7 @@ export const ResizeUi: React.FC<{
return (
<div className="mt-6 mb-6">
<ResizeShortcuts
- originalDimensions={rotatedDimensions}
+ originalDimensions={originalDimensions}
resolvedDimensions={dimensions}
setResizeMode={setResizeMode}
/>
@@ -119,16 +111,18 @@ export const ResizeUi: React.FC<{
className="rounded bg-white flex justify-center items-center outline-2 outline-slate-300"
>
<ResizeThumbnail
- dimensions={rotatedDimensions}
+ dimensions={originalDimensions}
thumbnailRef={thumbnailRef}
rotation={rotation}
- scale={dimensions.width / rotatedDimensions.width}
+ scale={dimensions.width / originalDimensions.width}
setResizeMode={setResizeMode}
- unrotatedDimensions={originalDimensions}
inputFocused={widthFocused || heightFocused}
cropRect={cropRect}
crop={crop}
dimensionsBeforeCrop={dimensionsBeforeCrop}
+ sourceDimensions={sourceDimensions}
+ mirrorHorizontal={mirrorHorizontal}
+ mirrorVertical={mirrorVertical}
/>
</div>
<div className="flex-1 flex flex-row items-center ml-[2px]">
diff --git a/packages/convert/app/components/crop-ui/CropUi.tsx b/packages/convert/app/components/crop-ui/CropUi.tsx
index 610fb039a9..4ac26f0ef9 100644
--- a/packages/convert/app/components/crop-ui/CropUi.tsx
+++ b/packages/convert/app/components/crop-ui/CropUi.tsx
@@ -1,6 +1,7 @@
import type {CropRectangle} from 'mediabunny';
import type React from 'react';
import {useRef, useState} from 'react';
+import {getVisibleCropRectangle} from '~/lib/apply-crop';
import type {Dimensions} from '~/lib/calculate-new-dimensions-from-dimensions';
import {CropBackdrop} from './Backdrop';
import {DragHandle} from './DragHandle';
@@ -22,27 +23,10 @@ export const CropUI: React.FC<{
const ref = useRef<HTMLDivElement>(null);
- const rect = (() => {
- const width = Math.min(
- (dimensions?.width ?? 0) - unclampedRect.left,
- Number.isFinite(unclampedRect.width)
- ? unclampedRect.width
- : (dimensions?.width ?? 0),
- );
- const height = Math.min(
- (dimensions?.height ?? 0) - unclampedRect.top,
- Number.isFinite(unclampedRect.height)
- ? unclampedRect.height
- : (dimensions?.height ?? 0),
- );
-
- return {
- left: unclampedRect.left,
- top: unclampedRect.top,
- width,
- height,
- };
- })();
+ const rect = getVisibleCropRectangle({
+ cropRect: unclampedRect,
+ dimensions,
+ });
return (
<div
diff --git a/packages/convert/app/components/make-crop.tsx b/packages/convert/app/components/make-crop.tsx
index c63689bd52..c38faacb5e 100644
--- a/packages/convert/app/components/make-crop.tsx
+++ b/packages/convert/app/components/make-crop.tsx
@@ -1,28 +1,42 @@
import type {CropRectangle, VideoCodec} from 'mediabunny';
+import {
+ getCropRectangleBeforeMirror,
+ getVisibleCropRectangle,
+} from '~/lib/apply-crop';
import type {Dimensions} from '~/lib/calculate-new-dimensions-from-dimensions';
export const makeCrop = ({
cropRect,
dimensions,
videoCodec,
+ mirrorHorizontal,
+ mirrorVertical,
}: {
cropRect: CropRectangle;
dimensions: Dimensions;
videoCodec: VideoCodec;
+ mirrorHorizontal: boolean;
+ mirrorVertical: boolean;
}) => {
- let width = Number.isFinite(cropRect.width)
- ? cropRect.width
- : dimensions!.width - cropRect.left;
- let height = Number.isFinite(cropRect.height)
- ? cropRect.height
- : dimensions!.height - cropRect.top;
+ const visibleCropRectangle = getVisibleCropRectangle({
+ cropRect,
+ dimensions,
+ });
+ let {height, width} = visibleCropRectangle;
// Round down to nearest even number if codec is avc or hevc
- let {left} = cropRect;
- let {top} = cropRect;
if (videoCodec === 'avc' || videoCodec === 'hevc') {
width = Math.floor(width / 2) * 2;
height = Math.floor(height / 2) * 2;
+ }
+
+ let {left, top} = getCropRectangleBeforeMirror({
+ cropRect: {...visibleCropRectangle, height, width},
+ dimensions,
+ mirrorHorizontal,
+ mirrorVertical,
+ });
+ if (videoCodec === 'avc' || videoCodec === 'hevc') {
left = Math.floor(left / 2) * 2;
top = Math.floor(top / 2) * 2;
}
diff --git a/packages/convert/app/lib/apply-crop.ts b/packages/convert/app/lib/apply-crop.ts
index 4f39be1329..cac3b42382 100644
--- a/packages/convert/app/lib/apply-crop.ts
+++ b/packages/convert/app/lib/apply-crop.ts
@@ -1,9 +1,109 @@
import type {CropRectangle} from 'mediabunny';
-import type {Dimensions} from './calculate-new-dimensions-from-dimensions';
+import {
+ type Dimensions,
+ normalizeVideoRotation,
+} from './calculate-new-dimensions-from-dimensions';
+
+export const getVisibleCropRectangle = ({
+ dimensions,
+ cropRect,
+}: {
+ dimensions: Dimensions;
+ cropRect: CropRectangle;
+}): CropRectangle => {
+ const left = Math.min(Math.max(0, cropRect.left), dimensions.width);
+ const top = Math.min(Math.max(0, cropRect.top), dimensions.height);
+ const width = Math.min(
+ Number.isFinite(cropRect.width)
+ ? Math.max(0, cropRect.width)
+ : dimensions.width - left,
+ dimensions.width - left,
+ );
+ const height = Math.min(
+ Number.isFinite(cropRect.height)
+ ? Math.max(0, cropRect.height)
+ : dimensions.height - top,
+ dimensions.height - top,
+ );
+
+ return {height, left, top, width};
+};
export const applyCrop = (dimensions: Dimensions, cropRect: CropRectangle) => {
+ const visibleCropRectangle = getVisibleCropRectangle({
+ cropRect,
+ dimensions,
+ });
+
+ return {
+ width: visibleCropRectangle.width,
+ height: visibleCropRectangle.height,
+ };
+};
+
+export const getCropRectangleBeforeMirror = ({
+ cropRect,
+ dimensions,
+ mirrorHorizontal,
+ mirrorVertical,
+}: {
+ cropRect: CropRectangle;
+ dimensions: Dimensions;
+ mirrorHorizontal: boolean;
+ mirrorVertical: boolean;
+}): CropRectangle => {
return {
- width: Math.min(dimensions.width, cropRect.width),
- height: Math.min(dimensions.height, cropRect.height),
+ ...cropRect,
+ left: mirrorHorizontal
+ ? dimensions.width - cropRect.left - cropRect.width
+ : cropRect.left,
+ top: mirrorVertical
+ ? dimensions.height - cropRect.top - cropRect.height
+ : cropRect.top,
};
};
+
+export const getCropRectangleBeforeRotation = ({
+ cropRect,
+ rotation,
+ sourceDimensions,
+}: {
+ cropRect: CropRectangle;
+ rotation: number;
+ sourceDimensions: Dimensions;
+}): CropRectangle => {
+ const normalizedRotation = normalizeVideoRotation(rotation);
+
+ if (normalizedRotation === 0) {
+ return cropRect;
+ }
+
+ if (normalizedRotation === 90) {
+ return {
+ left: cropRect.top,
+ top: sourceDimensions.height - cropRect.left - cropRect.width,
+ width: cropRect.height,
+ height: cropRect.width,
+ };
+ }
+
+ if (normalizedRotation === 180) {
+ return {
+ left: sourceDimensions.width - cropRect.left - cropRect.width,
+ top: sourceDimensions.height - cropRect.top - cropRect.height,
+ width: cropRect.width,
+ height: cropRect.height,
+ };
+ }
+
+ if (normalizedRotation === 270) {
+ return {
+ left: sourceDimensions.width - cropRect.top - cropRect.height,
+ top: cropRect.left,
+ width: cropRect.height,
+ height: cropRect.width,
+ };
+ }
+
+ throw new Error(`Unsupported rotation: ${rotation}`);
+};
diff --git a/packages/convert/app/lib/default-ui.ts b/packages/convert/app/lib/default-ui.ts
index a3e9ff85fd..983a3761bb 100644
--- a/packages/convert/app/lib/default-ui.ts
+++ b/packages/convert/app/lib/default-ui.ts
@@ -1,77 +1,19 @@
import type {RouteAction} from '~/seo';
-export type RotateOrMirrorOrCropState = 'rotate' | 'mirror' | 'crop' | null;
+export type VideoEditState = {
+ readonly crop: boolean;
+ readonly mirror: boolean;
+ readonly rotate: boolean;
+};
-export const defaultRotateOrMirorState = (
+export const getDefaultVideoEditState = (
action: RouteAction,
-): RotateOrMirrorOrCropState => {
- if (action.type === 'convert') {
- return null;
- }
-
- if (action.type === 'generic-probe') {
- return null;
- }
-
- if (action.type === 'generic-convert') {
- return null;
- }
-
- if (action.type === 'generic-rotate') {
- return 'rotate';
- }
-
- if (action.type === 'rotate-format') {
- return 'rotate';
- }
-
- if (action.type === 'mirror-format') {
- return 'mirror';
- }
-
- if (action.type === 'generic-mirror') {
- return 'mirror';
- }
-
- if (action.type === 'generic-resize') {
- return null;
- }
-
- if (action.type === 'resize-format') {
- return null;
- }
-
- if (action.type === 'report') {
- return null;
- }
-
- if (action.type === 'transcribe') {
- return null;
- }
-
- if (action.type === 'generic-crop') {
- return 'crop';
- }
-
- if (action.type === 'crop-format') {
- return 'crop';
- }
-
- if (action.type === 'generic-trim') {
- return null;
- }
-
- if (action.type === 'trim-format') {
- return null;
- }
-
- if (action.type === 'timing-editor') {
- return null;
- }
-
- throw new Error(
- 'Rotate is not enabled by default ' + (action satisfies never),
- );
+): VideoEditState => {
+ return {
+ crop: action.type === 'generic-crop' || action.type === 'crop-format',
+ mirror: action.type === 'generic-mirror' || action.type === 'mirror-format',
+ rotate: action.type === 'generic-rotate' || action.type === 'rotate-format',
+ };
};
export const isConvertEnabledByDefault = (action: RouteAction) => {
diff --git a/packages/convert/app/lib/is-submit-enabled.ts b/packages/convert/app/lib/is-submit-enabled.ts
index 8df3f2b8e4..4ef94ee201 100644
--- a/packages/convert/app/lib/is-submit-enabled.ts
+++ b/packages/convert/app/lib/is-submit-enabled.ts
@@ -1,6 +1,6 @@
import type {SupportedConfigs} from '~/components/get-supported-configs';
import {canRotateOrMirror} from './can-rotate-or-mirror';
-import type {RotateOrMirrorOrCropState} from './default-ui';
+import type {VideoEditState} from './default-ui';
import {isDroppingEverything} from './is-reencoding';
export const isSubmitDisabled = ({
@@ -8,29 +8,35 @@ export const isSubmitDisabled = ({
audioConfigIndexSelection,
videoConfigIndexSelection,
enableConvert,
- enableRotateOrMirror,
+ videoEditState,
enableTrim,
+ enableResize,
}: {
supportedConfigs: SupportedConfigs | null;
audioConfigIndexSelection: Record<number, string>;
videoConfigIndexSelection: Record<number, string>;
enableConvert: boolean;
- enableRotateOrMirror: RotateOrMirrorOrCropState;
+ videoEditState: VideoEditState;
enableTrim: boolean;
+ enableResize: boolean;
}) => {
if (!supportedConfigs) {
return true;
}
- const allActionsDisabled =
- !enableConvert && enableRotateOrMirror === null && !enableTrim;
+ const hasVideoEdit =
+ videoEditState.crop ||
+ videoEditState.mirror ||
+ videoEditState.rotate ||
+ enableResize;
+ const allActionsDisabled = !enableConvert && !hasVideoEdit && !enableTrim;
if (allActionsDisabled) {
return true;
}
- const isRotatingOrMirroring =
- enableRotateOrMirror !== null &&
+ const canApplyVideoEdit =
+ hasVideoEdit &&
canRotateOrMirror({
supportedConfigs,
enableConvert,
@@ -45,5 +51,5 @@ export const isSubmitDisabled = ({
enableConvert,
});
- return !(isRotatingOrMirroring || isConverting || enableTrim);
+ return !(canApplyVideoEdit || isConverting || enableTrim);
};
diff --git a/packages/convert/app/lib/use-thumbnail-copy.ts b/packages/convert/app/lib/use-thumbnail-copy.ts
index 19ebf4d719..65eef198c3 100644
--- a/packages/convert/app/lib/use-thumbnail-copy.ts
+++ b/packages/convert/app/lib/use-thumbnail-copy.ts
@@ -1,7 +1,15 @@
import type {CropRectangle} from 'mediabunny';
import {useCallback, useEffect, useState} from 'react';
import type {VideoThumbnailRef} from '~/components/VideoThumbnail';
-import type {Dimensions} from './calculate-new-dimensions-from-dimensions';
+import {
+ getCropRectangleBeforeMirror,
+ getCropRectangleBeforeRotation,
+ getVisibleCropRectangle,
+} from './apply-crop';
+import {
+ type Dimensions,
+ normalizeVideoRotation,
+} from './calculate-new-dimensions-from-dimensions';
export const useThumbnailCopy = ({
sourceRef,
@@ -10,6 +18,10 @@ export const useThumbnailCopy = ({
cropRect,
crop,
fullDimensionsBeforeCrop,
+ sourceDimensions,
+ rotation,
+ mirrorHorizontal,
+ mirrorVertical,
}: {
sourceRef: React.RefObject<VideoThumbnailRef | null>;
targetRef: React.RefObject<HTMLCanvasElement | null> | null;
@@ -17,6 +29,10 @@ export const useThumbnailCopy = ({
cropRect: CropRectangle;
crop: boolean;
fullDimensionsBeforeCrop: Dimensions;
+ sourceDimensions: Dimensions;
+ rotation: number;
+ mirrorHorizontal: boolean;
+ mirrorVertical: boolean;
}) => {
const [drawn, setDrawn] = useState(
() => sourceRef.current?.hasBitmap ?? false,
@@ -28,26 +44,60 @@ export const useThumbnailCopy = ({
}
sourceRef.current?.copy().then((map) => {
- const ctx = targetRef.current?.getContext('2d');
- if (!ctx) {
+ const canvas = targetRef.current;
+ const ctx = canvas?.getContext('2d');
+ if (!ctx || !canvas) {
return;
}
- if (!crop) {
- ctx.drawImage(map, 0, 0, dimensions.width, dimensions.height);
- } else {
- ctx.drawImage(
- map,
- (map.width / fullDimensionsBeforeCrop.width) * cropRect.left,
- (map.height / fullDimensionsBeforeCrop.height) * cropRect.top,
- (map.width / fullDimensionsBeforeCrop.width) * cropRect.width,
- (map.height / fullDimensionsBeforeCrop.height) * cropRect.height,
- 0,
- 0,
- dimensions.width,
- dimensions.height,
- );
- }
+ const visibleCropRectangle = getVisibleCropRectangle({
+ cropRect: crop
+ ? cropRect
+ : {
+ left: 0,
+ top: 0,
+ width: fullDimensionsBeforeCrop.width,
+ height: fullDimensionsBeforeCrop.height,
+ },
+ dimensions: fullDimensionsBeforeCrop,
+ });
+ const cropBeforeMirror = getCropRectangleBeforeMirror({
+ cropRect: visibleCropRectangle,
+ dimensions: fullDimensionsBeforeCrop,
+ mirrorHorizontal,
+ mirrorVertical,
+ });
+ const sourceCrop = getCropRectangleBeforeRotation({
+ cropRect: cropBeforeMirror,
+ rotation,
+ sourceDimensions,
+ });
+ const normalizedRotation = normalizeVideoRotation(rotation);
+ const switchesDimensions = normalizedRotation % 180 !== 0;
+ const drawWidth = switchesDimensions
+ ? dimensions.height
+ : dimensions.width;
+ const drawHeight = switchesDimensions
+ ? dimensions.width
+ : dimensions.height;
+
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ ctx.save();
+ ctx.translate(dimensions.width / 2, dimensions.height / 2);
+ ctx.scale(mirrorHorizontal ? -1 : 1, mirrorVertical ? -1 : 1);
+ ctx.rotate((normalizedRotation * Math.PI) / 180);
+ ctx.drawImage(
+ map,
+ (map.width / sourceDimensions.width) * sourceCrop.left,
+ (map.height / sourceDimensions.height) * sourceCrop.top,
+ (map.width / sourceDimensions.width) * sourceCrop.width,
+ (map.height / sourceDimensions.height) * sourceCrop.height,
+ -drawWidth / 2,
+ -drawHeight / 2,
+ drawWidth,
+ drawHeight,
+ );
+ ctx.restore();
setDrawn(true);
});
@@ -58,6 +108,10 @@ export const useThumbnailCopy = ({
dimensions,
fullDimensionsBeforeCrop,
cropRect,
+ sourceDimensions,
+ rotation,
+ mirrorHorizontal,
+ mirrorVertical,
]);
useEffect(() => {
diff --git a/packages/convert/test/combined-video-edits.test.ts b/packages/convert/test/combined-video-edits.test.ts
new file mode 100644
index 0000000000..17fa6bab57
--- /dev/null
+++ b/packages/convert/test/combined-video-edits.test.ts
@@ -0,0 +1,118 @@
+import {expect, test} from 'bun:test';
+import {makeCrop} from '../app/components/make-crop';
+import {
+ getPlayerDimensions,
+ getVideoPreviewStyle,
+} from '../app/components/MediaPlayer';
+import {
+ getCropRectangleBeforeMirror,
+ getCropRectangleBeforeRotation,
+} from '../app/lib/apply-crop';
+
+test('keeps a crop aligned between a rotated and mirrored preview and export', () => {
+ const dimensionsAfterRotation = getPlayerDimensions({
+ dimensions: {width: 200, height: 100},
+ isAudio: false,
+ rotation: 90,
+ });
+
+ expect(dimensionsAfterRotation).toEqual({width: 100, height: 200});
+ if (dimensionsAfterRotation === null) {
+ throw new Error('Expected video dimensions');
+ }
+
+ const cropRect = {left: 10, top: 20, width: 30, height: 50};
+ const previewStyle = getVideoPreviewStyle({
+ ...dimensionsAfterRotation,
+ mirrorHorizontal: true,
+ mirrorVertical: true,
+ rotation: 90,
+ });
+ const exportCrop = makeCrop({
+ cropRect,
+ dimensions: dimensionsAfterRotation,
+ mirrorHorizontal: true,
+ mirrorVertical: true,
+ videoCodec: 'vp9',
+ });
+
+ expect(previewStyle.transform).toBe(
+ 'translate(-50%, -50%) scale(-1, -1) rotate(90deg)',
+ );
+ expect(exportCrop).toEqual({
+ left: 60,
+ top: 130,
+ width: 30,
+ height: 50,
+ });
+});
+
+test('maps every mirror combination into Mediabunny crop coordinates', () => {
+ const dimensions = {width: 200, height: 100};
+ const cropRect = {left: 20, top: 10, width: 50, height: 30};
+
+ expect(
+ makeCrop({
+ cropRect,
+ dimensions,
+ mirrorHorizontal: false,
+ mirrorVertical: false,
+ videoCodec: 'vp9',
+ }),
+ ).toEqual({left: 20, top: 10, width: 50, height: 30});
+ expect(
+ makeCrop({
+ cropRect,
+ dimensions,
+ mirrorHorizontal: true,
+ mirrorVertical: false,
+ videoCodec: 'vp9',
+ }),
+ ).toEqual({left: 130, top: 10, width: 50, height: 30});
+ expect(
+ makeCrop({
+ cropRect,
+ dimensions,
+ mirrorHorizontal: false,
+ mirrorVertical: true,
+ videoCodec: 'vp9',
+ }),
+ ).toEqual({left: 20, top: 60, width: 50, height: 30});
+ expect(
+ makeCrop({
+ cropRect,
+ dimensions,
+ mirrorHorizontal: true,
+ mirrorVertical: true,
+ videoCodec: 'vp9',
+ }),
+ ).toEqual({left: 130, top: 60, width: 50, height: 30});
+});
+
+test('maps a visible crop back to the thumbnail source after rotation and mirroring', () => {
+ const cropBeforeMirror = getCropRectangleBeforeMirror({
+ cropRect: {left: 10, top: 20, width: 30, height: 50},
+ dimensions: {width: 100, height: 200},
+ mirrorHorizontal: true,
+ mirrorVertical: false,
+ });
+
+ expect(cropBeforeMirror).toEqual({
+ left: 60,
+ top: 20,
+ width: 30,
+ height: 50,
+ });
+ expect(
+ getCropRectangleBeforeRotation({
+ cropRect: cropBeforeMirror,
+ rotation: 90,
+ sourceDimensions: {width: 200, height: 100},
+ }),
+ ).toEqual({
+ left: 20,
+ top: 10,
+ width: 50,
+ height: 30,
+ });
+});
diff --git a/packages/convert/test/default-ui.test.ts b/packages/convert/test/default-ui.test.ts
index c14e5daceb..8c828105f6 100644
--- a/packages/convert/test/default-ui.test.ts
+++ b/packages/convert/test/default-ui.test.ts
@@ -1,6 +1,7 @@
import {expect, test} from 'bun:test';
import {HLS, MP4, QTFF, WEBM} from 'mediabunny';
import {
+ getDefaultVideoEditState,
isConvertEnabledByDefault,
isVideoOnlySection,
} from '../app/lib/default-ui';
@@ -47,6 +48,29 @@ test('only enables the convert controls by default on conversion pages', () => {
expect(isConvertEnabledByDefault({type: 'generic-mirror'})).toBe(false);
});
+test('enables each video edit independently based on the route', () => {
+ expect(getDefaultVideoEditState({type: 'generic-crop'})).toEqual({
+ crop: true,
+ mirror: false,
+ rotate: false,
+ });
+ expect(getDefaultVideoEditState({type: 'generic-mirror'})).toEqual({
+ crop: false,
+ mirror: true,
+ rotate: false,
+ });
+ expect(getDefaultVideoEditState({type: 'generic-rotate'})).toEqual({
+ crop: false,
+ mirror: false,
+ rotate: true,
+ });
+ expect(getDefaultVideoEditState({type: 'generic-convert'})).toEqual({
+ crop: false,
+ mirror: false,
+ rotate: false,
+ });
+});
+
test('keeps the input container by default on editing pages', () => {
expect(getDefaultEditOutputFormat(MP4)).toBe('mp4');
expect(getDefaultEditOutputFormat(WEBM)).toBe('webm');
diff --git a/packages/convert/test/media-player.test.ts b/packages/convert/test/media-player.test.ts
index 75fee7d6c5..4be90fb4ce 100644
--- a/packages/convert/test/media-player.test.ts
+++ b/packages/convert/test/media-player.test.ts
@@ -48,6 +48,6 @@ test('uses exported video geometry without changing player timing', () => {
).toMatchObject({
width: 1920,
height: 1080,
- transform: 'translate(-50%, -50%) rotate(90deg) scale(-1, 1)',
+ transform: 'translate(-50%, -50%) scale(-1, 1) rotate(90deg)',
});
});