1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8376],{72717:function(e,t,r){r.d(t,{Bb:function(){return ta},nk:function(){return tL}});var a,n=r(67294),o=r(93373),i=r(29872),s=r(32700),l=r(30219),d=r(74354),u=r(85893),c=Symbol.dispose||Symbol.for("Symbol.dispose"),m=Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose"),f=(e,t,r)=>{if(null!=t){var a;if("object"!=typeof t&&"function"!=typeof t)throw TypeError('Object expected to be assigned to "using" declaration');if(r&&(a=t[m]),void 0===a&&(a=t[c]),"function"!=typeof a)throw TypeError("Object not disposable");e.push([r,a,t])}else r&&e.push([r]);return t},p=(e,t,r)=>{var a="function"==typeof SuppressedError?SuppressedError:function(e,t,r,a){return(a=Error(r)).name="SuppressedError",a.error=e,a.suppressed=t,a},n=e=>t=r?new a(e,t,"An error was suppressed during disposal"):(r=!0,e),o=a=>{for(;a=e.pop();)try{var i=a[1]&&a[1].call(a[2]);if(a[0])return Promise.resolve(i).then(o,e=>(n(e),o()))}catch(e){n(e)}if(r)throw t};return o()},h=({loop:e,mediaDurationInSeconds:t,playbackRate:r,trimAfter:a,trimBefore:n,sequenceDurationInFrames:i,compFps:s})=>{if(!e||!t)return;let l=o.Internals.calculateMediaDuration({mediaDurationInFrames:t*s,playbackRate:r,trimAfter:a,trimBefore:n});return{numberOfTimes:i/l,startOffset:0,durationInFrames:l}},y=({loop:e,mediaDurationInSeconds:t,unloopedTimeInSeconds:r,src:a,trimAfter:n,trimBefore:i,fps:s,playbackRate:l,ifNoMediaDuration:d})=>{if(null===t&&e&&"fail"===d)throw Error(`Could not determine duration of ${a}, but "loop" was set.`);let u=e?o.Internals.calculateMediaDuration({trimAfter:n,mediaDurationInFrames:t?t*s:1/0,playbackRate:1,trimBefore:i}):1/0,c=e?r*l*s%u/s:r*l;return(n??null)!==null&&!e&&c>=(n-(i??0))/s?null:c+(i??0)/s},g=({mediaDurationInSeconds:e,ifNoMediaDuration:t,src:r,trimAfter:a,trimBefore:n,fps:i})=>{if(null===e&&"fail"===t)throw Error(`Could not determine duration of ${r}, but "loop" was set.`);return o.Internals.calculateMediaDuration({trimAfter:a,mediaDurationInFrames:e?e*i:1/0,playbackRate:1,trimBefore:n})/i+(n??0)/i},w=({startFromSecond:e,iterator:t,unscheduleAudioNode:r})=>{let a=!1,n=[],o=-1/0,i=()=>{for(let{node:e}of n){r(e);try{e.stop()}catch{}}n.length=0};return{destroy:()=>{i(),a=!0,t.return().catch(()=>{})},getNextFn:async()=>{let e=await t.next();return e.value&&(o=Math.max(o,e.value.timelineTimestamp+e.value.sourceDurationInSeconds)),e},isDestroyed:()=>a,addQueuedAudioNode:e=>{n.push(e)},guessNextTimestamp:()=>Number.isFinite(o)?o:e,getQueuedPeriod:()=>{let e=-1/0,t=1/0;for(let r of n)e=Math.max(e,r.timestamp+r.sourceDurationInSeconds),t=Math.min(t,r.timestamp);return Number.isFinite(t)&&Number.isFinite(e)?{from:t,until:e}:null}}},I=(e,t)=>!!t&&e>=t.from&&e<t.until,b=({mediaTimestamp:e,targetTime:t,currentTime:r,sequenceStartTime:a})=>t+r+((e<a?a-e:0)+(t<0?-t:0)),v=({sourceDurationInSeconds:e,sourceOffsetInSeconds:t,offset:r})=>Math.max(0,e-(r-t)),S=({mediaTimestamp:e,targetTime:t,sequenceStartTime:r,combinedPlaybackRate:a,sourceStartOffsetInSeconds:n})=>n+(e<r?r-e:0)+(t<0?-t*a:0);class k extends Error{constructor(){super("Waiter became stale before it got its turn"),this.name="StaleWaiterError"}}var C=[],T=0,x=null,F=()=>{if(T>=1){if(x?.waiter.getPriority()!==null)return;x.cancel()}let e=[];for(let t=C.length-1;t>=0;t--)if(null===C[t].getPriority()){let[r]=C.splice(t,1);e.push(r)}for(let t of e)t.onError(new k);if(0===C.length)return;let t=0,r=C[0].getPriority();if(null===r)throw Error("Stale waiter should have been removed");for(let e=1;e<C.length;e++){let a=C[e].getPriority();if(null===a)throw Error("Stale waiter should have been removed");a<r&&(r=a,t=e)}if(r>2)return;let[a]=C.splice(t,1);T++;let n=!1,o=!1,i={waiter:a,cancel:()=>{o=!0,i.settle()},settle:()=>{n||(n=!0,T--,x!==i||(x=null))}};x=i,a.fn().then(e=>{i.settle(),o||a.onDone(e,F)},e=>{i.settle(),o||a.onError(e)})},M=({getPriority:e,fn:t,onDone:r,onError:a})=>{C.push({getPriority:e,fn:t,onDone:r,onError:a}),F()};async function*A({audioSink:e,timeToSeek:t,maximumTimestamp:r}){for await(let a of e.buffers(Math.max(0,t-.5),r)){let e=Math.max(a.timestamp,t),n=Math.min(a.timestamp+a.duration,r);n<=e||(yield{buffer:a,timelineTimestamp:e,sourceOffsetInSeconds:e-a.timestamp,sourceDurationInSeconds:n-e})}}async function*E({audioSink:e,seekTimeInSeconds:t,loopStartInSeconds:r,segmentEndInSeconds:a,maximumContinuousTimestamp:n}){if(a<=r)throw Error(`Cannot loop audio over an empty range (${r} to ${a})`);let o=t,i=t;
1for(;;){let t=!1;for await(let r of A({audioSink:e,timeToSeek:o,maximumTimestamp:a})){t=!0;let e=i+(r.timelineTimestamp-o),a=Math.min(r.sourceDurationInSeconds,n-e);if(a<=0||(yield{...r,timelineTimestamp:e,sourceDurationInSeconds:a},e+a>=n))return}if(!t)throw Error(`Audio loop pass from ${o} to ${a} yielded no buffers`);i+=a-o,o=r}}var P=e=>e>=.1,R=({anchor:e,unloopedTimeInSeconds:t,playbackRate:r})=>e.mediaStartInSeconds+(t-e.unloopedStartInSeconds)*r,D=({audioTrack:e,delayPlaybackHandleIfNotPremounting:t,sharedAudioContext:r,getSequenceEndTimestamp:a,getSequenceDurationInSeconds:n,getMediaEndTimestamp:l,getStartTime:d,initialMuted:u,drawDebugOverlay:c,initialPlaybackRate:m,initialTrimBefore:f,initialTrimAfter:p,initialSequenceOffset:h,initialSequenceDurationInFrames:y,initialLoop:g,initialFps:v})=>{let S=u,C=1,T={time:-1,playbackRate:m,trimBefore:f,trimAfter:p,sequenceOffset:h,sequenceDurationInFrames:y,loop:g,fps:v},x=r.audioContext.createGain();x.connect(r.gainNode);let D=new i.L4(e),L=null,$=null,O=0,N=0,B=null,V=()=>{B&&(B.unblock(),B=null)},_=[],q=()=>{for(let e=_.length-1;e>=0;e--){let t=_[e];t.remaining--,t.remaining<=0&&(t.resolve(),_.splice(e,1))}},z=({buffer:e,mediaTimestamp:t,originalUnloopedMediaTimestamp:a,sourceOffsetInSeconds:n,sourceDurationInSeconds:i,playbackRate:s,scheduleAudioNode:l,logLevel:d})=>{if(!L)throw Error("Audio buffer iterator not found");if(S)return;let u=r.audioContext.createBufferSource();u.buffer=e,u.playbackRate.value=s,u.connect(x);let c=l(u,t,a,n,i);if("not-started"===c.type){o.Internals.Log.verbose({logLevel:d,tag:"audio-scheduling"},"not started, disconnected: %s %s",t.toFixed(3),e.duration.toFixed(3)),u.disconnect();return}L.addQueuedAudioNode({node:u,timestamp:t,buffer:e,sourceDurationInSeconds:i,scheduledTime:c.scheduledTime,playbackRate:s,scheduledAtAnchor:r.audioSyncAnchor.value})},j=({buffer:e,playbackRate:t,scheduleAudioNode:r,logLevel:n})=>{if(S)return;let o=d(),i=a();if(e.timelineTimestamp+e.sourceDurationInSeconds<=o||e.timelineTimestamp>=i)return;let s=Math.max(e.timelineTimestamp,o),l=Math.min(e.timelineTimestamp+e.sourceDurationInSeconds,i);N+=Math.max(0,l-s),z({buffer:e.buffer.buffer,mediaTimestamp:e.timelineTimestamp,playbackRate:t,scheduleAudioNode:r,logLevel:n,originalUnloopedMediaTimestamp:e.buffer.timestamp,sourceOffsetInSeconds:e.sourceOffsetInSeconds,sourceDurationInSeconds:e.sourceDurationInSeconds}),c()},U=({iterator:e,nonce:t,getTargetTime:r,playbackRate:a,scheduleAudioNode:n,onScheduled:o,onDestroyed:i,onDone:l,logLevel:u,currentTime:c,getAudioContextCurrentTimeMockedInTest:m})=>{M({getPriority:()=>{if(e.isDestroyed())return i(),null;let t=e.guessNextTimestamp(),a=r(t,c);return null===a?null:b({mediaTimestamp:t,targetTime:a,currentTime:c,sequenceStartTime:d()})-m()},fn:()=>e.getNextFn(),onDone:(s,d)=>{if(e.isDestroyed()){d(),i();return}if(!s.value){d(),l();return}o(s.value.sourceDurationInSeconds),q(),j({buffer:s.value,playbackRate:a,scheduleAudioNode:n,logLevel:u}),U({iterator:e,nonce:t,getTargetTime:r,playbackRate:a,scheduleAudioNode:n,onScheduled:o,onDestroyed:i,onDone:l,logLevel:u,currentTime:c,getAudioContextCurrentTimeMockedInTest:m}),d()},onError:e=>{if(e instanceof s.xh||e instanceof k){i();return}throw e}})},H=({nonce:e,playbackRate:a,startFromSecond:o,unloopedStartFromSecond:i,scheduleAudioNode:s,getTargetTime:u,logLevel:c,loop:m,unscheduleAudioNode:f,getAudioContextCurrentTimeMockedInTest:p})=>{if(S)return;let h=l();if(o>=h)return;L?.destroy(),V();let y=t();B=y,$={unloopedStartInSeconds:i,mediaStartInSeconds:o};let g=o+n()*a,I=m?E({audioSink:D,seekTimeInSeconds:o,loopStartInSeconds:d(),segmentEndInSeconds:h,maximumContinuousTimestamp:g}):A({audioSink:D,timeToSeek:o,maximumTimestamp:h}),b=w({startFromSecond:o,iterator:I,unscheduleAudioNode:f});O++,L=b;let v=0,k=!1,C=()=>{k||(k=!0,y.unblock())};U({iterator:b,nonce:e,getTargetTime:u,playbackRate:a,scheduleAudioNode:s,onScheduled:e=>{P(v+=e)&&C()},onDestroyed:()=>{C()},onDone:()=>{C()},logLevel:c,currentTime:r.audioContext.currentTime,getAudioContextCurrentTimeMockedInTest:p})};return{startAudioIterator:H,getAudioBufferIterator:()=>L,getCurrentAnchor:()=>$,destroyIterator:()=>{L?.destroy(),L=null,$=null,V()},seek:({newTime:e,unloopedNewTime:t,nonce:a,playbackRate:n,localPlaybackRate:o,scheduleAudioNode:i,getTargetTime:s,logLevel:l,loop:d,trimBefore:u,trimAfter:c,sequenceOffset:m,sequenceDurationInFrames:f,fps:p,getAudioContextCurrentTimeMockedInTest:h})=>{if(!a.isStale()&&(T.time!==e||T.playbackRate!==n||T.trimBefore!==u||T.trimAfter!==c||T.sequenceOffset!==m||T.sequenceDurationInFrames!==f||T.loop!==d||T.fps!==p)&&(T={time:e,playbackRate:n,trimBefore:u,trimAfter:c,sequenceOffset:m,sequenceDurationInFrames:f,loop:d,fps:p},!S)){if(L&&!L.isDestroyed()){let a=d&&$?R({anchor:$,unloopedTimeInSeconds:t,playbackRate:o}):e,n=L.getQueuedPeriod();if(I(a,n?{from:n.from-.1-r.audioContext.baseLatency-r.audioContext.outputLatency,until:n.until}:null)){F();return}let i=L.guessNextTimestamp();if(i<a&&1>Math.abs(i-a)){F();return}}H({nonce:a,playbackRate:n,startFromSecond:e,unloopedStartFromSecond:t,scheduleAudioNode:i,getTargetTime:s,logLevel:l,loop:d,unscheduleAudioNode:r.unscheduleAudioNode,getAudioContextCurrentTimeMockedInTest:h})}},getAudioIteratorsCreated:()=>O,getTotalAudioScheduledInSeconds:()=>N,setMuted:e=>{S=e,x.gain.value=S?0:C},setVolume:e=>{C=Math.max(0,e),x.gain.value=S?0:C},scheduleAudioChunk:z,waitForNScheduledNodes:e=>e<=0?Promise.resolve():new Promise(t=>{_.push({remaining:e,resolve:t})})}},L=({context:e,audioTime:t,audioContextState:r,audioSyncAnchor:a,playing:n,audioIteratorManager:o,videoIteratorManager:i,playbackRate:s})=>{let l=a?.value??0,d=["Debug overlay",`Video iterators created: ${i?.getVideoIteratorsCreated()}`,`Audio iterators created: ${o?.getAudioIteratorsCreated()}`,`Audio scheduled: ${(o?.getTotalAudioScheduledInSeconds()??0).toFixed(3)}s`,`Frames rendered: ${i?.getFramesRendered()}`,`Audio context state: ${r}`,t?`Audio time: ${((t-l)*s).toFixed(3)}
1s`:null].filter(Boolean);if(o){let e=o.getAudioBufferIterator()?.getQueuedPeriod();if(e){let r=t?` (${(e.until-(t-l)*s).toFixed(3)}s ahead)`:"";d.push(`Audio queued until ${e.until.toFixed(3)}s${r}`)}d.push(`Playing: ${n}`)}let u=30*d.length+20;e.fillStyle="rgba(0, 0, 0, 1)",e.fillRect(20,20,600,u),e.fillStyle="white",e.font="24px sans-serif",e.textBaseline="top";for(let t=0;t<d.length;t++)e.fillText(d[t],30,30+30*t)},$=async e=>await e.getDurationFromMetadata(void 0,{skipLiveWait:!0})??e.computeDuration(void 0,{skipLiveWait:!0}),O=e=>{if(!e)return;let t=[];if(e instanceof Headers)e.forEach((e,r)=>{t.push([r.toLowerCase(),e])});else if(Array.isArray(e))for(let[r,a]of e)t.push([r.toLowerCase(),a]);else for(let[r,a]of Object.entries(e))t.push([r.toLowerCase(),a]);return t.sort(([e],[t])=>e<t?-1:e>t?1:0),t},N=e=>{if(!e)return;let t=O(e.headers),r={...void 0===e.cache?null:{cache:e.cache},...void 0===e.credentials?null:{credentials:e.credentials},...void 0===t?null:{headers:t},...void 0===e.integrity?null:{integrity:e.integrity},...void 0===e.mode?null:{mode:e.mode},...void 0===e.redirect?null:{redirect:e.redirect},...void 0===e.referrer?null:{referrer:e.referrer},...void 0===e.referrerPolicy?null:{referrerPolicy:e.referrerPolicy}};return 0===Object.keys(r).length?void 0:r},B=e=>{let t=N(e);return t?[t.cache??null,t.credentials??null,t.integrity??null,t.mode??null,t.redirect??null,t.referrer??null,t.referrerPolicy??null,t.headers??null]:null},V=({credentials:e,requestInit:t})=>void 0===e?N(t):N({credentials:e,...t}),_={},q=({src:e,credentials:t,requestInit:r})=>JSON.stringify([e,t??null,B(r)]),z=({src:e,credentials:t,requestInit:r})=>{let a=N(r),n=q({src:e,credentials:t,requestInit:a}),o=_[n];if(o)return o.refCount++,{input:o.input,cacheKey:n};let i=V({credentials:t,requestInit:a}),u=new s.II({source:new l.IK(e,i?{requestInit:i}:void 0),formats:d.t6});return _[n]={input:u,refCount:1},{input:u,cacheKey:n}},j=e=>{let t=_[e];t&&(t.refCount--,t.refCount<=0&&(delete _[e],t.input.dispose()))},U=async({videoTrack:e,audioTracks:t,audioStreamIndex:r})=>null!==r?t[r]??null:e?await e.getPrimaryPairableAudioTrack()??null:t[0]??null;function H(e){return!!(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))}var W=()=>{let e=0;return{createAsyncOperation:()=>{let t=++e;return{isStale:()=>e!==t}}}};class K{isPremounting;isPostmounting;activeHandles=new Set;delayPlayback;constructor({bufferState:e,isPremounting:t,isPostmounting:r}){this.delayPlayback=e.delayPlayback,this.isPremounting=t,this.isPostmounting=r}shouldDelayPlayback(){return!this.isPremounting&&!this.isPostmounting}syncHandles(){for(let e of this.activeHandles)this.shouldDelayPlayback()?e.arm():e.disarm()}setIsPremounting(e){this.isPremounting=e,this.syncHandles()}setIsPostmounting(e){this.isPostmounting=e,this.syncHandles()}createHandle(){let e=!1,t=null,r=!1,a=()=>{e||r||(t=this.delayPlayback().unblock,e=!0)},n=()=>{e&&(t?.(),t=null,e=!1)},o={arm:a,disarm:n,dispose:()=>{}};return o.dispose=()=>{r||(r=!0,n(),this.activeHandles.delete(o))},this.activeHandles.add(o),this.shouldDelayPlayback()&&a(),{unblock:o.dispose,[Symbol.dispose]:o.dispose}}}var J=e=>Math.round(1e3*e)/1e3,Q=Symbol("releaseCanvas"),G=e=>{e?.[Q]?.()},X=()=>{let e=[];return{makeStableFrame:t=>{let{canvas:r}=t,a=e.pop()??new OffscreenCanvas(r.width,r.height);a.width!==r.width&&(a.width=r.width),a.height!==r.height&&(a.height=r.height);let n=a.getContext("2d");if(!n)throw Error("Could not create canvas context");n.clearRect(0,0,a.width,a.height),n.drawImage(r,0,0);let o=!1;return{canvas:a,duration:t.duration,timestamp:t.timestamp,[Q]:()=>{o||(o=!0,e.push(a))}}}}},Y=(e,t)=>{let r=e.canvases(t),a=[],n=!1,o=!1,i=!1,s=null,l=X(),d=e=>l.makeStableFrame(e),u=()=>{if(n||o||i||a.length>=3)return;n=!0;let e={promise:r.next(),resolved:null};a.push(e),s=e.promise.then(t=>{if(n=!1,s=null,t.done){e.resolved=t,o=!0;return}if(i){e.resolved={done:!0,value:void 0};return}e.resolved={...t,value:d(t.value)},u()},()=>{n=!1,s=null})};return u(),{next:()=>{let e=a.shift();if(u(),!e){if(o||i)return{type:"ready",frame:null};let e=s;return{type:"pending",wait:async()=>{await e;let t=a.shift();if(u(),!t)return null;if(t.resolved)return t.resolved.done?null:t.resolved.value;let r=await t.promise;return r.done?null:d(r.value)}}}return e.resolved?e.resolved.done?{type:"ready",frame:null}:{type:"ready",frame:e.resolved.value}:{type:"pending",wait:async()=>{let t=await e.promise;return e.resolved?e.resolved.done?null:e.resolved.value:t.done?null:d(t.value)}}},closeIterator:async()=>{for(let e of(i=!0,a))e.resolved&&!e.resolved.done&&G(e.resolved.value);a.length=0,await r.return()}}}
1,Z=e=>{let t=new Map;return{prewarmIteratorForLooping:({timeToSeek:r})=>{t.has(r)||t.set(r,Y(e,r))},makeIteratorOrUsePrewarmed:r=>{let a=t.get(r);return a?(t.delete(r),a):Y(e,r)},destroy:()=>{for(let e of t.values())e.closeIterator();t.clear()}}},ee=async(e,t)=>{let r=!1,a=t.makeIteratorOrUsePrewarmed(e),n=!1,o=a.next(),i=o&&"ready"===o.type?o.frame:await o.wait(),s=i,l=null,d=e=>{s!==e&&G(s),s=e},u=e=>(null===(l=e)&&(n=!0),l),c=()=>{if(l)return{type:"ready",frame:l};if(n)return{type:"ready",frame:null};let e=a.next();return"ready"===e.type?{type:"ready",frame:u(e.frame)}:{type:"pending",wait:e.wait}},m=e=>e?J(e.timestamp):1/0,f=async({pendingFrameBehavior:e,shouldContinue:t})=>{let r=c();if("ready"===r.type)return{type:"ready",timestamp:m(r.frame)};if("restart-iterator"===e)return{type:"pending"};if(!t())return{type:"cancelled"};let a=u(await r.wait());return t()?{type:"ready",timestamp:m(a)}:{type:"cancelled"}},p=()=>{if(l){let e=l;return d(e),l=null,{type:"got-frame-or-end",frame:e}}let e=a.next();return"pending"===e.type?{type:"need-to-wait-for-it",waitPromise:async()=>{let t=await e.wait();return t?d(t):n=!0,t}}:(e.frame?d(e.frame):n=!0,{type:"got-frame-or-end",frame:e.frame??null})},h=async(t,r)=>{if(!r.shouldContinue())return{type:"not-satisfied",reason:"seek was superseded"};let a=J(t);if(s){let n=J(s.timestamp);if(a<n)return s===i&&J(t)>=J(e)?{type:"satisfied",frame:s}:{type:"not-satisfied",reason:`iterator is too far, most recently returned ${n}`};let o=await f({pendingFrameBehavior:r.pendingFrameBehavior,shouldContinue:r.shouldContinue});if("cancelled"===o.type)return{type:"not-satisfied",reason:"seek was superseded"};
1if("pending"===o.type)return{type:"not-satisfied",reason:"iterator did not have next frame ready"};if(n<=a&&o.timestamp>a)return{type:"satisfied",frame:s}}if(n)return s?{type:"satisfied",frame:s}:{type:"not-satisfied",reason:"iterator ended"};for(;;){if(!r.shouldContinue())return{type:"not-satisfied",reason:"seek was superseded"};let e=p();if("need-to-wait-for-it"===e.type)return{type:"not-satisfied",reason:"iterator did not have frame ready"};if("got-frame-or-end"===e.type){if(null===e.frame){if(n=!0,s)return{type:"satisfied",frame:s};return{type:"not-satisfied",reason:"iterator ended and did not have frame ready"}}let t=J(e.frame.timestamp),o=await f({pendingFrameBehavior:r.pendingFrameBehavior,shouldContinue:r.shouldContinue});if("cancelled"===o.type)return{type:"not-satisfied",reason:"seek was superseded"};if("pending"===o.type)return{type:"not-satisfied",reason:"iterator did not have next frame ready"};if(t<=a&&o.timestamp>a)return{type:"satisfied",frame:e.frame};continue}throw Error("Unreachable")}};return{destroy:()=>{r=!0,G(s),l!==s&&G(l),s=null,l=null,a.closeIterator().catch(()=>{})},initialFrame:i,isDestroyed:()=>r,tryToSatisfySeek:h}},{runEffectChain:et}=o.Internals,er=({previousTime:e,newTime:t,fps:r,playbackRate:a,isPlaying:n})=>!!n&&!(t<e)&&J(t-e)<=J(Math.abs(a)/r),ea=async({delayPlaybackHandleIfNotPremounting:e,canvas:t,context:r,drawDebugOverlay:a,logLevel:n,getOnVideoFrameCallback:s,videoTrack:l,getLoopSegmentMediaEndTimestamp:d,getStartTime:u,getIsLooping:c,getEffects:m,getEffectChainState:h})=>{let y=0,g=null,w=0,I=null,b=null,v=null,S=()=>{b=null};if(t){let e=await l.getDisplayWidth(),r=await l.getDisplayHeight();(t.width!==e||t.height!==r)&&(t.width=e,t.height=r)}let k=Z(new i.C(l,{poolSize:3,fit:"contain",alpha:!0})),C=async e=>{if(r&&t){let a=m(),n=h(t.width,t.height);a.length>0&&n&&t instanceof HTMLCanvasElement?await et({state:n,source:e.canvas,effects:a,output:t,width:t.width,height:t.height}):(r.clearRect(0,0,t.width,t.height),r.drawImage(e.canvas,0,0))}},T=async e=>{await C(e),b=e,w++,a();let t=s();t&&t(e.canvas),o.Internals.Log.trace({logLevel:n,tag:"@remotion/media"},`[MediaPlayer] Drew frame ${e.timestamp.toFixed(3)}s`)},x=async(t,r)=>{let a=[];try{S(),g?.destroy(),I=f(a,e(),0),v=t;let n=await ee(t,k);if(y++,g=n,n.isDestroyed()||r.isStale()||g.isDestroyed()||!n.initialFrame)return;await T(n.initialFrame)}catch(e){var n=e,o=1}finally{p(a,n,o)}},F=async({newTime:e,nonce:t,fps:r,playbackRate:a,isPlaying:n})=>{if(!g||null!==v&&J(v)===J(e))return;let o=v;v=e,c()&&d()-e<1&&k.prewarmIteratorForLooping({timeToSeek:u()});let i=null!==o&&er({previousTime:o,newTime:e,fps:r,playbackRate:a,isPlaying:n})?"wait":"restart-iterator",s=await g.tryToSatisfySeek(e,{pendingFrameBehavior:i,shouldContinue:()=>!t.isStale()});if("satisfied"===s.type){await T(s.frame);return}t.isStale()||await x(e,t)};return{startVideoIterator:x,getVideoIteratorsCreated:()=>y,seek:F,destroy:()=>{S(),k.destroy(),g?.destroy(),r&&t&&r.clearRect(0,0,t.width,t.height),I&&(I.unblock(),I=null),g=null},getVideoFrameIterator:()=>g,drawFrame:T,redrawCurrentFrame:async()=>{if(!b)return;await C(b),a();let e=s();e&&e(b.canvas),o.Internals.Log.trace({logLevel:n,tag:"@remotion/media"},`[MediaPlayer] Redrew frame ${b.timestamp.toFixed(3)}s with updated effects`)},getFramesRendered:()=>w}};class en{tagType;canvas;context;src;logLevel;playbackRate;globalPlaybackRate;audioStreamIndex;sharedAudioContext;audioIteratorManager=null;videoIteratorManager=null;playing=!1;loop=!1;fps;trimBefore;trimAfter;sequenceDurationInFrames;sequenceOffset;totalDuration;debugOverlay=!1;nonceManager;onVideoFrameCallback=null;getEffects;getEffectChainState;initializationPromise=null;premountAwareDelayPlayback;seekPromiseChain=Promise.resolve();constructor({canvas:e,src:t,logLevel:r,sharedAudioContext:a,loop:n,trimBefore:o,trimAfter:i,playbackRate:s,globalPlaybackRate:l,audioStreamIndex:d,fps:u,debugOverlay:c,bufferState:m,isPremounting:f,isPostmounting:p,durationInFrames:h,onVideoFrameCallback:y,playing:g,sequenceOffset:w,credentials:I,requestInit:b,tagType:v,getEffects:S,getEffectChainState:k}){this.canvas=e??null,this.src=t,this.logLevel=r,this.sharedAudioContext=a,this.playbackRate=s,this.globalPlaybackRate=l,this.loop=n,this.trimBefore=o,this.trimAfter=i,this.audioStreamIndex=d,this.fps=u,this.debugOverlay=c,this.premountAwareDelayPlayback=new K({bufferState:m,isPremounting:f,isPostmounting:p}),this.sequenceDurationInFrames=h,this.nonceManager=W(),this.onVideoFrameCallback=y,this.playing=g,this.sequenceOffset=w;
1let{input:C,cacheKey:T}=z({src:this.src,credentials:I,requestInit:b});if(this.input=C,this.inputCacheKey=T,this.tagType=v,this.getEffects=S,this.getEffectChainState=k,e){let t=e.getContext("2d",{alpha:!0,desynchronized:!0});if(!t)throw Error("Could not get 2D context from canvas");this.context=t}else this.context=null}input;inputCacheKey;disposed=!1;isDisposalError(){return this.disposed||!0===this.input.disposed}initialize(e,t){let r=this._initialize(e,t);return this.initializationPromise=r,this.seekPromiseChain=r,r}getStartTime(){return(this.trimBefore??0)/this.fps}getSequenceEndTimestamp(){return this.sequenceDurationInFrames/this.fps*this.playbackRate+this.getStartTime()}getSequenceDurationInSeconds(){return this.sequenceDurationInFrames/this.fps}getMediaEndTimestamp(){return g({mediaDurationInSeconds:this.totalDuration,ifNoMediaDuration:"fail",src:this.src,trimAfter:this.trimAfter,trimBefore:this.trimBefore,fps:this.fps})}getLoopSegmentMediaEndTimestamp(){return Math.min(this.getMediaEndTimestamp(),this.getSequenceEndTimestamp())}async _initialize(e,t){let r=[];try{f(r,this.delayPlaybackHandleIfNotPremounting(),0);try{if(this.isDisposalError())return{type:"disposed"};try{await this.input.getFormat()}catch(e){if(this.isDisposalError())return{type:"disposed"};if(H(e))throw e;return o.Internals.Log.error({logLevel:this.logLevel,tag:"@remotion/media"},`[MediaPlayer] Failed to recognize format for ${this.src}`,e),{type:"unknown-container-format"}}let[r,a,n]=await Promise.all([$(this.input),this.input.getPrimaryVideoTrack(),this.input.getAudioTracks()]);if(this.isDisposalError())return{type:"disposed"};this.totalDuration=r;let i=await U({videoTrack:a,audioTracks:n,audioStreamIndex:this.audioStreamIndex});if(!a&&!i)return{type:"no-tracks"};if(a&&"video"===this.tagType){if(await a.isLive())throw Error("Live streams are not currently supported by Remotion. Sorry! Source: "+this.src);if(await a.isRelativeToUnixEpoch())throw Error("Streams with UNIX timestamps are not currently supported by Remotion. Sorry! Source: "+this.src);if(!await a.canDecode()){if("prores"===a.codec)return{type:"cannot-decode-prores"};return{type:"cannot-decode"}}if(this.isDisposalError())return{type:"disposed"};this.videoIteratorManager=await ea({videoTrack:a,delayPlaybackHandleIfNotPremounting:this.delayPlaybackHandleIfNotPremounting,context:this.context,canvas:this.canvas,getOnVideoFrameCallback:()=>this.onVideoFrameCallback,logLevel:this.logLevel,drawDebugOverlay:this.drawDebugOverlay,getLoopSegmentMediaEndTimestamp:()=>this.getLoopSegmentMediaEndTimestamp(),getStartTime:()=>this.getStartTime(),getIsLooping:()=>this.loop,getEffects:this.getEffects,getEffectChainState:this.getEffectChainState})}let s=this.getTrimmedTime(e);if(null===s)throw Error("should have asserted that the time is not null");if(i&&this.sharedAudioContext){if(await i.isLive())throw Error("Live streams are not currently supported by Remotion. Sorry! Source: "+this.src);if(await i.isRelativeToUnixEpoch())throw Error("Streams with UNIX timestamps are not currently supported by Remotion. Sorry! Source: "+this.src);if(!await i.canDecode())return{type:"cannot-decode"};if(this.isDisposalError())return{type:"disposed"};this.audioIteratorManager=D({audioTrack:i,delayPlaybackHandleIfNotPremounting:this.delayPlaybackHandleIfNotPremounting,sharedAudioContext:this.sharedAudioContext,getMediaEndTimestamp:()=>this.getMediaEndTimestamp(),getSequenceEndTimestamp:()=>this.getSequenceEndTimestamp(),getStartTime:()=>this.getStartTime(),initialMuted:t,drawDebugOverlay:this.drawDebugOverlay,initialPlaybackRate:this.playbackRate*this.globalPlaybackRate,getSequenceDurationInSeconds:()=>this.getSequenceDurationInSeconds(),initialTrimBefore:this.trimBefore,initialTrimAfter:this.trimAfter,initialSequenceOffset:this.sequenceOffset,initialSequenceDurationInFrames:this.sequenceDurationInFrames,initialLoop:this.loop,initialFps:this.fps})}let l=this.nonceManager.createAsyncOperation();try{await Promise.all([this.audioIteratorManager?this.audioIteratorManager.startAudioIterator({nonce:l,playbackRate:this.playbackRate*this.globalPlaybackRate,startFromSecond:s,unloopedStartFromSecond:e,scheduleAudioNode:this.scheduleAudioNode,getTargetTime:this.getTargetTime,logLevel:this.logLevel,loop:this.loop,unscheduleAudioNode:this.sharedAudioContext.unscheduleAudioNode,getAudioContextCurrentTimeMockedInTest:()=>this.sharedAudioContext.audioContext.currentTime}):Promise.resolve(),this.videoIteratorManager?this.videoIteratorManager.startVideoIterator(s,l):Promise.resolve()])}catch(e){if(this.isDisposalError())return{type:"disposed"};o.Internals.Log.error({logLevel:this.logLevel,tag:"@remotion/media"},"[MediaPlayer] Failed to start audio and video iterators",e)}return{type:"success",durationInSeconds:r}}catch(e){if(H(e))return o.Internals.Log.error({logLevel:this.logLevel,tag:"@remotion/media"},`[MediaPlayer] Network/CORS error for ${this.src}`,e),{type:"network-error"};throw o.Internals.Log.error({logLevel:this.logLevel,tag:"@remotion/media"},"[MediaPlayer] Failed to initialize",e),e}}catch(e){var a=e,n=1}finally{p(r,a,n)}}seekToWithQueue=async(e,t)=>{let r=this.nonceManager.createAsyncOperation();await this.seekPromiseChain,this.seekPromiseChain=this.seekToDoNotCallDirectly(e,t,r),await this.seekPromiseChain};async seekTo(e){let t=this.getTrimmedTime(e);
1if(null===t)throw Error("should have asserted that the time is not null");await this.seekToWithQueue(t,e)}async seekToDoNotCallDirectly(e,t,r){if(!r.isStale())try{await Promise.all([this.videoIteratorManager?.seek({newTime:e,nonce:r,fps:this.fps,playbackRate:this.playbackRate,isPlaying:this.playing}),this.audioIteratorManager?.seek({newTime:e,unloopedNewTime:t,nonce:r,playbackRate:this.playbackRate*this.globalPlaybackRate,localPlaybackRate:this.playbackRate,getTargetTime:this.getTargetTime,logLevel:this.logLevel,loop:this.loop,trimBefore:this.trimBefore,trimAfter:this.trimAfter,sequenceOffset:this.sequenceOffset,sequenceDurationInFrames:this.sequenceDurationInFrames,fps:this.fps,scheduleAudioNode:this.scheduleAudioNode,getAudioContextCurrentTimeMockedInTest:()=>this.sharedAudioContext.audioContext.currentTime})])}catch(e){if(this.isDisposalError())return;throw e}}play(){this.playing||(this.playing=!0,this.drawDebugOverlay())}delayPlaybackHandleIfNotPremounting=()=>this.premountAwareDelayPlayback.createHandle();pause(){this.playing&&(this.playing=!1,this.drawDebugOverlay())}setMuted(e){this.audioIteratorManager?.setMuted(e)}setVolume(e){this.audioIteratorManager&&this.audioIteratorManager.setVolume(e)}getTrimmedTime(e){return y({unloopedTimeInSeconds:e,playbackRate:this.playbackRate,loop:this.loop,trimBefore:this.trimBefore,trimAfter:this.trimAfter,mediaDurationInSeconds:this.totalDuration??null,fps:this.fps,ifNoMediaDuration:"infinity",src:this.src})}async setTrimBefore(e,t){this.trimBefore!==e&&(this.trimBefore=e,this.audioIteratorManager?.destroyIterator(),await this.seekTo(t))}async setTrimAfter(e,t){this.trimAfter!==e&&(this.trimAfter=e,this.audioIteratorManager?.destroyIterator(),await this.seekTo(t))}setDebugOverlay(e){this.debugOverlay=e}async setPlaybackRate(e,t){this.playbackRate!==e&&(this.playbackRate=e,this.audioIteratorManager?.destroyIterator(),await this.seekTo(t))}async setGlobalPlaybackRate(e,t){this.globalPlaybackRate!==e&&(this.globalPlaybackRate=e,this.audioIteratorManager?.destroyIterator(),await this.seekTo(t))}async setFps(e,t){this.fps!==e&&(this.fps=e,this.audioIteratorManager?.destroyIterator(),await this.seekTo(t))}setIsPremounting(e){this.premountAwareDelayPlayback.setIsPremounting(e)}setIsPostmounting(e){this.premountAwareDelayPlayback.setIsPostmounting(e)}async setLoop(e,t){this.loop!==e&&(this.loop=e,this.audioIteratorManager?.destroyIterator(),await this.seekTo(t))}async setSequenceOffset(e,t){this.sequenceOffset!==e&&(this.sequenceOffset=e,this.audioIteratorManager?.destroyIterator(),await this.seekTo(t))}async setSequenceDurationInFrames(e,t){this.sequenceDurationInFrames!==e&&(this.sequenceDurationInFrames=e,await this.seekTo(t))}async dispose(){if(!this.disposed){if(this.disposed=!0,this.initializationPromise)try{await this.initializationPromise}catch{}this.nonceManager.createAsyncOperation(),this.videoIteratorManager?.destroy(),this.audioIteratorManager?.destroyIterator(),j(this.inputCacheKey)}}getTargetTime=(e,t)=>{if(!this.sharedAudioContext)throw Error("Shared audio context not found");let r=(t-this.sharedAudioContext.audioSyncAnchor.value)*this.globalPlaybackRate-this.sequenceOffset,a=this.loop?this.audioIteratorManager?.getCurrentAnchor()??null:null,n=a?R({anchor:a,unloopedTimeInSeconds:r,playbackRate:this.playbackRate}):this.getTrimmedTime(r);return null===n?null:(e-n)/(this.playbackRate*this.globalPlaybackRate)};scheduleAudioNode=(e,t,r,a,n)=>{if(!this.sharedAudioContext)throw Error("Shared audio context not found");let o=this.getTargetTime(t,this.sharedAudioContext.audioContext.currentTime),i=this.playbackRate*this.globalPlaybackRate;if(null===o)return{type:"not-started",reason:"no target for"+t.toFixed(3)+","+this.sharedAudioContext.audioContext.currentTime.toFixed(3)};let s=this.getStartTime(),l=S({mediaTimestamp:t,targetTime:o,sequenceStartTime:s,combinedPlaybackRate:i,sourceStartOffsetInSeconds:a}),d=v({sourceDurationInSeconds:n,sourceOffsetInSeconds:a,offset:l}),u=b({mediaTimestamp:t,targetTime:o,sequenceStartTime:s,currentTime:this.sharedAudioContext.audioContext.currentTime});return this.sharedAudioContext.scheduleAudioNode({node:e,mediaTimestamp:t,sourceOffset:a,scheduledTime:u,duration:d,offset:l,originalUnloopedMediaTimestamp:r})};setVideoFrameCallback(e){this.onVideoFrameCallback=e}async redrawVideoEffects(){await this.videoIteratorManager?.redrawCurrentFrame()}drawDebugOverlay=()=>{this.debugOverlay&&this.context&&this.canvas&&L({context:this.context,audioTime:this.sharedAudioContext?.audioContext.currentTime??null,audioContextState:this.sharedAudioContext?.audioContext.state??null,audioSyncAnchor:this.sharedAudioContext?.audioSyncAnchor??null,audioIteratorManager:this.audioIteratorManager,playing:this.playing,videoIteratorManager:this.videoIteratorManager,playbackRate:this.playbackRate*this.globalPlaybackRate})};audioSyncAnchorChanged=()=>{this.audioIteratorManager&&this.audioIteratorManager.destroyIterator()}}
1var eo=({onError:e,error:t,disallowFallback:r,isClientSideRendering:a,clientSideError:n})=>{let o=e?.(t);return a?["fail",n]:o?[o,t]:r?["fail",t]:["fallback",t]},ei=({mediaPlayerRef:e,mediaPlayerReady:t,currentTimeRef:r,playing:a,isPlayerBuffering:i,frame:s,trimBefore:l,trimAfter:d,effectiveMuted:u,userPreferredVolume:c,playbackRate:m,globalPlaybackRate:f,fps:p,sequenceOffset:h,loop:y,durationInFrames:g,isPremounting:w,isPostmounting:I,currentTime:b,logLevel:v,label:S})=>{let k=(0,n.useContext)(o.Internals.SharedAudioContext);(0,n.useLayoutEffect)(()=>{let t=e.current;t&&(a&&!i?t.play():t.pause())},[i,a,v,t,s,e]),(0,n.useLayoutEffect)(()=>{if(!k)return;let{remove:t}=k.audioSyncAnchorEmitter.subscribe(t=>{"changed"===t&&e.current?.audioSyncAnchorChanged()});return()=>{t()}},[k,e]),(0,n.useLayoutEffect)(()=>{let a=e.current;a&&t&&a.setTrimBefore(l,r.current)},[l,t,e,r]),(0,n.useLayoutEffect)(()=>{let a=e.current;a&&t&&a.setTrimAfter(d,r.current)},[d,t,e,r]),(0,n.useLayoutEffect)(()=>{let r=e.current;r&&t&&r.setMuted(u)},[u,t,e]),(0,n.useLayoutEffect)(()=>{let r=e.current;r&&t&&r.setVolume(c)},[c,t,e]),(0,n.useLayoutEffect)(()=>{let a=e.current;a&&t&&a.setPlaybackRate(m,r.current)},[m,t,e,r]),(0,n.useLayoutEffect)(()=>{let a=e.current;a&&t&&a.setGlobalPlaybackRate(f,r.current)},[f,t,e,r]),(0,n.useLayoutEffect)(()=>{let a=e.current;a&&t&&a.setLoop(y,r.current)},[y,t,e,r]),(0,n.useLayoutEffect)(()=>{let a=e.current;a&&t&&a.setSequenceDurationInFrames(g,r.current)},[g,t,e,r]),(0,n.useLayoutEffect)(()=>{let t=e.current;t&&t.setIsPremounting(w)},[w,t,e]),(0,n.useLayoutEffect)(()=>{let t=e.current;t&&t.setIsPostmounting(I)},[I,t,e]),(0,n.useLayoutEffect)(()=>{let a=e.current;a&&t&&a.setFps(p,r.current)},[p,t,e,r]),(0,n.useLayoutEffect)(()=>{let a=e.current;a&&t&&a.setSequenceOffset(h,r.current)},[h,t,e,r]),(0,n.useLayoutEffect)(()=>{let r=e.current;r&&t&&(r.seekTo(b).catch(()=>{}),o.Internals.Log.trace({logLevel:v,tag:"@remotion/media"},`[${S}] Updating target time to ${b.toFixed(3)}s`))},[b,v,t,S,e])},{useUnsafeVideoConfig:es,Timeline:el,SharedAudioContext:ed,usePlayerMutedState:eu,useMediaVolumeState:ec,useFrameForVolumeProp:em,evaluateVolume:ef,warnAboutTooHighVolume:ep,usePreload:eh,SequenceContext:ey}=o.Internals,eg=({src:e,playbackRate:t,logLevel:r,muted:a,volume:i,loopVolumeCurveBehavior:s,loop:l,trimAfter:d,trimBefore:c,name:m,showInTimeline:f,_remotionInternalStack:p,disallowFallbackToHtml5Audio:h,toneFrequency:y,audioStreamIndex:g,fallbackHtml5AudioProps:w,onError:I,credentials:b,requestInit:v,setMediaDurationInSeconds:S,style:k})=>{let C=es(),T=(0,o.ND)(),x=(0,n.useRef)(null),F=(0,n.useRef)(c),M=(0,n.useRef)(d),[A]=(0,n.useState)(v),[E,P]=(0,n.useState)(!1),[R,D]=(0,n.useState)(!1),[L]=el.usePlayingState(),{playbackRate:$}=o.Internals.usePlaybackRate(),O=(0,n.useContext)(ed),N=(0,o.C1)(),[B]=eu(),[V]=ec(),_=ef({frame:em(s??"repeat"),volume:i,mediaVolume:V});if(ep(_),!C)throw Error("No video config found");if(!e)throw TypeError("No `src` was passed to <NewAudioForPreview>.");let q=T/C.fps,z=(0,n.useRef)(q);z.current=q;let j=eh(e),U=(0,n.useContext)(ey),H=!!U?.premounting,W=!!U?.postmounting,K=(U?.absoluteFrom??0)/C.fps,J=(0,n.useContext)(o.Internals.BufferingContextReact);if(!J)throw Error("useMediaPlayback must be used inside a <BufferingContext>");let Q=a||B||_<=0,G=o.Internals.useIsPlayerBuffering(J),X=(0,n.useRef)(L&&!G),Y=(0,n.useRef)(H),Z=(0,n.useRef)(W),ee=(0,n.useRef)($),et=(0,n.useRef)(t),er=(0,n.useRef)(Q),ea=(0,n.useRef)(C.durationInFrames),eg=(0,n.useRef)(K);return(ei({mediaPlayerRef:x,mediaPlayerReady:E,currentTimeRef:z,playing:L,isPlayerBuffering:G,frame:T,trimBefore:c,trimAfter:d,effectiveMuted:Q,userPreferredVolume:_,playbackRate:t,globalPlaybackRate:$,fps:C.fps,sequenceOffset:K,loop:l,durationInFrames:C.durationInFrames,isPremounting:H,isPostmounting:W,currentTime:q,logLevel:r,label:"AudioForPreview"}),(0,n.useEffect)(()=>{if(!O||!O.audioContext)return;let{audioContext:e,gainNode:t,audioSyncAnchor:a,scheduleAudioNode:n,unscheduleAudioNode:i}=O;if(t){try{let s=new en({src:j,logLevel:r,sharedAudioContext:{audioContext:e,gainNode:t,audioSyncAnchor:a,scheduleAudioNode:n,unscheduleAudioNode:i},loop:l,trimAfter:M.current,trimBefore:F.current,fps:C.fps,canvas:null,playbackRate:et.current,audioStreamIndex:g??null,debugOverlay:!1,bufferState:N,isPostmounting:Z.current,isPremounting:Y.current,globalPlaybackRate:ee.current,durationInFrames:ea.current,onVideoFrameCallback:null,playing:X.current,sequenceOffset:eg.current,credentials:b,requestInit:A,tagType:"audio",getEffects:()=>[],getEffectChainState:()=>null});x.current=s,s.initialize(z.current,er.current).then(e=>{if("disposed"===e.type)return;let t=(e,t)=>
1{let[a,n]=eo({onError:I,error:e,disallowFallback:h,isClientSideRendering:!1,clientSideError:e});if("fail"===a)throw n;o.Internals.Log.warn({logLevel:r,tag:"@remotion/media"},t),D(!0)};if("unknown-container-format"===e.type){t(Error(`Unknown container format ${j}.`),`Unknown container format for ${j} (Supported formats: https://www.remotion.dev/docs/mediabunny/formats), falling back to <Html5Audio>`);return}if("network-error"===e.type){t(Error(`Network error fetching ${j}.`),`Network error fetching ${j}, falling back to <Html5Audio>`);return}if("cannot-decode"===e.type){t(Error(`Cannot decode ${j}.`),`Cannot decode ${j}, falling back to <Html5Audio>`);return}if("no-tracks"===e.type){t(Error(`No video or audio tracks found for ${j}.`),`No video or audio tracks found for ${j}, falling back to <Html5Audio>`);return}if("cannot-decode-prores"===e.type)throw Error(`Encountered ProRes media for ${j}. But this should never happen, since you used the <Audio> tag. Please report this as a bug.`);"success"===e.type&&(P(!0),S(e.durationInSeconds),o.Internals.Log.trace({logLevel:r,tag:"@remotion/media"},"[AudioForPreview] MediaPlayer initialized successfully"))}).catch(e=>{let[t,a]=eo({onError:I,error:e,disallowFallback:h,isClientSideRendering:!1,clientSideError:e});if("fail"===t)throw a;o.Internals.Log.error({logLevel:r,tag:"@remotion/media"},"[AudioForPreview] Failed to initialize MediaPlayer",e),D(!0)})}catch(a){let[e,t]=eo({error:a,onError:I,disallowFallback:h,isClientSideRendering:!1,clientSideError:a});if("fail"===e)throw t;o.Internals.Log.error({logLevel:r,tag:"@remotion/media"},"[AudioForPreview] MediaPlayer initialization failed",t),D(!0)}return()=>{x.current&&(o.Internals.Log.trace({logLevel:r,tag:"@remotion/media"},"[AudioForPreview] Disposing MediaPlayer"),x.current.dispose(),x.current=null),P(!1),D(!1)}}},[j,r,O,l,C.fps,g,h,N,I,b,A,S]),R&&!h)?(0,u.jsx)(o.Bb,{src:e,muted:a,volume:i,startFrom:c,endAt:d,playbackRate:t,loopVolumeCurveBehavior:s,name:m,loop:l,showInTimeline:f,style:k??void 0,_remotionInternalStack:p??void 0,toneFrequency:y,audioStreamIndex:g,pauseWhenBuffering:w?.pauseWhenBuffering,crossOrigin:w?.crossOrigin,...w}):null},ew=({loop:e=!1,src:t,logLevel:r,muted:a,name:i,volume:s,loopVolumeCurveBehavior:l,playbackRate:d=1,trimAfter:c,trimBefore:m,showInTimeline:f,_remotionInternalStack:p,disallowFallbackToHtml5Audio:h,toneFrequency:g,audioStreamIndex:w,fallbackHtml5AudioProps:I,onError:b,credentials:v,requestInit:S,setMediaDurationInSeconds:k,style:C})=>{let T=eh(t),x=o.Internals.useLogLevel(),F=(0,o.ND)(),M=(0,o.rf)(),A=F/M.fps;if(!(0,n.useMemo)(()=>null!==y({unloopedTimeInSeconds:A,playbackRate:d,loop:e,trimBefore:m,trimAfter:c,mediaDurationInSeconds:1/0,fps:M.fps,ifNoMediaDuration:"infinity",src:t}),[A,d,t,c,m,M.fps,e]))return null;if(!k)throw Error("setMediaDurationInSeconds is required");return(0,u.jsx)(eg,{audioStreamIndex:w,src:T,playbackRate:d,logLevel:r??x,muted:a??!1,volume:s??1,loopVolumeCurveBehavior:l??"repeat",loop:e,trimAfter:c,trimBefore:m,name:i,showInTimeline:f??!0,_remotionInternalStack:p,disallowFallbackToHtml5Audio:h??!1,toneFrequency:g,onError:b,credentials:v,requestInit:S,fallbackHtml5AudioProps:I,setMediaDurationInSeconds:k,style:C})},eI=()=>{let e=[],t={};return{addFrame:r=>{e.push(r.timestamp),t[r.timestamp]=r},clearBeforeThreshold:r=>{for(let a of e.slice())if(a+t[a].duration<r){if(a===e[e.length-1])continue;t[a].close(),delete t[a],e.splice(e.indexOf(a),1)}},deleteAll:()=>{for(let r of e)t[r].close(),delete t[r];e.length=0},getSamples:(r,a)=>{let n=[];for(let o=0;o<e.length;o++){let i=t[e[o]];if(!(i.timestamp+i.duration-1e-10<=r)){if(i.timestamp>=r+a-1e-10)break;n.push(i)}}return n},getOldestTimestamp:()=>e[0],getNewestTimestamp:()=>{if(0===e.length)return null;let r=t[e[e.length-1]];return r.timestamp+r.duration},getOpenTimestamps:()=>e}},eb={},ev=(e,t)=>
1{eb[e]||(eb[e]=!0,o.Internals.Log.warn({logLevel:t,tag:"@remotion/media"},`Audio from ${e} will need to be read from the beginning. https://www.remotion.dev/docs/media/support#matroska-limitation`))},eS=({audioSampleSink:e,isMatroska:t,startTimestamp:r,src:a,actualMatroskaTimestamps:n,logLevel:i})=>{let s=e.samples(t?0:Math.max(0,r-1.5));t&&ev(a,i);let l=null,d=eI(),u=Date.now(),c=async()=>{u=Date.now();let{value:e,done:t}=await s.next();if(t)return l=d.getNewestTimestamp(),null;let r=n.getRealTimestamp(e.timestamp);return null!==r&&r!==e.timestamp&&e.setTimestamp(r),n.observeTimestamp(e.timestamp),n.observeTimestamp(e.timestamp+e.duration),d.addFrame(e),e},m=async(e,t)=>{if(u=Date.now(),null!==l&&e>l)return d.clearBeforeThreshold(l-.2),[];let r=d.getSamples(e,t),a=d.getNewestTimestamp();if(null!==a&&a>=e+t-1e-10)return r;for(;;){let a=await c(),n=null===l?e:Math.min(e,l);if(d.clearBeforeThreshold(n-.2),null===a)break;if(!(a.timestamp+a.duration-1e-10<=e)){if(a.timestamp>=e+t-1e-10)break;r.push(a)}}return r},f=Promise.resolve([]);return{src:a,getSamples:(e,t)=>f=f.then(()=>m(e,t)),waitForCompletion:async()=>(await f,!0),canSatisfyRequestedTime:e=>{let t=d.getOldestTimestamp()??r;return null!==l&&e>l||t<e&&10>Math.abs(t-e)},logOpenFrames:()=>{let e=d.getOpenTimestamps();if(e.length>0){let t=e[0],r=e[e.length-1];o.Internals.Log.verbose({logLevel:i,tag:"@remotion/media"},"Open audio samples for src",a,`${t.toFixed(3)}...${r.toFixed(3)}`)}},getCacheStats:()=>({count:d.getOpenTimestamps().length,size:d.getOpenTimestamps().reduce((e,t)=>e+t,0)}),getLastUsed:()=>u,prepareForDeletion:()=>{d.deleteAll(),s.return().then(e=>{e.value&&e.value.close()}),l=null},startTimestamp:r,clearBeforeThreshold:d.clearBeforeThreshold,getOldestTimestamp:d.getOldestTimestamp,getNewestTimestamp:d.getNewestTimestamp}},ek=e=>0===e.length?"(none)":1===e.length?e[0].toFixed(3):`${e[0].toFixed(3)}...${e[e.length-1].toFixed(3)}`,eC=e=>null===e.format?e.codedHeight*e.codedWidth*4:e.allocationSize(),eT=async({logLevel:e,src:t,videoSampleSink:r,initialTimestampRequest:a})=>{let n=r.samples(J(a)),i={},s=[],l=!1,d=Date.now(),u=0,c=e=>{let t=s.indexOf(e);if(-1===t)throw Error(`Frame ${e} not found`);let r=s[t+1];return void 0===r?null:r-e},m=e=>{let t=c(e);return null!==t?t:l?i[e].duration??0:null},f=e=>c(e)??i[e].duration??0,p=e=>{u-=eC(i[e]),s.splice(s.indexOf(e),1),i[e].close(),delete i[e]},h=({logLevel:e,timestampInSeconds:r})=>{let a=[];for(let e of s.slice()){if(l&&e===s[s.length-1]||!i[e])continue;let t=m(e);null!==t&&e+t<r&&(p(e),a.push(e))}a.length>0&&o.Internals.Log.verbose({logLevel:e,tag:"@remotion/media"},`Deleted ${a.length} frame${1===a.length?"":"s"} ${ek(a)} for src ${t} because it is lower than ${r}. Remaining: ${ek(s)}`)},y=e=>{let t=s[s.length-1];if(void 0===t)return!1;if(!i[t]||J(t)>=J(e))return!0;let r=m(t);return null!==r&&J(t+r)>J(e)},g=(e,t)=>{i[e.timestamp]&&p(e.timestamp),i[e.timestamp]=e,s.push(e.timestamp),u+=eC(e),d=Date.now(),o.Internals.Log.trace({logLevel:t,tag:"@remotion/media"},`Added frame at ${e.timestamp}sec to bank`)},w=async(t,r,a)=>{for(;!y(t);){let o=await n.next();if(o.value&&g(o.value,r),o.done){l=!0;break}h({logLevel:e,timestampInSeconds:t-ex(a)})}d=Date.now()},I=async(t,r)=>{d=Date.now();let a=t;l&&J(a)>J(s[s.length-1])&&(a=s[s.length-1]),await w(a,e,r);for(let e=s.length-1;e>=0;e--){let t=i[s[e]];if(!t)return null;if(J(t.timestamp)<=J(a)||.001>=Math.abs(t.timestamp-a))return t}return i[s[0]]??null},b=async(e,t)=>await I(e,t)!==null,v=Promise.resolve(void 0),S=await n.next();if(!S.value)throw Error("No first frame found");let k=S.value.timestamp;o.Internals.Log.verbose({logLevel:e,tag:"@remotion/media"},`Creating keyframe bank from ${k}sec`),g(S.value,e);let C=()=>{if(0===s.length)return null;let e=s[0],t=s[s.length-1],r=f(t);return{firstTimestamp:e,lastTimestamp:t+r}};return{getFrameFromTimestamp:(e,t)=>v=v.then(()=>I(e,t)),prepareForDeletion:(e,t)=>{let r=C();r&&o.Internals.Log.verbose({logLevel:e,tag:"@remotion/media"},`Preparing for deletion (${t}) of keyframe bank from ${r?.firstTimestamp}sec to ${r?.lastTimestamp}sec`);let a=0;for(let e of s.slice())i[e]&&(p(e),a++);return n.return(),s.length=0,{framesDeleted:a}},hasTimestampInSecond:(e,t)=>v=v.then(()=>b(e,t)),addFrame:g,deleteFramesBeforeTimestamp:h,src:t,getOpenFrameCount:()=>({size:u,timestamps:s}),getLastUsed:()=>d,canSatisfyTimestamp:e=>{if(0===s.length)return!1;let t=J(e),r=J(s[0]),n=C();if(!n)return!1;let o=J(s[s.length-1]),i=J(n.lastTimestamp);return!!l&&t>o||(t<r?r===k&&t>=a:!(t-3>i))},getRangeOfTimestamps:C}},ex=e=>6/e,eF=(()=>{let e={},t=({src:t,bank:r})=>{e[t]=e[t]??[],e[t].push(r)},r=t=>{let r=0,a=0;for(let n in e)for(let i of e[n]){let{size:e,timestamps:s}=i.getOpenFrameCount();r+=s.length,a+=e,0!==e&&o.Internals.Log.verbose({logLevel:t,tag:"@remotion/media"},`Open frames for src ${n}: ${ek(s)}`)}o.Internals.Log.verbose({logLevel:t,tag:"@remotion/media"},`Video cache stats: ${r} open frames, ${a} bytes`)},a=()=>{let t=null,r=null,a=0;for(let n in e)for(let o of e[n]){let i=e[n].indexOf(o),s=o.getLastUsed();(null===t||s<t)&&(t=s,r={src:n,bank:o,index:i}),a++}if(!r)throw Error("No keyframe bank found");return{mostInThePastBank:r,numberOfBanks:a}},n=t=>{let{mostInThePastBank:{bank:r,src:n,index:i},numberOfBanks:s}=a();if(s<2)return{finish:!0};if(r){let a=r.getRangeOfTimestamps(),{framesDeleted:s}=r.prepareForDeletion(t,"deleted oldest keyframe bank to stay under max cache size");e[n].splice(i,1),a&&o.Internals.Log.verbose({logLevel:t,tag:"@remotion/media"},`Deleted ${s} frames for src ${n} from ${a?.firstTimestamp}sec to ${a?.lastTimestamp}sec to free up memory.`)}return{finish:!1}},i=(e,t)=>{let r=eA(),a=0;for(;r.totalSize>t&&a<3;){let{finish:i}=n(e);if(i)break;o.Internals.Log.verbose({logLevel:e,tag:"@remotion/media"},"Deleted oldest keyframe bank to stay under max cache size",(r.totalSize/1024/1024).toFixed(1),"out of",(t/1024/1024).toFixed(1)),r=eA(),a++}r.totalSize>t&&a>=3&&o.Internals.Log.warn({logLevel:e,tag:"@remotion/media"},`Exceeded max cache size after 3 attempts. Remaining cache size: ${(r.totalSize/1024/1024).toFixed(1)} MB, target was ${(t/1024/1024).toFixed(1)} MB.`)},s=({timestampInSeconds:t,src:a,logLevel:n,fps:i})=>{let s=t-ex(i);if(!e[a])return;let l=e[a];for(let t of l){let r=t.getRangeOfTimestamps();if(r){if(r.lastTimestamp<s){t.prepareForDeletion(n,"cleared before threshold "+s),o.Internals.Log.verbose({logLevel:n,tag:"@remotion/media"},`[Video] Cleared frames for src ${a} from ${r.firstTimestamp}sec to ${r.lastTimestamp}sec`);let i=l.indexOf(t);delete e[a][i]}else t.deleteFramesBeforeTimestamp({timestampInSeconds:s,logLevel:n})}}e[a]=e[a].filter(e=>void 0!==e),r(n)},l=async({timestamp:r,videoSampleSink:a,src:n,logLevel:i})=>{let s=e[n]??[],l=s?.find(e=>e.canSatisfyTimestamp(r));if(!l){o.Internals.Log.trace({logLevel:i,tag:"@remotion/media"},`Creating new keyframe bank for src ${n} at timestamp ${r}`);let e=await eT({videoSampleSink:a,logLevel:i,src:n,initialTimestampRequest:r});return t({src:n,bank:e}),e}if(l.canSatisfyTimestamp(r))return o.Internals.Log.trace({logLevel:i,tag:"@remotion/media"},`Keyframe bank exists and satisfies timestamp ${r}`),l;o.Internals.Log.verbose({logLevel:i,tag:"@remotion/media"},`Keyframe bank exists but frame at time ${r} does not exist anymore.`),l.prepareForDeletion(i,"already existed but evicted"),e[n]=e[n].filter(e=>e!==l);let d=await eT({videoSampleSink:a,initialTimestampRequest:r,logLevel:i,src:n});return t({src:n,bank:d}),d},d=async({timestamp:e,videoSampleSink:t,src:r,logLevel:a,maxCacheSize:n,fps:o})=>(i(a,n),s({timestampInSeconds:e,src:r,logLevel:a,fps:o}),await l({timestamp:e,videoSampleSink:t,src:r,logLevel:a})),u=Promise.resolve(void 0);return{requestKeyframeBank:({timestamp:e,videoSampleSink:t,src:r,logLevel:a,maxCacheSize:n,fps:o})=>u=u.then(()=>d({timestamp:e,videoSampleSink:t,src:r,logLevel:a,maxCacheSize:n,fps:o})),getCacheStats:()=>{let t=0,r=0;for(let a in e)for(let n of e[a]){let{timestamps:e,size:a}=n.getOpenFrameCount();if(t+=e.length,r+=a,0===a)continue}return{count:t,totalSize:r}},clearAll:t=>{for(let r of Object.keys(e)){for(let a of e[r])a.prepareForDeletion(t,"clearAll");e[r]=[]}e={}}}})(),eM=(()=>{let e=[],t=({timeInSeconds:t,src:r,audioSampleSink:a,isMatroska:n,actualMatroskaTimestamps:o,logLevel:i})=>{let s=eS({audioSampleSink:a,isMatroska:n,startTimestamp:t,src:r,actualMatroskaTimestamps:o,logLevel:i});return e.push(s),s},r=()=>{let t=null,r=null;for(let a of e){let e=a.getLastUsed();(null===t||e<t)&&(t=e,r=a)}return r},a=()=>{let t=r();t&&(t.prepareForDeletion(),e.splice(e.indexOf(t),1))},n=t=>{let r=new Set;for(let a=0;a<e.length;a++){let n=e[a],i=`${n.src}-${n.getOldestTimestamp()}-${n.getNewestTimestamp()}`;r.has(i)&&(n.prepareForDeletion(),e.splice(e.indexOf(n),1),o.Internals.Log.verbose({logLevel:t,tag:"@remotion/media"},`Deleted duplicate iterator for ${n.src}`)),r.add(i)}},i=async({src:r,timeInSeconds:i,audioSampleSink:s,isMatroska:l,actualMatroskaTimestamps:d,logLevel:u,maxCacheSize:c})=>{let m=0;for(;(await eA()).totalSize>c&&m<3;)a(),m++;for(let t of((await eA()).totalSize>c&&m>=3&&o.Internals.Log.warn({logLevel:u,tag:"@remotion/media"},`Audio cache: Exceeded max cache size after 3 attempts. Still ${(await eA()).totalSize} bytes used, target was ${c} bytes.`),e))if(t.src===r&&await t.waitForCompletion()&&t.canSatisfyRequestedTime(i))return t;for(let t=0;t<e.length;t++){let a=e[t];a.src===r&&a.startTimestamp===i&&(a.prepareForDeletion(),e.splice(e.indexOf(a),1))}return n(u),t({src:r,timeInSeconds:i,audioSampleSink:s,isMatroska:l,actualMatroskaTimestamps:d,logLevel:u})},s=Promise.resolve(void 0);return{getIterator:({src:e,timeInSeconds:t,audioSampleSink:r,isMatroska:a,actualMatroskaTimestamps:n,logLevel:o,maxCacheSize:l})=>s=s.then(()=>i({src:e,timeInSeconds:t,audioSampleSink:r,isMatroska:a,actualMatroskaTimestamps:n,logLevel:o,maxCacheSize:l})),getCacheStats:()=>{let t=0,r=0;for(let a of e){let{count:e,size:n}=a.getCacheStats();t+=e,r+=n}return{count:t,totalSize:r}},getIteratorMostInThePast:r,logOpenFrames:()=>{for(let t of e)t.logOpenFrames()},deleteDuplicateIterators:n}})(),eA=()=>{let e=eF.getCacheStats(),t=eM.getCacheStats();return{count:e.count+t.count,totalSize:e.totalSize+t.totalSize}},eE=e=>{if("undefined"!=typeof window&&void 0!==window.remotion_mediaCacheSizeInBytes&&null!==window.remotion_mediaCacheSizeInBytes)return window.remotion_mediaCacheSizeInBytes<251658240&&(0,o.n_)(Error(`The minimum value for the "mediaCacheSizeInBytes" prop is 240MB (251658240), got: ${window.remotion_mediaCacheSizeInBytes}`)),window.remotion_mediaCacheSizeInBytes>2097152e4&&(0,o.n_)(Error(`The maximum value for the "mediaCacheSizeInBytes" prop is 20GB (20971520000), got: ${window.remotion_mediaCacheSizeInBytes}`)),o.Internals.Log.verbose({logLevel:e,tag:"@remotion/media"},`Using cache size set using "mediaCacheSizeInBytes": ${(window.remotion_mediaCacheSizeInBytes/1024/1024).toFixed(1)} MB`),window.remotion_mediaCacheSizeInBytes;if("undefined"!=typeof window&&void 0!==window.remotion_initialMemoryAvailable&&null!==window.remotion_initialMemoryAvailable){let t=window.remotion_initialMemoryAvailable/2;return t<524288e3?(o.Internals.Log.verbose({logLevel:e,tag:"@remotion/media"}
1,"Using cache size set based on minimum value of 500MB (which is more than half of the available system memory!)"),524288e3):t>2097152e4?(o.Internals.Log.verbose({logLevel:e,tag:"@remotion/media"},"Using cache size set based on maximum value of 20GB (which is less than half of the available system memory)"),2097152e4):(o.Internals.Log.verbose({logLevel:e,tag:"@remotion/media"},`Using cache size set based on available memory (50% of available memory): ${(t/1024/1024).toFixed(1)} MB`),t)}return 1e9},eP=null,eR=e=>null!==eP?eP:eP=eE(e),eD=e=>{let t=n.useContext(o.Internals.MaxMediaCacheSizeContext);return null===t?eR(e):t},eL=(e,t)=>{if(1!==t)for(let r=0;r<e.length;r++){let a=e[r]*t;a<-32768?e[r]=-32768:a>32767?e[r]=32767:e[r]=a}},e$=()=>"undefined"!=typeof window&&window.remotion_sampleRate?window.remotion_sampleRate:48e3,eO=e=>e%1<1e-7?Math.floor(e):e%1>.9999999?Math.ceil(e):e,eN=({srcNumberOfChannels:e,sourceChannels:t,destination:r,targetFrames:a,chunkSize:n})=>{let o=(r,a,n)=>{let o=eO(r),i=eO(a),s=Math.floor(o),l=Math.ceil(o),d=o-s,u=i-Math.floor(i),c=Math.floor(i),m=0,f=0;d>0&&(m+=t[s*e+n]*(1-d),f+=1-d);for(let r=l;r<c;r++)m+=t[r*e+n],f+=1;return u>0&&(m+=t[c*e+n]*u,f+=u),m/f};for(let t=0;t<a;t++){let a=t*n,i=a+n;if(2===e)for(let n=0;n<e;n++)r[t*e+n]=o(a,i,n);if(1===e){let e=o(a,i,0);r[2*t+0]=e,r[2*t+1]=e}else if(4===e){let e=o(a,i,0),n=o(a,i,1),s=o(a,i,2),l=o(a,i,3),d=.5*(e+s),u=.5*(n+l);r[2*t+0]=d,r[2*t+1]=u}else if(6===e){let e=o(a,i,0),n=o(a,i,1),s=o(a,i,2),l=o(a,i,3),d=o(a,i,4),u=Math.sqrt(.5),c=e+u*(s+l),m=n+u*(s+d);r[2*t+0]=c,r[2*t+1]=m}else for(let n=0;n<e;n++)r[2*t+n]=o(a,i,n)}},eB=({behavior:e,loop:t,assetDurationInSeconds:r,fps:a,frame:n,startsAt:o})=>t&&"extend"!==e?n%(Math.floor(r*a)-o)+o:n+o,eV=e=>{let t=Math.abs(e%1);return t<1e-7?e<0?Math.ceil(e):Math.floor(e):t>.9999999?e<0?Math.floor(e):Math.ceil(e):e},e_=e=>Math.ceil(eV(e)),eq=({audioData:e,trimStartInSeconds:t,trimEndInSeconds:r,playbackRate:a,audioDataTimestamp:n,isLast:o})=>{let{numberOfChannels:i,sampleRate:s,numberOfFrames:l}=e,d=s/e$(),u=Math.floor(eV(t*e.sampleRate)),c=l-r*e.sampleRate-u,m=o?e_(c):Math.round(c),f=o?e_(c/d/a):Math.round(c/d/a);if(0===f)throw Error("Cannot resample - the given sample rate would result in less than 1 sample");let p=new Int16Array(i*m);if("f32"===e.format||"f32-planar"===e.format){let t=4*m,r=new ArrayBuffer(i*t);for(let a=0;a<i;a++)e.copyTo(new Float32Array(r,a*t,m),{planeIndex:a,frameOffset:u,frameCount:m,format:"f32-planar"});let a=new AudioData({format:"f32-planar",sampleRate:s,numberOfFrames:m,numberOfChannels:i,timestamp:e.timestamp,data:r});a.copyTo(p,{planeIndex:0,format:"s16",frameOffset:0,frameCount:m}),a.close()}else e.copyTo(p,{planeIndex:0,format:"s16",frameOffset:u,frameCount:m});let h=new Int16Array(2*f),y=m/f,g=u/e.sampleRate*1e6;return f===m&&2===i&&1===a?{data:p,numberOfFrames:f,timestamp:1e6*n+eV(g),durationInMicroSeconds:eV(f/e$()*1e6)}:(eN({srcNumberOfChannels:i,sourceChannels:p,destination:h,targetFrames:f,chunkSize:y}),{data:h,numberOfFrames:f,timestamp:1e6*n+eV(g),durationInMicroSeconds:eV(f/e$()*1e6)})},ez=e=>{let t=0,r=0,{timestamp:a}=e[0];for(let a of e)t+=a.numberOfFrames,r+=a.durationInMicroSeconds;let n=new Int16Array(2*t),o=0;for(let t of e)n.set(t.data,o),o+=t.data.length;return{data:n,numberOfFrames:t,timestamp:eV(a),durationInMicroSeconds:eV(r)}},ej=null,eU=()=>null!==new OffscreenCanvas(1,1).getContext("webgl2"),eH=()=>null!==ej?ej:ej=eU(),eW=e=>{let t=[];return{observeTimestamp:r=>{e&&t.push(r)},getRealTimestamp:r=>e?t.find(e=>.001>Math.abs(r-e))??null:r}},eK=()=>null,eJ=async e=>{try{return await e.getFormat()}catch(e){if(H(e))return"network-error";return null}},eQ=async(e,t,r,a)=>{let n=V({credentials:r,requestInit:a}),u=new s.II({formats:d.t6,source:new l.IK(e,{getRetryDelay:eK,...n?{requestInit:n}:void 0})}),c=await eJ(u),m=c===d.Dl||c===d.ad,f=async()=>{if("network-error"===c)return"network-error";if(null===c)return"unknown-container-format";let r=await u.getPrimaryVideoTrack();if(!r)return"no-video-track";if(await r.isLive())throw Error("Live streams are not currently supported by Remotion. Sorry! Source: "+e);if(await r.isRelativeToUnixEpoch())throw Error("Streams with UNIX timestamps are not currently supported by Remotion. Sorry! Source: "+e);if(!await r.canDecode())return"prores"===r.codec?"cannot-decode-prores":"cannot-decode";let a=new i.dL(r),n=new i.a6(r),s=await n.getFirstPacket({verifyKeyPackets:!0});return s?.sideData.alpha&&!eH()&&o.Internals.Log.warn({logLevel:t,tag:"@remotion/media"},`WebGL2 is not available, using the non-fast CPU path to decode alpha for ${e}.`),{sampleSink:a}},p=null,h=()=>p||(p=f()),y={},g=async e=>{if(null===c)return"unknown-container-format";if("network-error"===c)return"network-error";let[t,r]=await Promise.all([u.getPrimaryVideoTrack(),u.getAudioTracks()]),a=await U({videoTrack:t,audioTracks:r,audioStreamIndex:e});return a?await a.canDecode()?{sampleSink:new i.O8(a)}:"cannot-decode-audio":"no-audio-track"},w=e=>{let t=null===e?-1:e;return y[t]||(y[t]=g(e)),y[t]};return{getVideo:()=>h(),getAudio:e=>w(e),actualMatroskaTimestamps:eW(m),isMatroska:m,getDuration:()=>$(u)}},eG={},eX=({src:e,credentials:t,requestInit:r})=>JSON.stringify([e,t,B(r)]),eY=(e,t,r,a)=>{let n=N(a),i=eX({src:e,credentials:r,requestInit:n}),s=eG[i];return s||(o.Internals.Log.verbose({logLevel:t,tag:"@remotion/media"},`Sink for ${e} was not found, creating new sink`),s=eQ(e,t,r,n),eG[i]=s),s},eZ=async({src:e,timeInSeconds:t,durationInSeconds:r,logLevel:a,loop:n,playbackRate:o,audioStreamIndex:i,trimBefore:s,trimAfter:l,fps:d,maxCacheSize:u,credentials:c,requestInit:m})=>{let{getAudio:f,actualMatroskaTimestamps:p,isMatroska:h,getDuration:g}=await eY(e,a,c,m),w=null;n&&(w=await g());let I=await f(i);if("network-error"===I)return"network-error";if("no-audio-track"===I)return{data:null,durationInSeconds:null};if("cannot-decode-audio"===I)return"cannot-decode";if("unknown-container-format"===I)return"unknown-container-format";let b=y({loop:n,mediaDurationInSeconds:w,unloopedTimeInSeconds:t,src:e,trimAfter:l,playbackRate:o,trimBefore:s,fps:d,ifNoMediaDuration:"fail"});if(null===b)return{data:null,durationInSeconds:w};
1try{let t=await eM.getIterator({src:e,timeInSeconds:b,audioSampleSink:I.sampleSink,isMatroska:h,actualMatroskaTimestamps:p,logLevel:a,maxCacheSize:u}),n=r*o,i=await t.getSamples(b,n);eM.logOpenFrames();let s=[];for(let e=0;e<i.length;e++){let t=i[e];if(Math.abs(t.timestamp-(b+n))*t.sampleRate<1||t.timestamp+t.duration<=b)continue;let r=0===e,a=e===i.length-1,l=t.toAudioData(),d=0,u=0,c=null;if(r&&(d=eV(b-t.timestamp))<0){let e=Math.ceil(eV(-d*e$()));c={data:new Int16Array(2*e),numberOfFrames:e,timestamp:1e6*b,durationInMicroSeconds:e/e$()*1e6},d=0}a&&(u=Math.max(0,t.timestamp+t.duration-(b+n)));let m=eq({audioData:l,trimStartInSeconds:d,trimEndInSeconds:u,playbackRate:o,audioDataTimestamp:t.timestamp,isLast:a});l.close(),0!==m.numberOfFrames&&(c&&s.push(c),s.push(m))}if(0===s.length)return{data:null,durationInSeconds:w};return{data:ez(s),durationInSeconds:w}}catch(e){if(H(e))return"network-error";if(e.message.includes("Unsupported configuration"))return"cannot-decode";throw e}},e0=Promise.resolve(void 0),e1=e=>e0=e0.then(()=>eZ(e)),e2=async({src:e,timeInSeconds:t,logLevel:r,loop:a,trimAfter:n,trimBefore:i,playbackRate:s,fps:l,maxCacheSize:d,credentials:u,requestInit:c})=>{let m=await eY(e,r,u,c),[f,p]=await Promise.all([m.getVideo(),a?m.getDuration():Promise.resolve(null)]),h=a?p:null;if("no-video-track"===f)throw Error(`No video track found for ${e}`);if("cannot-decode"===f)return{type:"cannot-decode",durationInSeconds:h};if("cannot-decode-prores"===f)return{type:"cannot-decode-prores",durationInSeconds:h};if("unknown-container-format"===f)return{type:"unknown-container-format"};if("network-error"===f)return{type:"network-error"};if("cannot-decode-alpha"===f)return{type:"cannot-decode-alpha",durationInSeconds:h};let g=y({loop:a,mediaDurationInSeconds:h,unloopedTimeInSeconds:t,src:e,trimAfter:n,playbackRate:s,trimBefore:i,fps:l,ifNoMediaDuration:"fail"});if(null===g)return{type:"success",frame:null,rotation:0,durationInSeconds:await m.getDuration()};try{let t=await eF.requestKeyframeBank({videoSampleSink:f.sampleSink,timestamp:g,src:e,logLevel:r,maxCacheSize:d,fps:l});if(!t)return{type:"success",frame:null,rotation:0,durationInSeconds:await m.getDuration()};let a=await t.getFrameFromTimestamp(g,l),n=a?.rotation??0;return{type:"success",frame:a?.toVideoFrame()??null,rotation:n,durationInSeconds:await m.getDuration()}}catch(t){return o.Internals.Log.info({logLevel:r,tag:"@remotion/media"},`Error decoding ${e} at time ${g}: ${t}`,t),{type:"cannot-decode",durationInSeconds:h}}},e3=Promise.resolve(void 0),e4=e=>e3=e3.then(()=>e2(e)),e5=async({frame:e,rotation:t})=>{if(0===t){let t=await createImageBitmap(e);return e.close(),t}let r=90===t||270===t?e.displayHeight:e.displayWidth,a=90===t||270===t?e.displayWidth:e.displayHeight,n=new OffscreenCanvas(r,a),o=n.getContext("2d");if(!o)throw Error("Could not get 2d context");n.width=r,n.height=a,90===t?o.translate(r,0):180===t?o.translate(r,a):270===t&&o.translate(0,a),o.rotate(Math.PI/180*t),o.drawImage(e,0,0);let i=await createImageBitmap(n);return e.close(),i},e6=async({src:e,timeInSeconds:t,logLevel:r,durationInSeconds:a,playbackRate:n,includeAudio:o,includeVideo:i,loop:s,audioStreamIndex:l,trimAfter:d,trimBefore:u,fps:c,maxCacheSize:m,credentials:f,requestInit:p})=>{try{let[h,y]=await Promise.all([i?e4({src:e,timeInSeconds:t,logLevel:r,loop:s,trimAfter:d,playbackRate:n,trimBefore:u,fps:c,maxCacheSize:m,credentials:f,requestInit:p}):null,o?e1({src:e,timeInSeconds:t,durationInSeconds:a,logLevel:r,loop:s,playbackRate:n,audioStreamIndex:l,trimAfter:d,fps:c,trimBefore:u,maxCacheSize:m,credentials:f,requestInit:p}):null]);if(h?.type==="cannot-decode")return{type:"cannot-decode",durationInSeconds:h.durationInSeconds};if(h?.type==="cannot-decode-prores")return{type:"cannot-decode-prores",durationInSeconds:h.durationInSeconds};if(h?.type==="unknown-container-format")return{type:"unknown-container-format"};if(h?.type==="cannot-decode-alpha")return{type:"cannot-decode-alpha",durationInSeconds:h.durationInSeconds};if(h?.type==="network-error")return{type:"network-error"};if("unknown-container-format"===y)return{type:"unknown-container-format"};if("network-error"===y)return{type:"network-error"};if("cannot-decode"===y)return{type:"cannot-decode",durationInSeconds:h?.type==="success"?h.durationInSeconds:null};return{type:"success",frame:h?.frame?await e5({frame:h.frame,rotation:h.rotation}):null,audio:y?.data??null,durationInSeconds:y?.durationInSeconds??null}}catch(e){if(H(e))return{type:"network-error"};throw e}},e9=null,e7=e=>e9||(e9=new Promise(t=>{let r=a=>{"main-tab-ready"===a.data.type&&(t(),e.removeEventListener("message",r))};e.addEventListener("message",r)}));"undefined"!=typeof window&&window.remotion_broadcastChannel&&window.remotion_isMainTab&&(window.remotion_broadcastChannel.addEventListener("message",async e=>{let t=e.data;if("request"===t.type)try{let e=await e6({src:t.src,timeInSeconds:t.timeInSeconds,logLevel:t.logLevel,durationInSeconds:t.durationInSeconds,playbackRate:t.playbackRate,includeAudio:t.includeAudio,includeVideo:t.includeVideo,loop:t.loop,audioStreamIndex:t.audioStreamIndex,trimAfter:t.trimAfter,trimBefore:t.trimBefore,fps:t.fps,maxCacheSize:t.maxCacheSize,credentials:t.credentials,requestInit:t.requestInit});if("cannot-decode"===e.type){let r={type:"response-cannot-decode",id:t.id,durationInSeconds:e.durationInSeconds};window.remotion_broadcastChannel.postMessage(r);return}if("cannot-decode-prores"===e.type){let r={type:"response-cannot-decode-prores",id:t.
1id,durationInSeconds:e.durationInSeconds};window.remotion_broadcastChannel.postMessage(r);return}if("cannot-decode-alpha"===e.type){let r={type:"response-cannot-decode-alpha",id:t.id,durationInSeconds:e.durationInSeconds};window.remotion_broadcastChannel.postMessage(r);return}if("network-error"===e.type){let e={type:"response-network-error",id:t.id};window.remotion_broadcastChannel.postMessage(e);return}if("unknown-container-format"===e.type){let e={type:"response-unknown-container-format",id:t.id};window.remotion_broadcastChannel.postMessage(e);return}let{frame:r,audio:a,durationInSeconds:n}=e,o=r?await createImageBitmap(r):null;r&&r.close();let i={type:"response-success",id:t.id,frame:o,audio:a,durationInSeconds:n??null};window.remotion_broadcastChannel.postMessage(i)}catch(r){let e={type:"response-error",id:t.id,errorStack:r.stack??"No stack trace"};window.remotion_broadcastChannel.postMessage(e)}else if("main-tab-ready"===t.type);else throw Error("Invalid message: "+JSON.stringify(t))}),(a=window.remotion_broadcastChannel).postMessage({type:"main-tab-ready"}),setInterval(()=>{a.postMessage({type:"main-tab-ready"})},300));var e8=async({src:e,timeInSeconds:t,logLevel:r,durationInSeconds:a,playbackRate:n,includeAudio:o,includeVideo:i,isClientSideRendering:s,loop:l,audioStreamIndex:d,trimAfter:u,trimBefore:c,fps:m,maxCacheSize:f,credentials:p,requestInit:h})=>{let y;if(s||window.remotion_isMainTab)return e6({logLevel:r,src:e,timeInSeconds:t,durationInSeconds:a,playbackRate:n,includeAudio:o,includeVideo:i,loop:l,audioStreamIndex:d,trimAfter:u,trimBefore:c,fps:m,maxCacheSize:f,credentials:p,requestInit:h});await e7(window.remotion_broadcastChannel);let g=crypto.randomUUID(),w=new Promise((e,t)=>{let r=a=>{let n=a.data;if(n&&"main-tab-ready"!==n.type&&n.id===g){if("response-success"===n.type){e({type:"success",frame:n.frame?n.frame:null,audio:n.audio?n.audio:null,durationInSeconds:n.durationInSeconds?n.durationInSeconds:null}),window.remotion_broadcastChannel.removeEventListener("message",r);return}if("response-error"===n.type){t(n.errorStack),window.remotion_broadcastChannel.removeEventListener("message",r);return}if("response-cannot-decode"===n.type){e({type:"cannot-decode",durationInSeconds:n.durationInSeconds}),window.remotion_broadcastChannel.removeEventListener("message",r);return}if("response-cannot-decode-prores"===n.type){e({type:"cannot-decode-prores",durationInSeconds:n.durationInSeconds}),window.remotion_broadcastChannel.removeEventListener("message",r);return}if("response-network-error"===n.type){e({type:"network-error"}),window.remotion_broadcastChannel.removeEventListener("message",r);return}if("response-unknown-container-format"===n.type){e({type:"unknown-container-format"}),window.remotion_broadcastChannel.removeEventListener("message",r);return}if("response-cannot-decode-alpha"===n.type){e({type:"cannot-decode-alpha",durationInSeconds:n.durationInSeconds}),window.remotion_broadcastChannel.removeEventListener("message",r);return}throw Error(`Invalid message: ${JSON.stringify(n)}`)}};window.remotion_broadcastChannel.addEventListener("message",r)}),I={type:"request",src:e,timeInSeconds:t,id:g,logLevel:r,durationInSeconds:a,playbackRate:n,includeAudio:o,includeVideo:i,loop:l,audioStreamIndex:d,trimAfter:u,trimBefore:c,fps:m,maxCacheSize:f,credentials:p,requestInit:N(h)};return window.remotion_broadcastChannel.postMessage(I),Promise.race([w.then(e=>(clearTimeout(y),e)),new Promise((r,a)=>{y=setTimeout(()=>{a(Error(`Timeout while extracting frame at time ${t}sec from ${e}`))},Math.max(3e3,window.remotion_puppeteerTimeout-5e3))})])},te=({volume:e,playbackRate:t,src:r,muted:a,loopVolumeCurveBehavior:i,delayRenderRetries:s,delayRenderTimeoutInMilliseconds:l,logLevel:d,loop:c,fallbackHtml5AudioProps:m,audioStreamIndex:f,showInTimeline:p,style:h,name:y,disallowFallbackToHtml5Audio:g,toneFrequency:w,trimAfter:I,trimBefore:b,onError:v,credentials:S,requestInit:k})=>{let C=o.Internals.useLogLevel(),T=d??C,x=(0,o.ND)(),F=o.Internals.useTimelinePosition(),M=o.Internals.useUnsafeVideoConfig(),{registerRenderAsset:A,unregisterRenderAsset:E}=(0,n.useContext)(o.Internals.RenderAssetManager),P=o.Internals.useMediaStartsAt(),R=(0,o.W2)();if(!M)throw Error("No video config found");if(!r)throw TypeError("No `src` was passed to <Audio>.");let{fps:D}=M,{delayRender:L,continueRender:$}
1=(0,o.ww)(),[O,N]=(0,n.useState)(!1),[B]=(0,n.useState)(k),V=(0,n.useContext)(o.Internals.SequenceContext),_=(0,n.useMemo)(()=>`media-audio-${(0,o.MX)(r)}-${V?.cumulatedFrom}-${V?.relativeFrom}-${V?.durationInFrames}`,[r,V?.cumulatedFrom,V?.relativeFrom,V?.durationInFrames]),q=eD(T),z=o.Internals.useAudioEnabled();return((0,n.useLayoutEffect)(()=>{let n=x/D,d=1/D,u=!!z&&!a;if(!u||O)return;let m=L(`Extracting audio for frame ${x}`,{retries:s??void 0,timeoutInMilliseconds:l??void 0});return e8({src:r,timeInSeconds:n,durationInSeconds:d,playbackRate:t??1,logLevel:T,includeAudio:u,includeVideo:!1,isClientSideRendering:R.isClientSideRendering,loop:c??!1,audioStreamIndex:f??null,trimAfter:I,trimBefore:b,fps:D,maxCacheSize:q,credentials:S,requestInit:B}).then(t=>{let a=(e,t,r)=>{let[a,n]=eo({onError:v,error:e,disallowFallback:g??!1,isClientSideRendering:R.isClientSideRendering,clientSideError:t});"fail"===a&&(0,o.n_)(n),o.Internals.Log.warn({logLevel:T,tag:"@remotion/media"},r),N(!0)};if("unknown-container-format"===t.type){a(Error(`Unknown container format ${r}.`),Error(`Cannot render audio "${r}": Unknown container format. See supported formats: https://www.remotion.dev/docs/mediabunny/formats`),`Unknown container format for ${r} (Supported formats: https://www.remotion.dev/docs/mediabunny/formats), falling back to <Html5Audio>`);return}if("cannot-decode"===t.type){a(Error(`Cannot decode ${r}.`),Error(`Cannot render audio "${r}": The audio could not be decoded by the browser.`),`Cannot decode ${r}, falling back to <Html5Audio>`);return}if("cannot-decode-alpha"===t.type)throw Error(`Cannot decode alpha component for ${r}, and 'disallowFallbackToHtml5Audio' was set. But this should never happen, since you used the <Audio> tag. Please report this as a bug.`);if("cannot-decode-prores"===t.type)throw Error(`Encountered ProRes media for ${r}. But this should never happen, since you used the <Audio> tag. Please report this as a bug.`);if("network-error"===t.type){a(Error(`Network error fetching ${r}.`),Error(`Cannot render audio "${r}": Network error while fetching the audio (possibly CORS).`),`Network error fetching ${r}, falling back to <Html5Audio>`);return}let{audio:n,durationInSeconds:s}=t,l=eB({behavior:i??"repeat",loop:c??!1,assetDurationInSeconds:s??0,fps:D,frame:x,startsAt:P}),d=o.Internals.evaluateVolume({volume:e,frame:l,mediaVolume:1});o.Internals.warnAboutTooHighVolume(d),n&&d>0&&(eL(n.data,d),A({type:"inline-audio",id:_,audio:R.isClientSideRendering?n.data:Array.from(n.data),frame:F,timestamp:n.timestamp,duration:n.numberOfFrames/e$()*1e6,toneFrequency:w??1})),$(m)}).catch(e=>{(0,o.n_)(e)}),()=>{$(m),E(_)}},[F,$,L,s,l,g,R.isClientSideRendering,D,x,_,T,c,i,a,t,A,r,P,E,e,f,w,I,b,O,q,z,v,S,B]),O)?(0,u.jsx)(o.Md,{src:r,playbackRate:t,muted:a,loop:c,volume:e,delayRenderRetries:s,delayRenderTimeoutInMilliseconds:l,style:h,loopVolumeCurveBehavior:i,audioStreamIndex:f,useWebAudioApi:m?.useWebAudioApi,onError:m?.onError,toneFrequency:w,acceptableTimeShiftInSeconds:m?.acceptableTimeShiftInSeconds,preservePitch:m?.preservePitch??!0,name:y,showInTimeline:p}):null},{validateMediaProps:tt}=o.Internals,tr={src:{type:"asset",default:void 0,description:"Source",keyframable:!1},...o.Internals.baseSchema,...o.Internals.premountSchema,volume:{type:"number",min:0,max:20,step:.01,default:1,description:"Volume",hiddenFromList:!1},playbackRate:{type:"number",min:.1,step:.01,default:1,description:"Playback rate",hiddenFromList:!1,keyframable:!1},loop:{type:"boolean",default:!1,description:"Loop"}},ta=o.vj.withSchema({Component:e=>{let{name:t,showInTimeline:r,controls:a,from:i,durationInFrames:s,freeze:l,hidden:d,style:c,premountFor:m,postmountFor:f,...p}=e,y=(0,o.W2)(),g=a?o.Internals.getStackForControls(a):null,[w]=o.Internals.useMediaVolumeState(),I=o.Internals.useMediaStartsAt(),b=(0,o.rf)(),v=Math.min(s??1/0,Math.max(0,b.durationInFrames-(i??0))),S=o.Internals.useBasicMediaInTimeline({src:e.src,volume:e.volume,playbackRate:e.playbackRate??1,trimBefore:e.trimBefore,trimAfter:e.trimAfter,sequenceDurationInFrames:v,mediaType:"audio",displayName:t??"<Audio>
1",mediaVolume:w,mediaStartsAt:I,loop:e.loop??!1}),[k,C]=(0,n.useState)(null),T=(0,n.useMemo)(()=>h({loop:e.loop??!1,mediaDurationInSeconds:k,playbackRate:e.playbackRate??1,trimAfter:e.trimAfter,trimBefore:e.trimBefore,sequenceDurationInFrames:v,compFps:b.fps}),[e.loop,k,e.playbackRate,e.trimAfter,e.trimBefore,v,b.fps]),x=(0,n.useMemo)(()=>({type:"audio",data:S}),[S]),{effectivePostmountFor:F,effectivePremountFor:M,freezeFrame:A,isPremountingOrPostmounting:E,postmountingActive:P,premountingActive:R,premountingStyle:D}=o.Internals.usePremounting({from:i??0,durationInFrames:S.duration,premountFor:m??null,postmountFor:f??null,style:c??null,styleWhilePremounted:null,styleWhilePostmounted:null,hideWhilePremounted:"display-none"});if("string"!=typeof e.src)throw TypeError(`The \`<Audio>\` tag requires a string for \`src\`, but got ${JSON.stringify(e.src)} instead.`);return(tt({playbackRate:e.playbackRate,volume:e.volume},"Audio"),0===v)?null:(0,u.jsx)(o.fM,{frame:A,active:E,children:(0,u.jsx)(o.T9,{layout:"none",from:i??0,durationInFrames:S.duration,freeze:l,_remotionInternalIsMedia:x,_remotionInternalPremountDisplay:M||null,_remotionInternalPostmountDisplay:F||null,_remotionInternalIsPremounting:R,_remotionInternalIsPostmounting:P,name:t??"<Audio>",_remotionInternalDocumentationLink:void 0===t?"https://www.remotion.dev/docs/media/audio":void 0,controls:a,_remotionInternalLoopDisplay:T,showInTimeline:r??!0,hidden:d,children:y.isRendering?(0,u.jsx)(te,{...p,style:D??void 0}):(0,u.jsx)(ew,{name:t,...p,style:D,_remotionInternalStack:g,setMediaDurationInSeconds:C})})})},componentName:"<Audio>",componentIdentity:"dev.remotion.media.Audio",schema:tr,supportsEffects:!1}),tn=({durationInFrames:e,loop:t,playbackRate:r,trimAfter:a,trimBefore:n})=>t||void 0===a?e:Math.min(e??1/0,o.Internals.calculateMediaDuration({trimAfter:a,trimBefore:n,playbackRate:r,mediaDurationInFrames:1/0})),to=e=>`Cannot decode "${e}": it is encoded with Apple ProRes, which WebCodecs does not support natively. ProRes decoding is not enabled by default. Register the ProRes decoder by calling registerProresDecoder() from "@mediabunny/prores" in your entry point, before registerRoot(). See https://www.remotion.dev/docs/videos/prores.`;class ti extends Error{constructor(e){super(to(e)),this.name="ProResDecoderNotEnabledError"}}var ts=new Map,tl=(e,t)=>{let{width:r,height:a}=t;if(0===r||0===a)return;let n=ts.get(e);n&&n.width===r&&n.height===a||(n=new OffscreenCanvas(r,a),ts.set(e,n));let o=n.getContext("2d");o&&(o.clearRect(0,0,r,a),o.drawImage(t,0,0))},td=e=>ts.get(e)??null,tu=/\bobject-(contain|cover|fill|none|scale-down)\b/,tc=!1,tm=!1,tf=({style:e,className:t,logLevel:r})=>{!tc&&e?.objectFit&&(tc=!0,o.Internals.Log.warn({logLevel:r,tag:"@remotion/media"},"Use the `objectFit` prop instead of the `style` prop.")),!tm&&t&&tu.test(t)&&(tm=!0,o.Internals.Log.warn({logLevel:r,tag:"@remotion/media"},"Use the `objectFit` prop instead of `object-*` CSS class names."))},{useUnsafeVideoConfig:tp,Timeline:th,SharedAudioContext:ty,usePlayerMutedState:tg,useMediaVolumeState:tw,useFrameForVolumeProp:tI,evaluateVolume:tb,warnAboutTooHighVolume:tv,usePreload:tS,SequenceContext:tk,useEffectChainState:tC}=o.Internals,tT=({src:e,style:t,playbackRate:r,logLevel:a,className:i,muted:s,volume:l,loopVolumeCurveBehavior:d,onVideoFrame:c,showInTimeline:m,loop:f,trimAfter:p,trimBefore:h,_remotionInternalStack:y,disallowFallbackToOffthreadVideo:g,fallbackOffthreadVideoProps:w,audioStreamIndex:I,debugOverlay:b,headless:v,onError:S,credentials:k,requestInit:C,objectFit:T,_experimentalInitiallyDrawCachedFrame:x,effects:F,setMediaDurationInSeconds:M,refForOutline:A,...E})=>{let P=tS(e),R=(0,n.useRef)(null),D=tp(),L=(0,o.ND)(),$=(0,n.useRef)(null),O=(0,n.useRef)(h),N=(0,n.useRef)(p),B=(0,n.useRef)(c),[V]=(0,n.useState)(C),[_,q]=(0,n.use
1State)(!1),[z,j]=(0,n.useState)(!1),[U]=th.usePlayingState(),{playbackRate:H}=o.Internals.usePlaybackRate(),W=(0,n.useContext)(ty),K=(0,o.C1)(),J=(0,n.useCallback)(e=>{R.current=e,A.current=e},[A]),Q=(0,n.useCallback)(e=>{A.current=e},[A]),[G]=tg(),[X]=tw(),Y=tb({frame:tI(d),volume:l,mediaVolume:X});if(!D)throw Error("No video config found");tv(Y);let Z=tC(),ee=(0,n.useRef)(F);ee.current=F;let et=(0,n.useRef)(S);et.current=S;let er=(0,n.useRef)(Z);er.current=Z;let ea=(0,n.useContext)(tk),es=!!ea?.premounting,el=!!ea?.postmounting,ed=(ea?.absoluteFrom??0)/D.fps,eu=L/D.fps,ec=(0,n.useRef)(eu);ec.current=eu;let em=tS(P),ef=(0,n.useContext)(o.Internals.BufferingContextReact);if(!ef)throw Error("useMediaPlayback must be used inside a <BufferingContext>");let ep=s||G||Y<=0,eh=o.Internals.useIsPlayerBuffering(ef),ey=(0,n.useRef)(U&&!eh),eg=(0,n.useRef)(es),ew=(0,n.useRef)(el),eI=(0,n.useRef)(H),eb=(0,n.useRef)(r),ev=(0,n.useRef)(ep),eS=(0,n.useRef)(D.durationInFrames),ek=(0,n.useRef)(ed),eC=(0,n.useRef)(!1),eT=(0,n.useRef)(es);eT.current=es,(0,n.useLayoutEffect)(()=>{if(!x)return;let e=R.current;if(!e)return;let t=td(P);if(!t)return;e.width=t.width,e.height=t.height;let r=e.getContext("2d",{alpha:!0,desynchronized:!0});r&&r.drawImage(t,0,0)},[x,P]),(0,n.useLayoutEffect)(()=>{if(x)return()=>{let e=R.current;e&&eC.current&&!eT.current&&tl(P,e)}},[x,P]),(0,n.useEffect)(()=>{let e=W?.audioContext&&W.gainNode?{audioContext:W.audioContext,gainNode:W.gainNode,audioSyncAnchor:W.audioSyncAnchor,scheduleAudioNode:W.scheduleAudioNode,unscheduleAudioNode:W.unscheduleAudioNode}:null;try{let t=new en({canvas:R.current,src:em,logLevel:a,sharedAudioContext:e,loop:f,trimAfter:N.current,trimBefore:O.current,fps:D.fps,playbackRate:eb.current,audioStreamIndex:I,debugOverlay:b,bufferState:K,isPremounting:eg.current,isPostmounting:ew.current,globalPlaybackRate:eI.current,durationInFrames:eS.current,onVideoFrameCallback:B.current??null,playing:ey.current,sequenceOffset:ek.current,credentials:k,requestInit:V,tagType:"video",getEffects:()=>ee.current,getEffectChainState:(e,t)=>er.current?.get(e,t)});$.current=t,t.initialize(ec.current,ev.current).then(e=>{if("disposed"===e.type)return;let t=(e,t)=>{let[r,n]=eo({onError:et.current,error:e,disallowFallback:g,isClientSideRendering:!1,clientSideError:e});if("fail"===r)throw n;o.Internals.Log.warn({logLevel:a,tag:"@remotion/media"},t),j(!0)};if("unknown-container-format"===e.type){t(Error(`Unknown container format ${em}.`),`Unknown container format for ${em} (Supported formats: https://www.remotion.dev/docs/mediabunny/formats), falling back to <OffthreadVideo>`);return}if("network-error"===e.type){t(Error(`Network error fetching ${em}.`),`Network error fetching ${em}, falling back to <OffthreadVideo>`);return}if("cannot-decode"===e.type){t(Error(`Cannot decode ${em}.`),`Cannot decode ${em}, falling back to <OffthreadVideo>`);return}if("cannot-decode-prores"===e.type)throw new ti(em);if("no-tracks"===e.type){t(Error(`No video or audio tracks found for ${em}.`),`No video or audio tracks found for ${em}, falling back to <OffthreadVideo>`);return}"success"===e.type&&(q(!0),M(e.durationInSeconds),eC.current=!0)}).catch(e=>{if(e instanceof ti)throw et.current?.(e),e;let[t,r]=eo({onError:et.current,error:e,disallowFallback:g,isClientSideRendering:!1,clientSideError:e});if("fail"===t)throw r;o.Internals.Log.error({logLevel:a,tag:"@remotion/media"},"[VideoForPreview] Failed to initialize MediaPlayer",r),j(!0)})}catch(r){let[e,t]=eo({error:r,onError:et.current,disallowFallback:g,isClientSideRendering:!1,clientSideError:r});if("fail"===e)throw t;o.Internals.Log.error({logLevel:a,tag:"@remotion/media"},"[VideoForPreview] MediaPlayer initialization failed",t),j(!0)}return()=>{$.current&&(o.Internals.Log.trace({logLevel:a,tag:"@remotion/media"},"[VideoForPreview] Disposing MediaPlayer"),$.current.dispose(),$.current=null),q(!1),j(!1),eC.current=!1}},[I,K,b,g,a,f,em,W,D.fps,k,V,M]),tf({style:t,className:i,logLevel:a});let ex=(0,n.useMemo)(()=>[o.Internals.OBJECTFIT_CONTAIN_CLASS_NAME,i].filter(o.Internals.truthy).join(" "),[i]);ei({mediaPlayerRef:$,mediaPlayerReady:_,currentTimeRef:ec,playing:U,isPlayerBuffer
1ing:eh,frame:L,trimBefore:h,trimAfter:p,effectiveMuted:ep,userPreferredVolume:Y,playbackRate:r,globalPlaybackRate:H,fps:D.fps,sequenceOffset:ed,loop:f,durationInFrames:D.durationInFrames,isPremounting:es,isPostmounting:el,currentTime:eu,logLevel:a,label:"VideoForPreview"}),(0,n.useLayoutEffect)(()=>{let e=$.current;e&&_&&e.setDebugOverlay(b)},[b,_]),(0,n.useLayoutEffect)(()=>{let e=$.current;e&&_&&e.setVideoFrameCallback(c??null)},[c,_]),(0,n.useLayoutEffect)(()=>{let e=$.current;e&&_&&e.redrawVideoEffects().catch(()=>{})},[F,_,$]);let eF=(0,n.useMemo)(()=>({...t,objectFit:T}),[T,t]);return z&&!g?(0,u.jsx)(o.iC,{...E,ref:Q,src:P,style:eF,className:i,muted:s,volume:l,trimAfter:p,trimBefore:h,playbackRate:r,loopVolumeCurveBehavior:d,name:"<Html5Video> (fallback)",loop:f,showInTimeline:m,_remotionInternalStack:y??void 0,...w}):v?null:(0,u.jsx)("canvas",{...E,ref:J,style:eF,className:ex})},tx=e=>{let t=(0,o.ND)(),r=(0,o.rf)(),a=t/r.fps;return(0,n.useMemo)(()=>null!==y({unloopedTimeInSeconds:a,playbackRate:e.playbackRate,loop:e.loop,trimBefore:e.trimBefore,trimAfter:e.trimAfter,mediaDurationInSeconds:1/0,fps:r.fps,ifNoMediaDuration:"infinity",src:e.src}),[a,e.loop,e.playbackRate,e.src,r.fps,e.trimBefore,e.trimAfter])?(0,u.jsx)(tT,{...e}):null},tF=({volume:e,playbackRate:t,src:r,muted:a,loopVolumeCurveBehavior:i,delayRenderRetries:s,delayRenderTimeoutInMilliseconds:l,onVideoFrame:d,logLevel:c,loop:m,style:f,className:p,fallbackOffthreadVideoProps:h,audioStreamIndex:y,disallowFallbackToOffthreadVideo:g,_remotionInternalStack:w,toneFrequency:I,trimAfterValue:b,trimBeforeValue:v,headless:S,onError:k,credentials:C,requestInit:T,objectFit:x,effects:F,...M})=>{if(!r)throw TypeError("No `src` was passed to <Video>.");let A=(0,o.ND)(),E=o.Internals.useTimelinePosition(),{fps:P}=(0,o.rf)(),{registerRenderAsset:R,unregisterRenderAsset:D}=(0,n.useContext)(o.Internals.RenderAssetManager),L=o.Internals.useMediaStartsAt(),$=(0,n.useContext)(o.Internals.SequenceContext),O=(0,n.useMemo)(()=>`media-video-${(0,o.MX)(r)}-${$?.cumulatedFrom}-${$?.relativeFrom}-${$?.durationInFrames}`,[r,$?.cumulatedFrom,$?.relativeFrom,$?.durationInFrames]),N=(0,o.W2)(),{delayRender:B,continueRender:V,cancelRender:_}=(0,o.ww)(),q=(0,n.useRef)(null),[z,j]=(0,n.useState)(!1),[U]=(0,n.useState)(T),H=o.Internals.useAudioEnabled(),W=o.Internals.useVideoEnabled(),K=eD(c),J=o.Internals.useEffectChainState(),[Q,G]=(0,n.useState)(null);if(Q)throw Q;(0,n.useLayoutEffect)(()=>{if(!q.current&&!S||z)return;if(!q.current?.getContext&&!S)return G(Error("Canvas does not have .getContext() method available. This could be because <Video> was mounted inside an <svg> tag."));let n=A/P,u=1/P,f=B(`Extracting frame at time ${n} from ${r}`,{retries:s??void 0,timeoutInMilliseconds:l??void 0});return e8({src:r,timeInSeconds:n,durationInSeconds:u,playbackRate:t,logLevel:c,includeAudio:!!H&&!a,includeVideo:W,isClientSideRendering:N.isClientSideRendering,loop:m,audioStreamIndex:y,trimAfter:b,trimBefore:v,fps:P,maxCacheSize:K,credentials:C,requestInit:U}).then(async t=>{let a=(e,t,r,a)=>{if(N.isClientSideRendering){_(t);return}let[n,i]=eo({onError:k,error:e,disallowFallback:g,isClientSideRendering:N.isClientSideRendering,clientSideError:e});if("fail"===n){_(i);return}window.remotion_isMainTab&&o.Internals.Log.warn({logLevel:c,tag:"@remotion/media"},r),j({durationInSeconds:a})};if("unknown-container-format"===t.type){a(Error(`Unknown container format ${r}.`),Error(`Cannot render video "${r}": Unknown container format. See supported formats: https://www.remotion.dev/docs/mediabunny/formats`),`Unknown container format for ${r} (Supported formats: https://www.remotion.dev/docs/mediabunny/formats), falling back to <OffthreadVideo>`,null);return}if("cannot-decode"===t.type){a(Error(`Cannot decode ${r}.`),Error(`Cannot render video "${r}": The video could not be decoded by the browser.`),`Cannot decode ${r}, falling back to <OffthreadVideo>`,t.durationInSeconds);return}if("cannot-decode-prores"===t.type){let e=new ti(r);k?.(e),_(e);return}if("cannot-decode-alpha"===t.type){a(Error(`Cannot decode alpha component for ${r}.`),Error(`Cannot render video "${r}": The alpha channel could not be decoded by the browser.`),`Cannot decode alpha component for ${r}, falling back to <OffthreadVideo>`,t.durationInSeconds);return}if("network-error"===t.type){a(Error(`Network error fetching ${r}.`),Error(`Cannot render video "${r}": Network error while fetching the video (possibly CORS).`),`Network error fetching ${r} (no CORS?), falling back to <OffthreadVideo>`,null);return}let{frame:n,audio:s,durationInSeconds:l}=t;if(n){d?.(n);let e=q.current?.getContext("2d",{alpha:!0});if(e&&(e.canvas.width=n.width,e.canvas.height=n.height,e.canvas.style.aspectRatio=`${e.canvas.width} / ${e.canvas.height}
1`,e.drawImage(n,0,0),F.length>0&&!await o.Internals.runEffectChain({state:J.get(n.width,n.height),source:e.canvas,effects:F,output:e.canvas,width:n.width,height:n.height}))){n.close();return}n.close()}else if(W){let e=q.current?.getContext("2d",{alpha:!0});e&&e.clearRect(0,0,e.canvas.width,e.canvas.height)}let u=eB({behavior:i,loop:m,assetDurationInSeconds:l??0,fps:P,frame:A,startsAt:L}),p=o.Internals.evaluateVolume({volume:e,frame:u,mediaVolume:1});o.Internals.warnAboutTooHighVolume(p),s&&p>0&&(eL(s.data,p),R({type:"inline-audio",id:O,audio:N.isClientSideRendering?s.data:Array.from(s.data),frame:E,timestamp:s.timestamp,duration:s.numberOfFrames/e$()*1e6,toneFrequency:I})),V(f)}).catch(e=>{_(e)}),()=>{V(f),D(O)}},[E,V,B,s,l,N.isClientSideRendering,P,A,O,c,m,i,a,d,t,R,r,L,D,e,z,y,g,I,b,v,H,W,K,_,S,k,C,J,F,U]),tf({style:f,className:p,logLevel:c});let X=(0,n.useMemo)(()=>[o.Internals.OBJECTFIT_CONTAIN_CLASS_NAME,p].filter(o.Internals.truthy).join(" "),[p]),Y=(0,n.useMemo)(()=>({...f,objectFit:x}),[x,f]);if(z){let n=(0,u.jsx)(o.Internals.InnerOffthreadVideo,{...M,src:r,playbackRate:t??1,muted:a??!1,acceptableTimeShiftInSeconds:h?.acceptableTimeShiftInSeconds,loopVolumeCurveBehavior:i??"repeat",delayRenderRetries:s??void 0,delayRenderTimeoutInMilliseconds:l??void 0,name:"Fallback to <OffthreadVideo>",style:Y,allowAmplificationDuringRender:!0,transparent:h?.transparent??!0,toneMapped:h?.toneMapped??!0,audioStreamIndex:y??0,className:p,onVideoFrame:d,volume:e,id:O,onError:h?.onError,toneFrequency:I,showInTimeline:!1,crossOrigin:h?.crossOrigin,onAutoPlayError:h?.onAutoPlayError??null,pauseWhenBuffering:h?.pauseWhenBuffering??!1,trimAfter:b,trimBefore:v,useWebAudioApi:h?.useWebAudioApi??!1,preservePitch:h?.preservePitch??!0,startFrom:void 0,endAt:void 0,_remotionInternalStack:w,_remotionInternalNativeLoopPassed:!1}
1);if(m){if(!z.durationInSeconds){let e=Error(`Cannot render video ${r}: @remotion/media was unable to render, and fell back to <OffthreadVideo>. Also, "loop" was set, but <OffthreadVideo> does not support looping and @remotion/media could also not determine the duration of the video.`);throw _(e),e}return(0,u.jsx)(o.rN,{layout:"none",durationInFrames:o.Internals.calculateMediaDuration({trimAfter:b,mediaDurationInFrames:z.durationInSeconds*P,playbackRate:t,trimBefore:v}),children:n})}return n}return S?null:(0,u.jsx)("canvas",{...M,ref:q,style:Y,className:X})},{validateMediaTrimProps:tM,resolveTrimProps:tA,validateMediaProps:tE,useCropStyle:tP}=o.Internals,tR={src:{type:"asset",default:void 0,description:"Source",keyframable:!1},...o.Internals.baseSchema,...o.Internals.premountSchema,volume:{type:"number",min:0,max:20,step:.01,default:1,description:"Volume",hiddenFromList:!1},playbackRate:{type:"number",min:.1,step:.01,default:1,description:"Playback rate",hiddenFromList:!1,keyframable:!1},muted:{type:"boolean",default:!1,description:"Muted"},loop:{type:"boolean",default:!1,description:"Loop"},...o.Internals.transformSchema,...o.vj.backgroundSchema,...o.vj.borderSchema,...o.vj.borderRadiusSchema,...o.vj.cropSchema},tD=({src:e,audioStreamIndex:t,className:r,delayRenderRetries:a,delayRenderTimeoutInMilliseconds:n,disallowFallbackToOffthreadVideo:i,fallbackOffthreadVideoProps:s,logLevel:l,loop:d,loopVolumeCurveBehavior:c,muted:m,onVideoFrame:f,playbackRate:p,style:h,trimAfter:y,trimBefore:g,volume:w,_remotionInternalStack:I,toneFrequency:b,showInTimeline:v,debugOverlay:S,headless:k,onError:C,credentials:T,requestInit:x,controls:F,objectFit:M,_experimentalInitiallyDrawCachedFrame:A,effects:E,setMediaDurationInSeconds:P,refForOutline:R,...D})=>{let L=(0,o.W2)();if("string"!=typeof e)throw TypeError(`The \`<Video>\` tag requires a string for \`src\`, but got ${JSON.stringify(e)} instead.`);tM({startFrom:void 0,endAt:void 0,trimBefore:g,trimAfter:y});let{trimBeforeValue:$,trimAfterValue:O}=tA({startFrom:void 0,endAt:void 0,trimBefore:g,trimAfter:y});return(tE({playbackRate:p,volume:w},"Video"),L.isRendering)?(0,u.jsx)(tF,{...D,audioStreamIndex:t??0,className:r,delayRenderRetries:a??null,delayRenderTimeoutInMilliseconds:n??null,disallowFallbackToOffthreadVideo:i??!1,fallbackOffthreadVideoProps:s,logLevel:l,loop:d,loopVolumeCurveBehavior:c,muted:m,onVideoFrame:f,playbackRate:p,src:e,_remotionInternalStack:I,style:h,volume:w,toneFrequency:b,trimAfterValue:O,trimBeforeValue:$,headless:k,onError:C,credentials:T,requestInit:x,objectFit:M,effects:E}):(0,u.jsx)(tx,{...D,setMediaDurationInSeconds:P,audioStreamIndex:t??0,className:r,logLevel:l,loop:d,loopVolumeCurveBehavior:c,muted:m,onVideoFrame:f,playbackRate:p,src:e,style:h,volume:w,showInTimeline:v,trimAfter:O,trimBefore:$,_remotionInternalStack:I??null,disallowFallbackToOffthreadVideo:i,fallbackOffthreadVideoProps:s,debugOverlay:S??!1,headless:k??!1,onError:C,credentials:T,requestInit:x,controls:F,objectFit:M,effects:E,_experimentalInitiallyDrawCachedFrame:A,refForOutline:R})},tL=o.vj.withSchema({Component:({src:e,audioStreamIndex:t,className:r,delayRenderRetries:a,delayRenderTimeoutInMilliseconds:i,disallowFallbackToOffthreadVideo:s,fallbackOffthreadVideoProps:l,logLevel:d,loop:c,loopVolumeCurveBehavior:m,muted:f,name:p,onVideoFrame:y,playbackRate:g,showInTimeline:w,style:I,trimAfter:b,trimBefore:v,volume:S,toneFrequency:k,debugOverlay:C,headless:T,onError:x,credentials:F,requestInit:M,controls:A,objectFit:E,_experimentalInitiallyDrawCachedFrame:P,effects:R,durationInFrames:D,from:L,freeze:$,hidden:O,premountFor:N,postmountFor:B,styleWhilePremounted:V,styleWhilePostmounted:_,cropLeft:q,cropRight:z,cropTop:j,cropBottom:U,...H})=>{let W=A?o.Internals.getStackForControls(A)??void 0:void 0,K=o.Internals.useLogLevel(),[J]=o.Internals.useMediaVolumeState(),Q=o.Internals.useMediaStartsAt(),G=(0,o.rf)(),X=Math.min(D??1/0,Math.max(0,G.durationInFrames-(L??0))),Y=tn({durationInFrames:D,loop:c??!1,playbackRate:g??1,trimAfter:b,trimBefore:v}),Z=o.Internals.useBasicMediaInTimeline({src:e,volume:S,playbackRate:g??1,trimBefore:v,trimAfter:b,sequenceDurationInFrames:X,mediaType:"video",displayName:p??"<Video>
1",mediaVolume:J,mediaStartsAt:Q,loop:c??!1}),[ee,et]=(0,n.useState)(null),er=(0,n.useMemo)(()=>h({loop:c??!1,mediaDurationInSeconds:ee,playbackRate:g??1,trimAfter:b,trimBefore:v,sequenceDurationInFrames:X,compFps:G.fps}),[c,ee,g,b,v,X,G.fps]),ea=(0,n.useMemo)(()=>({type:"video",data:Z}),[Z]),en=o.Internals.useMemoizedEffects({effects:R??[],overrideId:A?.overrideId??null}),eo=o.Internals.useMemoizedEffectDefinitions(R??[]),ei=n.useRef(null),{effectivePostmountFor:es,effectivePremountFor:el,freezeFrame:ed,isPremountingOrPostmounting:eu,postmountingActive:ec,premountingActive:em,premountingStyle:ef}=o.Internals.usePremounting({from:L??0,durationInFrames:Y??1/0,premountFor:N??null,postmountFor:B??null,style:I??null,styleWhilePremounted:V??null,styleWhilePostmounted:_??null,hideWhilePremounted:"display-none"}),ep=tP({cropLeft:q,cropRight:z,cropTop:j,cropBottom:U,style:ef,componentName:"<Video />"});return 0===X?null:(0,u.jsx)(o.fM,{frame:ed,active:eu,children:(0,u.jsx)(o.T9,{layout:"none",from:L??0,durationInFrames:Y,freeze:$,_remotionInternalIsMedia:ea,_remotionInternalPremountDisplay:el||null,_remotionInternalPostmountDisplay:es||null,_remotionInternalIsPremounting:em,_remotionInternalIsPostmounting:ec,name:p??"<Video>",_remotionInternalDocumentationLink:void 0===p?"https://www.remotion.dev/docs/media/video":void 0,controls:A,_remotionInternalLoopDisplay:er,_remotionInternalEffects:eo,outlineRef:ei,showInTimeline:w??!0,hidden:O,children:(0,u.jsx)(tD,{...H,audioStreamIndex:t??0,className:r,delayRenderRetries:a??null,delayRenderTimeoutInMilliseconds:i??null,disallowFallbackToOffthreadVideo:s??!1,fallbackOffthreadVideoProps:l??{},logLevel:d??K,loop:c??!1,loopVolumeCurveBehavior:m??"repeat",muted:f??!1,onVideoFrame:y,playbackRate:g??1,showInTimeline:w??!0,src:e,style:ep??{},trimAfter:b,trimBefore:v,volume:S??1,toneFrequency:k??1,_remotionInternalStack:W,debugOverlay:C??!1,headless:T??!1,onError:x,credentials:F,requestInit:M,controls:A,objectFit:E??"contain",_experimentalInitiallyDrawCachedFrame:P??!1,effects:en,setMediaDurationInSeconds:et,refForOutline:ei})})})},componentName:"<Video>",componentIdentity:"dev.remotion.media.Video",schema:tR,supportsEffects:!0})}}]);
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.