1"use strict"; 2(self["webpackChunk_N_E"] = self["webpackChunk_N_E"] || []).push([[9589],{ 3 4/***/ 24551: 5/***/ ((__webpack_module__, __webpack_exports__, __webpack_require__) => { 6 7/* harmony export */ __webpack_require__.d(__webpack_exports__, { 8/* harmony export */ BO: () => (/* binding */ Composition), 9/* harmony export */ GW: () => (/* binding */ interpolate), 10/* harmony export */ H1: () => (/* binding */ AbsoluteFill), 11/* harmony export */ UC: () => (/* binding */ useCurrentFrame), 12/* harmony export */ Xp: () => (/* binding */ Internals), 13/* harmony export */ oz: () => (/* binding */ spring), 14/* harmony export */ yT: () => (/* binding */ random) 15/* harmony export */ }); 16/* unused harmony exports watchStaticFile, useVideoConfig, useRemotionEnvironment, usePixelDensity, useDelayRender, useCurrentScale, useBufferState, staticFile, registerRoot, prefetch, measureSpring, isHtmlInCanvasSupported, interpolateColors, getStaticFiles, getRemotionEnvironment, getInputProps, delayRender, createEffect, continueRender, cancelRender, assertValidInterpolatePosterizeOption, assertValidInterpolateEasingOption, Video, VERSION, Still, Solid, Series, Sequence, OffthreadVideo, MediaPlaybackError, Loop, Interactive, Img, IFrame, HtmlInCanvas, Html5Video, Html5Audio, HTML_IN_CANVAS_UNSUPPORTED_MESSAGE, Freeze, FolderContext, Folder, Experimental, Easing, Config, CanvasImage, Audio, Artifact, AnimatedImage */ 17/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12115); 18/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(47650); 19/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(95155); 20/* provided dependency */ var process = __webpack_require__(41463); 21var __defProp = Object.defineProperty; 22var __export = (target, all)=>{ 23 for(var name in all)__defProp(target, name, { 24 get: all[name], 25 enumerable: true, 26 configurable: true, 27 set: (newValue)=>all[name] = ()=>newValue 28 }); 29};
30// src/_check-rsc.ts 31 32if (typeof react__WEBPACK_IMPORTED_MODULE_0__.createContext !== "function") { 33 const err = [ 34 'Remotion requires React.createContext, but it is "undefined".', 35 'If you are in a React Server Component, turn it into a client component by adding "use client" at the top of the file.', 36 "", 37 "Before:", 38 ' import {useCurrentFrame} from "remotion";', 39 "", 40 "After:", 41 ' "use client";', 42 ' import {useCurrentFrame} from "remotion";' 43 ]; 44 throw new Error(err.join(` 45`)); 46}
47// src/Clipper.tsx 48var Clipper = ()=>{ 49 throw new Error("<Clipper> has been removed as of Remotion v4.0.228. The native clipping APIs were experimental and subject to removal at any time. We removed them because they were sparingly used and made rendering often slower rather than faster."); 50};
51// src/Composition.tsx 52 53
54// src/CanUseRemotionHooks.tsx 55 56 57var CanUseRemotionHooks = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)(false); 58var CanUseRemotionHooksProvider = ({ children })=>{ 59 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(CanUseRemotionHooks.Provider, { 60 value: true, 61 children 62 }); 63};
64// src/composition-render-error-context.ts 65 66var CompositionRenderErrorContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({ 67 setError: ()=>{}, 68 clearError: ()=>{} 69});
70// src/CompositionErrorBoundary.tsx 71 72var getHot = ()=>{ 73 try { 74 if (false) {} 75 return __webpack_module__.hot ?? null; 76 } catch { 77 return null; 78 } 79}; 80class CompositionErrorBoundary extends react__WEBPACK_IMPORTED_MODULE_0__.Component { 81 static getDerivedStateFromError() { 82 return { 83 hasError: true 84 }; 85 } 86 componentDidCatch(error) { 87 this.props.onError(error); 88 this.subscribeToHmrReset(); 89 } 90 componentDidMount() { 91 if (!this.state.hasError) { 92 this.props.onClear(); 93 } 94 } 95 componentDidUpdate(_prevProps, prevState) { 96 if (prevState.hasError && !this.state.hasError) { 97 this.props.onClear(); 98 } 99 } 100 componentWillUnmount() { 101 this.unsubscribeFromHmrReset(); 102 } 103 subscribeToHmrReset() { 104 if (this.hmrStatusHandler) { 105 return; 106 } 107 const hot = getHot(); 108 if (!hot) { 109 return; 110 } 111 const handler = (status)=>{ 112 if (status !== "idle") { 113 return; 114 } 115 this.unsubscribeFromHmrReset(); 116 this.setState({ 117 hasError: false 118 }); 119 }; 120 this.hmrStatusHandler = handler; 121 hot.addStatusHandler(handler); 122 } 123 unsubscribeFromHmrReset() { 124 const handler = this.hmrStatusHandler; 125 if (!handler) { 126 return; 127 } 128 this.hmrStatusHandler = null; 129 const hot = getHot(); 130 if (!hot) { 131 return; 132 } 133 hot.removeStatusHandler(handler); 134 } 135 render() { 136 if (this.state.hasError) { 137 return null; 138 } 139 return this.props.children; 140 } 141 constructor(...args){ 142 super(...args), this.state = { 143 hasError: false 144 }, this.hmrStatusHandler = null; 145 } 146}
147// src/CompositionManagerContext.tsx 148 149var CompositionManager = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({ 150 compositions: [], 151 folders: [], 152 currentCompositionMetadata: null, 153 canvasContent: null 154}); 155var CompositionSetters = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({ 156 registerComposition: ()=>{ 157 return; 158 }, 159 unregisterComposition: ()=>{ 160 return; 161 }, 162 registerFolder: ()=>{ 163 return; 164 }, 165 unregisterFolder: ()=>{ 166 return; 167 }, 168 setCanvasContent: ()=>{ 169 return; 170 }, 171 onlyRenderComposition: null 172});
173// src/Folder.tsx 174
175// src/nonce.ts 176 177var NonceContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({ 178 getNonce: ()=>0 179}); 180var fastRefreshNonce = 0; 181try { 182 if (true) { 183 if (__webpack_module__.hot) { 184 __webpack_module__.hot.addStatusHandler((status)=>{ 185 if (status === "idle") { 186 fastRefreshNonce++; 187 } 188 }); 189 } 190 } 191} catch {} 192var useNonce = ()=>{ 193 const context = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(NonceContext); 194 const nonce = context.getNonce(); 195 const nonceRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(nonce); 196 nonceRef.current = nonce; 197 const history = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)([ 198 [ 199 fastRefreshNonce, 200 nonce 201 ] 202 ]); 203 const get = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(()=>{ 204 if (fastRefreshNonce !== history.current[history.current.length - 1][0]) { 205 history.current = [ 206 ...history.current, 207 [ 208 fastRefreshNonce, 209 nonceRef.current 210 ] 211 ]; 212 } 213 return history.current; 214 }, [ 215 history 216 ]); 217 return (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 218 return { 219 get 220 }; 221 }, [ 222 get 223 ]); 224};
225// src/truthy.ts 226function truthy(value) { 227 return Boolean(value); 228}
229// src/validation/validate-folder-name.ts 230var getRegex = ()=>/^([a-zA-Z0-9-\u4E00-\u9FFF])+$/g; 231var isFolderNameValid = (name)=>name.match(getRegex()); 232var validateFolderName = (name)=>{ 233 if (name === undefined || name === null) { 234 throw new TypeError("You must pass a name to a <Folder />."); 235 } 236 if (typeof name !== "string") { 237 throw new TypeError(`The "name" you pass into <Folder /> must be a string. Got: ${typeof name}`); 238 } 239 if (!isFolderNameValid(name)) { 240 throw new Error(`Folder name can only contain a-z, A-Z, 0-9 and -. You passed ${name}`); 241 } 242}; 243var invalidFolderNameErrorMessage = `Folder name must match ${String(getRegex())}`;
244// src/Folder.tsx 245 246var FolderContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({ 247 folderName: null, 248 parentName: null 249}); 250var Folder = (props)=>{ 251 const { name, children } = props; 252 const parent = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(FolderContext); 253 const { registerFolder, unregisterFolder } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(CompositionSetters); 254 const nonce = useNonce(); 255 const stack = props.stack ?? null; 256 validateFolderName(name); 257 const parentNameArr = [ 258 parent.parentName, 259 parent.folderName 260 ].filter(truthy); 261 const parentName = parentNameArr.length === 0 ? null : parentNameArr.join("/"); 262 const value = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 263 return { 264 folderName: name, 265 parentName 266 }; 267 }, [ 268 name, 269 parentName 270 ]); 271 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 272 registerFolder(name, parentName, nonce.get(), stack); 273 return ()=>{ 274 unregisterFolder(name, parentName); 275 }; 276 }, [ 277 name, 278 parent.folderName, 279 parentName, 280 registerFolder, 281 unregisterFolder, 282 nonce, 283 stack 284 ]); 285 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(FolderContext.Provider, { 286 value, 287 children 288 }); 289};
vendor: 3,214 bytes, lines 290-380
290// src/get-remotion-environment.ts 291function getNodeEnvString() { 292 return [ 293 "NOD", 294 "E_EN", 295 "V" 296 ].join(""); 297} 298var getEnvString = ()=>{ 299 return [ 300 "e", 301 "nv" 302 ].join(""); 303}; 304var getRemotionEnvironment = ()=>{ 305 const isPlayer = typeof window !== "undefined" && window.remotion_isPlayer; 306 const isRendering = typeof window !== "undefined" && typeof window.process !== "undefined" && typeof window.process.env !== "undefined" && (window.process[getEnvString()][getNodeEnvString()] === "test" || window.process[getEnvString()][getNodeEnvString()] === "production" && typeof window !== "undefined" && typeof window.remotion_puppeteerTimeout !== "undefined"); 307 const isStudio = typeof window !== "undefined" && window.remotion_isStudio; 308 const isReadOnlyStudio = typeof window !== "undefined" && window.remotion_isReadOnlyStudio; 309 return { 310 isStudio, 311 isRendering, 312 isPlayer, 313 isReadOnlyStudio, 314 isClientSideRendering: false 315 }; 316}; 317// src/input-props-serialization.ts 318var DATE_TOKEN = "remotion-date:"; 319var FILE_TOKEN = "remotion-file:"; 320var serializeJSONWithSpecialTypes = ({ data, indent, staticBase })=>{ 321 let customDateUsed = false; 322 let customFileUsed = false; 323 let mapUsed = false; 324 let setUsed = false; 325 try { 326 const serializedString = JSON.stringify(data, function(key, value) { 327 const item = this[key]; 328 if (item instanceof Date) { 329 customDateUsed = true; 330 return `${DATE_TOKEN}${item.toISOString()}`; 331 } 332 if (item instanceof Map) { 333 mapUsed = true; 334 return value; 335 } 336 if (item instanceof Set) { 337 setUsed = true; 338 return value; 339 } 340 if (typeof item === "string" && staticBase !== null && item.startsWith(staticBase)) { 341 customFileUsed = true; 342 return `${FILE_TOKEN}${item.replace(staticBase + "/", "")}`; 343 } 344 return value; 345 }, indent); 346 return { 347 serializedString, 348 customDateUsed, 349 customFileUsed, 350 mapUsed, 351 setUsed 352 }; 353 } catch (err) { 354 throw new Error("Could not serialize the passed input props to JSON: " + err.message); 355 } 356}; 357var deserializeJSONWithSpecialTypes = (data)=>{ 358 return JSON.parse(data, (_, value)=>{ 359 if (typeof value === "string" && value.startsWith(DATE_TOKEN)) { 360 return new Date(value.replace(DATE_TOKEN, "")); 361 } 362 if (typeof value === "string" && value.startsWith(FILE_TOKEN)) { 363 return `${window.remotion_staticBase}/${value.replace(FILE_TOKEN, "")}`; 364 } 365 return value; 366 }); 367}; 368var serializeThenDeserialize = (props)=>{ 369 return deserializeJSONWithSpecialTypes(serializeJSONWithSpecialTypes({ 370 data: props, 371 indent: 2, 372 staticBase: window.remotion_staticBase 373 }).serializedString); 374}; 375var serializeThenDeserializeInStudio = (props)=>{ 376 if (getRemotionEnvironment().isStudio) { 377 return serializeThenDeserialize(props); 378 } 379 return props; 380};
381// src/is-player.tsx 382 383 384var IsPlayerContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)(false); 385var IsPlayerContextProvider = ({ children })=>{ 386 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(IsPlayerContext.Provider, { 387 value: true, 388 children 389 }); 390}; 391var useIsPlayer = ()=>{ 392 return (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(IsPlayerContext); 393};
vendor: 3,624 bytes, lines 394-503
394// src/AbsoluteFill.tsx 395 396 397var hasTailwindClassName = ({ className, classPrefix, type })=>{ 398 if (!className) { 399 return false; 400 } 401 if (type === "exact") { 402 const split = className.split(" "); 403 return classPrefix.some((token)=>{ 404 return split.some((part)=>{ 405 return part.trim() === token || part.trim().endsWith(`:${token}`) || part.trim().endsWith(`!${token}`); 406 }); 407 }); 408 } 409 return classPrefix.some((prefix)=>{ 410 return className.startsWith(prefix) || className.includes(` ${prefix}`) || className.includes(`!${prefix}`) || className.includes(`:${prefix}`); 411 }); 412}; 413var AbsoluteFillRefForwarding = (props, ref)=>{ 414 const { style, ...other } = props; 415 const actualStyle = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 416 return { 417 position: "absolute", 418 top: hasTailwindClassName({ 419 className: other.className, 420 classPrefix: [ 421 "top-", 422 "inset-" 423 ], 424 type: "prefix" 425 }) ? undefined : 0, 426 left: hasTailwindClassName({ 427 className: other.className, 428 classPrefix: [ 429 "left-", 430 "inset-" 431 ], 432 type: "prefix" 433 }) ? undefined : 0, 434 right: hasTailwindClassName({ 435 className: other.className, 436 classPrefix: [ 437 "right-", 438 "inset-" 439 ], 440 type: "prefix" 441 }) ? undefined : 0, 442 bottom: hasTailwindClassName({ 443 className: other.className, 444 classPrefix: [ 445 "bottom-", 446 "inset-" 447 ], 448 type: "prefix" 449 }) ? undefined : 0, 450 width: hasTailwindClassName({ 451 className: other.className, 452 classPrefix: [ 453 "w-" 454 ], 455 type: "prefix" 456 }) ? undefined : "100%", 457 height: hasTailwindClassName({ 458 className: other.className, 459 classPrefix: [ 460 "h-" 461 ], 462 type: "prefix" 463 }) ? undefined : "100%", 464 display: hasTailwindClassName({ 465 className: other.className, 466 classPrefix: [ 467 "block", 468 "inline-block", 469 "inline", 470 "flex", 471 "inline-flex", 472 "flow-root", 473 "grid", 474 "inline-grid", 475 "contents", 476 "list-item", 477 "hidden" 478 ], 479 type: "exact" 480 }) ? undefined : "flex", 481 flexDirection: hasTailwindClassName({ 482 className: other.className, 483 classPrefix: [ 484 "flex-row", 485 "flex-col", 486 "flex-row-reverse", 487 "flex-col-reverse" 488 ], 489 type: "exact" 490 }) ? undefined : "column", 491 ...style 492 }; 493 }, [ 494 other.className, 495 style 496 ]); 497 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)("div", { 498 ref, 499 style: actualStyle, 500 ...other 501 }); 502}; 503var AbsoluteFill = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(AbsoluteFillRefForwarding);
504// src/loading-indicator.tsx 505 506var rotate = { 507 transform: `rotate(90deg)` 508}; 509var ICON_SIZE = 40; 510var label = { 511 color: "white", 512 fontSize: 14, 513 fontFamily: "sans-serif" 514}; 515var container = { 516 justifyContent: "center", 517 alignItems: "center" 518}; 519var Loading = ()=>{ 520 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsxs)(AbsoluteFill, { 521 style: container, 522 id: "remotion-comp-loading", 523 children: [ 524 /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)("style", { 525 type: "text/css", 526 children: ` 527 @keyframes anim { 528 from { 529 opacity: 0 530 } 531 to { 532 opacity: 1 533 } 534 } 535 #remotion-comp-loading { 536 animation: anim 2s; 537 animation-fill-mode: forwards; 538 } 539 ` 540 }), 541 /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)("svg", { 542 width: ICON_SIZE, 543 height: ICON_SIZE, 544 viewBox: "-100 -100 400 400", 545 style: rotate, 546 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)("path", { 547 fill: "#555", 548 stroke: "#555", 549 strokeWidth: "100", 550 strokeLinejoin: "round", 551 d: "M 2 172 a 196 100 0 0 0 195 5 A 196 240 0 0 0 100 2.259 A 196 240 0 0 0 2 172 z" 552 }) 553 }),
554 /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsxs)("p", { 555 style: label, 556 children: [ 557 "Resolving ", 558 "<Suspense>", 559 "..." 560 ] 561 }) 562 ] 563 }); 564};
565// src/portal-node.ts 566var _portalNode = null; 567var portalNode = ()=>{ 568 if (!_portalNode) { 569 if (typeof document === "undefined") { 570 throw new Error("Tried to call an API that only works in the browser from outside the browser"); 571 } 572 _portalNode = document.createElement("div"); 573 _portalNode.style.position = "absolute"; 574 _portalNode.style.top = "0px"; 575 _portalNode.style.left = "0px"; 576 _portalNode.style.right = "0px"; 577 _portalNode.style.bottom = "0px"; 578 _portalNode.style.width = "100%"; 579 _portalNode.style.height = "100%"; 580 _portalNode.style.display = "flex"; 581 _portalNode.style.flexDirection = "column"; 582 const containerNode = document.createElement("div"); 583 containerNode.style.position = "fixed"; 584 containerNode.style.top = -999999 + "px"; 585 containerNode.appendChild(_portalNode); 586 document.body.appendChild(containerNode); 587 } 588 return _portalNode; 589};
590// src/ResolveCompositionConfig.tsx 591
592// src/input-props-override.ts 593var getKey = ()=>{ 594 return `remotion_inputPropsOverride` + window.location.origin; 595}; 596var getInputPropsOverride = ()=>{ 597 if (typeof localStorage === "undefined") return null; 598 const override = localStorage.getItem(getKey()); 599 if (!override) return null; 600 return JSON.parse(override); 601}; 602var setInputPropsOverride = (override)=>{ 603 if (typeof localStorage === "undefined") return; 604 if (override === null) { 605 localStorage.removeItem(getKey()); 606 return; 607 } 608 localStorage.setItem(getKey(), JSON.stringify(override)); 609};
vendor: 1,378 bytes, lines 610-642
610// src/config/input-props.ts 611var didWarnSSRImport = false; 612var warnOnceSSRImport = ()=>{ 613 if (didWarnSSRImport) { 614 return; 615 } 616 didWarnSSRImport = true; 617 console.warn("Called `getInputProps()` on the server. This function is not available server-side and has returned an empty object."); 618 console.warn("To hide this warning, don't call this function on the server:"); 619 console.warn(" typeof window === 'undefined' ? {} : getInputProps()"); 620}; 621var getInputProps = ()=>{ 622 if (typeof window === "undefined") { 623 warnOnceSSRImport(); 624 return {}; 625 } 626 if (getRemotionEnvironment().isPlayer) { 627 throw new Error("You cannot call `getInputProps()` from a <Player>. Instead, the props are available as React props from component that you passed as `component` prop."); 628 } 629 const override = getInputPropsOverride(); 630 if (override) { 631 return override; 632 } 633 if (typeof window === "undefined" || typeof window.remotion_inputProps === "undefined") { 634 throw new Error("Cannot call `getInputProps()` - window.remotion_inputProps is not set. This API is only available if you are in the Studio, or while you are rendering server-side."); 635 } 636 const param = window.remotion_inputProps; 637 if (!param) { 638 return {}; 639 } 640 const parsed = deserializeJSONWithSpecialTypes(param); 641 return parsed; 642};
643// src/EditorProps.tsx 644 645 646var EditorPropsContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({ 647 props: {}, 648 updateProps: ()=>{ 649 throw new Error("Not implemented"); 650 } 651}); 652var timeValueRef = /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createRef(); 653var EditorPropsProvider = ({ children })=>{ 654 const [props, setProps] = react__WEBPACK_IMPORTED_MODULE_0__.useState({}); 655 const updateProps = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(({ defaultProps, id, newProps })=>{ 656 setProps((prev)=>{ 657 return { 658 ...prev, 659 [id]: typeof newProps === "function" ? newProps(prev[id] ?? defaultProps) : newProps 660 }; 661 }); 662 }, []); 663 const ctx = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 664 return { 665 props, 666 updateProps 667 }; 668 }, [ 669 props, 670 updateProps 671 ]); 672 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(EditorPropsContext.Provider, { 673 value: ctx, 674 children 675 }); 676};
677// src/use-remotion-environment.ts 678
679// src/remotion-environment-context.ts 680 681var RemotionEnvironmentContext = /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createContext(null);
682// src/use-remotion-environment.ts 683var useRemotionEnvironment = ()=>{ 684 const context = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(RemotionEnvironmentContext); 685 const [env] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(()=>getRemotionEnvironment()); 686 return context ?? env; 687};
688// src/validation/validate-dimensions.ts 689function validateDimension(amount, nameOfProp, location) { 690 if (typeof amount !== "number") { 691 throw new Error(`The "${nameOfProp}" prop ${location} must be a number, but you passed a value of type ${typeof amount}`); 692 } 693 if (isNaN(amount)) { 694 throw new TypeError(`The "${nameOfProp}" prop ${location} must not be NaN, but is NaN.`); 695 } 696 if (!Number.isFinite(amount)) { 697 throw new TypeError(`The "${nameOfProp}" prop ${location} must be finite, but is ${amount}.`); 698 } 699 if (amount % 1 !== 0) { 700 throw new TypeError(`The "${nameOfProp}" prop ${location} must be an integer, but is ${amount}.`); 701 } 702 if (amount <= 0) { 703 throw new TypeError(`The "${nameOfProp}" prop ${location} must be positive, but got ${amount}.`); 704 } 705}
706// src/validation/validate-duration-in-frames.ts 707function validateDurationInFrames(durationInFrames, options) { 708 const { allowFloats, component } = options; 709 if (typeof durationInFrames === "undefined") { 710 throw new Error(`The "durationInFrames" prop ${component} is missing.`); 711 } 712 if (typeof durationInFrames !== "number") { 713 throw new Error(`The "durationInFrames" prop ${component} must be a number, but you passed a value of type ${typeof durationInFrames}`); 714 } 715 if (durationInFrames <= 0) { 716 throw new TypeError(`The "durationInFrames" prop ${component} must be positive, but got ${durationInFrames}.`); 717 } 718 if (!allowFloats && durationInFrames % 1 !== 0) { 719 throw new TypeError(`The "durationInFrames" prop ${component} must be an integer, but got ${durationInFrames}.`); 720 } 721 if (!Number.isFinite(durationInFrames)) { 722 throw new TypeError(`The "durationInFrames" prop ${component} must be finite, but got ${durationInFrames}.`); 723 } 724}
725// src/validation/validate-fps.ts 726function validateFps(fps, location, isGif) { 727 if (typeof fps !== "number") { 728 throw new Error(`"fps" must be a number, but you passed a value of type ${typeof fps} ${location}`); 729 } 730 if (!Number.isFinite(fps)) { 731 throw new Error(`"fps" must be a finite, but you passed ${fps} ${location}`); 732 } 733 if (isNaN(fps)) { 734 throw new Error(`"fps" must not be NaN, but got ${fps} ${location}`); 735 } 736 if (fps <= 0) { 737 throw new TypeError(`"fps" must be positive, but got ${fps} ${location}`); 738 } 739 if (isGif && fps > 50) { 740 throw new TypeError(`The FPS for a GIF cannot be higher than 50. Use the --every-nth-frame option to lower the FPS: https://remotion.dev/docs/render-as-gif`); 741 } 742}
743// src/ResolveCompositionConfig.tsx 744var ResolveCompositionContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)(null); 745var resolveCompositionsRef = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createRef)(); 746var needsResolution = (composition)=>{ 747 return Boolean(composition.calculateMetadata); 748}; 749var useResolvedVideoConfig = (preferredCompositionId)=>{ 750 const context = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(ResolveCompositionContext); 751 const { props: allEditorProps } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(EditorPropsContext); 752 const { compositions, canvasContent, currentCompositionMetadata } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(CompositionManager); 753 const currentComposition = canvasContent?.type === "composition" ? canvasContent.compositionId : null; 754 const compositionId = preferredCompositionId ?? currentComposition; 755 const composition = compositions.find((c)=>c.id === compositionId); 756 const selectedEditorProps = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 757 return composition ? allEditorProps[composition.id] ?? {} : {}; 758 }, [ 759 allEditorProps, 760 composition 761 ]); 762 const env = useRemotionEnvironment(); 763 return (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 764 if (!composition) { 765 return null; 766 } 767 if (currentCompositionMetadata) { 768 return { 769 type: "success", 770 result: { 771 ...currentCompositionMetadata, 772 id: composition.id, 773 defaultProps: composition.defaultProps ?? {} 774 } 775 }; 776 } 777 if (!needsResolution(composition)) { 778 validateDurationInFrames(composition.durationInFrames, { 779 allowFloats: false, 780 component: `in <Composition id="${composition.id}">` 781 }); 782 validateFps(composition.fps, `in <Composition id="${composition.id}">`, false); 783 validateDimension(composition.width, "width", `in <Composition id="${composition.id}">`); 784 validateDimension(composition.height, "height", `in <Composition id="${composition.id}">`); 785 return { 786 type: "success", 787 result: { 788 width: composition.width, 789 height: composition.height, 790 fps: composition.fps, 791 id: composition.id, 792 durationInFrames: composition.durationInFrames, 793 defaultProps: composition.defaultProps ?? {}, 794 props: { 795 ...composition.defaultProps ?? {}, 796 ...selectedEditorProps ?? {}, 797 ...typeof window === "undefined" || env.isPlayer || !window.remotion_inputProps ? {} : getInputProps() ?? {} 798 }, 799 defaultCodec: null, 800 defaultOutName: null, 801 defaultVideoImageFormat: null, 802 defaultPixelFormat: null, 803 defaultProResProfile: null, 804 defaultSampleRate: null 805 } 806 }; 807 } 808 if (!context) { 809 return null; 810 } 811 if (!context[composition.id]) { 812 return null; 813 } 814 return context[composition.id]; 815 }, [ 816 composition, 817 context, 818 currentCompositionMetadata, 819 selectedEditorProps, 820 env.isPlayer 821 ]); 822};
823// src/use-delay-render.tsx 824
vendor: 3,194 bytes, lines 825-950
825// src/cancel-render.ts 826var getErrorStackWithMessage = (error)=>{ 827 const stack = error.stack ?? ""; 828 return stack.startsWith("Error:") ? stack : `${error.message} 829${stack}`; 830}; 831var isErrorLike = (err)=>{ 832 if (err instanceof Error) { 833 return true; 834 } 835 if (err === null) { 836 return false; 837 } 838 if (typeof err !== "object") { 839 return false; 840 } 841 if (!("stack" in err)) { 842 return false; 843 } 844 if (typeof err.stack !== "string") { 845 return false; 846 } 847 if (!("message" in err)) { 848 return false; 849 } 850 if (typeof err.message !== "string") { 851 return false; 852 } 853 return true; 854}; 855function cancelRenderInternal(scope, err) { 856 let error; 857 if (isErrorLike(err)) { 858 error = err; 859 if (!error.stack) { 860 error.stack = new Error(error.message).stack; 861 } 862 } else if (typeof err === "string") { 863 error = Error(err); 864 } else { 865 error = Error("Rendering was cancelled"); 866 } 867 if (scope) { 868 scope.remotion_cancelledError = getErrorStackWithMessage(error); 869 } 870 throw error; 871} 872function cancelRender(err) { 873 return cancelRenderInternal(typeof window !== "undefined" ? window : undefined, err); 874} 875// src/log.ts 876var logLevels = [ 877 "trace", 878 "verbose", 879 "info", 880 "warn", 881 "error" 882]; 883var getNumberForLogLevel = (level)=>{ 884 return logLevels.indexOf(level); 885}; 886var isEqualOrBelowLogLevel = (currentLevel, level)=>{ 887 return getNumberForLogLevel(currentLevel) <= getNumberForLogLevel(level); 888}; 889var transformArgs = ({ args, logLevel, tag })=>{ 890 const arr = [ 891 ...args 892 ]; 893 if (getRemotionEnvironment().isRendering && !getRemotionEnvironment().isClientSideRendering) { 894 arr.unshift(Symbol.for(`__remotion_level_${logLevel}`)); 895 } 896 if (tag && getRemotionEnvironment().isRendering && !getRemotionEnvironment().isClientSideRendering) { 897 arr.unshift(Symbol.for(`__remotion_tag_${tag}`)); 898 } 899 return arr; 900}; 901var verbose = (options, ...args)=>{ 902 if (isEqualOrBelowLogLevel(options.logLevel, "verbose")) { 903 return console.debug(...transformArgs({ 904 args, 905 logLevel: "verbose", 906 tag: options.tag 907 })); 908 } 909}; 910var trace = (options, ...args)=>{ 911 if (isEqualOrBelowLogLevel(options.logLevel, "trace")) { 912 return console.debug(...transformArgs({ 913 args, 914 logLevel: "trace", 915 tag: options.tag 916 })); 917 } 918}; 919var info = (options, ...args)=>{ 920 if (isEqualOrBelowLogLevel(options.logLevel, "info")) { 921 return console.log(...transformArgs({ 922 args, 923 logLevel: "info", 924 tag: options.tag 925 })); 926 } 927}; 928var warn = (options, ...args)=>{ 929 if (isEqualOrBelowLogLevel(options.logLevel, "warn")) { 930 return console.warn(...transformArgs({ 931 args, 932 logLevel: "warn", 933 tag: options.tag 934 })); 935 } 936}; 937var error = (options, ...args)=>{ 938 return console.error(...transformArgs({ 939 args, 940 logLevel: "error", 941 tag: options.tag 942 })); 943}; 944var Log = { 945 trace, 946 verbose, 947 info, 948 warn, 949 error 950};
951// src/delay-render.ts 952if (typeof window !== "undefined") { 953 window.remotion_renderReady = false; 954 if (!window.remotion_delayRenderTimeouts) { 955 window.remotion_delayRenderTimeouts = {}; 956 } 957 window.remotion_delayRenderHandles = []; 958} 959var DELAY_RENDER_CALLSTACK_TOKEN = "The delayRender was called:"; 960var DELAY_RENDER_RETRIES_LEFT = "Retries left: "; 961var DELAY_RENDER_RETRY_TOKEN = "- Rendering the frame will be retried."; 962var DELAY_RENDER_CLEAR_TOKEN = "handle was cleared after"; 963var defaultTimeout = 30000; 964var delayRenderInternal = ({ scope, environment, label: label2, options })=>{ 965 if (typeof label2 !== "string" && label2 !== null) { 966 throw new Error("The label parameter of delayRender() must be a string or undefined, got: " + JSON.stringify(label2)); 967 } 968 const handle = Math.random(); 969 scope.remotion_delayRenderHandles.push(handle); 970 const called = Error().stack?.replace(/^Error/g, "") ?? ""; 971 if (environment.isRendering) { 972 const timeoutToUse = (options?.timeoutInMilliseconds ?? scope.remotion_puppeteerTimeout ?? defaultTimeout) - 2000; 973 const retriesLeft = (options?.retries ?? 0) - (scope.remotion_attempt - 1); 974 scope.remotion_delayRenderTimeouts[handle] = { 975 label: label2 ?? null, 976 startTime: Date.now(), 977 timeout: setTimeout(()=>{ 978 const message = [ 979 `A delayRender()`, 980 label2 ? `"${label2}"` : null, 981 `was called but not cleared after ${timeoutToUse}ms. See https://remotion.dev/docs/timeout for help.`, 982 retriesLeft > 0 ? DELAY_RENDER_RETRIES_LEFT + retriesLeft : null, 983 retriesLeft > 0 ? DELAY_RENDER_RETRY_TOKEN : null, 984 DELAY_RENDER_CALLSTACK_TOKEN, 985 called 986 ].filter(truthy).join(" "); 987 if (environment.isClientSideRendering) { 988 scope.remotion_cancelledError = getErrorStackWithMessage(Error(message)); 989 } else { 990 cancelRenderInternal(scope, Error(message)); 991 } 992 }, timeoutToUse) 993 }; 994 } 995 scope.remotion_renderReady = false; 996 return handle; 997}; 998var delayRender = (label2, options)=>{ 999 if (typeof window === "undefined") { 1000 return Math.random(); 1001 } 1002 return delayRenderInternal({ 1003 scope: window, 1004 environment: getRemotionEnvironment(), 1005 label: label2 ?? null, 1006 options: options ?? {} 1007 }); 1008}; 1009var continueRenderInternal = ({ scope, handle, environment, logLevel })=>{ 1010 if (typeof handle === "undefined") { 1011 throw new TypeError("The continueRender() method must be called with a parameter that is the return value of delayRender(). No value was passed."); 1012 } 1013 if (typeof handle !== "number") { 1014 throw new TypeError("The parameter passed into continueRender() must be the return value of delayRender() which is a number. Got: " + JSON.stringify(handle)); 1015 } 1016 scope.remotion_delayRenderHandles = scope.remotion_delayRenderHandles.filter((h)=>{ 1017 if (h === handle) { 1018 if (environment.isRendering && scope !== undefined) { 1019 if (!scope.remotion_delayRenderTimeouts[handle]) { 1020 return false; 1021 } 1022 const { label: label2, startTime, timeout } = scope.remotion_delayRenderTimeouts[handle]; 1023 clearTimeout(timeout); 1024 const message = [ 1025 label2 ? `"${label2}"` : "A handle", 1026 DELAY_RENDER_CLEAR_TOKEN, 1027 `${Date.now() - startTime}ms` 1028 ].filter(truthy).join(" "); 1029 Log.verbose({ 1030 logLevel, 1031 tag: "delayRender()" 1032 }, message); 1033 delete scope.remotion_delayRenderTimeouts[handle]; 1034 } 1035 return false; 1036 } 1037 return true; 1038 }); 1039 if (scope.remotion_delayRenderHandles.length === 0) { 1040 scope.remotion_renderReady = true; 1041 } 1042}; 1043var continueRender = (handle)=>{ 1044 if (typeof window === "undefined") { 1045 return; 1046 } 1047 continueRenderInternal({ 1048 scope: window, 1049 handle, 1050 environment: getRemotionEnvironment(), 1051 logLevel: window.remotion_logLevel ?? "info" 1052 }); 1053};
1054// src/log-level-context.tsx 1055 1056 1057var LogLevelContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({ 1058 logLevel: "info", 1059 mountTime: 0 1060}); 1061var useLogLevel = ()=>{ 1062 const { logLevel } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(LogLevelContext); 1063 if (logLevel === null) { 1064 throw new Error("useLogLevel must be used within a LogLevelProvider"); 1065 } 1066 return logLevel; 1067}; 1068var useMountTime = ()=>{ 1069 const { mountTime } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(LogLevelContext); 1070 if (mountTime === null) { 1071 throw new Error("useMountTime must be used within a LogLevelProvider"); 1072 } 1073 return mountTime; 1074};
1075// src/use-delay-render.tsx 1076var DelayRenderContextType = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)(null); 1077var useDelayRender = ()=>{ 1078 const environment = useRemotionEnvironment(); 1079 const scope = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(DelayRenderContextType) ?? (typeof window !== "undefined" ? window : undefined); 1080 const logLevel = useLogLevel(); 1081 const delayRender2 = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((label2, options)=>{ 1082 if (!scope) { 1083 return Math.random(); 1084 } 1085 return delayRenderInternal({ 1086 scope, 1087 environment, 1088 label: label2 ?? null, 1089 options: options ?? {} 1090 }); 1091 }, [ 1092 environment, 1093 scope 1094 ]); 1095 const continueRender2 = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((handle)=>{ 1096 if (!scope) { 1097 return; 1098 } 1099 continueRenderInternal({ 1100 scope, 1101 handle, 1102 environment, 1103 logLevel 1104 }); 1105 }, [ 1106 environment, 1107 logLevel, 1108 scope 1109 ]); 1110 const cancelRender2 = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((err)=>{ 1111 return cancelRenderInternal(scope ?? (typeof window !== "undefined" ? window : undefined), err); 1112 }, [ 1113 scope 1114 ]); 1115 return { 1116 delayRender: delayRender2, 1117 continueRender: continueRender2, 1118 cancelRender: cancelRender2 1119 }; 1120};
vendor: 1,597 bytes, lines 1121-1153
1121// src/use-lazy-component.ts 1122 1123var useLazyComponent = ({ compProps, componentName, noSuspense })=>{ 1124 const componentRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 1125 if ("component" in compProps) { 1126 componentRef.current = compProps.component; 1127 } 1128 const lazy = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 1129 if ("component" in compProps) { 1130 if (typeof document === "undefined" || noSuspense) { 1131 return compProps.component; 1132 } 1133 if (typeof compProps.component === "undefined") { 1134 throw new Error(`A value of \`undefined\` was passed to the \`component\` prop. Check the value you are passing to the <${componentName}/> component.`); 1135 } 1136 const Wrapper = (props)=>{ 1137 const Comp = componentRef.current; 1138 return /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createElement(Comp, props); 1139 }; 1140 return Wrapper; 1141 } 1142 if ("lazyComponent" in compProps && typeof compProps.lazyComponent !== "undefined") { 1143 if (typeof compProps.lazyComponent === "undefined") { 1144 throw new Error(`A value of \`undefined\` was passed to the \`lazyComponent\` prop. Check the value you are passing to the <${componentName}/> component.`); 1145 } 1146 return /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.lazy(compProps.lazyComponent); 1147 } 1148 throw new Error("You must pass either 'component' or 'lazyComponent'"); 1149 }, [ 1150 compProps.lazyComponent 1151 ]); 1152 return lazy; 1153};
1154// src/use-video.ts 1155 1156var useVideo = ()=>{ 1157 const { canvasContent, compositions, currentCompositionMetadata } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(CompositionManager); 1158 const selected = compositions.find((c)=>{ 1159 return canvasContent?.type === "composition" && c.id === canvasContent.compositionId; 1160 }); 1161 const resolved = useResolvedVideoConfig(selected?.id ?? null); 1162 return (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 1163 if (!resolved) { 1164 return null; 1165 } 1166 if (resolved.type === "error") { 1167 return null; 1168 } 1169 if (resolved.type === "loading") { 1170 return null; 1171 } 1172 if (!selected) { 1173 return null; 1174 } 1175 return { 1176 ...resolved.result, 1177 defaultProps: selected.defaultProps ?? {}, 1178 id: selected.id, 1179 ...currentCompositionMetadata ?? {}, 1180 component: selected.component 1181 }; 1182 }, [ 1183 currentCompositionMetadata, 1184 resolved, 1185 selected 1186 ]); 1187};
1188// src/validation/validate-composition-id.ts 1189var getRegex2 = ()=>/^([a-zA-Z0-9-\u4E00-\u9FFF])+$/g; 1190var isCompositionIdValid = (id)=>id.match(getRegex2()); 1191var validateCompositionId = (id)=>{ 1192 if (!isCompositionIdValid(id)) { 1193 throw new Error(`Composition id can only contain a-z, A-Z, 0-9, CJK characters and -. You passed ${id}`); 1194 } 1195}; 1196var invalidCompositionErrorMessage = `Composition ID must match ${String(getRegex2())}`;
1197// src/validation/validate-default-props.ts 1198var validateDefaultAndInputProps = (defaultProps, name, compositionId)=>{ 1199 if (!defaultProps) { 1200 return; 1201 } 1202 if (typeof defaultProps !== "object") { 1203 throw new Error(`"${name}" must be an object, but you passed a value of type ${typeof defaultProps}`); 1204 } 1205 if (Array.isArray(defaultProps)) { 1206 throw new Error(`"${name}" must be an object, an array was passed ${compositionId ? `for composition "${compositionId}"` : ""}`); 1207 } 1208};
1209// src/Composition.tsx 1210 1211var Fallback = ()=>{ 1212 const { continueRender: continueRender2, delayRender: delayRender2 } = useDelayRender(); 1213 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 1214 const fallback = delayRender2("Waiting for Root component to unsuspend"); 1215 return ()=>continueRender2(fallback); 1216 }, [ 1217 continueRender2, 1218 delayRender2 1219 ]); 1220 return null; 1221}; 1222var InnerComposition = ({ width, height, fps, durationInFrames, id, defaultProps, schema, ...compProps })=>{ 1223 const compManager = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(CompositionSetters); 1224 const { registerComposition, unregisterComposition } = compManager; 1225 const video = useVideo(); 1226 const lazy = useLazyComponent({ 1227 compProps, 1228 componentName: "Composition", 1229 noSuspense: false 1230 }); 1231 const nonce = useNonce(); 1232 const isPlayer = useIsPlayer(); 1233 const environment = useRemotionEnvironment(); 1234 const canUseComposition = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(CanUseRemotionHooks); 1235 if (typeof window !== "undefined") { 1236 window.remotion_seenCompositionIds = Array.from(new Set([ 1237 ...window.remotion_seenCompositionIds ?? [], 1238 id 1239 ])); 1240 } 1241 if (canUseComposition) { 1242 if (isPlayer) { 1243 throw new Error("<Composition> was mounted inside the `component` that was passed to the <Player>. See https://remotion.dev/docs/wrong-composition-mount for help."); 1244 } 1245 throw new Error("<Composition> mounted inside another composition. See https://remotion.dev/docs/wrong-composition-mount for help."); 1246 } 1247 const { folderName, parentName } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(FolderContext); 1248 const stack = compProps.stack ?? null; 1249 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 1250 if (!id) { 1251 throw new Error("No id for composition passed."); 1252 } 1253 validateCompositionId(id); 1254 validateDefaultAndInputProps(defaultProps, "defaultProps", id); 1255 registerComposition({ 1256 durationInFrames: durationInFrames ?? undefined, 1257 fps: fps ?? undefined, 1258 height: height ?? undefined, 1259 width: width ?? undefined, 1260 id, 1261 folderName, 1262 component: lazy, 1263 defaultProps: serializeThenDeserializeInStudio(defaultProps ?? {}), 1264 nonce: nonce.get(), 1265 parentFolderName: parentName, 1266 schema: schema ?? null, 1267 calculateMetadata: compProps.calculateMetadata ?? null, 1268 stack 1269 }); 1270 return ()=>{ 1271 unregisterComposition(id); 1272 }; 1273 }, [ 1274 durationInFrames, 1275 fps, 1276 height, 1277 lazy, 1278 id, 1279 folderName, 1280 defaultProps, 1281 width, 1282 nonce, 1283 parentName, 1284 schema, 1285 compProps.calculateMetadata, 1286 stack, 1287 registerComposition, 1288 unregisterComposition 1289 ]); 1290 const resolved = useResolvedVideoConfig(id); 1291 const { setError, clearError } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(CompositionRenderErrorContext); 1292 const onError = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((error2)=>{ 1293 setError(error2); 1294 }, [ 1295 setError 1296 ]); 1297 const onClear = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(()=>{ 1298 clearError(); 1299 }, [ 1300 clearError 1301 ]); 1302 if (environment.isStudio && video && video.component === lazy && video.id === id) { 1303 const Comp = lazy; 1304 if (resolved === null || resolved.type !== "success" && resolved.type !== "success-and-refreshing") { 1305 return null; 1306 } 1307 return /*#__PURE__*/ (0,react_dom__WEBPACK_IMPORTED_MODULE_1__.createPortal)(/* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(CanUseRemotionHooksProvider, { 1308 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(CompositionErrorBoundary, { 1309 onError, 1310 onClear, 1311 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(react__WEBPACK_IMPORTED_MODULE_0__.Suspense, { 1312 fallback: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Loading, {}), 1313 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Comp, { 1314 ...resolved.result.props ?? {} 1315 }) 1316 }) 1317 }) 1318 }), portalNode()); 1319 } 1320 if (environment.isRendering && video && video.component === lazy && video.id === id) { 1321 const Comp = lazy; 1322 if (resolved === null || resolved.type !== "success" && resolved.type !== "success-and-refreshing") { 1323 return null; 1324 } 1325 return /*#__PURE__*/ (0,react_dom__WEBPACK_IMPORTED_MODULE_1__.createPortal)(/* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(CanUseRemotionHooksProvider, { 1326 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(react__WEBPACK_IMPORTED_MODULE_0__.Suspense, { 1327 fallback: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Fallback, {}), 1328 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Comp, { 1329 ...resolved.result.props ?? {} 1330 }) 1331 }) 1332 }), portalNode()); 1333 } 1334 return null; 1335}; 1336var Composition = (props)=>{ 1337 const { onlyRenderComposition } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(CompositionSetters); 1338 if (onlyRenderComposition && onlyRenderComposition !== props.id) { 1339 return null; 1340 } 1341 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(InnerComposition, { 1342 ...props 1343 }); 1344};
1345// src/enable-sequence-stack-traces.ts 1346var componentsToAddStacksTo = []; 1347var getComponentsToAddStacksTo = ()=>componentsToAddStacksTo; 1348var addSequenceStackTraces = (component)=>{ 1349 componentsToAddStacksTo.push(component); 1350};
1351// src/version.ts 1352var VERSION = "4.0.488";
vendor: 1,231 bytes, lines 1353-1380
1353// src/multiple-versions-warning.ts 1354var checkMultipleRemotionVersions = ()=>{ 1355 if (typeof globalThis === "undefined") { 1356 return; 1357 } 1358 const set = ()=>{ 1359 globalThis.remotion_imported = VERSION; 1360 if (typeof window !== "undefined") { 1361 window.remotion_imported = VERSION; 1362 } 1363 }; 1364 const alreadyImported = globalThis.remotion_imported || typeof window !== "undefined" && window.remotion_imported; 1365 if (alreadyImported) { 1366 if (alreadyImported === VERSION) { 1367 return; 1368 } 1369 if (typeof alreadyImported === "string" && alreadyImported.includes("webcodecs")) { 1370 set(); 1371 return; 1372 } 1373 throw new TypeError(`\uD83D\uDEA8 Multiple versions of Remotion detected: ${[ 1374 VERSION, 1375 typeof alreadyImported === "string" ? alreadyImported : "an older version" 1376 ].filter(truthy).join(" and ")}. This will cause things to break in an unexpected way. 1377Check that all your Remotion packages are on the same version. If your dependencies depend on Remotion, make them peer dependencies. You can also run \`npx remotion versions\` from your terminal to see which versions are mismatching.`); 1378 } 1379 set(); 1380};
1381// src/Null.tsx 1382var Null = ()=>{ 1383 throw new Error("<Null> has been removed as of Remotion v4.0.228. The native clipping APIs were experimental and subject to removal at any time. We removed them because they were sparingly used and made rendering often slower rather than faster."); 1384};
1385// src/Sequence.tsx 1386
1387// src/freeze.tsx 1388
1389// src/SequenceContext.tsx 1390 1391var SequenceContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)(null);
1392// src/timeline-position-state.ts 1393var exports_timeline_position_state = {}; 1394__export(exports_timeline_position_state, { 1395 useTimelineSetFrame: ()=>useTimelineSetFrame, 1396 useTimelinePosition: ()=>useTimelinePosition, 1397 useTimelineContext: ()=>useTimelineContext, 1398 usePlayingState: ()=>usePlayingState, 1399 usePlaybackRate: ()=>usePlaybackRate, 1400 useAbsoluteTimelinePosition: ()=>useAbsoluteTimelinePosition, 1401 persistCurrentFrame: ()=>persistCurrentFrame, 1402 getInitialFrameState: ()=>getInitialFrameState, 1403 getFrameForComposition: ()=>getFrameForComposition, 1404 clampFrameToCompositionRange: ()=>clampFrameToCompositionRange 1405}); 1406
1407// src/TimelineContext.tsx 1408
vendor: 876 bytes, lines 1409-1441
1409// src/random.ts 1410function mulberry32(a) { 1411 let t = a + 1831565813; 1412 t = Math.imul(t ^ t >>> 15, t | 1); 1413 t ^= t + Math.imul(t ^ t >>> 7, t | 61); 1414 return ((t ^ t >>> 14) >>> 0) / 4294967296; 1415} 1416function hashCode(str) { 1417 let i = 0; 1418 let chr = 0; 1419 let hash = 0; 1420 for(i = 0; i < str.length; i++){ 1421 chr = str.charCodeAt(i); 1422 hash = (hash << 5) - hash + chr; 1423 hash |= 0; 1424 } 1425 return hash; 1426} 1427var random = (seed, dummy)=>{ 1428 if (dummy !== undefined) { 1429 throw new TypeError("random() takes only one argument"); 1430 } 1431 if (seed === null) { 1432 return Math.random(); 1433 } 1434 if (typeof seed === "string") { 1435 return mulberry32(hashCode(seed)); 1436 } 1437 if (typeof seed === "number") { 1438 return mulberry32(seed * 10000000000); 1439 } 1440 throw new Error("random() argument must be a number or a string"); 1441};
1442// src/TimelineContext.tsx 1443 1444var SetTimelineContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({ 1445 setFrame: ()=>{ 1446 throw new Error("default"); 1447 }, 1448 setPlaying: ()=>{ 1449 throw new Error("default"); 1450 } 1451}); 1452var TimelineContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)(null); 1453var PlaybackRateContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)(null); 1454var AbsoluteTimeContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)(null); 1455var TimelineContextProvider = ({ children, frameState })=>{ 1456 const [playing, setPlaying] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false); 1457 const imperativePlaying = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(false); 1458 const [playbackRate, setPlaybackRate] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(1); 1459 const audioAndVideoTags = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)([]); 1460 const [remotionRootId] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(()=>String(random(null))); 1461 const [_frame, setFrame] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(()=>getInitialFrameState()); 1462 const frame = frameState ?? _frame; 1463 const { delayRender: delayRender2, continueRender: continueRender2 } = useDelayRender(); 1464 if (typeof window !== "undefined") { 1465 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 1466 window.remotion_setFrame = (f, composition, attempt)=>{ 1467 window.remotion_attempt = attempt; 1468 const id = delayRender2(`Setting the current frame to ${f}`); 1469 let asyncUpdate = true; 1470 setFrame((s)=>{ 1471 const currentFrame = s[composition] ?? window.remotion_initialFrame; 1472 if (currentFrame === f) { 1473 asyncUpdate = false; 1474 return s; 1475 } 1476 return { 1477 ...s, 1478 [composition]: f 1479 }; 1480 }); 1481 if (asyncUpdate) { 1482 requestAnimationFrame(()=>continueRender2(id)); 1483 } else { 1484 continueRender2(id); 1485 } 1486 }; 1487 window.remotion_isPlayer = false; 1488 }, [ 1489 continueRender2, 1490 delayRender2 1491 ]); 1492 } 1493 const timelineContextValue = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 1494 return { 1495 frame, 1496 playing, 1497 imperativePlaying, 1498 rootId: remotionRootId, 1499 audioAndVideoTags 1500 }; 1501 }, [ 1502 frame, 1503 playing, 1504 remotionRootId 1505 ]); 1506 const playbackRateContextValue = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 1507 return { 1508 playbackRate, 1509 setPlaybackRate 1510 }; 1511 }, [ 1512 playbackRate 1513 ]); 1514 const setTimelineContextValue = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 1515 return { 1516 setFrame, 1517 setPlaying 1518 }; 1519 }, []); 1520 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(AbsoluteTimeContext.Provider, { 1521 value: timelineContextValue, 1522 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(PlaybackRateContext.Provider, { 1523 value: playbackRateContextValue, 1524 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(TimelineContext.Provider, { 1525 value: timelineContextValue, 1526 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(SetTimelineContext.Provider, { 1527 value: setTimelineContextValue, 1528 children 1529 }) 1530 }) 1531 }) 1532 }); 1533};
1534// src/timeline-position-state.ts 1535var makeKey = ()=>{ 1536 return `remotion.time-all`; 1537}; 1538var persistCurrentFrame = (time)=>{ 1539 localStorage.setItem(makeKey(), JSON.stringify(time)); 1540}; 1541var getInitialFrameState = ()=>{ 1542 const item = localStorage.getItem(makeKey()) ?? "{}"; 1543 const obj = JSON.parse(item); 1544 return obj; 1545}; 1546var getFrameForComposition = (composition)=>{ 1547 const item = localStorage.getItem(makeKey()) ?? "{}"; 1548 const obj = JSON.parse(item); 1549 if (obj[composition] !== undefined) { 1550 return Number(obj[composition]); 1551 } 1552 if (typeof window === "undefined") { 1553 return 0; 1554 } 1555 return window.remotion_initialFrame ?? 0; 1556}; 1557var clampFrameToCompositionRange = (frame, durationInFrames)=>{ 1558 return Math.max(0, Math.min(Math.max(0, durationInFrames - 1), frame)); 1559}; 1560var useTimelinePositionFromContext = (state)=>{ 1561 const videoConfig = useVideo(); 1562 const env = useRemotionEnvironment(); 1563 if (!videoConfig) { 1564 return typeof window === "undefined" ? 0 : window.remotion_initialFrame ?? 0; 1565 } 1566 const unclamped = state.frame[videoConfig.id] ?? (env.isPlayer ? 0 : getFrameForComposition(videoConfig.id)); 1567 return clampFrameToCompositionRange(unclamped, videoConfig.durationInFrames); 1568}; 1569var useTimelineContext = ()=>{ 1570 const state = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(TimelineContext); 1571 if (state === null) { 1572 throw new Error("TimelineContext is not available. This hook must be used inside a <Player> or the Remotion Studio."); 1573 } 1574 return state; 1575}; 1576var usePlaybackRate = ()=>{ 1577 const state = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(PlaybackRateContext); 1578 if (state === null) { 1579 throw new Error("PlaybackRateContext is not available. This hook must be used inside a <Player> or the Remotion Studio."); 1580 } 1581 return state; 1582}; 1583var useTimelinePosition = ()=>{ 1584 const state = useTimelineContext(); 1585 return useTimelinePositionFromContext(state); 1586}; 1587var useAbsoluteTimelinePosition = ()=>{ 1588 const state = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(AbsoluteTimeContext); 1589 if (state === null) { 1590 throw new Error("AbsoluteTimeContext is not available. This hook must be used inside a <Player> or the Remotion Studio."); 1591 } 1592 return useTimelinePositionFromContext(state); 1593}; 1594var useTimelineSetFrame = ()=>{ 1595 const { setFrame } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SetTimelineContext); 1596 return setFrame; 1597}; 1598var usePlayingState = ()=>{ 1599 const { playing, imperativePlaying } = useTimelineContext(); 1600 const { setPlaying } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SetTimelineContext); 1601 return (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>[ 1602 playing, 1603 setPlaying, 1604 imperativePlaying 1605 ], [ 1606 imperativePlaying, 1607 playing, 1608 setPlaying 1609 ]); 1610};
1611// src/use-current-frame.ts 1612 1613var useCurrentFrame = ()=>{ 1614 const canUseRemotionHooks = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(CanUseRemotionHooks); 1615 const env = useRemotionEnvironment(); 1616 if (!canUseRemotionHooks) { 1617 if (env.isPlayer) { 1618 throw new Error(`useCurrentFrame can only be called inside a component that was passed to <Player>. See: https://www.remotion.dev/docs/player/examples`); 1619 } 1620 throw new Error(`useCurrentFrame() can only be called inside a component that was registered as a composition. See https://www.remotion.dev/docs/the-fundamentals#defining-compositions`); 1621 } 1622 const frame = useTimelinePosition(); 1623 const context = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SequenceContext); 1624 const contextOffset = context ? context.cumulatedFrom + context.relativeFrom : 0; 1625 return frame - contextOffset; 1626};
1627// src/use-video-config.ts 1628
1629// src/use-unsafe-video-config.ts 1630 1631var useUnsafeVideoConfig = ()=>{ 1632 const context = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SequenceContext); 1633 const ctxWidth = context?.width ?? null; 1634 const ctxHeight = context?.height ?? null; 1635 const ctxDuration = context?.durationInFrames ?? null; 1636 const video = useVideo(); 1637 return (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 1638 if (!video) { 1639 return null; 1640 } 1641 const { id, durationInFrames, fps, height, width, defaultProps, props, defaultCodec, defaultOutName, defaultVideoImageFormat, defaultPixelFormat, defaultProResProfile, defaultSampleRate } = video; 1642 return { 1643 id, 1644 width: ctxWidth ?? width, 1645 height: ctxHeight ?? height, 1646 fps, 1647 durationInFrames: ctxDuration ?? durationInFrames, 1648 defaultProps, 1649 props, 1650 defaultCodec, 1651 defaultOutName, 1652 defaultVideoImageFormat, 1653 defaultPixelFormat, 1654 defaultProResProfile, 1655 defaultSampleRate 1656 }; 1657 }, [ 1658 ctxDuration, 1659 ctxHeight, 1660 ctxWidth, 1661 video 1662 ]); 1663};
1664// src/use-video-config.ts 1665var useVideoConfig = ()=>{ 1666 const videoConfig = useUnsafeVideoConfig(); 1667 const context = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(CanUseRemotionHooks); 1668 const isPlayer = useIsPlayer(); 1669 if (!videoConfig) { 1670 if (typeof window !== "undefined" && window.remotion_isPlayer || isPlayer) { 1671 throw new Error([ 1672 "No video config found. Likely reasons:", 1673 "- You are probably calling useVideoConfig() from outside the component passed to <Player />. See https://www.remotion.dev/docs/player/examples for how to set up the Player correctly.", 1674 "- You have multiple versions of Remotion installed which causes the React context to get lost." 1675 ].join("-")); 1676 } 1677 throw new Error("No video config found. You are probably calling useVideoConfig() from a component which has not been registered as a <Composition />. See https://www.remotion.dev/docs/the-fundamentals#defining-compositions for more information."); 1678 } 1679 if (!context) { 1680 throw new Error("Called useVideoConfig() outside a Remotion composition."); 1681 } 1682 return videoConfig; 1683};
1684// src/freeze.tsx 1685 1686var Freeze = ({ frame: frameToFreeze, children, active = true })=>{ 1687 const frame = useCurrentFrame(); 1688 const videoConfig = useVideoConfig(); 1689 if (typeof frameToFreeze === "undefined") { 1690 throw new Error(`The <Freeze /> component requires a 'frame' prop, but none was passed.`); 1691 } 1692 if (typeof frameToFreeze !== "number") { 1693 throw new Error(`The 'frame' prop of <Freeze /> must be a number, but is of type ${typeof frameToFreeze}`); 1694 } 1695 if (Number.isNaN(frameToFreeze)) { 1696 throw new Error(`The 'frame' prop of <Freeze /> must be a real number, but it is NaN.`); 1697 } 1698 if (!Number.isFinite(frameToFreeze)) { 1699 throw new Error(`The 'frame' prop of <Freeze /> must be a finite number, but it is ${frameToFreeze}.`); 1700 } 1701 const isActive = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 1702 if (typeof active === "boolean") { 1703 return active; 1704 } 1705 if (typeof active === "function") { 1706 return active(frame); 1707 } 1708 }, [ 1709 active, 1710 frame 1711 ]); 1712 const timelineContext = useTimelineContext(); 1713 const sequenceContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SequenceContext); 1714 const relativeFrom = sequenceContext?.relativeFrom ?? 0; 1715 const timelineValue = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 1716 if (!isActive) { 1717 return timelineContext; 1718 } 1719 return { 1720 ...timelineContext, 1721 playing: false, 1722 imperativePlaying: { 1723 current: false 1724 }, 1725 frame: { 1726 [videoConfig.id]: frameToFreeze + relativeFrom 1727 } 1728 }; 1729 }, [ 1730 isActive, 1731 timelineContext, 1732 videoConfig.id, 1733 frameToFreeze, 1734 relativeFrom 1735 ]); 1736 const newSequenceContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 1737 if (!sequenceContext) { 1738 return null; 1739 } 1740 if (!isActive) { 1741 return sequenceContext; 1742 } 1743 return { 1744 ...sequenceContext, 1745 cumulatedFrom: 0 1746 }; 1747 }, [ 1748 sequenceContext, 1749 isActive 1750 ]); 1751 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(TimelineContext.Provider, { 1752 value: timelineValue, 1753 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(SequenceContext.Provider, { 1754 value: newSequenceContext, 1755 children 1756 }) 1757 }); 1758};
vendor: 5,014 bytes, lines 1759-1992
1759// src/interactivity-schema.ts 1760var transformSchema = { 1761 "style.transformOrigin": { 1762 type: "transform-origin", 1763 step: 1, 1764 default: "50% 50%", 1765 description: "Transform origin" 1766 }, 1767 "style.translate": { 1768 type: "translate", 1769 step: 1, 1770 default: "0px 0px", 1771 description: "Offset" 1772 }, 1773 "style.scale": { 1774 type: "scale", 1775 max: 100, 1776 step: 0.01, 1777 default: 1, 1778 description: "Scale" 1779 }, 1780 "style.rotate": { 1781 type: "rotation-css", 1782 step: 1, 1783 default: "0deg", 1784 description: "Rotation" 1785 }, 1786 "style.opacity": { 1787 type: "number", 1788 min: 0, 1789 max: 1, 1790 step: 0.01, 1791 default: 1, 1792 description: "Opacity", 1793 hiddenFromList: false 1794 } 1795}; 1796var sequenceVisualStyleSchema = transformSchema; 1797var textSchema = { 1798 "style.color": { 1799 type: "color", 1800 default: undefined, 1801 description: "Color" 1802 }, 1803 "style.fontFamily": { 1804 type: "font-family", 1805 default: undefined, 1806 description: "Font family", 1807 keyframable: false 1808 }, 1809 "style.fontSize": { 1810 type: "number", 1811 default: undefined, 1812 min: 0, 1813 step: 1, 1814 description: "Font size", 1815 hiddenFromList: false 1816 }, 1817 "style.lineHeight": { 1818 type: "number", 1819 default: undefined, 1820 min: 0, 1821 step: 0.05, 1822 description: "Line height", 1823 hiddenFromList: false 1824 }, 1825 "style.fontWeight": { 1826 type: "enum", 1827 default: "400", 1828 description: "Font weight", 1829 variants: { 1830 "100": {}, 1831 "200": {}, 1832 "300": {}, 1833 "400": {}, 1834 "500": {}, 1835 "600": {}, 1836 "700": {}, 1837 "800": {}, 1838 "900": {}, 1839 normal: {}, 1840 bold: {} 1841 } 1842 }, 1843 "style.fontStyle": { 1844 type: "enum", 1845 default: "normal", 1846 description: "Font style", 1847 variants: { 1848 normal: {}, 1849 italic: {}, 1850 oblique: {} 1851 } 1852 }, 1853 "style.textAlign": { 1854 type: "enum", 1855 default: "left", 1856 description: "Text align", 1857 variants: { 1858 left: {}, 1859 center: {}, 1860 right: {}, 1861 justify: {}, 1862 start: {}, 1863 end: {} 1864 } 1865 }, 1866 "style.letterSpacing": { 1867 type: "number", 1868 default: undefined, 1869 step: 0.1, 1870 description: "Letter spacing", 1871 hiddenFromList: false 1872 } 1873}; 1874var textContentSchema = { 1875 children: { 1876 type: "text-content", 1877 default: "", 1878 description: "Text", 1879 keyframable: false 1880 } 1881}; 1882var premountSchema = { 1883 premountFor: { 1884 type: "number", 1885 default: 0, 1886 description: "Premount For", 1887 min: 0, 1888 step: 1, 1889 hiddenFromList: false 1890 }, 1891 postmountFor: { 1892 type: "number", 1893 default: 0, 1894 min: 0, 1895 step: 1, 1896 hiddenFromList: true 1897 }, 1898 styleWhilePremounted: { 1899 type: "hidden" 1900 }, 1901 styleWhilePostmounted: { 1902 type: "hidden" 1903 } 1904}; 1905var sequencePremountSchema = premountSchema; 1906var sequenceStyleSchema = { 1907 ...transformSchema, 1908 ...premountSchema 1909}; 1910var hiddenField = { 1911 type: "boolean", 1912 default: false, 1913 description: "Hidden" 1914}; 1915var showInTimelineField = { 1916 type: "hidden" 1917}; 1918var sequenceNameField = { 1919 type: "hidden" 1920}; 1921var extendSchemaWithSequenceName = (schema)=>{ 1922 return { 1923 name: sequenceNameField, 1924 ...schema 1925 }; 1926}; 1927var durationInFramesField = { 1928 type: "number", 1929 default: undefined, 1930 min: 1, 1931 step: 1, 1932 hiddenFromList: true 1933}; 1934var fromField = { 1935 type: "number", 1936 default: 0, 1937 step: 1, 1938 hiddenFromList: true 1939}; 1940var trimBeforeField = { 1941 type: "number", 1942 default: 0, 1943 min: 0, 1944 step: 1, 1945 hiddenFromList: true 1946}; 1947var freezeField = { 1948 type: "number", 1949 default: null, 1950 step: 1, 1951 hiddenFromList: true 1952}; 1953var baseSchema = { 1954 durationInFrames: durationInFramesField, 1955 from: fromField, 1956 trimBefore: trimBeforeField, 1957 freeze: freezeField, 1958 hidden: hiddenField, 1959 name: sequenceNameField, 1960 showInTimeline: showInTimelineField 1961}; 1962var sequenceSchema = { 1963 ...baseSchema, 1964 layout: { 1965 type: "enum", 1966 default: "absolute-fill", 1967 description: "Layout", 1968 variants: { 1969 "absolute-fill": sequenceStyleSchema, 1970 none: {} 1971 } 1972 } 1973}; 1974var baseSchemaWithoutFrom = { 1975 durationInFrames: durationInFramesField, 1976 trimBefore: trimBeforeField, 1977 freeze: freezeField, 1978 hidden: hiddenField, 1979 name: sequenceNameField, 1980 showInTimeline: showInTimelineField 1981}; 1982var sequenceSchemaWithoutFrom = { 1983 ...baseSchemaWithoutFrom, 1984 layout: sequenceSchema.layout 1985}; 1986var sequenceSchemaDefaultLayoutNone = { 1987 ...sequenceSchema, 1988 layout: { 1989 ...sequenceSchema.layout, 1990 default: "none" 1991 } 1992};
1993// src/PremountContext.tsx 1994 1995var PremountContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({ 1996 premountFramesRemaining: 0 1997});
1998// src/SequenceManager.tsx 1999 2000 2001var SequenceManager = /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createContext({ 2002 registerSequence: ()=>{ 2003 throw new Error("SequenceManagerContext not initialized"); 2004 }, 2005 unregisterSequence: ()=>{ 2006 throw new Error("SequenceManagerContext not initialized"); 2007 }, 2008 sequences: [] 2009}); 2010var SequenceManagerRefContext = /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createContext({ 2011 current: [] 2012}); 2013var makeSequencePropsSubscriptionKey = (key)=>{ 2014 return `${key.nodePath.join(".")}.${key.sequenceKeys.join(".")}.${key.effectKeys.map((keys)=>keys.join(".")).join(".")}`; 2015}; 2016var VisualModePropStatusesContext = /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createContext({ 2017 propStatuses: {} 2018}); 2019var VisualModePropStatusesRefContext = /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createContext({ 2020 current: {} 2021}); 2022var VisualModeDragOverridesContext = /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createContext({ 2023 getDragOverrides: ()=>{ 2024 throw new Error("VisualModeDragOverridesContext not initialized"); 2025 }, 2026 getEffectDragOverrides: ()=>{ 2027 throw new Error("VisualModeDragOverridesContext not initialized"); 2028 } 2029}); 2030var VisualModeSettersContext = /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createContext({ 2031 setDragOverrides: ()=>{ 2032 throw new Error("VisualModeSettersContext not initialized"); 2033 }, 2034 clearDragOverrides: ()=>{ 2035 throw new Error("VisualModeSettersContext not initialized"); 2036 }, 2037 setEffectDragOverrides: ()=>{ 2038 throw new Error("VisualModeSettersContext not initialized"); 2039 }, 2040 clearEffectDragOverrides: ()=>{ 2041 throw new Error("VisualModeSettersContext not initialized"); 2042 }, 2043 setPropStatuses: ()=>{ 2044 throw new Error("VisualModeSettersContext not initialized"); 2045 } 2046}); 2047var effectDragOverridesKey = (nodePath, effectIndex)=>`${makeSequencePropsSubscriptionKey(nodePath)}.effects.${effectIndex}`; 2048var SequenceManagerProvider = ({ children })=>{ 2049 const [sequences, setSequences] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)([]); 2050 const sequencesRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(sequences); 2051 sequencesRef.current = sequences; 2052 const [dragOverrides, setControlOverrides] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)({}); 2053 const controlOverridesRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(dragOverrides); 2054 controlOverridesRef.current = dragOverrides; 2055 const [effectDragOverridesState, setEffectDragOverridesState] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)({}); 2056 const [propStatuses, setPropStatusesMapState] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)({}); 2057 const propStatusesRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(propStatuses); 2058 propStatusesRef.current = propStatuses; 2059 const setDragOverrides = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((nodePath, key, value)=>{ 2060 setControlOverrides((prev)=>({ 2061 ...prev, 2062 [makeSequencePropsSubscriptionKey(nodePath)]: { 2063 ...prev[makeSequencePropsSubscriptionKey(nodePath)], 2064 [key]: value 2065 } 2066 })); 2067 }, []); 2068 const clearDragOverrides = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((nodePath)=>{ 2069 setControlOverrides((prev)=>{ 2070 const key = makeSequencePropsSubscriptionKey(nodePath); 2071 if (!prev[key]) { 2072 return prev; 2073 } 2074 const next = { 2075 ...prev 2076 }; 2077 delete next[key]; 2078 return next; 2079 }); 2080 }, []); 2081 const setEffectDragOverrides = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((nodePath, effectIndex, key, value)=>{ 2082 setEffectDragOverridesState((prev)=>{ 2083 const mapKey = effectDragOverridesKey(nodePath, effectIndex); 2084 return { 2085 ...prev, 2086 [mapKey]: { 2087 ...prev[mapKey], 2088 [key]: value 2089 } 2090 }; 2091 }); 2092 }, []); 2093 const clearEffectDragOverrides = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((nodePath, effectIndex)=>{ 2094 setEffectDragOverridesState((prev)=>{ 2095 const mapKey = effectDragOverridesKey(nodePath, effectIndex); 2096 if (!prev[mapKey]) { 2097 return prev; 2098 } 2099 const next = { 2100 ...prev 2101 }; 2102 delete next[mapKey]; 2103 return next; 2104 }); 2105 }, []); 2106 const setPropStatuses = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((nodePath, values)=>{ 2107 setPropStatusesMapState((prev)=>{
2108 const key = makeSequencePropsSubscriptionKey(nodePath); 2109 const prevKey = prev[key]; 2110 const newKey = values(prevKey); 2111 if (prevKey === newKey) { 2112 return prev; 2113 } 2114 return { 2115 ...prev, 2116 [key]: newKey 2117 }; 2118 }); 2119 }, []); 2120 const registerSequence = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((seq)=>{ 2121 setSequences((seqs)=>{ 2122 return [ 2123 ...seqs, 2124 seq 2125 ]; 2126 }); 2127 }, []); 2128 const unregisterSequence = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((seq)=>{ 2129 setSequences((seqs)=>seqs.filter((s)=>s.id !== seq)); 2130 }, []); 2131 const sequenceContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 2132 return { 2133 registerSequence, 2134 sequences, 2135 unregisterSequence 2136 }; 2137 }, [ 2138 registerSequence, 2139 sequences, 2140 unregisterSequence 2141 ]); 2142 const getDragOverrides = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((nodePath)=>{ 2143 return dragOverrides[makeSequencePropsSubscriptionKey(nodePath)] ?? {}; 2144 }, [ 2145 dragOverrides 2146 ]); 2147 const getEffectDragOverrides = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((nodePath, effectIndex)=>{ 2148 return effectDragOverridesState[effectDragOverridesKey(nodePath, effectIndex)] ?? {}; 2149 }, [ 2150 effectDragOverridesState 2151 ]); 2152 const propStatusesContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 2153 return { 2154 propStatuses 2155 }; 2156 }, [ 2157 propStatuses 2158 ]); 2159 const dragOverridesContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 2160 return { 2161 getDragOverrides, 2162 getEffectDragOverrides 2163 }; 2164 }, [ 2165 getDragOverrides, 2166 getEffectDragOverrides 2167 ]); 2168 const settersContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 2169 return { 2170 setDragOverrides, 2171 clearDragOverrides, 2172 setEffectDragOverrides, 2173 clearEffectDragOverrides, 2174 setPropStatuses 2175 }; 2176 }, [ 2177 setDragOverrides, 2178 clearDragOverrides, 2179 setEffectDragOverrides, 2180 clearEffectDragOverrides, 2181 setPropStatuses 2182 ]); 2183 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(SequenceManagerRefContext.Provider, { 2184 value: sequencesRef, 2185 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(SequenceManager.Provider, { 2186 value: sequenceContext, 2187 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(VisualModePropStatusesRefContext.Provider, { 2188 value: propStatusesRef, 2189 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(VisualModePropStatusesContext.Provider, { 2190 value: propStatusesContext, 2191 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(VisualModeDragOverridesContext.Provider, { 2192 value: dragOverridesContext, 2193 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(VisualModeSettersContext.Provider, { 2194 value: settersContext, 2195 children 2196 }) 2197 }) 2198 }) 2199 }) 2200 }) 2201 }); 2202};
2203// src/series/is-inside-series.tsx 2204 2205 2206var IsInsideSeriesContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)(false); 2207var IsInsideSeriesContainer = ({ children })=>{ 2208 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(IsInsideSeriesContext.Provider, { 2209 value: true, 2210 children 2211 }); 2212}; 2213var IsNotInsideSeriesProvider = ({ children })=>{ 2214 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(IsInsideSeriesContext.Provider, { 2215 value: false, 2216 children 2217 }); 2218}; 2219var useRequireToBeInsideSeries = ()=>{ 2220 const isInsideSeries = react__WEBPACK_IMPORTED_MODULE_0__.useContext(IsInsideSeriesContext); 2221 if (!isInsideSeries) { 2222 throw new Error("This component must be inside a <Series /> component."); 2223 } 2224};
2225// src/v5-flag.ts 2226var ENABLE_V5_BREAKING_CHANGES = false;
2227// src/with-interactivity-schema.ts 2228
vendor: 999 bytes, lines 2229-2262
2229// src/delete-nested-key.ts 2230var deleteNestedKey = (obj, keysToRemove)=>{ 2231 for (const key of keysToRemove){ 2232 const parts = key.split("."); 2233 const parents = [ 2234 obj 2235 ]; 2236 let current = obj; 2237 for(let i = 0; i < parts.length - 1; i++){ 2238 const part = parts[i]; 2239 const next = current[part]; 2240 if (next === undefined || next === null) { 2241 current = null; 2242 break; 2243 } 2244 current = next; 2245 parents.push(current); 2246 } 2247 if (current === null) { 2248 continue; 2249 } 2250 delete current[parts[parts.length - 1]]; 2251 for(let i = parents.length - 1; i > 0; i--){ 2252 const parent = parents[i]; 2253 if (Object.keys(parent).length === 0) { 2254 const parentKey = parts[i - 1]; 2255 delete parents[i - 1][parentKey]; 2256 } else { 2257 break; 2258 } 2259 } 2260 } 2261 return obj; 2262};
2263// src/effects/use-memoized-effects.ts 2264
vendor: 3,283 bytes, lines 2265-2365
2265// src/bezier.ts 2266var NEWTON_ITERATIONS = 4; 2267var NEWTON_MIN_SLOPE = 0.001; 2268var SUBDIVISION_PRECISION = 0.0000001; 2269var SUBDIVISION_MAX_ITERATIONS = 10; 2270var kSplineTableSize = 11; 2271var kSampleStepSize = 1 / (kSplineTableSize - 1); 2272var float32ArraySupported = typeof Float32Array === "function"; 2273function a(aA1, aA2) { 2274 return 1 - 3 * aA2 + 3 * aA1; 2275} 2276function b(aA1, aA2) { 2277 return 3 * aA2 - 6 * aA1; 2278} 2279function c(aA1) { 2280 return 3 * aA1; 2281} 2282function calcBezier(aT, aA1, aA2) { 2283 return ((a(aA1, aA2) * aT + b(aA1, aA2)) * aT + c(aA1)) * aT; 2284} 2285function getSlope(aT, aA1, aA2) { 2286 return 3 * a(aA1, aA2) * aT * aT + 2 * b(aA1, aA2) * aT + c(aA1); 2287} 2288function binarySubdivide({ aX, _aA, _aB, mX1, mX2 }) { 2289 let currentX; 2290 let currentT; 2291 let i = 0; 2292 let aA = _aA; 2293 let aB = _aB; 2294 do { 2295 currentT = aA + (aB - aA) / 2; 2296 currentX = calcBezier(currentT, mX1, mX2) - aX; 2297 if (currentX > 0) { 2298 aB = currentT; 2299 } else { 2300 aA = currentT; 2301 } 2302 }while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS); 2303 return currentT; 2304} 2305function newtonRaphsonIterate(aX, _aGuessT, mX1, mX2) { 2306 let aGuessT = _aGuessT; 2307 for(let i = 0; i < NEWTON_ITERATIONS; ++i){ 2308 const currentSlope = getSlope(aGuessT, mX1, mX2); 2309 if (currentSlope === 0) { 2310 return aGuessT; 2311 } 2312 const currentX = calcBezier(aGuessT, mX1, mX2) - aX; 2313 aGuessT -= currentX / currentSlope; 2314 } 2315 return aGuessT; 2316} 2317function bezier(mX1, mY1, mX2, mY2) { 2318 if (!(mX1 >= 0 && mX1 <= 1 && mX2 >= 0 && mX2 <= 1)) { 2319 throw new Error("bezier x values must be in [0, 1] range"); 2320 } 2321 const sampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize); 2322 if (mX1 !== mY1 || mX2 !== mY2) { 2323 for(let i = 0; i < kSplineTableSize; ++i){ 2324 sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2); 2325 } 2326 } 2327 function getTForX(aX) { 2328 let intervalStart = 0; 2329 let currentSample = 1; 2330 const lastSample = kSplineTableSize - 1; 2331 for(; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample){ 2332 intervalStart += kSampleStepSize; 2333 } 2334 --currentSample; 2335 const dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]); 2336 const guessForT = intervalStart + dist * kSampleStepSize; 2337 const initialSlope = getSlope(guessForT, mX1, mX2); 2338 if (initialSlope >= NEWTON_MIN_SLOPE) { 2339 return newtonRaphsonIterate(aX, guessForT, mX1, mX2); 2340 } 2341 if (initialSlope === 0) { 2342 return guessForT; 2343 } 2344 return binarySubdivide({ 2345 aX, 2346 _aA: intervalStart, 2347 _aB: intervalStart + kSampleStepSize, 2348 mX1, 2349 mX2 2350 }); 2351 } 2352 return function(x) { 2353 const clampedX = Math.min(1, Math.max(0, x)); 2354 if (mX1 === mY1 && mX2 === mY2) { 2355 return clampedX; 2356 } 2357 if (clampedX === 0) { 2358 return 0; 2359 } 2360 if (clampedX === 1) { 2361 return 1; 2362 } 2363 return calcBezier(getTForX(clampedX), mY1, mY2); 2364 }; 2365}
2366// src/normalize-number.ts 2367var normalizeNumber = (value)=>{ 2368 return Math.round(value * 1e6) / 1e6; 2369};
vendor: 6,328 bytes, lines 2370-2609
2370// src/interpolate.ts 2371var angleUnits = new Set([ 2372 "deg", 2373 "rad", 2374 "grad", 2375 "turn" 2376]); 2377var lengthUnits = new Set([ 2378 "%", 2379 "cap", 2380 "ch", 2381 "cm", 2382 "cqb", 2383 "cqh", 2384 "cqi", 2385 "cqmax", 2386 "cqmin", 2387 "cqw", 2388 "dvh", 2389 "dvw", 2390 "em", 2391 "ex", 2392 "ic", 2393 "in", 2394 "lh", 2395 "lvh", 2396 "lvw", 2397 "mm", 2398 "pc", 2399 "pt", 2400 "px", 2401 "q", 2402 "rem", 2403 "rlh", 2404 "svh", 2405 "svw", 2406 "vb", 2407 "vh", 2408 "vi", 2409 "vmax", 2410 "vmin", 2411 "vw" 2412]); 2413var cssNumberRegex = /^([+-]?(?:\d+\.?\d*|\.\d+))([a-zA-Z%]+)?$/; 2414var transformOriginKeywords = new Set([ 2415 "left", 2416 "center", 2417 "right", 2418 "top", 2419 "bottom" 2420]); 2421var transformOriginKeywordOptions = (keyword)=>{ 2422 if (keyword === "left") { 2423 return [ 2424 { 2425 axis: "x", 2426 value: { 2427 value: 0, 2428 unit: "%" 2429 } 2430 } 2431 ]; 2432 } 2433 if (keyword === "right") { 2434 return [ 2435 { 2436 axis: "x", 2437 value: { 2438 value: 100, 2439 unit: "%" 2440 } 2441 } 2442 ]; 2443 } 2444 if (keyword === "top") { 2445 return [ 2446 { 2447 axis: "y", 2448 value: { 2449 value: 0, 2450 unit: "%" 2451 } 2452 } 2453 ]; 2454 } 2455 if (keyword === "bottom") { 2456 return [ 2457 { 2458 axis: "y", 2459 value: { 2460 value: 100, 2461 unit: "%" 2462 } 2463 } 2464 ]; 2465 } 2466 return [ 2467 { 2468 axis: "x", 2469 value: { 2470 value: 50, 2471 unit: "%" 2472 } 2473 }, 2474 { 2475 axis: "y", 2476 value: { 2477 value: 50, 2478 unit: "%" 2479 } 2480 } 2481 ]; 2482}; 2483var transformOriginCenter = { 2484 value: 50, 2485 unit: "%" 2486}; 2487var stringifyNumber = (value)=>{ 2488 return String(normalizeNumber(value)); 2489}; 2490var parseStringInterpolationComponent = (component, value)=>{ 2491 const match = cssNumberRegex.exec(component); 2492 if (match === null) { 2493 throw new TypeError(`Cannot interpolate "${value}" because "${component}" is not a supported scale, translate, or rotate value`); 2494 } 2495 const unit = match[2] ?? null; 2496 const numberValue = Number(match[1]); 2497 if (!Number.isFinite(numberValue)) { 2498 throw new TypeError(`Cannot interpolate "${value}" because "${component}" is not finite`); 2499 } 2500 if (unit === null) { 2501 return { 2502 kind: "scale", 2503 value: numberValue, 2504 unit: null 2505 }; 2506 } 2507 if (angleUnits.has(unit)) { 2508 return { 2509 kind: "rotate", 2510 value: numberValue, 2511 unit 2512 }; 2513 } 2514 if (lengthUnits.has(unit)) { 2515 return { 2516 kind: "translate", 2517 value: numberValue, 2518 unit 2519 }; 2520 } 2521 throw new TypeError(`Cannot interpolate "${value}" because "${unit}" is not a supported translate or rotate unit`); 2522}; 2523var parseTransformOriginLengthPercentage = ({ component, value, allowPercentage })=>{ 2524 const match = cssNumberRegex.exec(component); 2525 if (match === null) { 2526 throw new TypeError(`Cannot interpolate "${value}" because "${component}" is not a supported transform-origin ${allowPercentage ? "length-percentage" : "z length"}`); 2527 } 2528 const unit = match[2] ?? null; 2529 const numberValue = Number(match[1]); 2530 if (!Number.isFinite(numberValue)) { 2531 throw new TypeError(`Cannot interpolate "${value}" because "${component}" is not finite`); 2532 } 2533 if (unit === null || !lengthUnits.has(unit) || !allowPercentage && unit === "%") { 2534 throw new TypeError(`Cannot interpolate "${value}" because "${component}" is not a supported transform-origin ${allowPercentage ? "length-percentage" : "z length"}`); 2535 } 2536 return { 2537 value: numberValue, 2538 unit 2539 }; 2540}; 2541var parseTransformOriginToken = (component, value)=>{ 2542 const lower = component.toLowerCase(); 2543 if (transformOriginKeywords.has(lower)) { 2544 return { 2545 type: "keyword", 2546 keyword: lower 2547 }; 2548 } 2549 return { 2550 type: "length-percentage", 2551 parsed: parseTransformOriginLengthPercentage({ 2552 component, 2553 value, 2554 allowPercentage: true 2555 }) 2556 }; 2557}; 2558var parseTwoTransformOriginKeywords = (first, second, value)=>{ 2559 const candidates = []; 2560 for (const firstOption of transformOriginKeywordOptions(first)){ 2561 for (const secondOption of transformOriginKeywordOptions(second)){ 2562 if (firstOption.axis === secondOption.axis) { 2563 continue; 2564 } 2565 candidates.push(firstOption.axis === "x" ? [ 2566 firstOption.value, 2567 secondOption.value 2568 ] : [ 2569 secondOption.value, 2570 firstOption.value 2571 ]); 2572 } 2573 } 2574 if (candidates.length === 0) { 2575 throw new TypeError(`Cannot interpolate "${value}" because "${first} ${second}" is not a valid transform-origin keyword pair`); 2576 } 2577 return candidates[0]; 2578}; 2579var parseTransformOriginXY = (parts, value)=>{ 2580 if (parts.length === 1) { 2581 const token = parseTransformOriginToken(parts[0], value); 2582 if (token.type === "length-percentage") { 2583 return [ 2584 token.parsed, 2585 transformOriginCenter 2586 ]; 2587 } 2588 if (token.keyword === "top" || token.keyword === "bottom") { 2589 return [ 2590 transformOriginCenter, 2591 transformOriginKeywordOptions(token.keyword)[0].value 2592 ]; 2593 } 2594 return [ 2595 transformOriginKeywordOptions(token.keyword)[0].value, 2596 transformOriginCenter 2597 ]; 2598 } 2599 const first = parseTransformOriginToken(parts[0], value); 2600 const second = parseTransformOriginToken(parts[1], value); 2601 if (first.type === "length-percentage" && second.type === "length-percentage") { 2602 return [ 2603 first.parsed, 2604 second.parsed 2605 ]; 2606 } 2607 if (first.type === "keyword" && second.type === "keyword") { 2608 return parseTwoTransformOriginKeywords(first.keyword, second.keyword, value); 2609 }
2610 const keyword = first.type === "keyword" ? first : second.type === "keyword" ? second : null; 2611 const length = first.type === "length-percentage" ? first.parsed : second.type === "length-percentage" ? second.parsed : null; 2612 if (keyword === null || length === null) { 2613 throw new Error("Expected a keyword and a length-percentage value"); 2614 } 2615 const keywordIsFirst = first.type === "keyword"; 2616 if (keyword.keyword === "left" || keyword.keyword === "right") { 2617 if (!keywordIsFirst) { 2618 throw new TypeError(`Cannot interpolate "${value}" because horizontal transform-origin keywords must come before a length-percentage value`); 2619 } 2620 return [ 2621 transformOriginKeywordOptions(keyword.keyword)[0].value, 2622 length 2623 ]; 2624 } 2625 if (keyword.keyword === "top" || keyword.keyword === "bottom") { 2626 return [ 2627 length, 2628 transformOriginKeywordOptions(keyword.keyword)[0].value 2629 ]; 2630 } 2631 return keywordIsFirst ? [ 2632 transformOriginCenter, 2633 length 2634 ] : [ 2635 length, 2636 transformOriginCenter 2637 ]; 2638}; 2639var parseTransformOriginValue = (output, parts)=>{ 2640 const [x, y] = parseTransformOriginXY(parts.slice(0, 2), output); 2641 const z = parts[2] === undefined ? { 2642 value: 0, 2643 unit: null 2644 } : parseTransformOriginLengthPercentage({ 2645 component: parts[2], 2646 value: output, 2647 allowPercentage: false 2648 }); 2649 return { 2650 kind: "translate", 2651 values: [ 2652 x.value, 2653 y.value, 2654 z.value 2655 ], 2656 units: [ 2657 x.unit, 2658 y.unit, 2659 z.unit 2660 ], 2661 dimensions: parts[2] === undefined ? 2 : 3 2662 }; 2663}; 2664var parseStringInterpolationValue = (output)=>{ 2665 if (typeof output === "number") { 2666 if (!Number.isFinite(output)) { 2667 throw new Error(`outputRange must contain only finite numbers, but got [${output}]`); 2668 } 2669 return { 2670 kind: "scale", 2671 values: [ 2672 output, 2673 output, 2674 1 2675 ], 2676 units: [ 2677 null, 2678 null, 2679 null 2680 ], 2681 dimensions: 1 2682 }; 2683 } 2684 const parts = output.trim().split(/\s+/); 2685 if (parts.length < 1 || parts.length > 3 || parts[0] === "") { 2686 throw new TypeError(`String outputRange values must contain 1 to 3 components, but got "${output}"`); 2687 } 2688 if (parts.some((part)=>transformOriginKeywords.has(part.toLowerCase()))) { 2689 return parseTransformOriginValue(output, parts); 2690 } 2691 const parsed = parts.map((part)=>parseStringInterpolationComponent(part, output)); 2692 const [{ kind }] = parsed; 2693 for (const part of parsed){ 2694 if (part.kind !== kind) { 2695 throw new TypeError(`Cannot interpolate "${output}" because it mixes ${kind} and ${part.kind} values`); 2696 } 2697 } 2698 if (kind === "scale") { 2699 const x = parsed[0].value; 2700 const y = parsed[1]?.value ?? x; 2701 const z = parsed[2]?.value ?? 1; 2702 return { 2703 kind, 2704 values: [ 2705 x, 2706 y, 2707 z 2708 ], 2709 units: [ 2710 null, 2711 null, 2712 null 2713 ], 2714 dimensions: parsed.length 2715 }; 2716 } 2717 return { 2718 kind, 2719 values: [ 2720 parsed[0].value, 2721 parsed[1]?.value ?? 0, 2722 parsed[2]?.value ?? 0 2723 ], 2724 units: [ 2725 parsed[0].unit, 2726 parsed[1]?.unit ?? null, 2727 parsed[2]?.unit ?? null 2728 ], 2729 dimensions: parsed.length 2730 }; 2731}; 2732var serializeStringInterpolationValue = ({ kind, values, units, dimensions })=>{ 2733 if (kind === "scale") { 2734 return values.slice(0, dimensions).map((value)=>stringifyNumber(value)).join(" "); 2735 } 2736 return values.slice(0, dimensions).map((value, index)=>`${stringifyNumber(value)}${units[index]}`).join(" "); 2737}; 2738function interpolateFunction(input, inputRange, outputRange, options) { 2739 const { extrapolateLeft, extrapolateRight, easing } = options; 2740 let result = input; 2741 const [inputMin, inputMax] = inputRange; 2742 const [outputMin, outputMax] = outputRange; 2743 if (result < inputMin) { 2744 if (extrapolateLeft === "identity") { 2745 return result; 2746 } 2747 if (extrapolateLeft === "clamp") { 2748 result = inputMin; 2749 } else if (extrapolateLeft === "wrap") {
vendor: 10,514 bytes, lines 2750-3036
2750 const range = inputMax - inputMin; 2751 result = ((result - inputMin) % range + range) % range + inputMin; 2752 } else if (extrapolateLeft === "extend") {} 2753 } 2754 if (result > inputMax) { 2755 if (extrapolateRight === "identity") { 2756 return result; 2757 } 2758 if (extrapolateRight === "clamp") { 2759 result = inputMax; 2760 } else if (extrapolateRight === "wrap") { 2761 const range = inputMax - inputMin; 2762 result = ((result - inputMin) % range + range) % range + inputMin; 2763 } else if (extrapolateRight === "extend") {} 2764 } 2765 if (outputMin === outputMax) { 2766 return outputMin; 2767 } 2768 result = (result - inputMin) / (inputMax - inputMin); 2769 result = easing(result); 2770 result = result * (outputMax - outputMin) + outputMin; 2771 return result; 2772} 2773function findRange(input, inputRange) { 2774 let i; 2775 for(i = 1; i < inputRange.length - 1; ++i){ 2776 if (inputRange[i] >= input) { 2777 break; 2778 } 2779 } 2780 return i - 1; 2781} 2782var defaultEasing = (num)=>num; 2783var shouldExtendRightForEasing = (easing)=>{ 2784 return easing.remotionShouldExtendRight === true; 2785}; 2786var resolveEasingForSegment = ({ easing, segmentIndex })=>{ 2787 if (easing === undefined) { 2788 return defaultEasing; 2789 } 2790 if (typeof easing === "function") { 2791 return easing; 2792 } 2793 return easing[segmentIndex]; 2794}; 2795var interpolateSegment = ({ input, inputRange, outputRange, easing, extrapolateLeft, extrapolateRight })=>{ 2796 return interpolateFunction(input, inputRange, outputRange, { 2797 easing, 2798 extrapolateLeft, 2799 extrapolateRight: input > inputRange[1] && extrapolateRight === "clamp" && shouldExtendRightForEasing(easing) ? "extend" : extrapolateRight 2800 }); 2801}; 2802var interpolateNumber = ({ input, inputRange, outputRange, options })=>{ 2803 if (inputRange.length === 1) { 2804 return outputRange[0]; 2805 } 2806 const easingOption = options?.easing; 2807 let extrapolateLeft = "extend"; 2808 if (options?.extrapolateLeft !== undefined) { 2809 extrapolateLeft = options.extrapolateLeft; 2810 } 2811 let extrapolateRight = "extend"; 2812 if (options?.extrapolateRight !== undefined) { 2813 extrapolateRight = options.extrapolateRight; 2814 } 2815 const posterizedInput = options?.posterize === undefined ? input : Math.floor(input / options.posterize) * options.posterize; 2816 const range = findRange(posterizedInput, inputRange); 2817 const easing = resolveEasingForSegment({ 2818 easing: easingOption, 2819 segmentIndex: range 2820 }); 2821 let result = interpolateSegment({ 2822 input: posterizedInput, 2823 inputRange: [ 2824 inputRange[range], 2825 inputRange[range + 1] 2826 ], 2827 outputRange: [ 2828 outputRange[range], 2829 outputRange[range + 1] 2830 ], 2831 easing, 2832 extrapolateLeft, 2833 extrapolateRight 2834 }); 2835 for(let segmentIndex = 0; segmentIndex < range; segmentIndex++){ 2836 const previousEasing = resolveEasingForSegment({ 2837 easing: easingOption, 2838 segmentIndex 2839 }); 2840 if (!shouldExtendRightForEasing(previousEasing)) { 2841 continue; 2842 } 2843 const previousSegmentEnd = inputRange[segmentIndex + 1]; 2844 if (posterizedInput <= previousSegmentEnd) { 2845 continue; 2846 } 2847 const continuedSegmentValue = interpolateSegment({ 2848 input: posterizedInput, 2849 inputRange: [ 2850 inputRange[segmentIndex], 2851 previousSegmentEnd 2852 ], 2853 outputRange: [ 2854 outputRange[segmentIndex], 2855 outputRange[segmentIndex + 1] 2856 ], 2857 easing: previousEasing, 2858 extrapolateLeft, 2859 extrapolateRight: "extend" 2860 }); 2861 result += continuedSegmentValue - outputRange[segmentIndex + 1]; 2862 } 2863 return result; 2864}; 2865var interpolateString = ({ input, inputRange, outputRange, options })=>{ 2866 const parsedOutputRange = outputRange.map(parseStringInterpolationValue); 2867 const kind = parsedOutputRange[0]?.kind; 2868 if (kind === undefined) { 2869 throw new Error("outputRange must have at least 1 element"); 2870 } 2871 for (const parsed of parsedOutputRange){ 2872 if (parsed.kind !== kind) { 2873 throw new TypeError(`Cannot interpolate ${kind} values with ${parsed.kind} values`); 2874 } 2875 } 2876 const dimensions = Math.max(...parsedOutputRange.map((parsed)=>parsed.dimensions)); 2877 const units = [ 2878 null, 2879 null, 2880 null 2881 ]; 2882 if (kind !== "scale") { 2883 for(let axis = 0; axis < dimensions; axis++){ 2884 for (const parsed of parsedOutputRange){ 2885 const unit = parsed.units[axis]; 2886 if (unit === null) { 2887 continue; 2888 } 2889 if (units[axis] === null) { 2890 units[axis] = unit; 2891 continue; 2892 } 2893 if (units[axis] !== unit) { 2894 throw new TypeError(`Cannot interpolate ${kind} values with different units on axis ${axis + 1}: ${units[axis]} and ${unit}`); 2895 } 2896 } 2897 if (units[axis] === null) { 2898 throw new TypeError(`Cannot interpolate ${kind} values because axis ${axis + 1} has no unit`); 2899 } 2900 } 2901 } 2902 return serializeStringInterpolationValue({ 2903 kind, 2904 values: [ 2905 0, 2906 0, 2907 0 2908 ].map((_, axis)=>interpolateNumber({ 2909 input, 2910 inputRange, 2911 outputRange: parsedOutputRange.map((parsed)=>parsed.values[axis]), 2912 options 2913 })), 2914 units, 2915 dimensions 2916 }); 2917}; 2918var validateTupleOutputRange = (outputRange)=>{ 2919 const dimensions = outputRange[0]?.length; 2920 if (dimensions === undefined) { 2921 throw new Error("outputRange must have at least 1 element"); 2922 } 2923 if (dimensions === 0) { 2924 throw new TypeError("outputRange tuples must contain at least 1 number"); 2925 } 2926 for (const output of outputRange){ 2927 if (output.length !== dimensions) { 2928 throw new TypeError(`outputRange tuples must all have the same length, but got ${dimensions} and ${output.length}`); 2929 } 2930 for (const value of output){ 2931 if (typeof value !== "number" || !Number.isFinite(value)) { 2932 throw new TypeError(`outputRange tuples must contain only finite numbers, but got [${output.join(",")}]`); 2933 } 2934 } 2935 } 2936 return dimensions; 2937}; 2938var interpolateTuple = ({ input, inputRange, outputRange, options })=>{ 2939 const dimensions = validateTupleOutputRange(outputRange); 2940 return new Array(dimensions).fill(true).map((_, axis)=>interpolateNumber({ 2941 input, 2942 inputRange, 2943 outputRange: outputRange.map((output)=>output[axis]), 2944 options 2945 })); 2946}; 2947function checkValidInputRange(arr) { 2948 for(let i = 1; i < arr.length; ++i){ 2949 if (!(arr[i] > arr[i - 1])) { 2950 throw new Error(`inputRange must be strictly monotonically increasing but got [${arr.join(",")}]`); 2951 } 2952 } 2953} 2954function checkInfiniteRange(name, arr) { 2955 if (arr.length < 1) { 2956 throw new Error(name + " must have at least 1 element"); 2957 } 2958 for (const element of arr){ 2959 if (typeof element !== "number") { 2960 throw new Error(`${name} must contain only numbers`); 2961 } 2962 if (!Number.isFinite(element)) { 2963 throw new Error(`${name} must contain only finite numbers, but got [${arr.join(",")}]`); 2964 } 2965 } 2966} 2967function assertValidInterpolateEasingOption(easing, inputRangeLength) { 2968 if (easing === undefined) { 2969 return; 2970 } 2971 if (typeof easing === "function") { 2972 return; 2973 } 2974 const expectedLength = inputRangeLength - 1; 2975 if (easing.length !== expectedLength) { 2976 throw new Error(`When easing is an array, it must have one entry per segment between keyframes (length inputRange.length - 1 = ${expectedLength}), but got length ${easing.length}`); 2977 } 2978 for(let i = 0; i < easing.length; i++){ 2979 if (typeof easing[i] !== "function") { 2980 throw new Error(`easing[${i}] must be a function`); 2981 } 2982 } 2983} 2984function assertValidInterpolatePosterizeOption(posterize) { 2985 if (posterize === undefined) { 2986 return; 2987 } 2988 if (typeof posterize !== "number" || !Number.isFinite(posterize) || posterize <= 0) { 2989 throw new Error(`posterize must be a positive finite number, but got ${posterize}`); 2990 } 2991} 2992function interpolate(input, inputRange, outputRange, options) { 2993 if (typeof input === "undefined") { 2994 throw new Error("input can not be undefined"); 2995 } 2996 if (typeof inputRange === "undefined") { 2997 throw new Error("inputRange can not be undefined"); 2998 } 2999 if (typeof outputRange === "undefined") { 3000 throw new Error("outputRange can not be undefined"); 3001 } 3002 if (inputRange.length !== outputRange.length) { 3003 throw new Error("inputRange (" + inputRange.length + ") and outputRange (" + outputRange.length + ") must have the same length"); 3004 } 3005 checkInfiniteRange("inputRange", inputRange); 3006 checkValidInputRange(inputRange); 3007 assertValidInterpolateEasingOption(options?.easing, inputRange.length); 3008 assertValidInterpolatePosterizeOption(options?.posterize); 3009 if (typeof input !== "number") { 3010 throw new TypeError("Cannot interpolate an input which is not a number"); 3011 } 3012 if (!Array.isArray(outputRange)) { 3013 throw new Error("outputRange must contain only numbers"); 3014 } 3015 const hasStringOutput = outputRange.some((output)=>typeof output === "string"); 3016 if (hasStringOutput) { 3017 if (!outputRange.every((output)=>typeof output === "string" || typeof output === "number")) { 3018 throw new TypeError("outputRange must contain only numbers, or supported scale, translate, and rotate strings"); 3019 } 3020 return interpolateString({ 3021 input, 3022 inputRange, 3023 outputRange, 3024 options 3025 }); 3026 } 3027 if (outputRange.every((output)=>Array.isArray(output))) { 3028 return interpolateTuple({ 3029 input, 3030 inputRange, 3031 outputRange, 3032 options 3033 }); 3034 } 3035 if (!outputRange.every((output)=>typeof output === "number")) { 3036 throw new TypeError("outputRange must contain only numbers, numeric tuples, or supported scale, translate, and rotate str
3036ings"); 3037 } 3038 checkInfiniteRange("outputRange", outputRange); 3039 return interpolateNumber({ 3040 input, 3041 inputRange, 3042 outputRange, 3043 options 3044 }); 3045}
3046// src/validate-frame.ts 3047var validateFrame = ({ allowFloats, durationInFrames, frame })=>{ 3048 if (typeof frame === "undefined") { 3049 throw new TypeError(`Argument missing for parameter "frame"`); 3050 } 3051 if (typeof frame !== "number") { 3052 throw new TypeError(`Argument passed for "frame" is not a number: ${frame}`); 3053 } 3054 if (!Number.isFinite(frame)) { 3055 throw new RangeError(`Frame ${frame} is not finite`); 3056 } 3057 if (frame % 1 !== 0 && !allowFloats) { 3058 throw new RangeError(`Argument for frame must be an integer, but got ${frame}`); 3059 } 3060 if (frame < 0 && frame < -durationInFrames) { 3061 throw new RangeError(`Cannot use frame ${frame}: Duration of composition is ${durationInFrames}, therefore the lowest frame that can be rendered is ${-durationInFrames}`); 3062 } 3063 if (frame > durationInFrames - 1) { 3064 throw new RangeError(`Cannot use frame ${frame}: Duration of composition is ${durationInFrames}, therefore the highest frame that can be rendered is ${durationInFrames - 1}`); 3065 } 3066};
3067// src/validation/validation-spring-duration.ts 3068var validateSpringDuration = (dur)=>{ 3069 if (typeof dur === "undefined") { 3070 return; 3071 } 3072 if (typeof dur !== "number") { 3073 throw new TypeError(`A "duration" of a spring must be a "number" but is "${typeof dur}"`); 3074 } 3075 if (Number.isNaN(dur)) { 3076 throw new TypeError('A "duration" of a spring is NaN, which it must not be'); 3077 } 3078 if (!Number.isFinite(dur)) { 3079 throw new TypeError('A "duration" of a spring must be finite, but is ' + dur); 3080 } 3081 if (dur <= 0) { 3082 throw new TypeError('A "duration" of a spring must be positive, but is ' + dur); 3083 } 3084};
vendor: 29,555 bytes, lines 3085-4021
3085// src/spring/spring-utils.ts 3086var defaultSpringConfig = { 3087 damping: 10, 3088 mass: 1, 3089 stiffness: 100, 3090 overshootClamping: false 3091}; 3092var advanceCache = {}; 3093function advance({ animation, now, config }) { 3094 const { toValue, lastTimestamp, current, velocity } = animation; 3095 const deltaTime = Math.min(now - lastTimestamp, 64); 3096 if (config.damping <= 0) { 3097 throw new Error("Spring damping must be greater than 0, otherwise the spring() animation will never end, causing an infinite loop."); 3098 } 3099 const c2 = config.damping; 3100 const m = config.mass; 3101 const k = config.stiffness; 3102 const cacheKey = [ 3103 toValue, 3104 lastTimestamp, 3105 current, 3106 velocity, 3107 c2, 3108 m, 3109 k, 3110 now 3111 ].join("-"); 3112 if (advanceCache[cacheKey]) { 3113 return advanceCache[cacheKey]; 3114 } 3115 const v0 = -velocity; 3116 const x0 = toValue - current; 3117 const zeta = c2 / (2 * Math.sqrt(k * m)); 3118 const omega0 = Math.sqrt(k / m); 3119 const omega1 = omega0 * Math.sqrt(1 - zeta ** 2); 3120 const t = deltaTime / 1000; 3121 const sin1 = Math.sin(omega1 * t); 3122 const cos1 = Math.cos(omega1 * t); 3123 const underDampedEnvelope = Math.exp(-zeta * omega0 * t); 3124 const underDampedFrag1 = underDampedEnvelope * (sin1 * ((v0 + zeta * omega0 * x0) / omega1) + x0 * cos1); 3125 const underDampedPosition = toValue - underDampedFrag1; 3126 const underDampedVelocity = zeta * omega0 * underDampedFrag1 - underDampedEnvelope * (cos1 * (v0 + zeta * omega0 * x0) - omega1 * x0 * sin1); 3127 const criticallyDampedEnvelope = Math.exp(-omega0 * t); 3128 const criticallyDampedPosition = toValue - criticallyDampedEnvelope * (x0 + (v0 + omega0 * x0) * t); 3129 const criticallyDampedVelocity = criticallyDampedEnvelope * (v0 * (t * omega0 - 1) + t * x0 * omega0 * omega0); 3130 const animationNode = { 3131 toValue, 3132 prevPosition: current, 3133 lastTimestamp: now, 3134 current: zeta < 1 ? underDampedPosition : criticallyDampedPosition, 3135 velocity: zeta < 1 ? underDampedVelocity : criticallyDampedVelocity 3136 }; 3137 advanceCache[cacheKey] = animationNode; 3138 return animationNode; 3139} 3140var calculationCache = {}; 3141function springCalculation({ frame, fps, config = {} }) { 3142 const from = 0; 3143 const to = 1; 3144 const cacheKey = [ 3145 frame, 3146 fps, 3147 config.damping, 3148 config.mass, 3149 config.overshootClamping, 3150 config.stiffness 3151 ].join("-"); 3152 if (calculationCache[cacheKey]) { 3153 return calculationCache[cacheKey]; 3154 } 3155 let animation = { 3156 lastTimestamp: 0, 3157 current: from, 3158 toValue: to, 3159 velocity: 0, 3160 prevPosition: 0 3161 }; 3162 const frameClamped = Math.max(0, frame); 3163 const unevenRest = frameClamped % 1; 3164 for(let f = 0; f <= Math.floor(frameClamped); f++){ 3165 if (f === Math.floor(frameClamped)) { 3166 f += unevenRest; 3167 } 3168 const time = f / fps * 1000; 3169 animation = advance({ 3170 animation, 3171 now: time, 3172 config: { 3173 ...defaultSpringConfig, 3174 ...config 3175 } 3176 }); 3177 } 3178 calculationCache[cacheKey] = animation; 3179 return animation; 3180} 3181// src/spring/measure-spring.ts 3182var cache = new Map; 3183function measureSpring({ fps, config = {}, threshold = 0.005 }) { 3184 if (typeof threshold !== "number") { 3185 throw new TypeError(`threshold must be a number, got ${threshold} of type ${typeof threshold}`); 3186 } 3187 if (threshold === 0) { 3188 return Infinity; 3189 } 3190 if (threshold === 1) { 3191 return 0; 3192 } 3193 if (isNaN(threshold)) { 3194 throw new TypeError("Threshold is NaN"); 3195 } 3196 if (!Number.isFinite(threshold)) { 3197 throw new TypeError("Threshold is not finite"); 3198 } 3199 if (threshold < 0) { 3200 throw new TypeError("Threshold is below 0"); 3201 } 3202 const cacheKey = [ 3203 fps, 3204 config.damping, 3205 config.mass, 3206 config.overshootClamping, 3207 config.stiffness, 3208 threshold 3209 ].join("-"); 3210 if (cache.has(cacheKey)) { 3211 return cache.get(cacheKey); 3212 } 3213 validateFps(fps, "to the measureSpring() function", false); 3214 let frame = 0; 3215 let finishedFrame = 0; 3216 const calc = ()=>{ 3217 return springCalculation({ 3218 fps, 3219 frame, 3220 config 3221 }); 3222 }; 3223 let animation = calc(); 3224 const calcDifference = ()=>{ 3225 return Math.abs(animation.current - animation.toValue); 3226 }; 3227 let difference = calcDifference(); 3228 while(difference >= threshold){ 3229 frame++; 3230 animation = calc(); 3231 difference = calcDifference(); 3232 } 3233 finishedFrame = frame; 3234 for(let i = 0; i < 20; i++){ 3235 frame++; 3236 animation = calc(); 3237 difference = calcDifference(); 3238 if (difference >= threshold) { 3239 i = 0; 3240 finishedFrame = frame + 1; 3241 } 3242 } 3243 cache.set(cacheKey, finishedFrame); 3244 return finishedFrame; 3245} 3246// src/spring/index.ts 3247function spring({ frame: passedFrame, fps, config = {}, from = 0, to = 1, durationInFrames: passedDurationInFrames, durationRestThreshold, delay = 0, reverse = false }) { 3248 validateSpringDuration(passedDurationInFrames); 3249 validateFrame({ 3250 frame: passedFrame, 3251 durationInFrames: Infinity, 3252 allowFloats: true 3253 }); 3254 validateFps(fps, "to spring()", false); 3255 const needsToCalculateNaturalDuration = reverse || typeof passedDurationInFrames !== "undefined"; 3256 const naturalDuration = needsToCalculateNaturalDuration ? measureSpring({ 3257 fps, 3258 config, 3259 threshold: durationRestThreshold 3260 }) : undefined; 3261 const naturalDurationGetter = needsToCalculateNaturalDuration ? { 3262 get: ()=>naturalDuration 3263 } : { 3264 get: ()=>{ 3265 throw new Error("did not calculate natural duration, this is an error with Remotion. Please report"); 3266 } 3267 }; 3268 const reverseProcessed = reverse ? (passedDurationInFrames ?? naturalDurationGetter.get()) - passedFrame : passedFrame; 3269 const delayProcessed = reverseProcessed + (reverse ? delay : -delay); 3270 const durationProcessed = passedDurationInFrames === undefined ? delayProcessed : delayProcessed / (passedDurationInFrames / naturalDurationGetter.get()); 3271 if (passedDurationInFrames && delayProcessed > passedDurationInFrames) { 3272 return to; 3273 } 3274 const spr = springCalculation({ 3275 fps, 3276 frame: durationProcessed, 3277 config 3278 }); 3279 const inner = config.overshootClamping ? to >= from ? Math.min(spr.current, to) : Math.max(spr.current, to) : spr.current; 3280 const interpolated = from === 0 && to === 1 ? inner : interpolate(inner, [ 3281 0, 3282 1 3283 ], [ 3284 from, 3285 to 3286 ]); 3287 return interpolated; 3288} 3289// src/easing.ts 3290var clampUnit = (t)=>Math.min(1, Math.max(0, t)); 3291var springEasingDurationInFrames = 30; 3292class Easing { 3293 static step0(n) { 3294 return n > 0 ? 1 : 0; 3295 } 3296 static step1(n) { 3297 return n >= 1 ? 1 : 0; 3298 } 3299 static linear(t) { 3300 return t; 3301 } 3302 static ease(t) { 3303 return Easing.bezier(0.42, 0, 1, 1)(t); 3304 } 3305 static quad(t) { 3306 return t * t; 3307 } 3308 static cubic(t) { 3309 return t * t * t; 3310 } 3311 static poly(n) { 3312 return (t)=>t ** n; 3313 } 3314 static sin(t) { 3315 return 1 - Math.cos(t * Math.PI / 2); 3316 } 3317 static circle(t) { 3318 const u = clampUnit(t); 3319 return 1 - Math.sqrt(1 - u * u); 3320 } 3321 static exp(t) { 3322 return 2 ** (10 * (t - 1)); 3323 } 3324 static elastic(bounciness = 1) { 3325 const p = bounciness * Math.PI; 3326 return (t)=>1 - Math.cos(t * Math.PI / 2) ** 3 * Math.cos(t * p); 3327 } 3328 static back(s = 1.70158) { 3329 return (t)=>t * t * ((s + 1) * t - s); 3330 } 3331 static spring({ allowTail = false, durationRestThreshold, ...config } = {}) { 3332 const easing = (t)=>{ 3333 if (t <= 0) { 3334 return 0; 3335 } 3336 if (!allowTail && t >= 1) { 3337 return 1; 3338 } 3339 if (allowTail) { 3340 return spring({ 3341 fps: springEasingDurationInFrames, 3342 frame: t * measureSpring({ 3343 fps: springEasingDurationInFrames, 3344 config, 3345 threshold: durationRestThreshold 3346 }), 3347 config 3348 }); 3349 } 3350 return spring({ 3351 fps: springEasingDurationInFrames, 3352 frame: t * springEasingDurationInFrames, 3353 config, 3354 durationInFrames: springEasingDurationInFrames, 3355 durationRestThreshold 3356 }); 3357 }; 3358 return Object.assign(easing, { 3359 remotionShouldExtendRight: allowTail 3360 }); 3361 } 3362 static bounce(t) { 3363 const u = clampUnit(t); 3364 if (u < 1 / 2.75) { 3365 return 7.5625 * u * u; 3366 } 3367 if (u < 2 / 2.75) { 3368 const t2_ = u - 1.5 / 2.75; 3369 return 7.5625 * t2_ * t2_ + 0.75; 3370 } 3371 if (u < 2.5 / 2.75) { 3372 const t2_ = u - 2.25 / 2.75; 3373 return 7.5625 * t2_ * t2_ + 0.9375; 3374 } 3375 const t2 = u - 2.625 / 2.75; 3376 return 7.5625 * t2 * t2 + 0.984375; 3377 } 3378 static bezier(x1, y1, x2, y2) { 3379 return bezier(x1, y1, x2, y2); 3380 } 3381 static in(easing) { 3382 return easing; 3383 } 3384 static out(easing) { 3385 return (t)=>1 - easing(1 - t); 3386 } 3387 static inOut(easing) { 3388 return (t)=>{ 3389 if (t < 0.5) { 3390 return easing(t * 2) / 2; 3391 } 3392 return 1 - easing((1 - t) * 2) / 2; 3393 }; 3394 } 3395} 3396// src/interpolate-colors.ts 3397var NUMBER = "[-+]?\\d*\\.?\\d+"; 3398var PERCENTAGE = NUMBER + "%"; 3399function call(...args) { 3400 return "\\(\\s*(" + args.join(")\\s*,\\s*(") + ")\\s*\\)"; 3401} 3402var MODERN_VALUE = "(?:none|[-+]?\\d*\\.?\\d+(?:%|deg|rad|grad|turn)?)"; 3403function modernColorCall(name) { 3404 return new RegExp(name + "\\(\\s*(" + MODERN_VALUE + ")\\s+(" + MODERN_VALUE + ")\\s+(" + MODERN_VALUE + ")(?:\\s*\\/\\s*(" + MODERN_VALUE + "))?\\s*\\)"); 3405} 3406function getMatchers() { 3407 const cachedMatchers = { 3408 rgb: undefined, 3409 rgba: undefined, 3410 hsl: undefined, 3411 hsla: undefined, 3412 hex3: undefined, 3413 hex4: undefined, 3414 hex5: undefined, 3415 hex6: undefined, 3416 hex8: undefined, 3417 oklch: undefined, 3418 oklab: undefined, 3419 lab: undefined, 3420 lch: undefined, 3421 hwb: undefined 3422 }; 3423 if (cachedMatchers.rgb === undefined) { 3424 cachedMatchers.rgb = new RegExp("rgb" + call(NUMBER, NUMBER, NUMBER)); 3425 cachedMatchers.rgba = new RegExp("rgba" + call(NUMBER, NUMBER, NUMBER, NUMBER)); 3426 cachedMatchers.hsl = new RegExp("hsl" + call(NUMBER, PERCENTAGE, PERCENTAGE)); 3427 cachedMatchers.hsla = new RegExp("hsla" + call(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER)); 3428 cachedMatchers.hex3 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/; 3429 cachedMatchers.hex4 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/; 3430 cachedMatchers.hex6 = /^#([0-9a-fA-F]{6})$/; 3431 cachedMatchers.hex8 = /^#([0-9a-fA-F]{8})$/; 3432 cachedMatchers.oklch = modernColorCall("oklch"); 3433 cachedMatchers.oklab = modernColorCall("oklab"); 3434 cachedMatchers.lab = modernColorCall("lab"); 3435 cachedMatchers.lch = modernColorCall("lch"); 3436 cachedMatchers.hwb = modernColorCall("hwb"); 3437 } 3438 return cachedMatchers; 3439} 3440function hue2rgb(p, q, t) { 3441 if (t < 0) { 3442 t += 1; 3443 } 3444 if (t > 1) { 3445 t -= 1; 3446 } 3447 if (t < 1 / 6) { 3448 return p + (q - p) * 6 * t; 3449 } 3450 if (t < 1 / 2) { 3451 return q; 3452 } 3453 if (t < 2 / 3) { 3454 return p + (q - p) * (2 / 3 - t) * 6; 3455 } 3456 return p; 3457} 3458function hslToRgb(h, s, l) { 3459 const q = l < 0.5 ? l * (1 + s) : l + s - l * s; 3460 const p = 2 * l - q; 3461 const r = hue2rgb(p, q, h + 1 / 3); 3462 const g = hue2rgb(p, q, h); 3463 const b2 = hue2rgb(p, q, h - 1 / 3); 3464 return Math.round(r * 255) << 24 | Math.round(g * 255) << 16 | Math.round(b2 * 255) << 8; 3465} 3466function parse255(str) { 3467 const int = Number.parseInt(str, 10); 3468 if (int < 0) { 3469 return 0; 3470 } 3471 if (int > 255) { 3472 return 255; 3473 } 3474 return int; 3475} 3476function parse360(str) { 3477 const int = Number.parseFloat(str); 3478 return (int % 360 + 360) % 360 / 360; 3479} 3480function parse1(str) { 3481 const num = Number.parseFloat(str); 3482 if (num < 0) { 3483 return 0; 3484 } 3485 if (num > 1) { 3486 return 255; 3487 } 3488 return Math.round(num * 255); 3489} 3490function parsePercentage(str) { 3491 const int = Number.parseFloat(str); 3492 if (int < 0) { 3493 return 0; 3494 } 3495 if (int > 100) { 3496 return 1; 3497 } 3498 return int / 100; 3499} 3500function parseModernComponent(str, percentScale) { 3501 if (str === "none") return 0; 3502 if (str.endsWith("%")) { 3503 return Number.parseFloat(str) / 100 * percentScale; 3504 } 3505 return Number.parseFloat(str); 3506} 3507function parseHueAngle(str) { 3508 if (str === "none") return 0; 3509 if (str.endsWith("rad")) { 3510 return Number.parseFloat(str) * 180 / Math.PI; 3511 } 3512 if (str.endsWith("grad")) return Number.parseFloat(str) * 0.9; 3513 if (str.endsWith("turn")) return Number.parseFloat(str) * 360; 3514 return Number.parseFloat(str); 3515} 3516function parseModernAlpha(str) { 3517 if (str === undefined || str === "none") return 1; 3518 if (str.endsWith("%")) { 3519 return Math.max(0, Math.min(1, Number.parseFloat(str) / 100)); 3520 } 3521 return Math.max(0, Math.min(1, Number.parseFloat(str))); 3522} 3523function linearToSrgb(c2) { 3524 if (c2 <= 0.0031308) return 12.92 * c2; 3525 return 1.055 * c2 ** (1 / 2.4) - 0.055; 3526} 3527function clamp01(v) { 3528 return Math.max(0, Math.min(1, v)); 3529} 3530function rgbFloatToInt(r, g, b2, alpha) { 3531 const ri = Math.round(clamp01(r) * 255); 3532 const gi = Math.round(clamp01(g) * 255); 3533 const bi = Math.round(clamp01(b2) * 255); 3534 const ai = Math.round(clamp01(alpha) * 255); 3535 return (ri << 24 | gi << 16 | bi << 8 | ai) >>> 0; 3536} 3537function oklabToSrgb(L, a2, b2) { 3538 const l_ = L + 0.3963377774 * a2 + 0.2158037573 * b2; 3539 const m_ = L - 0.1055613458 * a2 - 0.0638541728 * b2; 3540 const s_ = L - 0.0894841775 * a2 - 1.291485548 * b2; 3541 const l = l_ * l_ * l_; 3542 const m = m_ * m_ * m_; 3543 const s = s_ * s_ * s_; 3544 const rLin = 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s; 3545 const gLin = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s; 3546 const bLin = -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s; 3547 return [ 3548 linearToSrgb(rLin), 3549 linearToSrgb(gLin), 3550 linearToSrgb(bLin) 3551 ]; 3552} 3553function labToSrgb(L, a2, b2) { 3554 const epsilon = 216 / 24389; 3555 const kappa = 24389 / 27; 3556 const Xn = 0.95047; 3557 const Yn = 1; 3558 const Zn = 1.08883; 3559 const fy = (L + 16) / 116; 3560 const fx = a2 / 500 + fy; 3561 const fz = fy - b2 / 200; 3562 const fx3 = fx * fx * fx; 3563 const fz3 = fz * fz * fz; 3564 const xr = fx3 > epsilon ? fx3 : (116 * fx - 16) / kappa; 3565 const yr = L > kappa * epsilon ? ((L + 16) / 116) ** 3 : L / kappa; 3566 const zr = fz3 > epsilon ? fz3 : (116 * fz - 16) / kappa; 3567 const X = xr * Xn; 3568 const Y = yr * Yn; 3569 const Z = zr * Zn; 3570 const rLin = 3.2404542 * X - 1.5371385 * Y - 0.4985314 * Z; 3571 const gLin = -0.969266 * X + 1.8760108 * Y + 0.041556 * Z; 3572 const bLin = 0.0556434 * X - 0.2040259 * Y + 1.0572252 * Z; 3573 return [ 3574 linearToSrgb(rLin), 3575 linearToSrgb(gLin), 3576 linearToSrgb(bLin) 3577 ]; 3578} 3579function hwbToSrgb(h, w, bk) { 3580 if (w + bk >= 1) { 3581 const gray = w / (w + bk); 3582 return [ 3583 gray, 3584 gray, 3585 gray 3586 ]; 3587 } 3588 const q = 1; 3589 const p = 0; 3590 const r = hue2rgb(p, q, h + 1 / 3); 3591 const g = hue2rgb(p, q, h); 3592 const bl = hue2rgb(p, q, h - 1 / 3); 3593 const factor = 1 - w - bk; 3594 return [ 3595 r * factor + w, 3596 g * factor + w, 3597 bl * factor + w 3598 ]; 3599} 3600var colorNames = { 3601 transparent: 0, 3602 aliceblue: 4042850303, 3603 antiquewhite: 4209760255, 3604 aqua: 16777215, 3605 aquamarine: 2147472639, 3606 azure: 4043309055, 3607 beige: 4126530815, 3608 bisque: 4293182719, 3609 black: 255, 3610 blanchedalmond: 4293643775, 3611 blue: 65535, 3612 blueviolet: 2318131967, 3613 brown: 2771004159, 3614 burlywood: 3736635391, 3615 burntsienna: 3934150143, 3616 cadetblue: 1604231423, 3617 chartreuse: 2147418367, 3618 chocolate: 3530104575, 3619 coral: 4286533887, 3620 cornflowerblue: 1687547391, 3621 cornsilk: 4294499583, 3622 crimson: 3692313855, 3623 cyan: 16777215, 3624 darkblue: 35839, 3625 darkcyan: 9145343, 3626 darkgoldenrod: 3095792639, 3627 darkgray: 2846468607, 3628 darkgreen: 6553855, 3629 darkgrey: 2846468607, 3630 darkkhaki: 3182914559, 3631 darkmagenta: 2332068863, 3632 darkolivegreen: 1433087999, 3633 darkorange: 4287365375, 3634 darkorchid: 2570243327, 3635 darkred: 2332033279, 3636 darksalmon: 3918953215, 3637 darkseagreen: 2411499519, 3638 darkslateblue: 1211993087, 3639 darkslategray: 793726975, 3640 darkslategrey: 793726975, 3641 darkturquoise: 13554175, 3642 darkviolet: 2483082239, 3643 deeppink: 4279538687, 3644 deepskyblue: 12582911, 3645 dimgray: 1768516095, 3646 dimgrey: 1768516095, 3647 dodgerblue: 512819199, 3648 firebrick: 2988581631, 3649 floralwhite: 4294635775, 3650 forestgreen: 579543807, 3651 fuchsia: 4278255615, 3652 gainsboro: 3705462015, 3653 ghostwhite: 4177068031, 3654 gold: 4292280575, 3655 goldenrod: 3668254975, 3656 gray: 2155905279, 3657 green: 8388863, 3658 greenyellow: 2919182335, 3659 grey: 2155905279, 3660 honeydew: 4043305215, 3661 hotpink: 4285117695, 3662 indianred: 3445382399, 3663 indigo: 1258324735, 3664 ivory: 4294963455, 3665 khaki: 4041641215, 3666 lavender: 3873897215, 3667 lavenderblush: 4293981695, 3668 lawngreen: 2096890111, 3669 lemonchiffon: 4294626815, 3670 lightblue: 2916673279, 3671 lightcoral: 4034953471, 3672 lightcyan: 3774873599, 3673 lightgoldenrodyellow: 4210742015, 3674 lightgray: 3553874943, 3675 lightgreen: 2431553791, 3676 lightgrey: 3553874943, 3677 lightpink: 4290167295, 3678 lightsalmon: 4288707327, 3679 lightseagreen: 548580095, 3680 lightskyblue: 2278488831, 3681 lightslategray: 2005441023, 3682 lightslategrey: 2005441023, 3683 lightsteelblue: 2965692159, 3684 lightyellow: 4294959359, 3685 lime: 16711935, 3686 limegreen: 852308735, 3687 linen: 4210091775, 3688 magenta: 4278255615, 3689 maroon: 2147483903, 3690 mediumaquamarine: 1724754687, 3691 mediumblue: 52735, 3692 mediumorchid: 3126187007, 3693 mediumpurple: 2473647103, 3694 mediumseagreen: 1018393087, 3695 mediumslateblue: 2070474495, 3696 mediumspringgreen: 16423679, 3697 mediumturquoise: 1221709055, 3698 mediumvioletred: 3340076543, 3699 midnightblue: 421097727, 3700 mintcream: 4127193855, 3701 mistyrose: 4293190143, 3702 moccasin: 4293178879, 3703 navajowhite: 4292783615, 3704 navy: 33023, 3705 oldlace: 4260751103, 3706 olive: 2155872511, 3707 olivedrab: 1804477439, 3708 orange: 4289003775, 3709 orangered: 4282712319, 3710 orchid: 3664828159, 3711 palegoldenrod: 4008225535, 3712 palegreen: 2566625535, 3713 paleturquoise: 2951671551, 3714 palevioletred: 3681588223, 3715 papayawhip: 4293907967, 3716 peachpuff: 4292524543, 3717 peru: 3448061951, 3718 pink: 4290825215, 3719 plum: 3718307327, 3720 powderblue: 2967529215, 3721 purple: 2147516671, 3722 rebeccapurple: 1714657791, 3723 red: 4278190335, 3724 rosybrown: 3163525119, 3725 royalblue: 1097458175, 3726 saddlebrown: 2336560127, 3727 salmon: 4202722047, 3728 sandybrown: 4104413439, 3729 seagreen: 780883967, 3730 seashell: 4294307583, 3731 sienna: 2689740287, 3732 silver: 3233857791, 3733 skyblue: 2278484991, 3734 slateblue: 1784335871, 3735 slategray: 1887473919, 3736 slategrey: 1887473919, 3737 snow: 4294638335, 3738 springgreen: 16744447, 3739 steelblue: 1182971135, 3740 tan: 3535047935, 3741 teal: 8421631, 3742 thistle: 3636451583, 3743 tomato: 4284696575, 3744 turquoise: 1088475391, 3745 violet: 4001558271, 3746 wheat: 4125012991, 3747 white: 4294967295, 3748 whitesmoke: 4126537215, 3749 yellow: 4294902015, 3750 yellowgreen: 2597139199 3751}; 3752function normalizeColor(color) { 3753 const matchers = getMatchers(); 3754 let match; 3755 if (matchers.hex6) { 3756 if (match = matchers.hex6.exec(color)) { 3757 return Number.parseInt(match[1] + "ff", 16) >>> 0; 3758 } 3759 } 3760 if (colorNames[color] !== undefined) { 3761 return colorNames[color]; 3762 } 3763 if (matchers.rgb) { 3764 if (match = matchers.rgb.exec(color)) { 3765 return (parse255(match[1]) << 24 | parse255(match[2]) << 16 | parse255(match[3]) << 8 | 255) >>> 0; 3766 } 3767 } 3768 if (matchers.rgba) { 3769 if (match = matchers.rgba.exec(color)) { 3770 return (parse255(match[1]) << 24 | parse255(match[2]) << 16 | parse255(match[3]) << 8 | parse1(match[4])) >>> 0; 3771 } 3772 } 3773 if (matchers.hex3) { 3774 if (match = matchers.hex3.exec(color)) { 3775 return Number.parseInt(match[1] + match[1] + match[2] + match[2] + match[3] + match[3] + "ff", 16) >>> 0; 3776 } 3777 } 3778 if (matchers.hex8) { 3779 if (match = matchers.hex8.exec(color)) { 3780 return Number.parseInt(match[1], 16) >>> 0; 3781 } 3782 } 3783 if (matchers.hex4) { 3784 if (match = matchers.hex4.exec(color)) { 3785 return Number.parseInt(match[1] + match[1] + match[2] + match[2] + match[3] + match[3] + match[4] + match[4], 16) >>> 0; 3786 } 3787 } 3788 if (matchers.hsl) { 3789 if (match = matchers.hsl.exec(color)) { 3790 return (hslToRgb(parse360(match[1]), parsePercentage(match[2]), parsePercentage(match[3])) | 255) >>> 0; 3791 } 3792 } 3793 if (matchers.hsla) { 3794 if (match = matchers.hsla.exec(color)) { 3795 return (hslToRgb(parse360(match[1]), parsePercentage(match[2]), parsePercentage(match[3])) | parse1(match[4])) >>> 0; 3796 } 3797 } 3798 if (matchers.oklch) { 3799 if (match = matchers.oklch.exec(color)) { 3800 const L = parseModernComponent(match[1], 1); 3801 const C = parseModernComponent(match[2], 0.4); 3802 const H = parseHueAngle(match[3]); 3803 const alpha = parseModernAlpha(match[4]); 3804 const hRad = H * Math.PI / 180; 3805 const [r, g, b2] = oklabToSrgb(L, C * Math.cos(hRad), C * Math.sin(hRad)); 3806 return rgbFloatToInt(r, g, b2, alpha); 3807 } 3808 } 3809 if (matchers.oklab) { 3810 if (match = matchers.oklab.exec(color)) { 3811 const L = parseModernComponent(match[1], 1); 3812 const a2 = parseModernComponent(match[2], 0.4); 3813 const b2 = parseModernComponent(match[3], 0.4); 3814 const alpha = parseModernAlpha(match[4]); 3815 const [r, g, bl] = oklabToSrgb(L, a2, b2); 3816 return rgbFloatToInt(r, g, bl, alpha); 3817 } 3818 } 3819 if (matchers.lab) { 3820 if (match = matchers.lab.exec(color)) { 3821 const L = parseModernComponent(match[1], 100); 3822 const a2 = parseModernComponent(match[2], 125); 3823 const b2 = parseModernComponent(match[3], 125); 3824 const alpha = parseModernAlpha(match[4]); 3825 const [r, g, bl] = labToSrgb(L, a2, b2); 3826 return rgbFloatToInt(r, g, bl, alpha); 3827 } 3828 } 3829 if (matchers.lch) { 3830 if (match = matchers.lch.exec(color)) { 3831 const L = parseModernComponent(match[1], 100); 3832 const C = parseModernComponent(match[2], 150); 3833 const H = parseHueAngle(match[3]); 3834 const alpha = parseModernAlpha(match[4]); 3835 const hRad = H * Math.PI / 180; 3836 const [r, g, bl] = labToSrgb(L, C * Math.cos(hRad), C * Math.sin(hRad)); 3837 return rgbFloatToInt(r, g, bl, alpha); 3838 } 3839 } 3840 if (matchers.hwb) { 3841 if (match = matchers.hwb.exec(color)) { 3842 const H = parseHueAngle(match[1]); 3843 const W = parseModernComponent(match[2], 1); 3844 const B = parseModernComponent(match[3], 1); 3845 const alpha = parseModernAlpha(match[4]); 3846 const [r, g, bl] = hwbToSrgb(H / 360, W, B); 3847 return rgbFloatToInt(r, g, bl, alpha); 3848 } 3849 } 3850 throw new Error(`invalid color string ${color} provided`); 3851} 3852var opacity = (c2)=>{ 3853 return (c2 >> 24 & 255) / 255; 3854}; 3855var red = (c2)=>{ 3856 return c2 >> 16 & 255; 3857}; 3858var green = (c2)=>{ 3859 return c2 >> 8 & 255; 3860}; 3861var blue = (c2)=>{ 3862 return c2 & 255; 3863}; 3864var rgbaColor = (r, g, b2, alpha)=>{ 3865 return `rgba(${r}, ${g}, ${b2}, ${alpha})`; 3866}; 3867function processColor(color) { 3868 const normalizedColor = normalizeColor(color); 3869 return (normalizedColor << 24 | normalizedColor >>> 8) >>> 0; 3870} 3871var interpolateColorsRGB = (value, inputRange, colors, options)=>{ 3872 const [r, g, b2, a2] = [ 3873 red, 3874 green, 3875 blue, 3876 opacity 3877 ].map((f)=>{ 3878 const unrounded = interpolate(value, inputRange, colors.map((c2)=>f(c2)), { 3879 easing: options?.easing, 3880 extrapolateLeft: "clamp", 3881 extrapolateRight: "clamp", 3882 posterize: options?.posterize 3883 }); 3884 if (f === opacity) { 3885 return Number(unrounded.toFixed(3)); 3886 } 3887 return Math.round(unrounded); 3888 }); 3889 return rgbaColor(r, g, b2, a2); 3890}; 3891var interpolateColors = (input, inputRange, outputRange, options)=>{ 3892 if (typeof input === "undefined") { 3893 throw new TypeError("input can not be undefined"); 3894 } 3895 if (typeof inputRange === "undefined") { 3896 throw new TypeError("inputRange can not be undefined"); 3897 } 3898 if (typeof outputRange === "undefined") { 3899 throw new TypeError("outputRange can not be undefined"); 3900 } 3901 if (inputRange.length !== outputRange.length) { 3902 throw new TypeError("inputRange (" + inputRange.length + " values provided) and outputRange (" + outputRange.length + " values provided) must have the same length"); 3903 } 3904 const processedOutputRange = outputRange.map((c2)=>processColor(c2)); 3905 return interpolateColorsRGB(input, inputRange, processedOutputRange, options); 3906}; 3907// src/interpolate-keyframed-status.ts 3908var easingToFn = ({ easing, forceSpringAllowTail })=>{ 3909 switch(easing.type){ 3910 case "linear": 3911 return Easing.linear; 3912 case "spring": 3913 return Easing.spring({ 3914 allowTail: forceSpringAllowTail ?? easing.allowTail ?? undefined, 3915 damping: easing.damping, 3916 durationRestThreshold: easing.durationRestThreshold ?? undefined, 3917 mass: easing.mass, 3918 overshootClamping: easing.overshootClamping, 3919 stiffness: easing.stiffness 3920 }); 3921 case "bezier": 3922 return bezier(easing.x1, easing.y1, easing.x2, easing.y2); 3923 default: 3924 throw new TypeError(`Unsupported easing: ${JSON.stringify(easing)}`); 3925 } 3926}; 3927var interpolateKeyframedStatus = ({ frame, forceSpringAllowTail, status })=>{ 3928 const { keyframes, easing, clamping, interpolationFunction } = status; 3929 if (keyframes.length === 0) { 3930 return null; 3931 } 3932 const sortedKeyframes = [ 3933 ...keyframes 3934 ].sort((a2, b2)=>a2.frame - b2.frame); 3935 const inputRange = sortedKeyframes.map((k)=>k.frame); 3936 const outputs = sortedKeyframes.map((k)=>k.value); 3937 if (interpolationFunction === "interpolateColors") { 3938 if (!outputs.every((v)=>typeof v === "string")) { 3939 return null; 3940 } 3941 if (keyframes.length === 1) { 3942 return outputs[0]; 3943 } 3944 try { 3945 return interpolateColors(frame, inputRange, outputs, { 3946 easing: easing.map((e)=>easingToFn({ 3947 easing: e, 3948 forceSpringAllowTail 3949 })), 3950 posterize: status.posterize 3951 }); 3952 } catch { 3953 return null; 3954 } 3955 } 3956 if (interpolationFunction !== "interpolate") { 3957 return null; 3958 } 3959 try { 3960 return interpolate(frame, inputRange, outputs, { 3961 easing: easing.map((e)=>easingToFn({ 3962 easing: e, 3963 forceSpringAllowTail 3964 })), 3965 extrapolateLeft: clamping.left, 3966 extrapolateRight: clamping.right, 3967 posterize: status.posterize 3968 }); 3969 } catch { 3970 return null; 3971 } 3972}; 3973// src/get-effective-visual-mode-value.ts 3974var resolveDragOverrideValue = ({ dragOverrideValue, frame })=>{ 3975 if (dragOverrideValue === undefined) { 3976 return { 3977 type: "none" 3978 }; 3979 } 3980 if (dragOverrideValue.type === "static") { 3981 return { 3982 type: "resolved", 3983 value: dragOverrideValue.value 3984 }; 3985 } 3986 if (frame === null) { 3987 return { 3988 type: "none" 3989 }; 3990 } 3991 const interpolated = interpolateKeyframedStatus({ 3992 forceSpringAllowTail: null, 3993 frame, 3994 status: dragOverrideValue.status 3995 }); 3996 if (interpolated === null) { 3997 return { 3998 type: "none" 3999 }; 4000 } 4001 return { 4002 type: "resolved", 4003 value: interpolated 4004 }; 4005}; 4006var getEffectiveVisualModeValue = ({ propStatus, dragOverrideValue, defaultValue, frame = null, shouldResortToDefaultValueIfUndefined = false })=>{ 4007 const dragOverride = resolveDragOverrideValue({ 4008 dragOverrideValue, 4009 frame 4010 }); 4011 if (dragOverride.type === "resolved" && dragOverride.value !== undefined) { 4012 return dragOverride.value; 4013 } 4014 if (propStatus.status === "keyframed") { 4015 if (frame !== null) { 4016 return interpolateKeyframedStatus({ 4017 forceSpringAllowTail: null, 4018 frame, 4019 status: propStatus 4020 }); 4021 }
4022 return shouldResortToDefaultValueIfUndefined ? defaultValue : undefined; 4023 } 4024 if (propStatus.codeValue === undefined && shouldResortToDefaultValueIfUndefined) { 4025 return defaultValue; 4026 } 4027 return propStatus.codeValue; 4028};
4029// src/sequence-node-path.tsx 4030 4031var OverrideIdsToNodePathsGettersContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({ 4032 overrideIdToNodePathMappings: {} 4033}); 4034var OverrideIdsToNodePathsSettersContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({ 4035 setOverrideIdToNodePath: ()=>{ 4036 throw new Error("OverrideIdsToNodePathsSettersContext not initialized"); 4037 } 4038});
vendor: 12,322 bytes, lines 4039-4395
4039// src/effects/use-memoized-effects.ts 4040var mergeOverrides = ({ descriptor, propStatusOverrides, dragOverrides, frame })=>{ 4041 if (!propStatusOverrides && !dragOverrides) { 4042 return { 4043 params: descriptor.params, 4044 effectKey: descriptor.effectKey 4045 }; 4046 } 4047 const merged = { 4048 ...descriptor.params 4049 }; 4050 if (propStatusOverrides) { 4051 for (const [key, value] of Object.entries(propStatusOverrides)){ 4052 if (value !== undefined) { 4053 merged[key] = value; 4054 } 4055 } 4056 } 4057 if (dragOverrides) { 4058 for (const [key, value] of Object.entries(dragOverrides)){ 4059 const resolved = resolveDragOverrideValue({ 4060 dragOverrideValue: value, 4061 frame 4062 }); 4063 if (resolved.type === "resolved") { 4064 merged[key] = resolved.value; 4065 } 4066 } 4067 } 4068 return { 4069 params: merged, 4070 effectKey: descriptor.definition.calculateKey(merged) 4071 }; 4072}; 4073var resolvePropStatusOverrides = (propStatus, frame)=>{ 4074 if (!propStatus) { 4075 return null; 4076 } 4077 const out = {}; 4078 let hasAny = false; 4079 for (const [key, status] of Object.entries(propStatus)){ 4080 if (status.status === "static") { 4081 out[key] = status.codeValue; 4082 hasAny = true; 4083 continue; 4084 } 4085 if (status.status === "keyframed") { 4086 const value = interpolateKeyframedStatus({ 4087 forceSpringAllowTail: null, 4088 frame, 4089 status 4090 }); 4091 if (value !== null) { 4092 out[key] = value; 4093 hasAny = true; 4094 } 4095 } 4096 } 4097 return hasAny ? out : null; 4098}; 4099var useMemoizedEffectDefinitions = (effects)=>{ 4100 const previousRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 4101 const definitions = effects.map((descriptor)=>descriptor.definition); 4102 const previous = previousRef.current; 4103 const isSame = previous !== null && previous.length === definitions.length && previous.every((def, i)=>def === definitions[i]); 4104 if (isSame) { 4105 return previous; 4106 } 4107 previousRef.current = definitions; 4108 return definitions; 4109}; 4110var getEffectPropStatusesCtx = ({ propStatuses, nodePath, effectIndex })=>{ 4111 const status = propStatuses[makeSequencePropsSubscriptionKey(nodePath)]; 4112 if (!status) { 4113 return { 4114 type: "cannot-update-sequence", 4115 reason: "not-found" 4116 }; 4117 } 4118 if (!status.canUpdate) { 4119 return { 4120 type: "cannot-update-sequence", 4121 reason: status.reason 4122 }; 4123 } 4124 const effect = status.effects.find((e)=>e.effectIndex === effectIndex); 4125 if (!effect) { 4126 return { 4127 type: "cannot-update-effect", 4128 reason: "not-found" 4129 }; 4130 } 4131 if (!effect.canUpdate) { 4132 return { 4133 type: "cannot-update-effect", 4134 reason: effect.reason 4135 }; 4136 } 4137 return { 4138 type: "can-update-effect", 4139 props: effect.props 4140 }; 4141}; 4142var getPropStatusesCtx = (propStatuses, nodePath)=>{ 4143 const status = propStatuses[makeSequencePropsSubscriptionKey(nodePath)]; 4144 if (!status) { 4145 return; 4146 } 4147 if (!status.canUpdate) { 4148 return; 4149 } 4150 return status.props; 4151}; 4152var useMemoizedEffects = ({ effects, overrideId })=>{ 4153 const previousRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 4154 const { propStatuses } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(VisualModePropStatusesContext); 4155 const { getEffectDragOverrides } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(VisualModeDragOverridesContext); 4156 const frame = useCurrentFrame(); 4157 const { overrideIdToNodePathMappings } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(OverrideIdsToNodePathsGettersContext); 4158 const previous = previousRef.current; 4159 const nodePath = overrideId ? overrideIdToNodePathMappings[overrideId] ?? null : null; 4160 const resolved = effects.map((descriptor, index)=>{ 4161 if (nodePath === null) { 4162 return { 4163 descriptor, 4164 params: descriptor.params, 4165 effectKey: descriptor.effectKey 4166 }; 4167 } 4168 const effectStatus = getEffectPropStatusesCtx({ 4169 propStatuses, 4170 nodePath, 4171 effectIndex: index 4172 }); 4173 const propStatusOverrides = effectStatus.type === "can-update-effect" ? resolvePropStatusOverrides(effectStatus.props, frame) : null; 4174 const dragOverridesMap = getEffectDragOverrides(nodePath, index); 4175 const dragOverrides = Object.keys(dragOverridesMap).length === 0 ? null : dragOverridesMap; 4176 const { params, effectKey } = mergeOverrides({ 4177 descriptor, 4178 propStatusOverrides, 4179 dragOverrides, 4180 frame 4181 }); 4182 return { 4183 descriptor, 4184 params, 4185 effectKey 4186 }; 4187 }); 4188 const isSame = previous !== null && previous.length === resolved.length && previous.every((p, i)=>p.definition === resolved[i].descriptor.definition && p.effectKey === resolved[i].effectKey); 4189 if (isSame) { 4190 return previous; 4191 } 4192 const next = resolved.map(({ descriptor, params, effectKey })=>({ 4193 definition: descriptor.definition, 4194 effectKey, 4195 params, 4196 memoized: true 4197 })); 4198 previousRef.current = next; 4199 return next; 4200}; 4201// src/flatten-schema.ts 4202var flattenActiveSchema = (schema, resolve)=>{ 4203 const out = {}; 4204 for (const key of Object.keys(schema)){ 4205 const field = schema[key]; 4206 if (field.type === "hidden") { 4207 continue; 4208 } else if (field.type === "enum") { 4209 out[key] = field; 4210 const current = resolve(key) ?? field.default; 4211 const variant = field.variants[current]; 4212 if (variant) { 4213 Object.assign(out, flattenActiveSchema(variant, resolve)); 4214 } 4215 } else { 4216 out[key] = field; 4217 } 4218 } 4219 return out; 4220}; 4221var getFlatSchemaWithAllKeys = (schema)=>{ 4222 const out = {}; 4223 const addKey = (key, field)=>{ 4224 if (key in out) { 4225 throw new Error(`Duplicate key "${key}" in schema: discriminated union variants must not share keys`); 4226 } 4227 out[key] = field; 4228 }; 4229 for (const key of Object.keys(schema)){ 4230 const field = schema[key]; 4231 addKey(key, field); 4232 if (field.type === "enum") { 4233 for (const variant of Object.values(field.variants)){ 4234 const flatVariant = getFlatSchemaWithAllKeys(variant); 4235 for (const variantKey of Object.keys(flatVariant)){ 4236 addKey(variantKey, flatVariant[variantKey]); 4237 } 4238 } 4239 } 4240 } 4241 return out; 4242}; 4243// src/find-props-to-delete.ts 4244var findPropsToDelete = ({ schema, key, value })=>{ 4245 const fieldSchema = schema[key]; 4246 if (!fieldSchema) { 4247 throw new Error("Key " + JSON.stringify(key) + " not found in schema"); 4248 } 4249 if (typeof value !== "string") { 4250 throw new Error("Value must be a string, but is " + JSON.stringify(value)); 4251 } 4252 if (fieldSchema.type !== "enum") { 4253 throw new Error("Key " + JSON.stringify(key) + " is not an enum"); 4254 } 4255 const currentVariant = fieldSchema.variants[value]; 4256 if (!currentVariant) { 4257 throw new Error("Value for " + JSON.stringify(key) + " must be one of " + Object.keys(fieldSchema.variants).map((v)=>JSON.stringify(v)).join(", ") + ", got " + JSON.stringify(value)); 4258 } 4259 const otherVariants = Object.keys(fieldSchema.variants).filter((v)=>v !== value); 4260 const otherKeys = new Set; 4261 for (const variant of otherVariants){ 4262 const otherVariant = fieldSchema.variants[variant]; 4263 const keys = Object.keys(otherVariant); 4264 for (const k of keys){ 4265 otherKeys.add(k); 4266 } 4267 } 4268 return [ 4269 ...otherKeys 4270 ]; 4271}; 4272// src/use-schema.ts 4273var DEFAULT_LINEAR_EASING = { 4274 type: "linear" 4275}; 4276var getEasingIndexToDuplicate = ({ insertedKeyframeIndex, easingLength, keyframeCount })=>{ 4277 const isSplittingExistingSegment = insertedKeyframeIndex > 0 && insertedKeyframeIndex < keyframeCount - 1; 4278 if (!isSplittingExistingSegment || easingLength === 0) { 4279 return null; 4280 } 4281 return Math.min(insertedKeyframeIndex - 1, easingLength - 1); 4282}; 4283var makeStaticDragOverride = (value)=>{ 4284 return { 4285 type: "static", 4286 value 4287 }; 4288}; 4289var makeKeyframedDragOverride = ({ status, frame, value })=>{ 4290 const existingIndex = status.keyframes.findIndex((keyframe)=>keyframe.frame === frame); 4291 const keyframes = existingIndex === -1 ? [ 4292 ...status.keyframes, 4293 { 4294 frame, 4295 value 4296 } 4297 ].sort((first, second)=>first.frame - second.frame) : status.keyframes.map((keyframe, index)=>index === existingIndex ? { 4298 frame, 4299 value 4300 } : keyframe); 4301 const easing = [ 4302 ...status.easing 4303 ]; 4304 if (existingIndex === -1) { 4305 const insertedKeyframeIndex = keyframes.findIndex((keyframe)=>keyframe.frame === frame); 4306 const easingIndexToDuplicate = getEasingIndexToDuplicate({ 4307 insertedKeyframeIndex, 4308 easingLength: easing.length, 4309 keyframeCount: keyframes.length 4310 }); 4311 const easingToDuplicate = easingIndexToDuplicate === null ? DEFAULT_LINEAR_EASING : easing[easingIndexToDuplicate]; 4312 easing.splice(insertedKeyframeIndex, 0, easingToDuplicate); 4313 } 4314 while(easing.length < keyframes.length - 1){ 4315 easing.push(DEFAULT_LINEAR_EASING); 4316 } 4317 if (easing.length > keyframes.length - 1) { 4318 easing.length = keyframes.length - 1; 4319 } 4320 return { 4321 type: "keyframed", 4322 status: { 4323 ...status, 4324 keyframes, 4325 easing 4326 } 4327 }; 4328}; 4329var getStaticDragOverrideValue = (dragOverrideValue)=>{ 4330 if (dragOverrideValue?.type !== "static") { 4331 return; 4332 } 4333 return dragOverrideValue.value; 4334}; 4335var isKeyframedStatus = (status)=>{ 4336 return status !== null && status.status === "keyframed"; 4337}; 4338var findFieldInSchema = (schema, key)=>{ 4339 if (key in schema) { 4340 return schema[key]; 4341 } 4342 for (const field of Object.values(schema)){ 4343 if (field.type !== "enum") { 4344 continue; 4345 } 4346 for (const variant of Object.values(field.variants)){ 4347 const found = findFieldInSchema(variant, key); 4348 if (found) { 4349 return found; 4350 } 4351 } 4352 } 4353 return; 4354}; 4355var computeEffectiveSchemaValuesDotNotation = ({ schema, currentValue, overrideValues, propStatus, frame })=>{ 4356 const merged = {}; 4357 const propsToDelete = new Set; 4358 for (const key of Object.keys(currentValue)){ 4359 const status = propStatus?.[key] ?? null; 4360 const field = findFieldInSchema(schema, key); 4361 if (field?.type === "hidden") { 4362 continue; 4363 } 4364 let value; 4365 if (status === null) { 4366 value = currentValue[key]; 4367 } else if (isKeyframedStatus(status)) { 4368 if (field?.type === "array" || field?.keyframable === false) { 4369 value = currentValue[key]; 4370 } else { 4371 const dragOverride = resolveDragOverrideValue({ 4372 dragOverrideValue: overrideValues[key], 4373 frame 4374 }); 4375 if (dragOverride.type === "resolved") { 4376 value = dragOverride.value; 4377 } else if (frame !== null) { 4378 const interpolated = interpolateKeyframedStatus({ 4379 forceSpringAllowTail: null, 4380 frame, 4381 status 4382 }); 4383 value = interpolated ?? currentValue[key]; 4384 } else { 4385 value = currentValue[key]; 4386 } 4387 } 4388 } else if (status.status === "computed") { 4389 value = currentValue[key]; 4390 } else { 4391 value = getEffectiveVisualModeValue({ 4392 propStatus: status, 4393 dragOverrideValue: overrideValues[key], 4394 defaultValue: field?.default, 4395 frame,
4396 shouldResortToDefaultValueIfUndefined: false 4397 }); 4398 } 4399 if (value === undefined) { 4400 propsToDelete.add(key); 4401 } 4402 merged[key] = value; 4403 } 4404 for (const key of Object.keys(overrideValues)){ 4405 if (schema[key]?.type === "enum") { 4406 const propsToDeleteForKey = findPropsToDelete({ 4407 schema, 4408 key, 4409 value: merged[key] 4410 }); 4411 for (const propToDelete of propsToDeleteForKey){ 4412 propsToDelete.add(propToDelete); 4413 } 4414 } 4415 } 4416 return { 4417 merged, 4418 propsToDelete 4419 }; 4420};
vendor: 6,138 bytes, lines 4421-4574
4421// src/with-interactivity-schema.ts 4422var getNestedValue = (obj, key)=>{ 4423 const parts = key.split("."); 4424 let current = obj; 4425 for (const part of parts){ 4426 if (current === null || current === undefined || typeof current !== "object") return; 4427 current = current[part]; 4428 } 4429 return current; 4430}; 4431var getRuntimeValueForSchemaKey = ({ flatSchema, key, props })=>{ 4432 const value = getNestedValue(props, key); 4433 if (flatSchema[key]?.type === "text-content" && typeof value !== "string") { 4434 return; 4435 } 4436 return value; 4437}; 4438var readValuesFromProps = (props, keys, flatSchema)=>{ 4439 const out = {}; 4440 for (const key of keys){ 4441 out[key] = flatSchema ? getRuntimeValueForSchemaKey({ 4442 flatSchema, 4443 key, 4444 props 4445 }) : getNestedValue(props, key); 4446 } 4447 return out; 4448}; 4449var selectActiveKeys = (schema, values)=>{ 4450 return Object.keys(flattenActiveSchema(schema, (key)=>values[key])); 4451}; 4452var mergeValues = ({ flatSchema, props, valuesDotNotation, schemaKeys, propsToDelete })=>{ 4453 const merged = { 4454 ...props 4455 }; 4456 for (const key of schemaKeys){ 4457 const value = valuesDotNotation[key]; 4458 if (flatSchema[key]?.type === "text-content" && value === undefined) { 4459 continue; 4460 } 4461 const parts = key.split("."); 4462 if (parts.length === 1) { 4463 merged[key] = value; 4464 continue; 4465 } 4466 let current = merged; 4467 for(let i = 0; i < parts.length - 1; i++){ 4468 const part = parts[i]; 4469 if (typeof current[part] === "object" && current[part] !== null) { 4470 current[part] = { 4471 ...current[part] 4472 }; 4473 } else { 4474 current[part] = {}; 4475 } 4476 current = current[part]; 4477 } 4478 current[parts[parts.length - 1]] = value; 4479 } 4480 const propsToDeleteWithoutTextContent = new Set([ 4481 ...propsToDelete 4482 ].filter((key)=>!(flatSchema[key]?.type === "text-content" && valuesDotNotation[key] === undefined))); 4483 deleteNestedKey(merged, propsToDeleteWithoutTextContent); 4484 return merged; 4485}; 4486var stackToOverrideMap = {}; 4487var withInteractivitySchema = ({ Component, componentName, componentIdentity, schema, supportsEffects })=>{ 4488 const schemaWithSequenceName = extendSchemaWithSequenceName(schema); 4489 const flatSchema = getFlatSchemaWithAllKeys(schemaWithSequenceName); 4490 const flatKeys = Object.keys(flatSchema); 4491 const Wrapped = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)((props, ref)=>{ 4492 const env = useRemotionEnvironment(); 4493 if (!env.isStudio || env.isReadOnlyStudio || env.isRendering) { 4494 return /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createElement(Component, { 4495 ...props, 4496 controls: null, 4497 ref 4498 }); 4499 } 4500 const { propStatuses } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(VisualModePropStatusesContext); 4501 const { getDragOverrides } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(VisualModeDragOverridesContext); 4502 const nodePathMapping = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(OverrideIdsToNodePathsGettersContext); 4503 const frame = useCurrentFrame(); 4504 if (props.controls) { 4505 return /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createElement(Component, { 4506 ...props, 4507 ref 4508 }); 4509 } 4510 const [overrideId] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(()=>{ 4511 const { stack } = props; 4512 if (!stack) { 4513 return String(Math.random()); 4514 } 4515 const existingOverrideId = stackToOverrideMap[stack]; 4516 if (existingOverrideId) { 4517 return existingOverrideId; 4518 } 4519 const newOverrideId = String(Math.random()); 4520 stackToOverrideMap[stack] = newOverrideId; 4521 return newOverrideId; 4522 }); 4523 const nodePath = nodePathMapping.overrideIdToNodePathMappings[overrideId] ?? null; 4524 const runtimeValues = flatKeys.map((key)=>getRuntimeValueForSchemaKey({ 4525 flatSchema, 4526 key, 4527 props 4528 })); 4529 const currentRuntimeValueDotNotation = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>readValuesFromProps(props, flatKeys, flatSchema), runtimeValues); 4530 const controls = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 4531 return { 4532 schema: schemaWithSequenceName, 4533 currentRuntimeValueDotNotation, 4534 overrideId, 4535 supportsEffects, 4536 componentIdentity, 4537 componentName 4538 }; 4539 }, [ 4540 currentRuntimeValueDotNotation, 4541 overrideId 4542 ]); 4543 const { merged: valuesDotNotation, propsToDelete } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 4544 return computeEffectiveSchemaValuesDotNotation({ 4545 schema: schemaWithSequenceName, 4546 currentValue: currentRuntimeValueDotNotation, 4547 overrideValues: nodePath === null ? {} : getDragOverrides(nodePath), 4548 propStatus: nodePath === null ? undefined : getPropStatusesCtx(propStatuses, nodePath), 4549 frame 4550 }); 4551 }, [ 4552 currentRuntimeValueDotNotation, 4553 getDragOverrides, 4554 nodePath, 4555 propStatuses, 4556 frame 4557 ]); 4558 const activeKeys = selectActiveKeys(schemaWithSequenceName, valuesDotNotation); 4559 const mergedProps = mergeValues({ 4560 flatSchema, 4561 props, 4562 valuesDotNotation, 4563 schemaKeys: activeKeys, 4564 propsToDelete 4565 }); 4566 return /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createElement(Component, { 4567 ...mergedProps, 4568 controls, 4569 ref 4570 }); 4571 }); 4572 Wrapped.displayName = `withInteractivitySchema(${Component.displayName || Component.name || "Component"})`; 4573 return Wrapped; 4574};
4575// src/Sequence.tsx 4576 4577var EMPTY_EFFECTS = []; 4578var RegularSequenceRefForwardingFunction = ({ from = 0, trimBefore = 0, freeze, durationInFrames = Infinity, children, name, height, width, showInTimeline = true, hidden = false, controls, _remotionInternalEffects, _remotionInternalLoopDisplay: loopDisplay, _remotionInternalStack: stack, _remotionInternalDocumentationLink: documentationLink, _remotionInternalPremountDisplay: premountDisplay, _remotionInternalPostmountDisplay: postmountDisplay, _remotionInternalIsMedia: isMedia, outlineRef: passedRefForOutline, ...other }, ref)=>{ 4579 const { layout = "absolute-fill" } = other; 4580 const [id] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(()=>String(Math.random())); 4581 const parentSequence = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SequenceContext); 4582 const { rootId } = useTimelineContext(); 4583 const cumulatedFrom = parentSequence ? parentSequence.cumulatedFrom + parentSequence.relativeFrom : 0; 4584 const nonce = useNonce(); 4585 if (layout !== "absolute-fill" && layout !== "none") { 4586 throw new TypeError(`The layout prop of <Sequence /> expects either "absolute-fill" or "none", but you passed: ${layout}`); 4587 } 4588 if (layout === "none" && typeof other.style !== "undefined") { 4589 throw new TypeError('If layout="none", you may not pass a style. Passed: ' + JSON.stringify(other.style)); 4590 } 4591 if (typeof durationInFrames !== "number") { 4592 throw new TypeError(`You passed to durationInFrames an argument of type ${typeof durationInFrames}, but it must be a number.`); 4593 } 4594 if (durationInFrames <= 0) { 4595 throw new TypeError(`durationInFrames must be positive, but got ${durationInFrames}`); 4596 } 4597 if (typeof from !== "number") { 4598 throw new TypeError(`You passed to the "from" props of your <Sequence> an argument of type ${typeof from}, but it must be a number.`); 4599 } 4600 if (!Number.isFinite(from)) { 4601 throw new TypeError(`The "from" prop of a sequence must be finite, but got ${from}.`); 4602 } 4603 if (typeof trimBefore !== "number") { 4604 throw new TypeError(`You passed to the "trimBefore" prop of your <Sequence> an argument of type ${typeof trimBefore}, but it must be a number.`); 4605 } 4606 if (trimBefore < 0) { 4607 throw new TypeError(`The "trimBefore" prop of <Sequence /> must be greater than or equal to 0, but got ${trimBefore}.`); 4608 } 4609 if (Number.isNaN(trimBefore)) { 4610 throw new TypeError('The "trimBefore" prop of <Sequence /> must be a real number, but it is NaN.'); 4611 } 4612 if (!Number.isFinite(trimBefore)) { 4613 throw new TypeError(`The "trimBefore" prop of <Sequence /> must be finite, but it is ${trimBefore}.`); 4614 } 4615 if (typeof freeze !== "undefined" && freeze !== null) { 4616 if (typeof freeze !== "number") { 4617 throw new TypeError(`The "freeze" prop of <Sequence /> must be a number, but is of type ${typeof freeze}.`); 4618 } 4619 if (Number.isNaN(freeze)) { 4620 throw new TypeError(`The "freeze" prop of <Sequence /> must be a real number, but it is NaN.`); 4621 } 4622 if (!Number.isFinite(freeze)) { 4623 throw new TypeError(`The "freeze" prop of <Sequence /> must be finite, but it is ${freeze}.`); 4624 } 4625 } 4626 const absoluteFrame = useTimelinePosition(); 4627 const videoConfig = useVideoConfig(); 4628 const effectiveRelativeFrom = from - trimBefore; 4629 const absoluteFrom = (parentSequence?.absoluteFrom ?? 0) + effectiveRelativeFrom; 4630 const parentSequenceDuration = parentSequence ? Math.min(parentSequence.durationInFrames - effectiveRelativeFrom, durationInFrames) : durationInFrames; 4631 const actualDurationInFrames = Math.max(0, Math.min(videoConfig.durationInFrames - from, parentSequenceDuration)); 4632 const { registerSequence, unregisterSequence } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SequenceManager); 4633 const wrapperRefForOutline = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 4634 const refForOutline = other.layout === "none" ? passedRefForOutline ?? null : passedRefForOutline ?? wrapperRefForOutline;
4635 const premounting = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 4636 return parentSequence?.premounting || Boolean(other._remotionInternalIsPremounting); 4637 }, [ 4638 other._remotionInternalIsPremounting, 4639 parentSequence?.premounting 4640 ]); 4641 const postmounting = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 4642 return parentSequence?.postmounting || Boolean(other._remotionInternalIsPostmounting); 4643 }, [ 4644 other._remotionInternalIsPostmounting, 4645 parentSequence?.postmounting 4646 ]); 4647 const currentSequenceStart = cumulatedFrom + effectiveRelativeFrom; 4648 const parentSequenceStart = parentSequence ? parentSequence.cumulatedFrom + parentSequence.relativeFrom : 0; 4649 const parentFirstFrame = parentSequence ? parentSequenceStart - parentSequence.cumulatedNegativeFrom : 0; 4650 const firstFrame = Math.max(0, parentFirstFrame, currentSequenceStart); 4651 const cumulatedNegativeFrom = currentSequenceStart - firstFrame; 4652 const contextValue = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 4653 return { 4654 absoluteFrom, 4655 cumulatedFrom, 4656 relativeFrom: effectiveRelativeFrom, 4657 cumulatedNegativeFrom, 4658 durationInFrames: actualDurationInFrames, 4659 parentFrom: parentSequence?.relativeFrom ?? 0, 4660 id, 4661 height: height ?? parentSequence?.height ?? null, 4662 width: width ?? parentSequence?.width ?? null, 4663 premounting, 4664 postmounting, 4665 premountDisplay: premountDisplay ?? null, 4666 postmountDisplay: postmountDisplay ?? null 4667 }; 4668 }, [ 4669 cumulatedFrom, 4670 absoluteFrom, 4671 effectiveRelativeFrom, 4672 actualDurationInFrames, 4673 parentSequence, 4674 id, 4675 height, 4676 width, 4677 premounting, 4678 postmounting, 4679 premountDisplay, 4680 postmountDisplay, 4681 cumulatedNegativeFrom 4682 ]); 4683 const timelineClipName = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 4684 return name ?? ""; 4685 }, [ 4686 name 4687 ]); 4688 const resolvedDocumentationLink = documentationLink ?? "https://www.remotion.dev/docs/sequence"; 4689 const env = useRemotionEnvironment(); 4690 const isInsideSeries = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(IsInsideSeriesContext); 4691 const inheritedStack = other?.stack ?? null; 4692 const stackRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 4693 stackRef.current = stack ?? inheritedStack; 4694 const registeredFrozenFrame = typeof freeze === "number" ? freeze : null; 4695 const registeredTrimBefore = trimBefore === 0 ? null : trimBefore; 4696 const parentCumulatedNegativeFrom = parentSequence?.cumulatedNegativeFrom ?? 0; 4697 const startMediaFrom = isMedia && isMedia.type !== "image" ? isMedia.data.startMediaFrom + parentCumulatedNegativeFrom - cumulatedNegativeFrom : null; 4698 const mediaFrameAtSequenceZero = isMedia && isMedia.type !== "image" ? isMedia.data.startMediaFrom + parentCumulatedNegativeFrom : null; 4699 const frozenMediaFrame = isMedia && isMedia.type !== "image" && mediaFrameAtSequenceZero !== null ? registeredFrozenFrame === null ? null : mediaFrameAtSequenceZero + (loopDisplay ? registeredFrozenFrame % loopDisplay.durationInFrames : registeredFrozenFrame) * isMedia.data.playbackRate : null; 4700 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 4701 if (!env.isStudio) { 4702 return; 4703 } 4704 if (isMedia) { 4705 if (isMedia.type === "image") { 4706 registerSequence({ 4707 type: "image", 4708 controls: controls ?? null, 4709 effects: _remotionInternalEffects ?? EMPTY_EFFECTS, 4710 displayName: timelineClipName, 4711 documentationLink: resolvedDocumentationLink, 4712 duration: actualDurationInFrames, 4713 from, 4714 trimBefore: registeredTrimBefore, 4715 id, 4716 loopDisplay, 4717 nonce: nonce.get(), 4718 parent: parentSequence?.id ?? null, 4719 postmountDisplay: postmountDisplay ?? null,
4720 premountDisplay: premountDisplay ?? null, 4721 rootId, 4722 showInTimeline, 4723 src: isMedia.src, 4724 getStack: ()=>stackRef.current, 4725 refForOutline: refForOutline ?? null, 4726 isInsideSeries, 4727 frozenFrame: registeredFrozenFrame 4728 }); 4729 } else { 4730 registerSequence({ 4731 type: isMedia.type, 4732 controls: controls ?? null, 4733 effects: _remotionInternalEffects ?? EMPTY_EFFECTS, 4734 displayName: timelineClipName, 4735 documentationLink: resolvedDocumentationLink, 4736 doesVolumeChange: isMedia.data.doesVolumeChange, 4737 duration: actualDurationInFrames, 4738 from, 4739 trimBefore: registeredTrimBefore, 4740 id, 4741 loopDisplay, 4742 nonce: nonce.get(), 4743 parent: parentSequence?.id ?? null, 4744 playbackRate: isMedia.data.playbackRate, 4745 postmountDisplay: postmountDisplay ?? null, 4746 premountDisplay: premountDisplay ?? null, 4747 rootId, 4748 showInTimeline, 4749 src: isMedia.data.src, 4750 getStack: ()=>stackRef.current, 4751 startMediaFrom: startMediaFrom ?? isMedia.data.startMediaFrom, 4752 volume: isMedia.data.volumes, 4753 refForOutline: refForOutline ?? null, 4754 isInsideSeries, 4755 frozenFrame: registeredFrozenFrame, 4756 frozenMediaFrame 4757 }); 4758 } 4759 return ()=>{ 4760 unregisterSequence(id); 4761 }; 4762 } 4763 registerSequence({ 4764 from, 4765 trimBefore: registeredTrimBefore, 4766 duration: actualDurationInFrames, 4767 id, 4768 displayName: timelineClipName, 4769 documentationLink: resolvedDocumentationLink, 4770 parent: parentSequence?.id ?? null, 4771 type: "sequence", 4772 rootId, 4773 showInTimeline, 4774 nonce: nonce.get(), 4775 loopDisplay, 4776 getStack: ()=>stackRef.current, 4777 premountDisplay: premountDisplay ?? null, 4778 postmountDisplay: postmountDisplay ?? null, 4779 controls: controls ?? null, 4780 effects: _remotionInternalEffects ?? EMPTY_EFFECTS, 4781 refForOutline: refForOutline ?? null, 4782 isInsideSeries, 4783 frozenFrame: registeredFrozenFrame 4784 }); 4785 return ()=>{ 4786 unregisterSequence(id); 4787 }; 4788 }, [ 4789 durationInFrames, 4790 id, 4791 name, 4792 registerSequence, 4793 timelineClipName, 4794 unregisterSequence, 4795 parentSequence?.id, 4796 actualDurationInFrames, 4797 rootId, 4798 from, 4799 trimBefore, 4800 registeredTrimBefore, 4801 showInTimeline, 4802 nonce, 4803 loopDisplay, 4804 premountDisplay, 4805 postmountDisplay, 4806 env.isStudio, 4807 controls, 4808 _remotionInternalEffects, 4809 isMedia, 4810 resolvedDocumentationLink, 4811 refForOutline, 4812 isInsideSeries, 4813 registeredFrozenFrame, 4814 startMediaFrom, 4815 frozenMediaFrame 4816 ]); 4817 const endThreshold = Math.ceil(cumulatedFrom + from + durationInFrames - 1); 4818 const content = absoluteFrame < cumulatedFrom + from ? null : absoluteFrame > endThreshold ? null : children; 4819 const frozenContent = content === null || typeof freeze === "undefined" || freeze === null ? content : /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Freeze, { 4820 frame: freeze, 4821 children: content 4822 }); 4823 const styleIfThere = other.layout === "none" ? undefined : other.style; 4824 const sequenceRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((node)=>{ 4825 wrapperRefForOutline.current = node; 4826 if (typeof ref === "function") { 4827 ref(node); 4828 } else if (ref) { 4829 ref.current = node; 4830 } 4831 }, [ 4832 ref 4833 ]); 4834 const defaultStyle = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 4835 return { 4836 flexDirection: undefined, 4837 ...width ? {
4838 width 4839 } : {}, 4840 ...height ? { 4841 height 4842 } : {}, 4843 ...styleIfThere ?? {} 4844 }; 4845 }, [ 4846 height, 4847 styleIfThere, 4848 width 4849 ]); 4850 if (ref !== null && layout === "none") { 4851 throw new TypeError('It is not supported to pass both a `ref` and `layout="none"` to <Sequence />.'); 4852 } 4853 if (hidden) { 4854 return null; 4855 } 4856 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(SequenceContext.Provider, { 4857 value: contextValue, 4858 children: frozenContent === null ? null : other.layout === "none" ? frozenContent : /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(AbsoluteFill, { 4859 ref: sequenceRef, 4860 style: defaultStyle, 4861 className: other.className, 4862 children: frozenContent 4863 }) 4864 }); 4865}; 4866var RegularSequence = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(RegularSequenceRefForwardingFunction); 4867var PremountedPostmountedSequenceRefForwardingFunction = (props, ref)=>{ 4868 const parentPremountContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(PremountContext); 4869 const frame = useCurrentFrame() - parentPremountContext.premountFramesRemaining; 4870 if (props.layout === "none") { 4871 throw new Error('`<Sequence>` with `premountFor` and `postmountFor` props does not support layout="none"'); 4872 } 4873 const { style: passedStyle, from = 0, durationInFrames = Infinity, premountFor = 0, postmountFor = 0, styleWhilePremounted, styleWhilePostmounted, ...otherProps } = props; 4874 const endThreshold = Math.ceil(from + durationInFrames - 1); 4875 const premountingActive = frame < from && frame >= from - premountFor; 4876 const postmountingActive = frame > endThreshold && frame <= endThreshold + postmountFor; 4877 const freezeFrame = premountingActive ? from : postmountingActive ? from + durationInFrames - 1 : 0; 4878 const isFreezingActive = premountingActive || postmountingActive; 4879 const style = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 4880 return { 4881 ...passedStyle, 4882 opacity: premountingActive || postmountingActive ? 0 : 1, 4883 pointerEvents: premountingActive || postmountingActive ? "none" : passedStyle?.pointerEvents ?? undefined, 4884 ...premountingActive ? styleWhilePremounted : {}, 4885 ...postmountingActive ? styleWhilePostmounted : {} 4886 }; 4887 }, [ 4888 passedStyle, 4889 premountingActive, 4890 postmountingActive, 4891 styleWhilePremounted, 4892 styleWhilePostmounted 4893 ]); 4894 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Freeze, { 4895 frame: freezeFrame, 4896 active: isFreezingActive, 4897 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(SequenceInner, { 4898 ref, 4899 from, 4900 durationInFrames, 4901 style, 4902 _remotionInternalPremountDisplay: premountFor, 4903 _remotionInternalPostmountDisplay: postmountFor, 4904 _remotionInternalIsPremounting: premountingActive, 4905 _remotionInternalIsPostmounting: postmountingActive, 4906 ...otherProps 4907 }) 4908 }); 4909}; 4910var PremountedPostmountedSequence = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(PremountedPostmountedSequenceRefForwardingFunction); 4911var SequenceRefForwardingFunction = (props, ref)=>{ 4912 const env = useRemotionEnvironment(); 4913 const { fps } = useVideoConfig(); 4914 if (props.layout !== "none" && !env.isRendering) { 4915 const effectivePremountFor = ENABLE_V5_BREAKING_CHANGES ? props.premountFor ?? fps : props.premountFor; 4916 if (effectivePremountFor || props.postmountFor) { 4917 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(PremountedPostmountedSequence, { 4918 ref, 4919 ...props, 4920 premountFor: effectivePremountFor 4921 }); 4922 } 4923 } 4924 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(RegularSequence, { 4925 ...props, 4926 ref 4927 }); 4928}; 4929var SequenceInner = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SequenceRefForwardingFunction); 4930var SequenceWithoutSchema = SequenceInner; 4931var Sequence = withInteractivitySchema({ 4932 Component: SequenceInner, 4933 componentName: "<Sequence>", 4934 componentIdentity: "dev.remotion.remotion.Sequence", 4935 schema: sequenceSchema, 4936 supportsEffects: false 4937}); 4938var SequenceWithoutFrom = withInteractivitySchema({ 4939 Component: SequenceInner, 4940 componentName: "<Sequence>", 4941 componentIdentity: null, 4942 schema: sequenceSchemaWithoutFrom, 4943 supportsEffects: false 4944});
4945// src/animated-image/AnimatedImage.tsx 4946
4947// src/animated-image/canvas.tsx 4948
vendor: 1,805 bytes, lines 4949-5000
4949// src/calculate-image-fit.ts 4950var calculateImageFit = (fit, imageSize, canvasSize)=>{ 4951 switch(fit){ 4952 case "fill": 4953 { 4954 return [ 4955 0, 4956 0, 4957 imageSize.width, 4958 imageSize.height, 4959 0, 4960 0, 4961 canvasSize.width, 4962 canvasSize.height 4963 ]; 4964 } 4965 case "contain": 4966 { 4967 const ratio = Math.min(canvasSize.width / imageSize.width, canvasSize.height / imageSize.height); 4968 const centerX = (canvasSize.width - imageSize.width * ratio) / 2; 4969 const centerY = (canvasSize.height - imageSize.height * ratio) / 2; 4970 return [ 4971 0, 4972 0, 4973 imageSize.width, 4974 imageSize.height, 4975 centerX, 4976 centerY, 4977 imageSize.width * ratio, 4978 imageSize.height * ratio 4979 ]; 4980 } 4981 case "cover": 4982 { 4983 const ratio = Math.max(canvasSize.width / imageSize.width, canvasSize.height / imageSize.height); 4984 const centerX = (canvasSize.width - imageSize.width * ratio) / 2; 4985 const centerY = (canvasSize.height - imageSize.height * ratio) / 2; 4986 return [ 4987 0, 4988 0, 4989 imageSize.width, 4990 imageSize.height, 4991 centerX, 4992 centerY, 4993 imageSize.width * ratio, 4994 imageSize.height * ratio 4995 ]; 4996 } 4997 default: 4998 throw new Error("Unknown fit: " + fit); 4999 } 5000};
5001// src/effects/webgl2-context-error.ts 5002var WEBGL_CONTEXT_DOCS_URL = "https://remotion.dev/docs/troubleshooting/webgl2-context"; 5003var webGlContextErrorMessage = (versionLabel, effectName)=>`Failed to acquire ${versionLabel} context for ${effectName}. ` + 'Pass --gl=angle when using the CLI, set chromiumOptions: { gl: "angle" } when using SSR APIs, ' + 'or set "OpenGL render backend" to "angle" in the Advanced section when rendering in the Studio. ' + `See ${WEBGL_CONTEXT_DOCS_URL}`; 5004var createWebGLContextError = (effectName)=>new Error(webGlContextErrorMessage("WebGL", effectName)); 5005var createWebGL2ContextError = (effectName)=>new Error(webGlContextErrorMessage("WebGL2", effectName));
vendor: 2,824 bytes, lines 5006-5080
5006// src/effects/canvas-pool.ts 5007class CanvasPool { 5008 constructor(width, height){ 5009 this.pairs = new Map; 5010 this.lostContexts = new Set; 5011 this.width = width; 5012 this.height = height; 5013 } 5014 getPair(backend) { 5015 const existing = this.pairs.get(backend); 5016 if (existing) { 5017 return existing; 5018 } 5019 const pair = [ 5020 this.allocateCanvas(backend), 5021 this.allocateCanvas(backend) 5022 ]; 5023 this.pairs.set(backend, pair); 5024 return pair; 5025 } 5026 assertContextNotLost(canvas) { 5027 if (this.lostContexts.has(canvas)) { 5028 throw new Error("WebGL context was lost during canvas effect rendering. " + "This typically happens in headless or memory-constrained environments (e.g. Remotion Lambda). " + "Try reducing concurrency or increasing the Lambda function memory."); 5029 } 5030 } 5031 allocateCanvas(backend) { 5032 const canvas = document.createElement("canvas"); 5033 canvas.width = this.width; 5034 canvas.height = this.height; 5035 switch(backend){ 5036 case "2d": 5037 { 5038 const ctx = canvas.getContext("2d", { 5039 colorSpace: "srgb" 5040 }); 5041 if (!ctx) { 5042 throw new Error("Failed to acquire 2D context for canvas effect"); 5043 } 5044 return canvas; 5045 } 5046 case "webgl2": 5047 { 5048 const ctx = canvas.getContext("webgl2", { 5049 premultipliedAlpha: true, 5050 alpha: true, 5051 preserveDrawingBuffer: true 5052 }); 5053 if (!ctx) { 5054 throw createWebGL2ContextError("canvas effect"); 5055 } 5056 canvas.addEventListener("webglcontextlost", (e)=>{ 5057 e.preventDefault(); 5058 this.lostContexts.add(canvas); 5059 }); 5060 canvas.addEventListener("webglcontextrestored", ()=>{ 5061 this.lostContexts.delete(canvas); 5062 }); 5063 ctx.pixelStorei(ctx.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true); 5064 return canvas; 5065 } 5066 case "webgpu": 5067 { 5068 if (typeof navigator === "undefined" || !("gpu" in navigator)) { 5069 throw new Error("WebGPU is not available in this environment for canvas effect"); 5070 } 5071 return canvas; 5072 } 5073 default: 5074 { 5075 const exhaustive = backend; 5076 throw new Error(`Unknown effect backend: ${exhaustive}`); 5077 } 5078 } 5079 } 5080}
5081// src/effects/effect-internals.ts 5082var groupByBackend = (effects)=>{ 5083 const runs = []; 5084 let current = []; 5085 let currentBackend = null; 5086 for (const eff of effects){ 5087 const { backend } = eff.definition; 5088 if (currentBackend === null || backend === currentBackend) { 5089 current.push(eff); 5090 currentBackend = backend; 5091 } else { 5092 runs.push({ 5093 backend: currentBackend, 5094 effects: current 5095 }); 5096 current = [ 5097 eff 5098 ]; 5099 currentBackend = backend; 5100 } 5101 } 5102 if (currentBackend !== null && current.length > 0) { 5103 runs.push({ 5104 backend: currentBackend, 5105 effects: current 5106 }); 5107 } 5108 return runs; 5109};
5110// src/effects/gpu-device.ts 5111var devicePromise = null; 5112var getGpuDevice = ()=>{ 5113 if (devicePromise) { 5114 return devicePromise; 5115 } 5116 devicePromise = (async ()=>{ 5117 if (typeof navigator === "undefined" || !("gpu" in navigator)) { 5118 throw new Error("WebGPU is not available in this environment"); 5119 } 5120 const { gpu } = navigator; 5121 const adapter = await gpu.requestAdapter(); 5122 if (!adapter) { 5123 throw new Error("No WebGPU adapter available"); 5124 } 5125 return adapter.requestDevice(); 5126 })(); 5127 return devicePromise; 5128};
vendor: 3,946 bytes, lines 5129-5244
5129// src/effects/run-effect-chain.ts 5130var createEffectChainState = (width, height)=>({ 5131 pool: new CanvasPool(width, height), 5132 setupCache: new WeakMap, 5133 cleanupRegistry: [], 5134 currentRunId: 0 5135 }); 5136var cleanupEffectChainState = (state)=>{ 5137 state.currentRunId++; 5138 for (const entry of state.cleanupRegistry){ 5139 entry.definition.cleanup(entry.state); 5140 } 5141}; 5142var ensureSetup = (state, def, target)=>{ 5143 const widened = def; 5144 let cacheForDefinition = state.setupCache.get(widened); 5145 if (!cacheForDefinition) { 5146 cacheForDefinition = new WeakMap; 5147 state.setupCache.set(widened, cacheForDefinition); 5148 } 5149 if (cacheForDefinition.has(target)) { 5150 return cacheForDefinition.get(target); 5151 } 5152 const setupState = def.setup(target); 5153 cacheForDefinition.set(target, setupState); 5154 state.cleanupRegistry.push({ 5155 definition: widened, 5156 state: setupState 5157 }); 5158 return setupState; 5159}; 5160var runEffectChain = async ({ state, source, effects, output, width, height })=>{ 5161 const runId = ++state.currentRunId; 5162 const isCancelled = ()=>state.currentRunId !== runId; 5163 const enabledEffects = effects.filter((e)=>!e.params.disabled); 5164 const runs = groupByBackend(enabledEffects); 5165 let currentImage = source; 5166 let lastTarget = null; 5167 if (runs.length === 0) { 5168 if (source === output) { 5169 return true; 5170 } 5171 const ctx = output.getContext("2d"); 5172 if (!ctx) { 5173 throw new Error("Failed to acquire 2D context for output canvas"); 5174 } 5175 ctx.clearRect(0, 0, width, height); 5176 ctx.drawImage(currentImage, 0, 0, width, height); 5177 return true; 5178 } 5179 let needsGpuDevice = false; 5180 for (const run of runs){ 5181 if (run.backend === "webgpu") { 5182 needsGpuDevice = true; 5183 break; 5184 } 5185 } 5186 const gpuDevice = needsGpuDevice ? await getGpuDevice() : null; 5187 if (isCancelled()) { 5188 return false; 5189 } 5190 let flipWebGLSourceY = true; 5191 for(let runIndex = 0; runIndex < runs.length; runIndex++){ 5192 const run = runs[runIndex]; 5193 const [a2, b2] = state.pool.getPair(run.backend); 5194 let dst = a2; 5195 for (const eff of run.effects){ 5196 const def = eff.definition; 5197 const setupState = ensureSetup(state, def, dst); 5198 def.apply({ 5199 source: currentImage, 5200 target: dst, 5201 state: setupState, 5202 params: eff.params, 5203 width, 5204 height, 5205 gpuDevice, 5206 flipSourceY: run.backend === "webgl2" ? flipWebGLSourceY : false 5207 }); 5208 if (run.backend === "webgl2") { 5209 flipWebGLSourceY = true; 5210 state.pool.assertContextNotLost(dst); 5211 } 5212 currentImage = dst; 5213 dst = dst === a2 ? b2 : a2; 5214 } 5215 lastTarget = currentImage ?? lastTarget; 5216 const nextRun = runs[runIndex + 1]; 5217 if (nextRun && nextRun.backend !== run.backend && lastTarget) { 5218 if (run.backend === "2d" && nextRun.backend === "webgl2") { 5219 currentImage = lastTarget; 5220 flipWebGLSourceY = true; 5221 } else { 5222 const bitmap = await createImageBitmap(lastTarget); 5223 if (isCancelled()) { 5224 bitmap.close(); 5225 return false; 5226 } 5227 currentImage = bitmap; 5228 if (nextRun.backend === "webgl2") { 5229 flipWebGLSourceY = false; 5230 } 5231 } 5232 } 5233 } 5234 if (!lastTarget) { 5235 return true; 5236 } 5237 const outCtx = output.getContext("2d"); 5238 if (!outCtx) { 5239 throw new Error("Failed to acquire 2D context for output canvas"); 5240 } 5241 outCtx.clearRect(0, 0, width, height); 5242 outCtx.drawImage(lastTarget, 0, 0, width, height); 5243 return true; 5244};
5245// src/effects/use-effect-chain-state.ts 5246 5247var useEffectChainState = ()=>{ 5248 const chainStateRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 5249 const sizeRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 5250 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 5251 return ()=>{ 5252 if (chainStateRef.current) { 5253 cleanupEffectChainState(chainStateRef.current); 5254 } 5255 }; 5256 }, []); 5257 return (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>({ 5258 get: (width, height)=>{ 5259 if (!sizeRef.current || sizeRef.current.width !== width || sizeRef.current.height !== height) { 5260 if (chainStateRef.current) { 5261 cleanupEffectChainState(chainStateRef.current); 5262 } 5263 chainStateRef.current = createEffectChainState(width, height); 5264 sizeRef.current = { 5265 width, 5266 height 5267 }; 5268 } 5269 return chainStateRef.current; 5270 } 5271 }), []); 5272};
5273// src/animated-image/canvas.tsx 5274 5275var CanvasRefForwardingFunction = ({ width, height, fit, className, style, effects, ...props }, ref)=>{ 5276 const canvasRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 5277 const chainState = useEffectChainState(); 5278 const sourceCanvas = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 5279 if (typeof document === "undefined") { 5280 return null; 5281 } 5282 return document.createElement("canvas"); 5283 }, []); 5284 const draw = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((imageData)=>{ 5285 const canvas = canvasRef.current; 5286 const canvasWidth = width ?? imageData.displayWidth; 5287 const canvasHeight = height ?? imageData.displayHeight; 5288 if (!canvas) { 5289 throw new Error("Canvas ref is not set"); 5290 } 5291 if (!sourceCanvas) { 5292 throw new Error("Source canvas is not available"); 5293 } 5294 sourceCanvas.width = canvasWidth; 5295 sourceCanvas.height = canvasHeight; 5296 const sourceCtx = sourceCanvas.getContext("2d"); 5297 if (!sourceCtx) { 5298 throw new Error("Could not get 2d context for source canvas"); 5299 } 5300 sourceCtx.drawImage(imageData, ...calculateImageFit(fit, { 5301 height: imageData.displayHeight, 5302 width: imageData.displayWidth 5303 }, { 5304 width: canvasWidth, 5305 height: canvasHeight 5306 })); 5307 canvas.width = canvasWidth; 5308 canvas.height = canvasHeight; 5309 return runEffectChain({ 5310 state: chainState.get(canvasWidth, canvasHeight), 5311 source: sourceCanvas, 5312 effects, 5313 output: canvas, 5314 width: canvasWidth, 5315 height: canvasHeight 5316 }); 5317 }, [ 5318 chainState, 5319 effects, 5320 fit, 5321 height, 5322 sourceCanvas, 5323 width 5324 ]); 5325 (0,react__WEBPACK_IMPORTED_MODULE_0__.useImperativeHandle)(ref, ()=>{ 5326 return { 5327 draw, 5328 getCanvas: ()=>{ 5329 if (!canvasRef.current) { 5330 throw new Error("Canvas ref is not set"); 5331 } 5332 return canvasRef.current; 5333 }, 5334 clear: ()=>{ 5335 const ctx = canvasRef.current?.getContext("2d"); 5336 if (!ctx) { 5337 throw new Error("Could not get 2d context"); 5338 } 5339 ctx.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height); 5340 } 5341 }; 5342 }, [ 5343 draw 5344 ]); 5345 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)("canvas", { 5346 ref: canvasRef, 5347 className, 5348 style, 5349 ...props 5350 }); 5351}; 5352var Canvas = /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.forwardRef(CanvasRefForwardingFunction);
vendor: 4,613 bytes, lines 5353-5477
5353// src/animated-image/decode-image.ts 5354var CACHE_SIZE = 5; 5355var getActualTime = ({ loopBehavior, durationFound, timeInSec })=>{ 5356 return loopBehavior === "loop" ? durationFound ? timeInSec % durationFound : timeInSec : Math.min(timeInSec, durationFound || Infinity); 5357}; 5358var decodeImage = async ({ resolvedSrc, signal, requestInit, currentTime, initialLoopBehavior })=>{ 5359 if (typeof ImageDecoder === "undefined") { 5360 throw new Error("Your browser does not support the WebCodecs ImageDecoder API."); 5361 } 5362 const res = await fetch(resolvedSrc, { 5363 ...requestInit, 5364 signal 5365 }); 5366 const { body } = res; 5367 if (!body) { 5368 throw new Error("Got no body"); 5369 } 5370 const decoder = new ImageDecoder({ 5371 data: body, 5372 type: res.headers.get("Content-Type") || "image/gif" 5373 }); 5374 await decoder.completed; 5375 const { selectedTrack } = decoder.tracks; 5376 if (!selectedTrack) { 5377 throw new Error("No selected track"); 5378 } 5379 const cache2 = []; 5380 let durationFound = null; 5381 const getFrameByIndex = async (frameIndex)=>{ 5382 const foundInCache = cache2.find((c2)=>c2.frameIndex === frameIndex); 5383 if (foundInCache && foundInCache.frame) { 5384 return foundInCache; 5385 } 5386 const frame = await decoder.decode({ 5387 frameIndex, 5388 completeFramesOnly: true 5389 }); 5390 if (foundInCache) { 5391 foundInCache.frame = frame.image; 5392 } else { 5393 cache2.push({ 5394 frame: frame.image, 5395 frameIndex, 5396 timeInSeconds: frame.image.timestamp / 1e6 5397 }); 5398 } 5399 return { 5400 frame: frame.image, 5401 frameIndex, 5402 timeInSeconds: frame.image.timestamp / 1e6 5403 }; 5404 }; 5405 const clearCache = (closeToTimeInSec)=>{ 5406 const itemsInCache = cache2.filter((c2)=>c2.frame); 5407 const sortByClosestToCurrentTime = itemsInCache.sort((a2, b2)=>{ 5408 const aDiff = Math.abs(a2.timeInSeconds - closeToTimeInSec); 5409 const bDiff = Math.abs(b2.timeInSeconds - closeToTimeInSec); 5410 return aDiff - bDiff; 5411 }); 5412 for(let i = 0; i < sortByClosestToCurrentTime.length; i++){ 5413 if (i < CACHE_SIZE) { 5414 continue; 5415 } 5416 const item = sortByClosestToCurrentTime[i]; 5417 item.frame = null; 5418 } 5419 }; 5420 const ensureFrameBeforeAndAfter = async ({ timeInSec, loopBehavior })=>{ 5421 const actualTimeInSec = getActualTime({ 5422 durationFound, 5423 loopBehavior, 5424 timeInSec 5425 }); 5426 const framesBefore = cache2.filter((c2)=>c2.timeInSeconds <= actualTimeInSec); 5427 const biggestIndex = framesBefore.map((c2)=>c2.frameIndex).reduce((a2, b2)=>Math.max(a2, b2), 0); 5428 let i = biggestIndex; 5429 while(true){ 5430 const f = await getFrameByIndex(i); 5431 i++; 5432 if (!f.frame) { 5433 throw new Error("No frame found"); 5434 } 5435 if (!f.frame.duration) { 5436 break; 5437 } 5438 if (i === selectedTrack.frameCount && durationFound === null) { 5439 const duration = (f.frame.timestamp + f.frame.duration) / 1e6; 5440 durationFound = duration; 5441 } 5442 if (f.timeInSeconds > actualTimeInSec || i === selectedTrack.frameCount) { 5443 break; 5444 } 5445 } 5446 if (selectedTrack.frameCount - biggestIndex < 3 && loopBehavior === "loop") { 5447 await getFrameByIndex(0); 5448 } 5449 clearCache(actualTimeInSec); 5450 }; 5451 await ensureFrameBeforeAndAfter({ 5452 timeInSec: currentTime, 5453 loopBehavior: initialLoopBehavior 5454 }); 5455 await ensureFrameBeforeAndAfter({ 5456 timeInSec: currentTime, 5457 loopBehavior: initialLoopBehavior 5458 }); 5459 const getFrame = async (timeInSec, loopBehavior)=>{ 5460 if (durationFound !== null && timeInSec > durationFound && loopBehavior === "clear-after-finish") { 5461 return null; 5462 } 5463 const actualTimeInSec = getActualTime({ 5464 loopBehavior, 5465 durationFound, 5466 timeInSec 5467 }); 5468 await ensureFrameBeforeAndAfter({ 5469 timeInSec: actualTimeInSec, 5470 loopBehavior 5471 }); 5472 const itemsInCache = cache2.filter((c2)=>c2.frame); 5473 const closest = itemsInCache.reduce((a2, b2)=>{ 5474 const aDiff = Math.abs(a2.timeInSeconds - actualTimeInSec); 5475 const bDiff = Math.abs(b2.timeInSeconds - actualTimeInSec); 5476 return aDiff < bDiff ? a2 : b2; 5477 });
5478 if (!closest.frame) { 5479 throw new Error("No frame found"); 5480 } 5481 return closest; 5482 }; 5483 return { 5484 getFrame, 5485 frameCount: selectedTrack.frameCount 5486 }; 5487};
5488// src/animated-image/request-init.ts 5489var serializeRequestInit = (requestInit)=>{ 5490 if (!requestInit) { 5491 return null; 5492 } 5493 const requestInitWithoutSignal = { 5494 ...requestInit 5495 }; 5496 delete requestInitWithoutSignal.signal; 5497 const { headers, ...rest } = requestInitWithoutSignal; 5498 return JSON.stringify({ 5499 ...rest, 5500 headers: headers ? Array.from(new Headers(headers).entries()) : null 5501 }); 5502};
5503// src/animated-image/resolve-image-source.tsx 5504var resolveAnimatedImageSource = (src)=>{ 5505 if (typeof window === "undefined") { 5506 return src; 5507 } 5508 return new URL(src, window.origin).href; 5509};
5510// src/animated-image/AnimatedImage.tsx 5511 5512var animatedImageSchema = { 5513 ...baseSchema, 5514 playbackRate: { 5515 type: "number", 5516 min: 0, 5517 max: 10, 5518 step: 0.1, 5519 default: 1, 5520 description: "Playback rate", 5521 hiddenFromList: false, 5522 keyframable: false 5523 }, 5524 ...transformSchema 5525}; 5526var getCanvasPropsFromSequenceProps = (props)=>{ 5527 const canvasProps = {}; 5528 const mutableCanvasProps = canvasProps; 5529 for(const key in props){ 5530 if (Object.prototype.hasOwnProperty.call(props, key) && (key.startsWith("data-") || key.startsWith("aria-"))) { 5531 mutableCanvasProps[key] = props[key]; 5532 } 5533 } 5534 return canvasProps; 5535}; 5536var AnimatedImageContent = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(({ src, width, height, onError, loopBehavior = "loop", playbackRate = 1, fit = "fill", requestInit, effects, controls, ...props }, canvasRef)=>{ 5537 const resolvedSrc = resolveAnimatedImageSource(src); 5538 const [imageDecoder, setImageDecoder] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(null); 5539 const { delayRender: delayRender2, continueRender: continueRender2 } = useDelayRender(); 5540 const [decodeHandle] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(()=>delayRender2(`Rendering <AnimatedImage/> with src="${resolvedSrc}"`)); 5541 const frame = useCurrentFrame(); 5542 const { fps } = useVideoConfig(); 5543 const currentTime = frame / playbackRate / fps; 5544 const currentTimeRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(currentTime); 5545 currentTimeRef.current = currentTime; 5546 const requestInitKey = serializeRequestInit(requestInit); 5547 const requestInitRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(requestInit); 5548 requestInitRef.current = requestInit; 5549 const ref = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 5550 const memoizedEffects = useMemoizedEffects({ 5551 effects, 5552 overrideId: controls?.overrideId ?? null 5553 }); 5554 (0,react__WEBPACK_IMPORTED_MODULE_0__.useImperativeHandle)(canvasRef, ()=>{ 5555 const c2 = ref.current?.getCanvas(); 5556 if (!c2) { 5557 throw new Error("Canvas ref is not set"); 5558 } 5559 return c2; 5560 }, []); 5561 const [initialLoopBehavior] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(()=>loopBehavior); 5562 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 5563 const controller = new AbortController; 5564 decodeImage({ 5565 resolvedSrc, 5566 signal: controller.signal, 5567 requestInit: requestInitRef.current, 5568 currentTime: currentTimeRef.current, 5569 initialLoopBehavior 5570 }).then((d)=>{ 5571 setImageDecoder(d); 5572 continueRender2(decodeHandle); 5573 }).catch((err)=>{ 5574 if (err.name === "AbortError") { 5575 continueRender2(decodeHandle); 5576 return; 5577 } 5578 if (onError) { 5579 onError?.(err); 5580 continueRender2(decodeHandle); 5581 } else { 5582 cancelRender(err); 5583 } 5584 }); 5585 return ()=>{ 5586 controller.abort(); 5587 }; 5588 }, [ 5589 resolvedSrc, 5590 decodeHandle, 5591 onError, 5592 requestInitKey, 5593 initialLoopBehavior, 5594 continueRender2 5595 ]); 5596 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 5597 if (!imageDecoder) { 5598 return; 5599 } 5600 const delay = delayRender2(`Rendering frame at ${currentTime} of <AnimatedImage src="${src}"/>`); 5601 let cancelled = false; 5602 imageDecoder.getFrame(currentTime, loopBehavior).then(async (videoFrame)=>{ 5603 if (cancelled) { 5604 return; 5605 } 5606 if (videoFrame === null) { 5607 ref.current?.clear(); 5608 continueRender2(delay); 5609 return; 5610 } 5611 const completed = await ref.current?.draw(videoFrame.frame); 5612 if (completed && !cancelled) { 5613 continueRender2(delay); 5614 } 5615 }).catch((err)=>{ 5616 if (cancelled) { 5617 return; 5618 } 5619 if (onError) { 5620 onError(err); 5621 continueRender2(delay); 5622 } else { 5623 cancelRender(err); 5624 } 5625 }); 5626 return ()=>{ 5627 cancelled = true; 5628 continueRender2(delay); 5629 }; 5630 }, [ 5631 currentTime, 5632 imageDecoder, 5633 loopBehavior, 5634 onError, 5635 src, 5636 continueRender2, 5637 delayRender2, 5638 memoizedEffects, 5639 fit, 5640 width, 5641 height 5642 ]); 5643 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Canvas, { 5644 ref, 5645 width, 5646 height, 5647 fit, 5648 effects: memoizedEffects, 5649 ...props 5650 }); 5651}); 5652AnimatedImageContent.displayName = "AnimatedImageContent"; 5653var AnimatedImageInner = ({ src, width, height, onError, fit, playbackRate, loopBehavior, id, className, style, durationInFrames, requestInit, effects = [], controls, ref, ...sequenceProps })=>{ 5654 const { durationInFrames: videoDuration } = useVideoConfig(); 5655 const resolvedDuration = durationInFrames ?? videoDuration; 5656 const actualRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 5657 const memoizedEffectDefinitions = useMemoizedEffectDefinitions(effects); 5658 (0,react__WEBPACK_IMPORTED_MODULE_0__.useImperativeHandle)(ref, ()=>{ 5659 return actualRef.current; 5660 }, []); 5661 const canvasProps = getCanvasPropsFromSequenceProps(sequenceProps); 5662 const animatedImageProps = { 5663 src, 5664 width, 5665 height, 5666 onError, 5667 fit, 5668 playbackRate, 5669 loopBehavior, 5670 id, 5671 className, 5672 style, 5673 requestInit, 5674 ...canvasProps 5675 }; 5676 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Sequence, { 5677 layout: "none", 5678 durationInFrames: resolvedDuration, 5679 name: "<AnimatedImage>", 5680 _remotionInternalDocumentationLink: "https://www.remotion.dev/docs/animatedimage", 5681 controls, 5682 _remotionInternalEffects: memoizedEffectDefinitions, 5683 ...sequenceProps, 5684 outlineRef: actualRef, 5685 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(AnimatedImageContent, { 5686 ...animatedImageProps, 5687 ref: actualRef, 5688 effects, 5689 controls 5690 }) 5691 }); 5692}; 5693var AnimatedImage = withInteractivitySchema({ 5694 Component: AnimatedImageInner, 5695 componentName: "<AnimatedImage>", 5696 componentIdentity: "dev.remotion.remotion.AnimatedImage", 5697 schema: animatedImageSchema, 5698 supportsEffects: true 5699}); 5700AnimatedImage.displayName = "AnimatedImage"; 5701addSequenceStackTraces(AnimatedImage);
vendor: 895 bytes, lines 5702-5732
5702// src/effects/create-effect.ts 5703var disabledEffectField = { 5704 type: "boolean", 5705 default: false, 5706 description: "Disabled" 5707}; 5708var createEffect = (definition)=>{ 5709 const { calculateKey: userCalculateKey, validateParams } = definition; 5710 const widened = { 5711 ...definition, 5712 documentationLink: definition.documentationLink ?? null, 5713 calculateKey: (params)=>{ 5714 const disabled = params.disabled ?? false; 5715 return `${userCalculateKey(params)}-disabled-${disabled}`; 5716 }, 5717 schema: { 5718 disabled: disabledEffectField, 5719 ...definition.schema 5720 } 5721 }; 5722 const factory = (params = {})=>{ 5723 validateParams(params); 5724 return { 5725 definition: widened, 5726 params, 5727 effectKey: widened.calculateKey(params), 5728 memoized: false 5729 }; 5730 }; 5731 return factory; 5732};
5733// src/Artifact.tsx 5734
5735// src/RenderAssetManager.tsx 5736
vendor: 1,197 bytes, lines 5737-5766
5737// src/validation/validate-artifact.ts 5738var validateArtifactFilename = (filename)=>{ 5739 if (typeof filename !== "string") { 5740 throw new TypeError(`The "filename" must be a string, but you passed a value of type ${typeof filename}`); 5741 } 5742 if (filename.trim() === "") { 5743 throw new Error("The `filename` must not be empty"); 5744 } 5745 if (!filename.match(/^([0-9a-zA-Z-!_.*'()/:&$@=;+,?]+)/g)) { 5746 throw new Error('The `filename` must match "/^([0-9a-zA-Z-!_.*\'()/:&$@=;+,?]+)/g". Use forward slashes only, even on Windows.'); 5747 } 5748}; 5749var validateContent = (content)=>{ 5750 if (typeof content !== "string" && !(content instanceof Uint8Array)) { 5751 throw new TypeError(`The "content" must be a string or Uint8Array, but you passed a value of type ${typeof content}`); 5752 } 5753 if (typeof content === "string" && content.trim() === "") { 5754 throw new Error("The `content` must not be empty"); 5755 } 5756}; 5757var validateRenderAsset = (artifact)=>{ 5758 if (artifact.type !== "artifact") { 5759 return; 5760 } 5761 validateArtifactFilename(artifact.filename); 5762 if (artifact.contentType === "thumbnail") { 5763 return; 5764 } 5765 validateContent(artifact.content); 5766};
5767// src/RenderAssetManager.tsx 5768 5769var RenderAssetManager = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({ 5770 registerRenderAsset: ()=>{ 5771 return; 5772 }, 5773 unregisterRenderAsset: ()=>{ 5774 return; 5775 }, 5776 renderAssets: [] 5777}); 5778var RenderAssetManagerProvider = ({ children, collectAssets })=>{ 5779 const [renderAssets, setRenderAssets] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)([]); 5780 const renderAssetsRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)([]); 5781 const registerRenderAsset = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((renderAsset)=>{ 5782 validateRenderAsset(renderAsset); 5783 renderAssetsRef.current = [ 5784 ...renderAssetsRef.current, 5785 renderAsset 5786 ]; 5787 setRenderAssets(renderAssetsRef.current); 5788 }, []); 5789 if (collectAssets) { 5790 (0,react__WEBPACK_IMPORTED_MODULE_0__.useImperativeHandle)(collectAssets, ()=>{ 5791 return { 5792 collectAssets: ()=>{ 5793 const assets = renderAssetsRef.current; 5794 renderAssetsRef.current = []; 5795 setRenderAssets([]); 5796 return assets; 5797 } 5798 }; 5799 }, []); 5800 } 5801 const unregisterRenderAsset = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((id)=>{ 5802 renderAssetsRef.current = renderAssetsRef.current.filter((a2)=>a2.id !== id); 5803 setRenderAssets(renderAssetsRef.current); 5804 }, []); 5805 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 5806 if (typeof window !== "undefined") { 5807 window.remotion_collectAssets = ()=>{ 5808 const assets = renderAssetsRef.current; 5809 renderAssetsRef.current = []; 5810 setRenderAssets([]); 5811 return assets; 5812 }; 5813 } 5814 }, []); 5815 const contextValue = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 5816 return { 5817 registerRenderAsset, 5818 unregisterRenderAsset, 5819 renderAssets 5820 }; 5821 }, [ 5822 renderAssets, 5823 registerRenderAsset, 5824 unregisterRenderAsset 5825 ]); 5826 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(RenderAssetManager.Provider, { 5827 value: contextValue, 5828 children 5829 }); 5830};
5831// src/Artifact.tsx 5832var ArtifactThumbnail = Symbol("Thumbnail"); 5833var Artifact = ({ filename, content, downloadBehavior })=>{ 5834 const { registerRenderAsset, unregisterRenderAsset } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(RenderAssetManager); 5835 const env = useRemotionEnvironment(); 5836 const frame = useCurrentFrame(); 5837 const [id] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(()=>{ 5838 return String(Math.random()); 5839 }); 5840 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 5841 if (!env.isRendering) { 5842 return; 5843 } 5844 if (content instanceof Uint8Array) { 5845 registerRenderAsset({ 5846 type: "artifact", 5847 id, 5848 content: btoa(new TextDecoder("utf8").decode(content)), 5849 filename, 5850 frame, 5851 contentType: "binary", 5852 downloadBehavior: downloadBehavior ?? null 5853 }); 5854 } else if (content === ArtifactThumbnail) { 5855 registerRenderAsset({ 5856 type: "artifact", 5857 id, 5858 filename, 5859 frame, 5860 contentType: "thumbnail", 5861 downloadBehavior: downloadBehavior ?? null 5862 }); 5863 } else { 5864 registerRenderAsset({ 5865 type: "artifact", 5866 id, 5867 content, 5868 filename, 5869 frame, 5870 contentType: "text", 5871 downloadBehavior: downloadBehavior ?? null 5872 }); 5873 } 5874 return ()=>{ 5875 return unregisterRenderAsset(id); 5876 }; 5877 }, [ 5878 content, 5879 env.isRendering, 5880 filename, 5881 frame, 5882 id, 5883 registerRenderAsset, 5884 unregisterRenderAsset, 5885 downloadBehavior 5886 ]); 5887 return null; 5888}; 5889Artifact.Thumbnail = ArtifactThumbnail;
5890// src/audio/html5-audio.tsx 5891
5892// src/absolute-src.ts 5893var getAbsoluteSrc = (relativeSrc)=>{ 5894 if (typeof window === "undefined") { 5895 return relativeSrc; 5896 } 5897 if (relativeSrc.startsWith("http://") || relativeSrc.startsWith("https://") || relativeSrc.startsWith("file://") || relativeSrc.startsWith("blob:") || relativeSrc.startsWith("data:")) { 5898 return relativeSrc; 5899 } 5900 return new URL(relativeSrc, window.origin).href; 5901};
5902// src/calculate-media-duration.ts 5903var calculateMediaDuration = ({ trimAfter, mediaDurationInFrames, playbackRate, trimBefore })=>{ 5904 let duration = mediaDurationInFrames; 5905 if (typeof trimAfter !== "undefined") { 5906 duration = trimAfter; 5907 } 5908 if (typeof trimBefore !== "undefined") { 5909 duration -= trimBefore; 5910 } 5911 const actualDuration = duration / playbackRate; 5912 return Number(actualDuration.toFixed(10)); 5913};
5914// src/loop/index.tsx 5915 5916 5917var LoopContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)(null); 5918var useLoop = ()=>{ 5919 return react__WEBPACK_IMPORTED_MODULE_0__.useContext(LoopContext); 5920}; 5921var Loop = ({ durationInFrames, times = Infinity, children, name, showInTimeline, ...props })=>{ 5922 const currentFrame = useCurrentFrame(); 5923 const { durationInFrames: compDuration } = useVideoConfig(); 5924 validateDurationInFrames(durationInFrames, { 5925 component: "of the <Loop /> component", 5926 allowFloats: true 5927 }); 5928 if (typeof times !== "number") { 5929 throw new TypeError(`You passed to "times" an argument of type ${typeof times}, but it must be a number.`); 5930 } 5931 if (times !== Infinity && times % 1 !== 0) { 5932 throw new TypeError(`The "times" prop of a loop must be an integer, but got ${times}.`); 5933 } 5934 if (times < 0) { 5935 throw new TypeError(`The "times" prop of a loop must be at least 0, but got ${times}`); 5936 } 5937 const maxTimes = Math.ceil(compDuration / durationInFrames); 5938 const actualTimes = Math.min(maxTimes, times); 5939 const style = props.layout === "none" ? undefined : props.style; 5940 const maxFrame = durationInFrames * (actualTimes - 1); 5941 const iteration = Math.floor(currentFrame / durationInFrames); 5942 const start = iteration * durationInFrames; 5943 const from = Math.min(start, maxFrame); 5944 const loopDisplay = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 5945 return { 5946 numberOfTimes: Math.min(compDuration / durationInFrames, times), 5947 startOffset: -from, 5948 durationInFrames 5949 }; 5950 }, [ 5951 compDuration, 5952 durationInFrames, 5953 from, 5954 times 5955 ]); 5956 const loopContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 5957 return { 5958 iteration: Math.floor(currentFrame / durationInFrames), 5959 durationInFrames 5960 }; 5961 }, [ 5962 currentFrame, 5963 durationInFrames 5964 ]); 5965 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(LoopContext.Provider, { 5966 value: loopContext, 5967 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Sequence, { 5968 durationInFrames, 5969 from, 5970 name: name ?? "<Loop>", 5971 _remotionInternalDocumentationLink: "https://www.remotion.dev/docs/loop", 5972 _remotionInternalLoopDisplay: loopDisplay, 5973 layout: props.layout, 5974 style, 5975 showInTimeline, 5976 children 5977 }) 5978 }); 5979}; 5980Loop.useLoop = useLoop;
5981// src/prefetch.ts 5982
5983// src/playback-logging.ts 5984var playbackLogging = ({ logLevel, tag, message, mountTime })=>{ 5985 const tags = [ 5986 mountTime ? Date.now() - mountTime + "ms " : null, 5987 tag 5988 ].filter(Boolean).join(" "); 5989 Log.trace({ 5990 logLevel, 5991 tag: null 5992 }, `[${tags}]`, message); 5993};
5994// src/prefetch-state.tsx 5995 5996 5997var PreloadContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({}); 5998var preloads = {}; 5999var updaters = []; 6000var setPreloads = (updater)=>{ 6001 preloads = updater(preloads); 6002 updaters.forEach((u)=>u()); 6003}; 6004var PrefetchProvider = ({ children })=>{ 6005 const [_preloads, _setPreloads] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(()=>preloads); 6006 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 6007 const updaterFunction = ()=>{ 6008 _setPreloads(preloads); 6009 }; 6010 updaters.push(updaterFunction); 6011 return ()=>{ 6012 updaters = updaters.filter((u)=>u !== updaterFunction); 6013 }; 6014 }, []); 6015 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(PreloadContext.Provider, { 6016 value: _preloads, 6017 children 6018 }); 6019};
vendor: 6,425 bytes, lines 6020-6222
6020// src/prefetch.ts 6021var removeAndGetHashFragment = (src)=>{ 6022 const hashIndex = src.indexOf("#"); 6023 if (hashIndex === -1) { 6024 return null; 6025 } 6026 return hashIndex; 6027}; 6028var getSrcWithoutHash = (src)=>{ 6029 const hashIndex = removeAndGetHashFragment(src); 6030 if (hashIndex === null) { 6031 return src; 6032 } 6033 return src.slice(0, hashIndex); 6034}; 6035var usePreload = (src)=>{ 6036 const preloads2 = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(PreloadContext); 6037 const hashFragmentIndex = removeAndGetHashFragment(src); 6038 const withoutHashFragment = getSrcWithoutHash(src); 6039 if (!preloads2[withoutHashFragment]) { 6040 return src; 6041 } 6042 if (hashFragmentIndex !== null) { 6043 return preloads2[withoutHashFragment] + src.slice(hashFragmentIndex); 6044 } 6045 return preloads2[withoutHashFragment]; 6046}; 6047var blobToBase64 = function(blob) { 6048 const reader = new FileReader; 6049 return new Promise((resolve, reject)=>{ 6050 reader.onload = function() { 6051 const dataUrl = reader.result; 6052 resolve(dataUrl); 6053 }; 6054 reader.onerror = (err)=>{ 6055 return reject(err); 6056 }; 6057 reader.readAsDataURL(blob); 6058 }); 6059}; 6060var getBlobFromReader = async ({ reader, contentType, contentLength, onProgress })=>{ 6061 let receivedLength = 0; 6062 const chunks = []; 6063 while(true){ 6064 const { done, value } = await reader.read(); 6065 if (done) { 6066 break; 6067 } 6068 chunks.push(value); 6069 receivedLength += value.length; 6070 if (onProgress) { 6071 onProgress({ 6072 loadedBytes: receivedLength, 6073 totalBytes: contentLength 6074 }); 6075 } 6076 } 6077 const chunksAll = new Uint8Array(receivedLength); 6078 let position = 0; 6079 for (const chunk of chunks){ 6080 chunksAll.set(chunk, position); 6081 position += chunk.length; 6082 } 6083 return new Blob([ 6084 chunksAll 6085 ], { 6086 type: contentType ?? undefined 6087 }); 6088}; 6089var prefetch = (src, options)=>{ 6090 const method = options?.method ?? "blob-url"; 6091 const logLevel = options?.logLevel ?? "info"; 6092 const srcWithoutHash = getSrcWithoutHash(src); 6093 if (getRemotionEnvironment().isRendering) { 6094 return { 6095 free: ()=>{ 6096 return; 6097 }, 6098 waitUntilDone: ()=>Promise.resolve(srcWithoutHash) 6099 }; 6100 } 6101 Log.verbose({ 6102 logLevel, 6103 tag: "prefetch" 6104 }, `Starting prefetch ${srcWithoutHash}`); 6105 let canceled = false; 6106 let objectUrl = null; 6107 let resolve = ()=>{ 6108 return; 6109 }; 6110 let reject = ()=>{ 6111 return; 6112 }; 6113 const waitUntilDone = new Promise((res, rej)=>{ 6114 resolve = res; 6115 reject = rej; 6116 }); 6117 waitUntilDone.catch(()=>{ 6118 return; 6119 }); 6120 const controller = new AbortController; 6121 let reader = null; 6122 fetch(srcWithoutHash, { 6123 signal: controller.signal, 6124 credentials: options?.credentials ?? undefined 6125 }).then((res)=>{ 6126 if (canceled) { 6127 return null; 6128 } 6129 if (!res.ok) { 6130 throw new Error(`HTTP error, status = ${res.status}`); 6131 } 6132 const headerContentType = res.headers.get("Content-Type"); 6133 const contentType = options?.contentType ?? headerContentType; 6134 const hasProperContentType = contentType && (contentType.startsWith("video/") || contentType.startsWith("audio/") || contentType.startsWith("image/")); 6135 if (!hasProperContentType) { 6136 console.warn(`Called prefetch() on ${srcWithoutHash} which returned a "Content-Type" of ${headerContentType}. Prefetched content should have a proper content type (video/... or audio/...) or a contentType passed the options of prefetch(). Otherwise, prefetching will not work properly in all browsers.`); 6137 } 6138 if (!res.body) { 6139 throw new Error(`HTTP response of ${srcWithoutHash} has no body`); 6140 } 6141 const responseReader = res.body.getReader(); 6142 reader = responseReader; 6143 return getBlobFromReader({ 6144 reader: responseReader, 6145 contentType: options?.contentType ?? headerContentType ?? null, 6146 contentLength: res.headers.get("Content-Length") ? parseInt(res.headers.get("Content-Length"), 10) : null, 6147 onProgress: options?.onProgress 6148 }); 6149 }).then((buf)=>{ 6150 if (!buf || canceled) { 6151 return; 6152 } 6153 const actualBlob = options?.contentType ? new Blob([ 6154 buf 6155 ], { 6156 type: options.contentType 6157 }) : buf; 6158 if (method === "base64") { 6159 return blobToBase64(actualBlob); 6160 } 6161 return URL.createObjectURL(actualBlob); 6162 }).then((url)=>{ 6163 if (canceled) { 6164 return; 6165 } 6166 playbackLogging({ 6167 logLevel, 6168 tag: "prefetch", 6169 message: `Finished prefetch ${srcWithoutHash} with method ${method}`, 6170 mountTime: null 6171 }); 6172 objectUrl = url; 6173 setPreloads((p)=>({ 6174 ...p, 6175 [srcWithoutHash]: objectUrl 6176 })); 6177 resolve(objectUrl); 6178 }).catch((err)=>{ 6179 if (err?.message.includes("free() called")) { 6180 return; 6181 } 6182 reject(err); 6183 }); 6184 return { 6185 free: ()=>{ 6186 playbackLogging({ 6187 logLevel, 6188 tag: "prefetch", 6189 message: `Freeing ${srcWithoutHash}`, 6190 mountTime: null 6191 }); 6192 if (objectUrl) { 6193 if (method === "blob-url") { 6194 URL.revokeObjectURL(objectUrl); 6195 } 6196 setPreloads((p)=>{ 6197 const copy = { 6198 ...p 6199 }; 6200 delete copy[srcWithoutHash]; 6201 return copy; 6202 }); 6203 } else { 6204 if (canceled) { 6205 return; 6206 } 6207 canceled = true; 6208 const cancellationError = new Error("free() called"); 6209 reject(cancellationError); 6210 try { 6211 controller.abort(cancellationError); 6212 } catch {} 6213 reader?.cancel(cancellationError).catch(()=>{ 6214 return; 6215 }); 6216 } 6217 }, 6218 waitUntilDone: ()=>{ 6219 return waitUntilDone; 6220 } 6221 }; 6222};
6223// src/validate-media-props.ts 6224var validateMediaProps = (props, component)=>{ 6225 if (typeof props.volume !== "number" && typeof props.volume !== "function" && typeof props.volume !== "undefined") { 6226 throw new TypeError(`You have passed a volume of type ${typeof props.volume} to your <${component} /> component. Volume must be a number or a function with the signature '(frame: number) => number' undefined.`); 6227 } 6228 if (typeof props.volume === "number" && props.volume < 0) { 6229 throw new TypeError(`You have passed a volume below 0 to your <${component} /> component. Volume must be between 0 and 1`); 6230 } 6231 if (typeof props.playbackRate !== "number" && typeof props.playbackRate !== "undefined") { 6232 throw new TypeError(`You have passed a playbackRate of type ${typeof props.playbackRate} to your <${component} /> component. Playback rate must a real number or undefined.`); 6233 } 6234 if (typeof props.playbackRate === "number" && (isNaN(props.playbackRate) || !Number.isFinite(props.playbackRate) || props.playbackRate <= 0)) { 6235 throw new TypeError(`You have passed a playbackRate of ${props.playbackRate} to your <${component} /> component. Playback rate must be a real number above 0.`); 6236 } 6237 if (typeof props.preservePitch !== "boolean" && typeof props.preservePitch !== "undefined") { 6238 throw new TypeError(`'preservePitch' must be a boolean or undefined but got '${typeof props.preservePitch}' instead`); 6239 } 6240};
vendor: 3,430 bytes, lines 6241-6318
6241// src/validate-start-from-props.ts 6242var validateStartFromProps = (startFrom, endAt)=>{ 6243 if (typeof startFrom !== "undefined") { 6244 if (typeof startFrom !== "number") { 6245 throw new TypeError(`type of startFrom prop must be a number, instead got type ${typeof startFrom}.`); 6246 } 6247 if (isNaN(startFrom) || startFrom === Infinity) { 6248 throw new TypeError("startFrom prop can not be NaN or Infinity."); 6249 } 6250 if (startFrom < 0) { 6251 throw new TypeError(`startFrom must be greater than equal to 0 instead got ${startFrom}.`); 6252 } 6253 } 6254 if (typeof endAt !== "undefined") { 6255 if (typeof endAt !== "number") { 6256 throw new TypeError(`type of endAt prop must be a number, instead got type ${typeof endAt}.`); 6257 } 6258 if (isNaN(endAt)) { 6259 throw new TypeError("endAt prop can not be NaN."); 6260 } 6261 if (endAt <= 0) { 6262 throw new TypeError(`endAt must be a positive number, instead got ${endAt}.`); 6263 } 6264 } 6265 if (endAt < startFrom) { 6266 throw new TypeError("endAt prop must be greater than startFrom prop."); 6267 } 6268}; 6269var validateTrimProps = (trimBefore, trimAfter)=>{ 6270 if (typeof trimBefore !== "undefined") { 6271 if (typeof trimBefore !== "number") { 6272 throw new TypeError(`type of trimBefore prop must be a number, instead got type ${typeof trimBefore}.`); 6273 } 6274 if (isNaN(trimBefore) || trimBefore === Infinity) { 6275 throw new TypeError("trimBefore prop can not be NaN or Infinity."); 6276 } 6277 if (trimBefore < 0) { 6278 throw new TypeError(`trimBefore must be greater than equal to 0 instead got ${trimBefore}.`); 6279 } 6280 } 6281 if (typeof trimAfter !== "undefined") { 6282 if (typeof trimAfter !== "number") { 6283 throw new TypeError(`type of trimAfter prop must be a number, instead got type ${typeof trimAfter}.`); 6284 } 6285 if (isNaN(trimAfter)) { 6286 throw new TypeError("trimAfter prop can not be NaN."); 6287 } 6288 if (trimAfter <= 0) { 6289 throw new TypeError(`trimAfter must be a positive number, instead got ${trimAfter}.`); 6290 } 6291 } 6292 if (trimAfter <= trimBefore) { 6293 throw new TypeError("trimAfter prop must be greater than trimBefore prop."); 6294 } 6295}; 6296var validateMediaTrimProps = ({ startFrom, endAt, trimBefore, trimAfter })=>{ 6297 if (typeof startFrom !== "undefined" && typeof trimBefore !== "undefined") { 6298 throw new TypeError("Cannot use both startFrom and trimBefore props. Use trimBefore instead as startFrom is deprecated."); 6299 } 6300 if (typeof endAt !== "undefined" && typeof trimAfter !== "undefined") { 6301 throw new TypeError("Cannot use both endAt and trimAfter props. Use trimAfter instead as endAt is deprecated."); 6302 } 6303 const hasNewProps = typeof trimBefore !== "undefined" || typeof trimAfter !== "undefined"; 6304 const hasOldProps = typeof startFrom !== "undefined" || typeof endAt !== "undefined"; 6305 if (hasNewProps) { 6306 validateTrimProps(trimBefore, trimAfter); 6307 } else if (hasOldProps) { 6308 validateStartFromProps(startFrom, endAt); 6309 } 6310}; 6311var resolveTrimProps = ({ startFrom, endAt, trimBefore, trimAfter })=>{ 6312 const trimBeforeValue = trimBefore ?? startFrom ?? undefined; 6313 const trimAfterValue = trimAfter ?? endAt ?? undefined; 6314 return { 6315 trimBeforeValue, 6316 trimAfterValue 6317 }; 6318};
6319// src/video/duration-state.tsx 6320 6321 6322var durationReducer = (state, action)=>{ 6323 switch(action.type){ 6324 case "got-duration": 6325 { 6326 const absoluteSrc = getAbsoluteSrc(action.src); 6327 if (state[absoluteSrc] === action.durationInSeconds) { 6328 return state; 6329 } 6330 return { 6331 ...state, 6332 [absoluteSrc]: action.durationInSeconds 6333 }; 6334 } 6335 default: 6336 return state; 6337 } 6338}; 6339var DurationsContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({ 6340 durations: {}, 6341 setDurations: ()=>{ 6342 throw new Error("context missing"); 6343 } 6344}); 6345var DurationsContextProvider = ({ children })=>{ 6346 const [durations, setDurations] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useReducer)(durationReducer, {}); 6347 const value = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 6348 return { 6349 durations, 6350 setDurations 6351 }; 6352 }, [ 6353 durations 6354 ]); 6355 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(DurationsContext.Provider, { 6356 value, 6357 children 6358 }); 6359};
6360// src/audio/AudioForPreview.tsx 6361 6362
6363// src/get-cross-origin-value.ts 6364var getCrossOriginValue = ({ crossOrigin, requestsVideoFrame, isClientSideRendering })=>{ 6365 if (crossOrigin !== undefined && crossOrigin !== null) { 6366 return crossOrigin; 6367 } 6368 if (isClientSideRendering) { 6369 return "anonymous"; 6370 } 6371 if (requestsVideoFrame) { 6372 return "anonymous"; 6373 } 6374 return; 6375};
6376// src/use-amplification.ts 6377
6378// src/audio/shared-audio-tags.tsx 6379
vendor: 2,001 bytes, lines 6380-6438
6380// src/play-and-handle-not-allowed-error.ts 6381var playAndHandleNotAllowedError = ({ mediaRef, mediaType, onAutoPlayError, logLevel, mountTime, reason, isPlayer })=>{ 6382 const { current } = mediaRef; 6383 if (!current) { 6384 return; 6385 } 6386 playbackLogging({ 6387 logLevel, 6388 tag: "play", 6389 message: `Attempting to play ${current.src}. Reason: ${reason}`, 6390 mountTime 6391 }); 6392 const prom = current.play(); 6393 if (!prom.catch) { 6394 return; 6395 } 6396 prom.catch((err)=>{ 6397 if (!current) { 6398 return; 6399 } 6400 if (err.message.includes("request was interrupted by a call to pause")) { 6401 return; 6402 } 6403 if (err.message.includes("The operation was aborted.")) { 6404 return; 6405 } 6406 if (err.message.includes("The fetching process for the media resource was aborted by the user agent")) { 6407 return; 6408 } 6409 if (err.message.includes("request was interrupted by a new load request")) { 6410 return; 6411 } 6412 if (err.message.includes("because the media was removed from the document")) { 6413 return; 6414 } 6415 if (err.message.includes("user didn't interact with the document") && current.muted) { 6416 return; 6417 } 6418 console.log(`Could not play ${mediaType} due to following error: `, err); 6419 if (!current.muted) { 6420 if (onAutoPlayError) { 6421 onAutoPlayError(); 6422 return; 6423 } 6424 if (mediaType === "video" && isPlayer) { 6425 Log.info({ 6426 logLevel, 6427 tag: "<" + mediaType + ">" 6428 }, `The video will be muted and we'll retry playing it.`); 6429 Log.info({ 6430 logLevel, 6431 tag: "<" + mediaType + ">" 6432 }, "Use onAutoPlayError() to handle this error yourself."); 6433 current.muted = true; 6434 current.play(); 6435 } 6436 } 6437 }); 6438};
6439// src/audio/shared-element-source-node.ts 6440var makeSharedElementSourceNode = ({ audioContext, ref })=>{ 6441 let connected = null; 6442 let disposed = false; 6443 return { 6444 attemptToConnect: ()=>{ 6445 if (disposed) { 6446 throw new Error("SharedElementSourceNode has been disposed"); 6447 } 6448 if (!connected && ref.current) { 6449 const mediaElementSourceNode = audioContext.createMediaElementSource(ref.current); 6450 connected = mediaElementSourceNode; 6451 } 6452 }, 6453 get: ()=>{ 6454 if (!connected) { 6455 throw new Error("Audio element not connected"); 6456 } 6457 return connected; 6458 }, 6459 cleanup: ()=>{ 6460 if (connected) { 6461 connected.disconnect(); 6462 connected = null; 6463 } 6464 disposed = true; 6465 } 6466 }; 6467};
vendor: 2,865 bytes, lines 6468-6557
6468// src/audio/use-audio-context.ts 6469 6470var warned = false; 6471var warnOnce = (logLevel)=>{ 6472 if (warned) { 6473 return; 6474 } 6475 warned = true; 6476 if (typeof window !== "undefined") { 6477 Log.warn({ 6478 logLevel, 6479 tag: null 6480 }, "AudioContext is not supported in this browser"); 6481 } 6482}; 6483var useSingletonAudioContext = ({ logLevel, latencyHint, audioEnabled, sampleRate })=>{ 6484 const env = useRemotionEnvironment(); 6485 const initialSampleRate = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(sampleRate); 6486 if (sampleRate !== initialSampleRate.current) { 6487 throw new Error(`Changing the AudioContext sample rate dynamically is not supported. The sample rate was initialized with ${initialSampleRate.current} Hz, but ${sampleRate} Hz was passed later.`); 6488 } 6489 const context = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 6490 if (env.isRendering) { 6491 return null; 6492 } 6493 if (!audioEnabled) { 6494 return null; 6495 } 6496 if (typeof AudioContext === "undefined") { 6497 warnOnce(logLevel); 6498 return null; 6499 } 6500 const audioContext = new AudioContext({ 6501 latencyHint, 6502 sampleRate 6503 }); 6504 const gainNode = audioContext.createGain(); 6505 gainNode.connect(audioContext.destination); 6506 Log.trace({ 6507 logLevel, 6508 tag: "audio" 6509 }, "Creating new audio context"); 6510 audioContext.suspend(); 6511 let transitionTarget = null; 6512 const getState = ()=>{ 6513 const nativeState = audioContext.state; 6514 if (transitionTarget === "running" && nativeState !== "running") { 6515 return "suspended-to-running"; 6516 } 6517 if (transitionTarget === "suspended" && nativeState !== "suspended") { 6518 return "running-to-suspended"; 6519 } 6520 return nativeState; 6521 }; 6522 const resume = ()=>{ 6523 transitionTarget = "running"; 6524 const promise = audioContext.resume(); 6525 promise.finally(()=>{ 6526 if (transitionTarget === "running") { 6527 transitionTarget = null; 6528 } 6529 }); 6530 return promise; 6531 }; 6532 const suspend = ()=>{ 6533 transitionTarget = "suspended"; 6534 const promise = audioContext.suspend(); 6535 promise.finally(()=>{ 6536 if (transitionTarget === "suspended") { 6537 transitionTarget = null; 6538 } 6539 }); 6540 return promise; 6541 }; 6542 return { 6543 audioContext, 6544 gainNode, 6545 getState, 6546 resume, 6547 suspend 6548 }; 6549 }, [ 6550 logLevel, 6551 latencyHint, 6552 env.isRendering, 6553 audioEnabled, 6554 sampleRate 6555 ]); 6556 return context; 6557};
6558// src/audio/wait-until-actually-resumed.ts 6559var waitUntilActuallyResumed = (audioContext, logLevel)=>{ 6560 return new Promise((resolve)=>{ 6561 const startCurrentTime = audioContext.currentTime; 6562 const start = audioContext.getOutputTimestamp(); 6563 const startOutputPerformanceTime = start.performanceTime; 6564 const startWallClock = performance.now(); 6565 const check = ()=>{ 6566 const { currentTime } = audioContext; 6567 const outputTimestamp = audioContext.getOutputTimestamp(); 6568 const elapsedWallClock = performance.now() - startWallClock; 6569 if (startOutputPerformanceTime !== undefined && outputTimestamp.performanceTime !== undefined && outputTimestamp.performanceTime > startOutputPerformanceTime && outputTimestamp.contextTime !== undefined && outputTimestamp.contextTime > startCurrentTime) { 6570 Log.verbose({ 6571 logLevel, 6572 tag: "audio" 6573 }, `waitUntilActuallyResumed: getOutputTimestamp.performanceTime advanced from ${startOutputPerformanceTime.toFixed(6)} to ${outputTimestamp.performanceTime.toFixed(6)} after ${elapsedWallClock.toFixed(1)}ms. currentTime=${currentTime.toFixed(6)} (advanced by ${(currentTime - startCurrentTime).toFixed(6)}), getOutputTimestamp.performanceTime=${outputTimestamp.performanceTime?.toFixed(1) ?? "undefined"}`); 6574 resolve(); 6575 return; 6576 } 6577 requestAnimationFrame(check); 6578 }; 6579 requestAnimationFrame(check); 6580 }); 6581};
6582// src/audio/shared-audio-tags.tsx 6583 6584var EMPTY_AUDIO = "data:audio/mp3;base64,/+MYxAAJcAV8AAgAABn//////+/gQ5BAMA+D4Pg+BAQBAEAwD4Pg+D4EBAEAQDAPg++hYBH///hUFQVBUFREDQNHmf///////+MYxBUGkAGIMAAAAP/29Xt6lUxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV/+MYxDUAAANIAAAAAFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"; 6585var compareProps = (obj1, obj2)=>{ 6586 const keysA = Object.keys(obj1).sort(); 6587 const keysB = Object.keys(obj2).sort(); 6588 if (keysA.length !== keysB.length) { 6589 return false; 6590 } 6591 for(let i = 0; i < keysA.length; i++){ 6592 if (keysA[i] !== keysB[i]) { 6593 return false; 6594 } 6595 if (obj1[keysA[i]] !== obj2[keysB[i]]) { 6596 return false; 6597 } 6598 } 6599 return true; 6600}; 6601var didPropChange = (key, newProp, prevProp)=>{ 6602 if (key === "src" && !prevProp.startsWith("data:") && !newProp.startsWith("data:")) { 6603 return new URL(prevProp, window.origin).toString() !== new URL(newProp, window.origin).toString(); 6604 } 6605 if (prevProp === newProp) { 6606 return false; 6607 } 6608 return true; 6609}; 6610var SharedAudioContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)(null); 6611var SharedAudioTagsContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)(null); 6612var shouldSaveForLater = (state)=>{ 6613 if (state === "suspended" || state === "running-to-suspended" || state === "interrupted") { 6614 return true; 6615 } 6616 if (state === "running" || state === "suspended-to-running") { 6617 return false; 6618 } 6619 throw new Error(`Unexpected audio context state: ${state}`); 6620}; 6621var SharedAudioContextProvider = ({ children, audioLatencyHint, audioEnabled, previewSampleRate })=>{ 6622 const logLevel = useLogLevel(); 6623 const sampleRate = previewSampleRate ?? 48000; 6624 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 6625 if (typeof window === "undefined") { 6626 return; 6627 } 6628 window.remotion_sampleRate = sampleRate; 6629 }, [ 6630 sampleRate 6631 ]); 6632 const ctxAndGain = useSingletonAudioContext({ 6633 logLevel, 6634 latencyHint: audioLatencyHint, 6635 audioEnabled, 6636 sampleRate 6637 }); 6638 const audioContextIsPlayingEventually = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(false); 6639 const isResuming = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 6640 const audioSyncAnchor = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>({ 6641 value: 0 6642 }), []); 6643 const audioSyncAnchorListeners = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)([]); 6644 const audioSyncAnchorEmitter = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 6645 return { 6646 dispatch: (event)=>{ 6647 audioSyncAnchorListeners.current.forEach((l)=>l(event)); 6648 }, 6649 subscribe: (listener)=>{ 6650 audioSyncAnchorListeners.current.push(listener); 6651 return { 6652 remove: ()=>{ 6653 audioSyncAnchorListeners.current = audioSyncAnchorListeners.current.filter((l)=>l !== listener); 6654 } 6655 }; 6656 } 6657 }; 6658 }, []); 6659 const prevEndTimes = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)({ 6660 scheduledEndTime: null, 6661 mediaEndTime: null 6662 }); 6663 const nodesToResume = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(new Map); 6664 const unscheduleAudioNode = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((node)=>{ 6665 nodesToResume.current.delete(node); 6666 }, []); 6667 const scheduleAudioNode = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 6668 return ({ node, mediaTimestamp, sourceOffset, scheduledTime, duration, offset, originalUnloopedMediaTimestamp })=>{ 6669 if (!ctxAndGain) { 6670 throw new Error("Audio context not found"); 6671 } 6672 const currentState = ctxAndGain.getState(); 6673 if (currentState === "closed") { 6674 return { 6675 type: "not-started", 6676 reason: "audio context is closed" 6677 }; 6678 } 6679 const saveForLater = shouldSaveForLater(currentState); 6680 if (duration > 0) { 6681 if (saveForLater) { 6682 nodesToResume.current.set(node, { 6683 scheduledTime, 6684 offset, 6685 duration 6686 }); 6687 } else { 6688 node.start(scheduledTime, offset, duration); 6689 } 6690 } 6691 const scheduledEndTime = scheduledTime + duration / node.playbackRate.value; 6692 const mediaTime = mediaTimestamp + offset - sourceOffset; 6693 const mediaEndTime = mediaTime + duration; 6694 const latency = ctxAndGain.audioContext.baseLatency + ctxAndGain.audioContext.outputLatency; 6695 const timeDiff = scheduledTime - ctxAndGain.audioContext.currentTime; 6696 const prev = prevEndTimes.current; 6697 const scheduledMismatch = prev.scheduledEndTime !== null && Math.abs(scheduledTime - prev.scheduledEndTime) > 0.001; 6698 const mediaMismatch = prev.mediaEndTime !== null && Math.abs(mediaTime - prev.mediaEndTime) > 0.001; 6699 Log.verbose({ 6700 logLevel, 6701 tag: "audio-scheduling" 6702 }
6702, "scheduled %c%s%c %s %c%s%c %s %c%s%c %s %s %s %s %s", scheduledMismatch ? "color: red; font-weight: bold" : "", scheduledTime.toFixed(4), "", scheduledEndTime.toFixed(4), mediaMismatch ? "color: red; font-weight: bold" : "", mediaTime.toFixed(4), "", mediaEndTime.toFixed(4), duration < 0 ? "color: red; font-weight: bold" : timeDiff < 0 ? "color: red; font-weight: bold" : "color: blue; font-weight: bold", duration < 0 ? "missed " + Math.abs(offset).toFixed(2) + "s" : Math.abs(timeDiff).toFixed(2) + (timeDiff < 0 ? " delay" : " ahead"), "", "current=" + ctxAndGain.audioContext.currentTime.toFixed(4), "offset=" + offset.toFixed(4), "latency=" + latency.toFixed(4), "state=" + ctxAndGain.audioContext.state, originalUnloopedMediaTimestamp !== mediaTime ? "original_ts=" + originalUnloopedMediaTimestamp.toFixed(4) : "", "action=" + (saveForLater ? "schedule" : "start"), ""); 6703 prev.scheduledEndTime = scheduledEndTime; 6704 prev.mediaEndTime = mediaEndTime; 6705 return duration > 0 ? { 6706 type: "started", 6707 scheduledTime 6708 } : { 6709 type: "not-started", 6710 reason: "missed " + Math.abs(offset).toFixed(2) + "s" 6711 }; 6712 }; 6713 }, [ 6714 ctxAndGain, 6715 logLevel 6716 ]); 6717 const resume = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(()=>{ 6718 if (!ctxAndGain) { 6719 return Promise.resolve(); 6720 } 6721 if (audioContextIsPlayingEventually.current) { 6722 return Promise.resolve(); 6723 } 6724 audioContextIsPlayingEventually.current = true; 6725 ctxAndGain.gainNode.gain.cancelScheduledValues(ctxAndGain.audioContext.currentTime); 6726 ctxAndGain.gainNode.gain.setValueAtTime(0, ctxAndGain.audioContext.currentTime); 6727 ctxAndGain.gainNode.gain.linearRampToValueAtTime(1, ctxAndGain.audioContext.currentTime + 0.03); 6728 nodesToResume.current.forEach((r, node)=>{ 6729 node.start(r.scheduledTime, r.offset, r.duration); 6730 }); 6731 nodesToResume.current.clear(); 6732 const resumePromise = ctxAndGain.resume(); 6733 isResuming.current = new Promise((resolve)=>{ 6734 waitUntilActuallyResumed(ctxAndGain.audioContext, logLevel).then(resolve); 6735 resumePromise.catch((err)=>{ 6736 Log.warn({ 6737 logLevel, 6738 tag: "audio" 6739 }, "AudioContext resume rejected, continuing without audio sync", err); 6740 resolve(); 6741 }); 6742 }).finally(()=>{ 6743 isResuming.current = null; 6744 }); 6745 return resumePromise.catch(()=>{}); 6746 }, [ 6747 ctxAndGain, 6748 logLevel 6749 ]); 6750 const getIsResumingAudioContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(()=>{ 6751 return isResuming.current; 6752 }, []); 6753 const suspend = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(()=>{ 6754 if (!ctxAndGain) { 6755 return Promise.resolve(); 6756 } 6757 if (!audioContextIsPlayingEventually.current) { 6758 return Promise.resolve(); 6759 } 6760 audioContextIsPlayingEventually.current = false; 6761 return ctxAndGain.suspend(); 6762 }, [ 6763 ctxAndGain 6764 ]); 6765 const audioContextValue = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 6766 return { 6767 audioContext: ctxAndGain?.audioContext ?? null, 6768 getAudioContextState: ()=>ctxAndGain?.getState() ?? null, 6769 gainNode: ctxAndGain?.gainNode ?? null, 6770 audioSyncAnchor, 6771 audioSyncAnchorEmitter, 6772 scheduleAudioNode, 6773 resume, 6774 suspend, 6775 getIsResumingAudioContext, 6776 unscheduleAudioNode 6777 }; 6778 }, [ 6779 ctxAndGain, 6780 audioSyncAnchor, 6781 audioSyncAnchorEmitter, 6782 scheduleAudioNode, 6783 resume, 6784 suspend, 6785 getIsResumingAudioContext, 6786 unscheduleAudioNode 6787 ]); 6788 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(SharedAudioContext.Provider, { 6789 value: audioContextValue, 6790 children 6791 }); 6792}; 6793var SharedAudioTagsContextProvider = ({ children, numberOfAudioTags })=>{ 6794 const audios = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)([]); 6795 const [initialNumberOfAudioTags] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(numberOfAudioTags); 6796 if (numberOfAudioTags !== initialNumberOfAudioTags) { 6797 throw new Error("The number of shared audio tags has changed dynamically. Once you have set this property, you cannot change it afterwards."); 6798 } 6799 const logLevel = useLogLevel(); 6800 const mountTime = useMountTime(); 6801 const env = useRemotionEnvironment(); 6802 const audioCtx = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SharedAudioContext); 6803 const audioContext = audioCtx?.audioContext ?? null; 6804 const resume = audioCtx?.resume; 6805 const refs = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 6806 return new Array(numberOfAudioTags).fill(true).map(()=>{ 6807 const ref = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createRef)(); 6808 return { 6809 id: Math.random(), 6810 ref, 6811 mediaElementSourceNode: audioContext ? makeSharedElementSourceNode({ 6812 audioContext, 6813 ref 6814 }) : null 6815 }; 6816 }); 6817 }, [ 6818 audioContext, 6819 numberOfAudioTags 6820 ]); 6821 const effectToUse = react__WEBPACK_IMPORTED_MODULE_0__.useInsertionEffect ?? react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect; 6822 effectToUse(()=>{ 6823 return ()=>{ 6824 requestAnimationFrame(()=>{
6825 refs.forEach(({ mediaElementSourceNode })=>{ 6826 mediaElementSourceNode?.cleanup(); 6827 }); 6828 }); 6829 }; 6830 }, [ 6831 refs 6832 ]); 6833 const takenAudios = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(new Array(numberOfAudioTags).fill(false)); 6834 const rerenderAudios = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(()=>{ 6835 refs.forEach(({ ref, id })=>{ 6836 const data = audios.current?.find((a2)=>a2.id === id); 6837 const { current } = ref; 6838 if (!current) { 6839 return; 6840 } 6841 if (data === undefined) { 6842 current.src = EMPTY_AUDIO; 6843 return; 6844 } 6845 if (!data) { 6846 throw new TypeError("Expected audio data to be there"); 6847 } 6848 Object.keys(data.props).forEach((key)=>{ 6849 if (didPropChange(key, data.props[key], current[key])) { 6850 current[key] = data.props[key]; 6851 } 6852 }); 6853 }); 6854 }, [ 6855 refs 6856 ]); 6857 const registerAudio = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((options)=>{ 6858 const { aud, audioId, premounting, postmounting } = options; 6859 const found = audios.current?.find((a2)=>a2.audioId === audioId); 6860 if (found) { 6861 return found; 6862 } 6863 const firstFreeAudio = takenAudios.current.findIndex((a2)=>a2 === false); 6864 if (firstFreeAudio === -1) { 6865 throw new Error(`Tried to simultaneously mount ${numberOfAudioTags + 1} <Html5Audio /> tags at the same time. With the current settings, the maximum amount of <Html5Audio /> tags is limited to ${numberOfAudioTags} at the same time. Remotion pre-mounts silent audio tags to help avoid browser autoplay restrictions. See https://remotion.dev/docs/player/autoplay#using-the-numberofsharedaudiotags-prop for more information on how to increase this limit.`); 6866 } 6867 const { id, ref, mediaElementSourceNode } = refs[firstFreeAudio]; 6868 const cloned = [ 6869 ...takenAudios.current 6870 ]; 6871 cloned[firstFreeAudio] = id; 6872 takenAudios.current = cloned; 6873 const newElem = { 6874 props: aud, 6875 id, 6876 el: ref, 6877 audioId, 6878 mediaElementSourceNode, 6879 premounting, 6880 audioMounted: Boolean(ref.current), 6881 postmounting, 6882 cleanupOnMediaTagUnmount: ()=>{} 6883 }; 6884 audios.current?.push(newElem); 6885 rerenderAudios(); 6886 return newElem; 6887 }, [ 6888 numberOfAudioTags, 6889 refs, 6890 rerenderAudios 6891 ]); 6892 const unregisterAudio = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((id)=>{ 6893 const cloned = [ 6894 ...takenAudios.current 6895 ]; 6896 const index = refs.findIndex((r)=>r.id === id); 6897 if (index === -1) { 6898 throw new TypeError("Error occured in "); 6899 } 6900 cloned[index] = false; 6901 takenAudios.current = cloned; 6902 audios.current = audios.current?.filter((a2)=>a2.id !== id); 6903 rerenderAudios(); 6904 }, [ 6905 refs, 6906 rerenderAudios 6907 ]); 6908 const updateAudio = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(({ aud, audioId, id, premounting, postmounting })=>{ 6909 let changed = false; 6910 audios.current = audios.current?.map((prevA)=>{ 6911 const audioMounted = Boolean(prevA.el.current); 6912 if (prevA.audioMounted !== audioMounted) { 6913 changed = true; 6914 } 6915 if (prevA.id === id) { 6916 const isTheSame = compareProps(aud, prevA.props) && prevA.premounting === premounting && prevA.postmounting === postmounting; 6917 if (isTheSame) { 6918 return prevA; 6919 } 6920 changed = true; 6921 return { 6922 ...prevA, 6923 props: aud, 6924 premounting, 6925 postmounting, 6926 audioId, 6927 audioMounted 6928 }; 6929 } 6930 return prevA; 6931 }); 6932 if (changed) { 6933 rerenderAudios(); 6934 } 6935 }, [ 6936 rerenderAudios 6937 ]); 6938 const playAllAudios = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(()=>{
6939 refs.forEach((ref)=>{ 6940 const audio = audios.current.find((a2)=>a2.el === ref.ref); 6941 if (audio?.premounting) { 6942 return; 6943 } 6944 playAndHandleNotAllowedError({ 6945 mediaRef: ref.ref, 6946 mediaType: "audio", 6947 onAutoPlayError: null, 6948 logLevel, 6949 mountTime, 6950 reason: "playing all audios", 6951 isPlayer: env.isPlayer 6952 }); 6953 }); 6954 resume?.(); 6955 }, [ 6956 logLevel, 6957 mountTime, 6958 refs, 6959 env.isPlayer, 6960 resume 6961 ]); 6962 const audioTagsValue = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 6963 return { 6964 registerAudio, 6965 unregisterAudio, 6966 updateAudio, 6967 playAllAudios, 6968 numberOfAudioTags 6969 }; 6970 }, [ 6971 numberOfAudioTags, 6972 playAllAudios, 6973 registerAudio, 6974 unregisterAudio, 6975 updateAudio 6976 ]); 6977 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsxs)(SharedAudioTagsContext.Provider, { 6978 value: audioTagsValue, 6979 children: [ 6980 refs.map(({ id, ref })=>{ 6981 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)("audio", { 6982 ref, 6983 preload: "metadata", 6984 src: EMPTY_AUDIO 6985 }, id); 6986 }), 6987 children 6988 ] 6989 }); 6990}; 6991var useSharedAudio = ({ aud, audioId, premounting, postmounting })=>{ 6992 const audioCtx = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SharedAudioContext); 6993 const tagsCtx = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SharedAudioTagsContext); 6994 const [elem] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(()=>{ 6995 if (tagsCtx && tagsCtx.numberOfAudioTags > 0) { 6996 return tagsCtx.registerAudio({ 6997 aud, 6998 audioId, 6999 premounting, 7000 postmounting 7001 }); 7002 } 7003 const el = /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createRef(); 7004 const mediaElementSourceNode = audioCtx?.audioContext ? makeSharedElementSourceNode({ 7005 audioContext: audioCtx.audioContext, 7006 ref: el 7007 }) : null; 7008 return { 7009 el, 7010 id: Math.random(), 7011 props: aud, 7012 audioId, 7013 mediaElementSourceNode, 7014 premounting, 7015 audioMounted: Boolean(el.current), 7016 postmounting, 7017 cleanupOnMediaTagUnmount: ()=>{ 7018 mediaElementSourceNode?.cleanup(); 7019 } 7020 }; 7021 }); 7022 const effectToUse = react__WEBPACK_IMPORTED_MODULE_0__.useInsertionEffect ?? react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect; 7023 if (typeof document !== "undefined") { 7024 effectToUse(()=>{ 7025 if (tagsCtx && tagsCtx.numberOfAudioTags > 0) { 7026 tagsCtx.updateAudio({ 7027 id: elem.id, 7028 aud, 7029 audioId, 7030 premounting, 7031 postmounting 7032 }); 7033 } 7034 }, [ 7035 aud, 7036 tagsCtx, 7037 elem.id, 7038 audioId, 7039 premounting, 7040 postmounting 7041 ]); 7042 effectToUse(()=>{ 7043 return ()=>{ 7044 if (tagsCtx && tagsCtx.numberOfAudioTags > 0) { 7045 tagsCtx.unregisterAudio(elem.id); 7046 } 7047 }; 7048 }, [ 7049 tagsCtx, 7050 elem.id 7051 ]); 7052 } 7053 return elem; 7054};
7055// src/is-approximately-the-same.ts 7056var FLOATING_POINT_ERROR_THRESHOLD = 0.00001; 7057var isApproximatelyTheSame = (num1, num2)=>{ 7058 return Math.abs(num1 - num2) < FLOATING_POINT_ERROR_THRESHOLD; 7059};
vendor: 6,828 bytes, lines 7060-7259
7060// src/video/video-fragment.ts 7061 7062var toSeconds = (time, fps)=>{ 7063 return Math.round(time / fps * 100) / 100; 7064}; 7065var isSafari = ()=>{ 7066 if (typeof window === "undefined") { 7067 return false; 7068 } 7069 const isAppleWebKit = /AppleWebKit/.test(window.navigator.userAgent); 7070 if (!isAppleWebKit) { 7071 return false; 7072 } 7073 const isNotChrome = !window.navigator.userAgent.includes("Chrome/"); 7074 return isNotChrome; 7075}; 7076var isIosSafari = ()=>{ 7077 if (typeof window === "undefined") { 7078 return false; 7079 } 7080 const isIpadIPodIPhone = /iP(ad|od|hone)/i.test(window.navigator.userAgent); 7081 return isIpadIPodIPhone && isSafari(); 7082}; 7083var isIOSSafariAndBlob = (actualSrc)=>{ 7084 return isIosSafari() && actualSrc.startsWith("blob:"); 7085}; 7086var getVideoFragmentStart = ({ actualFrom, fps })=>{ 7087 return toSeconds(Math.max(0, -actualFrom), fps); 7088}; 7089var getVideoFragmentEnd = ({ duration, fps })=>{ 7090 return toSeconds(duration, fps); 7091}; 7092var appendVideoFragment = ({ actualSrc, actualFrom, duration, fps })=>{ 7093 if (isIOSSafariAndBlob(actualSrc)) { 7094 return actualSrc; 7095 } 7096 if (actualSrc.startsWith("data:")) { 7097 return actualSrc; 7098 } 7099 const existingHash = Boolean(new URL(actualSrc, (typeof window === "undefined" ? null : window.location.href) ?? "http://localhost:3000").hash); 7100 if (existingHash) { 7101 return actualSrc; 7102 } 7103 if (!Number.isFinite(actualFrom)) { 7104 return actualSrc; 7105 } 7106 const withStartHash = `${actualSrc}#t=${getVideoFragmentStart({ 7107 actualFrom, 7108 fps 7109 })}`; 7110 if (!Number.isFinite(duration)) { 7111 return withStartHash; 7112 } 7113 return `${withStartHash},${getVideoFragmentEnd({ 7114 duration, 7115 fps 7116 })}`; 7117}; 7118var isSubsetOfDuration = ({ prevStartFrom, newStartFrom, prevDuration, newDuration, fps })=>{ 7119 const previousFrom = getVideoFragmentStart({ 7120 actualFrom: prevStartFrom, 7121 fps 7122 }); 7123 const newFrom = getVideoFragmentStart({ 7124 actualFrom: newStartFrom, 7125 fps 7126 }); 7127 const previousEnd = getVideoFragmentEnd({ 7128 duration: prevDuration, 7129 fps 7130 }); 7131 const newEnd = getVideoFragmentEnd({ 7132 duration: newDuration, 7133 fps 7134 }); 7135 if (newFrom < previousFrom) { 7136 return false; 7137 } 7138 if (newEnd > previousEnd) { 7139 return false; 7140 } 7141 return true; 7142}; 7143var useAppendVideoFragment = ({ actualSrc: initialActualSrc, actualFrom: initialActualFrom, duration: initialDuration, fps })=>{ 7144 const actualFromRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(initialActualFrom); 7145 const actualDuration = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(initialDuration); 7146 const actualSrc = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(initialActualSrc); 7147 if (!isSubsetOfDuration({ 7148 prevStartFrom: actualFromRef.current, 7149 newStartFrom: initialActualFrom, 7150 prevDuration: actualDuration.current, 7151 newDuration: initialDuration, 7152 fps 7153 }) || initialActualSrc !== actualSrc.current) { 7154 actualFromRef.current = initialActualFrom; 7155 actualDuration.current = initialDuration; 7156 actualSrc.current = initialActualSrc; 7157 } 7158 const appended = appendVideoFragment({ 7159 actualSrc: actualSrc.current, 7160 actualFrom: actualFromRef.current, 7161 duration: actualDuration.current, 7162 fps 7163 }); 7164 return appended; 7165}; 7166// src/use-amplification.ts 7167var warned2 = false; 7168var warnSafariOnce = (logLevel)=>{ 7169 if (warned2) { 7170 return; 7171 } 7172 warned2 = true; 7173 Log.warn({ 7174 logLevel, 7175 tag: null 7176 }, "In Safari, setting a volume and a playback rate at the same time is buggy."); 7177 Log.warn({ 7178 logLevel, 7179 tag: null 7180 }, "In Desktop Safari, only volumes <= 1 will be applied."); 7181 Log.warn({ 7182 logLevel, 7183 tag: null 7184 }, logLevel, "In Mobile Safari, the volume will be ignored and set to 1 if a playbackRate is set."); 7185}; 7186var useVolume = ({ mediaRef, volume, logLevel, source, shouldUseWebAudioApi })=>{ 7187 const audioStuffRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 7188 const currentVolumeRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(volume); 7189 currentVolumeRef.current = volume; 7190 const sharedAudioContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SharedAudioContext); 7191 if (!sharedAudioContext) { 7192 throw new Error("useAmplification must be used within a SharedAudioContext"); 7193 } 7194 const { audioContext, gainNode: masterGainNode } = sharedAudioContext; 7195 if (typeof window !== "undefined") { 7196 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 7197 if (!audioContext) { 7198 return; 7199 } 7200 if (!mediaRef.current) { 7201 return; 7202 } 7203 if (!shouldUseWebAudioApi) { 7204 return; 7205 } 7206 if (mediaRef.current.playbackRate !== 1 && isSafari()) { 7207 warnSafariOnce(logLevel); 7208 return; 7209 } 7210 if (!source) { 7211 return; 7212 } 7213 if (!masterGainNode) { 7214 return; 7215 } 7216 const gainNode = new GainNode(audioContext, { 7217 gain: currentVolumeRef.current 7218 }); 7219 source.attemptToConnect(); 7220 source.get().connect(gainNode); 7221 gainNode.connect(masterGainNode); 7222 audioStuffRef.current = { 7223 gainNode 7224 }; 7225 Log.trace({ 7226 logLevel, 7227 tag: null 7228 }, `Starting to amplify ${mediaRef.current?.src}. Gain = ${currentVolumeRef.current}, playbackRate = ${mediaRef.current?.playbackRate}`); 7229 return ()=>{ 7230 audioStuffRef.current = null; 7231 gainNode.disconnect(); 7232 source.get().disconnect(); 7233 }; 7234 }, [ 7235 logLevel, 7236 mediaRef, 7237 audioContext, 7238 source, 7239 shouldUseWebAudioApi, 7240 masterGainNode 7241 ]); 7242 } 7243 if (audioStuffRef.current) { 7244 const valueToSet = volume; 7245 if (!isApproximatelyTheSame(audioStuffRef.current.gainNode.gain.value, valueToSet)) { 7246 audioStuffRef.current.gainNode.gain.value = valueToSet; 7247 Log.trace({ 7248 logLevel, 7249 tag: null 7250 }, `Setting gain to ${valueToSet} for ${mediaRef.current?.src}`); 7251 } 7252 } 7253 const safariCase = isSafari() && mediaRef.current && mediaRef.current?.playbackRate !== 1; 7254 const shouldUseTraditionalVolume = safariCase || !shouldUseWebAudioApi; 7255 if (shouldUseTraditionalVolume && mediaRef.current && !isApproximatelyTheSame(volume, mediaRef.current?.volume)) { 7256 mediaRef.current.volume = Math.min(volume, 1); 7257 } 7258 return audioStuffRef; 7259};
7260// src/use-media-in-timeline.ts 7261
7262// src/audio/use-audio-frame.ts 7263 7264var useMediaStartsAt = ()=>{ 7265 const parentSequence = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SequenceContext); 7266 return parentSequence?.cumulatedNegativeFrom ?? 0; 7267}; 7268var useFrameForVolumeProp = (behavior)=>{ 7269 const loop = Loop.useLoop(); 7270 const frame = useCurrentFrame(); 7271 const startsAt = useMediaStartsAt(); 7272 if (behavior === "repeat" || loop === null) { 7273 return frame + startsAt; 7274 } 7275 return frame + startsAt + loop.durationInFrames * loop.iteration; 7276};
7277// src/get-asset-file-name.ts 7278var getAssetDisplayName = (filename)=>{ 7279 if (/data:|blob:/.test(filename.substring(0, 5))) { 7280 return "Data URL"; 7281 } 7282 const splitted = filename.split("/").map((s)=>s.split("\\")).flat(1); 7283 return splitted[splitted.length - 1]; 7284};
7285// src/get-timeline-duration.ts 7286var getTimelineDuration = ({ compositionDurationInFrames, playbackRate, trimBefore, trimAfter, parentSequenceDurationInFrames, loop })=>{ 7287 if (loop) { 7288 return compositionDurationInFrames; 7289 } 7290 const mediaDuration = calculateMediaDuration({ 7291 mediaDurationInFrames: compositionDurationInFrames * playbackRate + (trimBefore ?? 0), 7292 playbackRate, 7293 trimBefore, 7294 trimAfter 7295 }); 7296 if (parentSequenceDurationInFrames !== null) { 7297 const cappedDuration = Math.min(parentSequenceDurationInFrames, mediaDuration); 7298 return Number(cappedDuration.toFixed(10)); 7299 } 7300 return mediaDuration; 7301};
7302// src/volume-prop.ts 7303var evaluateVolume = ({ frame, volume, mediaVolume = 1 })=>{ 7304 if (typeof volume === "number") { 7305 return volume * mediaVolume; 7306 } 7307 if (typeof volume === "undefined") { 7308 return Number(mediaVolume); 7309 } 7310 const evaluated = volume(frame) * mediaVolume; 7311 if (typeof evaluated !== "number") { 7312 throw new TypeError(`You passed in a a function to the volume prop but it did not return a number but a value of type ${typeof evaluated} for frame ${frame}`); 7313 } 7314 if (Number.isNaN(evaluated)) { 7315 throw new TypeError(`You passed in a function to the volume prop but it returned NaN for frame ${frame}.`); 7316 } 7317 if (!Number.isFinite(evaluated)) { 7318 throw new TypeError(`You passed in a function to the volume prop but it returned a non-finite number for frame ${frame}.`); 7319 } 7320 return Math.max(0, evaluated); 7321};
7322// src/use-media-in-timeline.ts 7323var didWarn = {}; 7324var warnOnce2 = (message)=>{ 7325 if (didWarn[message]) { 7326 return; 7327 } 7328 console.warn(message); 7329 didWarn[message] = true; 7330}; 7331var useBasicMediaInTimeline = ({ volume, mediaVolume, mediaType, src, displayName, trimBefore, trimAfter, playbackRate, sequenceDurationInFrames, mediaStartsAt, loop })=>{ 7332 if (!src) { 7333 throw new Error("No src passed"); 7334 } 7335 const parentSequence = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SequenceContext); 7336 const [initialVolume] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(()=>volume); 7337 const duration = getTimelineDuration({ 7338 compositionDurationInFrames: sequenceDurationInFrames, 7339 playbackRate, 7340 trimBefore, 7341 trimAfter, 7342 parentSequenceDurationInFrames: parentSequence?.durationInFrames ?? null, 7343 loop 7344 }); 7345 const volumes = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 7346 if (typeof volume === "number") { 7347 return volume; 7348 } 7349 return new Array(Math.floor(Math.max(0, duration + mediaStartsAt))).fill(true).map((_, i)=>{ 7350 return evaluateVolume({ 7351 frame: i + mediaStartsAt, 7352 volume, 7353 mediaVolume 7354 }); 7355 }).join(","); 7356 }, [ 7357 duration, 7358 mediaStartsAt, 7359 volume, 7360 mediaVolume 7361 ]); 7362 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 7363 if (typeof volume === "number" && volume !== initialVolume) { 7364 warnOnce2(`Remotion: The ${mediaType} with src ${src} has changed it's volume. Prefer the callback syntax for setting volume to get better timeline display: https://www.remotion.dev/docs/audio/volume`); 7365 } 7366 }, [ 7367 initialVolume, 7368 mediaType, 7369 src, 7370 volume 7371 ]); 7372 const doesVolumeChange = typeof volume === "function"; 7373 const nonce = useNonce(); 7374 const { rootId } = useTimelineContext(); 7375 const startMediaFrom = 0 - mediaStartsAt + (trimBefore ?? 0); 7376 const memoizedResult = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 7377 return { 7378 volumes, 7379 duration, 7380 doesVolumeChange, 7381 nonce, 7382 rootId, 7383 finalDisplayName: displayName ?? getAssetDisplayName(src), 7384 startMediaFrom, 7385 src, 7386 playbackRate 7387 }; 7388 }, [ 7389 volumes, 7390 duration, 7391 doesVolumeChange, 7392 nonce, 7393 rootId, 7394 displayName, 7395 src, 7396 startMediaFrom, 7397 playbackRate 7398 ]); 7399 return memoizedResult; 7400}; 7401var useMediaInTimeline = ({ volume, mediaVolume, src, mediaType, playbackRate, displayName, id, getStack, showInTimeline, premountDisplay, postmountDisplay, loopDisplay, documentationLink, refForOutline })=>{ 7402 const parentSequence = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SequenceContext); 7403 const startsAt = useMediaStartsAt(); 7404 const { registerSequence, unregisterSequence } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SequenceManager); 7405 const { durationInFrames } = useVideoConfig(); 7406 const mediaStartsAt = useMediaStartsAt(); 7407 const { volumes, duration, doesVolumeChange, nonce, rootId, finalDisplayName } = useBasicMediaInTimeline({ 7408 volume, 7409 mediaVolume, 7410 mediaType, 7411 src, 7412 displayName, 7413 trimAfter: undefined, 7414 trimBefore: undefined, 7415 playbackRate, 7416 sequenceDurationInFrames: durationInFrames, 7417 mediaStartsAt, 7418 loop: false 7419 }); 7420 const { isStudio } = useRemotionEnvironment(); 7421 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 7422 if (!src) { 7423 throw new Error("No src passed"); 7424 } 7425 if (!isStudio && window.process?.env?.NODE_ENV !== "test") { 7426 return; 7427 } 7428 if (!showInTimeline) { 7429 return; 7430 } 7431 registerSequence({ 7432 type: mediaType, 7433 src, 7434 id, 7435 duration, 7436 from: 0, 7437 trimBefore: null, 7438 parent: parentSequence?.id ?? null, 7439 displayName: finalDisplayName, 7440 documentationLink, 7441 rootId, 7442 volume: volumes, 7443 showInTimeline: true, 7444 nonce: nonce.get(), 7445 startMediaFrom: 0 - startsAt, 7446 doesVolumeChange, 7447 loopDisplay, 7448 playbackRate, 7449 getStack,
7450 premountDisplay, 7451 postmountDisplay, 7452 controls: null, 7453 effects: [], 7454 refForOutline, 7455 isInsideSeries: false, 7456 frozenFrame: null, 7457 frozenMediaFrame: null 7458 }); 7459 return ()=>{ 7460 unregisterSequence(id); 7461 }; 7462 }, [ 7463 duration, 7464 id, 7465 parentSequence, 7466 src, 7467 registerSequence, 7468 unregisterSequence, 7469 volumes, 7470 doesVolumeChange, 7471 nonce, 7472 mediaType, 7473 startsAt, 7474 playbackRate, 7475 getStack, 7476 showInTimeline, 7477 premountDisplay, 7478 postmountDisplay, 7479 loopDisplay, 7480 documentationLink, 7481 rootId, 7482 finalDisplayName, 7483 isStudio, 7484 refForOutline 7485 ]); 7486};
7487// src/use-media-playback.ts 7488
7489// src/buffer-until-first-frame.ts 7490
7491// src/use-buffer-state.ts 7492
7493// src/buffering.tsx 7494 7495 7496var useBufferManager = (logLevel, mountTime)=>{ 7497 const [blocks, setBlocks] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)([]); 7498 const [onBufferingCallbacks, setOnBufferingCallbacks] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)([]); 7499 const [onResumeCallbacks, setOnResumeCallbacks] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)([]); 7500 const env = useRemotionEnvironment(); 7501 const rendering = env.isRendering; 7502 const buffering = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(false); 7503 const addBlock = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((block)=>{ 7504 if (rendering) { 7505 return { 7506 unblock: ()=>{ 7507 return; 7508 } 7509 }; 7510 } 7511 let unblocked = false; 7512 setBlocks((b2)=>[ 7513 ...b2, 7514 block 7515 ]); 7516 return { 7517 unblock: ()=>{ 7518 if (unblocked) { 7519 return; 7520 } 7521 unblocked = true; 7522 setBlocks((b2)=>{ 7523 const newArr = b2.filter((bx)=>bx !== block); 7524 if (newArr.length === b2.length) { 7525 return b2; 7526 } 7527 return newArr; 7528 }); 7529 } 7530 }; 7531 }, [ 7532 rendering 7533 ]); 7534 const listenForBuffering = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((callback)=>{ 7535 setOnBufferingCallbacks((c2)=>[ 7536 ...c2, 7537 callback 7538 ]); 7539 return { 7540 remove: ()=>{ 7541 setOnBufferingCallbacks((c2)=>c2.filter((cb)=>cb !== callback)); 7542 } 7543 }; 7544 }, []); 7545 const listenForResume = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((callback)=>{ 7546 setOnResumeCallbacks((c2)=>[ 7547 ...c2, 7548 callback 7549 ]); 7550 return { 7551 remove: ()=>{ 7552 setOnResumeCallbacks((c2)=>c2.filter((cb)=>cb !== callback)); 7553 } 7554 }; 7555 }, []); 7556 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 7557 if (rendering) { 7558 return; 7559 } 7560 if (blocks.length > 0 && !buffering.current) { 7561 buffering.current = true; 7562 onBufferingCallbacks.forEach((c2)=>c2()); 7563 playbackLogging({ 7564 logLevel, 7565 message: "Player is entering buffer state", 7566 mountTime, 7567 tag: "player" 7568 }); 7569 } 7570 }, [ 7571 blocks 7572 ]); 7573 if (typeof window !== "undefined") { 7574 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 7575 if (rendering) { 7576 return; 7577 } 7578 if (blocks.length === 0 && buffering.current) { 7579 buffering.current = false; 7580 onResumeCallbacks.forEach((c2)=>c2()); 7581 playbackLogging({ 7582 logLevel, 7583 message: "Player is exiting buffer state", 7584 mountTime, 7585 tag: "player" 7586 }); 7587 } 7588 }, [ 7589 blocks 7590 ]); 7591 } 7592 return (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 7593 return { 7594 addBlock, 7595 listenForBuffering, 7596 listenForResume, 7597 buffering 7598 }; 7599 }, [ 7600 addBlock, 7601 buffering, 7602 listenForBuffering, 7603 listenForResume 7604 ]); 7605}; 7606var BufferingContextReact = /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createContext(null); 7607var BufferingProvider = ({ children })=>{ 7608 const { logLevel, mountTime } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(LogLevelContext); 7609 const bufferManager = useBufferManager(logLevel ?? "info", mountTime); 7610 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(BufferingContextReact.Provider, { 7611 value: bufferManager, 7612 children 7613 }); 7614}; 7615var useIsPlayerBuffering = (bufferManager)=>{ 7616 const [isBuffering, setIsBuffering] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(bufferManager.buffering.current); 7617 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 7618 const onBuffer = ()=>{ 7619 setIsBuffering(true); 7620 }; 7621 const onResume = ()=>{ 7622 setIsBuffering(false); 7623 }; 7624 const buffer = bufferManager.listenForBuffering(onBuffer); 7625 const resume = bufferManager.listenForResume(onResume); 7626 return ()=>{ 7627 buffer.remove(); 7628 resume.remove(); 7629 }; 7630 }, [ 7631 bufferManager 7632 ]); 7633 return isBuffering; 7634};
7635// src/use-buffer-state.ts 7636var useBufferState = ()=>{ 7637 const buffer = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(BufferingContextReact); 7638 const logLevel = useLogLevel(); 7639 const addBlock = buffer ? buffer.addBlock : null; 7640 return (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>({ 7641 delayPlayback: ()=>{ 7642 if (!addBlock) { 7643 throw new Error("Tried to enable the buffering state, but a Remotion context was not found. This API can only be called in a component that was passed to the Remotion Player or a <Composition>. Or you might have experienced a version mismatch - run `npx remotion versions` and ensure all packages have the same version. This error is thrown by the buffer state https://remotion.dev/docs/player/buffer-state"); 7644 } 7645 Log.trace({ 7646 logLevel, 7647 tag: "[buffer-state]" 7648 }, "Adding buffer handle", new Error().stack); 7649 const { unblock } = addBlock({ 7650 id: String(Math.random()) 7651 }); 7652 let unblocked = false; 7653 return { 7654 unblock: ()=>{ 7655 if (unblocked) { 7656 return; 7657 } 7658 unblocked = true; 7659 Log.trace({ 7660 logLevel, 7661 tag: "[buffer-state]" 7662 }, "Removing buffer handle"); 7663 unblock(); 7664 } 7665 }; 7666 } 7667 }), [ 7668 addBlock, 7669 logLevel 7670 ]); 7671};
vendor: 6,111 bytes, lines 7672-7812
7672// src/buffer-until-first-frame.ts 7673var isSafariWebkit = ()=>{ 7674 const isSafari2 = /^((?!chrome|android).)*safari/i.test(window.navigator.userAgent); 7675 return isSafari2; 7676}; 7677var useBufferUntilFirstFrame = ({ mediaRef, mediaType, onVariableFpsVideoDetected, pauseWhenBuffering, logLevel, mountTime })=>{ 7678 const bufferingRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(false); 7679 const { delayPlayback } = useBufferState(); 7680 const bufferUntilFirstFrame = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((requestedTime)=>{ 7681 if (mediaType !== "video") { 7682 return; 7683 } 7684 if (!pauseWhenBuffering) { 7685 return; 7686 } 7687 const current = mediaRef.current; 7688 if (!current) { 7689 return; 7690 } 7691 if (current.readyState >= current.HAVE_FUTURE_DATA && !isSafariWebkit()) { 7692 playbackLogging({ 7693 logLevel, 7694 message: `Not using buffer until first frame, because readyState is ${current.readyState} and is not Safari or Desktop Chrome`, 7695 mountTime, 7696 tag: "buffer" 7697 }); 7698 return; 7699 } 7700 if (!current.requestVideoFrameCallback) { 7701 playbackLogging({ 7702 logLevel, 7703 message: `Not using buffer until first frame, because requestVideoFrameCallback is not supported`, 7704 mountTime, 7705 tag: "buffer" 7706 }); 7707 return; 7708 } 7709 bufferingRef.current = true; 7710 playbackLogging({ 7711 logLevel, 7712 message: `Buffering ${mediaRef.current?.src} until the first frame is received`, 7713 mountTime, 7714 tag: "buffer" 7715 }); 7716 const playback = delayPlayback(); 7717 const unblock = ()=>{ 7718 playback.unblock(); 7719 current.removeEventListener("ended", unblock, { 7720 once: true 7721 }); 7722 current.removeEventListener("pause", unblock, { 7723 once: true 7724 }); 7725 bufferingRef.current = false; 7726 }; 7727 const onEndedOrPauseOrCanPlay = ()=>{ 7728 unblock(); 7729 }; 7730 current.requestVideoFrameCallback((_, info2)=>{ 7731 const differenceFromRequested = Math.abs(info2.mediaTime - requestedTime); 7732 if (differenceFromRequested > 0.5) { 7733 onVariableFpsVideoDetected(); 7734 } 7735 unblock(); 7736 }); 7737 current.addEventListener("ended", onEndedOrPauseOrCanPlay, { 7738 once: true 7739 }); 7740 current.addEventListener("pause", onEndedOrPauseOrCanPlay, { 7741 once: true 7742 }); 7743 current.addEventListener("canplay", onEndedOrPauseOrCanPlay, { 7744 once: true 7745 }); 7746 }, [ 7747 delayPlayback, 7748 logLevel, 7749 mediaRef, 7750 mediaType, 7751 mountTime, 7752 onVariableFpsVideoDetected, 7753 pauseWhenBuffering 7754 ]); 7755 return (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 7756 return { 7757 isBuffering: ()=>bufferingRef.current, 7758 bufferUntilFirstFrame 7759 }; 7760 }, [ 7761 bufferUntilFirstFrame 7762 ]); 7763}; 7764// src/get-media-sync-action.ts 7765var getMediaSyncAction = (input)=>{ 7766 const { duration, currentTime, paused, ended, desiredUnclampedTime, mediaTagTime, mediaTagLastUpdate, rvcTime, rvcLastUpdate, isVariableFpsVideo, acceptableTimeShift, lastSeekDueToShift, playing, playbackRate, mediaTagBufferingOrStalled, playerBuffering, absoluteFrame, onlyWarnForMediaSeekingError, isPremounting, isPostmounting, pauseWhenBuffering } = input; 7767 const shouldBeTime = !Number.isNaN(duration) && Number.isFinite(duration) ? Math.min(duration, desiredUnclampedTime) : desiredUnclampedTime; 7768 const timeShiftMediaTag = Math.abs(shouldBeTime - mediaTagTime); 7769 const timeShiftRvcTag = rvcTime ? Math.abs(shouldBeTime - rvcTime) : null; 7770 const mostRecentTimeshift = rvcLastUpdate && rvcTime > mediaTagLastUpdate ? timeShiftRvcTag : timeShiftMediaTag; 7771 const timeShift = timeShiftRvcTag && !isVariableFpsVideo ? mostRecentTimeshift : timeShiftMediaTag; 7772 if (timeShift > acceptableTimeShift && lastSeekDueToShift !== shouldBeTime) { 7773 return { 7774 type: "seek-due-to-shift", 7775 shouldBeTime, 7776 why: `because time shift is too big. shouldBeTime = ${shouldBeTime}, isTime = ${mediaTagTime}, requestVideoCallbackTime = ${rvcTime}, timeShift = ${timeShift}${isVariableFpsVideo ? ", isVariableFpsVideo = true" : ""}, isPremounting = ${isPremounting}, isPostmounting = ${isPostmounting}, pauseWhenBuffering = ${pauseWhenBuffering}`, 7777 bufferUntilFirstFrame: playing && playbackRate > 0, 7778 playReason: playing && paused ? "player is playing but media tag is paused, and just seeked" : null, 7779 warnAboutNonSeekable: !onlyWarnForMediaSeekingError 7780 }; 7781 } 7782 const seekThreshold = playing ? 0.15 : 0.01; 7783 const makesSenseToSeek = Math.abs(currentTime - shouldBeTime) > seekThreshold; 7784 const isSomethingElseBuffering = playerBuffering && !mediaTagBufferingOrStalled; 7785 if (!playing || isSomethingElseBuffering) { 7786 return { 7787 type: "seek-if-not-playing", 7788 shouldBeTime, 7789 why: makesSenseToSeek ? `not playing or something else is buffering. time offset is over seek threshold (${seekThreshold})` : null 7790 }; 7791 } 7792 if (!playing || playerBuffering) { 7793 return { 7794 type: "none" 7795 }; 7796 } 7797 const pausedCondition = paused && !ended; 7798 const firstFrameCondition = absoluteFrame === 0; 7799 if (pausedCondition || firstFrameCondition) { 7800 const reason = pausedCondition ? "media tag is paused" : "absolute frame is 0"; 7801 return { 7802 type: "play-and-seek", 7803 shouldBeTime, 7804 why: makesSenseToSeek ? `is over timeshift threshold (threshold = ${seekThreshold}) and ${reason}` : null, 7805 playReason: `player is playing and ${reason}`, 7806 bufferUntilFirstFrame: !isVariableFpsVideo && playbackRate > 0 7807 }; 7808 } 7809 return { 7810 type: "none" 7811 }; 7812};
7813// src/media-tag-current-time-timestamp.ts 7814 7815var useCurrentTimeOfMediaTagWithUpdateTimeStamp = (mediaRef)=>{ 7816 const lastUpdate = react__WEBPACK_IMPORTED_MODULE_0__.useRef({ 7817 time: mediaRef.current?.currentTime ?? 0, 7818 lastUpdate: performance.now() 7819 }); 7820 const nowCurrentTime = mediaRef.current?.currentTime ?? null; 7821 if (nowCurrentTime !== null) { 7822 if (lastUpdate.current.time !== nowCurrentTime) { 7823 lastUpdate.current.time = nowCurrentTime; 7824 lastUpdate.current.lastUpdate = performance.now(); 7825 } 7826 } 7827 return lastUpdate; 7828};
7829// src/seek.ts 7830var seek = ({ mediaRef, time, logLevel, why, mountTime })=>{ 7831 const timeToSet = isIosSafari() ? Number(time.toFixed(1)) : time; 7832 playbackLogging({ 7833 logLevel, 7834 tag: "seek", 7835 message: `Seeking from ${mediaRef.currentTime} to ${timeToSet}. src= ${mediaRef.src} Reason: ${why}`, 7836 mountTime 7837 }); 7838 mediaRef.currentTime = timeToSet; 7839 return timeToSet; 7840};
vendor: 6,925 bytes, lines 7841-8034
7841// src/use-media-buffering.ts 7842 7843var useMediaBuffering = ({ element, shouldBuffer, isPremounting, isPostmounting, logLevel, mountTime, src })=>{ 7844 const buffer = useBufferState(); 7845 const [isBuffering, setIsBuffering] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false); 7846 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 7847 let cleanupFns = []; 7848 const { current } = element; 7849 if (!current) { 7850 return; 7851 } 7852 if (!shouldBuffer) { 7853 return; 7854 } 7855 if (isPremounting || isPostmounting) { 7856 if ((isPremounting || isPostmounting) && current.readyState < current.HAVE_FUTURE_DATA) { 7857 if (!navigator.userAgent.includes("Firefox/")) { 7858 playbackLogging({ 7859 logLevel, 7860 message: `Calling .load() on ${current.src} because readyState is ${current.readyState} and it is not Firefox. Element is premounted ${current.playbackRate}`, 7861 tag: "load", 7862 mountTime 7863 }); 7864 const previousPlaybackRate = current.playbackRate; 7865 current.load(); 7866 current.playbackRate = previousPlaybackRate; 7867 } 7868 } 7869 return; 7870 } 7871 const cleanup = (reason)=>{ 7872 let didDoSomething = false; 7873 cleanupFns.forEach((fn)=>{ 7874 fn(reason); 7875 didDoSomething = true; 7876 }); 7877 cleanupFns = []; 7878 setIsBuffering((previous)=>{ 7879 if (previous) { 7880 didDoSomething = true; 7881 } 7882 return false; 7883 }); 7884 if (didDoSomething) { 7885 playbackLogging({ 7886 logLevel, 7887 message: `Unmarking as buffering: ${current.src}. Reason: ${reason}`, 7888 tag: "buffer", 7889 mountTime 7890 }); 7891 } 7892 }; 7893 const blockMedia = (reason)=>{ 7894 setIsBuffering(true); 7895 playbackLogging({ 7896 logLevel, 7897 message: `Marking as buffering: ${current.src}. Reason: ${reason}`, 7898 tag: "buffer", 7899 mountTime 7900 }); 7901 const { unblock } = buffer.delayPlayback(); 7902 const onCanPlay = ()=>{ 7903 cleanup('"canplay" was fired'); 7904 init(); 7905 }; 7906 const onError = ()=>{ 7907 cleanup('"error" event was occurred'); 7908 init(); 7909 }; 7910 current.addEventListener("canplay", onCanPlay, { 7911 once: true 7912 }); 7913 cleanupFns.push(()=>{ 7914 current.removeEventListener("canplay", onCanPlay); 7915 }); 7916 current.addEventListener("error", onError, { 7917 once: true 7918 }); 7919 cleanupFns.push(()=>{ 7920 current.removeEventListener("error", onError); 7921 }); 7922 cleanupFns.push((cleanupReason)=>{ 7923 playbackLogging({ 7924 logLevel, 7925 message: `Unblocking ${current.src} from buffer. Reason: ${cleanupReason}`, 7926 tag: "buffer", 7927 mountTime 7928 }); 7929 unblock(); 7930 }); 7931 }; 7932 const init = ()=>{ 7933 if (current.readyState < current.HAVE_FUTURE_DATA) { 7934 blockMedia(`readyState is ${current.readyState}, which is less than HAVE_FUTURE_DATA`); 7935 if (!navigator.userAgent.includes("Firefox/")) { 7936 playbackLogging({ 7937 logLevel, 7938 message: `Calling .load() on ${src} because readyState is ${current.readyState} and it is not Firefox. ${current.playbackRate}`, 7939 tag: "load", 7940 mountTime 7941 }); 7942 const previousPlaybackRate = current.playbackRate; 7943 current.load(); 7944 current.playbackRate = previousPlaybackRate; 7945 } 7946 } else { 7947 const onWaiting = ()=>{ 7948 blockMedia('"waiting" event was fired'); 7949 }; 7950 current.addEventListener("waiting", onWaiting); 7951 cleanupFns.push(()=>{ 7952 current.removeEventListener("waiting", onWaiting); 7953 }); 7954 } 7955 }; 7956 init(); 7957 return ()=>{ 7958 cleanup("element was unmounted or prop changed"); 7959 }; 7960 }, [ 7961 buffer, 7962 src, 7963 element, 7964 isPremounting, 7965 isPostmounting, 7966 logLevel, 7967 shouldBuffer, 7968 mountTime 7969 ]); 7970 return isBuffering; 7971}; 7972// src/use-request-video-callback-time.ts 7973 7974var useRequestVideoCallbackTime = ({ mediaRef, mediaType, lastSeek, onVariableFpsVideoDetected })=>{ 7975 const currentTime = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 7976 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 7977 const { current } = mediaRef; 7978 if (current) { 7979 currentTime.current = { 7980 time: current.currentTime, 7981 lastUpdate: performance.now() 7982 }; 7983 } else { 7984 currentTime.current = null; 7985 return; 7986 } 7987 if (mediaType !== "video") { 7988 currentTime.current = null; 7989 return; 7990 } 7991 const videoTag = current; 7992 if (!videoTag.requestVideoFrameCallback) { 7993 return; 7994 } 7995 let cancel = ()=>{ 7996 return; 7997 }; 7998 const request = ()=>{ 7999 if (!videoTag) { 8000 return; 8001 } 8002 const cb = videoTag.requestVideoFrameCallback((_, info2)=>{ 8003 if (currentTime.current !== null) { 8004 const difference = Math.abs(currentTime.current.time - info2.mediaTime); 8005 const differenceToLastSeek = Math.abs(lastSeek.current === null ? Infinity : info2.mediaTime - lastSeek.current); 8006 if (difference > 0.5 && differenceToLastSeek > 0.5 && info2.mediaTime > currentTime.current.time) { 8007 onVariableFpsVideoDetected(); 8008 } 8009 } 8010 currentTime.current = { 8011 time: info2.mediaTime, 8012 lastUpdate: performance.now() 8013 }; 8014 request(); 8015 }); 8016 cancel = ()=>{ 8017 videoTag.cancelVideoFrameCallback(cb); 8018 cancel = ()=>{ 8019 return; 8020 }; 8021 }; 8022 }; 8023 request(); 8024 return ()=>{ 8025 cancel(); 8026 }; 8027 }, [ 8028 lastSeek, 8029 mediaRef, 8030 mediaType, 8031 onVariableFpsVideoDetected 8032 ]); 8033 return currentTime; 8034};
8035// src/video/get-current-time.ts 8036var getExpectedMediaFrameUncorrected = ({ frame, playbackRate, startFrom })=>{ 8037 return interpolate(frame, [ 8038 -1, 8039 startFrom, 8040 startFrom + 1 8041 ], [ 8042 -1, 8043 startFrom, 8044 startFrom + playbackRate 8045 ]); 8046}; 8047var getMediaTime = ({ fps, frame, playbackRate, startFrom })=>{ 8048 const expectedFrame = getExpectedMediaFrameUncorrected({ 8049 frame, 8050 playbackRate, 8051 startFrom 8052 }); 8053 const msPerFrame = 1000 / fps; 8054 return expectedFrame * msPerFrame / 1000; 8055};
vendor: 1,419 bytes, lines 8056-8093
8056// src/warn-about-non-seekable-media.ts 8057var alreadyWarned = {}; 8058var warnAboutNonSeekableMedia = (ref, type)=>{ 8059 if (ref === null) { 8060 return; 8061 } 8062 if (ref.seekable.length === 0) { 8063 return; 8064 } 8065 if (ref.seekable.length > 1) { 8066 return; 8067 } 8068 if (alreadyWarned[ref.src]) { 8069 return; 8070 } 8071 const range = { 8072 start: ref.seekable.start(0), 8073 end: ref.seekable.end(0) 8074 }; 8075 if (range.start === 0 && range.end === 0) { 8076 const msg = [ 8077 `The media ${ref.src} cannot be seeked. This could be one of few reasons:`, 8078 "1) The media resource was replaced while the video is playing but it was not loaded yet.", 8079 "2) The media does not support seeking.", 8080 "3) The media was loaded with security headers prventing it from being included.", 8081 "Please see https://remotion.dev/docs/non-seekable-media for assistance." 8082 ].join(` 8083`); 8084 if (type === "console-error") { 8085 console.error(msg); 8086 } else if (type === "console-warning") { 8087 console.warn(`The media ${ref.src} does not support seeking. The video will render fine, but may not play correctly in the Remotion Studio and in the <Player>. See https://remotion.dev/docs/non-seekable-media for an explanation.`); 8088 } else { 8089 throw new Error(msg); 8090 } 8091 alreadyWarned[ref.src] = true; 8092 } 8093};
8094// src/use-media-playback.ts 8095var useMediaPlayback = ({ mediaRef, src, mediaType, playbackRate: localPlaybackRate, preservePitch = true, onlyWarnForMediaSeekingError, acceptableTimeshift, pauseWhenBuffering, isPremounting, isPostmounting, onAutoPlayError })=>{ 8096 const { playbackRate: globalPlaybackRate } = usePlaybackRate(); 8097 const frame = useCurrentFrame(); 8098 const absoluteFrame = useTimelinePosition(); 8099 const [playing] = usePlayingState(); 8100 const buffering = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(BufferingContextReact); 8101 const { fps } = useVideoConfig(); 8102 const mediaStartsAt = useMediaStartsAt(); 8103 const lastSeekDueToShift = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 8104 const lastSeek = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 8105 const logLevel = useLogLevel(); 8106 const mountTime = useMountTime(); 8107 if (!buffering) { 8108 throw new Error("useMediaPlayback must be used inside a <BufferingContext>"); 8109 } 8110 const isVariableFpsVideoMap = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)({}); 8111 const onVariableFpsVideoDetected = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(()=>{ 8112 if (!src) { 8113 return; 8114 } 8115 if (isVariableFpsVideoMap.current[src]) { 8116 return; 8117 } 8118 Log.verbose({ 8119 logLevel, 8120 tag: null 8121 }, `Detected ${src} as a variable FPS video. Disabling buffering while seeking.`); 8122 isVariableFpsVideoMap.current[src] = true; 8123 }, [ 8124 logLevel, 8125 src 8126 ]); 8127 const rvcCurrentTime = useRequestVideoCallbackTime({ 8128 mediaRef, 8129 mediaType, 8130 lastSeek, 8131 onVariableFpsVideoDetected 8132 }); 8133 const mediaTagCurrentTime = useCurrentTimeOfMediaTagWithUpdateTimeStamp(mediaRef); 8134 const desiredUnclampedTime = getMediaTime({ 8135 frame, 8136 playbackRate: localPlaybackRate, 8137 startFrom: -mediaStartsAt, 8138 fps 8139 }); 8140 const isMediaTagBuffering = useMediaBuffering({ 8141 element: mediaRef, 8142 shouldBuffer: pauseWhenBuffering, 8143 isPremounting, 8144 isPostmounting, 8145 logLevel, 8146 mountTime, 8147 src: src ?? null 8148 }); 8149 const { bufferUntilFirstFrame, isBuffering } = useBufferUntilFirstFrame({ 8150 mediaRef, 8151 mediaType, 8152 onVariableFpsVideoDetected, 8153 pauseWhenBuffering, 8154 logLevel, 8155 mountTime 8156 }); 8157 const playbackRate = localPlaybackRate * globalPlaybackRate; 8158 const acceptableTimeShiftButLessThanDuration = (()=>{ 8159 const DEFAULT_ACCEPTABLE_TIMESHIFT_WITH_NORMAL_PLAYBACK = 0.45; 8160 const DEFAULT_ACCEPTABLE_TIMESHIFT_WITH_AMPLIFICATION = DEFAULT_ACCEPTABLE_TIMESHIFT_WITH_NORMAL_PLAYBACK + 0.2; 8161 const defaultAcceptableTimeshift = DEFAULT_ACCEPTABLE_TIMESHIFT_WITH_AMPLIFICATION; 8162 if (mediaRef.current?.duration) { 8163 return Math.min(mediaRef.current.duration, acceptableTimeshift ?? defaultAcceptableTimeshift); 8164 } 8165 return acceptableTimeshift ?? defaultAcceptableTimeshift; 8166 })(); 8167 const isPlayerBuffering = useIsPlayerBuffering(buffering); 8168 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 8169 if (mediaRef.current?.paused) { 8170 return; 8171 } 8172 if (!playing) { 8173 playbackLogging({ 8174 logLevel, 8175 tag: "pause", 8176 message: `Pausing ${mediaRef.current?.src} because ${isPremounting ? "media is premounting" : isPostmounting ? "media is postmounting" : "Player is not playing"}`, 8177 mountTime 8178 }); 8179 mediaRef.current?.pause(); 8180 return; 8181 } 8182 const isMediaTagBufferingOrStalled = isMediaTagBuffering || isBuffering(); 8183 const playerBufferingNotStateButLive = buffering.buffering.current; 8184 if (playerBufferingNotStateButLive && !isMediaTagBufferingOrStalled) { 8185 playbackLogging({ 8186 logLevel, 8187 tag: "pause", 8188 message: `Pausing ${mediaRef.current?.src} because player is buffering but media tag is not`, 8189 mountTime 8190 }); 8191 mediaRef.current?.pause(); 8192 } 8193 }, [ 8194 isBuffering, 8195 isMediaTagBuffering, 8196 buffering,
8197 isPlayerBuffering, 8198 isPremounting, 8199 logLevel, 8200 mediaRef, 8201 mediaType, 8202 mountTime, 8203 playing, 8204 isPostmounting 8205 ]); 8206 const env = useRemotionEnvironment(); 8207 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 8208 const playbackRateToSet = Math.max(0, playbackRate); 8209 if (mediaRef.current && mediaRef.current.playbackRate !== playbackRateToSet) { 8210 mediaRef.current.playbackRate = playbackRateToSet; 8211 } 8212 if (mediaRef.current && mediaRef.current.preservesPitch !== preservePitch) { 8213 mediaRef.current.preservesPitch = preservePitch; 8214 } 8215 }, [ 8216 mediaRef, 8217 playbackRate, 8218 preservePitch 8219 ]); 8220 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 8221 const tagName = mediaType === "audio" ? "<Html5Audio>" : "<Html5Video>"; 8222 if (!mediaRef.current) { 8223 throw new Error(`No ${mediaType} ref found`); 8224 } 8225 if (!src) { 8226 throw new Error(`No 'src' attribute was passed to the ${tagName} element.`); 8227 } 8228 const { current } = mediaRef; 8229 const action = getMediaSyncAction({ 8230 duration: current.duration, 8231 currentTime: current.currentTime, 8232 paused: current.paused, 8233 ended: current.ended, 8234 desiredUnclampedTime, 8235 mediaTagTime: mediaTagCurrentTime.current.time, 8236 mediaTagLastUpdate: mediaTagCurrentTime.current.lastUpdate, 8237 rvcTime: rvcCurrentTime.current?.time ?? null, 8238 rvcLastUpdate: rvcCurrentTime.current?.lastUpdate ?? null, 8239 isVariableFpsVideo: Boolean(isVariableFpsVideoMap.current[src]), 8240 acceptableTimeShift: acceptableTimeShiftButLessThanDuration, 8241 lastSeekDueToShift: lastSeekDueToShift.current, 8242 playing, 8243 playbackRate, 8244 mediaTagBufferingOrStalled: isMediaTagBuffering || isBuffering(), 8245 playerBuffering: buffering.buffering.current, 8246 absoluteFrame, 8247 onlyWarnForMediaSeekingError, 8248 isPremounting, 8249 isPostmounting, 8250 pauseWhenBuffering 8251 }); 8252 if (action.type === "none") { 8253 return; 8254 } 8255 if (action.type === "seek-due-to-shift") { 8256 lastSeek.current = seek({ 8257 mediaRef: current, 8258 time: action.shouldBeTime, 8259 logLevel, 8260 why: action.why, 8261 mountTime 8262 }); 8263 lastSeekDueToShift.current = lastSeek.current; 8264 if (action.bufferUntilFirstFrame) { 8265 bufferUntilFirstFrame(action.shouldBeTime); 8266 } 8267 if (action.playReason !== null) { 8268 playAndHandleNotAllowedError({ 8269 mediaRef, 8270 mediaType, 8271 onAutoPlayError, 8272 logLevel, 8273 mountTime, 8274 reason: action.playReason, 8275 isPlayer: env.isPlayer 8276 }); 8277 } 8278 if (action.warnAboutNonSeekable) { 8279 warnAboutNonSeekableMedia(current, "console-error"); 8280 } 8281 return; 8282 } 8283 if (action.type === "seek-if-not-playing") { 8284 if (action.why !== null) { 8285 lastSeek.current = seek({ 8286 mediaRef: current, 8287 time: action.shouldBeTime, 8288 logLevel, 8289 why: action.why, 8290 mountTime 8291 }); 8292 } 8293 return; 8294 } 8295 if (action.why !== null) { 8296 lastSeek.current = seek({ 8297 mediaRef: current, 8298 time: action.shouldBeTime, 8299 logLevel, 8300 why: action.why, 8301 mountTime 8302 }); 8303 } 8304 playAndHandleNotAllowedError({ 8305 mediaRef, 8306 mediaType, 8307 onAutoPlayError, 8308 logLevel, 8309 mountTime, 8310 reason: action.playReason, 8311 isPlayer: env.isPlayer 8312 }); 8313 if (action.bufferUntilFirstFrame) { 8314 bufferUntilFirstFrame(action.shouldBeTime); 8315 } 8316 }, [ 8317 absoluteFrame, 8318 acceptableTimeShiftButLessThanDuration, 8319 bufferUntilFirstFrame, 8320 buffering.buffering, 8321 rvcCurrentTime, 8322 logLevel, 8323 desiredUnclampedTime, 8324 isBuffering, 8325 isMediaTagBuffering, 8326 mediaRef, 8327 mediaType, 8328 onlyWarnForMediaSeekingError, 8329 playbackRate, 8330 playing, 8331 src, 8332 onAutoPlayError, 8333 isPremounting, 8334 isPostmounting, 8335 pauseWhenBuffering, 8336 mountTime, 8337 mediaTagCurrentTime, 8338 env.isPlayer 8339 ]); 8340};
8341// src/use-media-tag.ts 8342 8343var useMediaTag = ({ mediaRef, id, mediaType, onAutoPlayError, isPremounting, isPostmounting })=>{ 8344 const { audioAndVideoTags, imperativePlaying } = useTimelineContext(); 8345 const logLevel = useLogLevel(); 8346 const mountTime = useMountTime(); 8347 const env = useRemotionEnvironment(); 8348 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 8349 const tag = { 8350 id, 8351 play: (reason)=>{ 8352 if (!imperativePlaying.current) { 8353 return; 8354 } 8355 if (isPremounting || isPostmounting) { 8356 return; 8357 } 8358 return playAndHandleNotAllowedError({ 8359 mediaRef, 8360 mediaType, 8361 onAutoPlayError, 8362 logLevel, 8363 mountTime, 8364 reason, 8365 isPlayer: env.isPlayer 8366 }); 8367 } 8368 }; 8369 audioAndVideoTags.current.push(tag); 8370 return ()=>{ 8371 audioAndVideoTags.current = audioAndVideoTags.current.filter((a2)=>a2.id !== id); 8372 }; 8373 }, [ 8374 audioAndVideoTags, 8375 id, 8376 mediaRef, 8377 mediaType, 8378 onAutoPlayError, 8379 imperativePlaying, 8380 isPremounting, 8381 isPostmounting, 8382 logLevel, 8383 mountTime, 8384 env.isPlayer 8385 ]); 8386};
8387// src/volume-position-state.ts 8388 8389var MediaVolumeContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({ 8390 playerMuted: false, 8391 mediaVolume: 1 8392}); 8393var SetMediaVolumeContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({ 8394 setPlayerMuted: ()=>{ 8395 throw new Error("default"); 8396 }, 8397 setMediaVolume: ()=>{ 8398 throw new Error("default"); 8399 } 8400}); 8401var useMediaVolumeState = ()=>{ 8402 const { mediaVolume } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(MediaVolumeContext); 8403 const { setMediaVolume } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SetMediaVolumeContext); 8404 return (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 8405 return [ 8406 mediaVolume, 8407 setMediaVolume 8408 ]; 8409 }, [ 8410 mediaVolume, 8411 setMediaVolume 8412 ]); 8413}; 8414var usePlayerMutedState = ()=>{ 8415 const { playerMuted } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(MediaVolumeContext); 8416 const { setPlayerMuted } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SetMediaVolumeContext); 8417 return (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 8418 return [ 8419 playerMuted, 8420 setPlayerMuted 8421 ]; 8422 }, [ 8423 playerMuted, 8424 setPlayerMuted 8425 ]); 8426};
8427// src/volume-safeguard.ts 8428var warnAboutTooHighVolume = (volume)=>{ 8429 if (volume >= 100) { 8430 throw new Error(`Volume was set to ${volume}, but regular volume is 1, not 100. Did you forget to divide by 100? Set a volume of less than 100 to dismiss this error.`); 8431 } 8432};
8433// src/audio/AudioForPreview.tsx 8434 8435var AudioForDevelopmentForwardRefFunction = (props, ref)=>{ 8436 const [initialShouldPreMountAudioElements] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(props.shouldPreMountAudioTags); 8437 if (props.shouldPreMountAudioTags !== initialShouldPreMountAudioElements) { 8438 throw new Error("Cannot change the behavior for pre-mounting audio tags dynamically."); 8439 } 8440 const logLevel = useLogLevel(); 8441 const { volume, muted, playbackRate, preservePitch, shouldPreMountAudioTags, src, onDuration, acceptableTimeShiftInSeconds, _remotionInternalNeedsDurationCalculation, _remotionInternalNativeLoopPassed, _remotionInternalStack, allowAmplificationDuringRender, name, pauseWhenBuffering, showInTimeline, loopVolumeCurveBehavior, stack, crossOrigin, delayRenderRetries, delayRenderTimeoutInMilliseconds, toneFrequency, useWebAudioApi, onError, onNativeError, audioStreamIndex, ...nativeProps } = props; 8442 const _propsValid = true; 8443 if (!_propsValid) { 8444 throw new Error("typecheck error"); 8445 } 8446 const [mediaVolume] = useMediaVolumeState(); 8447 const [playerMuted] = usePlayerMutedState(); 8448 const volumePropFrame = useFrameForVolumeProp(loopVolumeCurveBehavior ?? "repeat"); 8449 if (!src) { 8450 throw new TypeError("No 'src' was passed to <Html5Audio>."); 8451 } 8452 const preloadedSrc = usePreload(src); 8453 const sequenceContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SequenceContext); 8454 const [timelineId] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(()=>String(Math.random())); 8455 const userPreferredVolume = evaluateVolume({ 8456 frame: volumePropFrame, 8457 volume, 8458 mediaVolume 8459 }); 8460 warnAboutTooHighVolume(userPreferredVolume); 8461 const crossOriginValue = getCrossOriginValue({ 8462 crossOrigin, 8463 requestsVideoFrame: false, 8464 isClientSideRendering: false 8465 }); 8466 const propsToPass = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 8467 return { 8468 muted: muted || playerMuted || userPreferredVolume <= 0, 8469 src: preloadedSrc, 8470 loop: _remotionInternalNativeLoopPassed, 8471 crossOrigin: crossOriginValue, 8472 ...nativeProps 8473 }; 8474 }, [ 8475 _remotionInternalNativeLoopPassed, 8476 playerMuted, 8477 muted, 8478 nativeProps, 8479 preloadedSrc, 8480 userPreferredVolume, 8481 crossOriginValue 8482 ]); 8483 const id = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>`audio-${random(src ?? "")}-${sequenceContext?.relativeFrom}-${sequenceContext?.cumulatedFrom}-${sequenceContext?.durationInFrames}-muted:${props.muted}-loop:${props.loop}`, [ 8484 src, 8485 sequenceContext?.relativeFrom, 8486 sequenceContext?.cumulatedFrom, 8487 sequenceContext?.durationInFrames, 8488 props.muted, 8489 props.loop 8490 ]); 8491 const { el: audioRef, mediaElementSourceNode, cleanupOnMediaTagUnmount } = useSharedAudio({ 8492 aud: propsToPass, 8493 audioId: id, 8494 premounting: Boolean(sequenceContext?.premounting), 8495 postmounting: Boolean(sequenceContext?.postmounting) 8496 }); 8497 const getStack = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(()=>{ 8498 return _remotionInternalStack ?? null; 8499 }, [ 8500 _remotionInternalStack 8501 ]); 8502 useMediaInTimeline({ 8503 volume, 8504 mediaVolume, 8505 src, 8506 mediaType: "audio", 8507 playbackRate: playbackRate ?? 1, 8508 displayName: name ?? null, 8509 id: timelineId, 8510 getStack, 8511 showInTimeline, 8512 premountDisplay: sequenceContext?.premountDisplay ?? null, 8513 postmountDisplay: sequenceContext?.postmountDisplay ?? null, 8514 loopDisplay: undefined, 8515 documentationLink: "https://www.remotion.dev/docs/html5-audio", 8516 refForOutline: null 8517 }); 8518 useMediaPlayback({ 8519 mediaRef: audioRef, 8520 src, 8521 mediaType: "audio", 8522 playbackRate: playbackRate ?? 1, 8523 preservePitch, 8524 onlyWarnForMediaSeekingError: false, 8525 acceptableTimeshift: acceptableTimeShiftInSeconds ?? null, 8526 isPremounting: Boolean(sequenceContext?.premounting),
8527 isPostmounting: Boolean(sequenceContext?.postmounting), 8528 pauseWhenBuffering, 8529 onAutoPlayError: null 8530 }); 8531 useMediaTag({ 8532 id: timelineId, 8533 isPostmounting: Boolean(sequenceContext?.postmounting), 8534 isPremounting: Boolean(sequenceContext?.premounting), 8535 mediaRef: audioRef, 8536 mediaType: "audio", 8537 onAutoPlayError: null 8538 }); 8539 useVolume({ 8540 logLevel, 8541 mediaRef: audioRef, 8542 source: mediaElementSourceNode, 8543 volume: userPreferredVolume, 8544 shouldUseWebAudioApi: useWebAudioApi ?? false 8545 }); 8546 const effectToUse = react__WEBPACK_IMPORTED_MODULE_0__.useInsertionEffect ?? react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect; 8547 effectToUse(()=>{ 8548 return ()=>{ 8549 requestAnimationFrame(()=>{ 8550 cleanupOnMediaTagUnmount(); 8551 }); 8552 }; 8553 }, [ 8554 cleanupOnMediaTagUnmount 8555 ]); 8556 (0,react__WEBPACK_IMPORTED_MODULE_0__.useImperativeHandle)(ref, ()=>{ 8557 return audioRef.current; 8558 }, [ 8559 audioRef 8560 ]); 8561 const currentOnDurationCallback = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(onDuration); 8562 currentOnDurationCallback.current = onDuration; 8563 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 8564 const { current } = audioRef; 8565 if (!current) { 8566 return; 8567 } 8568 if (current.duration) { 8569 currentOnDurationCallback.current?.(current.src, current.duration); 8570 return; 8571 } 8572 const onLoadedMetadata = ()=>{ 8573 currentOnDurationCallback.current?.(current.src, current.duration); 8574 }; 8575 current.addEventListener("loadedmetadata", onLoadedMetadata); 8576 return ()=>{ 8577 current.removeEventListener("loadedmetadata", onLoadedMetadata); 8578 }; 8579 }, [ 8580 audioRef, 8581 src 8582 ]); 8583 if (initialShouldPreMountAudioElements) { 8584 return null; 8585 } 8586 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)("audio", { 8587 ref: audioRef, 8588 preload: "metadata", 8589 crossOrigin: crossOriginValue, 8590 ...propsToPass 8591 }); 8592}; 8593var AudioForPreview = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(AudioForDevelopmentForwardRefFunction);
8594// src/audio/AudioForRendering.tsx 8595 8596 8597var AudioForRenderingRefForwardingFunction = (props, ref)=>{ 8598 const audioRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 8599 const { volume: volumeProp, playbackRate, allowAmplificationDuringRender, onDuration, toneFrequency, _remotionInternalNeedsDurationCalculation, _remotionInternalNativeLoopPassed, acceptableTimeShiftInSeconds, name, onNativeError, delayRenderRetries, delayRenderTimeoutInMilliseconds, loopVolumeCurveBehavior, pauseWhenBuffering, audioStreamIndex, preservePitch: _preservePitch, ...nativeProps } = props; 8600 const absoluteFrame = useTimelinePosition(); 8601 const volumePropFrame = useFrameForVolumeProp(loopVolumeCurveBehavior ?? "repeat"); 8602 const frame = useCurrentFrame(); 8603 const sequenceContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SequenceContext); 8604 const { registerRenderAsset, unregisterRenderAsset } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(RenderAssetManager); 8605 const { delayRender: delayRender2, continueRender: continueRender2 } = useDelayRender(); 8606 const id = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>`audio-${random(props.src ?? "")}-${sequenceContext?.relativeFrom}-${sequenceContext?.cumulatedFrom}-${sequenceContext?.durationInFrames}`, [ 8607 props.src, 8608 sequenceContext?.relativeFrom, 8609 sequenceContext?.cumulatedFrom, 8610 sequenceContext?.durationInFrames 8611 ]); 8612 const volume = evaluateVolume({ 8613 volume: volumeProp, 8614 frame: volumePropFrame, 8615 mediaVolume: 1 8616 }); 8617 warnAboutTooHighVolume(volume); 8618 (0,react__WEBPACK_IMPORTED_MODULE_0__.useImperativeHandle)(ref, ()=>{ 8619 return audioRef.current; 8620 }, []); 8621 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 8622 if (!props.src) { 8623 throw new Error("No src passed"); 8624 } 8625 if (!window.remotion_audioEnabled) { 8626 return; 8627 } 8628 if (props.muted) { 8629 return; 8630 } 8631 if (volume <= 0) { 8632 return; 8633 } 8634 registerRenderAsset({ 8635 type: "audio", 8636 src: getAbsoluteSrc(props.src), 8637 id, 8638 frame: absoluteFrame, 8639 volume, 8640 mediaFrame: frame, 8641 playbackRate: props.playbackRate ?? 1, 8642 toneFrequency: toneFrequency ?? 1, 8643 audioStartFrame: Math.max(0, -(sequenceContext?.cumulatedNegativeFrom ?? 0)), 8644 audioStreamIndex: audioStreamIndex ?? 0 8645 }); 8646 return ()=>unregisterRenderAsset(id); 8647 }, [ 8648 props.muted, 8649 props.src, 8650 registerRenderAsset, 8651 absoluteFrame, 8652 id, 8653 unregisterRenderAsset, 8654 volume, 8655 volumePropFrame, 8656 frame, 8657 playbackRate, 8658 props.playbackRate, 8659 toneFrequency, 8660 sequenceContext?.cumulatedNegativeFrom, 8661 audioStreamIndex 8662 ]); 8663 const { src } = props; 8664 const needsToRenderAudioTag = ref || _remotionInternalNeedsDurationCalculation; 8665 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 8666 if (window.process?.env?.NODE_ENV === "test") { 8667 return; 8668 } 8669 if (!needsToRenderAudioTag) { 8670 return; 8671 } 8672 const newHandle = delayRender2("Loading <Html5Audio> duration with src=" + src, { 8673 retries: delayRenderRetries ?? undefined, 8674 timeoutInMilliseconds: delayRenderTimeoutInMilliseconds ?? undefined 8675 }); 8676 const { current } = audioRef; 8677 const didLoad = ()=>{ 8678 if (current?.duration) { 8679 onDuration(current.src, current.duration); 8680 } 8681 continueRender2(newHandle); 8682 }; 8683 if (current?.duration) { 8684 onDuration(current.src, current.duration); 8685 continueRender2(newHandle); 8686 } else { 8687 current?.addEventListener("loadedmetadata", didLoad, { 8688 once: true 8689 }); 8690 } 8691 return ()=>{ 8692 current?.removeEventListener("loadedmetadata", didLoad); 8693 continueRender2(newHandle); 8694 }; 8695 }, [ 8696 src, 8697 onDuration, 8698 needsToRenderAudioTag, 8699 delayRenderRetries, 8700 delayRenderTimeoutInMilliseconds, 8701 continueRender2, 8702 delayRender2 8703 ]); 8704 if (!needsToRenderAudioTag) { 8705 return null; 8706 } 8707 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)("audio", { 8708 ref: audioRef, 8709 ...nativeProps, 8710 onError: onNativeError 8711 }); 8712}; 8713var AudioForRendering = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(AudioForRenderingRefForwardingFunction);
8714// src/audio/html5-audio.tsx 8715 8716var AudioRefForwardingFunction = (props, ref)=>{ 8717 const audioTagsContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SharedAudioTagsContext); 8718 const propsWithFreeze = props; 8719 const { startFrom, endAt, trimBefore, trimAfter, name, stack, pauseWhenBuffering, showInTimeline, onError: onRemotionError, freeze, ...otherProps } = propsWithFreeze; 8720 const { loop, freeze: _freeze, ...propsOtherThanLoop } = propsWithFreeze; 8721 const { fps } = useVideoConfig(); 8722 const environment = useRemotionEnvironment(); 8723 if (environment.isClientSideRendering) { 8724 throw new Error("<Html5Audio> is not supported in @remotion/web-renderer. Use <Audio> from @remotion/media instead. See https://remotion.dev/docs/client-side-rendering/limitations"); 8725 } 8726 if (typeof freeze !== "undefined") { 8727 throw new TypeError('The "freeze" prop is not supported on <Html5Audio />. Use <Sequence freeze={...}> to freeze media playback.'); 8728 } 8729 const { durations, setDurations } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(DurationsContext); 8730 if (typeof props.src !== "string") { 8731 throw new TypeError(`The \`<Html5Audio>\` tag requires a string for \`src\`, but got ${JSON.stringify(props.src)} instead.`); 8732 } 8733 const preloadedSrc = usePreload(props.src); 8734 const onError = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((e)=>{ 8735 console.log(e.currentTarget.error); 8736 const errMessage = `Could not play audio with src ${preloadedSrc}: ${e.currentTarget.error}. See https://remotion.dev/docs/media-playback-error for help.`; 8737 if (loop) { 8738 if (onRemotionError) { 8739 onRemotionError(new Error(errMessage)); 8740 return; 8741 } 8742 cancelRender(new Error(errMessage)); 8743 } else { 8744 onRemotionError?.(new Error(errMessage)); 8745 console.warn(errMessage); 8746 } 8747 }, [ 8748 loop, 8749 onRemotionError, 8750 preloadedSrc 8751 ]); 8752 const onDuration = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((src, durationInSeconds)=>{ 8753 setDurations({ 8754 type: "got-duration", 8755 durationInSeconds, 8756 src 8757 }); 8758 }, [ 8759 setDurations 8760 ]); 8761 const durationFetched = durations[getAbsoluteSrc(preloadedSrc)] ?? durations[getAbsoluteSrc(props.src)]; 8762 validateMediaTrimProps({ 8763 startFrom, 8764 endAt, 8765 trimBefore, 8766 trimAfter 8767 }); 8768 const { trimBeforeValue, trimAfterValue } = resolveTrimProps({ 8769 startFrom, 8770 endAt, 8771 trimBefore, 8772 trimAfter 8773 }); 8774 if (loop && durationFetched !== undefined) { 8775 if (!Number.isFinite(durationFetched)) { 8776 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Html5Audio, { 8777 ...propsOtherThanLoop, 8778 ref, 8779 _remotionInternalNativeLoopPassed: true 8780 }); 8781 } 8782 const duration = durationFetched * fps; 8783 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Loop, { 8784 layout: "none", 8785 durationInFrames: calculateMediaDuration({ 8786 trimAfter: trimAfterValue, 8787 mediaDurationInFrames: duration, 8788 playbackRate: props.playbackRate ?? 1, 8789 trimBefore: trimBeforeValue 8790 }), 8791 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Html5Audio, { 8792 ...propsOtherThanLoop, 8793 ref, 8794 _remotionInternalNativeLoopPassed: true 8795 }) 8796 }); 8797 } 8798 if (typeof trimBeforeValue !== "undefined" || typeof trimAfterValue !== "undefined") { 8799 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Sequence, { 8800 layout: "none", 8801 from: 0 - (trimBeforeValue ?? 0), 8802 showInTimeline: false, 8803 durationInFrames: trimAfterValue, 8804 name, 8805 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Html5Audio, { 8806 _remotionInternalNeedsDurationCalculation: Boolean(loop), 8807 pauseWhenBuffering: pauseWhenBuffering ?? false, 8808 ...otherProps, 8809 ref 8810 }) 8811 }); 8812 } 8813 validateMediaProps({ 8814 playbackRate: props.playbackRate, 8815 preservePitch: props.preservePitch, 8816 volume: props.volume 8817 }, "Html5Audio"); 8818 if (environment.isRendering) { 8819 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(AudioForRendering, { 8820 onDuration, 8821 ...props, 8822 ref, 8823 onNativeError: onError, 8824 _remotionInternalNeedsDurationCalculation: Boolean(loop) 8825 }); 8826 } 8827 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(AudioForPreview, { 8828 _remotionInternalNativeLoopPassed: props._remotionInternalNativeLoopPassed ?? false, 8829 _remotionInternalStack: stack ?? null, 8830 shouldPreMountAudioTags: audioTagsContext !== null && audioTagsContext.numberOfAudioTags > 0, 8831 ...props, 8832 ref, 8833 onNativeError: onError, 8834 onDuration, 8835 pauseWhenBuffering: pauseWhenBuffering ?? false, 8836 _remotionInternalNeedsDurationCalculation: Boolean(loop), 8837 showInTimeline: showInTimeline ?? true 8838 }); 8839}; 8840var Html5Audio = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(AudioRefForwardingFunction);
8841addSequenceStackTraces(Html5Audio); 8842var Audio = (/* unused pure expression or super */ null && (Html5Audio));
8843// src/effects/Solid.tsx 8844 8845 8846var resolveSolidPixelDensity = (pixelDensity)=>{ 8847 if (pixelDensity === undefined) { 8848 return 1; 8849 } 8850 if (typeof pixelDensity !== "number" || !Number.isFinite(pixelDensity) || pixelDensity <= 0) { 8851 throw new Error(`<Solid>: \`pixelDensity\` must be a positive finite number. Received: ${String(pixelDensity)}.`); 8852 } 8853 return pixelDensity; 8854}; 8855var solidSchema = { 8856 ...baseSchema, 8857 color: { 8858 type: "color", 8859 default: "transparent", 8860 description: "Color" 8861 }, 8862 width: { 8863 type: "number", 8864 min: 1, 8865 step: 1, 8866 default: 1920, 8867 description: "Width", 8868 hiddenFromList: false 8869 }, 8870 height: { 8871 type: "number", 8872 min: 1, 8873 step: 1, 8874 default: 1080, 8875 description: "Height", 8876 hiddenFromList: false 8877 }, 8878 pixelDensity: { 8879 type: "number", 8880 min: 1, 8881 max: 3, 8882 step: 0.1, 8883 default: 1, 8884 description: "Pixel density", 8885 hiddenFromList: false 8886 }, 8887 ...transformSchema 8888}; 8889var SolidInner = ({ color, width, height, effects = [], className, style, pixelDensity, overrideId, reference })=>{ 8890 const { delayRender: delayRender2, continueRender: continueRender2, cancelRender: cancelRender2 } = useDelayRender(); 8891 const resolvedPixelDensity = resolveSolidPixelDensity(pixelDensity); 8892 const canvasWidth = Math.ceil(width * resolvedPixelDensity); 8893 const canvasHeight = Math.ceil(height * resolvedPixelDensity); 8894 const [outputCanvas, setOutputCanvas] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(null); 8895 const memoizedEffects = useMemoizedEffects({ 8896 effects, 8897 overrideId: overrideId ?? null 8898 }); 8899 const sourceCanvas = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 8900 if (typeof document === "undefined") { 8901 return null; 8902 } 8903 const canvas = document.createElement("canvas"); 8904 canvas.width = 1; 8905 canvas.height = 1; 8906 return canvas; 8907 }, []); 8908 const chainState = useEffectChainState(); 8909 const canvasRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((canvas)=>{ 8910 setOutputCanvas(canvas); 8911 if (typeof reference === "function") { 8912 reference(canvas); 8913 } else if (reference) { 8914 reference.current = canvas; 8915 } 8916 }, [ 8917 reference 8918 ]); 8919 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 8920 if (!outputCanvas || !sourceCanvas) { 8921 return; 8922 } 8923 const handle = delayRender2("Solid effect chain"); 8924 if (!chainState) { 8925 continueRender2(handle); 8926 return ()=>{ 8927 continueRender2(handle); 8928 }; 8929 } 8930 const ctx = sourceCanvas.getContext("2d", { 8931 colorSpace: "srgb" 8932 }); 8933 if (!ctx) { 8934 cancelRender2(new Error("Failed to acquire 2D context for <Solid> source")); 8935 return; 8936 } 8937 ctx.clearRect(0, 0, 1, 1); 8938 if (color !== undefined) { 8939 ctx.fillStyle = color; 8940 ctx.fillRect(0, 0, 1, 1); 8941 } 8942 runEffectChain({ 8943 state: chainState.get(canvasWidth, canvasHeight), 8944 source: sourceCanvas, 8945 effects: memoizedEffects, 8946 output: outputCanvas, 8947 width: canvasWidth, 8948 height: canvasHeight 8949 }).then((completed)=>{ 8950 if (completed) { 8951 continueRender2(handle); 8952 } 8953 }).catch((err)=>{ 8954 cancelRender2(err); 8955 }); 8956 return ()=>{ 8957 continueRender2(handle); 8958 }; 8959 }, [ 8960 color, 8961 outputCanvas, 8962 sourceCanvas, 8963 chainState, 8964 canvasWidth, 8965 canvasHeight, 8966 delayRender2, 8967 continueRender2, 8968 cancelRender2, 8969 memoizedEffects 8970 ]); 8971 const canvasStyle = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 8972 return { 8973 width, 8974 height, 8975 ...style ?? {} 8976 }; 8977 }, [ 8978 height, 8979 style, 8980 width 8981 ]); 8982 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)("canvas", { 8983 ref: canvasRef, 8984 width: canvasWidth, 8985 height: canvasHeight, 8986 className, 8987 style: canvasStyle 8988 }); 8989}; 8990var SolidOuter = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(({ effects = [], controls, color, height, width, className, durationInFrames, style, name, from, trimBefore, freeze, hidden, showInTimeline, pixelDensity, ...props2 }, ref)=>{ 8991 const memoizedEffectDefinitions = useMemoizedEffectDefinitions(effects); 8992 const actualRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 8993 (0,react__WEBPACK_IMPORTED_MODULE_0__.useImperativeHandle)(ref, ()=>{ 8994 return actualRef.current; 8995 }, []); 8996 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Sequence, { 8997 layout: "none", 8998 from, 8999 trimBefore, 9000 freeze, 9001 hidden, 9002 showInTimeline, 9003 controls, 9004 _remotionInternalEffects: memoizedEffectDefinitions, 9005 durationInFrames, 9006 name: name ?? "<Solid>", 9007 outlineRef: actualRef, 9008 _remotionInternalDocumentationLink: "https://www.remotion.dev/docs/solid", 9009 ...props2, 9010 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(SolidInner, { 9011 reference: actualRef, 9012 overrideId: controls?.overrideId ?? null, 9013 color, 9014 height, 9015 width, 9016 className, 9017 style, 9018 effects, 9019 pixelDensity 9020 }) 9021 }); 9022}); 9023var Solid = withInteractivitySchema({ 9024 Component: SolidOuter, 9025 componentName: "<Solid>", 9026 componentIdentity: "dev.remotion.remotion.Solid", 9027 schema: solidSchema, 9028 supportsEffects: true 9029}); 9030Solid.displayName = "Solid"; 9031addSequenceStackTraces(Solid);
9032// src/HtmlInCanvas.tsx 9033 9034 9035var cachedSupport = null; 9036var isHtmlInCanvasSupported = ()=>{ 9037 if (cachedSupport !== null) { 9038 return cachedSupport; 9039 } 9040 if (typeof document === "undefined") { 9041 return false; 9042 } 9043 const canvas = document.createElement("canvas"); 9044 const ctx = canvas.getContext("2d"); 9045 cachedSupport = typeof ctx?.drawElementImage === "function" && typeof canvas.requestPaint === "function" && typeof canvas.captureElementImage === "function" && "transferControlToOffscreen" in HTMLCanvasElement.prototype; 9046 return cachedSupport; 9047}; 9048var HTML_IN_CANVAS_UNSUPPORTED_MESSAGE = "HTML in Canvas is not supported. Two common causes: Chrome is older than version 148 (update Chrome), or the HTML-in-Canvas flag is disabled at chrome://flags/#canvas-draw-element (enable it and restart Chrome)."; 9049function assertHtmlInCanvasDimensions(width, height) { 9050 if (typeof width !== "number" || typeof height !== "number") { 9051 throw new Error(`HtmlInCanvas: \`width\` and \`height\` must be numbers. Received width=${String(width)}, height=${String(height)}.`); 9052 } 9053 if (!Number.isInteger(width) || width <= 0) { 9054 throw new Error(`HtmlInCanvas: \`width\` must be a positive integer. Received: ${String(width)}.`); 9055 } 9056 if (!Number.isInteger(height) || height <= 0) { 9057 throw new Error(`HtmlInCanvas: \`height\` must be a positive integer. Received: ${String(height)}.`); 9058 } 9059} 9060function resolveHtmlInCanvasPixelDensity(pixelDensity) { 9061 if (pixelDensity === undefined) { 9062 return 1; 9063 } 9064 if (typeof pixelDensity !== "number" || !Number.isFinite(pixelDensity) || pixelDensity <= 0) { 9065 throw new Error(`HtmlInCanvas: \`pixelDensity\` must be a positive finite number. Received: ${String(pixelDensity)}.`); 9066 } 9067 return pixelDensity; 9068} 9069var isMissingPaintRecordError = (error2)=>{ 9070 return error2 instanceof DOMException && error2.name === "InvalidStateError"; 9071}; 9072var missingPaintRecordMessage = "HtmlInCanvas: Expected the element to be inside the viewport during rendering, but Chrome had no cached paint record for it."; 9073var resizeOffscreenCanvas = ({ offscreen, width, height })=>{ 9074 if (offscreen.width !== width) { 9075 offscreen.width = width; 9076 } 9077 if (offscreen.height !== height) { 9078 offscreen.height = height; 9079 } 9080}; 9081var defaultOnPaint = ({ canvas, element, elementImage })=>{ 9082 const ctx = canvas.getContext("2d"); 9083 if (!ctx) { 9084 throw new Error("Failed to acquire 2D context for <HtmlInCanvas> canvas"); 9085 } 9086 ctx.reset(); 9087 const transform = ctx.drawElementImage(elementImage, 0, 0); 9088 element.style.transform = transform.toString(); 9089}; 9090var HtmlInCanvasAncestorContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)(false); 9091var HtmlInCanvasContent = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(({ width, height, effects, children, onPaint, onInit, pixelDensity, controls, style }, ref)=>{ 9092 const isInsideAncestorHtmlInCanvas = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(HtmlInCanvasAncestorContext); 9093 assertHtmlInCanvasDimensions(width, height); 9094 const resolvedPixelDensity = resolveHtmlInCanvasPixelDensity(pixelDensity); 9095 const canvasWidth = Math.ceil(width * resolvedPixelDensity); 9096 const canvasHeight = Math.ceil(height * resolvedPixelDensity); 9097 const { continueRender: continueRender2, cancelRender: cancelRender2 } = useDelayRender(); 9098 const { isRendering } = useRemotionEnvironment(); 9099 if (!isHtmlInCanvasSupported()) { 9100 cancelRender2(new Error(HTML_IN_CANVAS_UNSUPPORTED_MESSAGE)); 9101 } 9102 const canvas2dRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 9103 const offscreenRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 9104 const divRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 9105 const canvasSizeKey = `${width}x${height}@${resolvedPixelDensity}`; 9106 const setLayoutCanvasRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((node)=>{ 9107 canvas2dRef.current = node; 9108 if (typeof ref === "function") { 9109 ref(node); 9110 } else if (ref) { 9111 ref.current = node; 9112 } 9113 }, [ 9114 ref 9115 ]); 9116 const chainState = useEffectChainState(); 9117 const memoizedEffects = useMemoizedEffects({ 9118 effects, 9119 overrideId: controls?.overrideId ?? null 9120 }); 9121 const effectsRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(memoizedEffects); 9122 effectsRef.current = memoizedEffects; 9123 const onPaintRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(onPaint); 9124 onPaintRef.current = onPaint; 9125 const onInitRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(onInit); 9126 onInitRef.current = onInit; 9127 const initializedRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(false); 9128 const onInitCleanupRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 9129 const unmountedRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(false); 9130 const onPaintCb = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(async ()=>{ 9131 const element = divRef.current; 9132 if (!element) { 9133 throw new Error("Canvas or scene element not found"); 9134 } 9135 const offscreen = offscreenRef.current; 9136 if (!offscreen) { 9137 throw new Error("HtmlInCanvas: offscreen canvas not ready (transferControlToOffscreen failed or canvas is remounting)"); 9138 } 9139 resizeOffscreenCanvas({ 9140 offscreen, 9141 width: canvasWidth, 9142 height: canvasHeight 9143 }); 9144 try { 9145 const placeholderCanvas = canvas2dRef.current; 9146 if (!placeholderCanvas) { 9147 throw new Error("Canvas not found"); 9148 } 9149 const handle = delayRender("onPaint"); 9150 if (!initializedRef.current) { 9151 let initImage = null; 9152 try { 9153 initImage = placeholderCanvas.captureElementImage(element); 9154 } catch (error2) { 9155 if (isMissingPaintRecordError(error2) && !isRendering) {} else if (isMissingPaintRecordError(error2)) { 9156 throw new Error(missingPaintRecordMessage); 9157 } else { 9158 throw error2; 9159 } 9160 } 9161 if (initImage) { 9162 initializedRef.current = true; 9163 const currentOnInit = onInitRef.current; 9164 if (currentOnInit) { 9165 const cleanup = await currentOnInit({ 9166 canvas: offscreen, 9167 element, 9168 elementImage: initImage, 9169 pixelDensity: resolvedPixelDensity 9170 }); 9171 if (typeof cleanup !== "function") { 9172 throw new Error("HtmlInCanvas: when `onInit` is provided, it must return a cleanup function, or a Promise that resolves to one."); 9173 } 9174 if (unmountedRef.current) { 9175 cleanup(); 9176 } else { 9177 onInitCleanupRef.current = cleanup; 9178 } 9179 } 9180 } 9181 } 9182 const handler = onPaintRef.current ?? defaultOnPaint; 9183 let elImage; 9184 try { 9185 elImage = placeholderCanvas.captureElementImage(element); 9186 } catch (error2) { 9187 if (isMissingPaintRecordError(error2) && !isRendering) { 9188 continueRender2(handle); 9189 return; 9190 } 9191 if (isMissingPaintRecordError(error2)) { 9192 throw new Error(missingPaintRecordMessage); 9193 } 9194 throw error2; 9195 } 9196 await handler({ 9197 canvas: offscreen, 9198 element, 9199 elementImage: elImage, 9200 pixelDensity: resolvedPixelDensity 9201 }); 9202 await runEffectChain({ 9203 state: chainState.get(canvasWidth, canvasHeight),
9204 source: offscreen, 9205 effects: effectsRef.current, 9206 output: offscreen, 9207 width: canvasWidth, 9208 height: canvasHeight 9209 }); 9210 continueRender2(handle); 9211 } catch (error2) { 9212 cancelRender2(error2); 9213 } 9214 }, [ 9215 canvasHeight, 9216 canvasWidth, 9217 chainState, 9218 continueRender2, 9219 cancelRender2, 9220 resolvedPixelDensity, 9221 isRendering 9222 ]); 9223 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 9224 const placeholder = canvas2dRef.current; 9225 if (!placeholder) { 9226 throw new Error("Canvas not found"); 9227 } 9228 placeholder.layoutSubtree = true; 9229 const offscreen = placeholder.transferControlToOffscreen(); 9230 offscreenRef.current = offscreen; 9231 resizeOffscreenCanvas({ 9232 offscreen, 9233 width: canvasWidth, 9234 height: canvasHeight 9235 }); 9236 initializedRef.current = false; 9237 unmountedRef.current = false; 9238 placeholder.addEventListener("paint", onPaintCb); 9239 return ()=>{ 9240 placeholder.removeEventListener("paint", onPaintCb); 9241 offscreenRef.current = null; 9242 initializedRef.current = false; 9243 unmountedRef.current = true; 9244 onInitCleanupRef.current?.(); 9245 onInitCleanupRef.current = null; 9246 }; 9247 }, [ 9248 onPaintCb, 9249 cancelRender2, 9250 canvasWidth, 9251 canvasHeight 9252 ]); 9253 const onPaintChangedRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(false); 9254 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 9255 if (!onPaintChangedRef.current) { 9256 onPaintChangedRef.current = true; 9257 return; 9258 } 9259 const canvas = canvas2dRef.current; 9260 if (!canvas) { 9261 return; 9262 } 9263 canvas.requestPaint?.(); 9264 }, [ 9265 onPaint, 9266 memoizedEffects 9267 ]); 9268 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 9269 const canvas = canvas2dRef.current; 9270 if (!canvas) { 9271 return; 9272 } 9273 const handle = delayRender("waiting for first paint after canvas resize"); 9274 canvas.addEventListener("paint", ()=>{ 9275 continueRender2(handle); 9276 }, { 9277 once: true 9278 }); 9279 return ()=>{ 9280 continueRender2(handle); 9281 }; 9282 }, [ 9283 width, 9284 height, 9285 continueRender2, 9286 canvasSizeKey 9287 ]); 9288 const innerStyle = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 9289 return { 9290 width, 9291 height 9292 }; 9293 }, [ 9294 width, 9295 height 9296 ]); 9297 const canvasStyle = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 9298 return { 9299 width, 9300 height, 9301 ...style ?? {} 9302 }; 9303 }, [ 9304 height, 9305 style, 9306 width 9307 ]); 9308 if (isInsideAncestorHtmlInCanvas) { 9309 throw new Error("<HtmlInCanvas> effects cannot be nested together. Chrome will only display the outer effect. Consider merging the effects into one if you can."); 9310 } 9311 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(HtmlInCanvasAncestorContext.Provider, { 9312 value: true, 9313 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)("canvas", { 9314 ref: setLayoutCanvasRef, 9315 width: canvasWidth, 9316 height: canvasHeight, 9317 style: canvasStyle, 9318 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)("div", { 9319 ref: divRef, 9320 style: innerStyle, 9321 children 9322 }) 9323 }, canvasSizeKey) 9324 }); 9325}); 9326HtmlInCanvasContent.displayName = "HtmlInCanvasContent"; 9327var HtmlInCanvasInner = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(({ width, height, effects = [], children, onPaint, onInit, pixelDensity, controls, style, durationInFrames, name, ...sequenceProps }, ref)=>{ 9328 const { durationInFrames: videoDuration } = useVideoConfig(); 9329 const resolvedDuration = durationInFrames ?? videoDuration; 9330 const memoizedEffectDefinitions = useMemoizedEffectDefinitions(effects); 9331 const actualRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 9332 const setCanvasRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((node)=>{ 9333 actualRef.current = node; 9334 if (typeof ref === "function") { 9335 ref(node); 9336 } else if (ref) { 9337 ref.current = node; 9338 } 9339 }, [ 9340 ref 9341 ]); 9342 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Sequence, { 9343 durationInFrames: resolvedDuration, 9344 name: name ?? "<HtmlInCanvas>", 9345 _remotionInternalDocumentationLink: "https://www.remotion.dev/docs/remotion/html-in-canvas", 9346 controls, 9347 _remotionInternalEffects: memoizedEffectDefinitions, 9348 outlineRef: actualRef, 9349 layout: "none", 9350 ...sequenceProps, 9351 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(HtmlInCanvasContent, { 9352 ref: setCanvasRef, 9353 width, 9354 height, 9355 effects, 9356 onPaint, 9357 onInit, 9358 pixelDensity, 9359 controls, 9360 style, 9361 children 9362 }) 9363 }); 9364});
9365HtmlInCanvasInner.displayName = "HtmlInCanvas"; 9366var htmlInCanvasSchema = { 9367 ...baseSchema, 9368 pixelDensity: { 9369 type: "number", 9370 min: 1, 9371 max: 3, 9372 step: 0.1, 9373 default: 1, 9374 description: "Pixel density", 9375 hiddenFromList: false 9376 }, 9377 ...transformSchema 9378}; 9379var HtmlInCanvasWrapped = withInteractivitySchema({ 9380 Component: HtmlInCanvasInner, 9381 componentName: "<HtmlInCanvas>", 9382 componentIdentity: "dev.remotion.remotion.HtmlInCanvas", 9383 schema: htmlInCanvasSchema, 9384 supportsEffects: true 9385}); 9386var HtmlInCanvas = Object.assign(HtmlInCanvasWrapped, { 9387 isSupported: isHtmlInCanvasSupported 9388}); 9389HtmlInCanvas.displayName = "HtmlInCanvas"; 9390addSequenceStackTraces(HtmlInCanvas);
9391// src/canvas-image/CanvasImage.tsx 9392
9393// src/truncate-src-for-label.ts 9394function truncateSrcForLabel(src) { 9395 if (src.startsWith("data:") && src.length > 100) { 9396 return src.slice(0, 60) + "...[" + src.length + " chars total]"; 9397 } 9398 return src; 9399}
9400// src/canvas-image/CanvasImage.tsx 9401 9402var canvasImageSchema = { 9403 ...baseSchema, 9404 fit: { 9405 type: "enum", 9406 default: "fill", 9407 description: "Fit", 9408 variants: { 9409 fill: {}, 9410 contain: {}, 9411 cover: {} 9412 } 9413 }, 9414 ...transformSchema 9415}; 9416var makeAbortError = ()=>{ 9417 if (typeof DOMException !== "undefined") { 9418 return new DOMException("Image loading was aborted", "AbortError"); 9419 } 9420 const error2 = new Error("Image loading was aborted"); 9421 error2.name = "AbortError"; 9422 return error2; 9423}; 9424var loadImage = ({ src, signal })=>{ 9425 return new Promise((resolve, reject)=>{ 9426 const image = new Image; 9427 let settled = false; 9428 function cleanup() { 9429 image.onload = null; 9430 image.onerror = null; 9431 } 9432 function settle(callback) { 9433 if (settled) { 9434 return; 9435 } 9436 settled = true; 9437 cleanup(); 9438 callback(); 9439 } 9440 function onAbort() { 9441 settle(()=>reject(makeAbortError())); 9442 } 9443 image.onload = ()=>{ 9444 Promise.resolve(image.decode?.()).catch(()=>{ 9445 return; 9446 }).then(()=>{ 9447 const imageWidth = image.naturalWidth || image.width; 9448 const imageHeight = image.naturalHeight || image.height; 9449 if (imageWidth <= 0 || imageHeight <= 0) { 9450 settle(()=>reject(new Error(`Could not determine dimensions for <CanvasImage> with src="${truncateSrcForLabel(src)}"`))); 9451 return; 9452 } 9453 settle(()=>resolve({ 9454 element: image, 9455 width: imageWidth, 9456 height: imageHeight 9457 })); 9458 }); 9459 }; 9460 image.onerror = ()=>{ 9461 settle(()=>reject(new Error(`Could not load <CanvasImage> with src="${truncateSrcForLabel(src)}"`))); 9462 }; 9463 signal.addEventListener("abort", onAbort, { 9464 once: true 9465 }); 9466 if (signal.aborted) { 9467 onAbort(); 9468 return; 9469 } 9470 image.crossOrigin = "anonymous"; 9471 image.src = src; 9472 }); 9473}; 9474function exponentialBackoff(errorCount) { 9475 return 1000 * 2 ** (errorCount - 1); 9476} 9477var waitForNextFrame = ({ onFrame })=>{ 9478 if (typeof requestAnimationFrame === "undefined") { 9479 onFrame(); 9480 return ()=>{ 9481 return; 9482 }; 9483 } 9484 const frame = requestAnimationFrame(onFrame); 9485 return ()=>cancelAnimationFrame(frame); 9486}; 9487var CanvasImageContent = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(({ src, width, height, fit = "fill", effects, controls, onError, className, style, id, pauseWhenLoading, maxRetries = 2, delayRenderRetries, delayRenderTimeoutInMilliseconds, refForOutline, ...canvasProps }, ref)=>{ 9488 const { delayRender: delayRender2, continueRender: continueRender2, cancelRender: cancelRender2 } = useDelayRender(); 9489 const { delayPlayback } = useBufferState(); 9490 const [outputCanvas, setOutputCanvas] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(null); 9491 const [loadedImage, setLoadedImage] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(null); 9492 const actualSrc = usePreload(src); 9493 const chainState = useEffectChainState(); 9494 const memoizedEffects = useMemoizedEffects({ 9495 effects, 9496 overrideId: controls?.overrideId ?? null 9497 }); 9498 const sequenceContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SequenceContext); 9499 const pendingLoadDelayRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 9500 const [isLoadPending, setIsLoadPending] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false); 9501 const isPremounting = Boolean(sequenceContext?.premounting); 9502 const isPostmounting = Boolean(sequenceContext?.postmounting); 9503 const continuePendingLoadDelay = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(({ markAsReady })=>{ 9504 const pending = pendingLoadDelayRef.current; 9505 if (!pending || pending.continued) { 9506 return; 9507 } 9508 pending.continued = true; 9509 if (markAsReady) { 9510 setIsLoadPending(false); 9511 } 9512 continueRender2(pending.handle); 9513 pendingLoadDelayRef.current = null; 9514 }, [ 9515 continueRender2 9516 ]); 9517 const sourceCanvas = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 9518 if (typeof document === "undefined") { 9519 return null; 9520 } 9521 return document.createElement("canvas"); 9522 }, []); 9523 const canvasRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((canvas)=>{ 9524 setOutputCanvas(canvas); 9525 if (refForOutline) { 9526 refForOutline.current = canvas; 9527 } 9528 if (typeof ref === "function") { 9529 ref(canvas); 9530 } else if (ref) { 9531 ref.current = canvas; 9532 } 9533 }, [ 9534 ref, 9535 refForOutline 9536 ]); 9537 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 9538 if (!pauseWhenLoading || !isLoadPending || isPremounting || isPostmounting) { 9539 return; 9540 } 9541 return delayPlayback().unblock; 9542 }, [ 9543 delayPlayback, 9544 isLoadPending, 9545 isPostmounting, 9546 isPremounting, 9547 pauseWhenLoading 9548 ]); 9549 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 9550 const handle = delayRender2(`Rendering <CanvasImage> with src="${truncateSrcForLabel(actualSrc)}"`, { 9551 retries: delayRenderRetries ?? undefined, 9552 timeoutInMilliseconds: delayRenderTimeoutInMilliseconds ?? undefined 9553 }); 9554 const controller = new AbortController; 9555 let cancelled = false;
vendor: 10,116 bytes, lines 9556-9853
9556 let errorCount = 0; 9557 let timeoutId = null; 9558 setLoadedImage(null); 9559 setIsLoadPending(true); 9560 pendingLoadDelayRef.current = { 9561 handle, 9562 continued: false 9563 }; 9564 const attemptLoad = ()=>{ 9565 loadImage({ 9566 src: actualSrc, 9567 signal: controller.signal 9568 }).then((image)=>{ 9569 if (cancelled) { 9570 return; 9571 } 9572 setLoadedImage(image); 9573 }).catch((err)=>{ 9574 if (err.name === "AbortError") { 9575 continuePendingLoadDelay({ 9576 markAsReady: false 9577 }); 9578 return; 9579 } 9580 errorCount++; 9581 if (errorCount <= maxRetries) { 9582 const backoff = exponentialBackoff(errorCount); 9583 console.warn(`Could not load <CanvasImage> with src="${truncateSrcForLabel(actualSrc)}", retrying in ${backoff}ms`); 9584 timeoutId = setTimeout(()=>{ 9585 if (!cancelled) { 9586 attemptLoad(); 9587 } 9588 }, backoff); 9589 } else if (onError) { 9590 onError(err); 9591 continuePendingLoadDelay({ 9592 markAsReady: true 9593 }); 9594 } else { 9595 cancelRender2(err); 9596 } 9597 }); 9598 }; 9599 attemptLoad(); 9600 return ()=>{ 9601 cancelled = true; 9602 if (timeoutId !== null) { 9603 clearTimeout(timeoutId); 9604 } 9605 controller.abort(); 9606 continuePendingLoadDelay({ 9607 markAsReady: false 9608 }); 9609 }; 9610 }, [ 9611 actualSrc, 9612 cancelRender2, 9613 continuePendingLoadDelay, 9614 delayRender2, 9615 delayRenderRetries, 9616 delayRenderTimeoutInMilliseconds, 9617 maxRetries, 9618 onError 9619 ]); 9620 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 9621 if (!loadedImage || !outputCanvas || !sourceCanvas) { 9622 return; 9623 } 9624 const handle = delayRender2(`Applying effects to <CanvasImage> with src="${truncateSrcForLabel(actualSrc)}"`); 9625 let cancelled = false; 9626 let continued = false; 9627 let cancelWaitForNextFrame = ()=>{ 9628 return; 9629 }; 9630 const continueRenderOnce = ()=>{ 9631 if (continued) { 9632 return; 9633 } 9634 continued = true; 9635 continueRender2(handle); 9636 }; 9637 const canvasWidth = width ?? loadedImage.width; 9638 const canvasHeight = height ?? loadedImage.height; 9639 const sourceContext = sourceCanvas.getContext("2d", { 9640 colorSpace: "srgb" 9641 }); 9642 if (!sourceContext) { 9643 cancelRender2(new Error("Could not get 2D context for <CanvasImage> source canvas")); 9644 continueRenderOnce(); 9645 return ()=>{ 9646 continueRenderOnce(); 9647 }; 9648 } 9649 sourceCanvas.width = canvasWidth; 9650 sourceCanvas.height = canvasHeight; 9651 outputCanvas.width = canvasWidth; 9652 outputCanvas.height = canvasHeight; 9653 sourceContext.clearRect(0, 0, canvasWidth, canvasHeight); 9654 sourceContext.drawImage(loadedImage.element, ...calculateImageFit(fit, { 9655 width: loadedImage.width, 9656 height: loadedImage.height 9657 }, { 9658 width: canvasWidth, 9659 height: canvasHeight 9660 })); 9661 runEffectChain({ 9662 state: chainState.get(canvasWidth, canvasHeight), 9663 source: sourceCanvas, 9664 effects: memoizedEffects, 9665 output: outputCanvas, 9666 width: canvasWidth, 9667 height: canvasHeight 9668 }).then((completed)=>{ 9669 if (completed && !cancelled) { 9670 cancelWaitForNextFrame = waitForNextFrame({ 9671 onFrame: ()=>{ 9672 if (cancelled) { 9673 return; 9674 } 9675 continueRenderOnce(); 9676 continuePendingLoadDelay({ 9677 markAsReady: true 9678 }); 9679 } 9680 }); 9681 } 9682 }).catch((err)=>{ 9683 if (cancelled) { 9684 return; 9685 } 9686 if (onError) { 9687 onError(err); 9688 continueRenderOnce(); 9689 continuePendingLoadDelay({ 9690 markAsReady: true 9691 }); 9692 } else { 9693 cancelRender2(err); 9694 } 9695 }); 9696 return ()=>{ 9697 cancelled = true; 9698 cancelWaitForNextFrame(); 9699 continueRenderOnce(); 9700 }; 9701 }, [ 9702 actualSrc, 9703 cancelRender2, 9704 chainState, 9705 continueRender2, 9706 continuePendingLoadDelay, 9707 delayRender2, 9708 fit, 9709 height, 9710 loadedImage, 9711 memoizedEffects, 9712 onError, 9713 outputCanvas, 9714 sourceCanvas, 9715 width 9716 ]); 9717 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)("canvas", { 9718 ...canvasProps, 9719 ref: canvasRef, 9720 width, 9721 height, 9722 className, 9723 style, 9724 id 9725 }); 9726}); 9727CanvasImageContent.displayName = "CanvasImageContent"; 9728var CanvasImageInner = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(({ src, width, height, fit, effects = [], className, style, id, onError, pauseWhenLoading, maxRetries, delayRenderRetries, delayRenderTimeoutInMilliseconds, durationInFrames, from, trimBefore, freeze, hidden, name, showInTimeline, stack, controls, _remotionInternalDocumentationLink, outlineRef, ...canvasProps }, ref)=>{ 9729 if (!src) { 9730 throw new Error('No "src" prop was passed to <CanvasImage>.'); 9731 } 9732 const memoizedEffectDefinitions = useMemoizedEffectDefinitions(effects); 9733 const actualRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 9734 (0,react__WEBPACK_IMPORTED_MODULE_0__.useImperativeHandle)(ref, ()=>{ 9735 return actualRef.current; 9736 }, []); 9737 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Sequence, { 9738 layout: "none", 9739 from: from ?? 0, 9740 trimBefore, 9741 durationInFrames: durationInFrames ?? Infinity, 9742 freeze, 9743 hidden, 9744 showInTimeline: showInTimeline ?? true, 9745 name: name ?? "<CanvasImage>", 9746 _remotionInternalDocumentationLink: _remotionInternalDocumentationLink ?? "https://www.remotion.dev/docs/canvasimage", 9747 controls, 9748 _remotionInternalEffects: memoizedEffectDefinitions, 9749 _remotionInternalIsMedia: { 9750 type: "image", 9751 src 9752 }, 9753 _remotionInternalStack: stack, 9754 outlineRef: outlineRef ?? actualRef, 9755 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(CanvasImageContent, { 9756 ref: actualRef, 9757 src, 9758 width, 9759 height, 9760 fit, 9761 effects, 9762 controls, 9763 className, 9764 style, 9765 id, 9766 onError, 9767 pauseWhenLoading, 9768 maxRetries, 9769 delayRenderRetries, 9770 delayRenderTimeoutInMilliseconds, 9771 refForOutline: outlineRef ?? null, 9772 ...canvasProps 9773 }) 9774 }); 9775}); 9776var CanvasImage = withInteractivitySchema({ 9777 Component: CanvasImageInner, 9778 componentName: "<CanvasImage>", 9779 componentIdentity: "dev.remotion.remotion.CanvasImage", 9780 schema: canvasImageSchema, 9781 supportsEffects: true 9782}); 9783CanvasImage.displayName = "CanvasImage"; 9784addSequenceStackTraces(CanvasImage); 9785// src/get-static-files.ts 9786var warnedServer = false; 9787var warnedPlayer = false; 9788var warnServerOnce = ()=>{ 9789 if (warnedServer) { 9790 return; 9791 } 9792 warnedServer = true; 9793 console.warn("Called getStaticFiles() on the server. The API is only available in the browser. An empty array was returned."); 9794}; 9795var warnPlayerOnce = ()=>{ 9796 if (warnedPlayer) { 9797 return; 9798 } 9799 warnedPlayer = true; 9800 console.warn("Called getStaticFiles() while using the Remotion Player. The API is only available while using the Remotion Studio. An empty array was returned."); 9801}; 9802var getStaticFiles = ()=>{ 9803 if (ENABLE_V5_BREAKING_CHANGES) { 9804 throw new Error("getStaticFiles() has moved into the `@remotion/studio` package. Update your imports."); 9805 } 9806 if (typeof document === "undefined") { 9807 warnServerOnce(); 9808 return []; 9809 } 9810 if (window.remotion_isPlayer) { 9811 warnPlayerOnce(); 9812 return []; 9813 } 9814 return window.remotion_staticFiles; 9815}; 9816// src/IFrame.tsx 9817 9818 9819var IFrameRefForwarding = ({ onLoad, onError, delayRenderRetries, delayRenderTimeoutInMilliseconds, ...props2 }, ref)=>{ 9820 const { delayRender: delayRender2, continueRender: continueRender2 } = useDelayRender(); 9821 const [handle] = useState17(()=>delayRender2(`Loading <IFrame> with source ${props2.src}`, { 9822 retries: delayRenderRetries ?? undefined, 9823 timeoutInMilliseconds: delayRenderTimeoutInMilliseconds ?? undefined 9824 })); 9825 const didLoad = useCallback18((e)=>{ 9826 continueRender2(handle); 9827 onLoad?.(e); 9828 }, [ 9829 handle, 9830 onLoad, 9831 continueRender2 9832 ]); 9833 const didGetError = useCallback18((e)=>{ 9834 continueRender2(handle); 9835 if (onError) { 9836 onError(e); 9837 } else { 9838 console.error("Error loading iframe:", e, "Handle the event using the onError() prop to make this message disappear."); 9839 } 9840 }, [ 9841 handle, 9842 onError, 9843 continueRender2 9844 ]); 9845 return /* @__PURE__ */ jsx27("iframe", { 9846 referrerPolicy: "strict-origin-when-cross-origin", 9847 ...props2, 9848 ref, 9849 onError: didGetError, 9850 onLoad: didLoad 9851 }); 9852}; 9853var IFrame = /*#__PURE__*/ (/* unused pure expression or super */ null && (forwardRef11(IFrameRefForwarding)));
9854// src/Img.tsx 9855 9856 9857function exponentialBackoff2(errorCount) { 9858 return 1000 * 2 ** (errorCount - 1); 9859} 9860var ImgContent = ({ onError, maxRetries = 2, src, pauseWhenLoading, delayRenderRetries, delayRenderTimeoutInMilliseconds, onImageFrame, crossOrigin, decoding, ref, refForOutline, ...props2 })=>{ 9861 const imageRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 9862 const errors = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)({}); 9863 const { delayPlayback } = useBufferState(); 9864 const sequenceContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SequenceContext); 9865 const [isLoading, setIsLoading] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false); 9866 const _propsValid = true; 9867 if (!_propsValid) { 9868 throw new Error("typecheck error"); 9869 } 9870 const imageCallbackRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((img)=>{ 9871 imageRef.current = img; 9872 refForOutline.current = img; 9873 if (typeof ref === "function") { 9874 ref(img); 9875 } else if (ref) { 9876 ref.current = img; 9877 } 9878 }, [ 9879 ref, 9880 refForOutline 9881 ]); 9882 const actualSrc = usePreload(src); 9883 const retryIn = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((timeout)=>{ 9884 if (!imageRef.current) { 9885 return; 9886 } 9887 const currentSrc = imageRef.current.src; 9888 setTimeout(()=>{ 9889 if (!imageRef.current) { 9890 return; 9891 } 9892 const newSrc = imageRef.current?.src; 9893 if (newSrc !== currentSrc) { 9894 return; 9895 } 9896 imageRef.current.removeAttribute("src"); 9897 imageRef.current.setAttribute("src", newSrc); 9898 }, timeout); 9899 }, []); 9900 const { delayRender: delayRender2, continueRender: continueRender2, cancelRender: cancelRender2 } = useDelayRender(); 9901 const isPremounting = Boolean(sequenceContext?.premounting); 9902 const isPostmounting = Boolean(sequenceContext?.postmounting); 9903 const didGetError = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((e)=>{ 9904 if (!errors.current) { 9905 return; 9906 } 9907 errors.current[imageRef.current?.src] = (errors.current[imageRef.current?.src] ?? 0) + 1; 9908 if (onError && (errors.current[imageRef.current?.src] ?? 0) > maxRetries) { 9909 onError(e); 9910 return; 9911 } 9912 if ((errors.current[imageRef.current?.src] ?? 0) <= maxRetries) { 9913 const backoff = exponentialBackoff2(errors.current[imageRef.current?.src] ?? 0); 9914 console.warn(`Could not load image with source ${truncateSrcForLabel(imageRef.current?.src)}, retrying again in ${backoff}ms`); 9915 retryIn(backoff); 9916 return; 9917 } 9918 try { 9919 cancelRender2("Error loading image with src: " + truncateSrcForLabel(imageRef.current?.src)); 9920 } catch {} 9921 }, [ 9922 cancelRender2, 9923 maxRetries, 9924 onError, 9925 retryIn 9926 ]); 9927 if (typeof window !== "undefined") { 9928 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 9929 if (!pauseWhenLoading || !isLoading || isPremounting || isPostmounting) { 9930 return; 9931 } 9932 return delayPlayback().unblock; 9933 }, [ 9934 delayPlayback, 9935 isLoading, 9936 isPostmounting, 9937 isPremounting, 9938 pauseWhenLoading 9939 ]); 9940 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 9941 if (window.process?.env?.NODE_ENV === "test") { 9942 if (imageRef.current) { 9943 imageRef.current.src = actualSrc; 9944 } 9945 return; 9946 } 9947 const { current } = imageRef; 9948 if (!current) { 9949 return; 9950 } 9951 setIsLoading(true); 9952 const newHandle = delayRender2("Loading <Img> with src=" + truncateSrcForLabel(actualSrc), { 9953 retries: delayRenderRetries ?? undefined, 9954 timeoutInMilliseconds: delayRenderTimeoutInMilliseconds ?? undefined 9955 }); 9956 let unmounted = false;
vendor: 4,294 bytes, lines 9957-10074
9957 const onComplete = ()=>{ 9958 if (unmounted) { 9959 continueRender2(newHandle); 9960 return; 9961 } 9962 if ((errors.current[imageRef.current?.src] ?? 0) > 0) { 9963 delete errors.current[imageRef.current?.src]; 9964 console.info(`Retry successful - ${truncateSrcForLabel(imageRef.current?.src)} is now loaded`); 9965 } 9966 if (current) { 9967 onImageFrame?.(current); 9968 } 9969 setIsLoading(false); 9970 continueRender2(newHandle); 9971 }; 9972 if (!imageRef.current) { 9973 onComplete(); 9974 return; 9975 } 9976 current.src = actualSrc; 9977 current.decode().then(onComplete).catch((err)=>{ 9978 console.warn(err); 9979 if (current.complete && current.naturalWidth > 0 && current.naturalHeight > 0) { 9980 onComplete(); 9981 } else { 9982 current.addEventListener("load", onComplete); 9983 } 9984 }); 9985 return ()=>{ 9986 unmounted = true; 9987 current.removeEventListener("load", onComplete); 9988 continueRender2(newHandle); 9989 }; 9990 }, [ 9991 actualSrc, 9992 delayRenderRetries, 9993 delayRenderTimeoutInMilliseconds, 9994 onImageFrame, 9995 continueRender2, 9996 delayRender2 9997 ]); 9998 } 9999 const { isClientSideRendering, isRendering } = useRemotionEnvironment(); 10000 const crossOriginValue = getCrossOriginValue({ 10001 crossOrigin, 10002 requestsVideoFrame: false, 10003 isClientSideRendering 10004 }); 10005 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)("img", { 10006 ...props2, 10007 ref: imageCallbackRef, 10008 crossOrigin: crossOriginValue, 10009 onError: didGetError, 10010 decoding: isRendering ? "sync" : decoding 10011 }); 10012}; 10013var NativeImgInner = ({ hidden, name, stack, showInTimeline, src, from, trimBefore, durationInFrames, freeze, controls, outlineRef: refForOutline, ...props2 })=>{ 10014 if (!src) { 10015 throw new Error('No "src" prop was passed to <Img>.'); 10016 } 10017 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Sequence, { 10018 layout: "none", 10019 from: from ?? 0, 10020 trimBefore, 10021 durationInFrames: durationInFrames ?? Infinity, 10022 freeze, 10023 _remotionInternalStack: stack, 10024 _remotionInternalDocumentationLink: "https://www.remotion.dev/docs/img", 10025 _remotionInternalIsMedia: { 10026 type: "image", 10027 src 10028 }, 10029 name: name ?? "<Img>", 10030 controls, 10031 showInTimeline: showInTimeline ?? true, 10032 hidden, 10033 outlineRef: refForOutline, 10034 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(ImgContent, { 10035 src, 10036 refForOutline, 10037 ...props2 10038 }) 10039 }); 10040}; 10041var CanvasImageWithPrivateProps = CanvasImage; 10042var imgSchema = { 10043 ...baseSchema, 10044 ...transformSchema 10045}; 10046var imgCanvasFallbackIncompatibleProps = new Set([ 10047 "alt", 10048 "crossOrigin", 10049 "decoding", 10050 "fetchPriority", 10051 "loading", 10052 "onError", 10053 "onImageFrame", 10054 "onLoad", 10055 "sizes", 10056 "srcSet", 10057 "useMap" 10058]); 10059var getIncompatiblePropNames = (props2)=>Object.keys(props2).filter((key)=>props2[key] !== undefined && imgCanvasFallbackIncompatibleProps.has(key)); 10060var formatPropList = (props2)=>{ 10061 return props2.map((prop)=>`"${prop}"`).join(", "); 10062}; 10063var validateCanvasImageFallbackProps = ({ props: props2, ref, width, height })=>{ 10064 if (typeof width === "string" || typeof height === "string") { 10065 throw new Error('The "width" and "height" props must be numbers on <Img> when effects are passed, because <Img> renders a <CanvasImage>. Use numeric props or CSS dimensions in "style".'); 10066 } 10067 const conflictingProps = getIncompatiblePropNames(props2); 10068 if (ref !== null && ref !== undefined) { 10069 conflictingProps.unshift("ref"); 10070 } 10071 if (conflictingProps.length === 0) { 10072 return; 10073 } 10074 throw new Error(`The ${formatPropList(conflictingProps)} prop${conflictingProps.length === 1 ? "" : "s"}
10074 cannot be used on <Img> when effects are passed, because <Img> renders a <canvas> instead of a native <img>. Remove ${conflictingProps.length === 1 ? "this prop" : "these props"}.`); 10075}; 10076var getFitFromObjectFit = (style)=>{ 10077 const objectFit = style?.objectFit; 10078 if (objectFit === "fill" || objectFit === "contain" || objectFit === "cover") { 10079 return objectFit; 10080 } 10081 return; 10082}; 10083var ImgInner = ({ effects = [], ref, hidden, name, stack, showInTimeline, src, from, trimBefore, durationInFrames, freeze, controls, width, height, className, style, id, pauseWhenLoading, maxRetries, delayRenderRetries, delayRenderTimeoutInMilliseconds, ...props2 })=>{ 10084 const refForOutline = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 10085 if (effects.length === 0) { 10086 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(NativeImgInner, { 10087 ...props2, 10088 ref, 10089 hidden, 10090 name, 10091 stack, 10092 showInTimeline, 10093 src, 10094 from, 10095 trimBefore, 10096 durationInFrames, 10097 freeze, 10098 controls, 10099 width, 10100 height, 10101 className, 10102 style, 10103 id, 10104 pauseWhenLoading, 10105 maxRetries, 10106 delayRenderRetries, 10107 delayRenderTimeoutInMilliseconds, 10108 outlineRef: refForOutline 10109 }); 10110 } 10111 if (!src) { 10112 throw new Error('No "src" prop was passed to <Img>.'); 10113 } 10114 validateCanvasImageFallbackProps({ 10115 props: props2, 10116 ref, 10117 width, 10118 height 10119 }); 10120 const canvasWidth = typeof width === "number" ? width : undefined; 10121 const canvasHeight = typeof height === "number" ? height : undefined; 10122 const canvasProps = props2; 10123 const canvasFit = getFitFromObjectFit(style) ?? "fill"; 10124 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(CanvasImageWithPrivateProps, { 10125 src, 10126 width: canvasWidth, 10127 height: canvasHeight, 10128 fit: canvasFit, 10129 effects, 10130 className, 10131 style, 10132 id, 10133 pauseWhenLoading, 10134 maxRetries, 10135 delayRenderRetries, 10136 delayRenderTimeoutInMilliseconds, 10137 from, 10138 trimBefore, 10139 durationInFrames, 10140 freeze, 10141 hidden, 10142 name: name ?? "<Img>", 10143 showInTimeline, 10144 stack, 10145 _remotionInternalDocumentationLink: "https://www.remotion.dev/docs/img", 10146 controls, 10147 outlineRef: refForOutline, 10148 ...canvasProps 10149 }); 10150}; 10151var Img = withInteractivitySchema({ 10152 Component: ImgInner, 10153 componentName: "<Img>", 10154 componentIdentity: "dev.remotion.remotion.Img", 10155 schema: imgSchema, 10156 supportsEffects: true 10157}); 10158addSequenceStackTraces(Img);
10159// src/Interactive.tsx 10160 10161 10162var interactiveElementSchema = { 10163 ...baseSchema, 10164 ...transformSchema, 10165 ...textSchema, 10166 ...textContentSchema 10167}; 10168var setRef = (ref, value)=>{ 10169 if (typeof ref === "function") { 10170 ref(value); 10171 } else if (ref) { 10172 ref.current = value; 10173 } 10174}; 10175var makeInteractiveElement = (tag, displayName)=>{ 10176 const Inner = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)((propsWithControls, ref)=>{ 10177 const { durationInFrames, from, trimBefore, freeze, hidden, name, showInTimeline, stack, controls, ...props2 } = propsWithControls; 10178 const refForOutline = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 10179 const callbackRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((element)=>{ 10180 refForOutline.current = element; 10181 setRef(ref, element); 10182 }, [ 10183 ref 10184 ]); 10185 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Sequence, { 10186 layout: "none", 10187 from: from ?? 0, 10188 trimBefore, 10189 durationInFrames: durationInFrames ?? Infinity, 10190 freeze, 10191 hidden, 10192 name: name ?? displayName, 10193 showInTimeline: showInTimeline ?? true, 10194 controls, 10195 _remotionInternalStack: stack, 10196 _remotionInternalDocumentationLink: "https://www.remotion.dev/docs/interactive", 10197 outlineRef: refForOutline, 10198 children: /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createElement(tag, { 10199 ...props2, 10200 ref: callbackRef 10201 }) 10202 }); 10203 }); 10204 Inner.displayName = displayName; 10205 const Wrapped = withInteractivitySchema({ 10206 Component: Inner, 10207 componentName: displayName, 10208 componentIdentity: `dev.remotion.remotion.${displayName.slice(1, -1)}`, 10209 schema: interactiveElementSchema, 10210 supportsEffects: false 10211 }); 10212 Wrapped.displayName = displayName; 10213 addSequenceStackTraces(Wrapped); 10214 return Wrapped; 10215}; 10216var Interactive = { 10217 baseSchema, 10218 transformSchema, 10219 textSchema, 10220 premountSchema, 10221 sequenceSchema, 10222 withSchema: withInteractivitySchema, 10223 A: makeInteractiveElement("a", "<Interactive.A>"), 10224 Article: makeInteractiveElement("article", "<Interactive.Article>"), 10225 Aside: makeInteractiveElement("aside", "<Interactive.Aside>"), 10226 Button: makeInteractiveElement("button", "<Interactive.Button>"), 10227 Circle: makeInteractiveElement("circle", "<Interactive.Circle>"), 10228 Code: makeInteractiveElement("code", "<Interactive.Code>"), 10229 Div: makeInteractiveElement("div", "<Interactive.Div>"), 10230 Ellipse: makeInteractiveElement("ellipse", "<Interactive.Ellipse>"), 10231 Em: makeInteractiveElement("em", "<Interactive.Em>"), 10232 Footer: makeInteractiveElement("footer", "<Interactive.Footer>"), 10233 G: makeInteractiveElement("g", "<Interactive.G>"), 10234 H1: makeInteractiveElement("h1", "<Interactive.H1>"), 10235 H2: makeInteractiveElement("h2", "<Interactive.H2>"), 10236 H3: makeInteractiveElement("h3", "<Interactive.H3>"), 10237 H4: makeInteractiveElement("h4", "<Interactive.H4>"), 10238 H5: makeInteractiveElement("h5", "<Interactive.H5>"), 10239 H6: makeInteractiveElement("h6", "<Interactive.H6>"), 10240 Header: makeInteractiveElement("header", "<Interactive.Header>"), 10241 Label: makeInteractiveElement("label", "<Interactive.Label>"), 10242 Li: makeInteractiveElement("li", "<Interactive.Li>"), 10243 Line: makeInteractiveElement("line", "<Interactive.Line>"), 10244 Main: makeInteractiveElement("main", "<Interactive.Main>"), 10245 Nav: makeInteractiveElement("nav", "<Interactive.Nav>"), 10246 Ol: makeInteractiveElement("ol", "<Interactive.Ol>"), 10247 P: makeInteractiveElement("p", "<Interactive.P>"), 10248 Path: makeInteractiveElement("path", "<Interactive.Path>"), 10249 Pre: makeInteractiveElement("pre", "<Interactive.Pre>"), 10250 Rect: makeInteractiveElement("rect", "<Interactive.Rect>"), 10251 Section: makeInteractiveElement("section", "<Interactive.Section>"), 10252 Small: makeInteractiveElement("small", "<Interactive.Small>"), 10253 Span: makeInteractiveElement("span", "<Interactive.Span>"), 10254 Strong: makeInteractiveElement("strong", "<Interactive.Strong>"), 10255 Svg: makeInteractiveElement("svg", "<Interactive.Svg>"), 10256 Text: makeInteractiveElement("text", "<Interactive.Text>"), 10257 Ul: makeInteractiveElement("ul", "<Interactive.Ul>") 10258};
10259// src/internals.ts 10260
10261// src/CompositionManager.tsx 10262 10263var compositionsRef = /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createRef();
10264// src/CompositionManagerProvider.tsx 10265 10266 10267var CompositionManagerProvider = ({ children, onlyRenderComposition, currentCompositionMetadata, initialCompositions, initialCanvasContent })=>{ 10268 const [folders, setFolders] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)([]); 10269 const [canvasContent, setCanvasContent] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(initialCanvasContent); 10270 const [compositions, setCompositions] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(initialCompositions); 10271 const currentcompositionsRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(compositions); 10272 const updateCompositions = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((updateComps)=>{ 10273 setCompositions((comps)=>{ 10274 const updated = updateComps(comps); 10275 currentcompositionsRef.current = updated; 10276 return updated; 10277 }); 10278 }, []); 10279 const registerComposition = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((comp)=>{ 10280 updateCompositions((comps)=>{ 10281 if (comps.find((c2)=>c2.id === comp.id)) { 10282 throw new Error(`Multiple composition with id ${comp.id} are registered.`); 10283 } 10284 return [ 10285 ...comps, 10286 comp 10287 ]; 10288 }); 10289 }, [ 10290 updateCompositions 10291 ]); 10292 const unregisterComposition = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((id)=>{ 10293 setCompositions((comps)=>{ 10294 return comps.filter((c2)=>c2.id !== id); 10295 }); 10296 }, []); 10297 const registerFolder = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((name, parent, nonce, stack)=>{ 10298 setFolders((prevFolders)=>{ 10299 return [ 10300 ...prevFolders, 10301 { 10302 name, 10303 parent, 10304 nonce, 10305 stack 10306 } 10307 ]; 10308 }); 10309 }, []); 10310 const unregisterFolder = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((name, parent)=>{ 10311 setFolders((prevFolders)=>{ 10312 return prevFolders.filter((p)=>!(p.name === name && p.parent === parent)); 10313 }); 10314 }, []); 10315 (0,react__WEBPACK_IMPORTED_MODULE_0__.useImperativeHandle)(compositionsRef, ()=>{ 10316 return { 10317 getCompositions: ()=>currentcompositionsRef.current 10318 }; 10319 }, []); 10320 const compositionManagerSetters = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 10321 return { 10322 registerComposition, 10323 unregisterComposition, 10324 registerFolder, 10325 unregisterFolder, 10326 setCanvasContent, 10327 onlyRenderComposition 10328 }; 10329 }, [ 10330 registerComposition, 10331 registerFolder, 10332 unregisterComposition, 10333 unregisterFolder, 10334 onlyRenderComposition 10335 ]); 10336 const compositionManagerContextValue = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 10337 return { 10338 compositions, 10339 folders, 10340 currentCompositionMetadata, 10341 canvasContent 10342 }; 10343 }, [ 10344 compositions, 10345 folders, 10346 currentCompositionMetadata, 10347 canvasContent 10348 ]); 10349 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(CompositionManager.Provider, { 10350 value: compositionManagerContextValue, 10351 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(CompositionSetters.Provider, { 10352 value: compositionManagerSetters, 10353 children 10354 }) 10355 }); 10356};
vendor: 1,508 bytes, lines 10357-10415
10357// src/default-css.ts 10358var exports_default_css = {}; 10359__export(exports_default_css, { 10360 makeDefaultPreviewCSS: ()=>makeDefaultPreviewCSS, 10361 injectCSS: ()=>injectCSS, 10362 OBJECTFIT_CONTAIN_CLASS_NAME: ()=>OBJECTFIT_CONTAIN_CLASS_NAME 10363}); 10364var injected = {}; 10365var injectCSS = (css)=>{ 10366 if (typeof document === "undefined") { 10367 return ()=>{}; 10368 } 10369 if (injected[css]) { 10370 return ()=>{}; 10371 } 10372 const head = document.head || document.getElementsByTagName("head")[0]; 10373 const style = document.createElement("style"); 10374 style.appendChild(document.createTextNode(css)); 10375 head.prepend(style); 10376 injected[css] = style; 10377 return ()=>{ 10378 const styleElement = injected[css]; 10379 if (styleElement) { 10380 if (styleElement.parentNode) { 10381 styleElement.parentNode.removeChild(styleElement); 10382 } 10383 delete injected[css]; 10384 } 10385 }; 10386}; 10387var OBJECTFIT_CONTAIN_CLASS_NAME = "__remotion_objectfitcontain"; 10388var makeDefaultPreviewCSS = (scope, backgroundColor)=>{ 10389 if (!scope) { 10390 return ` 10391 * { 10392 box-sizing: border-box; 10393 } 10394 body { 10395 margin: 0; 10396 background-color: ${backgroundColor}; 10397 } 10398 .${OBJECTFIT_CONTAIN_CLASS_NAME} { 10399 object-fit: contain; 10400 } 10401 `; 10402 } 10403 return ` 10404 ${scope} * { 10405 box-sizing: border-box; 10406 } 10407 ${scope} *:-webkit-full-screen { 10408 width: 100%; 10409 height: 100%; 10410 } 10411 ${scope} .${OBJECTFIT_CONTAIN_CLASS_NAME} { 10412 object-fit: contain; 10413 } 10414 `; 10415};
10416// src/get-preview-dom-element.ts 10417var REMOTION_STUDIO_CONTAINER_ELEMENT = "__remotion-studio-container"; 10418var getPreviewDomElement = ()=>{ 10419 return document.getElementById(REMOTION_STUDIO_CONTAINER_ELEMENT); 10420};
10421// src/max-video-cache-size.ts 10422 10423var MaxMediaCacheSizeContext = /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createContext(null);
vendor: 660 bytes, lines 10424-10453
10424// src/register-root.ts 10425var Root = null; 10426var listeners = []; 10427var registerRoot = (comp)=>{ 10428 if (!comp) { 10429 throw new Error(`You must pass a React component to registerRoot(), but ${JSON.stringify(comp)} was passed.`); 10430 } 10431 if (Root) { 10432 throw new Error("registerRoot() was called more than once."); 10433 } 10434 Root = comp; 10435 listeners.forEach((l)=>{ 10436 l(comp); 10437 }); 10438}; 10439var getRoot = ()=>{ 10440 return Root; 10441}; 10442var waitForRoot = (fn)=>{ 10443 if (Root) { 10444 fn(Root); 10445 return ()=>{ 10446 return; 10447 }; 10448 } 10449 listeners.push(fn); 10450 return ()=>{ 10451 listeners = listeners.filter((l)=>l !== fn); 10452 }; 10453};
10454// src/RemotionRoot.tsx 10455
10456// src/use-media-enabled.tsx 10457 10458 10459var MediaEnabledContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)(null); 10460var useVideoEnabled = ()=>{ 10461 const context = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(MediaEnabledContext); 10462 if (!context) { 10463 return window.remotion_videoEnabled; 10464 } 10465 if (context.videoEnabled === null) { 10466 return window.remotion_videoEnabled; 10467 } 10468 return context.videoEnabled; 10469}; 10470var useAudioEnabled = ()=>{ 10471 const context = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(MediaEnabledContext); 10472 if (!context) { 10473 return window.remotion_audioEnabled; 10474 } 10475 if (context.audioEnabled === null) { 10476 return window.remotion_audioEnabled; 10477 } 10478 return context.audioEnabled; 10479}; 10480var MediaEnabledProvider = ({ children, videoEnabled, audioEnabled })=>{ 10481 const value = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>({ 10482 videoEnabled, 10483 audioEnabled 10484 }), [ 10485 videoEnabled, 10486 audioEnabled 10487 ]); 10488 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(MediaEnabledContext.Provider, { 10489 value, 10490 children 10491 }); 10492};
10493// src/RemotionRoot.tsx 10494 10495var RemotionRootContexts = ({ children, numberOfAudioTags, logLevel, audioLatencyHint, previewSampleRate, videoEnabled, audioEnabled, frameState })=>{ 10496 const nonceContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 10497 let counter = 0; 10498 return { 10499 getNonce: ()=>counter++ 10500 }; 10501 }, []); 10502 const logging = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 10503 return { 10504 logLevel, 10505 mountTime: Date.now() 10506 }; 10507 }, [ 10508 logLevel 10509 ]); 10510 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(LogLevelContext.Provider, { 10511 value: logging, 10512 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(NonceContext.Provider, { 10513 value: nonceContext, 10514 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(TimelineContextProvider, { 10515 frameState, 10516 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(MediaEnabledProvider, { 10517 videoEnabled, 10518 audioEnabled, 10519 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(EditorPropsProvider, { 10520 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(PrefetchProvider, { 10521 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(SequenceManagerProvider, { 10522 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(DurationsContextProvider, { 10523 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(BufferingProvider, { 10524 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(SharedAudioContextProvider, { 10525 audioLatencyHint, 10526 audioEnabled, 10527 previewSampleRate, 10528 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(SharedAudioTagsContextProvider, { 10529 numberOfAudioTags, 10530 children 10531 }) 10532 }) 10533 }) 10534 }) 10535 }) 10536 }) 10537 }) 10538 }) 10539 }) 10540 }) 10541 }); 10542};
10543// src/codec.ts 10544var validCodecs = [ 10545 "h264", 10546 "h265", 10547 "vp8", 10548 "vp9", 10549 "av1", 10550 "mp3", 10551 "aac", 10552 "wav", 10553 "prores", 10554 "h264-mkv", 10555 "h264-ts", 10556 "gif" 10557];
10558// src/validation/validate-default-codec.ts 10559function validateCodec(defaultCodec, location, name) { 10560 if (typeof defaultCodec === "undefined") { 10561 return; 10562 } 10563 if (typeof defaultCodec !== "string") { 10564 throw new TypeError(`The "${name}" prop ${location} must be a string, but you passed a value of type ${typeof defaultCodec}.`); 10565 } 10566 if (!validCodecs.includes(defaultCodec)) { 10567 throw new Error(`The "${name}" prop ${location} must be one of ${validCodecs.join(", ")}, but you passed ${defaultCodec}.`); 10568 } 10569}
10570// src/resolve-video-config.ts 10571var validateCalculated = ({ calculated, compositionId, compositionFps, compositionHeight, compositionWidth, compositionDurationInFrames })=>{ 10572 const calculateMetadataErrorLocation = `calculated by calculateMetadata() for the composition "${compositionId}"`; 10573 const defaultErrorLocation = `of the "<Composition />" component with the id "${compositionId}"`; 10574 const width = calculated?.width ?? compositionWidth ?? undefined; 10575 validateDimension(width, "width", calculated?.width ? calculateMetadataErrorLocation : defaultErrorLocation); 10576 const height = calculated?.height ?? compositionHeight ?? undefined; 10577 validateDimension(height, "height", calculated?.height ? calculateMetadataErrorLocation : defaultErrorLocation); 10578 const fps = calculated?.fps ?? compositionFps ?? null; 10579 validateFps(fps, calculated?.fps ? calculateMetadataErrorLocation : defaultErrorLocation, false); 10580 const durationInFrames = calculated?.durationInFrames ?? compositionDurationInFrames ?? null; 10581 validateDurationInFrames(durationInFrames, { 10582 allowFloats: false, 10583 component: `of the "<Composition />" component with the id "${compositionId}"` 10584 }); 10585 const defaultCodec = calculated?.defaultCodec; 10586 validateCodec(defaultCodec, calculateMetadataErrorLocation, "defaultCodec"); 10587 const defaultOutName = calculated?.defaultOutName; 10588 const defaultVideoImageFormat = calculated?.defaultVideoImageFormat; 10589 const defaultPixelFormat = calculated?.defaultPixelFormat; 10590 const defaultProResProfile = calculated?.defaultProResProfile; 10591 const defaultSampleRate = calculated?.defaultSampleRate; 10592 return { 10593 width, 10594 height, 10595 fps, 10596 durationInFrames, 10597 defaultCodec, 10598 defaultOutName, 10599 defaultVideoImageFormat, 10600 defaultPixelFormat, 10601 defaultProResProfile, 10602 defaultSampleRate 10603 }; 10604}; 10605var resolveVideoConfig = ({ calculateMetadata, signal, defaultProps, inputProps: originalProps, compositionId, compositionDurationInFrames, compositionFps, compositionHeight, compositionWidth })=>{ 10606 const calculatedProm = calculateMetadata ? calculateMetadata({ 10607 defaultProps, 10608 props: originalProps, 10609 abortSignal: signal, 10610 compositionId, 10611 isRendering: getRemotionEnvironment().isRendering 10612 }) : null; 10613 if (calculatedProm !== null && typeof calculatedProm === "object" && "then" in calculatedProm) { 10614 return calculatedProm.then((c2)=>{ 10615 const { height, width, durationInFrames, fps, defaultCodec, defaultOutName, defaultVideoImageFormat, defaultPixelFormat, defaultProResProfile, defaultSampleRate } = validateCalculated({ 10616 calculated: c2, 10617 compositionDurationInFrames, 10618 compositionFps, 10619 compositionHeight, 10620 compositionWidth, 10621 compositionId 10622 }); 10623 return { 10624 width, 10625 height, 10626 fps, 10627 durationInFrames, 10628 id: compositionId, 10629 defaultProps: serializeThenDeserializeInStudio(defaultProps), 10630 props: serializeThenDeserializeInStudio(c2.props ?? originalProps), 10631 defaultCodec: defaultCodec ?? null, 10632 defaultOutName: defaultOutName ?? null, 10633 defaultVideoImageFormat: defaultVideoImageFormat ?? null, 10634 defaultPixelFormat: defaultPixelFormat ?? null, 10635 defaultProResProfile: defaultProResProfile ?? null, 10636 defaultSampleRate: defaultSampleRate ?? null 10637 }; 10638 }); 10639 } 10640 const data = validateCalculated({ 10641 calculated: calculatedProm, 10642 compositionDurationInFrames, 10643 compositionFps, 10644 compositionHeight, 10645 compositionWidth, 10646 compositionId 10647 }); 10648 if (calculatedProm === null) { 10649 return { 10650 ...data, 10651 id: compositionId, 10652 defaultProps: serializeThenDeserializeInStudio(defaultProps ?? {}), 10653 props: serializeThenDeserializeInStudio(originalProps), 10654 defaultCodec: null, 10655 defaultOutName: null, 10656 defaultVideoImageFormat: null, 10657 defaultPixelFormat: null, 10658 defaultProResProfile: null, 10659 defaultSampleRate: null 10660 }; 10661 } 10662 return { 10663 ...data, 10664 id: compositionId, 10665 defaultProps: serializeThenDeserializeInStudio(defaultProps ?? {}), 10666 props: serializeThenDeserializeInStudio(calculatedProm.props ?? originalProps), 10667 defaultCodec: calculatedProm.defaultCodec ?? null, 10668 defaultOutName: calculatedProm.defaultOutName ?? null, 10669 defaultVideoImageFormat: calculatedProm.defaultVideoImageFormat ?? null, 10670 defaultPixelFormat: calculatedProm.defaultPixelFormat ?? null, 10671 defaultProResProfile: calculatedProm.defaultProResProfile ?? null, 10672 defaultSampleRate: calculatedProm.defaultSampleRate ?? null 10673 }; 10674}; 10675var resolveVideoConfigOrCatch = (params)=>{ 10676 try { 10677 const promiseOrReturnValue = resolveVideoConfig(params); 10678 return { 10679 type: "success", 10680 result: promiseOrReturnValue 10681 }; 10682 } catch (err) { 10683 return { 10684 type: "error", 10685 error: err 10686 }; 10687 } 10688};
10689// src/sequence-stack-traces.ts 10690 10691var SequenceStackTracesUpdateContext = /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createContext(()=>{});
vendor: 678 bytes, lines 10692-10720
10692// src/setup-env-variables.ts 10693var getEnvVariables = ()=>{ 10694 if (getRemotionEnvironment().isRendering) { 10695 const param = window.remotion_envVariables; 10696 if (!param) { 10697 return {}; 10698 } 10699 return { 10700 ...JSON.parse(param), 10701 NODE_ENV: "production" 10702 }; 10703 } 10704 if (false) {} 10705 return { 10706 NODE_ENV: "production" 10707 }; 10708}; 10709var setupEnvVariables = ()=>{ 10710 const env = getEnvVariables(); 10711 if (!window.process) { 10712 window.process = {}; 10713 } 10714 if (!window.process.env) { 10715 window.process.env = {}; 10716 } 10717 Object.keys(env).forEach((key)=>{ 10718 window.process.env[key] = env[key]; 10719 }); 10720};
10721// src/use-current-scale.ts 10722 10723var CurrentScaleContext = /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createContext(null); 10724var PreviewSizeContext = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({ 10725 setSize: ()=>{ 10726 return; 10727 }, 10728 size: { 10729 size: "auto", 10730 translation: { 10731 x: 0, 10732 y: 0 10733 } 10734 } 10735}); 10736var calculateScale = ({ canvasSize, compositionHeight, compositionWidth, previewSize })=>{ 10737 const heightRatio = canvasSize.height / compositionHeight; 10738 const widthRatio = canvasSize.width / compositionWidth; 10739 const ratio = Math.min(heightRatio, widthRatio); 10740 if (previewSize === "auto") { 10741 if (ratio === 0) { 10742 return 1; 10743 } 10744 return ratio; 10745 } 10746 return Number(previewSize); 10747}; 10748var useCurrentScale = (options)=>{ 10749 const hasContext = React34.useContext(CurrentScaleContext); 10750 const zoomContext = React34.useContext(PreviewSizeContext); 10751 const config = useUnsafeVideoConfig(); 10752 const env = useRemotionEnvironment(); 10753 if (hasContext === null || config === null || zoomContext === null) { 10754 if (options?.dontThrowIfOutsideOfRemotion) { 10755 return 1; 10756 } 10757 if (env.isRendering) { 10758 return 1; 10759 } 10760 throw new Error([ 10761 "useCurrentScale() was called outside of a Remotion context.", 10762 "This hook can only be called in a component that is being rendered by Remotion.", 10763 "If you want to this hook to return 1 outside of Remotion, pass {dontThrowIfOutsideOfRemotion: true} as an option.", 10764 "If you think you called this hook in a Remotion component, make sure all versions of Remotion are aligned." 10765 ].join(` 10766`)); 10767 } 10768 if (hasContext.type === "scale") { 10769 return hasContext.scale; 10770 } 10771 return calculateScale({ 10772 canvasSize: hasContext.canvasSize, 10773 compositionHeight: config.height, 10774 compositionWidth: config.width, 10775 previewSize: zoomContext.size.size 10776 }); 10777};
10778// src/use-pixel-density.ts 10779 10780var PixelDensityContext = /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createContext(null); 10781var getBrowserPixelDensity = ()=>{ 10782 if (typeof window === "undefined") { 10783 return 1; 10784 } 10785 return window.devicePixelRatio || 1; 10786}; 10787var usePixelDensity = (options)=>{ 10788 const pixelDensity = useContext35(PixelDensityContext); 10789 const canUseRemotionHooks = useContext35(CanUseRemotionHooks); 10790 if (pixelDensity !== null) { 10791 return pixelDensity; 10792 } 10793 if (canUseRemotionHooks || options?.dontThrowIfOutsideOfRemotion) { 10794 return getBrowserPixelDensity(); 10795 } 10796 throw new Error([ 10797 "usePixelDensity() was called outside of a Remotion context.", 10798 "This hook can only be called in a component that is being rendered by Remotion.", 10799 "If you want this hook to return the browser pixel density outside of Remotion, pass {dontThrowIfOutsideOfRemotion: true} as an option.", 10800 "If you think you called this hook in a Remotion component, make sure all versions of Remotion are aligned." 10801 ].join(` 10802`)); 10803};
10804// src/video/OffthreadVideo.tsx 10805
10806// src/video/OffthreadVideoForRendering.tsx 10807
10808// src/video/offthread-video-source.ts 10809var getOffthreadVideoSource = ({ src, transparent, currentTime, toneMapped })=>{ 10810 return `http://localhost:${window.remotion_proxyPort}/proxy?src=${encodeURIComponent(getAbsoluteSrc(src))}&time=${encodeURIComponent(Math.max(0, currentTime))}&transparent=${String(transparent)}&toneMapped=${String(toneMapped)}`; 10811};
10812// src/video/OffthreadVideoForRendering.tsx 10813 10814var OffthreadVideoForRendering = ({ onError, volume: volumeProp, playbackRate, src, muted, allowAmplificationDuringRender, transparent, toneMapped, toneFrequency, name, loopVolumeCurveBehavior, delayRenderRetries, delayRenderTimeoutInMilliseconds, onVideoFrame, crossOrigin, audioStreamIndex, preservePitch: _preservePitch, ...props2 })=>{ 10815 const absoluteFrame = useTimelinePosition(); 10816 const frame = useCurrentFrame(); 10817 const volumePropsFrame = useFrameForVolumeProp(loopVolumeCurveBehavior); 10818 const videoConfig = useUnsafeVideoConfig(); 10819 const sequenceContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SequenceContext); 10820 const mediaStartsAt = useMediaStartsAt(); 10821 const { registerRenderAsset, unregisterRenderAsset } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(RenderAssetManager); 10822 if (!src) { 10823 throw new TypeError("No `src` was passed to <OffthreadVideo>."); 10824 } 10825 const id = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>`offthreadvideo-${random(src)}-${sequenceContext?.cumulatedFrom}-${sequenceContext?.relativeFrom}-${sequenceContext?.durationInFrames}`, [ 10826 src, 10827 sequenceContext?.cumulatedFrom, 10828 sequenceContext?.relativeFrom, 10829 sequenceContext?.durationInFrames 10830 ]); 10831 if (!videoConfig) { 10832 throw new Error("No video config found"); 10833 } 10834 const volume = evaluateVolume({ 10835 volume: volumeProp, 10836 frame: volumePropsFrame, 10837 mediaVolume: 1 10838 }); 10839 warnAboutTooHighVolume(volume); 10840 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 10841 if (!src) { 10842 throw new Error("No src passed"); 10843 } 10844 if (!window.remotion_audioEnabled) { 10845 return; 10846 } 10847 if (muted) { 10848 return; 10849 } 10850 if (volume <= 0) { 10851 return; 10852 } 10853 registerRenderAsset({ 10854 type: "video", 10855 src: getAbsoluteSrc(src), 10856 id, 10857 frame: absoluteFrame, 10858 volume, 10859 mediaFrame: frame, 10860 playbackRate, 10861 toneFrequency, 10862 audioStartFrame: Math.max(0, -(sequenceContext?.cumulatedNegativeFrom ?? 0)), 10863 audioStreamIndex 10864 }); 10865 return ()=>unregisterRenderAsset(id); 10866 }, [ 10867 muted, 10868 src, 10869 registerRenderAsset, 10870 id, 10871 unregisterRenderAsset, 10872 volume, 10873 frame, 10874 absoluteFrame, 10875 playbackRate, 10876 toneFrequency, 10877 sequenceContext?.cumulatedNegativeFrom, 10878 audioStreamIndex 10879 ]); 10880 const currentTime = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 10881 return getExpectedMediaFrameUncorrected({ 10882 frame, 10883 playbackRate: playbackRate || 1, 10884 startFrom: -mediaStartsAt 10885 }) / videoConfig.fps; 10886 }, [ 10887 frame, 10888 mediaStartsAt, 10889 playbackRate, 10890 videoConfig.fps 10891 ]); 10892 const actualSrc = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 10893 return getOffthreadVideoSource({ 10894 src, 10895 currentTime, 10896 transparent, 10897 toneMapped 10898 }); 10899 }, [ 10900 toneMapped, 10901 currentTime, 10902 src, 10903 transparent 10904 ]); 10905 const [imageSrc, setImageSrc] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(null); 10906 const { delayRender: delayRender2, continueRender: continueRender2 } = useDelayRender(); 10907 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 10908 if (!window.remotion_videoEnabled) { 10909 return; 10910 } 10911 const cleanup = []; 10912 setImageSrc(null); 10913 const controller = new AbortController; 10914 const newHandle = delayRender2(`Fetching ${actualSrc} from server`, { 10915 retries: delayRenderRetries ?? undefined, 10916 timeoutInMilliseconds: delayRenderTimeoutInMilliseconds ?? undefined 10917 }); 10918 const execute = async ()=>{ 10919 try { 10920 const res = await fetch(actualSrc, { 10921 signal: controller.signal, 10922 cache: "no-store" 10923 }); 10924 if (res.status !== 200) { 10925 if (res.status === 500) { 10926 const json = await res.json(); 10927 if (json.error) { 10928 const cleanedUpErrorMessage = json.error.replace(/^Error: /, ""); 10929 throw new Error(cleanedUpErrorMessage); 10930 } 10931 } 10932 throw new Error(`Server returned status ${res.status} while fetching ${actualSrc}`); 10933 } 10934 const blob = await res.blob(); 10935 const url = URL.createObjectURL(blob); 10936 cleanup.push(()=>URL.revokeObjectURL(url)); 10937 setImageSrc({ 10938 src: url, 10939 handle: newHandle 10940 }); 10941 } catch (err) { 10942 if (err.message.includes("aborted")) { 10943 continueRender2(newHandle); 10944 return; 10945 } 10946 if (controller.signal.aborted) { 10947 continueRender2(newHandle); 10948 return; 10949 } 10950 if (err.message.includes("Failed to fetch")) { 10951 err = new Error(`Failed to fetch ${actualSrc}. This could be caused by Chrome rejecting the request because the disk space is low. Consider increasing the disk size of your environment.`, { 10952 cause: err 10953 }); 10954 } 10955 if (onError) { 10956 onError(err); 10957 } else { 10958 cancelRender(err); 10959 } 10960 } 10961 }; 10962 execute(); 10963 cleanup.push(()=>{ 10964 if (controller.signal.aborted) { 10965 return; 10966 } 10967 controller.abort(); 10968 }); 10969 return ()=>{ 10970 cleanup.forEach((c2)=>c2()); 10971 }; 10972 }, [ 10973 actualSrc, 10974 delayRenderRetries, 10975 delayRenderTimeoutInMilliseconds, 10976 onError, 10977 continueRender2, 10978 delayRender2 10979 ]); 10980 const onErr = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(()=>{ 10981 if (onError) { 10982 onError?.(new Error("Failed to load image with src " + imageSrc)); 10983 } else { 10984 cancelRender("Failed to load image with src " + imageSrc); 10985 } 10986 }, [ 10987 imageSrc, 10988 onError 10989 ]); 10990 const className = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 10991 return [ 10992 OBJECTFIT_CONTAIN_CLASS_NAME, 10993 props2.className 10994 ].filter(truthy).join(" "); 10995 }, [ 10996 props2.className 10997 ]); 10998 const onImageFrame = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((img)=>{ 10999 if (onVideoFrame) { 11000 onVideoFrame(img); 11001 } 11002 }, [ 11003 onVideoFrame 11004 ]); 11005 if (!imageSrc || !window.remotion_videoEnabled) { 11006 return null; 11007 } 11008 continueRender2(imageSrc.handle); 11009 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Img, { 11010 src: imageSrc.src, 11011 delayRenderRetries, 11012 delayRenderTimeoutInMilliseconds, 11013 onImageFrame, 11014 ...props2, 11015 onError: onErr, 11016 className 11017 }); 11018};
11019// src/video/VideoForPreview.tsx 11020
vendor: 922 bytes, lines 11021-11054
11021// src/video/emit-video-frame.ts 11022 11023var useEmitVideoFrame = ({ ref, onVideoFrame })=>{ 11024 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 11025 const { current } = ref; 11026 if (!current) { 11027 return; 11028 } 11029 if (!onVideoFrame) { 11030 return; 11031 } 11032 let handle = 0; 11033 const callback = (_now, metadata)=>{ 11034 if (!ref.current) { 11035 return; 11036 } 11037 onVideoFrame(ref.current, _now, metadata); 11038 handle = ref.current.requestVideoFrameCallback(callback); 11039 }; 11040 onVideoFrame(current); 11041 if (!current.requestVideoFrameCallback) { 11042 return; 11043 } 11044 handle = current.requestVideoFrameCallback(callback); 11045 return ()=>{ 11046 if (handle) { 11047 current.cancelVideoFrameCallback(handle); 11048 } 11049 }; 11050 }, [ 11051 onVideoFrame, 11052 ref 11053 ]); 11054};
11055// src/video/MediaPlaybackError.ts 11056class MediaPlaybackError extends Error { 11057 constructor({ message, src }){ 11058 super(message); 11059 this.name = "MediaPlaybackError"; 11060 this.src = src; 11061 } 11062}
11063// src/video/VideoForPreview.tsx 11064 11065var VideoForDevelopmentRefForwardingFunction = (props2, ref)=>{ 11066 const context = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SharedAudioContext); 11067 if (!context) { 11068 throw new Error("SharedAudioContext not found"); 11069 } 11070 const videoRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 11071 const sharedSource = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 11072 if (!context.audioContext) { 11073 return null; 11074 } 11075 return makeSharedElementSourceNode({ 11076 audioContext: context.audioContext, 11077 ref: videoRef 11078 }); 11079 }, [ 11080 context.audioContext 11081 ]); 11082 const effectToUse = react__WEBPACK_IMPORTED_MODULE_0__.useInsertionEffect ?? react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect; 11083 effectToUse(()=>{ 11084 return ()=>{ 11085 requestAnimationFrame(()=>{ 11086 sharedSource?.cleanup(); 11087 }); 11088 }; 11089 }, [ 11090 sharedSource 11091 ]); 11092 const { volume, muted, playbackRate, preservePitch, onlyWarnForMediaSeekingError, src, onDuration, acceptableTimeShift, acceptableTimeShiftInSeconds, toneFrequency, name, _remotionInternalNativeLoopPassed, _remotionInternalStack, style, pauseWhenBuffering, showInTimeline, loopVolumeCurveBehavior, onError, onAutoPlayError, onVideoFrame, crossOrigin, delayRenderRetries, delayRenderTimeoutInMilliseconds, allowAmplificationDuringRender, useWebAudioApi, audioStreamIndex, ...nativeProps } = props2; 11093 const _propsValid = true; 11094 if (!_propsValid) { 11095 throw new Error("typecheck error"); 11096 } 11097 const volumePropFrame = useFrameForVolumeProp(loopVolumeCurveBehavior ?? "repeat"); 11098 const { fps, durationInFrames } = useVideoConfig(); 11099 const parentSequence = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SequenceContext); 11100 const logLevel = useLogLevel(); 11101 const mountTime = useMountTime(); 11102 const [timelineId] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(()=>String(Math.random())); 11103 if (typeof acceptableTimeShift !== "undefined") { 11104 throw new Error("acceptableTimeShift has been removed. Use acceptableTimeShiftInSeconds instead."); 11105 } 11106 const [mediaVolume] = useMediaVolumeState(); 11107 const [playerMuted] = usePlayerMutedState(); 11108 const userPreferredVolume = evaluateVolume({ 11109 frame: volumePropFrame, 11110 volume, 11111 mediaVolume 11112 }); 11113 warnAboutTooHighVolume(userPreferredVolume); 11114 const getStack = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(()=>{ 11115 return _remotionInternalStack ?? null; 11116 }, [ 11117 _remotionInternalStack 11118 ]); 11119 useMediaInTimeline({ 11120 volume, 11121 mediaVolume, 11122 mediaType: "video", 11123 src, 11124 playbackRate: props2.playbackRate ?? 1, 11125 displayName: name ?? null, 11126 id: timelineId, 11127 getStack, 11128 showInTimeline, 11129 premountDisplay: parentSequence?.premountDisplay ?? null, 11130 postmountDisplay: parentSequence?.postmountDisplay ?? null, 11131 loopDisplay: undefined, 11132 documentationLink: onlyWarnForMediaSeekingError ? "https://www.remotion.dev/docs/offthreadvideo" : "https://www.remotion.dev/docs/html5-video", 11133 refForOutline: videoRef 11134 }); 11135 useMediaPlayback({ 11136 mediaRef: videoRef, 11137 src, 11138 mediaType: "video", 11139 playbackRate: props2.playbackRate ?? 1, 11140 preservePitch, 11141 onlyWarnForMediaSeekingError, 11142 acceptableTimeshift: acceptableTimeShiftInSeconds ?? null, 11143 isPremounting: Boolean(parentSequence?.premounting), 11144 isPostmounting: Boolean(parentSequence?.postmounting), 11145 pauseWhenBuffering, 11146 onAutoPlayError: onAutoPlayError ?? null 11147 }); 11148 useMediaTag({ 11149 id: timelineId, 11150 isPostmounting: Boolean(parentSequence?.postmounting), 11151 isPremounting: Boolean(parentSequence?.premounting), 11152 mediaRef: videoRef, 11153 mediaType: "video", 11154 onAutoPlayError: onAutoPlayError ?? null 11155 }); 11156 useVolume({ 11157 logLevel, 11158 mediaRef: videoRef, 11159 volume: userPreferredVolume, 11160 source: sharedSource, 11161 shouldUseWebAudioApi: useWebAudioApi ?? false 11162 }); 11163 const actualFrom = parentSequence ? parentSequence.relativeFrom : 0; 11164 const duration = parentSequence ? Math.min(parentSequence.durationInFrames, durationInFrames) : durationInFrames; 11165 const preloadedSrc = usePreload(src); 11166 const actualSrc = useAppendVideoFragment({ 11167 actualSrc: preloadedSrc, 11168 actualFrom, 11169 duration, 11170 fps 11171 }); 11172 (0,react__WEBPACK_IMPORTED_MODULE_0__.useImperativeHandle)(ref, ()=>{ 11173 return videoRef.current; 11174 }, []); 11175 (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(()=>playbackLogging({ 11176 logLevel, 11177 message: `Mounting video with source = ${actualSrc}, v=${VERSION}, user agent=${typeof navigator === "undefined" ? "server" : navigator.userAgent}`, 11178 tag: "video", 11179 mountTime 11180 })); 11181 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 11182 const { current } = videoRef; 11183 if (!current) { 11184 return; 11185 } 11186 const errorHandler = ()=>{ 11187 if (current.error) { 11188 console.error("Error occurred in video", current?.error); 11189 if (onError) { 11190 const err = new MediaPlaybackError({ 11191 message: `Code ${current.error.code}: ${current.error.message}`, 11192 src 11193 }); 11194 onError(err); 11195 return; 11196 } 11197 throw new MediaPlaybackError({ 11198 message: `The browser threw an error while playing the video ${src}: Code ${current.error.code} - ${current?.error?.message}. See https://remotion.dev/docs/media-playback-error for help. Pass an onError() prop to handle the error.`, 11199 src 11200 }); 11201 } else { 11202 if (onError) { 11203 const err = new MediaPlaybackError({ 11204 message: `The browser threw an error while playing the video ${src}`, 11205 src 11206 }); 11207 onError(err); 11208 return; 11209 } 11210 throw new MediaPlaybackError({ 11211 message: "The browser threw an error while playing the video", 11212 src 11213 }); 11214 } 11215 }; 11216 current.addEventListener("error", errorHandler, { 11217 once: true 11218 }); 11219 return ()=>{ 11220 current.removeEventListener("error", errorHandler); 11221 }; 11222 }, [ 11223 onError, 11224 src 11225 ]); 11226 const currentOnDurationCallback = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(onDuration); 11227 currentOnDurationCallback.current = onDuration; 11228 useEmitVideoFrame({ 11229 ref: videoRef, 11230 onVideoFrame 11231 }); 11232 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 11233 const { current } = videoRef; 11234 if (!current) { 11235 return; 11236 } 11237 if (current.duration) { 11238 currentOnDurationCallback.current?.(src, current.duration); 11239 return; 11240 } 11241 const onLoadedMetadata = ()=>{ 11242 currentOnDurationCallback.current?.(src, current.duration); 11243 }; 11244 current.addEventListener("loadedmetadata", onLoadedMetadata); 11245 return ()=>{ 11246 current.removeEventListener("loadedmetadata", onLoadedMetadata); 11247 }; 11248 }, [ 11249 src 11250 ]); 11251 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 11252 const { current } = videoRef; 11253 if (!current) { 11254 return; 11255 } 11256 if (isIosSafari()) { 11257 current.preload = "metadata"; 11258 } else { 11259 current.preload = "auto"; 11260 } 11261 }, []); 11262 const actualStyle = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 11263 return { 11264 ...style 11265 }; 11266 }, [ 11267 style 11268 ]); 11269 const crossOriginValue = getCrossOriginValue({ 11270 crossOrigin, 11271 requestsVideoFrame: Boolean(onVideoFrame), 11272 isClientSideRendering: false 11273 }); 11274 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)("video", { 11275 ...nativeProps, 11276 ref: videoRef, 11277 muted: muted || playerMuted || userPreferredVolume <= 0,
11278 playsInline: true, 11279 src: actualSrc, 11280 loop: _remotionInternalNativeLoopPassed, 11281 style: actualStyle, 11282 disableRemotePlayback: true, 11283 crossOrigin: crossOriginValue, 11284 controls: false 11285 }); 11286}; 11287var VideoForPreview = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(VideoForDevelopmentRefForwardingFunction);
11288// src/video/OffthreadVideo.tsx 11289 11290var InnerOffthreadVideo = (props2)=>{ 11291 const { startFrom, endAt, trimBefore, trimAfter, name, pauseWhenBuffering, stack, showInTimeline, ...otherProps } = props2; 11292 const environment = useRemotionEnvironment(); 11293 if (environment.isClientSideRendering) { 11294 throw new Error("<OffthreadVideo> is not supported in @remotion/web-renderer. Use <Video> from @remotion/media instead. See https://remotion.dev/docs/client-side-rendering/limitations"); 11295 } 11296 const onDuration = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)(()=>{ 11297 return; 11298 }, []); 11299 if (typeof props2.src !== "string") { 11300 throw new TypeError(`The \`<OffthreadVideo>\` tag requires a string for \`src\`, but got ${JSON.stringify(props2.src)} instead.`); 11301 } 11302 validateMediaTrimProps({ 11303 startFrom, 11304 endAt, 11305 trimBefore, 11306 trimAfter 11307 }); 11308 const { trimBeforeValue, trimAfterValue } = resolveTrimProps({ 11309 startFrom, 11310 endAt, 11311 trimBefore, 11312 trimAfter 11313 }); 11314 if (typeof trimBeforeValue !== "undefined" || typeof trimAfterValue !== "undefined") { 11315 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Sequence, { 11316 layout: "none", 11317 from: 0 - (trimBeforeValue ?? 0), 11318 showInTimeline: false, 11319 durationInFrames: trimAfterValue, 11320 name, 11321 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(InnerOffthreadVideo, { 11322 pauseWhenBuffering: pauseWhenBuffering ?? false, 11323 ...otherProps, 11324 trimAfter: undefined, 11325 name: undefined, 11326 showInTimeline, 11327 trimBefore: undefined, 11328 stack: undefined, 11329 startFrom: undefined, 11330 endAt: undefined 11331 }) 11332 }); 11333 } 11334 validateMediaProps(props2, "Video"); 11335 if (environment.isRendering) { 11336 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(OffthreadVideoForRendering, { 11337 pauseWhenBuffering: pauseWhenBuffering ?? false, 11338 ...otherProps, 11339 trimAfter: undefined, 11340 name: undefined, 11341 showInTimeline, 11342 trimBefore: undefined, 11343 stack: undefined, 11344 startFrom: undefined, 11345 endAt: undefined 11346 }); 11347 } 11348 const { transparent, toneMapped, onAutoPlayError, onVideoFrame, crossOrigin, delayRenderRetries, delayRenderTimeoutInMilliseconds, ...propsForPreview } = otherProps; 11349 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(VideoForPreview, { 11350 _remotionInternalStack: stack ?? null, 11351 onDuration, 11352 onlyWarnForMediaSeekingError: true, 11353 pauseWhenBuffering: pauseWhenBuffering ?? false, 11354 showInTimeline: showInTimeline ?? true, 11355 onAutoPlayError: onAutoPlayError ?? undefined, 11356 onVideoFrame: onVideoFrame ?? null, 11357 crossOrigin, 11358 ...propsForPreview, 11359 _remotionInternalNativeLoopPassed: false 11360 }); 11361}; 11362var OffthreadVideo = ({ src, acceptableTimeShiftInSeconds, allowAmplificationDuringRender, audioStreamIndex, crossOrigin, delayRenderRetries, delayRenderTimeoutInMilliseconds, loopVolumeCurveBehavior, muted, name, onAutoPlayError, onError, onVideoFrame, pauseWhenBuffering, playbackRate, preservePitch, showInTimeline, style, toneFrequency, toneMapped, transparent, trimAfter, trimBefore, useWebAudioApi, volume, _remotionInternalNativeLoopPassed, endAt, stack, startFrom, imageFormat, ...props2 })=>{ 11363 if (imageFormat) { 11364 throw new TypeError(`The \`<OffthreadVideo>\` tag does no longer accept \`imageFormat\`. Use the \`transparent\` prop if you want to render a transparent video.`); 11365 } 11366 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(InnerOffthreadVideo, { 11367 acceptableTimeShiftInSeconds, 11368 allowAmplificationDuringRender: allowAmplificationDuringRender ?? true, 11369 audioStreamIndex: audioStreamIndex ?? 0, 11370 crossOrigin, 11371 delayRenderRetries, 11372 delayRenderTimeoutInMilliseconds, 11373 loopVolumeCurveBehavior: loopVolumeCurveBehavior ?? "repeat", 11374 muted: muted ?? false, 11375 name, 11376 onAutoPlayError: onAutoPlayError ?? null, 11377 onError, 11378 onVideoFrame, 11379 pauseWhenBuffering: pauseWhenBuffering ?? true, 11380 playbackRate: playbackRate ?? 1, 11381 preservePitch, 11382 toneFrequency: toneFrequency ?? 1, 11383 showInTimeline: showInTimeline ?? true, 11384 src, 11385 stack, 11386 startFrom, 11387 _remotionInternalNativeLoopPassed: _remotionInternalNativeLoopPassed ?? false, 11388 endAt, 11389 style, 11390 toneMapped: toneMapped ?? true, 11391 transparent: transparent ?? false, 11392 trimAfter, 11393 trimBefore, 11394 useWebAudioApi: useWebAudioApi ?? false, 11395 volume, 11396 ...props2 11397 }); 11398}; 11399addSequenceStackTraces(OffthreadVideo);
vendor: 1,672 bytes, lines 11400-11439
11400// src/watch-static-file.ts 11401var WATCH_REMOTION_STATIC_FILES = "remotion_staticFilesChanged"; 11402var watchStaticFile = (fileName, callback)=>{ 11403 if (ENABLE_V5_BREAKING_CHANGES) { 11404 throw new Error("watchStaticFile() has moved into the `@remotion/studio` package. Update your imports."); 11405 } 11406 if (!getRemotionEnvironment().isStudio) { 11407 console.warn("The watchStaticFile() API is only available while using the Remotion Studio."); 11408 return { 11409 cancel: ()=>{ 11410 return; 11411 } 11412 }; 11413 } 11414 const withoutStaticBase = fileName.startsWith(window.remotion_staticBase) ? fileName.replace(window.remotion_staticBase, "") : fileName; 11415 const withoutLeadingSlash = withoutStaticBase.startsWith("/") ? withoutStaticBase.slice(1) : withoutStaticBase; 11416 let prevFileData = window.remotion_staticFiles.find((file)=>file.name === withoutLeadingSlash); 11417 const checkFile = (event)=>{ 11418 const staticFiles = event.detail.files; 11419 const newFileData = staticFiles.find((file)=>file.name === withoutLeadingSlash); 11420 if (!newFileData) { 11421 if (prevFileData !== undefined) { 11422 callback(null); 11423 } 11424 prevFileData = undefined; 11425 return; 11426 } 11427 if (prevFileData === undefined || prevFileData.lastModified !== newFileData.lastModified) { 11428 callback(newFileData); 11429 prevFileData = newFileData; 11430 } 11431 }; 11432 window.addEventListener(WATCH_REMOTION_STATIC_FILES, checkFile); 11433 const cancel = ()=>{ 11434 return window.removeEventListener(WATCH_REMOTION_STATIC_FILES, checkFile); 11435 }; 11436 return { 11437 cancel 11438 }; 11439};
11440// src/wrap-remotion-context.tsx 11441 11442 11443function useRemotionContexts() { 11444 const compositionManagerCtx = react__WEBPACK_IMPORTED_MODULE_0__.useContext(CompositionManager); 11445 const timelineContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(TimelineContext); 11446 const setTimelineContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(SetTimelineContext); 11447 const sequenceContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(SequenceContext); 11448 const nonceContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(NonceContext); 11449 const canUseRemotionHooksContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(CanUseRemotionHooks); 11450 const preloadContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(PreloadContext); 11451 const resolveCompositionContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(ResolveCompositionContext); 11452 const renderAssetManagerContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(RenderAssetManager); 11453 const sequenceManagerContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(SequenceManager); 11454 const sequenceManagerRefContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(SequenceManagerRefContext); 11455 const visualModePropStatusesRefContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(VisualModePropStatusesRefContext); 11456 const bufferManagerContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(BufferingContextReact); 11457 const logLevelContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(LogLevelContext); 11458 return (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>({ 11459 compositionManagerCtx, 11460 timelineContext, 11461 setTimelineContext, 11462 sequenceContext, 11463 nonceContext, 11464 canUseRemotionHooksContext, 11465 preloadContext, 11466 resolveCompositionContext, 11467 renderAssetManagerContext, 11468 sequenceManagerContext, 11469 sequenceManagerRefContext, 11470 visualModePropStatusesRefContext, 11471 bufferManagerContext, 11472 logLevelContext 11473 }), [ 11474 compositionManagerCtx, 11475 nonceContext, 11476 sequenceContext, 11477 setTimelineContext, 11478 timelineContext, 11479 canUseRemotionHooksContext, 11480 preloadContext, 11481 resolveCompositionContext, 11482 renderAssetManagerContext, 11483 sequenceManagerContext, 11484 sequenceManagerRefContext, 11485 visualModePropStatusesRefContext, 11486 bufferManagerContext, 11487 logLevelContext 11488 ]); 11489} 11490var RemotionContextProvider = (props2)=>{ 11491 const { children, contexts } = props2; 11492 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(LogLevelContext.Provider, { 11493 value: contexts.logLevelContext, 11494 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(CanUseRemotionHooks.Provider, { 11495 value: contexts.canUseRemotionHooksContext, 11496 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(NonceContext.Provider, { 11497 value: contexts.nonceContext, 11498 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(PreloadContext.Provider, { 11499 value: contexts.preloadContext, 11500 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(CompositionManager.Provider, { 11501 value: contexts.compositionManagerCtx, 11502 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(SequenceManagerRefContext.Provider, { 11503 value: contexts.sequenceManagerRefContext, 11504 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(SequenceManager.Provider, { 11505 value: contexts.sequenceManagerContext, 11506 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(VisualModePropStatusesRefContext.Provider, { 11507 value: contexts.visualModePropStatusesRefContext, 11508 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(RenderAssetManager.Provider, { 11509 value: contexts.renderAssetManagerContext, 11510 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(ResolveCompositionContext.Provider, { 11511 value: contexts.resolveCompositionContext, 11512 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(TimelineContext.Provider, { 11513 value: contexts.timelineContext, 11514 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(SetTimelineContext.Provider, { 11515 value: contexts.setTimelineContext, 11516 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(SequenceContext.Provider, { 11517 value: contexts.sequenceContext, 11518 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(BufferingContextReact.Provider, { 11519 value: contexts.bufferManagerContext, 11520 children 11521 }) 11522 }) 11523 }) 11524 }) 11525 }) 11526 }) 11527 }) 11528 }) 11529 }) 11530 }) 11531 }) 11532 }) 11533 }) 11534 }); 11535};
11536// src/internals.ts 11537var compositionSelectorRef = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.createRef)(); 11538var Internals = { 11539 MaxMediaCacheSizeContext, 11540 useUnsafeVideoConfig, 11541 useFrameForVolumeProp, 11542 useTimelinePosition, 11543 useAbsoluteTimelinePosition, 11544 evaluateVolume, 11545 getAbsoluteSrc, 11546 getAssetDisplayName, 11547 Timeline: exports_timeline_position_state, 11548 validateMediaTrimProps, 11549 validateMediaProps, 11550 resolveTrimProps, 11551 VideoForPreview, 11552 CompositionManager, 11553 CompositionSetters, 11554 VisualModePropStatusesContext, 11555 VisualModePropStatusesRefContext, 11556 VisualModeDragOverridesContext, 11557 VisualModeSettersContext, 11558 SequenceManager, 11559 SequenceManagerRefContext, 11560 SequenceStackTracesUpdateContext, 11561 baseSchema, 11562 sequenceSchema, 11563 SequenceWithoutSchema, 11564 sequenceStyleSchema, 11565 sequenceVisualStyleSchema, 11566 sequencePremountSchema, 11567 textSchema, 11568 transformSchema, 11569 premountSchema, 11570 flattenActiveSchema, 11571 getFlatSchemaWithAllKeys, 11572 RemotionRootContexts, 11573 CompositionManagerProvider, 11574 useVideo, 11575 getRoot, 11576 useMediaVolumeState, 11577 usePlayerMutedState, 11578 useMediaInTimeline, 11579 useLazyComponent, 11580 truthy, 11581 SequenceContext, 11582 PremountContext, 11583 useRemotionContexts, 11584 RemotionContextProvider, 11585 CSSUtils: exports_default_css, 11586 setupEnvVariables, 11587 MediaVolumeContext, 11588 SetMediaVolumeContext, 11589 getRemotionEnvironment, 11590 SharedAudioContext, 11591 SharedAudioContextProvider, 11592 SharedAudioTagsContext, 11593 SharedAudioTagsContextProvider, 11594 invalidCompositionErrorMessage, 11595 invalidFolderNameErrorMessage, 11596 calculateMediaDuration, 11597 isCompositionIdValid, 11598 isFolderNameValid, 11599 getPreviewDomElement, 11600 compositionsRef, 11601 portalNode, 11602 waitForRoot, 11603 SetTimelineContext, 11604 CanUseRemotionHooksProvider, 11605 CanUseRemotionHooks, 11606 PrefetchProvider, 11607 DurationsContextProvider, 11608 IsPlayerContextProvider, 11609 useIsPlayer, 11610 EditorPropsProvider, 11611 EditorPropsContext, 11612 usePreload, 11613 NonceContext, 11614 resolveVideoConfig, 11615 resolveVideoConfigOrCatch, 11616 ResolveCompositionContext, 11617 useResolvedVideoConfig, 11618 resolveCompositionsRef, 11619 REMOTION_STUDIO_CONTAINER_ELEMENT, 11620 RenderAssetManager, 11621 persistCurrentFrame, 11622 usePlaybackRate, 11623 useTimelineContext, 11624 useTimelineSetFrame, 11625 isIosSafari, 11626 WATCH_REMOTION_STATIC_FILES, 11627 addSequenceStackTraces, 11628 useMediaStartsAt, 11629 BufferingProvider, 11630 BufferingContextReact, 11631 getComponentsToAddStacksTo, 11632 CurrentScaleContext, 11633 PixelDensityContext, 11634 PreviewSizeContext, 11635 calculateScale, 11636 validateRenderAsset, 11637 Log, 11638 LogLevelContext,
11639 useLogLevel, 11640 playbackLogging, 11641 timeValueRef, 11642 compositionSelectorRef, 11643 RemotionEnvironmentContext, 11644 warnAboutTooHighVolume, 11645 AudioForPreview, 11646 OBJECTFIT_CONTAIN_CLASS_NAME, 11647 InnerOffthreadVideo, 11648 useBasicMediaInTimeline, 11649 getInputPropsOverride, 11650 setInputPropsOverride, 11651 useVideoEnabled, 11652 useAudioEnabled, 11653 useIsPlayerBuffering, 11654 TimelinePosition: exports_timeline_position_state, 11655 DelayRenderContextType, 11656 TimelineContext, 11657 PlaybackRateContext, 11658 AbsoluteTimeContext, 11659 RenderAssetManagerProvider, 11660 getEffectiveVisualModeValue, 11661 CompositionRenderErrorContext, 11662 useEffectChainState, 11663 createEffectChainState, 11664 cleanupEffectChainState, 11665 runEffectChain, 11666 useMemoizedEffects, 11667 useMemoizedEffectDefinitions, 11668 createEffect, 11669 createWebGLContextError, 11670 createWebGL2ContextError, 11671 computeEffectiveSchemaValuesDotNotation, 11672 interpolateKeyframedStatus, 11673 makeStaticDragOverride, 11674 makeKeyframedDragOverride, 11675 resolveDragOverrideValue, 11676 getStaticDragOverrideValue, 11677 OverrideIdsToNodePathsGettersContext, 11678 OverrideIdsToNodePathsSettersContext, 11679 findPropsToDelete, 11680 makeSequencePropsSubscriptionKey, 11681 getPropStatusesCtx, 11682 getEffectPropStatusesCtx, 11683 hiddenField, 11684 durationInFramesField, 11685 freezeField, 11686 fromField 11687};
11688// src/series/index.tsx 11689
11690// src/series/flatten-children.tsx 11691 11692var flattenChildren = (children)=>{ 11693 const childrenArray = react__WEBPACK_IMPORTED_MODULE_0__.Children.toArray(children); 11694 return childrenArray.reduce((flatChildren, child)=>{ 11695 if (child.type === react__WEBPACK_IMPORTED_MODULE_0__.Fragment) { 11696 return flatChildren.concat(flattenChildren(child.props.children)); 11697 } 11698 flatChildren.push(child); 11699 return flatChildren; 11700 }, []); 11701};
11702// src/series/index.tsx 11703 11704var SeriesSequenceRefForwardingFunction = ({ children }, _ref)=>{ 11705 useRequireToBeInsideSeries(); 11706 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(IsNotInsideSeriesProvider, { 11707 children 11708 }); 11709}; 11710var SeriesSequence = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SeriesSequenceRefForwardingFunction); 11711var SequenceWithoutSchemaWithRef = SequenceWithoutSchema; 11712var SeriesInner = (props2)=>{ 11713 const childrenValue = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>{ 11714 let startFrame = 0; 11715 const flattenedChildren = flattenChildren(props2.children); 11716 return react__WEBPACK_IMPORTED_MODULE_0__.Children.map(flattenedChildren, (child, i)=>{ 11717 const castedChild = child; 11718 if (typeof castedChild === "string") { 11719 if (castedChild.trim() === "") { 11720 return null; 11721 } 11722 throw new TypeError(`The <Series /> component only accepts a list of <Series.Sequence /> components as its children, but you passed a string "${castedChild}"`); 11723 } 11724 if (castedChild.type !== SeriesSequence) { 11725 throw new TypeError(`The <Series /> component only accepts a list of <Series.Sequence /> components as its children, but got ${castedChild} instead`); 11726 } 11727 const debugInfo = `index = ${i}, duration = ${castedChild.props.durationInFrames}`; 11728 const durationInFramesProp = castedChild.props.durationInFrames; 11729 const { durationInFrames, children: _children, from, name, ...passedProps } = castedChild.props; 11730 if (i !== flattenedChildren.length - 1 || durationInFramesProp !== Infinity) { 11731 validateDurationInFrames(durationInFramesProp, { 11732 component: `of a <Series.Sequence /> component`, 11733 allowFloats: true 11734 }); 11735 } 11736 const offset = castedChild.props.offset ?? 0; 11737 if (Number.isNaN(offset)) { 11738 throw new TypeError(`The "offset" property of a <Series.Sequence /> must not be NaN, but got NaN (${debugInfo}).`); 11739 } 11740 if (!Number.isFinite(offset)) { 11741 throw new TypeError(`The "offset" property of a <Series.Sequence /> must be finite, but got ${offset} (${debugInfo}).`); 11742 } 11743 if (offset % 1 !== 0) { 11744 throw new TypeError(`The "offset" property of a <Series.Sequence /> must be finite, but got ${offset} (${debugInfo}).`); 11745 } 11746 const currentStartFrame = startFrame + offset; 11747 startFrame += durationInFramesProp + offset; 11748 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(SequenceWithoutSchemaWithRef, { 11749 ref: castedChild.ref, 11750 name: name || "<Series.Sequence>", 11751 _remotionInternalDocumentationLink: name ? undefined : "https://www.remotion.dev/docs/series", 11752 from: currentStartFrame, 11753 durationInFrames: durationInFramesProp, 11754 ...passedProps, 11755 children: child 11756 }); 11757 }); 11758 }, [ 11759 props2.children 11760 ]); 11761 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(IsInsideSeriesContainer, { 11762 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Sequence, { 11763 layout: "none", 11764 name: "<Series>", 11765 _remotionInternalDocumentationLink: "https://www.remotion.dev/docs/series", 11766 ...props2, 11767 children: childrenValue 11768 }) 11769 }); 11770}; 11771var Series = Object.assign(withInteractivitySchema({ 11772 Component: SeriesInner, 11773 componentName: "<Series>", 11774 componentIdentity: "dev.remotion.remotion.Series", 11775 schema: sequenceSchemaDefaultLayoutNone, 11776 supportsEffects: false 11777}), { 11778 Sequence: SeriesSequence 11779}); 11780addSequenceStackTraces(Series);
vendor: 3,630 bytes, lines 11781-11874
11781// src/static-file.ts 11782var problematicCharacters = { 11783 "%3A": ":", 11784 "%2F": "/", 11785 "%3F": "?", 11786 "%23": "#", 11787 "%5B": "[", 11788 "%5D": "]", 11789 "%40": "@", 11790 "%21": "!", 11791 "%24": "$", 11792 "%26": "&", 11793 "%27": "'", 11794 "%28": "(", 11795 "%29": ")", 11796 "%2A": "*", 11797 "%2B": "+", 11798 "%2C": ",", 11799 "%3B": ";" 11800}; 11801var didWarn2 = {}; 11802var warnOnce3 = (message)=>{ 11803 if (didWarn2[message]) { 11804 return; 11805 } 11806 console.warn(message); 11807 didWarn2[message] = true; 11808}; 11809var includesHexOfUnsafeChar = (path)=>{ 11810 for (const key of Object.keys(problematicCharacters)){ 11811 if (path.includes(key)) { 11812 return { 11813 containsHex: true, 11814 hexCode: key 11815 }; 11816 } 11817 } 11818 return { 11819 containsHex: false 11820 }; 11821}; 11822var trimLeadingSlash = (path)=>{ 11823 if (path.startsWith("/")) { 11824 return trimLeadingSlash(path.substring(1)); 11825 } 11826 return path; 11827}; 11828var inner = (path)=>{ 11829 if (typeof window !== "undefined" && window.remotion_staticBase) { 11830 if (path.startsWith(window.remotion_staticBase)) { 11831 throw new Error(`The value "${path}" is already prefixed with the static base ${window.remotion_staticBase}. You don't need to call staticFile() on it.`); 11832 } 11833 return `${window.remotion_staticBase}/${trimLeadingSlash(path)}`; 11834 } 11835 return `/${trimLeadingSlash(path)}`; 11836}; 11837var encodeBySplitting = (path)=>{ 11838 const splitBySlash = path.split("/"); 11839 const encodedArray = splitBySlash.map((element)=>{ 11840 return encodeURIComponent(element); 11841 }); 11842 const merged = encodedArray.join("/"); 11843 return merged; 11844}; 11845var staticFile = (path)=>{ 11846 if (path === null) { 11847 throw new TypeError("null was passed to staticFile()"); 11848 } 11849 if (typeof path === "undefined") { 11850 throw new TypeError("undefined was passed to staticFile()"); 11851 } 11852 if (path.startsWith("http://") || path.startsWith("https://")) { 11853 throw new TypeError(`staticFile() does not support remote URLs - got "${path}". Instead, pass the URL without wrapping it in staticFile(). See: https://remotion.dev/docs/staticfile-remote-urls`); 11854 } 11855 if (path.startsWith("..") || path.startsWith("./")) { 11856 throw new TypeError(`staticFile() does not support relative paths - got "${path}". Instead, pass the name of a file that is inside the public/ folder. See: https://remotion.dev/docs/staticfile-relative-paths`); 11857 } 11858 if (path.startsWith("/Users") || path.startsWith("/home") || path.startsWith("/tmp") || path.startsWith("/etc") || path.startsWith("/opt") || path.startsWith("/var") || path.startsWith("C:") || path.startsWith("D:") || path.startsWith("E:")) { 11859 throw new TypeError(`staticFile() does not support absolute paths - got "${path}". Instead, pass the name of a file that is inside the public/ folder. See: https://remotion.dev/docs/staticfile-relative-paths`); 11860 } 11861 if (path.startsWith("public/")) { 11862 throw new TypeError(`Do not include the public/ prefix when using staticFile() - got "${path}". See: https://remotion.dev/docs/staticfile-relative-paths`); 11863 } 11864 const includesHex = includesHexOfUnsafeChar(path); 11865 if (includesHex.containsHex) { 11866 warnOnce3(`WARNING: You seem to pass an already encoded path (path contains ${includesHex.hexCode}). Since Remotion 4.0, the encoding is done by staticFile() itself. You may want to remove a encodeURIComponent() wrapping.`); 11867 } 11868 const preprocessed = encodeBySplitting(path); 11869 const preparsed = inner(preprocessed); 11870 if (!preparsed.startsWith("/")) { 11871 return `/${preparsed}`; 11872 } 11873 return preparsed; 11874};
11875// src/Still.tsx 11876 11877var Still = (props2)=>{ 11878 const newProps = { 11879 ...props2, 11880 durationInFrames: 1, 11881 fps: 1 11882 }; 11883 return /*#__PURE__*/ react__WEBPACK_IMPORTED_MODULE_0__.createElement(Composition, newProps); 11884}; 11885addSequenceStackTraces(Still);
11886// src/video/html5-video.tsx 11887
11888// src/video/VideoForRendering.tsx 11889
vendor: 3,557 bytes, lines 11890-12004
11890// src/video/seek-until-right.ts 11891var roundTo6Commas = (num)=>{ 11892 return Math.round(num * 1e5) / 1e5; 11893}; 11894var seekToTime = ({ element, desiredTime, logLevel, mountTime })=>{ 11895 if (isApproximatelyTheSame(element.currentTime, desiredTime)) { 11896 return { 11897 wait: Promise.resolve(desiredTime), 11898 cancel: ()=>{} 11899 }; 11900 } 11901 seek({ 11902 logLevel, 11903 mediaRef: element, 11904 time: desiredTime, 11905 why: "Seeking during rendering", 11906 mountTime 11907 }); 11908 let cancel; 11909 let cancelSeeked = null; 11910 const prom = new Promise((resolve)=>{ 11911 cancel = element.requestVideoFrameCallback((now, metadata)=>{ 11912 const displayIn = metadata.expectedDisplayTime - now; 11913 if (displayIn <= 0) { 11914 resolve(metadata.mediaTime); 11915 return; 11916 } 11917 setTimeout(()=>{ 11918 resolve(metadata.mediaTime); 11919 }, displayIn + 150); 11920 }); 11921 }); 11922 const waitForSeekedEvent = new Promise((resolve)=>{ 11923 const onDone = ()=>{ 11924 resolve(); 11925 }; 11926 element.addEventListener("seeked", onDone, { 11927 once: true 11928 }); 11929 cancelSeeked = ()=>{ 11930 element.removeEventListener("seeked", onDone); 11931 }; 11932 }); 11933 return { 11934 wait: Promise.all([ 11935 prom, 11936 waitForSeekedEvent 11937 ]).then(([time])=>time), 11938 cancel: ()=>{ 11939 cancelSeeked?.(); 11940 element.cancelVideoFrameCallback(cancel); 11941 } 11942 }; 11943}; 11944var seekToTimeMultipleUntilRight = ({ element, desiredTime, fps, logLevel, mountTime })=>{ 11945 const threshold = 1 / fps / 2; 11946 let currentCancel = ()=>{ 11947 return; 11948 }; 11949 if (Number.isFinite(element.duration) && element.currentTime >= element.duration && desiredTime >= element.duration) { 11950 return { 11951 prom: Promise.resolve(), 11952 cancel: ()=>{} 11953 }; 11954 } 11955 const prom = new Promise((resolve, reject)=>{ 11956 const firstSeek = seekToTime({ 11957 element, 11958 desiredTime: desiredTime + threshold, 11959 logLevel, 11960 mountTime 11961 }); 11962 firstSeek.wait.then((seekedTo)=>{ 11963 const difference = Math.abs(desiredTime - seekedTo); 11964 if (difference <= threshold) { 11965 return resolve(); 11966 } 11967 const sign = desiredTime > seekedTo ? 1 : -1; 11968 const newSeek = seekToTime({ 11969 element, 11970 desiredTime: seekedTo + threshold * sign, 11971 logLevel, 11972 mountTime 11973 }); 11974 currentCancel = newSeek.cancel; 11975 newSeek.wait.then((newTime)=>{ 11976 const newDifference = Math.abs(desiredTime - newTime); 11977 if (roundTo6Commas(newDifference) <= roundTo6Commas(threshold)) { 11978 return resolve(); 11979 } 11980 const thirdSeek = seekToTime({ 11981 element, 11982 desiredTime: desiredTime + threshold, 11983 logLevel, 11984 mountTime 11985 }); 11986 currentCancel = thirdSeek.cancel; 11987 return thirdSeek.wait.then(()=>{ 11988 resolve(); 11989 }).catch((err)=>{ 11990 reject(err); 11991 }); 11992 }).catch((err)=>{ 11993 reject(err); 11994 }); 11995 }); 11996 currentCancel = firstSeek.cancel; 11997 }); 11998 return { 11999 prom, 12000 cancel: ()=>{ 12001 currentCancel(); 12002 } 12003 }; 12004};
12005// src/video/VideoForRendering.tsx 12006 12007var VideoForRenderingForwardFunction = ({ onError, volume: volumeProp, allowAmplificationDuringRender, playbackRate, onDuration, toneFrequency, name, acceptableTimeShiftInSeconds, delayRenderRetries, delayRenderTimeoutInMilliseconds, loopVolumeCurveBehavior, audioStreamIndex, onVideoFrame, preservePitch: _preservePitch, ...props2 }, ref)=>{ 12008 const absoluteFrame = useTimelinePosition(); 12009 const frame = useCurrentFrame(); 12010 const volumePropsFrame = useFrameForVolumeProp(loopVolumeCurveBehavior ?? "repeat"); 12011 const videoConfig = useUnsafeVideoConfig(); 12012 const videoRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); 12013 const sequenceContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(SequenceContext); 12014 const mediaStartsAt = useMediaStartsAt(); 12015 const environment = useRemotionEnvironment(); 12016 const logLevel = useLogLevel(); 12017 const mountTime = useMountTime(); 12018 const { delayRender: delayRender2, continueRender: continueRender2 } = useDelayRender(); 12019 const { registerRenderAsset, unregisterRenderAsset } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(RenderAssetManager); 12020 const id = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(()=>`video-${random(props2.src ?? "")}-${sequenceContext?.cumulatedFrom}-${sequenceContext?.relativeFrom}-${sequenceContext?.durationInFrames}`, [ 12021 props2.src, 12022 sequenceContext?.cumulatedFrom, 12023 sequenceContext?.relativeFrom, 12024 sequenceContext?.durationInFrames 12025 ]); 12026 if (!videoConfig) { 12027 throw new Error("No video config found"); 12028 } 12029 const volume = evaluateVolume({ 12030 volume: volumeProp, 12031 frame: volumePropsFrame, 12032 mediaVolume: 1 12033 }); 12034 warnAboutTooHighVolume(volume); 12035 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 12036 if (!props2.src) { 12037 throw new Error("No src passed"); 12038 } 12039 if (props2.muted) { 12040 return; 12041 } 12042 if (volume <= 0) { 12043 return; 12044 } 12045 if (!window.remotion_audioEnabled) { 12046 return; 12047 } 12048 registerRenderAsset({ 12049 type: "video", 12050 src: getAbsoluteSrc(props2.src), 12051 id, 12052 frame: absoluteFrame, 12053 volume, 12054 mediaFrame: frame, 12055 playbackRate: playbackRate ?? 1, 12056 toneFrequency: toneFrequency ?? 1, 12057 audioStartFrame: Math.max(0, -(sequenceContext?.cumulatedNegativeFrom ?? 0)), 12058 audioStreamIndex: audioStreamIndex ?? 0 12059 }); 12060 return ()=>unregisterRenderAsset(id); 12061 }, [ 12062 props2.muted, 12063 props2.src, 12064 registerRenderAsset, 12065 id, 12066 unregisterRenderAsset, 12067 volume, 12068 frame, 12069 absoluteFrame, 12070 playbackRate, 12071 toneFrequency, 12072 sequenceContext?.cumulatedNegativeFrom, 12073 audioStreamIndex 12074 ]); 12075 (0,react__WEBPACK_IMPORTED_MODULE_0__.useImperativeHandle)(ref, ()=>{ 12076 return videoRef.current; 12077 }, []); 12078 useEmitVideoFrame({ 12079 ref: videoRef, 12080 onVideoFrame 12081 }); 12082 (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(()=>{ 12083 if (!window.remotion_videoEnabled) { 12084 return; 12085 } 12086 const { current } = videoRef; 12087 if (!current) { 12088 return; 12089 } 12090 const currentTime = getMediaTime({ 12091 frame, 12092 playbackRate: playbackRate || 1, 12093 startFrom: -mediaStartsAt, 12094 fps: videoConfig.fps 12095 }); 12096 const handle = delayRender2(`Rendering <Html5Video /> with src="${props2.src}" at time ${currentTime}`, { 12097 retries: delayRenderRetries ?? undefined, 12098 timeoutInMilliseconds: delayRenderTimeoutInMilliseconds ?? undefined 12099 }); 12100 if (window.process?.env?.NODE_ENV === "test") { 12101 continueRender2(handle); 12102 return; 12103 } 12104 if (isApproximatelyTheSame(current.currentTime, currentTime)) { 12105 if (current.readyState >= 2) { 12106 continueRender2(handle); 12107 return; 12108 } 12109 const loadedDataHandler = ()=>{ 12110 continueRender2(handle); 12111 }; 12112 current.addEventListener("loadeddata", loadedDataHandler, { 12113 once: true 12114 }); 12115 return ()=>{ 12116 current.removeEventListener("loadeddata", loadedDataHandler); 12117 }; 12118 } 12119 const endedHandler = ()=>{ 12120 continueRender2(handle); 12121 }; 12122 const seek2 = seekToTimeMultipleUntilRight({ 12123 element: current, 12124 desiredTime: currentTime, 12125 fps: videoConfig.fps, 12126 logLevel, 12127 mountTime 12128 }); 12129 seek2.prom.then(()=>{ 12130 continueRender2(handle); 12131 }); 12132 current.addEventListener("ended", endedHandler, { 12133 once: true 12134 }); 12135 const errorHandler = ()=>{ 12136 if (current?.error) { 12137 console.error("Error occurred in video", current?.error); 12138 if (onError) { 12139 return; 12140 } 12141 throw new MediaPlaybackError({ 12142 message: `The browser threw an error while playing the video ${props2.src}: Code ${current.error.code} - ${current?.error?.message}. See https://remotion.dev/docs/media-playback-error for help. Pass an onError() prop to handle the error.`, 12143 src: props2.src 12144 }); 12145 } else { 12146 throw new MediaPlaybackError({ 12147 message: "The browser threw an error", 12148 src: props2.src 12149 }); 12150 } 12151 }; 12152 current.addEventListener("error", errorHandler, { 12153 once: true 12154 }); 12155 return ()=>{ 12156 seek2.cancel(); 12157 current.removeEventListener("ended", endedHandler); 12158 current.removeEventListener("error", errorHandler); 12159 continueRender2(handle); 12160 }; 12161 }, [ 12162 volumePropsFrame, 12163 props2.src, 12164 playbackRate, 12165 videoConfig.fps, 12166 frame, 12167 mediaStartsAt, 12168 onError, 12169 delayRenderRetries, 12170 delayRenderTimeoutInMilliseconds, 12171 logLevel, 12172 mountTime, 12173 continueRender2, 12174 delayRender2 12175 ]); 12176 const { src } = props2; 12177 if (environment.isRendering) { 12178 (0,react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect)(()=>{ 12179 if (window.process?.env?.NODE_ENV === "test") { 12180 return; 12181 } 12182 const newHandle = delayRender2("Loading <Html5Video> duration with src=" + src, { 12183 retries: delayRenderRetries ?? undefined, 12184 timeoutInMilliseconds: delayRenderTimeoutInMilliseconds ?? undefined 12185 }); 12186 const { current } = videoRef; 12187 const didLoad = ()=>{ 12188 if (current?.duration) { 12189 onDuration(src, current.duration); 12190 } 12191 continueRender2(newHandle); 12192 }; 12193 if (current?.duration) { 12194 onDuration(src, current.duration); 12195 continueRender2(newHandle); 12196 } else { 12197 current?.addEventListener("loadedmetadata", didLoad, { 12198 once: true 12199 }); 12200 } 12201 return ()=>{ 12202 current?.removeEventListener("loadedmetadata", didLoad); 12203 continueRender2(newHandle); 12204 }; 12205 }, [ 12206 src, 12207 onDuration, 12208 delayRenderRetries, 12209 delayRenderTimeoutInMilliseconds, 12210 continueRender2, 12211 delayRender2 12212 ]); 12213 } 12214 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)("video", { 12215 ref: videoRef, 12216 disableRemotePlayback: true, 12217 ...props2 12218 }); 12219}; 12220var VideoForRendering = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(VideoForRenderingForwardFunction);
12221// src/video/html5-video.tsx 12222 12223var VideoForwardingFunction = (props2, ref)=>{ 12224 const { startFrom, endAt, trimBefore, trimAfter, name, pauseWhenBuffering, stack, _remotionInternalNativeLoopPassed, showInTimeline, onAutoPlayError, onVideoFrame, ...otherProps } = props2; 12225 const { loop, ...propsOtherThanLoop } = props2; 12226 const { fps } = useVideoConfig(); 12227 const environment = useRemotionEnvironment(); 12228 if (environment.isClientSideRendering) { 12229 throw new Error("<Html5Video> is not supported in @remotion/web-renderer. Use <Video> from @remotion/media instead. See https://remotion.dev/docs/client-side-rendering/limitations"); 12230 } 12231 const { durations, setDurations } = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(DurationsContext); 12232 if (typeof ref === "string") { 12233 throw new Error("string refs are not supported"); 12234 } 12235 if (typeof props2.src !== "string") { 12236 throw new TypeError(`The \`<Html5Video>\` tag requires a string for \`src\`, but got ${JSON.stringify(props2.src)} instead.`); 12237 } 12238 const preloadedSrc = usePreload(props2.src); 12239 const onDuration = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((src, durationInSeconds)=>{ 12240 setDurations({ 12241 type: "got-duration", 12242 durationInSeconds, 12243 src 12244 }); 12245 }, [ 12246 setDurations 12247 ]); 12248 const durationFetched = durations[getAbsoluteSrc(preloadedSrc)] ?? durations[getAbsoluteSrc(props2.src)]; 12249 validateMediaTrimProps({ 12250 startFrom, 12251 endAt, 12252 trimBefore, 12253 trimAfter 12254 }); 12255 const { trimBeforeValue, trimAfterValue } = resolveTrimProps({ 12256 startFrom, 12257 endAt, 12258 trimBefore, 12259 trimAfter 12260 }); 12261 if (loop && durationFetched !== undefined) { 12262 if (!Number.isFinite(durationFetched)) { 12263 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Html5Video, { 12264 ...propsOtherThanLoop, 12265 ref, 12266 stack, 12267 _remotionInternalNativeLoopPassed: true 12268 }); 12269 } 12270 const mediaDuration = durationFetched * fps; 12271 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Loop, { 12272 durationInFrames: calculateMediaDuration({ 12273 trimAfter: trimAfterValue, 12274 mediaDurationInFrames: mediaDuration, 12275 playbackRate: props2.playbackRate ?? 1, 12276 trimBefore: trimBeforeValue 12277 }), 12278 layout: "none", 12279 name, 12280 showInTimeline: false, 12281 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Html5Video, { 12282 ...propsOtherThanLoop, 12283 ref, 12284 stack, 12285 _remotionInternalNativeLoopPassed: true 12286 }) 12287 }); 12288 } 12289 if (typeof trimBeforeValue !== "undefined" || typeof trimAfterValue !== "undefined") { 12290 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Sequence, { 12291 layout: "none", 12292 from: 0 - (trimBeforeValue ?? 0), 12293 showInTimeline: false, 12294 durationInFrames: trimAfterValue === undefined ? undefined : trimAfterValue / (props2.playbackRate ?? 1), 12295 name, 12296 children: /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(Html5Video, { 12297 pauseWhenBuffering: pauseWhenBuffering ?? false, 12298 onVideoFrame, 12299 ...otherProps, 12300 ref, 12301 stack 12302 }) 12303 }); 12304 } 12305 validateMediaProps({ 12306 playbackRate: props2.playbackRate, 12307 preservePitch: props2.preservePitch, 12308 volume: props2.volume 12309 }, "Html5Video"); 12310 if (environment.isRendering) { 12311 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(VideoForRendering, { 12312 onDuration, 12313 onVideoFrame: onVideoFrame ?? null, 12314 ...otherProps, 12315 ref 12316 }); 12317 } 12318 return /* @__PURE__ */ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(VideoForPreview, { 12319 onlyWarnForMediaSeekingError: false, 12320 ...otherProps, 12321 ref, 12322 onVideoFrame: onVideoFrame ?? null, 12323 pauseWhenBuffering: pauseWhenBuffering ?? false, 12324 onDuration, 12325 _remotionInternalStack: stack ?? null, 12326 _remotionInternalNativeLoopPassed: _remotionInternalNativeLoopPassed ?? false, 12327 showInTimeline: showInTimeline ?? true, 12328 onAutoPlayError: onAutoPlayError ?? undefined 12329 }); 12330}; 12331var Html5Video = /*#__PURE__*/ (0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(VideoForwardingFunction);
12332addSequenceStackTraces(Html5Video); 12333var Video = (/* unused pure expression or super */ null && (Html5Video));
12334// src/index.ts 12335checkMultipleRemotionVersions(); 12336var Experimental = { 12337 Clipper, 12338 Null, 12339 useIsPlayer 12340}; 12341var proxyObj = {}; 12342var Config = new Proxy(proxyObj, { 12343 get (_, prop) { 12344 if (prop === "Bundling" || prop === "Rendering" || prop === "Log" || prop === "Puppeteer" || prop === "Output") { 12345 return Config; 12346 } 12347 return ()=>{ 12348 console.warn("â ï¸ The CLI configuration has been extracted from Remotion Core."); 12349 console.warn("Update the import from the config file:"); 12350 console.warn(); 12351 console.warn("- Delete:"); 12352 console.warn('import {Config} from "remotion";'); 12353 console.warn("+ Replace:"); 12354 console.warn('import {Config} from "@remotion/cli/config";'); 12355 console.warn(); 12356 console.warn("For more information, see https://www.remotion.dev/docs/4-0-migration."); 12357 process.exit(1); 12358 }; 12359 } 12360}); 12361Sequence.displayName = "Sequence"; 12362addSequenceStackTraces(Sequence); 12363addSequenceStackTraces(Composition); 12364addSequenceStackTraces(Folder); 12365 12366 12367 12368/***/ }) 12369 12370}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.