🎥 Make videos programmatically with React
`@remotion/effects`: Smooth pixelDissolve endpoint (#8438)
Jonny Burger239e113bf605
diff --git a/packages/docs/build-docs.ts b/packages/docs/build-docs.tsindex 088b74fedc..975fb76b75 100644--- a/packages/docs/build-docs.ts+++ b/packages/docs/build-docs.ts@@ -3,6 +3,24 @@ import {spawn} from 'child_process';const isVercel = process.env.VERCEL === '1' || process.env.VERCEL === 'true';const lowMemoryBuild =isVercel || process.env.REMOTION_DOCS_LOW_MEMORY_BUILD === '1';+const heartbeatIntervalMs = process.env.REMOTION_DOCS_BUILD_HEARTBEAT_MS+ ? parseInt(process.env.REMOTION_DOCS_BUILD_HEARTBEAT_MS, 10)+ : isVercel+ ? 60_000+ : 0;++const formatDuration = (ms: number) => {+ const seconds = ms / 1000;+ if (seconds < 60) {+ return `${seconds.toFixed(1)}s`;+ }++ const minutes = Math.floor(seconds / 60);+ const remainingSeconds = Math.floor(seconds % 60)+ .toString()+ .padStart(2, '0');+ return `${minutes}m ${remainingSeconds}s`;+};const appendNodeOption = (value: string) => {const current = process.env.NODE_OPTIONS ?? '';@@ -14,34 +32,65 @@ const appendNodeOption = (value: string) => {};const run = (+ label: string,command: string,args: string[],env: Record<string, string | undefined> = {},) =>new Promise<void>((resolve, reject) => {+ const start = performance.now();+ console.log(`[docs build] Starting ${label}...`);const child = spawn(command, args, {env: {...process.env, ...env},shell: false,stdio: 'inherit',});+ const heartbeat =+ heartbeatIntervalMs > 0 && Number.isFinite(heartbeatIntervalMs)+ ? setInterval(() => {+ console.log(+ `[docs build] Still running ${label} after ${formatDuration(+ performance.now() - start,+ )}...`,+ );+ }, heartbeatIntervalMs)+ : null;+ heartbeat?.unref();++ const clearHeartbeat = () => {+ if (heartbeat) {+ clearInterval(heartbeat);+ }+ };child.on('close', (code, signal) => {+ clearHeartbeat();if (code === 0) {+ console.log(+ `[docs build] Finished ${label} in ${formatDuration(+ performance.now() - start,+ )}.`,+ );resolve();} else {reject(new Error(- `${command} ${args.join(' ')} exited with code ${code}, signal ${signal}`,+ `${label} (${command} ${args.join(' ')}) exited with code ${code}, signal ${signal}`,),);}});- child.on('error', reject);+ child.on('error', (err) => {+ clearHeartbeat();+ reject(err);+ });});const docusaurusEnv = {DOCUSAURUS_IGNORE_SSG_WARNINGS: 'true',+ DOCUSAURUS_PERF_LOGGER:+ process.env.DOCUSAURUS_PERF_LOGGER ?? (isVercel ? 'true' : undefined),NODE_OPTIONS: appendNodeOption('--max-old-space-size=4096'),...(lowMemoryBuild? {@@ -63,9 +112,9 @@ const twoslashEnv = lowMemoryBuild}: {};-await run('bun', ['copy-raw-docs.ts']);-await run('bun', ['fetch-prompt-submissions.ts']);-await run('bun', ['prewarm-twoslash.ts'], twoslashEnv);-await run('docusaurus', ['build'], docusaurusEnv);-await run('bun', ['copy-convert.ts']);-await run('bun', ['count-pages.ts']);+await run('copy raw docs', 'bun', ['copy-raw-docs.ts']);+await run('fetch prompt submissions', 'bun', ['fetch-prompt-submissions.ts']);+await run('prewarm twoslash', 'bun', ['prewarm-twoslash.ts'], twoslashEnv);+await run('Docusaurus build', 'bunx', ['docusaurus', 'build'], docusaurusEnv);+await run('copy convert assets', 'bun', ['copy-convert.ts']);+await run('count generated pages', 'bun', ['count-pages.ts']);diff --git a/packages/docs/copy-convert.ts b/packages/docs/copy-convert.tsindex 809b71ef97..f0f82bf279 100644--- a/packages/docs/copy-convert.ts+++ b/packages/docs/copy-convert.ts@@ -4,17 +4,29 @@ import {$} from 'bun';// @ts-ignore outside projectimport * as seo from '../convert/app/seo';-await $`bunx turbo "@remotion/convert#build-spa" "@remotion/brand#bundle" "@remotion/example#bundle-testbed"`;-const dir = path.join(__dirname, '../convert/spa-dist/client');+const brandDir = path.join(__dirname, '../brand/build');+const testbedDir = path.join(__dirname, '../example/build-testbed');+const isVercel = process.env.VERCEL === '1' || process.env.VERCEL === 'true';+const prebuiltAssetsExist = [dir, brandDir, testbedDir].every((assetDir) =>+ fs.existsSync(assetDir),+);++if (isVercel && prebuiltAssetsExist) {+ console.log(+ '[docs build] Reusing prebuilt convert, brand, and testbed assets.',+ );+} else {+ await $`bunx turbo "@remotion/convert#build-spa" "@remotion/brand#bundle" "@remotion/example#bundle-testbed"`;+}fs.cpSync(dir, path.join(__dirname, './build/convert'), {recursive: true});-const brandDir = path.join(__dirname, '../brand/build');fs.cpSync(brandDir, path.join(__dirname, './build/brand'), {recursive: true});-const testbedDir = path.join(__dirname, '../example/build-testbed');-fs.cpSync(testbedDir, path.join(__dirname, './build/testbed'), {recursive: true});+fs.cpSync(testbedDir, path.join(__dirname, './build/testbed'), {+ recursive: true,+});fs.cpSync(path.join(__dirname, './build/convert/convert-service-worker.js'),diff --git a/packages/effects/src/pixel-dissolve.ts b/packages/effects/src/pixel-dissolve.tsindex 4495c0a6e6..0bb8b9bb59 100644--- a/packages/effects/src/pixel-dissolve.ts+++ b/packages/effects/src/pixel-dissolve.ts@@ -167,13 +167,15 @@ float hash21(vec2 p) {return fract((p3.x + p3.y) * p3.z);}-float dissolveMask(float noise, float threshold, float feather) {+float dissolveMask(float noise, float progress, float feather) {float edge = max(feather, 0.0);+ float threshold = 1.0 - clamp(progress, 0.0, 1.0) * (1.0 + edge);+if (edge <= 0.0001) {- return step(noise, threshold);+ return 1.0 - step(threshold, noise);}- return 1.0 - smoothstep(threshold, min(threshold + edge, 1.0), noise);+ return 1.0 - smoothstep(threshold, threshold + edge, noise);}void main() {@@ -182,9 +184,8 @@ void main() {vec2 cell = floor(gridUv * divisions);vec4 color = texture(uSource, vUv);- float threshold = 1.0 - clamp(uProgress, 0.0, 1.0);float noise = hash21(cell + vec2(uSeed, uSeed * 1.618));- float mask = dissolveMask(noise, threshold, uFeather);+ float mask = dissolveMask(noise, uProgress, uFeather);fragColor = vec4(color.rgb * mask, color.a * mask);}diff --git a/packages/effects/src/visual-test/effects-visual.test.ts b/packages/effects/src/visual-test/effects-visual.test.tsindex 93b9de73f3..dc521252b7 100644--- a/packages/effects/src/visual-test/effects-visual.test.ts+++ b/packages/effects/src/visual-test/effects-visual.test.ts@@ -1,10 +1,12 @@-import {test} from 'vitest';+import {expect, test} from 'vitest';import {blur} from '../blur.js';import {evolve} from '../evolve.js';import {noise} from '../noise.js';+import {pixelDissolve} from '../pixel-dissolve.js';import {descriptorsToMemoizedEffects,renderEffectChainToBlob,+ renderEffectChainToCanvas,testImage,} from './visual-utils.js';@@ -35,3 +37,43 @@ test('evolve() reveals with feather', async () => {testId: 'evolve-left-feather',});});++const maxAlphaForPixelDissolveProgress = async (progress: number) => {+ const canvas = await renderEffectChainToCanvas({+ width: 32,+ height: 32,+ effects: descriptorsToMemoizedEffects([+ pixelDissolve({+ progress,+ columns: 1,+ rows: 1,+ seed: 0,+ feather: 0.5,+ }),+ ]),+ });+ const context = canvas.getContext('2d');+ if (!context) {+ throw new Error('Could not get 2D context');+ }++ const {data} = context.getImageData(0, 0, canvas.width, canvas.height);+ let maxAlpha = 0;+ for (let i = 3; i < data.length; i += 4) {+ maxAlpha = Math.max(maxAlpha, data[i]);+ }++ return maxAlpha;+};++test('pixelDissolve() smoothly fades to full transparency with feather', async () => {+ const tailAlpha = await maxAlphaForPixelDissolveProgress(0.95);+ expect(tailAlpha).toBeGreaterThan(5);+ expect(tailAlpha).toBeLessThan(30);++ const nearlyDoneAlpha = await maxAlphaForPixelDissolveProgress(0.99);+ expect(nearlyDoneAlpha).toBeLessThanOrEqual(2);++ const doneAlpha = await maxAlphaForPixelDissolveProgress(1);+ expect(doneAlpha).toBe(0);+});diff --git a/packages/effects/src/visual-test/visual-utils.ts b/packages/effects/src/visual-test/visual-utils.tsindex dbbb8d5e15..d9ac0b0d5a 100644--- a/packages/effects/src/visual-test/visual-utils.ts+++ b/packages/effects/src/visual-test/visual-utils.ts@@ -90,7 +90,7 @@ const makeTestSource = (width: number, height: number): HTMLCanvasElement => {return canvas;};-export const renderEffectChainToBlob = async ({+export const renderEffectChainToCanvas = async ({effects,width = 320,height = 180,@@ -98,7 +98,7 @@ export const renderEffectChainToBlob = async ({effects: EffectDefinitionAndStack<unknown>[];width?: number;height?: number;-}): Promise<Blob> => {+}): Promise<HTMLCanvasElement> => {const source = makeTestSource(width, height);const output = document.createElement('canvas');output.width = width;@@ -122,6 +122,20 @@ export const renderEffectChainToBlob = async ({Internals.cleanupEffectChainState(state);}+ return output;+};++export const renderEffectChainToBlob = async ({+ effects,+ width = 320,+ height = 180,+}: {+ effects: EffectDefinitionAndStack<unknown>[];+ width?: number;+ height?: number;+}): Promise<Blob> => {+ const output = await renderEffectChainToCanvas({effects, width, height});+const blob = await new Promise<Blob>((resolve, reject) => {output.toBlob((result) => {if (result) {