🎥 Make videos programmatically with React
`@remotion/effects`: Add tile effect (#10505)
Jonny Burger6f4f82b7fe25
diff --git a/packages/docs/components/effects-demos/registry.ts b/packages/docs/components/effects-demos/registry.tsindex 7659f986e6..a964fd426e 100644--- a/packages/docs/components/effects-demos/registry.ts+++ b/packages/docs/components/effects-demos/registry.ts@@ -55,6 +55,7 @@ import {skew} from '@remotion/effects/skew';import {speckle} from '@remotion/effects/speckle';import {starburst} from '@remotion/effects/starburst';import {thermalVision} from '@remotion/effects/thermal-vision';+import {tile} from '@remotion/effects/tile';import {tint} from '@remotion/effects/tint';import {uvTranslate, xyTranslate} from '@remotion/effects/translate';import {tvSignalOff} from '@remotion/effects/tv-signal-off';@@ -146,6 +147,7 @@ import {STARBURST_PREVIEW_PARAMS,} from '../effects/effects-starburst-preview';import {EffectsThermalVisionPreview} from '../effects/effects-thermal-vision-preview';+import {EffectsTilePreview} from '../effects/effects-tile-preview';import {EffectsTintPreview} from '../effects/effects-tint-preview';import {EffectsUvTranslatePreview,@@ -539,6 +541,14 @@ export const effectsDemos: EffectsDemoType[] = [comp: EffectsScalePreview,schema: scale({scale: 1}).definition.schema,},+ {+ ...defaults,+ id: 'effects-tile',+ effectName: 'tile',+ effectImportPath: '@remotion/effects/tile',+ comp: EffectsTilePreview,+ schema: tile().definition.schema,+ },{...defaults,id: 'effects-xy-translate',diff --git a/packages/docs/components/effects/effects-tile-preview.tsx b/packages/docs/components/effects/effects-tile-preview.tsxnew file mode 100644index 0000000000..2accd78be4--- /dev/null+++ b/packages/docs/components/effects/effects-tile-preview.tsx@@ -0,0 +1,20 @@+import {scale} from '@remotion/effects/scale';+import {tile} from '@remotion/effects/tile';+import React from 'react';+import {CanvasImage} from 'remotion';+import {EFFECTS_PREVIEW_IMAGE_SRC} from './effects-preview-image';++export const EffectsTilePreview: React.FC<{+ readonly horizontal: boolean;+ readonly vertical: boolean;+}> = ({horizontal, vertical}) => {+ return (+ <CanvasImage+ src={EFFECTS_PREVIEW_IMAGE_SRC}+ width={1280}+ height={720}+ fit="cover"+ effects={[scale({scale: 0.36}), tile({horizontal, vertical})]}+ />+ );+};diff --git a/packages/docs/docs/effects/tile.mdx b/packages/docs/docs/effects/tile.mdxnew file mode 100644index 0000000000..26a6bea5d8--- /dev/null+++ b/packages/docs/docs/effects/tile.mdx@@ -0,0 +1,71 @@+---+image: /generated/articles-docs-effects-tile.png+slug: /effects/tile+title: tile()+sidebar_label: tile()+crumb: '@remotion/effects'+---++# tile()<AvailableFrom v="4.0.513" />++_Part of the [`@remotion/effects`](/docs/effects/api) package._++Repeats the non-transparent area of a canvas source across the canvas. Every other copy is mirrored so neighboring tiles meet at matching edges.++Place [`scale()`](/docs/effects/scale) before `tile()` to expand a texture beyond its original edges.++## Preview++<EffectsDemo type="effects-tile" />++## Example++```tsx twoslash title="MyComp.tsx"+import {AbsoluteFill} from 'remotion';+import {Video} from '@remotion/media';+import {tile} from '@remotion/effects/tile';+import {scale} from '@remotion/effects/scale';++export const MyComp: React.FC = () => {+ return (+ <AbsoluteFill>+ <Video+ src="https://remotion.media/video.mp4"+ effects={[+ scale({scale: 0.25}),+ tile(),+ ]}+ />+ </AbsoluteFill>+ );+};+```++Effects are applied in array order. `tile()` finds the non-transparent bounds left by `scale()` and alternates mirrored copies along each enabled axis.++## API++You can call `tile()` without arguments or pass an object with the following properties.++### `horizontal?`++Whether to repeat the tile horizontally. Defaults to `true`.++### `vertical?`++Whether to repeat the tile vertically. Defaults to `true`.++### `disabled?`++When `true`, the effect is skipped. Defaults to `false`.++## Compatibility++<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering serverSideRendering player studio hideServers />++## See also++- [`@remotion/effects`](/docs/effects/api)+- [`scale()`](/docs/effects/scale)+- [`pattern()`](/docs/effects/pattern)+- [Source code for this effect](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/tile.ts)diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex e0d40a8d3a..86619c85df 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -330,6 +330,7 @@ const sidebars: SidebarsConfig = {'effects/speckle','effects/starburst','effects/thermal-vision',+ 'effects/tile','effects/tint','effects/tv-signal-off','effects/uv-translate',diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex e5b05f20e4..2aa9b3ec19 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -2330,6 +2330,15 @@ export const articles = [noAi: false,slug: 'effects/thermal-vision',},+ {+ id: 'effects/tile',+ title: 'tile()',+ relativePath: 'docs/effects/tile.mdx',+ compId: 'articles-docs-effects-tile',+ crumb: '@remotion/effects',+ noAi: false,+ slug: 'effects/tile',+ },{id: 'effects/tint',title: 'tint()',diff --git a/packages/docs/src/remotion/Root.tsx b/packages/docs/src/remotion/Root.tsxindex 2824669ea8..1c04bc20ec 100644--- a/packages/docs/src/remotion/Root.tsx+++ b/packages/docs/src/remotion/Root.tsx@@ -89,6 +89,7 @@ import {STARBURST_PREVIEW_PARAMS,} from '../../components/effects/effects-starburst-preview';import {EffectsThermalVisionPreview} from '../../components/effects/effects-thermal-vision-preview';+import {EffectsTilePreview} from '../../components/effects/effects-tile-preview';import {EffectsTintPreview} from '../../components/effects/effects-tint-preview';import {EffectsUvTranslatePreview,@@ -451,6 +452,13 @@ export const RemotionRoot: React.FC = () => {height={720}defaultProps={{scale: 0.8, horizontal: true, vertical: true}}/>+ <Still+ id="effects-tile-preview"+ component={EffectsTilePreview}+ width={1280}+ height={720}+ defaultProps={{horizontal: true, vertical: true}}+ /><Stillid="effects-xy-translate-preview"component={EffectsXyTranslatePreview}diff --git a/packages/docs/static/generated/articles-docs-effects-tile.png b/packages/docs/static/generated/articles-docs-effects-tile.pngnew file mode 100644index 0000000000..44000ba4b5Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-tile.png differdiff --git a/packages/docs/static/img/effects-tile-preview.png b/packages/docs/static/img/effects-tile-preview.pngnew file mode 100644index 0000000000..0278f89fc6Binary files /dev/null and b/packages/docs/static/img/effects-tile-preview.png differdiff --git a/packages/effects/bundle.ts b/packages/effects/bundle.tsindex 03876c7e31..7a61a8dbf1 100644--- a/packages/effects/bundle.ts+++ b/packages/effects/bundle.ts@@ -64,6 +64,7 @@ const effectEntrypoints = ['src/speckle.ts','src/starburst.ts','src/thermal-vision.ts',+ 'src/tile.ts','src/tint.ts','src/translate.ts','src/tv-signal-off.ts',diff --git a/packages/effects/package.json b/packages/effects/package.jsonindex ec62d0bf28..62a6d786c7 100644--- a/packages/effects/package.json+++ b/packages/effects/package.json@@ -319,6 +319,11 @@"module": "./dist/esm/thermal-vision.mjs","import": "./dist/esm/thermal-vision.mjs"},+ "./tile": {+ "types": "./dist/tile.d.ts",+ "module": "./dist/esm/tile.mjs",+ "import": "./dist/esm/tile.mjs"+ },"./tint": {"types": "./dist/tint.d.ts","module": "./dist/esm/tint.mjs",@@ -554,6 +559,9 @@"thermal-vision": ["dist/thermal-vision.d.ts"],+ "tile": [+ "dist/tile.d.ts"+ ],"tint": ["dist/tint.d.ts"],diff --git a/packages/effects/src/index.ts b/packages/effects/src/index.tsindex 439e630afd..f766d3f976 100644--- a/packages/effects/src/index.ts+++ b/packages/effects/src/index.ts@@ -1,5 +1,6 @@export {checkerboard, type CheckerboardParams} from './checkerboard.js';export {pattern, type PatternOrigin, type PatternParams} from './pattern.js';+export {tile, type TileParams} from './tile.js';export {rings, type RingsCenter, type RingsParams} from './rings.js';export {starburst,diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.tsindex ed763410ea..0968bfbbf4 100644--- a/packages/effects/src/test/effect-params.test.ts+++ b/packages/effects/src/test/effect-params.test.ts@@ -66,6 +66,7 @@ import {skew} from '../skew.js';import {speckle} from '../speckle.js';import {starburst} from '../starburst.js';import {thermalVision} from '../thermal-vision.js';+import {tile} from '../tile.js';import {tint} from '../tint.js';import {uvTranslate, xyTranslate} from '../translate.js';import {tvSignalOff} from '../tv-signal-off.js';@@ -239,6 +240,9 @@ test('@remotion/effects expose documentation links', () => {regionBlur({topLeft: [0.25, 0.25], bottomRight: [0.75, 0.75]}).definition.documentationLink,).toBe('https://www.remotion.dev/docs/effects/region-blur');+ expect(tile().definition.documentationLink).toBe(+ 'https://www.remotion.dev/docs/effects/tile',+ );expect(radialProgressivePixelate().definition.documentationLink).toBe('https://www.remotion.dev/docs/effects/radial-progressive-pixelate',);@@ -371,6 +375,7 @@ test('@remotion/effects expose API names as Studio labels', () => {expect(radialProgressivePixelate().definition.label).toBe('radialProgressivePixelate()',);+ expect(tile().definition.label).toBe('tile()');expect(rings().definition.label).toBe('rings()');expect(saturation().definition.label).toBe('saturation()');expect(scanlines().definition.label).toBe('scanlines()');@@ -3011,6 +3016,37 @@ test('pattern() parameters produce distinct effect keys', () => {).toBe(10);});+test('tile() accepts default params', () => {+ expect(() => tile()).not.toThrow();+});++test('tile() accepts axis params', () => {+ expect(() => tile({horizontal: false, vertical: true})).not.toThrow();+});++test('tile() rejects invalid axis params', () => {+ expect(() => tile({horizontal: 'yes' as unknown as boolean})).toThrow(+ '"horizontal" must be a boolean',+ );+ expect(() => tile({vertical: 1 as unknown as boolean})).toThrow(+ '"vertical" must be a boolean',+ );+});++test('tile() parameters produce distinct effect keys', () => {+ const defaults = tile();+ const horizontalOnly = tile({vertical: false});+ const verticalOnly = tile({horizontal: false});++ expect(+ new Set([+ defaults.effectKey,+ horizontalOnly.effectKey,+ verticalOnly.effectKey,+ ]).size,+ ).toBe(3);+});+test('saturation() accepts default params', () => {expect(() => saturation()).not.toThrow();});diff --git a/packages/effects/src/tile.ts b/packages/effects/src/tile.tsnew file mode 100644index 0000000000..d1d107e9c6--- /dev/null+++ b/packages/effects/src/tile.ts@@ -0,0 +1,236 @@+import type {InteractivitySchema} from 'remotion';+import {Internals} from 'remotion';+import {+ assertEffectParamsObject,+ assertOptionalBoolean,+} from './validate-effect-param.js';++const {createEffect} = Internals;++const DEFAULT_HORIZONTAL = true as const;+const DEFAULT_VERTICAL = true as const;++const tileSchema = {+ horizontal: {+ type: 'boolean',+ default: DEFAULT_HORIZONTAL,+ description: 'Horizontal',+ },+ vertical: {+ type: 'boolean',+ default: DEFAULT_VERTICAL,+ description: 'Vertical',+ },+} as const satisfies InteractivitySchema;++export type TileParams = {+ /** Whether to repeat the source horizontally. Defaults to `true`. */+ readonly horizontal?: boolean;+ /** Whether to repeat the source vertically. Defaults to `true`. */+ readonly vertical?: boolean;+};++type TileResolved = {+ readonly horizontal: boolean;+ readonly vertical: boolean;+};++type TileState = {+ readonly boundsCanvas: HTMLCanvasElement;+ readonly boundsContext: CanvasRenderingContext2D;+ readonly tileCanvas: HTMLCanvasElement;+ readonly tileContext: CanvasRenderingContext2D;+};++const resolve = (params: TileParams): TileResolved => ({+ horizontal: params.horizontal ?? DEFAULT_HORIZONTAL,+ vertical: params.vertical ?? DEFAULT_VERTICAL,+});++const validateTileParams = (params: TileParams): void => {+ assertEffectParamsObject(params, 'Tile');+ assertOptionalBoolean(params.horizontal, 'horizontal');+ assertOptionalBoolean(params.vertical, 'vertical');+};++export const tile = createEffect<TileParams, TileState>({+ type: 'dev.remotion.effects.tile',+ label: 'tile()',+ documentationLink: 'https://www.remotion.dev/docs/effects/tile',+ backend: '2d',+ calculateKey: (params) => {+ const r = resolve(params);+ return `tile-${r.horizontal}-${r.vertical}`;+ },+ setup: (target) => {+ const boundsCanvas = target.ownerDocument.createElement('canvas');+ const boundsContext = boundsCanvas.getContext('2d', {+ colorSpace: 'srgb',+ willReadFrequently: true,+ });+ if (!boundsContext) {+ throw new Error('Failed to acquire 2D context for tile effect.');+ }++ const tileCanvas = target.ownerDocument.createElement('canvas');+ const tileContext = tileCanvas.getContext('2d');+ if (!tileContext) {+ throw new Error('Failed to acquire 2D context for tile effect.');+ }++ return {boundsCanvas, boundsContext, tileCanvas, tileContext};+ },+ apply: ({source, target, width, height, params, state}) => {+ const context = target.getContext('2d');+ if (!context) {+ throw new Error(+ 'Failed to acquire 2D context for tile effect. The canvas may have been assigned a different context type.',+ );+ }++ const r = resolve(params);+ context.clearRect(0, 0, width, height);++ if (!r.horizontal && !r.vertical) {+ context.drawImage(source, 0, 0, width, height);+ return;+ }++ if (+ state.boundsCanvas.width !== width ||+ state.boundsCanvas.height !== height+ ) {+ state.boundsCanvas.width = width;+ state.boundsCanvas.height = height;+ }++ state.boundsContext.clearRect(0, 0, width, height);+ state.boundsContext.drawImage(source, 0, 0, width, height);+ const pixels = state.boundsContext.getImageData(0, 0, width, height).data;+ const rowMaximumAlpha = (y: number) => {+ let maximumAlpha = 0;+ for (let x = 0; x < width; x++) {+ maximumAlpha = Math.max(maximumAlpha, pixels[(y * width + x) * 4 + 3]);+ }++ return maximumAlpha;+ };++ const columnMaximumAlpha = (+ x: number,+ visibleTop: number,+ visibleBottom: number,+ ) => {+ let maximumAlpha = 0;+ for (let y = visibleTop; y <= visibleBottom; y++) {+ maximumAlpha = Math.max(maximumAlpha, pixels[(y * width + x) * 4 + 3]);+ }++ return maximumAlpha;+ };++ let top = 0;+ while (top < height && rowMaximumAlpha(top) === 0) {+ top++;+ }++ if (top === height) {+ context.clearRect(0, 0, width, height);+ return;+ }++ let bottom = height - 1;+ while (bottom > top && rowMaximumAlpha(bottom) === 0) {+ bottom--;+ }++ let left = 0;+ while (left < width && columnMaximumAlpha(left, top, bottom) === 0) {+ left++;+ }++ let right = width - 1;+ while (right > left && columnMaximumAlpha(right, top, bottom) === 0) {+ right--;+ }++ // Fractional scaling can leave a one-pixel antialias fringe around an+ // otherwise opaque source. Repeating that fringe exposes the transparent+ // pixels as a line between copies. Only trim a boundary when the adjacent+ // row or column is more opaque, preserving intentionally uniform alpha.+ if (r.vertical && top < bottom) {+ if (rowMaximumAlpha(top) < rowMaximumAlpha(top + 1)) {+ top++;+ }++ if (rowMaximumAlpha(bottom) < rowMaximumAlpha(bottom - 1)) {+ bottom--;+ }+ }++ if (r.horizontal && left < right) {+ if (+ columnMaximumAlpha(left, top, bottom) <+ columnMaximumAlpha(left + 1, top, bottom)+ ) {+ left++;+ }++ if (+ columnMaximumAlpha(right, top, bottom) <+ columnMaximumAlpha(right - 1, top, bottom)+ ) {+ right--;+ }+ }++ const tileWidth = right - left + 1;+ const tileHeight = bottom - top + 1;+ state.tileCanvas.width = tileWidth;+ state.tileCanvas.height = tileHeight;+ state.tileContext.clearRect(0, 0, tileWidth, tileHeight);+ state.tileContext.drawImage(+ source,+ left,+ top,+ tileWidth,+ tileHeight,+ 0,+ 0,+ tileWidth,+ tileHeight,+ );++ context.clearRect(0, 0, width, height);+ const startX = r.horizontal+ ? left - Math.ceil(left / tileWidth) * tileWidth+ : left;+ const startY = r.vertical+ ? top - Math.ceil(top / tileHeight) * tileHeight+ : top;+ const endX = r.horizontal ? width : left + tileWidth;+ const endY = r.vertical ? height : top + tileHeight;++ for (let y = startY; y < endY; y += tileHeight) {+ const tileY = Math.round((y - top) / tileHeight);+ const mirrorY = r.vertical && Math.abs(tileY) % 2 === 1;++ for (let x = startX; x < endX; x += tileWidth) {+ const tileX = Math.round((x - left) / tileWidth);+ const mirrorX = r.horizontal && Math.abs(tileX) % 2 === 1;++ context.save();+ context.translate(+ mirrorX ? x + tileWidth : x,+ mirrorY ? y + tileHeight : y,+ );+ context.scale(mirrorX ? -1 : 1, mirrorY ? -1 : 1);+ context.drawImage(state.tileCanvas, 0, 0);+ context.restore();+ }+ }+ },+ cleanup: () => undefined,+ schema: tileSchema,+ validateParams: validateTileParams,+});diff --git a/packages/effects/src/visual-test/effects-visual.test.ts b/packages/effects/src/visual-test/effects-visual.test.tsindex ae20bf6fae..e691426816 100644--- a/packages/effects/src/visual-test/effects-visual.test.ts+++ b/packages/effects/src/visual-test/effects-visual.test.ts@@ -8,7 +8,9 @@ import {levels} from '../levels.js';import {noise} from '../noise.js';import {pixelDissolve} from '../pixel-dissolve.js';import {saturation} from '../saturation.js';+import {scale} from '../scale.js';import {shadowsHighlights} from '../shadows-highlights.js';+import {tile} from '../tile.js';import {vibrance} from '../vibrance.js';import {vignette} from '../vignette.js';import {whiteBalance} from '../white-balance.js';@@ -490,6 +492,97 @@ test('vignette() color mode works on transparent sources', async () => {}});+test('tile() mirrors neighboring copies on both axes without seams', async () => {+ const source = document.createElement('canvas');+ source.width = 6;+ source.height = 6;+ const sourceContext = source.getContext('2d');+ if (!sourceContext) {+ throw new Error('Could not get source context');+ }++ sourceContext.putImageData(+ new ImageData(+ new Uint8ClampedArray([+ 255, 0, 0, 128, 0, 255, 0, 128, 0, 0, 255, 128, 255, 255, 0, 128,+ ]),+ 2,+ 2,+ ),+ 2,+ 2,+ );++ const canvas = await renderEffectChainToCanvas({+ source,+ width: 6,+ height: 6,+ effects: descriptorsToMemoizedEffects([tile()]),+ });+ const context = canvas.getContext('2d');+ if (!context) {+ throw new Error('Could not get output context');+ }++ const pixels = context.getImageData(0, 0, 6, 6).data;+ const colors = [];+ const alphas = [];+ for (let i = 0; i < pixels.length; i += 4) {+ colors.push(`${pixels[i]}-${pixels[i + 1]}-${pixels[i + 2]}`);+ alphas.push(pixels[i + 3]);+ }++ const red = '255-0-0';+ const green = '0-255-0';+ const blue = '0-0-255';+ const yellow = '255-255-0';+ expect(colors).toEqual(+ [+ [yellow, blue, blue, yellow, yellow, blue],+ [green, red, red, green, green, red],+ [green, red, red, green, green, red],+ [yellow, blue, blue, yellow, yellow, blue],+ [yellow, blue, blue, yellow, yellow, blue],+ [green, red, red, green, green, red],+ ].flat(),+ );+ expect(alphas).toEqual(new Array(36).fill(128));+});++test('tile() does not leave transparent seams after scale()', async () => {+ const width = 20;+ const height = 20;+ const source = document.createElement('canvas');+ source.width = width;+ source.height = height;+ const sourceContext = source.getContext('2d');+ if (!sourceContext) {+ throw new Error('Could not get source context');+ }++ sourceContext.fillStyle = 'red';+ sourceContext.fillRect(0, 0, width, height);++ const canvas = await renderEffectChainToCanvas({+ source,+ width,+ height,+ effects: descriptorsToMemoizedEffects([scale({scale: 0.36}), tile()]),+ });+ const context = canvas.getContext('2d');+ if (!context) {+ throw new Error('Could not get output context');+ }++ const pixels = context.getImageData(0, 0, width, height).data;+ const alphas = [];+ for (let i = 3; i < pixels.length; i += 4) {+ alphas.push(pixels[i]);+ }++ expect(alphas).toEqual(new Array(width * height).fill(255));+});+const maxAlphaForPixelDissolveProgress = async (progress: number) => {const canvas = await renderEffectChainToCanvas({width: 32,diff --git a/packages/studio-shared/src/effect-catalog.ts b/packages/studio-shared/src/effect-catalog.tsindex d719470617..db694c2a42 100644--- a/packages/studio-shared/src/effect-catalog.ts+++ b/packages/studio-shared/src/effect-catalog.ts@@ -402,6 +402,17 @@ export const EFFECT_CATALOG: readonly EffectCatalogItem[] = [},},},+ {+ id: 'effects-tile',+ category: 'Transform',+ label: 'tile()',+ description: 'Repeat the visible source bounds',+ effect: {+ name: 'tile',+ importPath: '@remotion/effects/tile',+ config: {},+ },+ },{id: 'effects-uv-translate',category: 'Transform',