🎥 Make videos programmatically with React
`@remotion/media`: Add `objectFit` prop to `<Video>` (#6924)
Jonny Burger9b2e0631e3f5
diff --git a/packages/docs/docs/media/video.mdx b/packages/docs/docs/media/video.mdxindex 893768e7a9..49fa2e9f2c 100644--- a/packages/docs/docs/media/video.mdx+++ b/packages/docs/docs/media/video.mdx@@ -204,6 +204,40 @@ export const MyComposition = () => {};```+### `objectFit?`<AvailableFrom v="4.0.442" />++Controls how the video content is resized to fit the canvas element, similar to the CSS `object-fit` property on `<img>` elements.++Accepts `'contain'` (default), `'cover'`, `'fill'`, `'none'`, or `'scale-down'`.++- `'contain'`: The video is scaled to maintain its aspect ratio while fitting within the element's content box. Letterboxing is applied if the aspect ratios don't match.+- `'cover'`: The video is sized to maintain its aspect ratio while filling the element's entire content box. The video will be clipped to fit.+- `'fill'`: The video is stretched to fill the element's content box. The video's aspect ratio is not preserved.+- `'none'`: The video is not resized. It is centered within the element.+- `'scale-down'`: The video is sized as if `none` or `contain` were specified, whichever would result in a smaller size.++```tsx twoslash+import {AbsoluteFill, staticFile} from 'remotion';+import {Video} from '@remotion/media';++// ---cut---+export const MyComposition = () => {+ return (+ <AbsoluteFill>+ <Video+ src={staticFile('video.webm')}+ style={{width: '100%', height: '100%'}}+ objectFit="cover"+ />+ </AbsoluteFill>+ );+};+```++:::note+The CSS property `object-fit` is not supported.+:::+### `loop?`Makes the video loop indefinitely.diff --git a/packages/eslint-plugin/src/index.ts b/packages/eslint-plugin/src/index.tsindex 4b2ef13687..1a07c50b0c 100644--- a/packages/eslint-plugin/src/index.ts+++ b/packages/eslint-plugin/src/index.ts@@ -3,6 +3,7 @@ import evenDimensions from './rules/even-dimensions';import noBackgroundImage from './rules/no-background-image';import durationInFrames from './rules/no-duration-frames-infinity';import noFrom0 from './rules/no-from-0';+import noObjectFitOnMediaVideo from './rules/no-object-fit-on-media-video';import noStringAssets from './rules/no-string-assets';import nonPureAnimation from './rules/non-pure-animation';import slowCssProperty from './rules/slow-css-property';@@ -28,6 +29,7 @@ const rules = {'non-pure-animation': nonPureAnimation,'slow-css-property': slowCssProperty,'v4-config-import': v4Import,+ 'no-object-fit-on-media-video': noObjectFitOnMediaVideo,};const recommendedRuleConfig = {@@ -44,6 +46,7 @@ const recommendedRuleConfig = {'@remotion/no-background-image': 'error','@remotion/non-pure-animation': 'warn','@remotion/v4-config-import': 'error',+ '@remotion/no-object-fit-on-media-video': 'warn',} as const;const configs = {diff --git a/packages/eslint-plugin/src/rules/no-object-fit-on-media-video.ts b/packages/eslint-plugin/src/rules/no-object-fit-on-media-video.tsnew file mode 100644index 0000000000..5e465c110f--- /dev/null+++ b/packages/eslint-plugin/src/rules/no-object-fit-on-media-video.ts@@ -0,0 +1,130 @@+import {ESLintUtils} from '@typescript-eslint/utils';++const createRule = ESLintUtils.RuleCreator(() => {+ return 'https://remotion.dev/docs/media/video#objectfit';+});++type Options = [];+type MessageIds = 'NoObjectFitInStyle' | 'NoObjectFitInClassName';++const NoObjectFitInStyle = [+ 'Passing `objectFit` via the `style` prop is not supported for `<Video>` from `@remotion/media`.',+ 'Use the `objectFit` prop directly instead.',+ 'See: https://remotion.dev/docs/media/video#objectfit',+].join('\n');++const NoObjectFitInClassName = [+ 'Passing an `object-fit` CSS class via `className` is not supported for `<Video>` from `@remotion/media`.',+ 'Use the `objectFit` prop directly instead.',+ 'See: https://remotion.dev/docs/media/video#objectfit',+].join('\n');++const objectFitClassPattern =+ /\bobject-(contain|cover|fill|none|scale-down)\b/;++export default createRule<Options, MessageIds>({+ name: 'no-object-fit-on-media-video',+ meta: {+ type: 'problem',+ docs: {+ description: NoObjectFitInStyle,+ recommended: 'warn',+ },+ fixable: undefined,+ schema: [],+ messages: {+ NoObjectFitInStyle,+ NoObjectFitInClassName,+ },+ },+ defaultOptions: [],+ create: (context) => {+ return {+ JSXOpeningElement: (node) => {+ if (node.name.type !== 'JSXIdentifier' || node.name.name !== 'Video') {+ return;+ }++ for (const attr of node.attributes) {+ if (attr.type !== 'JSXAttribute') {+ continue;+ }++ // Check style={{ objectFit: ... }}+ if (+ attr.name.type === 'JSXIdentifier' &&+ attr.name.name === 'style' &&+ attr.value+ ) {+ if (+ attr.value.type === 'JSXExpressionContainer' &&+ attr.value.expression.type === 'ObjectExpression'+ ) {+ for (const prop of attr.value.expression.properties) {+ if (prop.type !== 'Property') {+ continue;+ }++ let propertyName: string | undefined;+ if (prop.key.type === 'Identifier') {+ propertyName = prop.key.name;+ } else if (+ prop.key.type === 'Literal' &&+ typeof prop.key.value === 'string'+ ) {+ propertyName = prop.key.value;+ }++ if (+ propertyName === 'objectFit' ||+ propertyName === 'object-fit'+ ) {+ context.report({+ messageId: 'NoObjectFitInStyle',+ node: prop,+ });+ }+ }+ }+ }++ // Check className for Tailwind object-fit classes+ if (+ attr.name.type === 'JSXIdentifier' &&+ attr.name.name === 'className' &&+ attr.value+ ) {+ let classString: string | undefined;++ if (+ attr.value.type === 'Literal' &&+ typeof attr.value.value === 'string'+ ) {+ classString = attr.value.value;+ } else if (+ attr.value.type === 'JSXExpressionContainer' &&+ attr.value.expression.type === 'Literal' &&+ typeof attr.value.expression.value === 'string'+ ) {+ classString = attr.value.expression.value;+ } else if (+ attr.value.type === 'JSXExpressionContainer' &&+ attr.value.expression.type === 'TemplateLiteral'+ ) {+ classString = attr.value.expression.quasis+ .map((q) => q.value.cooked || q.value.raw)+ .join(' ');+ }++ if (classString && objectFitClassPattern.test(classString)) {+ context.report({+ messageId: 'NoObjectFitInClassName',+ node: attr,+ });+ }+ }+ }+ },+ };+ },+});diff --git a/packages/eslint-plugin/src/tests/no-object-fit-on-media-video.test.ts b/packages/eslint-plugin/src/tests/no-object-fit-on-media-video.test.tsnew file mode 100644index 0000000000..6ac13808a7--- /dev/null+++ b/packages/eslint-plugin/src/tests/no-object-fit-on-media-video.test.ts@@ -0,0 +1,94 @@+import {ESLintUtils} from '@typescript-eslint/utils';+import rule from '../rules/no-object-fit-on-media-video';++const ruleTester = new ESLintUtils.RuleTester({+ parser: '@typescript-eslint/parser',+ parserOptions: {+ ecmaFeatures: {+ jsx: true,+ },+ },+});++ruleTester.run('no-object-fit-on-media-video', rule, {+ valid: [+ // objectFit as a prop is fine+ `<Video src="video.mp4" objectFit="cover" />`,+ // No objectFit in style is fine+ `<Video src="video.mp4" style={{width: '100%', height: '100%'}} />`,+ // Other components with objectFit in style are fine+ `<img style={{objectFit: 'cover'}} />`,+ `<div style={{objectFit: 'cover'}} />`,+ // Other components with object-fit className are fine+ `<img className="object-cover" />`,+ // Video with unrelated className+ `<Video src="video.mp4" className="w-full h-full" />`,+ // Video with unrelated style props+ `<Video src="video.mp4" style={{opacity: 0.5}} />`,+ ],+ invalid: [+ // objectFit in style object+ {+ code: `<Video src="video.mp4" style={{objectFit: 'cover'}} />`,+ errors: [{messageId: 'NoObjectFitInStyle'}],+ },+ // objectFit in style alongside other props+ {+ code: `<Video src="video.mp4" style={{width: '100%', objectFit: 'contain'}} />`,+ errors: [{messageId: 'NoObjectFitInStyle'}],+ },+ // kebab-case object-fit in style+ {+ code: `<Video src="video.mp4" style={{"object-fit": 'fill'}} />`,+ errors: [{messageId: 'NoObjectFitInStyle'}],+ },+ // Tailwind object-cover in className string+ {+ code: `<Video src="video.mp4" className="object-cover" />`,+ errors: [{messageId: 'NoObjectFitInClassName'}],+ },+ // Tailwind object-contain in className string+ {+ code: `<Video src="video.mp4" className="object-contain" />`,+ errors: [{messageId: 'NoObjectFitInClassName'}],+ },+ // Tailwind object-fill in className+ {+ code: `<Video src="video.mp4" className="object-fill" />`,+ errors: [{messageId: 'NoObjectFitInClassName'}],+ },+ // Tailwind object-none in className+ {+ code: `<Video src="video.mp4" className="object-none" />`,+ errors: [{messageId: 'NoObjectFitInClassName'}],+ },+ // Tailwind object-scale-down in className+ {+ code: `<Video src="video.mp4" className="object-scale-down" />`,+ errors: [{messageId: 'NoObjectFitInClassName'}],+ },+ // Tailwind class mixed with others+ {+ code: `<Video src="video.mp4" className="w-full h-full object-cover" />`,+ errors: [{messageId: 'NoObjectFitInClassName'}],+ },+ // className as JSX expression+ {+ code: `<Video src="video.mp4" className={"object-cover"} />`,+ errors: [{messageId: 'NoObjectFitInClassName'}],+ },+ // className as template literal+ {+ code: `<Video src="video.mp4" className={\`object-cover \${variant}\`} />`,+ errors: [{messageId: 'NoObjectFitInClassName'}],+ },+ // Both style and className violations+ {+ code: `<Video src="video.mp4" style={{objectFit: 'cover'}} className="object-cover" />`,+ errors: [+ {messageId: 'NoObjectFitInStyle'},+ {messageId: 'NoObjectFitInClassName'},+ ],+ },+ ],+});diff --git a/packages/example/src/ObjectFitTest.tsx b/packages/example/src/ObjectFitTest.tsxnew file mode 100644index 0000000000..20ced61e6a--- /dev/null+++ b/packages/example/src/ObjectFitTest.tsx@@ -0,0 +1,40 @@+import {Video, VideoObjectFit} from '@remotion/media';+import React from 'react';+import {AbsoluteFill, Composition, staticFile} from 'remotion';+import {z} from 'zod';++const objectFitSchema = z.object({+ objectFit: z.enum(['fill', 'contain', 'cover', 'none', 'scale-down']),+});++const ObjectFitTest: React.FC<z.infer<typeof objectFitSchema>> = ({+ objectFit,+}) => {+ return (+ <AbsoluteFill style={{backgroundColor: '#333'}}>+ <Video+ src={staticFile('bigbuckbunny.mp4')}+ style={{width: '100%', height: '100%'}}+ objectFit={objectFit as VideoObjectFit}+ muted+ />+ </AbsoluteFill>+ );+};++export const ObjectFitTestComp = () => {+ return (+ <Composition+ id="ObjectFitTest"+ component={ObjectFitTest}+ width={1080}+ height={1920}+ fps={30}+ durationInFrames={150}+ schema={objectFitSchema}+ defaultProps={{+ objectFit: 'cover' as const,+ }}+ />+ );+};diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsxindex a602f391b7..70fd2147c9 100644--- a/packages/example/src/Root.tsx+++ b/packages/example/src/Root.tsx@@ -130,6 +130,7 @@ import {LightLeakAnimatedSize} from './LightLeak/AnimatedSize';import {LoopDisplayTestComp} from './LoopDisplayTest';import {NewAudioExample} from './NewAudio/NewAudio';import {NewVideoComp} from './NewVideo';+import {ObjectFitTestComp} from './ObjectFitTest';import {ChangingTrimBeforeValue} from './OffthreadRemoteVideo/ChangingTrimBefore';import {LoopedNewVideo} from './OffthreadRemoteVideo/LoopedNewVideo';import {LoopedOffthreadRemoteVideo} from './OffthreadRemoteVideo/LoopedOffthreadRemoteVideo';@@ -807,6 +808,7 @@ export const Index: React.FC = () => {/><OffthreadRemoteVideo /><NewVideoComp />+ <ObjectFitTestComp /><NewVideoBufferStateComp /><LoopDisplayTestComp /><OffthreadRemoteSeries />diff --git a/packages/media/src/index.ts b/packages/media/src/index.tsindex 6bc908ec34..85342d9e12 100644--- a/packages/media/src/index.ts+++ b/packages/media/src/index.ts@@ -13,5 +13,9 @@ export const experimental_Video = Video;export {AudioForPreview} from './audio/audio-for-preview';export {AudioProps, FallbackHtml5AudioProps} from './audio/props';export {MediaErrorAction} from './on-error';-export {FallbackOffthreadVideoProps, VideoProps} from './video/props';+export {+ FallbackOffthreadVideoProps,+ VideoObjectFit,+ VideoProps,+} from './video/props';export {Audio, Video};diff --git a/packages/media/src/video/props.ts b/packages/media/src/video/props.tsindex 6956f8ada3..ad43c30150 100644--- a/packages/media/src/video/props.ts+++ b/packages/media/src/video/props.ts@@ -10,6 +10,13 @@ export type MediaErrorEvent = {error: Error;};+export type VideoObjectFit =+ | 'fill'+ | 'contain'+ | 'cover'+ | 'none'+ | 'scale-down';+export type FallbackOffthreadVideoProps = {acceptableTimeShiftInSeconds?: number;transparent?: boolean;@@ -59,6 +66,7 @@ type OptionalVideoProps = {headless: boolean;onError: MediaOnError | undefined;credentials: RequestCredentials | undefined;+ objectFit: VideoObjectFit;};export type InnerVideoProps = MandatoryVideoProps &diff --git a/packages/media/src/video/video-for-preview.tsx b/packages/media/src/video/video-for-preview.tsxindex 63cdfa2c02..f81e3077cc 100644--- a/packages/media/src/video/video-for-preview.tsx+++ b/packages/media/src/video/video-for-preview.tsx@@ -25,7 +25,8 @@ import {type MediaOnError, callOnErrorAndResolve} from '../on-error';import {useLoopDisplay} from '../show-in-timeline';import {useCommonEffects} from '../use-common-effects';import {useMediaInTimeline} from '../use-media-in-timeline';-import type {FallbackOffthreadVideoProps} from './props';+import type {FallbackOffthreadVideoProps, VideoObjectFit} from './props';+import {warnAboutObjectFitInStyleOrClassName} from './warn-object-fit-css';const {useUnsafeVideoConfig,@@ -65,6 +66,7 @@ type VideoForPreviewProps = {readonly headless: boolean;readonly onError: MediaOnError | undefined;readonly credentials: RequestCredentials | undefined;+ readonly objectFit: VideoObjectFit;};type VideoForPreviewAssertedShowingProps = VideoForPreviewProps & {@@ -98,6 +100,7 @@ const VideoForPreviewAssertedShowing: React.FC<onError,credentials,controls,+ objectFit: objectFitProp,}) => {const src = usePreload(unpreloadedSrc);@@ -367,6 +370,8 @@ const VideoForPreviewAssertedShowing: React.FC<credentials,]);+ warnAboutObjectFitInStyleOrClassName({style, className, logLevel});+const classNameValue = useMemo(() => {return [Internals.OBJECTFIT_CONTAIN_CLASS_NAME, className].filter(Internals.truthy)@@ -421,8 +426,9 @@ const VideoForPreviewAssertedShowing: React.FC<return {...style,opacity: isSequenceHidden ? 0 : (style?.opacity ?? 1),+ objectFit: objectFitProp,};- }, [isSequenceHidden, style]);+ }, [isSequenceHidden, objectFitProp, style]);if (shouldFallbackToNativeVideo && !disallowFallbackToOffthreadVideo) {// <Video> will fallback to <VideoForPreview> anywaydiff --git a/packages/media/src/video/video-for-rendering.tsx b/packages/media/src/video/video-for-rendering.tsxindex b96a88ccf5..59792093e7 100644--- a/packages/media/src/video/video-for-rendering.tsx+++ b/packages/media/src/video/video-for-rendering.tsx@@ -26,7 +26,8 @@ import {TARGET_SAMPLE_RATE} from '../convert-audiodata/resample-audiodata';import {frameForVolumeProp} from '../looped-frame';import {type MediaOnError, callOnErrorAndResolve} from '../on-error';import {extractFrameViaBroadcastChannel} from '../video-extraction/extract-frame-via-broadcast-channel';-import type {FallbackOffthreadVideoProps} from './props';+import type {FallbackOffthreadVideoProps, VideoObjectFit} from './props';+import {warnAboutObjectFitInStyleOrClassName} from './warn-object-fit-css';type InnerVideoProps = {readonly className: string | undefined;@@ -52,6 +53,7 @@ type InnerVideoProps = {readonly headless: boolean;readonly onError: MediaOnError | undefined;readonly credentials: RequestCredentials | undefined;+ readonly objectFit: VideoObjectFit;};type FallbackToOffthreadVideo = {@@ -82,6 +84,7 @@ export const VideoForRendering: React.FC<InnerVideoProps> = ({headless,onError,credentials,+ objectFit: objectFitProp,}) => {if (!src) {throw new TypeError('No `src` was passed to <Video>.');@@ -389,12 +392,21 @@ export const VideoForRendering: React.FC<InnerVideoProps> = ({credentials,]);+ warnAboutObjectFitInStyleOrClassName({style, className, logLevel});+const classNameValue = useMemo(() => {return [Internals.OBJECTFIT_CONTAIN_CLASS_NAME, className].filter(Internals.truthy).join(' ');}, [className]);+ const styleWithObjectFit: React.CSSProperties = useMemo(() => {+ return {+ ...style,+ objectFit: objectFitProp,+ };+ }, [objectFitProp, style]);+if (replaceWithOffthreadVideo) {const fallback = (<Internals.InnerOffthreadVideo@@ -409,7 +421,7 @@ export const VideoForRendering: React.FC<InnerVideoProps> = ({delayRenderTimeoutInMilliseconds={delayRenderTimeoutInMilliseconds ?? undefined}- style={style}+ style={styleWithObjectFit}allowAmplificationDuringRendertransparent={fallbackOffthreadVideoProps?.transparent ?? true}toneMapped={fallbackOffthreadVideoProps?.toneMapped ?? true}@@ -472,5 +484,11 @@ export const VideoForRendering: React.FC<InnerVideoProps> = ({return null;}- return <canvas ref={canvasRef} style={style} className={classNameValue} />;+ return (+ <canvas+ ref={canvasRef}+ style={styleWithObjectFit}+ className={classNameValue}+ />+ );};diff --git a/packages/media/src/video/video.tsx b/packages/media/src/video/video.tsxindex af47cd243e..e03c53379e 100644--- a/packages/media/src/video/video.tsx+++ b/packages/media/src/video/video.tsx@@ -87,6 +87,7 @@ const InnerVideo: React.FC<onError,credentials,controls,+ objectFit,}) => {const environment = useRemotionEnvironment();@@ -144,6 +145,7 @@ const InnerVideo: React.FC<headless={headless}onError={onError}credentials={credentials}+ objectFit={objectFit}/>);}@@ -174,6 +176,7 @@ const InnerVideo: React.FC<onError={onError}credentials={credentials}controls={controls}+ objectFit={objectFit}/>);};@@ -210,6 +213,7 @@ const VideoInner: React.FC<onError,credentials,controls,+ objectFit,}) => {const fallbackLogLevel = Internals.useLogLevel();return (@@ -245,6 +249,7 @@ const VideoInner: React.FC<onError={onError}credentials={credentials}controls={controls}+ objectFit={objectFit ?? 'contain'}/>);};diff --git a/packages/media/src/video/warn-object-fit-css.ts b/packages/media/src/video/warn-object-fit-css.tsnew file mode 100644index 0000000000..26ccdc9052--- /dev/null+++ b/packages/media/src/video/warn-object-fit-css.ts@@ -0,0 +1,38 @@+import type {LogLevel} from 'remotion';+import {Internals} from 'remotion';++const OBJECT_FIT_CLASS_PATTERN =+ /\bobject-(contain|cover|fill|none|scale-down)\b/;++let warnedStyle = false;+let warnedClassName = false;++export const warnAboutObjectFitInStyleOrClassName = ({+ style,+ className,+ logLevel,+}: {+ style: React.CSSProperties | undefined;+ className: string | undefined;+ logLevel: LogLevel;+}): void => {+ if (!warnedStyle && style?.objectFit) {+ warnedStyle = true;+ Internals.Log.warn(+ {logLevel, tag: '@remotion/media'},+ 'Use the `objectFit` prop instead of the `style` prop.',+ );+ }++ if (+ !warnedClassName &&+ className &&+ OBJECT_FIT_CLASS_PATTERN.test(className)+ ) {+ warnedClassName = true;+ Internals.Log.warn(+ {logLevel, tag: '@remotion/media'},+ 'Use the `objectFit` prop instead of `object-*` CSS class names.',+ );+ }+};