@remotion/motion-blur 4.0.544 → 4.0.546

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,37 +447,54 @@ 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,
497
+ ...Interactive.transformSchema,
75
498
  shutterAngle: {
76
499
  type: "number",
77
500
  min: 0,
@@ -96,6 +519,12 @@ var htmlInCanvasMotionBlurSchema = {
96
519
  type: "boolean",
97
520
  default: false,
98
521
  description: "Disabled"
522
+ },
523
+ disabledInPreview: {
524
+ type: "boolean",
525
+ default: false,
526
+ description: "Disabled in preview",
527
+ keyframable: false
99
528
  }
100
529
  };
101
530
  var MotionBlurSample = ({
@@ -106,12 +535,13 @@ var MotionBlurSample = ({
106
535
  count,
107
536
  shutterInFrames,
108
537
  firstFrame,
109
- lastFrame
538
+ lastFrame,
539
+ registry
110
540
  }) => {
111
541
  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", {
542
+ const isRepresentativeSample = index === 0;
543
+ const sampleFrame = isRepresentativeSample ? frame : Math.max(firstFrame, Math.min(lastFrame, frame + ((index - 0.5) / count - 0.5) * shutterInFrames));
544
+ return /* @__PURE__ */ jsx3("div", {
115
545
  "aria-hidden": !isRepresentativeSample,
116
546
  ...index === 0 ? {} : { drawable: "" },
117
547
  style: {
@@ -123,10 +553,12 @@ var MotionBlurSample = ({
123
553
  visibility: "visible",
124
554
  pointerEvents: isRepresentativeSample ? "auto" : "none"
125
555
  },
126
- children: /* @__PURE__ */ jsx2(Internals.DisableSequenceRegistrationProvider, {
127
- disabled: !isRepresentativeSample,
128
- children: /* @__PURE__ */ jsx2(Freeze2, {
129
- frame: sampleFrame,
556
+ children: /* @__PURE__ */ jsx3(Freeze2, {
557
+ frame: sampleFrame,
558
+ active: !isRepresentativeSample,
559
+ children: /* @__PURE__ */ jsx3(MotionBlurSampleProvider, {
560
+ sampleIndex: index,
561
+ registry,
130
562
  children
131
563
  })
132
564
  })
@@ -139,6 +571,7 @@ var HtmlInCanvasMotionBlurInner = ({
139
571
  shutterAngle = 180,
140
572
  samples = 8,
141
573
  disabled = false,
574
+ disabledInPreview = false,
142
575
  from,
143
576
  durationInFrames,
144
577
  trimBefore,
@@ -150,28 +583,42 @@ var HtmlInCanvasMotionBlurInner = ({
150
583
  premountFor,
151
584
  postmountFor,
152
585
  showInTimeline,
586
+ style,
153
587
  styleWhilePremounted,
154
588
  styleWhilePostmounted,
155
589
  controls
156
590
  }) => {
157
591
  const { durationInFrames: compositionDurationInFrames } = useVideoConfig();
158
- const videoEnabled = Internals.useVideoEnabled();
159
- const accumulationCanvasRef = useRef(null);
592
+ const { isRendering } = useRemotionEnvironment();
593
+ const videoEnabled = Internals3.useVideoEnabled();
594
+ const preferredBackend = useContext2(Internals3.PreferredEffectBackendContext);
595
+ const registry = useMotionBlurRegistry("HtmlInCanvasMotionBlur");
596
+ const gpuDeviceRef = useRef(null);
597
+ const compositorRef = useRef(null);
160
598
  if (!Number.isInteger(samples) || samples < 1 || samples > 64) {
161
599
  throw new TypeError(`"samples" must be an integer between 1 and 64, but got ${String(samples)}`);
162
600
  }
163
601
  if (typeof shutterAngle !== "number" || !Number.isFinite(shutterAngle) || shutterAngle < 0 || shutterAngle > 360) {
164
602
  throw new TypeError(`"shutterAngle" must be between 0 and 360, but got ${String(shutterAngle)}`);
165
603
  }
166
- const actualSamples = disabled || shutterAngle === 0 || !videoEnabled ? 1 : samples;
604
+ const actualSamples = disabled || disabledInPreview && !isRendering || shutterAngle === 0 || !videoEnabled ? 1 : samples;
605
+ const renderedSampleCount = actualSamples === 1 ? 1 : actualSamples + 1;
167
606
  const shutterInFrames = shutterAngle / 360 * (playbackRate ?? 1);
168
607
  const firstFrame = trimBefore ?? 0;
169
- const visibleDuration = Math.max(0, Math.min(Internals.resolveSequenceDuration({
608
+ const visibleDuration = Math.max(0, Math.min(Internals3.resolveSequenceDuration({
170
609
  durationInFrames,
171
610
  playbackRate,
172
611
  loop
173
612
  }), compositionDurationInFrames - (from ?? 0)));
174
613
  const lastFrame = firstFrame + Math.max(0, visibleDuration - 1) * (playbackRate ?? 1);
614
+ const onInit = useCallback(async () => {
615
+ gpuDeviceRef.current = await getMotionBlurGpuDevice();
616
+ return () => {
617
+ gpuDeviceRef.current = null;
618
+ compositorRef.current?.compositor.dispose();
619
+ compositorRef.current = null;
620
+ };
621
+ }, []);
175
622
  const onPaint = useCallback(({ canvas, element, elementImage }) => {
176
623
  const context = canvas.getContext("2d");
177
624
  if (!context) {
@@ -182,42 +629,60 @@ var HtmlInCanvasMotionBlurInner = ({
182
629
  throw new Error("Failed to find the HTML-in-canvas layout canvas");
183
630
  }
184
631
  const captureElements = Array.from(layoutCanvas.children);
185
- if (captureElements.length !== actualSamples || captureElements[0] !== element) {
632
+ if (captureElements.length !== renderedSampleCount || captureElements[0] !== element) {
186
633
  throw new Error("Motion blur samples are not ready to paint");
187
634
  }
188
- if (accumulationCanvasRef.current === null || accumulationCanvasRef.current.width !== canvas.width || accumulationCanvasRef.current.height !== canvas.height) {
189
- accumulationCanvasRef.current = new OffscreenCanvas(canvas.width, canvas.height);
635
+ if (actualSamples === 1) {
636
+ compositorRef.current?.compositor.dispose();
637
+ compositorRef.current = null;
638
+ context.reset();
639
+ context.drawElementImage(elementImage, 0, 0);
640
+ return;
190
641
  }
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");
642
+ const preferWebGl = (preferredBackend ?? window.remotion_preferredEffectBackend) === "webgl2" || Boolean(window.remotion_disableWebGpuEffects);
643
+ if (compositorRef.current?.compositor.isLost()) {
644
+ if (compositorRef.current.compositor.backend === "webgpu") {
645
+ gpuDeviceRef.current = null;
646
+ }
647
+ compositorRef.current.compositor.dispose();
648
+ compositorRef.current = null;
199
649
  }
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);
650
+ if (compositorRef.current === null || compositorRef.current.width !== canvas.width || compositorRef.current.height !== canvas.height || compositorRef.current.preferWebGl !== preferWebGl) {
651
+ compositorRef.current?.compositor.dispose();
652
+ compositorRef.current = null;
653
+ const createdCompositor = createMotionBlurCompositor({
654
+ width: canvas.width,
655
+ height: canvas.height,
656
+ device: preferWebGl ? null : gpuDeviceRef.current,
657
+ requestPaint: () => layoutCanvas.requestPaint?.()
658
+ });
659
+ compositorRef.current = {
660
+ compositor: createdCompositor,
661
+ width: canvas.width,
662
+ height: canvas.height,
663
+ preferWebGl
664
+ };
665
+ }
666
+ const { compositor } = compositorRef.current;
667
+ const sampleWeight = 1 / actualSamples;
668
+ for (const [index, sampleElement] of captureElements.slice(1).entries()) {
669
+ const image = layoutCanvas.captureElementImage(sampleElement);
205
670
  try {
206
671
  context.reset();
207
672
  context.drawElementImage(image, 0, 0);
208
- accumulationContext.drawImage(canvas, 0, 0);
673
+ compositor.addSample(canvas, index, sampleWeight);
209
674
  } finally {
210
- if (index !== 0) {
211
- image.close();
212
- }
675
+ image.close();
213
676
  }
214
677
  }
215
678
  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, {
679
+ context.drawImage(compositor.finish(), 0, 0);
680
+ }, [actualSamples, preferredBackend, renderedSampleCount]);
681
+ const passThrough = Internals3.useHtmlInCanvasUnsupportedMessage() !== null;
682
+ if (registry === null)
683
+ return null;
684
+ const sampleElements = Array.from({ length: passThrough ? 0 : renderedSampleCount }, (_, index) => {
685
+ return /* @__PURE__ */ jsx3(MotionBlurSample, {
221
686
  width,
222
687
  height,
223
688
  index,
@@ -225,10 +690,11 @@ var HtmlInCanvasMotionBlurInner = ({
225
690
  shutterInFrames,
226
691
  firstFrame,
227
692
  lastFrame,
693
+ registry,
228
694
  children
229
695
  }, index);
230
696
  });
231
- return /* @__PURE__ */ jsx2(HtmlInCanvas, {
697
+ return /* @__PURE__ */ jsx3(HtmlInCanvas, {
232
698
  width,
233
699
  height,
234
700
  from,
@@ -242,10 +708,12 @@ var HtmlInCanvasMotionBlurInner = ({
242
708
  premountFor,
243
709
  postmountFor,
244
710
  showInTimeline,
711
+ style,
245
712
  styleWhilePremounted,
246
713
  styleWhilePostmounted,
247
714
  ...{ controls },
248
715
  onPaint,
716
+ onInit,
249
717
  _remotionInternalCanvasSiblings: sampleElements.slice(1),
250
718
  _remotionInternalFallbackLabel: "Motion blur is not visible",
251
719
  children: passThrough ? children : sampleElements[0]
@@ -261,7 +729,7 @@ var HtmlInCanvasMotionBlur = Interactive.withSchema({
261
729
  HtmlInCanvasMotionBlur.displayName = "HtmlInCanvasMotionBlur";
262
730
  // src/Trail.tsx
263
731
  import { AbsoluteFill as AbsoluteFill2, Freeze as Freeze3, useCurrentFrame as useCurrentFrame3 } from "remotion";
264
- import { jsx as jsx3, jsxs } from "react/jsx-runtime";
732
+ import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
265
733
  var Trail = ({
266
734
  children,
267
735
  layers,
@@ -269,6 +737,7 @@ var Trail = ({
269
737
  trailOpacity
270
738
  }) => {
271
739
  const frame = useCurrentFrame3();
740
+ const registry = useMotionBlurRegistry("Trail");
272
741
  if (typeof layers !== "number" || Number.isNaN(layers) || !Number.isFinite(layers)) {
273
742
  throw new TypeError(`"layers" must be a number, but got ${JSON.stringify(layers)}`);
274
743
  }
@@ -284,25 +753,42 @@ var Trail = ({
284
753
  if (typeof lagInFrames !== "number" || Number.isNaN(lagInFrames) || !Number.isFinite(lagInFrames)) {
285
754
  throw new TypeError(`"lagInFrames" must be a number, but got ${JSON.stringify(lagInFrames)}`);
286
755
  }
287
- return /* @__PURE__ */ jsxs(AbsoluteFill2, {
756
+ if (registry === null)
757
+ return null;
758
+ return /* @__PURE__ */ jsxs2(AbsoluteFill2, {
288
759
  children: [
289
760
  new Array(layers).fill(true).map((_, i) => {
290
- return /* @__PURE__ */ jsx3(AbsoluteFill2, {
761
+ return /* @__PURE__ */ jsx4(AbsoluteFill2, {
291
762
  style: {
292
763
  opacity: trailOpacity - (layers - i) / layers * trailOpacity
293
764
  },
294
- children: /* @__PURE__ */ jsx3(Freeze3, {
765
+ children: /* @__PURE__ */ jsx4(Freeze3, {
295
766
  frame: frame - lagInFrames * (layers - i),
296
- children
767
+ children: /* @__PURE__ */ jsx4(MotionBlurSampleProvider, {
768
+ sampleIndex: i + 1,
769
+ registry,
770
+ children
771
+ })
297
772
  })
298
773
  }, `frame-${i.toString()}`);
299
774
  }),
300
- children
775
+ /* @__PURE__ */ jsx4(MotionBlurSampleProvider, {
776
+ sampleIndex: 0,
777
+ registry,
778
+ children
779
+ })
301
780
  ]
302
781
  });
303
782
  };
783
+
784
+ // src/index.ts
785
+ var MotionBlurInternals = {
786
+ createMotionBlurCompositor,
787
+ getMotionBlurGpuDevice
788
+ };
304
789
  export {
305
790
  CameraMotionBlur,
306
791
  HtmlInCanvasMotionBlur,
792
+ MotionBlurInternals,
307
793
  Trail
308
794
  };