@remotion/motion-blur 4.0.544 → 4.0.545

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,411 @@
1
+ // src/motion-blur-compositor.ts
2
+ import { Internals } from "remotion";
3
+ var webGpuShader = `
4
+ @group(0) @binding(0) var source: texture_2d<f32>;
5
+ @group(0) @binding(1) var<uniform> weight: f32;
6
+
7
+ @vertex fn vertex(@builtin(vertex_index) index: u32) -> @builtin(position) vec4f {
8
+ let positions = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
9
+ return vec4f(positions[index], 0, 1);
10
+ }
11
+
12
+ @fragment fn accumulate(@builtin(position) position: vec4f) -> @location(0) vec4f {
13
+ return textureLoad(source, vec2i(position.xy), 0) * weight;
14
+ }
15
+
16
+ @fragment fn resolve(@builtin(position) position: vec4f) -> @location(0) vec4f {
17
+ return textureLoad(source, vec2i(position.xy), 0);
18
+ }
19
+ `;
20
+ var webGlVertexShader = `#version 300 es
21
+ void main() {
22
+ vec2 positions[3] = vec2[3](vec2(-1, -1), vec2(3, -1), vec2(-1, 3));
23
+ gl_Position = vec4(positions[gl_VertexID], 0, 1);
24
+ }
25
+ `;
26
+ var webGlFragmentShader = `#version 300 es
27
+ precision highp float;
28
+ uniform sampler2D source;
29
+ uniform float weight;
30
+ out vec4 color;
31
+ void main() {
32
+ color = texelFetch(source, ivec2(gl_FragCoord.xy), 0) * weight;
33
+ }
34
+ `;
35
+ var sharedWebGl = null;
36
+ var deviceLossListeners = new WeakMap;
37
+ var lostDevices = new WeakSet;
38
+ var webGpuPipelines = new WeakMap;
39
+ var getMotionBlurGpuDevice = async () => {
40
+ const device = await Internals.getGpuDevice();
41
+ if (!device || lostDevices.has(device))
42
+ return null;
43
+ if (!deviceLossListeners.has(device)) {
44
+ const listeners = new Set;
45
+ deviceLossListeners.set(device, listeners);
46
+ device.lost.then(() => {
47
+ lostDevices.add(device);
48
+ for (const callback of listeners)
49
+ callback();
50
+ listeners.clear();
51
+ });
52
+ }
53
+ return device;
54
+ };
55
+ var createWebGlCompositor = (width, height, requestPaint) => {
56
+ if (sharedWebGl === null || sharedWebGl.gl.isContextLost()) {
57
+ const canvas = document.createElement("canvas");
58
+ const gl = canvas.getContext("webgl2", {
59
+ alpha: true,
60
+ premultipliedAlpha: true,
61
+ preserveDrawingBuffer: true,
62
+ antialias: false,
63
+ depth: false,
64
+ stencil: false
65
+ });
66
+ if (!gl) {
67
+ throw Internals.createWebGL2ContextError("motion blur accumulation");
68
+ }
69
+ try {
70
+ if (!gl.getExtension("EXT_color_buffer_float")) {
71
+ throw new Error("Motion blur requires WebGL floating-point render targets");
72
+ }
73
+ const program = gl.createProgram();
74
+ if (!program) {
75
+ throw new Error("Failed to create the motion blur WebGL program");
76
+ }
77
+ for (const [type, code] of [
78
+ [gl.VERTEX_SHADER, webGlVertexShader],
79
+ [gl.FRAGMENT_SHADER, webGlFragmentShader]
80
+ ]) {
81
+ const shader = gl.createShader(type);
82
+ if (!shader) {
83
+ throw new Error("Failed to create a motion blur WebGL shader");
84
+ }
85
+ gl.shaderSource(shader, code);
86
+ gl.compileShader(shader);
87
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
88
+ const message = gl.getShaderInfoLog(shader);
89
+ gl.deleteShader(shader);
90
+ throw new Error(`Failed to compile motion blur shader: ${message}`);
91
+ }
92
+ gl.attachShader(program, shader);
93
+ gl.deleteShader(shader);
94
+ }
95
+ gl.linkProgram(program);
96
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
97
+ throw new Error(`Failed to link motion blur shaders: ${gl.getProgramInfoLog(program)}`);
98
+ }
99
+ const sourceTexture = gl.createTexture();
100
+ const accumulationTexture = gl.createTexture();
101
+ const framebuffer = gl.createFramebuffer();
102
+ const weight = gl.getUniformLocation(program, "weight");
103
+ if (!sourceTexture || !accumulationTexture || !framebuffer || !weight) {
104
+ throw new Error("Failed to allocate motion blur WebGL resources");
105
+ }
106
+ for (const texture of [sourceTexture, accumulationTexture]) {
107
+ gl.bindTexture(gl.TEXTURE_2D, texture);
108
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
109
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
110
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
111
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
112
+ }
113
+ gl.useProgram(program);
114
+ gl.uniform1i(gl.getUniformLocation(program, "source"), 0);
115
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
116
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
117
+ gl.disable(gl.DITHER);
118
+ sharedWebGl = {
119
+ canvas,
120
+ gl,
121
+ program,
122
+ sourceTexture,
123
+ accumulationTexture,
124
+ framebuffer,
125
+ weight,
126
+ requestPaint: new Set,
127
+ users: 0,
128
+ width: 0,
129
+ height: 0
130
+ };
131
+ const createdState = sharedWebGl;
132
+ canvas.addEventListener("webglcontextlost", (event) => {
133
+ event.preventDefault();
134
+ for (const repaint of createdState.requestPaint)
135
+ repaint();
136
+ });
137
+ } catch (error) {
138
+ setTimeout(() => gl.getExtension("WEBGL_lose_context")?.loseContext(), 0);
139
+ throw error;
140
+ }
141
+ }
142
+ const state = sharedWebGl;
143
+ state.users++;
144
+ state.requestPaint.add(requestPaint);
145
+ let disposed = false;
146
+ return {
147
+ backend: "webgl2",
148
+ isLost: () => state.gl.isContextLost(),
149
+ addSample: (source, index, weight) => {
150
+ const { gl, canvas, sourceTexture, accumulationTexture, framebuffer } = state;
151
+ if (index === 0) {
152
+ if (state.width !== width || state.height !== height) {
153
+ canvas.width = width;
154
+ canvas.height = height;
155
+ gl.bindTexture(gl.TEXTURE_2D, sourceTexture);
156
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
157
+ gl.bindTexture(gl.TEXTURE_2D, accumulationTexture);
158
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, width, height, 0, gl.RGBA, gl.HALF_FLOAT, null);
159
+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
160
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, accumulationTexture, 0);
161
+ if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {
162
+ throw new Error("Motion blur WebGL framebuffer is incomplete");
163
+ }
164
+ state.width = width;
165
+ state.height = height;
166
+ }
167
+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
168
+ gl.viewport(0, 0, width, height);
169
+ gl.clearColor(0, 0, 0, 0);
170
+ gl.clear(gl.COLOR_BUFFER_BIT);
171
+ gl.enable(gl.BLEND);
172
+ gl.blendFunc(gl.ONE, gl.ONE);
173
+ gl.uniform1f(state.weight, weight);
174
+ }
175
+ gl.bindTexture(gl.TEXTURE_2D, sourceTexture);
176
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, source);
177
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
178
+ },
179
+ finish: () => {
180
+ const { gl } = state;
181
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
182
+ gl.disable(gl.BLEND);
183
+ gl.uniform1f(state.weight, 1);
184
+ gl.bindTexture(gl.TEXTURE_2D, state.accumulationTexture);
185
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
186
+ return state.canvas;
187
+ },
188
+ dispose: () => {
189
+ if (disposed)
190
+ return;
191
+ disposed = true;
192
+ state.requestPaint.delete(requestPaint);
193
+ state.users--;
194
+ if (state.users !== 0)
195
+ return;
196
+ const { gl, canvas } = state;
197
+ if (sharedWebGl === state)
198
+ sharedWebGl = null;
199
+ canvas.width = 0;
200
+ canvas.height = 0;
201
+ setTimeout(() => gl.getExtension("WEBGL_lose_context")?.loseContext(), 0);
202
+ }
203
+ };
204
+ };
205
+ var createMotionBlurCompositor = ({
206
+ width,
207
+ height,
208
+ device,
209
+ requestPaint
210
+ }) => {
211
+ if (!device || lostDevices.has(device) || width > device.limits.maxTextureDimension2D || height > device.limits.maxTextureDimension2D) {
212
+ return createWebGlCompositor(width, height, requestPaint);
213
+ }
214
+ const canvas = document.createElement("canvas");
215
+ canvas.width = width;
216
+ canvas.height = height;
217
+ const context = canvas.getContext("webgpu");
218
+ if (!context)
219
+ return createWebGlCompositor(width, height, requestPaint);
220
+ const sourceTexture = device.createTexture({
221
+ size: [width, height],
222
+ format: "rgba8unorm",
223
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT
224
+ });
225
+ const accumulationTexture = device.createTexture({
226
+ size: [width, height],
227
+ format: "rgba16float",
228
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.RENDER_ATTACHMENT
229
+ });
230
+ const weight = device.createBuffer({
231
+ size: 16,
232
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
233
+ });
234
+ const format = navigator.gpu.getPreferredCanvasFormat();
235
+ context.configure({
236
+ device,
237
+ format,
238
+ alphaMode: "premultiplied"
239
+ });
240
+ let pipelines = webGpuPipelines.get(device);
241
+ if (!pipelines) {
242
+ const module = device.createShaderModule({ code: webGpuShader });
243
+ const accumulation = device.createRenderPipeline({
244
+ layout: "auto",
245
+ vertex: { module, entryPoint: "vertex" },
246
+ fragment: {
247
+ module,
248
+ entryPoint: "accumulate",
249
+ targets: [
250
+ {
251
+ format: "rgba16float",
252
+ blend: {
253
+ color: { srcFactor: "one", dstFactor: "one", operation: "add" },
254
+ alpha: { srcFactor: "one", dstFactor: "one", operation: "add" }
255
+ }
256
+ }
257
+ ]
258
+ }
259
+ });
260
+ const output = device.createRenderPipeline({
261
+ layout: "auto",
262
+ vertex: { module, entryPoint: "vertex" },
263
+ fragment: { module, entryPoint: "resolve", targets: [{ format }] }
264
+ });
265
+ pipelines = { accumulation, output };
266
+ webGpuPipelines.set(device, pipelines);
267
+ }
268
+ const { accumulation: accumulationPipeline, output: outputPipeline } = pipelines;
269
+ const sourceGroup = device.createBindGroup({
270
+ layout: accumulationPipeline.getBindGroupLayout(0),
271
+ entries: [
272
+ { binding: 0, resource: sourceTexture.createView() },
273
+ { binding: 1, resource: { buffer: weight } }
274
+ ]
275
+ });
276
+ const outputGroup = device.createBindGroup({
277
+ layout: outputPipeline.getBindGroupLayout(0),
278
+ entries: [{ binding: 0, resource: accumulationTexture.createView() }]
279
+ });
280
+ let lost = false;
281
+ let disposed = false;
282
+ const listeners = deviceLossListeners.get(device);
283
+ const onDeviceLost = () => {
284
+ lost = true;
285
+ requestPaint();
286
+ };
287
+ listeners.add(onDeviceLost);
288
+ return {
289
+ backend: "webgpu",
290
+ isLost: () => lost,
291
+ addSample: (source, index, sampleWeight) => {
292
+ if (index === 0) {
293
+ device.queue.writeBuffer(weight, 0, new Float32Array([sampleWeight]));
294
+ }
295
+ device.queue.copyExternalImageToTexture({ source }, { texture: sourceTexture, premultipliedAlpha: true }, [width, height]);
296
+ const encoder = device.createCommandEncoder();
297
+ const pass = encoder.beginRenderPass({
298
+ colorAttachments: [
299
+ {
300
+ view: accumulationTexture.createView(),
301
+ clearValue: { r: 0, g: 0, b: 0, a: 0 },
302
+ loadOp: index === 0 ? "clear" : "load",
303
+ storeOp: "store"
304
+ }
305
+ ]
306
+ });
307
+ pass.setPipeline(accumulationPipeline);
308
+ pass.setBindGroup(0, sourceGroup);
309
+ pass.draw(3);
310
+ pass.end();
311
+ device.queue.submit([encoder.finish()]);
312
+ },
313
+ finish: () => {
314
+ const encoder = device.createCommandEncoder();
315
+ const pass = encoder.beginRenderPass({
316
+ colorAttachments: [
317
+ {
318
+ view: context.getCurrentTexture().createView(),
319
+ clearValue: { r: 0, g: 0, b: 0, a: 0 },
320
+ loadOp: "clear",
321
+ storeOp: "store"
322
+ }
323
+ ]
324
+ });
325
+ pass.setPipeline(outputPipeline);
326
+ pass.setBindGroup(0, outputGroup);
327
+ pass.draw(3);
328
+ pass.end();
329
+ device.queue.submit([encoder.finish()]);
330
+ return canvas;
331
+ },
332
+ dispose: () => {
333
+ if (disposed)
334
+ return;
335
+ disposed = true;
336
+ listeners.delete(onDeviceLost);
337
+ sourceTexture.destroy();
338
+ accumulationTexture.destroy();
339
+ weight.destroy();
340
+ context.unconfigure();
341
+ canvas.width = 0;
342
+ canvas.height = 0;
343
+ }
344
+ };
345
+ };
346
+
1
347
  // src/CameraMotionBlur.tsx
2
348
  import { AbsoluteFill, Freeze, useCurrentFrame } from "remotion";
349
+
350
+ // src/motion-blur-context.tsx
351
+ import { useContext, useLayoutEffect, useMemo, useState } from "react";
352
+ import { Internals as Internals2 } from "remotion";
3
353
  import { jsx } from "react/jsx-runtime";
354
+ var useMotionBlurRegistry = (componentName) => {
355
+ const parent = useContext(Internals2.MotionBlurContext);
356
+ const [registry] = useState(() => ({
357
+ canvases: new Map,
358
+ nestedScopes: new Map
359
+ }));
360
+ const [nested, setNested] = useState(null);
361
+ useLayoutEffect(() => {
362
+ if (parent === null)
363
+ return;
364
+ const scopes = parent.registry.nestedScopes.get(componentName) ?? [];
365
+ parent.registry.nestedScopes.set(componentName, scopes);
366
+ let scope = scopes.find((candidate) => !candidate.registrations.has(parent.sampleIndex));
367
+ if (!scope) {
368
+ scope = {
369
+ registrations: new Set,
370
+ registry: { canvases: new Map, nestedScopes: new Map }
371
+ };
372
+ scopes.push(scope);
373
+ }
374
+ scope.registrations.add(parent.sampleIndex);
375
+ setNested({ parent, registry: scope.registry });
376
+ const current = scope;
377
+ return () => {
378
+ current.registrations.delete(parent.sampleIndex);
379
+ if (current.registrations.size === 0) {
380
+ scopes.splice(scopes.indexOf(current), 1);
381
+ if (scopes.length === 0) {
382
+ parent.registry.nestedScopes.delete(componentName);
383
+ }
384
+ }
385
+ };
386
+ }, [componentName, parent]);
387
+ return parent === null ? registry : nested?.parent === parent ? nested.registry : null;
388
+ };
389
+ var MotionBlurSampleProvider = ({ children, sampleIndex, registry }) => {
390
+ const parent = useContext(Internals2.MotionBlurContext);
391
+ const parentIndex = parent?.sampleIndex ?? "";
392
+ const parentIsPrimary = parent?.isPrimarySample ?? true;
393
+ const value = useMemo(() => ({
394
+ sampleIndex: `${parentIndex}/${sampleIndex}`,
395
+ isPrimarySample: parentIsPrimary && sampleIndex === 0,
396
+ registry
397
+ }), [parentIndex, parentIsPrimary, sampleIndex, registry]);
398
+ return /* @__PURE__ */ jsx(Internals2.DisableSequenceRegistrationProvider, {
399
+ disabled: !value.isPrimarySample,
400
+ children: /* @__PURE__ */ jsx(Internals2.MotionBlurContext.Provider, {
401
+ value,
402
+ children
403
+ })
404
+ });
405
+ };
406
+
407
+ // src/CameraMotionBlur.tsx
408
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
4
409
  var getNumberOfSamples = ({
5
410
  shutterFraction,
6
411
  samples,
@@ -20,6 +425,7 @@ var CameraMotionBlur = ({
20
425
  samples = 10
21
426
  }) => {
22
427
  const currentFrame = useCurrentFrame();
428
+ const registry = useMotionBlurRegistry("CameraMotionBlur");
23
429
  if (typeof samples !== "number" || Number.isNaN(samples) || !Number.isFinite(samples)) {
24
430
  throw new TypeError(`"samples" must be a number, but got ${JSON.stringify(samples)}`);
25
431
  }
@@ -41,35 +447,51 @@ var CameraMotionBlur = ({
41
447
  samples,
42
448
  shutterFraction
43
449
  });
44
- return /* @__PURE__ */ jsx(AbsoluteFill, {
450
+ if (registry === null)
451
+ return null;
452
+ return /* @__PURE__ */ jsxs(AbsoluteFill, {
45
453
  style: { isolation: "isolate" },
46
- children: new Array(actualSamples).fill(true).map((_, i) => {
47
- const sample = i + 1;
48
- const sampleFrameOffset = shutterFraction * (sample / actualSamples);
49
- return /* @__PURE__ */ jsx(AbsoluteFill, {
50
- style: {
51
- mixBlendMode: "plus-lighter",
52
- filter: `opacity(${1 / actualSamples})`
53
- },
54
- children: /* @__PURE__ */ jsx(Freeze, {
55
- frame: currentFrame - sampleFrameOffset + 1,
454
+ children: [
455
+ /* @__PURE__ */ jsx2(AbsoluteFill, {
456
+ style: { opacity: actualSamples > 1 ? 0 : 1 },
457
+ children: /* @__PURE__ */ jsx2(MotionBlurSampleProvider, {
458
+ sampleIndex: 0,
459
+ registry,
56
460
  children
57
461
  })
58
- }, `frame-${i.toString()}`);
59
- })
462
+ }),
463
+ new Array(actualSamples > 1 ? actualSamples : 0).fill(true).map((_, i) => {
464
+ const sampleFrameOffset = shutterFraction * ((i + 1) / actualSamples);
465
+ return /* @__PURE__ */ jsx2(AbsoluteFill, {
466
+ style: {
467
+ mixBlendMode: "plus-lighter",
468
+ filter: `opacity(${1 / actualSamples})`
469
+ },
470
+ children: /* @__PURE__ */ jsx2(Freeze, {
471
+ frame: currentFrame - sampleFrameOffset + 1,
472
+ children: /* @__PURE__ */ jsx2(MotionBlurSampleProvider, {
473
+ sampleIndex: i + 1,
474
+ registry,
475
+ children
476
+ })
477
+ })
478
+ }, `frame-${i.toString()}`);
479
+ })
480
+ ]
60
481
  });
61
482
  };
62
483
  // src/HtmlInCanvasMotionBlur.tsx
63
- import { useCallback, useRef } from "react";
484
+ import { useCallback, useContext as useContext2, useRef } from "react";
64
485
  import {
65
486
  Freeze as Freeze2,
66
487
  HtmlInCanvas,
67
488
  Interactive,
68
- Internals,
489
+ Internals as Internals3,
69
490
  useCurrentFrame as useCurrentFrame2,
491
+ useRemotionEnvironment,
70
492
  useVideoConfig
71
493
  } from "remotion";
72
- import { jsx as jsx2 } from "react/jsx-runtime";
494
+ import { jsx as jsx3 } from "react/jsx-runtime";
73
495
  var htmlInCanvasMotionBlurSchema = {
74
496
  ...Interactive.baseSchema,
75
497
  shutterAngle: {
@@ -96,6 +518,12 @@ var htmlInCanvasMotionBlurSchema = {
96
518
  type: "boolean",
97
519
  default: false,
98
520
  description: "Disabled"
521
+ },
522
+ disabledInPreview: {
523
+ type: "boolean",
524
+ default: false,
525
+ description: "Disabled in preview",
526
+ keyframable: false
99
527
  }
100
528
  };
101
529
  var MotionBlurSample = ({
@@ -106,12 +534,13 @@ var MotionBlurSample = ({
106
534
  count,
107
535
  shutterInFrames,
108
536
  firstFrame,
109
- lastFrame
537
+ lastFrame,
538
+ registry
110
539
  }) => {
111
540
  const frame = useCurrentFrame2();
112
- const sampleFrame = Math.max(firstFrame, Math.min(lastFrame, frame + ((index + 0.5) / count - 0.5) * shutterInFrames));
113
- const isRepresentativeSample = index === Math.floor(count / 2);
114
- return /* @__PURE__ */ jsx2("div", {
541
+ const isRepresentativeSample = index === 0;
542
+ const sampleFrame = isRepresentativeSample ? frame : Math.max(firstFrame, Math.min(lastFrame, frame + ((index - 0.5) / count - 0.5) * shutterInFrames));
543
+ return /* @__PURE__ */ jsx3("div", {
115
544
  "aria-hidden": !isRepresentativeSample,
116
545
  ...index === 0 ? {} : { drawable: "" },
117
546
  style: {
@@ -123,10 +552,12 @@ var MotionBlurSample = ({
123
552
  visibility: "visible",
124
553
  pointerEvents: isRepresentativeSample ? "auto" : "none"
125
554
  },
126
- children: /* @__PURE__ */ jsx2(Internals.DisableSequenceRegistrationProvider, {
127
- disabled: !isRepresentativeSample,
128
- children: /* @__PURE__ */ jsx2(Freeze2, {
129
- frame: sampleFrame,
555
+ children: /* @__PURE__ */ jsx3(Freeze2, {
556
+ frame: sampleFrame,
557
+ active: !isRepresentativeSample,
558
+ children: /* @__PURE__ */ jsx3(MotionBlurSampleProvider, {
559
+ sampleIndex: index,
560
+ registry,
130
561
  children
131
562
  })
132
563
  })
@@ -139,6 +570,7 @@ var HtmlInCanvasMotionBlurInner = ({
139
570
  shutterAngle = 180,
140
571
  samples = 8,
141
572
  disabled = false,
573
+ disabledInPreview = false,
142
574
  from,
143
575
  durationInFrames,
144
576
  trimBefore,
@@ -155,23 +587,36 @@ var HtmlInCanvasMotionBlurInner = ({
155
587
  controls
156
588
  }) => {
157
589
  const { durationInFrames: compositionDurationInFrames } = useVideoConfig();
158
- const videoEnabled = Internals.useVideoEnabled();
159
- const accumulationCanvasRef = useRef(null);
590
+ const { isRendering } = useRemotionEnvironment();
591
+ const videoEnabled = Internals3.useVideoEnabled();
592
+ const preferredBackend = useContext2(Internals3.PreferredEffectBackendContext);
593
+ const registry = useMotionBlurRegistry("HtmlInCanvasMotionBlur");
594
+ const gpuDeviceRef = useRef(null);
595
+ const compositorRef = useRef(null);
160
596
  if (!Number.isInteger(samples) || samples < 1 || samples > 64) {
161
597
  throw new TypeError(`"samples" must be an integer between 1 and 64, but got ${String(samples)}`);
162
598
  }
163
599
  if (typeof shutterAngle !== "number" || !Number.isFinite(shutterAngle) || shutterAngle < 0 || shutterAngle > 360) {
164
600
  throw new TypeError(`"shutterAngle" must be between 0 and 360, but got ${String(shutterAngle)}`);
165
601
  }
166
- const actualSamples = disabled || shutterAngle === 0 || !videoEnabled ? 1 : samples;
602
+ const actualSamples = disabled || disabledInPreview && !isRendering || shutterAngle === 0 || !videoEnabled ? 1 : samples;
603
+ const renderedSampleCount = actualSamples === 1 ? 1 : actualSamples + 1;
167
604
  const shutterInFrames = shutterAngle / 360 * (playbackRate ?? 1);
168
605
  const firstFrame = trimBefore ?? 0;
169
- const visibleDuration = Math.max(0, Math.min(Internals.resolveSequenceDuration({
606
+ const visibleDuration = Math.max(0, Math.min(Internals3.resolveSequenceDuration({
170
607
  durationInFrames,
171
608
  playbackRate,
172
609
  loop
173
610
  }), compositionDurationInFrames - (from ?? 0)));
174
611
  const lastFrame = firstFrame + Math.max(0, visibleDuration - 1) * (playbackRate ?? 1);
612
+ const onInit = useCallback(async () => {
613
+ gpuDeviceRef.current = await getMotionBlurGpuDevice();
614
+ return () => {
615
+ gpuDeviceRef.current = null;
616
+ compositorRef.current?.compositor.dispose();
617
+ compositorRef.current = null;
618
+ };
619
+ }, []);
175
620
  const onPaint = useCallback(({ canvas, element, elementImage }) => {
176
621
  const context = canvas.getContext("2d");
177
622
  if (!context) {
@@ -182,42 +627,60 @@ var HtmlInCanvasMotionBlurInner = ({
182
627
  throw new Error("Failed to find the HTML-in-canvas layout canvas");
183
628
  }
184
629
  const captureElements = Array.from(layoutCanvas.children);
185
- if (captureElements.length !== actualSamples || captureElements[0] !== element) {
630
+ if (captureElements.length !== renderedSampleCount || captureElements[0] !== element) {
186
631
  throw new Error("Motion blur samples are not ready to paint");
187
632
  }
188
- if (accumulationCanvasRef.current === null || accumulationCanvasRef.current.width !== canvas.width || accumulationCanvasRef.current.height !== canvas.height) {
189
- accumulationCanvasRef.current = new OffscreenCanvas(canvas.width, canvas.height);
633
+ if (actualSamples === 1) {
634
+ compositorRef.current?.compositor.dispose();
635
+ compositorRef.current = null;
636
+ context.reset();
637
+ context.drawElementImage(elementImage, 0, 0);
638
+ return;
190
639
  }
191
- const accumulationCanvas = accumulationCanvasRef.current;
192
- const accumulationSettings = {
193
- colorSpace: "srgb",
194
- colorType: "float16"
195
- };
196
- const accumulationContext = accumulationCanvas.getContext("2d", accumulationSettings);
197
- if (!accumulationContext) {
198
- throw new Error("Failed to acquire 2D context for motion blur samples");
640
+ const preferWebGl = (preferredBackend ?? window.remotion_preferredEffectBackend) === "webgl2" || Boolean(window.remotion_disableWebGpuEffects);
641
+ if (compositorRef.current?.compositor.isLost()) {
642
+ if (compositorRef.current.compositor.backend === "webgpu") {
643
+ gpuDeviceRef.current = null;
644
+ }
645
+ compositorRef.current.compositor.dispose();
646
+ compositorRef.current = null;
199
647
  }
200
- accumulationContext.reset();
201
- accumulationContext.globalCompositeOperation = "lighter";
202
- accumulationContext.globalAlpha = 1 / actualSamples;
203
- for (const [index, sampleElement] of captureElements.entries()) {
204
- const image = index === 0 ? elementImage : layoutCanvas.captureElementImage(sampleElement);
648
+ if (compositorRef.current === null || compositorRef.current.width !== canvas.width || compositorRef.current.height !== canvas.height || compositorRef.current.preferWebGl !== preferWebGl) {
649
+ compositorRef.current?.compositor.dispose();
650
+ compositorRef.current = null;
651
+ const createdCompositor = createMotionBlurCompositor({
652
+ width: canvas.width,
653
+ height: canvas.height,
654
+ device: preferWebGl ? null : gpuDeviceRef.current,
655
+ requestPaint: () => layoutCanvas.requestPaint?.()
656
+ });
657
+ compositorRef.current = {
658
+ compositor: createdCompositor,
659
+ width: canvas.width,
660
+ height: canvas.height,
661
+ preferWebGl
662
+ };
663
+ }
664
+ const { compositor } = compositorRef.current;
665
+ const sampleWeight = Math.round(255 / actualSamples) / 255;
666
+ for (const [index, sampleElement] of captureElements.slice(1).entries()) {
667
+ const image = layoutCanvas.captureElementImage(sampleElement);
205
668
  try {
206
669
  context.reset();
207
670
  context.drawElementImage(image, 0, 0);
208
- accumulationContext.drawImage(canvas, 0, 0);
671
+ compositor.addSample(canvas, index, sampleWeight);
209
672
  } finally {
210
- if (index !== 0) {
211
- image.close();
212
- }
673
+ image.close();
213
674
  }
214
675
  }
215
676
  context.reset();
216
- context.drawImage(accumulationCanvas, 0, 0);
217
- }, [actualSamples]);
218
- const passThrough = Internals.useHtmlInCanvasUnsupportedMessage() !== null;
219
- const sampleElements = Array.from({ length: passThrough ? 0 : actualSamples }, (_, index) => {
220
- return /* @__PURE__ */ jsx2(MotionBlurSample, {
677
+ context.drawImage(compositor.finish(), 0, 0);
678
+ }, [actualSamples, preferredBackend, renderedSampleCount]);
679
+ const passThrough = Internals3.useHtmlInCanvasUnsupportedMessage() !== null;
680
+ if (registry === null)
681
+ return null;
682
+ const sampleElements = Array.from({ length: passThrough ? 0 : renderedSampleCount }, (_, index) => {
683
+ return /* @__PURE__ */ jsx3(MotionBlurSample, {
221
684
  width,
222
685
  height,
223
686
  index,
@@ -225,10 +688,11 @@ var HtmlInCanvasMotionBlurInner = ({
225
688
  shutterInFrames,
226
689
  firstFrame,
227
690
  lastFrame,
691
+ registry,
228
692
  children
229
693
  }, index);
230
694
  });
231
- return /* @__PURE__ */ jsx2(HtmlInCanvas, {
695
+ return /* @__PURE__ */ jsx3(HtmlInCanvas, {
232
696
  width,
233
697
  height,
234
698
  from,
@@ -246,6 +710,7 @@ var HtmlInCanvasMotionBlurInner = ({
246
710
  styleWhilePostmounted,
247
711
  ...{ controls },
248
712
  onPaint,
713
+ onInit,
249
714
  _remotionInternalCanvasSiblings: sampleElements.slice(1),
250
715
  _remotionInternalFallbackLabel: "Motion blur is not visible",
251
716
  children: passThrough ? children : sampleElements[0]
@@ -261,7 +726,7 @@ var HtmlInCanvasMotionBlur = Interactive.withSchema({
261
726
  HtmlInCanvasMotionBlur.displayName = "HtmlInCanvasMotionBlur";
262
727
  // src/Trail.tsx
263
728
  import { AbsoluteFill as AbsoluteFill2, Freeze as Freeze3, useCurrentFrame as useCurrentFrame3 } from "remotion";
264
- import { jsx as jsx3, jsxs } from "react/jsx-runtime";
729
+ import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
265
730
  var Trail = ({
266
731
  children,
267
732
  layers,
@@ -269,6 +734,7 @@ var Trail = ({
269
734
  trailOpacity
270
735
  }) => {
271
736
  const frame = useCurrentFrame3();
737
+ const registry = useMotionBlurRegistry("Trail");
272
738
  if (typeof layers !== "number" || Number.isNaN(layers) || !Number.isFinite(layers)) {
273
739
  throw new TypeError(`"layers" must be a number, but got ${JSON.stringify(layers)}`);
274
740
  }
@@ -284,25 +750,42 @@ var Trail = ({
284
750
  if (typeof lagInFrames !== "number" || Number.isNaN(lagInFrames) || !Number.isFinite(lagInFrames)) {
285
751
  throw new TypeError(`"lagInFrames" must be a number, but got ${JSON.stringify(lagInFrames)}`);
286
752
  }
287
- return /* @__PURE__ */ jsxs(AbsoluteFill2, {
753
+ if (registry === null)
754
+ return null;
755
+ return /* @__PURE__ */ jsxs2(AbsoluteFill2, {
288
756
  children: [
289
757
  new Array(layers).fill(true).map((_, i) => {
290
- return /* @__PURE__ */ jsx3(AbsoluteFill2, {
758
+ return /* @__PURE__ */ jsx4(AbsoluteFill2, {
291
759
  style: {
292
760
  opacity: trailOpacity - (layers - i) / layers * trailOpacity
293
761
  },
294
- children: /* @__PURE__ */ jsx3(Freeze3, {
762
+ children: /* @__PURE__ */ jsx4(Freeze3, {
295
763
  frame: frame - lagInFrames * (layers - i),
296
- children
764
+ children: /* @__PURE__ */ jsx4(MotionBlurSampleProvider, {
765
+ sampleIndex: i + 1,
766
+ registry,
767
+ children
768
+ })
297
769
  })
298
770
  }, `frame-${i.toString()}`);
299
771
  }),
300
- children
772
+ /* @__PURE__ */ jsx4(MotionBlurSampleProvider, {
773
+ sampleIndex: 0,
774
+ registry,
775
+ children
776
+ })
301
777
  ]
302
778
  });
303
779
  };
780
+
781
+ // src/index.ts
782
+ var MotionBlurInternals = {
783
+ createMotionBlurCompositor,
784
+ getMotionBlurGpuDevice
785
+ };
304
786
  export {
305
787
  CameraMotionBlur,
306
788
  HtmlInCanvasMotionBlur,
789
+ MotionBlurInternals,
307
790
  Trail
308
791
  };