@omnimedia/omnitool 1.1.0-45 → 1.1.0-46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omnimedia/omnitool",
3
- "version": "1.1.0-45",
3
+ "version": "1.1.0-46",
4
4
  "description": "open source video processing tools",
5
5
  "license": "MIT",
6
6
  "author": "Przemysław Gałęzki",
@@ -12,14 +12,14 @@ export class ResourcePool {
12
12
  async store(datafile: Datafile) {
13
13
  const media = await Media.analyze(datafile)
14
14
  const {hash} = media.datafile.checksum
15
- const {filename, bytes, url} = media.datafile
15
+ const {filename, bytes, url, blob} = media.datafile
16
16
 
17
17
  if (this.#map.has(hash)) {
18
18
  const alreadyExists = this.#map.require(hash)
19
19
  alreadyExists.filename = filename
20
20
  }
21
21
  else
22
- this.#map.set(hash, {kind: "media", filename, bytes, url})
22
+ this.#map.set(hash, {kind: "media", filename, bytes, url, blob})
23
23
 
24
24
  return media
25
25
  }
@@ -4,6 +4,7 @@ export namespace Resource {
4
4
  kind: "media"
5
5
  filename: string
6
6
  bytes: Uint8Array
7
+ blob: Blob
7
8
  url: string
8
9
  }
9
10
 
@@ -5,6 +5,7 @@ export class Datafile {
5
5
  constructor(
6
6
  public url: string,
7
7
  public bytes: Uint8Array,
8
+ public blob: Blob,
8
9
  public filename: string,
9
10
  public checksum: Checksum,
10
11
  ) {}
@@ -15,7 +16,7 @@ export class Datafile {
15
16
  const checksum = await Checksum.make(bytes)
16
17
  const filename = name ?? checksum.nickname
17
18
  const url = URL.createObjectURL(file)
18
- return new this(url, bytes, filename, checksum)
19
+ return new this(url, bytes, file, filename, checksum)
19
20
  }
20
21
 
21
22
  static async load(path: string) {
@@ -2412,7 +2412,7 @@ vec4 transition(vec2 uv) {
2412
2412
  vec2 uv = vTextureCoord.xy;
2413
2413
  gl_FragColor = transition(vTextureCoord);
2414
2414
  }
2415
- `;function Va({name:n,renderer:e}){let t=La.default.find(c=>c.name===n),r=new xt,o=new Kt,i=new Ir({}),s=new Ir({}),a=new To({glProgram:new vo({vertex:Na,fragment:Ua(t.glsl)}),resources:{from:i,to:s,uniforms:{...As.basics,...As.custom(t)}}});return r.filters=[a],{render({width:c,height:l,from:u,to:d,progress:f}){return(r.width!==c||r.height!==l)&&(r.setSize({width:c,height:l}),o.source.resize(c,l)),i.resource=u,s.resource=d,i.update(),s.update(),a.resources.uniforms.uniforms.progress=f,e.render({container:r,target:o,clear:!1,width:c,height:l}),o}}}var Xn=class{pixi;static async setup(){let e=await Is({width:1920,height:1080,preference:"webgl",background:"black",preferWebGLVersion:2}),t=new yo;return t.interactive=!0,new this({renderer:e,stage:t})}constructor(e){this.pixi=e}#e=new Map;#t=new Map;async composite(e){let{stage:t,renderer:r}=this.pixi;this.#l(this.#c(e));let{dispose:o}=await this.#r(e,t);r.render(t);let i=new VideoFrame(r.canvas,{timestamp:0,duration:0});return o(),i}async#r(e,t){if(Array.isArray(e)){e.reverse();let r=[];for(let o of e){let i=await this.#r(o,t);r.push(i.dispose)}return{dispose:()=>r.forEach(o=>o())}}switch(e.kind){case"text":return this.#n(e,t);case"image":return this.#o(e,t);case"transition":return this.#a(e,t);case"gap":return this.pixi?.renderer.clear(),{dispose:()=>{}};default:return console.warn("Unknown layer kind",e.kind),{dispose:()=>{}}}}#n(e,t){let r=this.#i(e);return this.#s(r,e.matrix),t.addChild(r),{dispose:()=>{}}}#o(e,t){let r=Kt.from(e.frame),o=this.#i(e);return o.texture=r,this.#s(o,e.matrix),t.addChild(o),{dispose:()=>{r.destroy(!0),e.frame.close()}}}#a({from:e,to:t,progress:r,name:o},i){let a=(this.#e.get(o)??(this.#e.set(o,Va({name:"circle",renderer:this.pixi.renderer})),this.#e.get(o))).render({from:e,to:t,progress:r,width:e.displayWidth,height:e.displayHeight}),c=new xt(a);return i.addChild(c),{dispose:()=>c.destroy(!1)}}#s(e,t){if(!t)return;let r=Ra(t);e.setFromMatrix(r)}#i(e){let t=this.#t.get(e.id);if(t)return t;switch(e.kind){case"text":{let r=new kr({text:e.content,style:e.style});return r.onmouseenter=()=>console.log("enter text"),this.#t.set(e.id,r).get(e.id)}case"image":{let r=new xt;return r.onmouseenter=()=>console.log("enter"),this.#t.set(e.id,r).get(e.id)}}}#c(e){let t=new Set,r=o=>{if(Array.isArray(o))for(let i of o)r(i);else t.add(o.id)};return r(e),t}#l(e){for(let t of this.#t.keys())e.has(t)||(this.#t.get(t).destroy(!0),this.#t.delete(t))}};var Ha=n=>$r.host(e=>({async world(){n.count++}}));async function je(n){return n instanceof Blob?new wr(n):new Tr(n)}var Kn=class{machina;thread;compositor;static async setup(e){let t=new qn,r=await $r.thread({label:"OmnitoolDriver",workerUrl:e?.workerUrl??"/node_modules/@omnimedia/omnitool/x/driver/driver.worker.bundle.min.js",setupHost:Ha(t)}),o=await Xn.setup();return new this(t,r,o)}constructor(e,t,r){this.machina=e,this.thread=t,this.compositor=r}async hello(){return this.thread.work.hello()}async getAudioDuration(e){let r=await new he({source:await je(e),formats:Oe}).getPrimaryAudioTrack();if(!r)throw new Error("primary audio track not found");return await r.computeDuration()}async getVideoDuration(e){return await(await new he({source:await je(e),formats:Oe}).getPrimaryVideoTrack())?.computeDuration()}decodeVideo(e){let t=null,r=new TransformStream({async transform(o,i){let s=await e.onFrame?.(o)??o;t?.close(),i.enqueue(s),t=s}});return this.thread.work.decodeVideo[wt]({transfer:[r.writable]})({source:e.source,video:r.writable,start:e.start,end:e.end}),r.readable}decodeAudio(e){let t=new TransformStream;return this.thread.work.decodeAudio[wt]({transfer:[t.writable]})({source:e.source,audio:t.writable,start:e.start,end:e.end}),t.readable}async encode({video:e,audio:t,config:r}){let i=await(await window.showSaveFilePicker()).createWritable(),s=new WritableStream({async write(a){await i.write(a)},async close(){await i.close()}});return await this.thread.work.encode[wt]({transfer:[t??[],e??[],s]})({video:e,audio:t,config:r,bridge:s})}async composite(e){return await this.compositor.composite(e)}};function Wa(n,e){document.querySelector(".export").addEventListener("click",()=>{n.render(e).then(()=>console.log("done"))})}var H;(function(n){n[n.Sequence=0]="Sequence",n[n.Stack=1]="Stack",n[n.Video=2]="Video",n[n.Audio=3]="Audio",n[n.Text=4]="Text",n[n.Gap=5]="Gap",n[n.Spatial=6]="Spatial",n[n.Transition=7]="Transition",n[n.TextStyle=8]="TextStyle"})(H||(H={}));var Qn;(function(n){n[n.Crossfade=0]="Crossfade"})(Qn||(Qn={}));var Yn=class{datafile;duration=0;hasVideo=!1;hasAudio=!1;constructor(e){this.datafile=e}static async analyze(e){let t=new this(e),r=await this.duration(e.url)*1e3;t.duration=r;let{video:o,audio:i}=await this.#e(e.url);return t.hasAudio=i,t.hasVideo=o,t}static async duration(e){return new he({formats:Oe,source:await je(e)}).computeDuration()}static async#e(e){let t=new he({formats:Oe,source:await je(e)});return{audio:!!await t.getPrimaryAudioTrack(),video:!!await t.getPrimaryVideoTrack()}}};var Jn=class{#e=new Nr;async store(e){let t=await Yn.analyze(e),{hash:r}=t.datafile.checksum,{filename:o,bytes:i,url:s}=t.datafile;if(this.#e.has(r)){let a=this.#e.require(r);a.filename=o}else this.#e.set(r,{kind:"media",filename:o,bytes:i,url:s});return t}require(e){return this.#e.require(e)}};var Zn=class n{videoTrack;options;#e;#t=new Map;#r=[0,0];constructor(e,t){this.videoTrack=e,this.options=t,this.#e=new fr(e,t.canvasSinkOptions)}static async init(e,t){let o=await new he({formats:Oe,source:await je(e)}).getPrimaryVideoTrack();if(o)return new n(o,{frequency:t.frequency??1,canvasSinkOptions:t.canvasSinkOptions??{width:80,height:50,fit:"fill"},onChange:t.onChange,onPlaceholders:t.onPlaceholders});throw new Error("Source has no video track")}set frequency(e){e!==this.options.frequency&&(this.options.frequency=e,this.#c())}get frequency(){return this.options.frequency}#n([e,t],r=1){let o=t-e;return[e-o*r,t+o*r]}async#o(){let[e,t]=this.#r,r=new Set,o=await this.videoTrack.computeDuration();for(let i=Math.max(0,e);i<=t;i+=this.options.frequency)i>=0&&i<=o&&r.add(i);this.options.onPlaceholders?.([...r])}async#a(){let[e,t]=this.#r,r=new Set,o=await this.videoTrack.computeDuration();for(let c=Math.max(0,e);c<=t;c+=this.options.frequency)c>=0&&c<=o&&r.add(c);let i=[...r].filter(c=>!this.#t.has(c)),s=0;for await(let c of this.#e.canvasesAtTimestamps(i))if(c){let l=i[s++];this.#t.set(l,c)}for(let c of this.#t.keys())r.has(c)||this.#t.delete(c);let a=[...this.#t.entries()].map(([c,l])=>({time:c,canvas:l}));this.options.onChange(a)}set range(e){let[t,r]=e,o=r-t,[i,s]=this.#r,a=i+o,c=s-o,l=t<a,u=r>c;!l&&!u||(this.#r=this.#n(e,2),this.#c())}#s=null;#i=!1;async#c(){if(this.#o(),this.#s){this.#i=!0;return}this.#s=this.#a(),await this.#s,this.#s=null,this.#i&&(this.#i=!1,await this.#c())}getThumbnail(e){return this.#t.get(e)}};function ne(n,e,t,r){return new(t||(t=Promise))((function(o,i){function s(l){try{c(r.next(l))}catch(u){i(u)}}function a(l){try{c(r.throw(l))}catch(u){i(u)}}function c(l){var u;l.done?o(l.value):(u=l.value,u instanceof t?u:new t((function(d){d(u)}))).then(s,a)}c((r=r.apply(n,e||[])).next())}))}var ht=class{constructor(){this.listeners={}}on(e,t,r){if(this.listeners[e]||(this.listeners[e]=new Set),r?.once){let o=(...i)=>{this.un(e,o),t(...i)};return this.listeners[e].add(o),()=>this.un(e,o)}return this.listeners[e].add(t),()=>this.un(e,t)}un(e,t){var r;(r=this.listeners[e])===null||r===void 0||r.delete(t)}once(e,t){return this.on(e,t,{once:!0})}unAll(){this.listeners={}}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach((r=>r(...t)))}},eo={decode:function(n,e){return ne(this,void 0,void 0,(function*(){let t=new AudioContext({sampleRate:e});try{return yield t.decodeAudioData(n)}finally{t.close()}}))},createBuffer:function(n,e){if(!n||n.length===0)throw new Error("channelData must be a non-empty array");if(e<=0)throw new Error("duration must be greater than 0");if(typeof n[0]=="number"&&(n=[n]),!n[0]||n[0].length===0)throw new Error("channelData must contain non-empty channel arrays");(function(r){let o=r[0];if(o.some((i=>i>1||i<-1))){let i=o.length,s=0;for(let a=0;a<i;a++){let c=Math.abs(o[a]);c>s&&(s=c)}for(let a of r)for(let c=0;c<i;c++)a[c]/=s}})(n);let t=n.map((r=>r instanceof Float32Array?r:Float32Array.from(r)));return{duration:e,length:t[0].length,sampleRate:t[0].length/e,numberOfChannels:t.length,getChannelData:r=>{let o=t[r];if(!o)throw new Error(`Channel ${r} not found`);return o},copyFromChannel:AudioBuffer.prototype.copyFromChannel,copyToChannel:AudioBuffer.prototype.copyToChannel}}};function Xa(n,e){let t=e.xmlns?document.createElementNS(e.xmlns,n):document.createElement(n);for(let[r,o]of Object.entries(e))if(r==="children"&&o)for(let[i,s]of Object.entries(o))s instanceof Node?t.appendChild(s):typeof s=="string"?t.appendChild(document.createTextNode(s)):t.appendChild(Xa(i,s));else r==="style"?Object.assign(t.style,o):r==="textContent"?t.textContent=o:t.setAttribute(r,o.toString());return t}function qa(n,e,t){let r=Xa(n,e||{});return t?.appendChild(r),r}var sl=Object.freeze({__proto__:null,createElement:qa,default:qa}),il={fetchBlob:function(n,e,t){return ne(this,void 0,void 0,(function*(){let r=yield fetch(n,t);if(r.status>=400)throw new Error(`Failed to fetch ${n}: ${r.status} (${r.statusText})`);return(function(o,i){ne(this,void 0,void 0,(function*(){if(!o.body||!o.headers)return;let s=o.body.getReader(),a=Number(o.headers.get("Content-Length"))||0,c=0,l=u=>{c+=u?.length||0;let d=Math.round(c/a*100);i(d)};try{for(;;){let u=yield s.read();if(u.done)break;l(u.value)}}catch(u){console.warn("Progress tracking error:",u)}}))})(r.clone(),e),r.blob()}))}};function W(n){let e=n,t=new Set;return{get value(){return e},set(r){Object.is(e,r)||(e=r,t.forEach((o=>o(e))))},update(r){this.set(r(e))},subscribe:r=>(t.add(r),()=>t.delete(r))}}function pt(n,e){let t=W(n());return e.forEach((r=>r.subscribe((()=>{let o=n();Object.is(t.value,o)||t.set(o)})))),{get value(){return t.value},subscribe:r=>t.subscribe(r)}}function $e(n,e){let t,r=()=>{t&&(t(),t=void 0),t=n()},o=e.map((i=>i.subscribe(r)));return r(),()=>{t&&(t(),t=void 0),o.forEach((i=>i()))}}var _s=class extends ht{get isPlayingSignal(){return this._isPlaying}get currentTimeSignal(){return this._currentTime}get durationSignal(){return this._duration}get volumeSignal(){return this._volume}get mutedSignal(){return this._muted}get playbackRateSignal(){return this._playbackRate}get seekingSignal(){return this._seeking}constructor(e){super(),this.isExternalMedia=!1,this.reactiveMediaEventCleanups=[],e.media?(this.media=e.media,this.isExternalMedia=!0):this.media=document.createElement("audio"),this._isPlaying=W(!1),this._currentTime=W(0),this._duration=W(0),this._volume=W(this.media.volume),this._muted=W(this.media.muted),this._playbackRate=W(this.media.playbackRate||1),this._seeking=W(!1),this.setupReactiveMediaEvents(),e.mediaControls&&(this.media.controls=!0),e.autoplay&&(this.media.autoplay=!0),e.playbackRate!=null&&this.onMediaEvent("canplay",(()=>{e.playbackRate!=null&&(this.media.playbackRate=e.playbackRate)}),{once:!0})}setupReactiveMediaEvents(){this.reactiveMediaEventCleanups.push(this.onMediaEvent("play",(()=>{this._isPlaying.set(!0)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("pause",(()=>{this._isPlaying.set(!1)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("ended",(()=>{this._isPlaying.set(!1)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("timeupdate",(()=>{this._currentTime.set(this.media.currentTime)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("durationchange",(()=>{this._duration.set(this.media.duration||0)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("loadedmetadata",(()=>{this._duration.set(this.media.duration||0)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("seeking",(()=>{this._seeking.set(!0)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("seeked",(()=>{this._seeking.set(!1)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("volumechange",(()=>{this._volume.set(this.media.volume),this._muted.set(this.media.muted)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("ratechange",(()=>{this._playbackRate.set(this.media.playbackRate)})))}onMediaEvent(e,t,r){return this.media.addEventListener(e,t,r),()=>this.media.removeEventListener(e,t,r)}getSrc(){return this.media.currentSrc||this.media.src||""}revokeSrc(){let e=this.getSrc();e.startsWith("blob:")&&URL.revokeObjectURL(e)}canPlayType(e){return this.media.canPlayType(e)!==""}setSrc(e,t){let r=this.getSrc();if(e&&r===e)return;this.revokeSrc();let o=t instanceof Blob&&(this.canPlayType(t.type)||!e)?URL.createObjectURL(t):e;if(r&&this.media.removeAttribute("src"),o||e)try{this.media.src=o}catch{this.media.src=e}}destroy(){this.reactiveMediaEventCleanups.forEach((e=>e())),this.reactiveMediaEventCleanups=[],this.isExternalMedia||(this.media.pause(),this.revokeSrc(),this.media.removeAttribute("src"),this.media.load(),this.media.remove())}setMediaElement(e){this.reactiveMediaEventCleanups.forEach((t=>t())),this.reactiveMediaEventCleanups=[],this.media=e,this.setupReactiveMediaEvents()}play(){return ne(this,void 0,void 0,(function*(){try{return yield this.media.play()}catch(e){if(e instanceof DOMException&&e.name==="AbortError")return;throw e}}))}pause(){this.media.pause()}isPlaying(){return!this.media.paused&&!this.media.ended}setTime(e){this.media.currentTime=Math.max(0,Math.min(e,this.getDuration()))}getDuration(){return this.media.duration}getCurrentTime(){return this.media.currentTime}getVolume(){return this.media.volume}setVolume(e){this.media.volume=e}getMuted(){return this.media.muted}setMuted(e){this.media.muted=e}getPlaybackRate(){return this.media.playbackRate}isSeeking(){return this.media.seeking}setPlaybackRate(e,t){t!=null&&(this.media.preservesPitch=t),this.media.playbackRate=e}getMediaElement(){return this.media}setSinkId(e){return this.media.setSinkId(e)}};function al({maxTop:n,maxBottom:e,halfHeight:t,vScale:r,barMinHeight:o=0,barAlign:i}){let s=Math.round(n*t*r),a=s+Math.round(e*t*r)||1;return a<o&&(a=o,i||(s=a/2)),{topHeight:s,totalHeight:a}}function cl({barAlign:n,halfHeight:e,topHeight:t,totalHeight:r,canvasHeight:o}){return n==="top"?0:n==="bottom"?o-r:e-t}function Ga(n,e,t){let r=e-n.left,o=t-n.top;return[r/n.width,o/n.height]}function Ka(n){return!!(n.barWidth||n.barGap||n.barAlign)}function ja(n,e){if(!Ka(e))return n;let t=e.barWidth||.5,r=t+(e.barGap||t/2);return r===0?n:Math.floor(n/r)*r}function $a({scrollLeft:n,totalWidth:e,numCanvases:t}){if(e===0)return[0];let r=n/e,o=Math.floor(r*t);return[o-1,o,o+1]}function Qa(n){let e=n._cleanup;typeof e=="function"&&e()}function ll(n){let e=W({scrollLeft:n.scrollLeft,scrollWidth:n.scrollWidth,clientWidth:n.clientWidth}),t=pt((()=>(function(i){let{scrollLeft:s,scrollWidth:a,clientWidth:c}=i;if(a===0)return{startX:0,endX:1};let l=s/a,u=(s+c)/a;return{startX:Math.max(0,Math.min(1,l)),endX:Math.max(0,Math.min(1,u))}})(e.value)),[e]),r=pt((()=>(function(i){return{left:i.scrollLeft,right:i.scrollLeft+i.clientWidth}})(e.value)),[e]),o=()=>{e.set({scrollLeft:n.scrollLeft,scrollWidth:n.scrollWidth,clientWidth:n.clientWidth})};return n.addEventListener("scroll",o,{passive:!0}),{scrollData:e,percentages:t,bounds:r,cleanup:()=>{n.removeEventListener("scroll",o),Qa(e)}}}var Es=class extends ht{constructor(e,t){super(),this.timeouts=[],this.isScrollable=!1,this.audioData=null,this.resizeObserver=null,this.lastContainerWidth=0,this.isDragging=!1,this.subscriptions=[],this.unsubscribeOnScroll=[],this.dragStream=null,this.scrollStream=null,this.subscriptions=[],this.options=e;let r=this.parentFromOptionsContainer(e.container);this.parent=r;let[o,i]=this.initHtml();r.appendChild(o),this.container=o,this.scrollContainer=i.querySelector(".scroll"),this.wrapper=i.querySelector(".wrapper"),this.canvasWrapper=i.querySelector(".canvases"),this.progressWrapper=i.querySelector(".progress"),this.cursor=i.querySelector(".cursor"),t&&i.appendChild(t),this.initEvents()}parentFromOptionsContainer(e){let t;if(typeof e=="string"?t=document.querySelector(e):e instanceof HTMLElement&&(t=e),!t)throw new Error("Container not found");return t}initEvents(){this.wrapper.addEventListener("click",(t=>{let r=this.wrapper.getBoundingClientRect(),[o,i]=Ga(r,t.clientX,t.clientY);this.emit("click",o,i)})),this.wrapper.addEventListener("dblclick",(t=>{let r=this.wrapper.getBoundingClientRect(),[o,i]=Ga(r,t.clientX,t.clientY);this.emit("dblclick",o,i)})),this.options.dragToSeek!==!0&&typeof this.options.dragToSeek!="object"||this.initDrag(),this.scrollStream=ll(this.scrollContainer);let e=$e((()=>{let{startX:t,endX:r}=this.scrollStream.percentages.value,{left:o,right:i}=this.scrollStream.bounds.value;this.emit("scroll",t,r,o,i)}),[this.scrollStream.percentages,this.scrollStream.bounds]);if(this.subscriptions.push(e),typeof ResizeObserver=="function"){let t=this.createDelay(100);this.resizeObserver=new ResizeObserver((()=>{t().then((()=>this.onContainerResize())).catch((()=>{}))})),this.resizeObserver.observe(this.scrollContainer)}}onContainerResize(){let e=this.parent.clientWidth;e===this.lastContainerWidth&&this.options.height!=="auto"||(this.lastContainerWidth=e,this.reRender(),this.emit("resize"))}initDrag(){if(this.dragStream)return;this.dragStream=(function(t,r={}){let{threshold:o=3,mouseButton:i=0,touchDelay:s=100}=r,a=W(null),c=new Map,l=matchMedia("(pointer: coarse)").matches,u=()=>{},d=f=>{if(f.button!==i||(c.set(f.pointerId,f),c.size>1))return;let m=f.clientX,p=f.clientY,h=!1,x=Date.now(),y=t.getBoundingClientRect(),{left:b,top:v}=y,w=E=>{if(E.defaultPrevented||c.size>1||l&&Date.now()-x<s)return;let R=E.clientX,D=E.clientY,L=R-m,Z=D-p;(h||Math.abs(L)>o||Math.abs(Z)>o)&&(E.preventDefault(),E.stopPropagation(),h||(a.set({type:"start",x:m-b,y:p-v}),h=!0),a.set({type:"move",x:R-b,y:D-v,deltaX:L,deltaY:Z}),m=R,p=D)},S=E=>{if(c.delete(E.pointerId),h){let R=E.clientX,D=E.clientY;a.set({type:"end",x:R-b,y:D-v})}u()},k=E=>{c.delete(E.pointerId),E.relatedTarget&&E.relatedTarget!==document.documentElement||S(E)},I=E=>{h&&(E.stopPropagation(),E.preventDefault())},C=E=>{E.defaultPrevented||c.size>1||h&&E.preventDefault()};document.addEventListener("pointermove",w),document.addEventListener("pointerup",S),document.addEventListener("pointerout",k),document.addEventListener("pointercancel",k),document.addEventListener("touchmove",C,{passive:!1}),document.addEventListener("click",I,{capture:!0}),u=()=>{document.removeEventListener("pointermove",w),document.removeEventListener("pointerup",S),document.removeEventListener("pointerout",k),document.removeEventListener("pointercancel",k),document.removeEventListener("touchmove",C),setTimeout((()=>{document.removeEventListener("click",I,{capture:!0})}),10)}};return t.addEventListener("pointerdown",d),{signal:a,cleanup:()=>{u(),t.removeEventListener("pointerdown",d),c.clear(),Qa(a)}}})(this.wrapper);let e=$e((()=>{let t=this.dragStream.signal.value;if(!t)return;let r=this.wrapper.getBoundingClientRect().width,o=(i=t.x/r)<0?0:i>1?1:i;var i;t.type==="start"?(this.isDragging=!0,this.emit("dragstart",o)):t.type==="move"?this.emit("drag",o):t.type==="end"&&(this.isDragging=!1,this.emit("dragend",o))}),[this.dragStream.signal]);this.subscriptions.push(e)}initHtml(){let e=document.createElement("div"),t=e.attachShadow({mode:"open"}),r=this.options.cspNonce&&typeof this.options.cspNonce=="string"?this.options.cspNonce.replace(/"/g,""):"";return t.innerHTML=`
2415
+ `;function Va({name:n,renderer:e}){let t=La.default.find(c=>c.name===n),r=new xt,o=new Kt,i=new Ir({}),s=new Ir({}),a=new To({glProgram:new vo({vertex:Na,fragment:Ua(t.glsl)}),resources:{from:i,to:s,uniforms:{...As.basics,...As.custom(t)}}});return r.filters=[a],{render({width:c,height:l,from:u,to:d,progress:f}){return(r.width!==c||r.height!==l)&&(r.setSize({width:c,height:l}),o.source.resize(c,l)),i.resource=u,s.resource=d,i.update(),s.update(),a.resources.uniforms.uniforms.progress=f,e.render({container:r,target:o,clear:!1,width:c,height:l}),o}}}var Xn=class{pixi;static async setup(){let e=await Is({width:1920,height:1080,preference:"webgl",background:"black",preferWebGLVersion:2}),t=new yo;return t.interactive=!0,new this({renderer:e,stage:t})}constructor(e){this.pixi=e}#e=new Map;#t=new Map;async composite(e){let{stage:t,renderer:r}=this.pixi;this.#l(this.#c(e));let{dispose:o}=await this.#r(e,t);r.render(t);let i=new VideoFrame(r.canvas,{timestamp:0,duration:0});return o(),i}async#r(e,t){if(Array.isArray(e)){e.reverse();let r=[];for(let o of e){let i=await this.#r(o,t);r.push(i.dispose)}return{dispose:()=>r.forEach(o=>o())}}switch(e.kind){case"text":return this.#n(e,t);case"image":return this.#o(e,t);case"transition":return this.#a(e,t);case"gap":return this.pixi?.renderer.clear(),{dispose:()=>{}};default:return console.warn("Unknown layer kind",e.kind),{dispose:()=>{}}}}#n(e,t){let r=this.#i(e);return this.#s(r,e.matrix),t.addChild(r),{dispose:()=>{}}}#o(e,t){let r=Kt.from(e.frame),o=this.#i(e);return o.texture=r,this.#s(o,e.matrix),t.addChild(o),{dispose:()=>{r.destroy(!0),e.frame.close()}}}#a({from:e,to:t,progress:r,name:o},i){let a=(this.#e.get(o)??(this.#e.set(o,Va({name:"circle",renderer:this.pixi.renderer})),this.#e.get(o))).render({from:e,to:t,progress:r,width:e.displayWidth,height:e.displayHeight}),c=new xt(a);return i.addChild(c),{dispose:()=>c.destroy(!1)}}#s(e,t){if(!t)return;let r=Ra(t);e.setFromMatrix(r)}#i(e){let t=this.#t.get(e.id);if(t)return t;switch(e.kind){case"text":{let r=new kr({text:e.content,style:e.style});return r.onmouseenter=()=>console.log("enter text"),this.#t.set(e.id,r).get(e.id)}case"image":{let r=new xt;return r.onmouseenter=()=>console.log("enter"),this.#t.set(e.id,r).get(e.id)}}}#c(e){let t=new Set,r=o=>{if(Array.isArray(o))for(let i of o)r(i);else t.add(o.id)};return r(e),t}#l(e){for(let t of this.#t.keys())e.has(t)||(this.#t.get(t).destroy(!0),this.#t.delete(t))}};var Ha=n=>$r.host(e=>({async world(){n.count++}}));async function je(n){return n instanceof Blob?new wr(n):new Tr(n)}var Kn=class{machina;thread;compositor;static async setup(e){let t=new qn,r=await $r.thread({label:"OmnitoolDriver",workerUrl:e?.workerUrl??"/node_modules/@omnimedia/omnitool/x/driver/driver.worker.bundle.min.js",setupHost:Ha(t)}),o=await Xn.setup();return new this(t,r,o)}constructor(e,t,r){this.machina=e,this.thread=t,this.compositor=r}async hello(){return this.thread.work.hello()}async getAudioDuration(e){let r=await new he({source:await je(e),formats:Oe}).getPrimaryAudioTrack();if(!r)throw new Error("primary audio track not found");return await r.computeDuration()}async getVideoDuration(e){return await(await new he({source:await je(e),formats:Oe}).getPrimaryVideoTrack())?.computeDuration()}decodeVideo(e){let t=null,r=new TransformStream({async transform(o,i){let s=await e.onFrame?.(o)??o;t?.close(),i.enqueue(s),t=s}});return this.thread.work.decodeVideo[wt]({transfer:[r.writable]})({source:e.source,video:r.writable,start:e.start,end:e.end}),r.readable}decodeAudio(e){let t=new TransformStream;return this.thread.work.decodeAudio[wt]({transfer:[t.writable]})({source:e.source,audio:t.writable,start:e.start,end:e.end}),t.readable}async encode({video:e,audio:t,config:r}){let i=await(await window.showSaveFilePicker()).createWritable(),s=new WritableStream({async write(a){await i.write(a)},async close(){await i.close()}});return await this.thread.work.encode[wt]({transfer:[t??[],e??[],s]})({video:e,audio:t,config:r,bridge:s})}async composite(e){return await this.compositor.composite(e)}};function Wa(n,e){document.querySelector(".export").addEventListener("click",()=>{n.render(e).then(()=>console.log("done"))})}var H;(function(n){n[n.Sequence=0]="Sequence",n[n.Stack=1]="Stack",n[n.Video=2]="Video",n[n.Audio=3]="Audio",n[n.Text=4]="Text",n[n.Gap=5]="Gap",n[n.Spatial=6]="Spatial",n[n.Transition=7]="Transition",n[n.TextStyle=8]="TextStyle"})(H||(H={}));var Qn;(function(n){n[n.Crossfade=0]="Crossfade"})(Qn||(Qn={}));var Yn=class{datafile;duration=0;hasVideo=!1;hasAudio=!1;constructor(e){this.datafile=e}static async analyze(e){let t=new this(e),r=await this.duration(e.url)*1e3;t.duration=r;let{video:o,audio:i}=await this.#e(e.url);return t.hasAudio=i,t.hasVideo=o,t}static async duration(e){return new he({formats:Oe,source:await je(e)}).computeDuration()}static async#e(e){let t=new he({formats:Oe,source:await je(e)});return{audio:!!await t.getPrimaryAudioTrack(),video:!!await t.getPrimaryVideoTrack()}}};var Jn=class{#e=new Nr;async store(e){let t=await Yn.analyze(e),{hash:r}=t.datafile.checksum,{filename:o,bytes:i,url:s,blob:a}=t.datafile;if(this.#e.has(r)){let c=this.#e.require(r);c.filename=o}else this.#e.set(r,{kind:"media",filename:o,bytes:i,url:s,blob:a});return t}require(e){return this.#e.require(e)}};var Zn=class n{videoTrack;options;#e;#t=new Map;#r=[0,0];constructor(e,t){this.videoTrack=e,this.options=t,this.#e=new fr(e,t.canvasSinkOptions)}static async init(e,t){let o=await new he({formats:Oe,source:await je(e)}).getPrimaryVideoTrack();if(o)return new n(o,{frequency:t.frequency??1,canvasSinkOptions:t.canvasSinkOptions??{width:80,height:50,fit:"fill"},onChange:t.onChange,onPlaceholders:t.onPlaceholders});throw new Error("Source has no video track")}set frequency(e){e!==this.options.frequency&&(this.options.frequency=e,this.#c())}get frequency(){return this.options.frequency}#n([e,t],r=1){let o=t-e;return[e-o*r,t+o*r]}async#o(){let[e,t]=this.#r,r=new Set,o=await this.videoTrack.computeDuration();for(let i=Math.max(0,e);i<=t;i+=this.options.frequency)i>=0&&i<=o&&r.add(i);this.options.onPlaceholders?.([...r])}async#a(){let[e,t]=this.#r,r=new Set,o=await this.videoTrack.computeDuration();for(let c=Math.max(0,e);c<=t;c+=this.options.frequency)c>=0&&c<=o&&r.add(c);let i=[...r].filter(c=>!this.#t.has(c)),s=0;for await(let c of this.#e.canvasesAtTimestamps(i))if(c){let l=i[s++];this.#t.set(l,c)}for(let c of this.#t.keys())r.has(c)||this.#t.delete(c);let a=[...this.#t.entries()].map(([c,l])=>({time:c,canvas:l}));this.options.onChange(a)}set range(e){let[t,r]=e,o=r-t,[i,s]=this.#r,a=i+o,c=s-o,l=t<a,u=r>c;!l&&!u||(this.#r=this.#n(e,2),this.#c())}#s=null;#i=!1;async#c(){if(this.#o(),this.#s){this.#i=!0;return}this.#s=this.#a(),await this.#s,this.#s=null,this.#i&&(this.#i=!1,await this.#c())}getThumbnail(e){return this.#t.get(e)}};function ne(n,e,t,r){return new(t||(t=Promise))((function(o,i){function s(l){try{c(r.next(l))}catch(u){i(u)}}function a(l){try{c(r.throw(l))}catch(u){i(u)}}function c(l){var u;l.done?o(l.value):(u=l.value,u instanceof t?u:new t((function(d){d(u)}))).then(s,a)}c((r=r.apply(n,e||[])).next())}))}var ht=class{constructor(){this.listeners={}}on(e,t,r){if(this.listeners[e]||(this.listeners[e]=new Set),r?.once){let o=(...i)=>{this.un(e,o),t(...i)};return this.listeners[e].add(o),()=>this.un(e,o)}return this.listeners[e].add(t),()=>this.un(e,t)}un(e,t){var r;(r=this.listeners[e])===null||r===void 0||r.delete(t)}once(e,t){return this.on(e,t,{once:!0})}unAll(){this.listeners={}}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach((r=>r(...t)))}},eo={decode:function(n,e){return ne(this,void 0,void 0,(function*(){let t=new AudioContext({sampleRate:e});try{return yield t.decodeAudioData(n)}finally{t.close()}}))},createBuffer:function(n,e){if(!n||n.length===0)throw new Error("channelData must be a non-empty array");if(e<=0)throw new Error("duration must be greater than 0");if(typeof n[0]=="number"&&(n=[n]),!n[0]||n[0].length===0)throw new Error("channelData must contain non-empty channel arrays");(function(r){let o=r[0];if(o.some((i=>i>1||i<-1))){let i=o.length,s=0;for(let a=0;a<i;a++){let c=Math.abs(o[a]);c>s&&(s=c)}for(let a of r)for(let c=0;c<i;c++)a[c]/=s}})(n);let t=n.map((r=>r instanceof Float32Array?r:Float32Array.from(r)));return{duration:e,length:t[0].length,sampleRate:t[0].length/e,numberOfChannels:t.length,getChannelData:r=>{let o=t[r];if(!o)throw new Error(`Channel ${r} not found`);return o},copyFromChannel:AudioBuffer.prototype.copyFromChannel,copyToChannel:AudioBuffer.prototype.copyToChannel}}};function Xa(n,e){let t=e.xmlns?document.createElementNS(e.xmlns,n):document.createElement(n);for(let[r,o]of Object.entries(e))if(r==="children"&&o)for(let[i,s]of Object.entries(o))s instanceof Node?t.appendChild(s):typeof s=="string"?t.appendChild(document.createTextNode(s)):t.appendChild(Xa(i,s));else r==="style"?Object.assign(t.style,o):r==="textContent"?t.textContent=o:t.setAttribute(r,o.toString());return t}function qa(n,e,t){let r=Xa(n,e||{});return t?.appendChild(r),r}var sl=Object.freeze({__proto__:null,createElement:qa,default:qa}),il={fetchBlob:function(n,e,t){return ne(this,void 0,void 0,(function*(){let r=yield fetch(n,t);if(r.status>=400)throw new Error(`Failed to fetch ${n}: ${r.status} (${r.statusText})`);return(function(o,i){ne(this,void 0,void 0,(function*(){if(!o.body||!o.headers)return;let s=o.body.getReader(),a=Number(o.headers.get("Content-Length"))||0,c=0,l=u=>{c+=u?.length||0;let d=Math.round(c/a*100);i(d)};try{for(;;){let u=yield s.read();if(u.done)break;l(u.value)}}catch(u){console.warn("Progress tracking error:",u)}}))})(r.clone(),e),r.blob()}))}};function W(n){let e=n,t=new Set;return{get value(){return e},set(r){Object.is(e,r)||(e=r,t.forEach((o=>o(e))))},update(r){this.set(r(e))},subscribe:r=>(t.add(r),()=>t.delete(r))}}function pt(n,e){let t=W(n());return e.forEach((r=>r.subscribe((()=>{let o=n();Object.is(t.value,o)||t.set(o)})))),{get value(){return t.value},subscribe:r=>t.subscribe(r)}}function $e(n,e){let t,r=()=>{t&&(t(),t=void 0),t=n()},o=e.map((i=>i.subscribe(r)));return r(),()=>{t&&(t(),t=void 0),o.forEach((i=>i()))}}var _s=class extends ht{get isPlayingSignal(){return this._isPlaying}get currentTimeSignal(){return this._currentTime}get durationSignal(){return this._duration}get volumeSignal(){return this._volume}get mutedSignal(){return this._muted}get playbackRateSignal(){return this._playbackRate}get seekingSignal(){return this._seeking}constructor(e){super(),this.isExternalMedia=!1,this.reactiveMediaEventCleanups=[],e.media?(this.media=e.media,this.isExternalMedia=!0):this.media=document.createElement("audio"),this._isPlaying=W(!1),this._currentTime=W(0),this._duration=W(0),this._volume=W(this.media.volume),this._muted=W(this.media.muted),this._playbackRate=W(this.media.playbackRate||1),this._seeking=W(!1),this.setupReactiveMediaEvents(),e.mediaControls&&(this.media.controls=!0),e.autoplay&&(this.media.autoplay=!0),e.playbackRate!=null&&this.onMediaEvent("canplay",(()=>{e.playbackRate!=null&&(this.media.playbackRate=e.playbackRate)}),{once:!0})}setupReactiveMediaEvents(){this.reactiveMediaEventCleanups.push(this.onMediaEvent("play",(()=>{this._isPlaying.set(!0)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("pause",(()=>{this._isPlaying.set(!1)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("ended",(()=>{this._isPlaying.set(!1)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("timeupdate",(()=>{this._currentTime.set(this.media.currentTime)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("durationchange",(()=>{this._duration.set(this.media.duration||0)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("loadedmetadata",(()=>{this._duration.set(this.media.duration||0)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("seeking",(()=>{this._seeking.set(!0)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("seeked",(()=>{this._seeking.set(!1)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("volumechange",(()=>{this._volume.set(this.media.volume),this._muted.set(this.media.muted)}))),this.reactiveMediaEventCleanups.push(this.onMediaEvent("ratechange",(()=>{this._playbackRate.set(this.media.playbackRate)})))}onMediaEvent(e,t,r){return this.media.addEventListener(e,t,r),()=>this.media.removeEventListener(e,t,r)}getSrc(){return this.media.currentSrc||this.media.src||""}revokeSrc(){let e=this.getSrc();e.startsWith("blob:")&&URL.revokeObjectURL(e)}canPlayType(e){return this.media.canPlayType(e)!==""}setSrc(e,t){let r=this.getSrc();if(e&&r===e)return;this.revokeSrc();let o=t instanceof Blob&&(this.canPlayType(t.type)||!e)?URL.createObjectURL(t):e;if(r&&this.media.removeAttribute("src"),o||e)try{this.media.src=o}catch{this.media.src=e}}destroy(){this.reactiveMediaEventCleanups.forEach((e=>e())),this.reactiveMediaEventCleanups=[],this.isExternalMedia||(this.media.pause(),this.revokeSrc(),this.media.removeAttribute("src"),this.media.load(),this.media.remove())}setMediaElement(e){this.reactiveMediaEventCleanups.forEach((t=>t())),this.reactiveMediaEventCleanups=[],this.media=e,this.setupReactiveMediaEvents()}play(){return ne(this,void 0,void 0,(function*(){try{return yield this.media.play()}catch(e){if(e instanceof DOMException&&e.name==="AbortError")return;throw e}}))}pause(){this.media.pause()}isPlaying(){return!this.media.paused&&!this.media.ended}setTime(e){this.media.currentTime=Math.max(0,Math.min(e,this.getDuration()))}getDuration(){return this.media.duration}getCurrentTime(){return this.media.currentTime}getVolume(){return this.media.volume}setVolume(e){this.media.volume=e}getMuted(){return this.media.muted}setMuted(e){this.media.muted=e}getPlaybackRate(){return this.media.playbackRate}isSeeking(){return this.media.seeking}setPlaybackRate(e,t){t!=null&&(this.media.preservesPitch=t),this.media.playbackRate=e}getMediaElement(){return this.media}setSinkId(e){return this.media.setSinkId(e)}};function al({maxTop:n,maxBottom:e,halfHeight:t,vScale:r,barMinHeight:o=0,barAlign:i}){let s=Math.round(n*t*r),a=s+Math.round(e*t*r)||1;return a<o&&(a=o,i||(s=a/2)),{topHeight:s,totalHeight:a}}function cl({barAlign:n,halfHeight:e,topHeight:t,totalHeight:r,canvasHeight:o}){return n==="top"?0:n==="bottom"?o-r:e-t}function Ga(n,e,t){let r=e-n.left,o=t-n.top;return[r/n.width,o/n.height]}function Ka(n){return!!(n.barWidth||n.barGap||n.barAlign)}function ja(n,e){if(!Ka(e))return n;let t=e.barWidth||.5,r=t+(e.barGap||t/2);return r===0?n:Math.floor(n/r)*r}function $a({scrollLeft:n,totalWidth:e,numCanvases:t}){if(e===0)return[0];let r=n/e,o=Math.floor(r*t);return[o-1,o,o+1]}function Qa(n){let e=n._cleanup;typeof e=="function"&&e()}function ll(n){let e=W({scrollLeft:n.scrollLeft,scrollWidth:n.scrollWidth,clientWidth:n.clientWidth}),t=pt((()=>(function(i){let{scrollLeft:s,scrollWidth:a,clientWidth:c}=i;if(a===0)return{startX:0,endX:1};let l=s/a,u=(s+c)/a;return{startX:Math.max(0,Math.min(1,l)),endX:Math.max(0,Math.min(1,u))}})(e.value)),[e]),r=pt((()=>(function(i){return{left:i.scrollLeft,right:i.scrollLeft+i.clientWidth}})(e.value)),[e]),o=()=>{e.set({scrollLeft:n.scrollLeft,scrollWidth:n.scrollWidth,clientWidth:n.clientWidth})};return n.addEventListener("scroll",o,{passive:!0}),{scrollData:e,percentages:t,bounds:r,cleanup:()=>{n.removeEventListener("scroll",o),Qa(e)}}}var Es=class extends ht{constructor(e,t){super(),this.timeouts=[],this.isScrollable=!1,this.audioData=null,this.resizeObserver=null,this.lastContainerWidth=0,this.isDragging=!1,this.subscriptions=[],this.unsubscribeOnScroll=[],this.dragStream=null,this.scrollStream=null,this.subscriptions=[],this.options=e;let r=this.parentFromOptionsContainer(e.container);this.parent=r;let[o,i]=this.initHtml();r.appendChild(o),this.container=o,this.scrollContainer=i.querySelector(".scroll"),this.wrapper=i.querySelector(".wrapper"),this.canvasWrapper=i.querySelector(".canvases"),this.progressWrapper=i.querySelector(".progress"),this.cursor=i.querySelector(".cursor"),t&&i.appendChild(t),this.initEvents()}parentFromOptionsContainer(e){let t;if(typeof e=="string"?t=document.querySelector(e):e instanceof HTMLElement&&(t=e),!t)throw new Error("Container not found");return t}initEvents(){this.wrapper.addEventListener("click",(t=>{let r=this.wrapper.getBoundingClientRect(),[o,i]=Ga(r,t.clientX,t.clientY);this.emit("click",o,i)})),this.wrapper.addEventListener("dblclick",(t=>{let r=this.wrapper.getBoundingClientRect(),[o,i]=Ga(r,t.clientX,t.clientY);this.emit("dblclick",o,i)})),this.options.dragToSeek!==!0&&typeof this.options.dragToSeek!="object"||this.initDrag(),this.scrollStream=ll(this.scrollContainer);let e=$e((()=>{let{startX:t,endX:r}=this.scrollStream.percentages.value,{left:o,right:i}=this.scrollStream.bounds.value;this.emit("scroll",t,r,o,i)}),[this.scrollStream.percentages,this.scrollStream.bounds]);if(this.subscriptions.push(e),typeof ResizeObserver=="function"){let t=this.createDelay(100);this.resizeObserver=new ResizeObserver((()=>{t().then((()=>this.onContainerResize())).catch((()=>{}))})),this.resizeObserver.observe(this.scrollContainer)}}onContainerResize(){let e=this.parent.clientWidth;e===this.lastContainerWidth&&this.options.height!=="auto"||(this.lastContainerWidth=e,this.reRender(),this.emit("resize"))}initDrag(){if(this.dragStream)return;this.dragStream=(function(t,r={}){let{threshold:o=3,mouseButton:i=0,touchDelay:s=100}=r,a=W(null),c=new Map,l=matchMedia("(pointer: coarse)").matches,u=()=>{},d=f=>{if(f.button!==i||(c.set(f.pointerId,f),c.size>1))return;let m=f.clientX,p=f.clientY,h=!1,x=Date.now(),y=t.getBoundingClientRect(),{left:b,top:v}=y,w=E=>{if(E.defaultPrevented||c.size>1||l&&Date.now()-x<s)return;let R=E.clientX,D=E.clientY,L=R-m,Z=D-p;(h||Math.abs(L)>o||Math.abs(Z)>o)&&(E.preventDefault(),E.stopPropagation(),h||(a.set({type:"start",x:m-b,y:p-v}),h=!0),a.set({type:"move",x:R-b,y:D-v,deltaX:L,deltaY:Z}),m=R,p=D)},S=E=>{if(c.delete(E.pointerId),h){let R=E.clientX,D=E.clientY;a.set({type:"end",x:R-b,y:D-v})}u()},k=E=>{c.delete(E.pointerId),E.relatedTarget&&E.relatedTarget!==document.documentElement||S(E)},I=E=>{h&&(E.stopPropagation(),E.preventDefault())},C=E=>{E.defaultPrevented||c.size>1||h&&E.preventDefault()};document.addEventListener("pointermove",w),document.addEventListener("pointerup",S),document.addEventListener("pointerout",k),document.addEventListener("pointercancel",k),document.addEventListener("touchmove",C,{passive:!1}),document.addEventListener("click",I,{capture:!0}),u=()=>{document.removeEventListener("pointermove",w),document.removeEventListener("pointerup",S),document.removeEventListener("pointerout",k),document.removeEventListener("pointercancel",k),document.removeEventListener("touchmove",C),setTimeout((()=>{document.removeEventListener("click",I,{capture:!0})}),10)}};return t.addEventListener("pointerdown",d),{signal:a,cleanup:()=>{u(),t.removeEventListener("pointerdown",d),c.clear(),Qa(a)}}})(this.wrapper);let e=$e((()=>{let t=this.dragStream.signal.value;if(!t)return;let r=this.wrapper.getBoundingClientRect().width,o=(i=t.x/r)<0?0:i>1?1:i;var i;t.type==="start"?(this.isDragging=!0,this.emit("dragstart",o)):t.type==="move"?this.emit("drag",o):t.type==="end"&&(this.isDragging=!1,this.emit("dragend",o))}),[this.dragStream.signal]);this.subscriptions.push(e)}initHtml(){let e=document.createElement("div"),t=e.attachShadow({mode:"open"}),r=this.options.cspNonce&&typeof this.options.cspNonce=="string"?this.options.cspNonce.replace(/"/g,""):"";return t.innerHTML=`
2416
2416
  <style${r?` nonce="${r}"`:""}>
2417
2417
  :host {
2418
2418
  user-select: none;
@@ -2485,7 +2485,7 @@ vec4 transition(vec2 uv) {
2485
2485
  <div class="cursor" part="cursor"></div>
2486
2486
  </div>
2487
2487
  </div>
2488
- `,[e,t]}setOptions(e){if(this.options.container!==e.container){let t=this.parentFromOptionsContainer(e.container);t.appendChild(this.container),this.parent=t}e.dragToSeek!==!0&&typeof this.options.dragToSeek!="object"||this.initDrag(),this.options=e,this.reRender()}getWrapper(){return this.wrapper}getWidth(){return this.scrollContainer.clientWidth}getScroll(){return this.scrollContainer.scrollLeft}setScroll(e){this.scrollContainer.scrollLeft=e}setScrollPercentage(e){let{scrollWidth:t}=this.scrollContainer,r=t*e;this.setScroll(r)}destroy(){var e;this.subscriptions.forEach((t=>t())),this.container.remove(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),(e=this.unsubscribeOnScroll)===null||e===void 0||e.forEach((t=>t())),this.unsubscribeOnScroll=[],this.dragStream&&(this.dragStream.cleanup(),this.dragStream=null),this.scrollStream&&(this.scrollStream.cleanup(),this.scrollStream=null)}createDelay(e=10){let t,r,o=()=>{t&&(clearTimeout(t),t=void 0),r&&(r(),r=void 0)};return this.timeouts.push(o),()=>new Promise(((i,s)=>{o(),r=s,t=setTimeout((()=>{t=void 0,r=void 0,i()}),e)}))}getHeight(e,t){var r;let o=((r=this.audioData)===null||r===void 0?void 0:r.numberOfChannels)||1;return(function({optionsHeight:i,optionsSplitChannels:s,parentHeight:a,numberOfChannels:c,defaultHeight:l=128}){if(i==null)return l;let u=Number(i);if(!isNaN(u))return u;if(i==="auto"){let d=a||l;return s?.every((f=>!f.overlay))?d/c:d}return l})({optionsHeight:e,optionsSplitChannels:t,parentHeight:this.parent.clientHeight,numberOfChannels:o,defaultHeight:128})}convertColorValues(e,t){return(function(r,o,i){if(!Array.isArray(r))return r||"";if(r.length===0)return"#999";if(r.length<2)return r[0]||"";let s=document.createElement("canvas"),a=s.getContext("2d"),c=i??s.height*o,l=a.createLinearGradient(0,0,0,c||o),u=1/(r.length-1);return r.forEach(((d,f)=>{l.addColorStop(f*u,d)})),l})(e,this.getPixelRatio(),t?.canvas.height)}getPixelRatio(){return e=window.devicePixelRatio,Math.max(1,e||1);var e}renderBarWaveform(e,t,r,o){let{width:i,height:s}=r.canvas,{halfHeight:a,barWidth:c,barRadius:l,barIndexScale:u,barSpacing:d,barMinHeight:f}=(function({width:p,height:h,length:x,options:y,pixelRatio:b}){let v=h/2,w=y.barWidth?y.barWidth*b:1,S=y.barGap?y.barGap*b:y.barWidth?w/2:0,k=w+S||1;return{halfHeight:v,barWidth:w,barGap:S,barRadius:y.barRadius||0,barMinHeight:y.barMinHeight?y.barMinHeight*b:0,barIndexScale:x>0?p/k/x:0,barSpacing:k}})({width:i,height:s,length:(e[0]||[]).length,options:t,pixelRatio:this.getPixelRatio()}),m=(function({channelData:p,barIndexScale:h,barSpacing:x,barWidth:y,halfHeight:b,vScale:v,canvasHeight:w,barAlign:S,barMinHeight:k}){let I=p[0]||[],C=p[1]||I,E=I.length,R=[],D=0,L=0,Z=0;for(let O=0;O<=E;O++){let ze=Math.round(O*h);if(ze>D){let{topHeight:fc,totalHeight:Ls}=al({maxTop:L,maxBottom:Z,halfHeight:b,vScale:v,barMinHeight:k,barAlign:S}),mc=cl({barAlign:S,halfHeight:b,topHeight:fc,totalHeight:Ls,canvasHeight:w});R.push({x:D*x,y:mc,width:y,height:Ls}),D=ze,L=0,Z=0}let Ns=Math.abs(I[O]||0),Us=Math.abs(C[O]||0);Ns>L&&(L=Ns),Us>Z&&(Z=Us)}return R})({channelData:e,barIndexScale:u,barSpacing:d,barWidth:c,halfHeight:a,vScale:o,canvasHeight:s,barAlign:t.barAlign,barMinHeight:f});r.beginPath();for(let p of m)l&&"roundRect"in r?r.roundRect(p.x,p.y,p.width,p.height,l):r.rect(p.x,p.y,p.width,p.height);r.fill(),r.closePath()}renderLineWaveform(e,t,r,o){let{width:i,height:s}=r.canvas,a=(function({channelData:c,width:l,height:u,vScale:d}){let f=u/2,m=c[0]||[];return[m,c[1]||m].map(((p,h)=>{let x=p.length,y=x?l/x:0,b=f,v=h===0?-1:1,w=[{x:0,y:b}],S=0,k=0;for(let I=0;I<=x;I++){let C=Math.round(I*y);if(C>S){let R=b+(Math.round(k*f*d)||1)*v;w.push({x:S,y:R}),S=C,k=0}let E=Math.abs(p[I]||0);E>k&&(k=E)}return w.push({x:S,y:b}),w}))})({channelData:e,width:i,height:s,vScale:o});r.beginPath();for(let c of a)if(c.length){r.moveTo(c[0].x,c[0].y);for(let l=1;l<c.length;l++){let u=c[l];r.lineTo(u.x,u.y)}}r.fill(),r.closePath()}renderWaveform(e,t,r){if(r.fillStyle=this.convertColorValues(t.waveColor,r),t.renderFunction)return void t.renderFunction(e,r);let o=(function({channelData:i,barHeight:s,normalize:a,maxPeak:c}){var l;let u=s||1;if(!a)return u;let d=i[0];if(!d||d.length===0)return u;let f=c??0;if(!c)for(let m=0;m<d.length;m++){let p=(l=d[m])!==null&&l!==void 0?l:0,h=Math.abs(p);h>f&&(f=h)}return f?u/f:u})({channelData:e,barHeight:t.barHeight,normalize:t.normalize,maxPeak:t.maxPeak});Ka(t)?this.renderBarWaveform(e,t,r,o):this.renderLineWaveform(e,t,r,o)}renderSingleCanvas(e,t,r,o,i,s,a){let c=this.getPixelRatio(),l=document.createElement("canvas");l.width=Math.round(r*c),l.height=Math.round(o*c),l.style.width=`${r}px`,l.style.height=`${o}px`,l.style.left=`${Math.round(i)}px`,s.appendChild(l);let u=l.getContext("2d");if(t.renderFunction?(u.fillStyle=this.convertColorValues(t.waveColor,u),t.renderFunction(e,u)):this.renderWaveform(e,t,u),l.width>0&&l.height>0){let d=l.cloneNode(),f=d.getContext("2d");f.drawImage(l,0,0),f.globalCompositeOperation="source-in",f.fillStyle=this.convertColorValues(t.progressColor,f),f.fillRect(0,0,l.width,l.height),a.appendChild(d)}}renderMultiCanvas(e,t,r,o,i,s){let a=this.getPixelRatio(),{clientWidth:c}=this.scrollContainer,l=r/a,u=(function({clientWidth:p,totalWidth:h,options:x}){return ja(Math.min(8e3,p,h),x)})({clientWidth:c,totalWidth:l,options:t}),d={};if(u===0)return;let f=p=>{if(p<0||p>=m||d[p])return;d[p]=!0;let h=p*u,x=Math.min(l-h,u);if(x=ja(x,t),x<=0)return;let y=(function({channelData:b,offset:v,clampedWidth:w,totalWidth:S}){return b.map((k=>{let I=Math.floor(v/S*k.length),C=Math.floor((v+w)/S*k.length);return k.slice(I,C)}))})({channelData:e,offset:h,clampedWidth:x,totalWidth:l});this.renderSingleCanvas(y,t,x,o,h,i,s)},m=Math.ceil(l/u);if(!this.isScrollable){for(let p=0;p<m;p++)f(p);return}if($a({scrollLeft:this.scrollContainer.scrollLeft,totalWidth:l,numCanvases:m}).forEach((p=>f(p))),m>1){let p=this.on("scroll",(()=>{let{scrollLeft:h}=this.scrollContainer;Object.keys(d).length>10&&(i.innerHTML="",s.innerHTML="",d={}),$a({scrollLeft:h,totalWidth:l,numCanvases:m}).forEach((x=>f(x)))}));this.unsubscribeOnScroll.push(p)}}renderChannel(e,t,r,o){var{overlay:i}=t,s=(function(u,d){var f={};for(var m in u)Object.prototype.hasOwnProperty.call(u,m)&&d.indexOf(m)<0&&(f[m]=u[m]);if(u!=null&&typeof Object.getOwnPropertySymbols=="function"){var p=0;for(m=Object.getOwnPropertySymbols(u);p<m.length;p++)d.indexOf(m[p])<0&&Object.prototype.propertyIsEnumerable.call(u,m[p])&&(f[m[p]]=u[m[p]])}return f})(t,["overlay"]);let a=document.createElement("div"),c=this.getHeight(s.height,s.splitChannels);a.style.height=`${c}px`,i&&o>0&&(a.style.marginTop=`-${c}px`),this.canvasWrapper.style.minHeight=`${c}px`,this.canvasWrapper.appendChild(a);let l=a.cloneNode();this.progressWrapper.appendChild(l),this.renderMultiCanvas(e,s,r,c,a,l)}render(e){return ne(this,void 0,void 0,(function*(){var t;this.timeouts.forEach((l=>l())),this.timeouts=[],this.canvasWrapper.innerHTML="",this.progressWrapper.innerHTML="",this.options.width!=null&&(this.scrollContainer.style.width=typeof this.options.width=="number"?`${this.options.width}px`:this.options.width);let r=this.getPixelRatio(),o=this.scrollContainer.clientWidth,{scrollWidth:i,isScrollable:s,useParentWidth:a,width:c}=(function({duration:l,minPxPerSec:u=0,parentWidth:d,fillParent:f,pixelRatio:m}){let p=Math.ceil(l*u),h=p>d,x=!!(f&&!h);return{scrollWidth:p,isScrollable:h,useParentWidth:x,width:(x?d:p)*m}})({duration:e.duration,minPxPerSec:this.options.minPxPerSec||0,parentWidth:o,fillParent:this.options.fillParent,pixelRatio:r});if(this.isScrollable=s,this.wrapper.style.width=a?"100%":`${i}px`,this.scrollContainer.style.overflowX=this.isScrollable?"auto":"hidden",this.scrollContainer.classList.toggle("noScrollbar",!!this.options.hideScrollbar),this.cursor.style.backgroundColor=`${this.options.cursorColor||this.options.progressColor}`,this.cursor.style.width=`${this.options.cursorWidth}px`,this.audioData=e,this.emit("render"),this.options.splitChannels)for(let l=0;l<e.numberOfChannels;l++){let u=Object.assign(Object.assign({},this.options),(t=this.options.splitChannels)===null||t===void 0?void 0:t[l]);this.renderChannel([e.getChannelData(l)],u,c,l)}else{let l=[e.getChannelData(0)];e.numberOfChannels>1&&l.push(e.getChannelData(1)),this.renderChannel(l,this.options,c,0)}Promise.resolve().then((()=>this.emit("rendered")))}))}reRender(){if(this.unsubscribeOnScroll.forEach((r=>r())),this.unsubscribeOnScroll=[],!this.audioData)return;let{scrollWidth:e}=this.scrollContainer,{right:t}=this.progressWrapper.getBoundingClientRect();if(this.render(this.audioData),this.isScrollable&&e!==this.scrollContainer.scrollWidth){let{right:r}=this.progressWrapper.getBoundingClientRect(),o=(function(i){let s=2*i;return(s<0?Math.floor(s):Math.ceil(s))/2})(r-t);this.scrollContainer.scrollLeft+=o}}zoom(e){this.options.minPxPerSec=e,this.reRender()}scrollIntoView(e,t=!1){let{scrollLeft:r,scrollWidth:o,clientWidth:i}=this.scrollContainer,s=e*o,a=r,c=r+i,l=i/2;if(this.isDragging)s+30>c?this.scrollContainer.scrollLeft+=30:s-30<a&&(this.scrollContainer.scrollLeft-=30);else{(s<a||s>c)&&(this.scrollContainer.scrollLeft=s-(this.options.autoCenter?l:0));let u=s-r-l;t&&this.options.autoCenter&&u>0&&(this.scrollContainer.scrollLeft+=u)}}renderProgress(e,t){if(isNaN(e))return;let r=100*e;this.canvasWrapper.style.clipPath=`polygon(${r}% 0%, 100% 0%, 100% 100%, ${r}% 100%)`,this.progressWrapper.style.width=`${r}%`,this.cursor.style.left=`${r}%`,this.cursor.style.transform=this.options.cursorWidth?`translateX(-${e*this.options.cursorWidth}px)`:"",this.isScrollable&&this.options.autoScroll&&this.audioData&&this.audioData.duration>0&&this.scrollIntoView(e,t)}exportImage(e,t,r){return ne(this,void 0,void 0,(function*(){let o=this.canvasWrapper.querySelectorAll("canvas");if(!o.length)throw new Error("No waveform data");if(r==="dataURL"){let i=Array.from(o).map((s=>s.toDataURL(e,t)));return Promise.resolve(i)}return Promise.all(Array.from(o).map((i=>new Promise(((s,a)=>{i.toBlob((c=>{c?s(c):a(new Error("Could not export image"))}),e,t)})))))}))}},Fs=class extends ht{constructor(){super(...arguments),this.animationFrameId=null,this.isRunning=!1}start(){if(this.isRunning)return;this.isRunning=!0;let e=()=>{this.isRunning&&(this.emit("tick"),this.animationFrameId=requestAnimationFrame(e))};e()}stop(){this.isRunning=!1,this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}destroy(){this.stop()}},Sr=class extends ht{constructor(e=new AudioContext){super(),this.bufferNode=null,this.playStartTime=0,this.playedDuration=0,this._muted=!1,this._playbackRate=1,this._duration=void 0,this.buffer=null,this.currentSrc="",this.paused=!0,this.crossOrigin=null,this.seeking=!1,this.autoplay=!1,this.addEventListener=this.on,this.removeEventListener=this.un,this.audioContext=e,this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination)}load(){return ne(this,void 0,void 0,(function*(){}))}get src(){return this.currentSrc}set src(e){if(this.currentSrc=e,this._duration=void 0,!e)return this.buffer=null,void this.emit("emptied");fetch(e).then((t=>{if(t.status>=400)throw new Error(`Failed to fetch ${e}: ${t.status} (${t.statusText})`);return t.arrayBuffer()})).then((t=>this.currentSrc!==e?null:this.audioContext.decodeAudioData(t))).then((t=>{this.currentSrc===e&&(this.buffer=t,this.emit("loadedmetadata"),this.emit("canplay"),this.autoplay&&this.play())})).catch((t=>{console.error("WebAudioPlayer load error:",t)}))}_play(){if(!this.paused)return;this.paused=!1,this.bufferNode&&(this.bufferNode.onended=null,this.bufferNode.disconnect()),this.bufferNode=this.audioContext.createBufferSource(),this.buffer&&(this.bufferNode.buffer=this.buffer),this.bufferNode.playbackRate.value=this._playbackRate,this.bufferNode.connect(this.gainNode);let e=this.playedDuration*this._playbackRate;(e>=this.duration||e<0)&&(e=0,this.playedDuration=0),this.bufferNode.start(this.audioContext.currentTime,e),this.playStartTime=this.audioContext.currentTime,this.bufferNode.onended=()=>{this.currentTime>=this.duration&&(this.pause(),this.emit("ended"))}}_pause(){var e;this.paused=!0,(e=this.bufferNode)===null||e===void 0||e.stop(),this.playedDuration+=this.audioContext.currentTime-this.playStartTime}play(){return ne(this,void 0,void 0,(function*(){this.paused&&(this._play(),this.emit("play"))}))}pause(){this.paused||(this._pause(),this.emit("pause"))}stopAt(e){let t=e-this.currentTime,r=this.bufferNode;r?.stop(this.audioContext.currentTime+t),r?.addEventListener("ended",(()=>{r===this.bufferNode&&(this.bufferNode=null,this.pause())}),{once:!0})}setSinkId(e){return ne(this,void 0,void 0,(function*(){return this.audioContext.setSinkId(e)}))}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e,this.bufferNode&&(this.bufferNode.playbackRate.value=e)}get currentTime(){return(this.paused?this.playedDuration:this.playedDuration+(this.audioContext.currentTime-this.playStartTime))*this._playbackRate}set currentTime(e){let t=!this.paused;t&&this._pause(),this.playedDuration=e/this._playbackRate,t&&this._play(),this.emit("seeking"),this.emit("timeupdate")}get duration(){var e,t;return(e=this._duration)!==null&&e!==void 0?e:((t=this.buffer)===null||t===void 0?void 0:t.duration)||0}set duration(e){this._duration=e}get volume(){return this.gainNode.gain.value}set volume(e){this.gainNode.gain.value=e,this.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted!==e&&(this._muted=e,this._muted?this.gainNode.disconnect():this.gainNode.connect(this.audioContext.destination))}canPlayType(e){return/^(audio|video)\//.test(e)}getGainNode(){return this.gainNode}getChannelData(){let e=[];if(!this.buffer)return e;let t=this.buffer.numberOfChannels;for(let r=0;r<t;r++)e.push(this.buffer.getChannelData(r));return e}removeAttribute(e){switch(e){case"src":this.src="";break;case"playbackRate":this.playbackRate=0;break;case"currentTime":this.currentTime=0;break;case"duration":this.duration=0;break;case"volume":this.volume=0;break;case"muted":this.muted=!1}}},ul={waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,dragToSeek:!1,autoScroll:!0,autoCenter:!0,sampleRate:8e3},Wt=class n extends _s{static create(e){return new n(e)}getState(){return this.wavesurferState}getRenderer(){return this.renderer}constructor(e){let t=e.media||(e.backend==="WebAudio"?new Sr:void 0);super({media:t,mediaControls:e.mediaControls,autoplay:e.autoplay,playbackRate:e.audioRate}),this.plugins=[],this.decodedData=null,this.stopAtPosition=null,this.subscriptions=[],this.mediaSubscriptions=[],this.abortController=null,this.reactiveCleanups=[],this.options=Object.assign({},ul,e);let{state:r,actions:o}=(function(a){var c,l,u,d,f,m;let p=(c=a?.currentTime)!==null&&c!==void 0?c:W(0),h=(l=a?.duration)!==null&&l!==void 0?l:W(0),x=(u=a?.isPlaying)!==null&&u!==void 0?u:W(!1),y=(d=a?.isSeeking)!==null&&d!==void 0?d:W(!1),b=(f=a?.volume)!==null&&f!==void 0?f:W(1),v=(m=a?.playbackRate)!==null&&m!==void 0?m:W(1),w=W(null),S=W(null),k=W(""),I=W(0),C=W(0),E=pt((()=>!x.value),[x]),R=pt((()=>w.value!==null),[w]),D=pt((()=>R.value&&h.value>0),[R,h]),L=pt((()=>p.value),[p]),Z=pt((()=>h.value>0?p.value/h.value:0),[p,h]);return{state:{currentTime:p,duration:h,isPlaying:x,isPaused:E,isSeeking:y,volume:b,playbackRate:v,audioBuffer:w,peaks:S,url:k,zoom:I,scrollPosition:C,canPlay:R,isReady:D,progress:L,progressPercent:Z},actions:{setCurrentTime:O=>{let ze=Math.max(0,Math.min(h.value||1/0,O));p.set(ze)},setDuration:O=>{h.set(Math.max(0,O))},setPlaying:O=>{x.set(O)},setSeeking:O=>{y.set(O)},setVolume:O=>{let ze=Math.max(0,Math.min(1,O));b.set(ze)},setPlaybackRate:O=>{let ze=Math.max(.1,Math.min(16,O));v.set(ze)},setAudioBuffer:O=>{w.set(O),O&&h.set(O.duration)},setPeaks:O=>{S.set(O)},setUrl:O=>{k.set(O)},setZoom:O=>{I.set(Math.max(0,O))},setScrollPosition:O=>{C.set(Math.max(0,O))}}}})({isPlaying:this.isPlayingSignal,currentTime:this.currentTimeSignal,duration:this.durationSignal,volume:this.volumeSignal,playbackRate:this.playbackRateSignal,isSeeking:this.seekingSignal});this.wavesurferState=r,this.wavesurferActions=o,this.timer=new Fs;let i=t?void 0:this.getMediaElement();this.renderer=new Es(this.options,i),this.initPlayerEvents(),this.initRendererEvents(),this.initTimerEvents(),this.initReactiveState(),this.initPlugins();let s=this.options.url||this.getSrc()||"";Promise.resolve().then((()=>{this.emit("init");let{peaks:a,duration:c}=this.options;(s||a&&c)&&this.load(s,a,c).catch((l=>{this.emit("error",l instanceof Error?l:new Error(String(l)))}))}))}updateProgress(e=this.getCurrentTime()){return this.renderer.renderProgress(e/this.getDuration(),this.isPlaying()),e}initTimerEvents(){this.subscriptions.push(this.timer.on("tick",(()=>{if(!this.isSeeking()){let e=this.updateProgress();this.emit("timeupdate",e),this.emit("audioprocess",e),this.stopAtPosition!=null&&this.isPlaying()&&e>=this.stopAtPosition&&this.pause()}})))}initReactiveState(){this.reactiveCleanups.push((function(e,t){let r=[];r.push($e((()=>{let s=e.isPlaying.value;t.emit(s?"play":"pause")}),[e.isPlaying])),r.push($e((()=>{let s=e.currentTime.value;t.emit("timeupdate",s),e.isPlaying.value&&t.emit("audioprocess",s)}),[e.currentTime,e.isPlaying])),r.push($e((()=>{e.isSeeking.value&&t.emit("seeking",e.currentTime.value)}),[e.isSeeking,e.currentTime]));let o=!1;r.push($e((()=>{e.isReady.value&&!o&&(o=!0,t.emit("ready",e.duration.value))}),[e.isReady,e.duration]));let i=!1;return r.push($e((()=>{let s=e.isPlaying.value,a=e.currentTime.value,c=e.duration.value,l=c>0&&a>=c;i&&!s&&l&&t.emit("finish"),i=s&&l}),[e.isPlaying,e.currentTime,e.duration])),r.push($e((()=>{let s=e.zoom.value;s>0&&t.emit("zoom",s)}),[e.zoom])),()=>{r.forEach((s=>s()))}})(this.wavesurferState,{emit:this.emit.bind(this)}))}initPlayerEvents(){this.isPlaying()&&(this.emit("play"),this.timer.start()),this.mediaSubscriptions.push(this.onMediaEvent("timeupdate",(()=>{let e=this.updateProgress();this.emit("timeupdate",e)})),this.onMediaEvent("play",(()=>{this.emit("play"),this.timer.start()})),this.onMediaEvent("pause",(()=>{this.emit("pause"),this.timer.stop(),this.stopAtPosition=null})),this.onMediaEvent("emptied",(()=>{this.timer.stop(),this.stopAtPosition=null})),this.onMediaEvent("ended",(()=>{this.emit("timeupdate",this.getDuration()),this.emit("finish"),this.stopAtPosition=null})),this.onMediaEvent("seeking",(()=>{this.emit("seeking",this.getCurrentTime())})),this.onMediaEvent("error",(()=>{var e;this.emit("error",(e=this.getMediaElement().error)!==null&&e!==void 0?e:new Error("Media error")),this.stopAtPosition=null})))}initRendererEvents(){this.subscriptions.push(this.renderer.on("click",((e,t)=>{this.options.interact&&(this.seekTo(e),this.emit("interaction",e*this.getDuration()),this.emit("click",e,t))})),this.renderer.on("dblclick",((e,t)=>{this.emit("dblclick",e,t)})),this.renderer.on("scroll",((e,t,r,o)=>{let i=this.getDuration();this.emit("scroll",e*i,t*i,r,o)})),this.renderer.on("render",(()=>{this.emit("redraw")})),this.renderer.on("rendered",(()=>{this.emit("redrawcomplete")})),this.renderer.on("dragstart",(e=>{this.emit("dragstart",e)})),this.renderer.on("dragend",(e=>{this.emit("dragend",e)})),this.renderer.on("resize",(()=>{this.emit("resize")})));{let e,t=this.renderer.on("drag",(r=>{var o;if(!this.options.interact)return;this.renderer.renderProgress(r),clearTimeout(e);let i=0,s=this.options.dragToSeek;this.isPlaying()?i=0:s===!0?i=200:s&&typeof s=="object"&&(i=(o=s.debounceTime)!==null&&o!==void 0?o:200),e=setTimeout((()=>{this.seekTo(r)}),i),this.emit("interaction",r*this.getDuration()),this.emit("drag",r)}));this.subscriptions.push((()=>{clearTimeout(e),t()}))}}initPlugins(){var e;!((e=this.options.plugins)===null||e===void 0)&&e.length&&this.options.plugins.forEach((t=>{this.registerPlugin(t)}))}unsubscribePlayerEvents(){this.mediaSubscriptions.forEach((e=>e())),this.mediaSubscriptions=[]}setOptions(e){this.options=Object.assign({},this.options,e),e.duration&&!e.peaks&&(this.decodedData=eo.createBuffer(this.exportPeaks(),e.duration)),e.peaks&&e.duration&&(this.decodedData=eo.createBuffer(e.peaks,e.duration)),this.renderer.setOptions(this.options),e.audioRate&&this.setPlaybackRate(e.audioRate),e.mediaControls!=null&&(this.getMediaElement().controls=e.mediaControls)}registerPlugin(e){if(this.plugins.includes(e))return e;e._init(this),this.plugins.push(e);let t=e.once("destroy",(()=>{this.plugins=this.plugins.filter((r=>r!==e)),this.subscriptions=this.subscriptions.filter((r=>r!==t))}));return this.subscriptions.push(t),e}unregisterPlugin(e){this.plugins=this.plugins.filter((t=>t!==e)),e.destroy()}getWrapper(){return this.renderer.getWrapper()}getWidth(){return this.renderer.getWidth()}getScroll(){return this.renderer.getScroll()}setScroll(e){return this.renderer.setScroll(e)}setScrollTime(e){let t=e/this.getDuration();this.renderer.setScrollPercentage(t)}getActivePlugins(){return this.plugins}loadAudio(e,t,r,o){return ne(this,void 0,void 0,(function*(){var i;if(this.emit("load",e),!this.options.media&&this.isPlaying()&&this.pause(),this.decodedData=null,this.stopAtPosition=null,(i=this.abortController)===null||i===void 0||i.abort(),this.abortController=null,!t&&!r){let a=this.options.fetchParams||{};window.AbortController&&!a.signal&&(this.abortController=new AbortController,a.signal=this.abortController.signal);let c=u=>this.emit("loading",u);t=yield il.fetchBlob(e,c,a);let l=this.options.blobMimeType;l&&(t=new Blob([t],{type:l}))}this.setSrc(e,t);let s=yield new Promise((a=>{let c=o||this.getDuration();c?a(c):this.mediaSubscriptions.push(this.onMediaEvent("loadedmetadata",(()=>a(this.getDuration())),{once:!0}))}));if(!e&&!t){let a=this.getMediaElement();a instanceof Sr&&(a.duration=s)}if(r)this.decodedData=eo.createBuffer(r,s||0);else if(t){let a=yield t.arrayBuffer();this.decodedData=yield eo.decode(a,this.options.sampleRate)}this.decodedData&&(this.emit("decode",this.getDuration()),this.renderer.render(this.decodedData)),this.emit("ready",this.getDuration())}))}load(e,t,r){return ne(this,void 0,void 0,(function*(){try{return yield this.loadAudio(e,void 0,t,r)}catch(o){throw this.emit("error",o),o}}))}loadBlob(e,t,r){return ne(this,void 0,void 0,(function*(){try{return yield this.loadAudio("",e,t,r)}catch(o){throw this.emit("error",o),o}}))}zoom(e){if(!this.decodedData)throw new Error("No audio loaded");this.renderer.zoom(e),this.emit("zoom",e)}getDecodedData(){return this.decodedData}exportPeaks({channels:e=2,maxLength:t=8e3,precision:r=1e4}={}){if(!this.decodedData)throw new Error("The audio has not been decoded yet");let o=Math.min(e,this.decodedData.numberOfChannels),i=[];for(let s=0;s<o;s++){let a=this.decodedData.getChannelData(s),c=[],l=a.length/t;for(let u=0;u<t;u++){let d=a.slice(Math.floor(u*l),Math.ceil((u+1)*l)),f=0;for(let m=0;m<d.length;m++){let p=d[m];Math.abs(p)>Math.abs(f)&&(f=p)}c.push(Math.round(f*r)/r)}i.push(c)}return i}getDuration(){let e=super.getDuration()||0;return e!==0&&e!==1/0||!this.decodedData||(e=this.decodedData.duration),e}toggleInteraction(e){this.options.interact=e}setTime(e){this.stopAtPosition=null,super.setTime(e),this.updateProgress(e),this.emit("timeupdate",e)}seekTo(e){let t=this.getDuration()*e;this.setTime(t)}play(e,t){let r=Object.create(null,{play:{get:()=>super.play}});return ne(this,void 0,void 0,(function*(){e!=null&&this.setTime(e);let o=yield r.play.call(this);return t!=null&&(this.media instanceof Sr?this.media.stopAt(t):this.stopAtPosition=t),o}))}playPause(){return ne(this,void 0,void 0,(function*(){return this.isPlaying()?this.pause():this.play()}))}stop(){this.pause(),this.setTime(0)}skip(e){this.setTime(this.getCurrentTime()+e)}empty(){this.load("",[[0]],.001)}setMediaElement(e){this.unsubscribePlayerEvents(),super.setMediaElement(e),this.initPlayerEvents()}exportImage(){return ne(this,arguments,void 0,(function*(e="image/png",t=1,r="dataURL"){return this.renderer.exportImage(e,t,r)}))}destroy(){var e;this.emit("destroy"),(e=this.abortController)===null||e===void 0||e.abort(),this.plugins.forEach((t=>t.destroy())),this.subscriptions.forEach((t=>t())),this.unsubscribePlayerEvents(),this.reactiveCleanups.forEach((t=>t())),this.reactiveCleanups=[],this.timer.destroy(),this.renderer.destroy(),super.destroy()}};Wt.BasePlugin=class extends ht{constructor(n){super(),this.subscriptions=[],this.isDestroyed=!1,this.options=n}onInit(){}_init(n){this.isDestroyed&&(this.subscriptions=[],this.isDestroyed=!1),this.wavesurfer=n,this.onInit()}destroy(){this.emit("destroy"),this.subscriptions.forEach((n=>n())),this.subscriptions=[],this.isDestroyed=!0,this.wavesurfer=void 0}},Wt.dom=sl;var to=class n{wavesurfer;constructor(e,t,r){this.wavesurfer=Wt.create({container:t,waveColor:"rgb(200, 0, 200)",progressColor:"rgb(100, 0, 100)",barWidth:10,barRadius:10,barGap:2,peaks:[e],duration:r})}static async init(e,t,r){let o=e.decodeAudio({source:t}).getReader(),i=[],s=[],a=1024,c=await e.getAudioDuration(t);for(;;){let{done:l,value:u}=await o.read();if(l)break;let d=u.numberOfFrames,f=new Float32Array(d);u.copyTo(f,{planeIndex:0});for(let m=0;m<f.length;m++)if(s.push(f[m]),s.length>=a){let p=s.splice(0,a),h=Math.min(...p),x=Math.max(...p);i.push(h,x)}u.close()}return new n(i,r,c??0)}set width(e){this.wavesurfer.setOptions({width:e})}};function Ya(n){return Pe.freeze(Pe.clone(n))}var Ds=class{#e=[];#t=new WeakMap;#r=[];#n=new Set;notifyRead(e){this.#e.at(-1)?.add(e)}async notifyWrite(e){if(this.#n.has(e))throw new Error("circularity forbidden");let t=this.#o(e).pub();return this.#r.at(-1)?.add(t),t}observe(e){this.#e.push(new Set);let t=e();return{seen:this.#e.pop(),result:t}}subscribe(e,t){return this.#o(e)(async()=>{let r=new Set;this.#r.push(r),this.#n.add(e),r.add(t()),this.#n.delete(e),await Promise.all(r),this.#r.pop()})}#o(e){let t=this.#t.get(e);return t||(t=vt(),this.#t.set(e,t)),t}},Q=globalThis[Symbol.for("e280.tracker")]??=new Ds;var ke=Symbol("optic");var ro=class{calculate;#e=!1;#t;constructor(e){this.calculate=e,this.#t=e()}get(){return this.#e&&(this.#e=!1,this.#t=this.calculate()),this.#t}invalidate(){this.#e=!0}};var no=class n{on=vt();[ke];#e;#t;#r=zr(()=>this.on.publish(this.state));constructor(e){this[ke]=e,this.#e=Pe.clone(e.getState()),this.#t=new ro(()=>Ya(e.getState()))}async update(){let e=this[ke].getState();!Pe.equal(e,this.#e)&&(this.#t.invalidate(),this.#e=Pe.clone(e),this.#r(),await Q.notifyWrite(this))}get state(){return Q.notifyRead(this),this.#t.get()}async mutate(e){return this[ke].mutate(e)}lens(e){let t=new n({getState:()=>e(this[ke].getState()),mutate:r=>this[ke].mutate(o=>r(e(o))),registerLens:this[ke].registerLens});return this[ke].registerLens(t),t}};var qt=class{sneak;constructor(e){this.sneak=e}get(){return Q.notifyRead(this),this.sneak}get value(){return this.get()}};var Gt=class extends qt{on=vt();dispose(){this.on.clear()}};function oo(n,e=n){let{seen:t,result:r}=Q.observe(n),o=zr(e),i=[],s=()=>i.forEach(a=>a());for(let a of t){let c=Q.subscribe(a,o);i.push(c)}return{result:r,dispose:s}}function jt(n,e){return n===e}var so=class extends Gt{#e;constructor(e,t){let r=t?.compare??jt,{result:o,dispose:i}=oo(e,async()=>{let s=e();!r(this.sneak,s)&&(this.sneak=s,await Promise.all([Q.notifyWrite(this),this.on.pub(s)]))});super(o),this.#e=i}toString(){return`(derived "${String(this.get())}")`}dispose(){super.dispose(),this.#e()}get core(){return this}fn(){let e=this;function t(){return e.get()}return t.core=e,t.get=e.get.bind(e),t.on=e.on,t.dispose=e.dispose.bind(e),t.fn=e.fn.bind(e),Object.defineProperty(t,"value",{get:()=>e.value}),Object.defineProperty(t,"sneak",{get:()=>e.sneak}),t}};var io=class extends qt{#e;#t;#r=!1;#n;constructor(e,t){super(void 0),this.#e=e,this.#t=t?.compare??jt}toString(){return`($lazy "${String(this.get())}")`}get(){if(!this.#n){let{result:e,dispose:t}=oo(this.#e,()=>this.#r=!0);this.#n=t,this.sneak=e}if(this.#r){this.#r=!1;let e=this.#e();!this.#t(this.sneak,e)&&(this.sneak=e,Q.notifyWrite(this))}return super.get()}dispose(){this.#n&&this.#n()}get core(){return this}fn(){let e=this;function t(){return e.get()}return t.core=e,t.get=e.get.bind(e),t.dispose=e.dispose.bind(e),t.fn=e.fn.bind(e),Object.defineProperty(t,"value",{get:()=>e.value}),Object.defineProperty(t,"sneak",{get:()=>e.sneak}),t}};var ao=class extends Gt{#e=!1;#t;constructor(e,t){super(e),this.#t=t?.compare??jt}toString(){return`($signal "${String(this.get())}")`}async set(e,t=!1){let r=this.sneak;return this.sneak=e,(t||!this.#t(r,e))&&await this.publish(),e}get value(){return this.get()}set value(e){this.set(e)}async publish(){if(this.#e)throw new Error("forbid circularity");let e=this.sneak,t=Promise.resolve();try{this.#e=!0,t=Promise.all([Q.notifyWrite(this),this.on.publish(e)])}finally{this.#e=!1}return await t,e}get core(){return this}fn(){let e=this;function t(r){return arguments.length===0?e.get():e.set(arguments[0])}return t.core=e,t.get=e.get.bind(e),t.set=e.set.bind(e),t.on=e.on,t.dispose=e.dispose.bind(e),t.publish=e.publish.bind(e),t.fn=e.fn.bind(e),Object.defineProperty(t,"value",{get:()=>e.value,set:r=>e.value=r}),Object.defineProperty(t,"sneak",{get:()=>e.sneak,set:r=>e.sneak=r}),t}};function dl(n,e){return new io(n,e).fn()}function fl(n,e){return new so(n,e).fn()}function Pr(n,e){return new ao(n,e).fn()}Pr.lazy=dl;Pr.derived=fl;var Ja=(n,e)=>{let t=!1,r=null,o=60,i=1e3/o,s=0,a=0,c=0,l=0,u=d=>{if(!t)return;let f=d-a;for(a=d,c+=f,l+=f,e(l);c>=i;)n(s),s+=i,c-=i;r=requestAnimationFrame(u)};return{play(){t||(t=!0,a=performance.now(),r=requestAnimationFrame(u))},pause(){t&&(t=!1,r!==null&&cancelAnimationFrame(r),r=null)},seek(d){s=d,c=0,l=d,e(d)},dispose(){this.pause()},isPlaying(){return t},setFPS(d){o=d,i=1e3/o}}},Za=async(n,e)=>{let t=1e3/n.fps,r=n.duration/1e3,o=Math.ceil(r*n.fps);for(let i=0;i<o&&!n.abort?.aborted;i++){let s=i*t;await e(s,i)}};var ec=n=>n instanceof Blob?URL.createObjectURL(n):String(n);function rc(n){let e=new Map,t=new Map;function r(s){let a=e.get(s.id);return a||(a=document.createElement("video"),a.playsInline=!0,a.muted=!0,a.preload="auto",a.crossOrigin="anonymous",a.src=ec(n(s.mediaHash)),e.set(s.id,a)),a}function o(s){let a=t.get(s.id);return a||(a=document.createElement("audio"),a.preload="auto",a.crossOrigin="anonymous",a.src=ec(n(s.mediaHash)),a.volume=.2,t.set(s.id,a)),a}let i=!0;return{async video(s,a){let c=r(s);return{duration:s.duration,visuals:{sampleAt:async l=>{let u=s.start+l,d=s.start+s.duration;if(u<s.start||u>=d)return c.pause(),[];c.paused&&i&&await tc(c,u/1e3),c.paused&&!i&&await c.play();let f=new VideoFrame(c);return f?[{kind:"image",frame:f,matrix:a,id:s.id}]:[]}}}},async audio(s){let a=o(s);return{duration:s.duration,audio:{onTimeUpdate:async c=>{let l=s.start+c,u=s.start+s.duration;return l<s.start||l>=u?(a.pause(),[]):(a.paused&&i&&await tc(a,l/1e3),a.paused&&!i&&await a.play(),[])}}}},async dispose(){let s=[...e.values(),...t.values()];for(let a of s)a.pause(),a.src.startsWith("blob:")&&URL.revokeObjectURL(a.src),a.remove();e.clear(),t.clear()},async setPaused(s){i=s;let a=[...e.values(),...t.values()];for(let c of a)s&&c.pause()}}}function tc(n,e){return new Promise(t=>{let r=()=>{n.removeEventListener("seeked",r),t()};n.addEventListener("seeked",r),n.fastSeek?n.fastSeek(e):n.currentTime=e})}var Rs=(n,e)=>n.get(e),co=(n,e,t)=>{let r=t??Ba;if(e.spatialId){let o=Rs(n,e.spatialId);if(o.enabled){let i=Da(o.transform);r=Ma(i,r)}}return r},$t=class{items;sampler;constructor(e,t){this.items=e,this.sampler=t}async build(e,t){switch(e.kind){case H.Video:return this.sampler.video(e,co(this.items,e,t));case H.Audio:return this.sampler.audio(e);case H.Text:{let r=co(this.items,e,t),o=e.styleId!==void 0?this.items.get(e.styleId):void 0;return{duration:e.duration,visuals:{sampleAt:async i=>i<0||i>=e.duration?[]:[{id:e.id,kind:"text",content:e.content,style:o?.style,matrix:r}]}}}case H.Gap:return{duration:e.duration,visuals:{sampleAt:async()=>[]}};case H.Stack:{let r=co(this.items,e,t),o=await Promise.all(e.childrenIds.map(i=>this.build(Rs(this.items,i),r)));return this.#r(o)}case H.Sequence:{let r=co(this.items,e,t);return this.#n(e,r)}default:return{duration:0}}}#e(e){return{sampleAt:async t=>(await Promise.all(e.map(o=>o.visuals?o.visuals.sampleAt(t):Promise.resolve([])))).flat()}}#t(e){return{sampleAt:async t=>{let r=Math.round(t);for(let o of e){if(r<=o.duration)return o.visuals?o.visuals.sampleAt(r):[];r-=o.duration}return[]}}}#r(e){return{duration:Math.max(0,...e.map(r=>Number.isFinite(r.duration)?r.duration:0)),visuals:this.#e(e),audio:this.composeAudio_Stack(e)}}async#n(e,t){let r=e.childrenIds.map(s=>Rs(this.items,s)),o=await this.#o(r,t);return{duration:o.reduce((s,a)=>s+a.duration,0),visuals:this.#t(o),audio:this.composeAudio_Sequence(o)}}async#o(e,t){let r=[];for(let o=0;o<e.length;o++){let i=e[o];if(i.kind!==H.Transition){r.push(await this.build(i,t));continue}let s=r.pop(),a=e[o+1];if(!s||!a||a.kind===H.Transition){s&&r.push(s);continue}let c=await this.build(a,t),l=await this.#a(i,s,c);r.push(l),o++}return r}async#a(e,t,r){let o=Math.max(0,Math.min(e.duration,t.duration,r.duration)),i=Math.max(0,t.duration-o);return{duration:t.duration+r.duration-o,visuals:{sampleAt:async a=>{if(!t.visuals||!r.visuals)return[];if(a<i)return t.visuals.sampleAt(a);if(a<t.duration){let c=a-i,l=o>0?c/o:1,u=await t.visuals.sampleAt(a),d=await r.visuals.sampleAt(c);return!u[0]?.frame||!d[0]?.frame?[]:[{id:e.id,kind:"transition",name:"circle",progress:l,from:u[0].frame,to:d[0].frame}]}return r.visuals.sampleAt(a-t.duration+o)}},audio:this.composeAudio_Sequence([t,r])}}};var Ms=class extends $t{items;sampler;constructor(e,t){super(e,t),this.items=e,this.sampler=t}composeAudio_Stack(e){return{onTimeUpdate:t=>{for(let r of e)r.audio&&r.audio.onTimeUpdate(t)}}}composeAudio_Sequence(e){return{onTimeUpdate:t=>{let r=Math.round(t);for(let o of e){if(r<=o.duration){o.audio&&o.audio.onTimeUpdate(r);break}r-=o.duration}}}}};function Bs(n,e,t){return new Ms(e,t).build(n)}var lo=class{driver;canvas;root;sampler;currentTime=Pr(0);#e=Ja(e=>this.#t(e),e=>this.currentTime(e));constructor(e,t,r,o){this.driver=e,this.canvas=t,this.root=r,this.sampler=o,this.#e.setFPS(30)}static async create(e,t,r){let o=new Map(t.items.map(l=>[l.id,l])).get(t.rootId),i=new Map(t.items.map(l=>[l.id,l])),s=rc(r),a=await Bs(o,i,s),c=e.compositor.pixi.renderer.canvas;return new this(e,c,a,s)}async#t(e){let t=this.root.duration,r=e>t?t:e;this.root.audio?.onTimeUpdate(r);let o=await this.root.visuals?.sampleAt(r)??[];(await this.driver.composite(o)).close(),e>=t&&this.pause()}async play(){this.#e.isPlaying()||(this.sampler.setPaused(!1),this.#e.play())}pause(){this.#e.isPlaying()&&(this.#e.pause(),this.sampler.setPaused(!0))}async seek(e){this.pause(),this.#e.seek(e),this.root.audio?.onTimeUpdate(e);let t=await this.root.visuals?.sampleAt(e)??[];(await this.driver.composite(t)).close()}setFPS(e){this.#e.setFPS(e)}async update(e){let t=new Map(e.items.map(o=>[o.id,o])).get(e.rootId),r=new Map(e.items.map(o=>[o.id,o]));this.root=await Bs(t,r,this.sampler),await this.seek(this.currentTime())}};var Xt=class{state;constructor(e){this.state=e}require(e){return e===void 0?void 0:this.state.project.items.find(r=>r.id===e)}#e(){return xe.toInteger(xe.random())}#t(e){this.state.project=e(this.state.project)}register(e){this.#t(t=>({...t,items:[...t.items,e]}))}textStyle=e=>{let t={id:this.#e(),kind:H.TextStyle,style:e};return this.register(t),t};spatial=e=>{let t={id:this.#e(),kind:H.Spatial,transform:e,enabled:!0};return this.register(t),t};sequence=(...e)=>{let t={id:this.#e(),kind:H.Sequence,childrenIds:e.map(r=>r.id)};return this.register(t),t};stack=(...e)=>{let t={kind:H.Stack,id:this.#e(),childrenIds:e.map(r=>r.id)};return this.register(t),t};video=(e,t)=>{if(!e.hasVideo)throw new Error(`Video clip error: media "${e.datafile.filename}" has no video track.`);let r={kind:H.Video,id:this.#e(),mediaHash:e.datafile.checksum.hash,start:t?.start??0,duration:t?.duration??e.duration};return this.register(r),r};audio=(e,t)=>{if(!e.hasAudio)throw new Error(`Audio clip error: media "${e.datafile.filename}" has no audio track.`);let r={kind:H.Audio,id:this.#e(),mediaHash:e.datafile.checksum.hash,start:t?.start??0,duration:t?.duration??e.duration};return this.register(r),r};text=(e,t)=>{let r={id:this.#e(),content:e,kind:H.Text,duration:t?.duration??2e3};return t?.styles&&(r.styleId=this.textStyle(t.styles).id),this.register(r),r};gap=e=>{let t={id:this.#e(),kind:H.Gap,duration:e};return this.register(t),t};transition={crossfade:e=>{let t={id:this.#e(),kind:H.Transition,effect:Qn.Crossfade,duration:e};return this.register(t),t}};transform=e=>{let t=[e?.position?.[0]??0,e?.position?.[1]??0],r=[e?.scale?.[0]??1,e?.scale?.[1]??1],o=e?.rotation??0;return[t,r,o]};addChildren(e,...t){this.#t(r=>(r.items.find(({id:i})=>i===e.id).childrenIds.push(...t.map(i=>i.id)),r))}set=(e,t)=>{this.#t(r=>({...r,items:r.items.map(o=>o.id===e?{...o,...t}:o)}))}};var uo=class{reader;constructor(e){this.reader=e}async atOrNear(e){let t=null;for(;;){let{done:r,value:o}=await this.reader.read();if(r){let s=t?new VideoFrame(t):void 0;return t?.close(),s}let i=o.timestamp??0;if(i>=e){let s=t?.timestamp??Number.NEGATIVE_INFINITY,a=!!t&&Math.abs(s-e)<Math.abs(i-e),c=a?t:o,l=a?o:t,u=new VideoFrame(c);return c.close(),l?.close(),u}t?.close(),t=o}}cancel=async()=>await this.reader.cancel()};var fo=class{reader;constructor(e){this.reader=e}async*stream(){for(;;){let{done:e,value:t}=await this.reader.read();if(e)break;yield t}}cancel=async()=>await this.reader.cancel()};var nc=n=>Math.round(n*1e3);function oc(n,e){let t=new Map;async function r(o){let i=t.get(o.id);if(i)return i;let s=e(o.mediaHash),a=n.decodeVideo({source:s}),c=new uo(a.getReader());return t.set(o.id,c),c}return{async video(o,i){let s=await r(o),a=nc(o.start);return{duration:o.duration,visuals:{sampleAt:async c=>{let l=await s.atOrNear(a+nc(c));return l?[{kind:"image",frame:l,matrix:i,id:o.id}]:[]}}}},async audio(o){return{duration:o.duration,audio:{getStream:async function*(){let i=e(o.mediaHash),s=o.start/1e3,a=(o.start+o.duration)/1e3,c=n.decodeAudio({source:i,start:s,end:a});yield*new fo(c.getReader()).stream()}}}},async dispose(){let o=Array.from([...t.values()],i=>i.cancel());t.clear(),await Promise.all(o)}}}var Os=class extends $t{composeAudio_Stack(e){return{getStream:async function*(){for(let t of e)t.audio&&(yield*t.audio.getStream())}}}composeAudio_Sequence(e){return{getStream:async function*(){for(let t of e)t.audio&&(yield*t.audio.getStream())}}}};function sc(n,e,t){return new Os(e,t).build(n)}var mo=class{driver;framerate;resolveMedia;#e;constructor(e,t=30,r=o=>"/assets/temp/gl.mp4"){this.driver=e,this.framerate=t,this.resolveMedia=r,this.#e=oc(this.driver,this.resolveMedia)}async#t(e){let t=new Map(e.items.map(o=>[o.id,o])).get(e.rootId),r=new Map(e.items.map(o=>[o.id,o]));return await sc(t,r,this.#e)}async render(e){let t=await this.#t(e),r=new TransformStream,o=new TransformStream,i=this.driver.encode({video:r.readable,audio:o.readable,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}}),s=r.writable.getWriter(),a=o.writable.getWriter(),c=(async()=>{if(t.audio)for await(let u of t.audio.getStream())await a.write(u);await a.close()})(),l=(async()=>{let u=0,d=1/this.framerate;await Za({fps:this.framerate,duration:t.duration??0},async f=>{let m=await t.visuals?.sampleAt(f)??[],p=await this.driver.composite(m),h=new VideoFrame(p,{timestamp:Math.round(u*d*1e6),duration:Math.round(d*1e6)});await s.write(h),p.close(),u++}),await s.close()})();await c,await l,await i}};var po=class{driver;resources=new Jn;#e;constructor(e){this.driver=e,this.#e=new mo(e)}load=async e=>Object.fromEntries(await Promise.all(Object.entries(e).map(async([t,r])=>[t,await this.resources.store(await r)])));timeline=e=>{let t=new Xt({project:{format:"timeline",info:"https://omniclip.app/",version:0,items:[],rootId:0}}),r=e(t);return t.state.project.rootId=r.id,t.state.project};render=async e=>{await this.#e.render(e)}};var ho=class{data;bytes;hash;nickname;constructor(e,t,r,o){this.data=e,this.bytes=t,this.hash=r,this.nickname=o}static async make(e){let t=new Uint8Array(e),r=new Uint8Array(await crypto.subtle.digest("SHA-256",t)),o=Or.fromBytes(r),i=ti.sigil.fromBytes(r);return new this(e,r,o,i)}};var go=class{url;bytes;filename;checksum;constructor(e,t,r,o){this.url=e,this.bytes=t,this.filename=r,this.checksum=o}static async make(e,t){let r=await e.arrayBuffer(),o=new Uint8Array(r),i=await ho.make(o),s=t??i.nickname,a=URL.createObjectURL(e);return new this(a,o,s,i)}static async load(e){}};async function ic(n,e,t){let r=document.querySelector(".play"),o=document.querySelector(".stop"),i=document.querySelector(".seek"),s=new Xt({project:e}),a=await lo.create(n,e,c=>t.resources.require(c).url);document.body.appendChild(a.canvas),r.addEventListener("click",()=>a.play()),o.addEventListener("click",()=>a.pause()),i.addEventListener("change",async c=>{let l=c.target;await a.seek(+l.value)}),a.update(s.state.project)}async function ac(n){let e=document.querySelector(".waveform-demo"),t=document.querySelector(".width"),r=await to.init(n,"/assets/temp/gl.mp4",e);t.addEventListener("change",()=>{let o=+t.value;r.width=o})}async function cc(n,e){let t=new po(n),{videoA:r}=await t.load({videoA:go.make(e)});return{timeline:t.timeline(i=>{let s=i.text("content",{duration:1e3}),a=i.textStyle({fill:"green",fontSize:100});return i.set(s.id,{styleId:a.id}),i.sequence(i.stack(s,i.video(r,{duration:3e3,start:3e3}),i.audio(r,{duration:1e3,start:3e3})),i.gap(500),i.video(r,{duration:7e3,start:5e3}))}),omni:t}}async function lc(n){let e=document.querySelector(".range"),t=document.querySelector(".range-view"),r=document.querySelector(".range-size"),o=document.querySelector(".frequency"),i=document.querySelector(".frequency-view"),s=document.querySelector("#filmstrip"),a=1e3/10/1e3,c=.5,l=await Zn.init(n,{onChange(u){let d=u.sort((f,m)=>f.time-m.time);s.replaceChildren(...d.map(({time:f,canvas:m})=>pl(f,m.canvas)))},frequency:a,canvasSinkOptions:{width:80,height:50,fit:"fill"}});r.addEventListener("change",()=>{c=+r.value;let[u,d]=[+e.value,+e.value+c];l.range=[u,d],t.textContent=`visible time range: [${u}, ${d}]`}),e.addEventListener("change",()=>{let[u,d]=[+e.value,+e.value+c];l.range=[u,d],t.textContent=`visible time range: [${u}, ${d}]`}),o.addEventListener("change",()=>{l.frequency=1e3/+o.value/1e3,i.textContent=`frame every ${l.frequency.toFixed(3)} second (${o.value} frames per second)`}),l.range=[10,10.5]}function pl(n,e){let t=document.createElement("div");t.style.position="relative",t.style.display="inline-block",t.style.marginRight="4px",t.appendChild(e);let r=document.createElement("div");return r.textContent=`${n.toFixed(2)}s`,r.style.position="absolute",r.style.top="2px",r.style.right="4px",r.style.fontSize="10px",r.style.color="white",r.style.background="rgba(0,0,0,0.6)",r.style.padding="2px 4px",r.style.borderRadius="4px",r.style.pointerEvents="none",t.appendChild(r),t}function zs(n,e){let t={width:1920,height:1080},r=document.createElement("canvas");r.width=t.width,r.height=t.height;let o=r.getContext("2d");async function i(){let s=n.decodeVideo({source:e,async onFrame(c){let l=await n.composite([{id:0,kind:"image",frame:c},{id:1,kind:"text",content:"omnitool",style:{fontSize:50,fill:"green"}}]);return c.close(),o?.drawImage(l,0,0),l}}),a=n.decodeAudio({source:e});await n.encode({video:s,audio:a,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}})}return{canvas:r,run:i}}var gt=await Kn.setup({workerUrl:new URL("../driver/driver.worker.bundle.min.js",import.meta.url)}),hl=document.querySelector(".results"),gl=document.querySelector(".fetch"),uc=document.querySelector(".file-input");gl?.addEventListener("click",bl);uc?.addEventListener("input",xl);ac(gt);await gt.thread.work.hello(),gt.machina.count===1?console.log("\u2705 driver works"):console.error("\u274C FAIL driver call didn't work");async function xl(n){let e=uc.files?.[0];if(e){let t=zs(gt,e);await lc(e),dc(t,e.name);let{timeline:r,omni:o}=await cc(gt,e);ic(gt,r,o),Wa(o,r)}}async function bl(){let n=["/assets/temp/gl.mp4"];for(let e of n){let t=zs(gt,"/assets/temp/gl.mp4");dc(t,e)}}async function dc(n,e){let t=document.createElement("div");hl.append(t);let r=document.createElement("p");r.textContent=e,t.append(r),t.append(n.canvas),await n.run()}
2488
+ `,[e,t]}setOptions(e){if(this.options.container!==e.container){let t=this.parentFromOptionsContainer(e.container);t.appendChild(this.container),this.parent=t}e.dragToSeek!==!0&&typeof this.options.dragToSeek!="object"||this.initDrag(),this.options=e,this.reRender()}getWrapper(){return this.wrapper}getWidth(){return this.scrollContainer.clientWidth}getScroll(){return this.scrollContainer.scrollLeft}setScroll(e){this.scrollContainer.scrollLeft=e}setScrollPercentage(e){let{scrollWidth:t}=this.scrollContainer,r=t*e;this.setScroll(r)}destroy(){var e;this.subscriptions.forEach((t=>t())),this.container.remove(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),(e=this.unsubscribeOnScroll)===null||e===void 0||e.forEach((t=>t())),this.unsubscribeOnScroll=[],this.dragStream&&(this.dragStream.cleanup(),this.dragStream=null),this.scrollStream&&(this.scrollStream.cleanup(),this.scrollStream=null)}createDelay(e=10){let t,r,o=()=>{t&&(clearTimeout(t),t=void 0),r&&(r(),r=void 0)};return this.timeouts.push(o),()=>new Promise(((i,s)=>{o(),r=s,t=setTimeout((()=>{t=void 0,r=void 0,i()}),e)}))}getHeight(e,t){var r;let o=((r=this.audioData)===null||r===void 0?void 0:r.numberOfChannels)||1;return(function({optionsHeight:i,optionsSplitChannels:s,parentHeight:a,numberOfChannels:c,defaultHeight:l=128}){if(i==null)return l;let u=Number(i);if(!isNaN(u))return u;if(i==="auto"){let d=a||l;return s?.every((f=>!f.overlay))?d/c:d}return l})({optionsHeight:e,optionsSplitChannels:t,parentHeight:this.parent.clientHeight,numberOfChannels:o,defaultHeight:128})}convertColorValues(e,t){return(function(r,o,i){if(!Array.isArray(r))return r||"";if(r.length===0)return"#999";if(r.length<2)return r[0]||"";let s=document.createElement("canvas"),a=s.getContext("2d"),c=i??s.height*o,l=a.createLinearGradient(0,0,0,c||o),u=1/(r.length-1);return r.forEach(((d,f)=>{l.addColorStop(f*u,d)})),l})(e,this.getPixelRatio(),t?.canvas.height)}getPixelRatio(){return e=window.devicePixelRatio,Math.max(1,e||1);var e}renderBarWaveform(e,t,r,o){let{width:i,height:s}=r.canvas,{halfHeight:a,barWidth:c,barRadius:l,barIndexScale:u,barSpacing:d,barMinHeight:f}=(function({width:p,height:h,length:x,options:y,pixelRatio:b}){let v=h/2,w=y.barWidth?y.barWidth*b:1,S=y.barGap?y.barGap*b:y.barWidth?w/2:0,k=w+S||1;return{halfHeight:v,barWidth:w,barGap:S,barRadius:y.barRadius||0,barMinHeight:y.barMinHeight?y.barMinHeight*b:0,barIndexScale:x>0?p/k/x:0,barSpacing:k}})({width:i,height:s,length:(e[0]||[]).length,options:t,pixelRatio:this.getPixelRatio()}),m=(function({channelData:p,barIndexScale:h,barSpacing:x,barWidth:y,halfHeight:b,vScale:v,canvasHeight:w,barAlign:S,barMinHeight:k}){let I=p[0]||[],C=p[1]||I,E=I.length,R=[],D=0,L=0,Z=0;for(let O=0;O<=E;O++){let ze=Math.round(O*h);if(ze>D){let{topHeight:fc,totalHeight:Ls}=al({maxTop:L,maxBottom:Z,halfHeight:b,vScale:v,barMinHeight:k,barAlign:S}),mc=cl({barAlign:S,halfHeight:b,topHeight:fc,totalHeight:Ls,canvasHeight:w});R.push({x:D*x,y:mc,width:y,height:Ls}),D=ze,L=0,Z=0}let Ns=Math.abs(I[O]||0),Us=Math.abs(C[O]||0);Ns>L&&(L=Ns),Us>Z&&(Z=Us)}return R})({channelData:e,barIndexScale:u,barSpacing:d,barWidth:c,halfHeight:a,vScale:o,canvasHeight:s,barAlign:t.barAlign,barMinHeight:f});r.beginPath();for(let p of m)l&&"roundRect"in r?r.roundRect(p.x,p.y,p.width,p.height,l):r.rect(p.x,p.y,p.width,p.height);r.fill(),r.closePath()}renderLineWaveform(e,t,r,o){let{width:i,height:s}=r.canvas,a=(function({channelData:c,width:l,height:u,vScale:d}){let f=u/2,m=c[0]||[];return[m,c[1]||m].map(((p,h)=>{let x=p.length,y=x?l/x:0,b=f,v=h===0?-1:1,w=[{x:0,y:b}],S=0,k=0;for(let I=0;I<=x;I++){let C=Math.round(I*y);if(C>S){let R=b+(Math.round(k*f*d)||1)*v;w.push({x:S,y:R}),S=C,k=0}let E=Math.abs(p[I]||0);E>k&&(k=E)}return w.push({x:S,y:b}),w}))})({channelData:e,width:i,height:s,vScale:o});r.beginPath();for(let c of a)if(c.length){r.moveTo(c[0].x,c[0].y);for(let l=1;l<c.length;l++){let u=c[l];r.lineTo(u.x,u.y)}}r.fill(),r.closePath()}renderWaveform(e,t,r){if(r.fillStyle=this.convertColorValues(t.waveColor,r),t.renderFunction)return void t.renderFunction(e,r);let o=(function({channelData:i,barHeight:s,normalize:a,maxPeak:c}){var l;let u=s||1;if(!a)return u;let d=i[0];if(!d||d.length===0)return u;let f=c??0;if(!c)for(let m=0;m<d.length;m++){let p=(l=d[m])!==null&&l!==void 0?l:0,h=Math.abs(p);h>f&&(f=h)}return f?u/f:u})({channelData:e,barHeight:t.barHeight,normalize:t.normalize,maxPeak:t.maxPeak});Ka(t)?this.renderBarWaveform(e,t,r,o):this.renderLineWaveform(e,t,r,o)}renderSingleCanvas(e,t,r,o,i,s,a){let c=this.getPixelRatio(),l=document.createElement("canvas");l.width=Math.round(r*c),l.height=Math.round(o*c),l.style.width=`${r}px`,l.style.height=`${o}px`,l.style.left=`${Math.round(i)}px`,s.appendChild(l);let u=l.getContext("2d");if(t.renderFunction?(u.fillStyle=this.convertColorValues(t.waveColor,u),t.renderFunction(e,u)):this.renderWaveform(e,t,u),l.width>0&&l.height>0){let d=l.cloneNode(),f=d.getContext("2d");f.drawImage(l,0,0),f.globalCompositeOperation="source-in",f.fillStyle=this.convertColorValues(t.progressColor,f),f.fillRect(0,0,l.width,l.height),a.appendChild(d)}}renderMultiCanvas(e,t,r,o,i,s){let a=this.getPixelRatio(),{clientWidth:c}=this.scrollContainer,l=r/a,u=(function({clientWidth:p,totalWidth:h,options:x}){return ja(Math.min(8e3,p,h),x)})({clientWidth:c,totalWidth:l,options:t}),d={};if(u===0)return;let f=p=>{if(p<0||p>=m||d[p])return;d[p]=!0;let h=p*u,x=Math.min(l-h,u);if(x=ja(x,t),x<=0)return;let y=(function({channelData:b,offset:v,clampedWidth:w,totalWidth:S}){return b.map((k=>{let I=Math.floor(v/S*k.length),C=Math.floor((v+w)/S*k.length);return k.slice(I,C)}))})({channelData:e,offset:h,clampedWidth:x,totalWidth:l});this.renderSingleCanvas(y,t,x,o,h,i,s)},m=Math.ceil(l/u);if(!this.isScrollable){for(let p=0;p<m;p++)f(p);return}if($a({scrollLeft:this.scrollContainer.scrollLeft,totalWidth:l,numCanvases:m}).forEach((p=>f(p))),m>1){let p=this.on("scroll",(()=>{let{scrollLeft:h}=this.scrollContainer;Object.keys(d).length>10&&(i.innerHTML="",s.innerHTML="",d={}),$a({scrollLeft:h,totalWidth:l,numCanvases:m}).forEach((x=>f(x)))}));this.unsubscribeOnScroll.push(p)}}renderChannel(e,t,r,o){var{overlay:i}=t,s=(function(u,d){var f={};for(var m in u)Object.prototype.hasOwnProperty.call(u,m)&&d.indexOf(m)<0&&(f[m]=u[m]);if(u!=null&&typeof Object.getOwnPropertySymbols=="function"){var p=0;for(m=Object.getOwnPropertySymbols(u);p<m.length;p++)d.indexOf(m[p])<0&&Object.prototype.propertyIsEnumerable.call(u,m[p])&&(f[m[p]]=u[m[p]])}return f})(t,["overlay"]);let a=document.createElement("div"),c=this.getHeight(s.height,s.splitChannels);a.style.height=`${c}px`,i&&o>0&&(a.style.marginTop=`-${c}px`),this.canvasWrapper.style.minHeight=`${c}px`,this.canvasWrapper.appendChild(a);let l=a.cloneNode();this.progressWrapper.appendChild(l),this.renderMultiCanvas(e,s,r,c,a,l)}render(e){return ne(this,void 0,void 0,(function*(){var t;this.timeouts.forEach((l=>l())),this.timeouts=[],this.canvasWrapper.innerHTML="",this.progressWrapper.innerHTML="",this.options.width!=null&&(this.scrollContainer.style.width=typeof this.options.width=="number"?`${this.options.width}px`:this.options.width);let r=this.getPixelRatio(),o=this.scrollContainer.clientWidth,{scrollWidth:i,isScrollable:s,useParentWidth:a,width:c}=(function({duration:l,minPxPerSec:u=0,parentWidth:d,fillParent:f,pixelRatio:m}){let p=Math.ceil(l*u),h=p>d,x=!!(f&&!h);return{scrollWidth:p,isScrollable:h,useParentWidth:x,width:(x?d:p)*m}})({duration:e.duration,minPxPerSec:this.options.minPxPerSec||0,parentWidth:o,fillParent:this.options.fillParent,pixelRatio:r});if(this.isScrollable=s,this.wrapper.style.width=a?"100%":`${i}px`,this.scrollContainer.style.overflowX=this.isScrollable?"auto":"hidden",this.scrollContainer.classList.toggle("noScrollbar",!!this.options.hideScrollbar),this.cursor.style.backgroundColor=`${this.options.cursorColor||this.options.progressColor}`,this.cursor.style.width=`${this.options.cursorWidth}px`,this.audioData=e,this.emit("render"),this.options.splitChannels)for(let l=0;l<e.numberOfChannels;l++){let u=Object.assign(Object.assign({},this.options),(t=this.options.splitChannels)===null||t===void 0?void 0:t[l]);this.renderChannel([e.getChannelData(l)],u,c,l)}else{let l=[e.getChannelData(0)];e.numberOfChannels>1&&l.push(e.getChannelData(1)),this.renderChannel(l,this.options,c,0)}Promise.resolve().then((()=>this.emit("rendered")))}))}reRender(){if(this.unsubscribeOnScroll.forEach((r=>r())),this.unsubscribeOnScroll=[],!this.audioData)return;let{scrollWidth:e}=this.scrollContainer,{right:t}=this.progressWrapper.getBoundingClientRect();if(this.render(this.audioData),this.isScrollable&&e!==this.scrollContainer.scrollWidth){let{right:r}=this.progressWrapper.getBoundingClientRect(),o=(function(i){let s=2*i;return(s<0?Math.floor(s):Math.ceil(s))/2})(r-t);this.scrollContainer.scrollLeft+=o}}zoom(e){this.options.minPxPerSec=e,this.reRender()}scrollIntoView(e,t=!1){let{scrollLeft:r,scrollWidth:o,clientWidth:i}=this.scrollContainer,s=e*o,a=r,c=r+i,l=i/2;if(this.isDragging)s+30>c?this.scrollContainer.scrollLeft+=30:s-30<a&&(this.scrollContainer.scrollLeft-=30);else{(s<a||s>c)&&(this.scrollContainer.scrollLeft=s-(this.options.autoCenter?l:0));let u=s-r-l;t&&this.options.autoCenter&&u>0&&(this.scrollContainer.scrollLeft+=u)}}renderProgress(e,t){if(isNaN(e))return;let r=100*e;this.canvasWrapper.style.clipPath=`polygon(${r}% 0%, 100% 0%, 100% 100%, ${r}% 100%)`,this.progressWrapper.style.width=`${r}%`,this.cursor.style.left=`${r}%`,this.cursor.style.transform=this.options.cursorWidth?`translateX(-${e*this.options.cursorWidth}px)`:"",this.isScrollable&&this.options.autoScroll&&this.audioData&&this.audioData.duration>0&&this.scrollIntoView(e,t)}exportImage(e,t,r){return ne(this,void 0,void 0,(function*(){let o=this.canvasWrapper.querySelectorAll("canvas");if(!o.length)throw new Error("No waveform data");if(r==="dataURL"){let i=Array.from(o).map((s=>s.toDataURL(e,t)));return Promise.resolve(i)}return Promise.all(Array.from(o).map((i=>new Promise(((s,a)=>{i.toBlob((c=>{c?s(c):a(new Error("Could not export image"))}),e,t)})))))}))}},Fs=class extends ht{constructor(){super(...arguments),this.animationFrameId=null,this.isRunning=!1}start(){if(this.isRunning)return;this.isRunning=!0;let e=()=>{this.isRunning&&(this.emit("tick"),this.animationFrameId=requestAnimationFrame(e))};e()}stop(){this.isRunning=!1,this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}destroy(){this.stop()}},Sr=class extends ht{constructor(e=new AudioContext){super(),this.bufferNode=null,this.playStartTime=0,this.playedDuration=0,this._muted=!1,this._playbackRate=1,this._duration=void 0,this.buffer=null,this.currentSrc="",this.paused=!0,this.crossOrigin=null,this.seeking=!1,this.autoplay=!1,this.addEventListener=this.on,this.removeEventListener=this.un,this.audioContext=e,this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination)}load(){return ne(this,void 0,void 0,(function*(){}))}get src(){return this.currentSrc}set src(e){if(this.currentSrc=e,this._duration=void 0,!e)return this.buffer=null,void this.emit("emptied");fetch(e).then((t=>{if(t.status>=400)throw new Error(`Failed to fetch ${e}: ${t.status} (${t.statusText})`);return t.arrayBuffer()})).then((t=>this.currentSrc!==e?null:this.audioContext.decodeAudioData(t))).then((t=>{this.currentSrc===e&&(this.buffer=t,this.emit("loadedmetadata"),this.emit("canplay"),this.autoplay&&this.play())})).catch((t=>{console.error("WebAudioPlayer load error:",t)}))}_play(){if(!this.paused)return;this.paused=!1,this.bufferNode&&(this.bufferNode.onended=null,this.bufferNode.disconnect()),this.bufferNode=this.audioContext.createBufferSource(),this.buffer&&(this.bufferNode.buffer=this.buffer),this.bufferNode.playbackRate.value=this._playbackRate,this.bufferNode.connect(this.gainNode);let e=this.playedDuration*this._playbackRate;(e>=this.duration||e<0)&&(e=0,this.playedDuration=0),this.bufferNode.start(this.audioContext.currentTime,e),this.playStartTime=this.audioContext.currentTime,this.bufferNode.onended=()=>{this.currentTime>=this.duration&&(this.pause(),this.emit("ended"))}}_pause(){var e;this.paused=!0,(e=this.bufferNode)===null||e===void 0||e.stop(),this.playedDuration+=this.audioContext.currentTime-this.playStartTime}play(){return ne(this,void 0,void 0,(function*(){this.paused&&(this._play(),this.emit("play"))}))}pause(){this.paused||(this._pause(),this.emit("pause"))}stopAt(e){let t=e-this.currentTime,r=this.bufferNode;r?.stop(this.audioContext.currentTime+t),r?.addEventListener("ended",(()=>{r===this.bufferNode&&(this.bufferNode=null,this.pause())}),{once:!0})}setSinkId(e){return ne(this,void 0,void 0,(function*(){return this.audioContext.setSinkId(e)}))}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e,this.bufferNode&&(this.bufferNode.playbackRate.value=e)}get currentTime(){return(this.paused?this.playedDuration:this.playedDuration+(this.audioContext.currentTime-this.playStartTime))*this._playbackRate}set currentTime(e){let t=!this.paused;t&&this._pause(),this.playedDuration=e/this._playbackRate,t&&this._play(),this.emit("seeking"),this.emit("timeupdate")}get duration(){var e,t;return(e=this._duration)!==null&&e!==void 0?e:((t=this.buffer)===null||t===void 0?void 0:t.duration)||0}set duration(e){this._duration=e}get volume(){return this.gainNode.gain.value}set volume(e){this.gainNode.gain.value=e,this.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted!==e&&(this._muted=e,this._muted?this.gainNode.disconnect():this.gainNode.connect(this.audioContext.destination))}canPlayType(e){return/^(audio|video)\//.test(e)}getGainNode(){return this.gainNode}getChannelData(){let e=[];if(!this.buffer)return e;let t=this.buffer.numberOfChannels;for(let r=0;r<t;r++)e.push(this.buffer.getChannelData(r));return e}removeAttribute(e){switch(e){case"src":this.src="";break;case"playbackRate":this.playbackRate=0;break;case"currentTime":this.currentTime=0;break;case"duration":this.duration=0;break;case"volume":this.volume=0;break;case"muted":this.muted=!1}}},ul={waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,dragToSeek:!1,autoScroll:!0,autoCenter:!0,sampleRate:8e3},Wt=class n extends _s{static create(e){return new n(e)}getState(){return this.wavesurferState}getRenderer(){return this.renderer}constructor(e){let t=e.media||(e.backend==="WebAudio"?new Sr:void 0);super({media:t,mediaControls:e.mediaControls,autoplay:e.autoplay,playbackRate:e.audioRate}),this.plugins=[],this.decodedData=null,this.stopAtPosition=null,this.subscriptions=[],this.mediaSubscriptions=[],this.abortController=null,this.reactiveCleanups=[],this.options=Object.assign({},ul,e);let{state:r,actions:o}=(function(a){var c,l,u,d,f,m;let p=(c=a?.currentTime)!==null&&c!==void 0?c:W(0),h=(l=a?.duration)!==null&&l!==void 0?l:W(0),x=(u=a?.isPlaying)!==null&&u!==void 0?u:W(!1),y=(d=a?.isSeeking)!==null&&d!==void 0?d:W(!1),b=(f=a?.volume)!==null&&f!==void 0?f:W(1),v=(m=a?.playbackRate)!==null&&m!==void 0?m:W(1),w=W(null),S=W(null),k=W(""),I=W(0),C=W(0),E=pt((()=>!x.value),[x]),R=pt((()=>w.value!==null),[w]),D=pt((()=>R.value&&h.value>0),[R,h]),L=pt((()=>p.value),[p]),Z=pt((()=>h.value>0?p.value/h.value:0),[p,h]);return{state:{currentTime:p,duration:h,isPlaying:x,isPaused:E,isSeeking:y,volume:b,playbackRate:v,audioBuffer:w,peaks:S,url:k,zoom:I,scrollPosition:C,canPlay:R,isReady:D,progress:L,progressPercent:Z},actions:{setCurrentTime:O=>{let ze=Math.max(0,Math.min(h.value||1/0,O));p.set(ze)},setDuration:O=>{h.set(Math.max(0,O))},setPlaying:O=>{x.set(O)},setSeeking:O=>{y.set(O)},setVolume:O=>{let ze=Math.max(0,Math.min(1,O));b.set(ze)},setPlaybackRate:O=>{let ze=Math.max(.1,Math.min(16,O));v.set(ze)},setAudioBuffer:O=>{w.set(O),O&&h.set(O.duration)},setPeaks:O=>{S.set(O)},setUrl:O=>{k.set(O)},setZoom:O=>{I.set(Math.max(0,O))},setScrollPosition:O=>{C.set(Math.max(0,O))}}}})({isPlaying:this.isPlayingSignal,currentTime:this.currentTimeSignal,duration:this.durationSignal,volume:this.volumeSignal,playbackRate:this.playbackRateSignal,isSeeking:this.seekingSignal});this.wavesurferState=r,this.wavesurferActions=o,this.timer=new Fs;let i=t?void 0:this.getMediaElement();this.renderer=new Es(this.options,i),this.initPlayerEvents(),this.initRendererEvents(),this.initTimerEvents(),this.initReactiveState(),this.initPlugins();let s=this.options.url||this.getSrc()||"";Promise.resolve().then((()=>{this.emit("init");let{peaks:a,duration:c}=this.options;(s||a&&c)&&this.load(s,a,c).catch((l=>{this.emit("error",l instanceof Error?l:new Error(String(l)))}))}))}updateProgress(e=this.getCurrentTime()){return this.renderer.renderProgress(e/this.getDuration(),this.isPlaying()),e}initTimerEvents(){this.subscriptions.push(this.timer.on("tick",(()=>{if(!this.isSeeking()){let e=this.updateProgress();this.emit("timeupdate",e),this.emit("audioprocess",e),this.stopAtPosition!=null&&this.isPlaying()&&e>=this.stopAtPosition&&this.pause()}})))}initReactiveState(){this.reactiveCleanups.push((function(e,t){let r=[];r.push($e((()=>{let s=e.isPlaying.value;t.emit(s?"play":"pause")}),[e.isPlaying])),r.push($e((()=>{let s=e.currentTime.value;t.emit("timeupdate",s),e.isPlaying.value&&t.emit("audioprocess",s)}),[e.currentTime,e.isPlaying])),r.push($e((()=>{e.isSeeking.value&&t.emit("seeking",e.currentTime.value)}),[e.isSeeking,e.currentTime]));let o=!1;r.push($e((()=>{e.isReady.value&&!o&&(o=!0,t.emit("ready",e.duration.value))}),[e.isReady,e.duration]));let i=!1;return r.push($e((()=>{let s=e.isPlaying.value,a=e.currentTime.value,c=e.duration.value,l=c>0&&a>=c;i&&!s&&l&&t.emit("finish"),i=s&&l}),[e.isPlaying,e.currentTime,e.duration])),r.push($e((()=>{let s=e.zoom.value;s>0&&t.emit("zoom",s)}),[e.zoom])),()=>{r.forEach((s=>s()))}})(this.wavesurferState,{emit:this.emit.bind(this)}))}initPlayerEvents(){this.isPlaying()&&(this.emit("play"),this.timer.start()),this.mediaSubscriptions.push(this.onMediaEvent("timeupdate",(()=>{let e=this.updateProgress();this.emit("timeupdate",e)})),this.onMediaEvent("play",(()=>{this.emit("play"),this.timer.start()})),this.onMediaEvent("pause",(()=>{this.emit("pause"),this.timer.stop(),this.stopAtPosition=null})),this.onMediaEvent("emptied",(()=>{this.timer.stop(),this.stopAtPosition=null})),this.onMediaEvent("ended",(()=>{this.emit("timeupdate",this.getDuration()),this.emit("finish"),this.stopAtPosition=null})),this.onMediaEvent("seeking",(()=>{this.emit("seeking",this.getCurrentTime())})),this.onMediaEvent("error",(()=>{var e;this.emit("error",(e=this.getMediaElement().error)!==null&&e!==void 0?e:new Error("Media error")),this.stopAtPosition=null})))}initRendererEvents(){this.subscriptions.push(this.renderer.on("click",((e,t)=>{this.options.interact&&(this.seekTo(e),this.emit("interaction",e*this.getDuration()),this.emit("click",e,t))})),this.renderer.on("dblclick",((e,t)=>{this.emit("dblclick",e,t)})),this.renderer.on("scroll",((e,t,r,o)=>{let i=this.getDuration();this.emit("scroll",e*i,t*i,r,o)})),this.renderer.on("render",(()=>{this.emit("redraw")})),this.renderer.on("rendered",(()=>{this.emit("redrawcomplete")})),this.renderer.on("dragstart",(e=>{this.emit("dragstart",e)})),this.renderer.on("dragend",(e=>{this.emit("dragend",e)})),this.renderer.on("resize",(()=>{this.emit("resize")})));{let e,t=this.renderer.on("drag",(r=>{var o;if(!this.options.interact)return;this.renderer.renderProgress(r),clearTimeout(e);let i=0,s=this.options.dragToSeek;this.isPlaying()?i=0:s===!0?i=200:s&&typeof s=="object"&&(i=(o=s.debounceTime)!==null&&o!==void 0?o:200),e=setTimeout((()=>{this.seekTo(r)}),i),this.emit("interaction",r*this.getDuration()),this.emit("drag",r)}));this.subscriptions.push((()=>{clearTimeout(e),t()}))}}initPlugins(){var e;!((e=this.options.plugins)===null||e===void 0)&&e.length&&this.options.plugins.forEach((t=>{this.registerPlugin(t)}))}unsubscribePlayerEvents(){this.mediaSubscriptions.forEach((e=>e())),this.mediaSubscriptions=[]}setOptions(e){this.options=Object.assign({},this.options,e),e.duration&&!e.peaks&&(this.decodedData=eo.createBuffer(this.exportPeaks(),e.duration)),e.peaks&&e.duration&&(this.decodedData=eo.createBuffer(e.peaks,e.duration)),this.renderer.setOptions(this.options),e.audioRate&&this.setPlaybackRate(e.audioRate),e.mediaControls!=null&&(this.getMediaElement().controls=e.mediaControls)}registerPlugin(e){if(this.plugins.includes(e))return e;e._init(this),this.plugins.push(e);let t=e.once("destroy",(()=>{this.plugins=this.plugins.filter((r=>r!==e)),this.subscriptions=this.subscriptions.filter((r=>r!==t))}));return this.subscriptions.push(t),e}unregisterPlugin(e){this.plugins=this.plugins.filter((t=>t!==e)),e.destroy()}getWrapper(){return this.renderer.getWrapper()}getWidth(){return this.renderer.getWidth()}getScroll(){return this.renderer.getScroll()}setScroll(e){return this.renderer.setScroll(e)}setScrollTime(e){let t=e/this.getDuration();this.renderer.setScrollPercentage(t)}getActivePlugins(){return this.plugins}loadAudio(e,t,r,o){return ne(this,void 0,void 0,(function*(){var i;if(this.emit("load",e),!this.options.media&&this.isPlaying()&&this.pause(),this.decodedData=null,this.stopAtPosition=null,(i=this.abortController)===null||i===void 0||i.abort(),this.abortController=null,!t&&!r){let a=this.options.fetchParams||{};window.AbortController&&!a.signal&&(this.abortController=new AbortController,a.signal=this.abortController.signal);let c=u=>this.emit("loading",u);t=yield il.fetchBlob(e,c,a);let l=this.options.blobMimeType;l&&(t=new Blob([t],{type:l}))}this.setSrc(e,t);let s=yield new Promise((a=>{let c=o||this.getDuration();c?a(c):this.mediaSubscriptions.push(this.onMediaEvent("loadedmetadata",(()=>a(this.getDuration())),{once:!0}))}));if(!e&&!t){let a=this.getMediaElement();a instanceof Sr&&(a.duration=s)}if(r)this.decodedData=eo.createBuffer(r,s||0);else if(t){let a=yield t.arrayBuffer();this.decodedData=yield eo.decode(a,this.options.sampleRate)}this.decodedData&&(this.emit("decode",this.getDuration()),this.renderer.render(this.decodedData)),this.emit("ready",this.getDuration())}))}load(e,t,r){return ne(this,void 0,void 0,(function*(){try{return yield this.loadAudio(e,void 0,t,r)}catch(o){throw this.emit("error",o),o}}))}loadBlob(e,t,r){return ne(this,void 0,void 0,(function*(){try{return yield this.loadAudio("",e,t,r)}catch(o){throw this.emit("error",o),o}}))}zoom(e){if(!this.decodedData)throw new Error("No audio loaded");this.renderer.zoom(e),this.emit("zoom",e)}getDecodedData(){return this.decodedData}exportPeaks({channels:e=2,maxLength:t=8e3,precision:r=1e4}={}){if(!this.decodedData)throw new Error("The audio has not been decoded yet");let o=Math.min(e,this.decodedData.numberOfChannels),i=[];for(let s=0;s<o;s++){let a=this.decodedData.getChannelData(s),c=[],l=a.length/t;for(let u=0;u<t;u++){let d=a.slice(Math.floor(u*l),Math.ceil((u+1)*l)),f=0;for(let m=0;m<d.length;m++){let p=d[m];Math.abs(p)>Math.abs(f)&&(f=p)}c.push(Math.round(f*r)/r)}i.push(c)}return i}getDuration(){let e=super.getDuration()||0;return e!==0&&e!==1/0||!this.decodedData||(e=this.decodedData.duration),e}toggleInteraction(e){this.options.interact=e}setTime(e){this.stopAtPosition=null,super.setTime(e),this.updateProgress(e),this.emit("timeupdate",e)}seekTo(e){let t=this.getDuration()*e;this.setTime(t)}play(e,t){let r=Object.create(null,{play:{get:()=>super.play}});return ne(this,void 0,void 0,(function*(){e!=null&&this.setTime(e);let o=yield r.play.call(this);return t!=null&&(this.media instanceof Sr?this.media.stopAt(t):this.stopAtPosition=t),o}))}playPause(){return ne(this,void 0,void 0,(function*(){return this.isPlaying()?this.pause():this.play()}))}stop(){this.pause(),this.setTime(0)}skip(e){this.setTime(this.getCurrentTime()+e)}empty(){this.load("",[[0]],.001)}setMediaElement(e){this.unsubscribePlayerEvents(),super.setMediaElement(e),this.initPlayerEvents()}exportImage(){return ne(this,arguments,void 0,(function*(e="image/png",t=1,r="dataURL"){return this.renderer.exportImage(e,t,r)}))}destroy(){var e;this.emit("destroy"),(e=this.abortController)===null||e===void 0||e.abort(),this.plugins.forEach((t=>t.destroy())),this.subscriptions.forEach((t=>t())),this.unsubscribePlayerEvents(),this.reactiveCleanups.forEach((t=>t())),this.reactiveCleanups=[],this.timer.destroy(),this.renderer.destroy(),super.destroy()}};Wt.BasePlugin=class extends ht{constructor(n){super(),this.subscriptions=[],this.isDestroyed=!1,this.options=n}onInit(){}_init(n){this.isDestroyed&&(this.subscriptions=[],this.isDestroyed=!1),this.wavesurfer=n,this.onInit()}destroy(){this.emit("destroy"),this.subscriptions.forEach((n=>n())),this.subscriptions=[],this.isDestroyed=!0,this.wavesurfer=void 0}},Wt.dom=sl;var to=class n{wavesurfer;constructor(e,t,r){this.wavesurfer=Wt.create({container:t,waveColor:"rgb(200, 0, 200)",progressColor:"rgb(100, 0, 100)",barWidth:10,barRadius:10,barGap:2,peaks:[e],duration:r})}static async init(e,t,r){let o=e.decodeAudio({source:t}).getReader(),i=[],s=[],a=1024,c=await e.getAudioDuration(t);for(;;){let{done:l,value:u}=await o.read();if(l)break;let d=u.numberOfFrames,f=new Float32Array(d);u.copyTo(f,{planeIndex:0});for(let m=0;m<f.length;m++)if(s.push(f[m]),s.length>=a){let p=s.splice(0,a),h=Math.min(...p),x=Math.max(...p);i.push(h,x)}u.close()}return new n(i,r,c??0)}set width(e){this.wavesurfer.setOptions({width:e})}};function Ya(n){return Pe.freeze(Pe.clone(n))}var Ds=class{#e=[];#t=new WeakMap;#r=[];#n=new Set;notifyRead(e){this.#e.at(-1)?.add(e)}async notifyWrite(e){if(this.#n.has(e))throw new Error("circularity forbidden");let t=this.#o(e).pub();return this.#r.at(-1)?.add(t),t}observe(e){this.#e.push(new Set);let t=e();return{seen:this.#e.pop(),result:t}}subscribe(e,t){return this.#o(e)(async()=>{let r=new Set;this.#r.push(r),this.#n.add(e),r.add(t()),this.#n.delete(e),await Promise.all(r),this.#r.pop()})}#o(e){let t=this.#t.get(e);return t||(t=vt(),this.#t.set(e,t)),t}},Q=globalThis[Symbol.for("e280.tracker")]??=new Ds;var ke=Symbol("optic");var ro=class{calculate;#e=!1;#t;constructor(e){this.calculate=e,this.#t=e()}get(){return this.#e&&(this.#e=!1,this.#t=this.calculate()),this.#t}invalidate(){this.#e=!0}};var no=class n{on=vt();[ke];#e;#t;#r=zr(()=>this.on.publish(this.state));constructor(e){this[ke]=e,this.#e=Pe.clone(e.getState()),this.#t=new ro(()=>Ya(e.getState()))}async update(){let e=this[ke].getState();!Pe.equal(e,this.#e)&&(this.#t.invalidate(),this.#e=Pe.clone(e),this.#r(),await Q.notifyWrite(this))}get state(){return Q.notifyRead(this),this.#t.get()}async mutate(e){return this[ke].mutate(e)}lens(e){let t=new n({getState:()=>e(this[ke].getState()),mutate:r=>this[ke].mutate(o=>r(e(o))),registerLens:this[ke].registerLens});return this[ke].registerLens(t),t}};var qt=class{sneak;constructor(e){this.sneak=e}get(){return Q.notifyRead(this),this.sneak}get value(){return this.get()}};var Gt=class extends qt{on=vt();dispose(){this.on.clear()}};function oo(n,e=n){let{seen:t,result:r}=Q.observe(n),o=zr(e),i=[],s=()=>i.forEach(a=>a());for(let a of t){let c=Q.subscribe(a,o);i.push(c)}return{result:r,dispose:s}}function jt(n,e){return n===e}var so=class extends Gt{#e;constructor(e,t){let r=t?.compare??jt,{result:o,dispose:i}=oo(e,async()=>{let s=e();!r(this.sneak,s)&&(this.sneak=s,await Promise.all([Q.notifyWrite(this),this.on.pub(s)]))});super(o),this.#e=i}toString(){return`(derived "${String(this.get())}")`}dispose(){super.dispose(),this.#e()}get core(){return this}fn(){let e=this;function t(){return e.get()}return t.core=e,t.get=e.get.bind(e),t.on=e.on,t.dispose=e.dispose.bind(e),t.fn=e.fn.bind(e),Object.defineProperty(t,"value",{get:()=>e.value}),Object.defineProperty(t,"sneak",{get:()=>e.sneak}),t}};var io=class extends qt{#e;#t;#r=!1;#n;constructor(e,t){super(void 0),this.#e=e,this.#t=t?.compare??jt}toString(){return`($lazy "${String(this.get())}")`}get(){if(!this.#n){let{result:e,dispose:t}=oo(this.#e,()=>this.#r=!0);this.#n=t,this.sneak=e}if(this.#r){this.#r=!1;let e=this.#e();!this.#t(this.sneak,e)&&(this.sneak=e,Q.notifyWrite(this))}return super.get()}dispose(){this.#n&&this.#n()}get core(){return this}fn(){let e=this;function t(){return e.get()}return t.core=e,t.get=e.get.bind(e),t.dispose=e.dispose.bind(e),t.fn=e.fn.bind(e),Object.defineProperty(t,"value",{get:()=>e.value}),Object.defineProperty(t,"sneak",{get:()=>e.sneak}),t}};var ao=class extends Gt{#e=!1;#t;constructor(e,t){super(e),this.#t=t?.compare??jt}toString(){return`($signal "${String(this.get())}")`}async set(e,t=!1){let r=this.sneak;return this.sneak=e,(t||!this.#t(r,e))&&await this.publish(),e}get value(){return this.get()}set value(e){this.set(e)}async publish(){if(this.#e)throw new Error("forbid circularity");let e=this.sneak,t=Promise.resolve();try{this.#e=!0,t=Promise.all([Q.notifyWrite(this),this.on.publish(e)])}finally{this.#e=!1}return await t,e}get core(){return this}fn(){let e=this;function t(r){return arguments.length===0?e.get():e.set(arguments[0])}return t.core=e,t.get=e.get.bind(e),t.set=e.set.bind(e),t.on=e.on,t.dispose=e.dispose.bind(e),t.publish=e.publish.bind(e),t.fn=e.fn.bind(e),Object.defineProperty(t,"value",{get:()=>e.value,set:r=>e.value=r}),Object.defineProperty(t,"sneak",{get:()=>e.sneak,set:r=>e.sneak=r}),t}};function dl(n,e){return new io(n,e).fn()}function fl(n,e){return new so(n,e).fn()}function Pr(n,e){return new ao(n,e).fn()}Pr.lazy=dl;Pr.derived=fl;var Ja=(n,e)=>{let t=!1,r=null,o=60,i=1e3/o,s=0,a=0,c=0,l=0,u=d=>{if(!t)return;let f=d-a;for(a=d,c+=f,l+=f,e(l);c>=i;)n(s),s+=i,c-=i;r=requestAnimationFrame(u)};return{play(){t||(t=!0,a=performance.now(),r=requestAnimationFrame(u))},pause(){t&&(t=!1,r!==null&&cancelAnimationFrame(r),r=null)},seek(d){s=d,c=0,l=d,e(d)},dispose(){this.pause()},isPlaying(){return t},setFPS(d){o=d,i=1e3/o}}},Za=async(n,e)=>{let t=1e3/n.fps,r=n.duration/1e3,o=Math.ceil(r*n.fps);for(let i=0;i<o&&!n.abort?.aborted;i++){let s=i*t;await e(s,i)}};var ec=n=>n instanceof Blob?URL.createObjectURL(n):String(n);function rc(n){let e=new Map,t=new Map;function r(s){let a=e.get(s.id);return a||(a=document.createElement("video"),a.playsInline=!0,a.muted=!0,a.preload="auto",a.crossOrigin="anonymous",a.src=ec(n(s.mediaHash)),e.set(s.id,a)),a}function o(s){let a=t.get(s.id);return a||(a=document.createElement("audio"),a.preload="auto",a.crossOrigin="anonymous",a.src=ec(n(s.mediaHash)),a.volume=.2,t.set(s.id,a)),a}let i=!0;return{async video(s,a){let c=r(s);return{duration:s.duration,visuals:{sampleAt:async l=>{let u=s.start+l,d=s.start+s.duration;if(u<s.start||u>=d)return c.pause(),[];c.paused&&i&&await tc(c,u/1e3),c.paused&&!i&&await c.play();let f=new VideoFrame(c);return f?[{kind:"image",frame:f,matrix:a,id:s.id}]:[]}}}},async audio(s){let a=o(s);return{duration:s.duration,audio:{onTimeUpdate:async c=>{let l=s.start+c,u=s.start+s.duration;return l<s.start||l>=u?(a.pause(),[]):(a.paused&&i&&await tc(a,l/1e3),a.paused&&!i&&await a.play(),[])}}}},async dispose(){let s=[...e.values(),...t.values()];for(let a of s)a.pause(),a.src.startsWith("blob:")&&URL.revokeObjectURL(a.src),a.remove();e.clear(),t.clear()},async setPaused(s){i=s;let a=[...e.values(),...t.values()];for(let c of a)s&&c.pause()}}}function tc(n,e){return new Promise(t=>{let r=()=>{n.removeEventListener("seeked",r),t()};n.addEventListener("seeked",r),n.fastSeek?n.fastSeek(e):n.currentTime=e})}var Rs=(n,e)=>n.get(e),co=(n,e,t)=>{let r=t??Ba;if(e.spatialId){let o=Rs(n,e.spatialId);if(o.enabled){let i=Da(o.transform);r=Ma(i,r)}}return r},$t=class{items;sampler;constructor(e,t){this.items=e,this.sampler=t}async build(e,t){switch(e.kind){case H.Video:return this.sampler.video(e,co(this.items,e,t));case H.Audio:return this.sampler.audio(e);case H.Text:{let r=co(this.items,e,t),o=e.styleId!==void 0?this.items.get(e.styleId):void 0;return{duration:e.duration,visuals:{sampleAt:async i=>i<0||i>=e.duration?[]:[{id:e.id,kind:"text",content:e.content,style:o?.style,matrix:r}]}}}case H.Gap:return{duration:e.duration,visuals:{sampleAt:async()=>[]}};case H.Stack:{let r=co(this.items,e,t),o=await Promise.all(e.childrenIds.map(i=>this.build(Rs(this.items,i),r)));return this.#r(o)}case H.Sequence:{let r=co(this.items,e,t);return this.#n(e,r)}default:return{duration:0}}}#e(e){return{sampleAt:async t=>(await Promise.all(e.map(o=>o.visuals?o.visuals.sampleAt(t):Promise.resolve([])))).flat()}}#t(e){return{sampleAt:async t=>{let r=Math.round(t);for(let o of e){if(r<=o.duration)return o.visuals?o.visuals.sampleAt(r):[];r-=o.duration}return[]}}}#r(e){return{duration:Math.max(0,...e.map(r=>Number.isFinite(r.duration)?r.duration:0)),visuals:this.#e(e),audio:this.composeAudio_Stack(e)}}async#n(e,t){let r=e.childrenIds.map(s=>Rs(this.items,s)),o=await this.#o(r,t);return{duration:o.reduce((s,a)=>s+a.duration,0),visuals:this.#t(o),audio:this.composeAudio_Sequence(o)}}async#o(e,t){let r=[];for(let o=0;o<e.length;o++){let i=e[o];if(i.kind!==H.Transition){r.push(await this.build(i,t));continue}let s=r.pop(),a=e[o+1];if(!s||!a||a.kind===H.Transition){s&&r.push(s);continue}let c=await this.build(a,t),l=await this.#a(i,s,c);r.push(l),o++}return r}async#a(e,t,r){let o=Math.max(0,Math.min(e.duration,t.duration,r.duration)),i=Math.max(0,t.duration-o);return{duration:t.duration+r.duration-o,visuals:{sampleAt:async a=>{if(!t.visuals||!r.visuals)return[];if(a<i)return t.visuals.sampleAt(a);if(a<t.duration){let c=a-i,l=o>0?c/o:1,u=await t.visuals.sampleAt(a),d=await r.visuals.sampleAt(c);return!u[0]?.frame||!d[0]?.frame?[]:[{id:e.id,kind:"transition",name:"circle",progress:l,from:u[0].frame,to:d[0].frame}]}return r.visuals.sampleAt(a-t.duration+o)}},audio:this.composeAudio_Sequence([t,r])}}};var Ms=class extends $t{items;sampler;constructor(e,t){super(e,t),this.items=e,this.sampler=t}composeAudio_Stack(e){return{onTimeUpdate:t=>{for(let r of e)r.audio&&r.audio.onTimeUpdate(t)}}}composeAudio_Sequence(e){return{onTimeUpdate:t=>{let r=Math.round(t);for(let o of e){if(r<=o.duration){o.audio&&o.audio.onTimeUpdate(r);break}r-=o.duration}}}}};function Bs(n,e,t){return new Ms(e,t).build(n)}var lo=class{driver;canvas;root;sampler;currentTime=Pr(0);#e=Ja(e=>this.#t(e),e=>this.currentTime(e));constructor(e,t,r,o){this.driver=e,this.canvas=t,this.root=r,this.sampler=o,this.#e.setFPS(30)}static async create(e,t,r){let o=new Map(t.items.map(l=>[l.id,l])).get(t.rootId),i=new Map(t.items.map(l=>[l.id,l])),s=rc(r),a=await Bs(o,i,s),c=e.compositor.pixi.renderer.canvas;return new this(e,c,a,s)}async#t(e){let t=this.root.duration,r=e>t?t:e;this.root.audio?.onTimeUpdate(r);let o=await this.root.visuals?.sampleAt(r)??[];(await this.driver.composite(o)).close(),e>=t&&this.pause()}async play(){this.#e.isPlaying()||(this.sampler.setPaused(!1),this.#e.play())}pause(){this.#e.isPlaying()&&(this.#e.pause(),this.sampler.setPaused(!0))}async seek(e){this.pause(),this.#e.seek(e),this.root.audio?.onTimeUpdate(e);let t=await this.root.visuals?.sampleAt(e)??[];(await this.driver.composite(t)).close()}setFPS(e){this.#e.setFPS(e)}async update(e){let t=new Map(e.items.map(o=>[o.id,o])).get(e.rootId),r=new Map(e.items.map(o=>[o.id,o]));this.root=await Bs(t,r,this.sampler),await this.seek(this.currentTime())}};var Xt=class{state;constructor(e){this.state=e}require(e){return e===void 0?void 0:this.state.project.items.find(r=>r.id===e)}#e(){return xe.toInteger(xe.random())}#t(e){this.state.project=e(this.state.project)}register(e){this.#t(t=>({...t,items:[...t.items,e]}))}textStyle=e=>{let t={id:this.#e(),kind:H.TextStyle,style:e};return this.register(t),t};spatial=e=>{let t={id:this.#e(),kind:H.Spatial,transform:e,enabled:!0};return this.register(t),t};sequence=(...e)=>{let t={id:this.#e(),kind:H.Sequence,childrenIds:e.map(r=>r.id)};return this.register(t),t};stack=(...e)=>{let t={kind:H.Stack,id:this.#e(),childrenIds:e.map(r=>r.id)};return this.register(t),t};video=(e,t)=>{if(!e.hasVideo)throw new Error(`Video clip error: media "${e.datafile.filename}" has no video track.`);let r={kind:H.Video,id:this.#e(),mediaHash:e.datafile.checksum.hash,start:t?.start??0,duration:t?.duration??e.duration};return this.register(r),r};audio=(e,t)=>{if(!e.hasAudio)throw new Error(`Audio clip error: media "${e.datafile.filename}" has no audio track.`);let r={kind:H.Audio,id:this.#e(),mediaHash:e.datafile.checksum.hash,start:t?.start??0,duration:t?.duration??e.duration};return this.register(r),r};text=(e,t)=>{let r={id:this.#e(),content:e,kind:H.Text,duration:t?.duration??2e3};return t?.styles&&(r.styleId=this.textStyle(t.styles).id),this.register(r),r};gap=e=>{let t={id:this.#e(),kind:H.Gap,duration:e};return this.register(t),t};transition={crossfade:e=>{let t={id:this.#e(),kind:H.Transition,effect:Qn.Crossfade,duration:e};return this.register(t),t}};transform=e=>{let t=[e?.position?.[0]??0,e?.position?.[1]??0],r=[e?.scale?.[0]??1,e?.scale?.[1]??1],o=e?.rotation??0;return[t,r,o]};addChildren(e,...t){this.#t(r=>(r.items.find(({id:i})=>i===e.id).childrenIds.push(...t.map(i=>i.id)),r))}set=(e,t)=>{this.#t(r=>({...r,items:r.items.map(o=>o.id===e?{...o,...t}:o)}))}};var uo=class{reader;constructor(e){this.reader=e}async atOrNear(e){let t=null;for(;;){let{done:r,value:o}=await this.reader.read();if(r){let s=t?new VideoFrame(t):void 0;return t?.close(),s}let i=o.timestamp??0;if(i>=e){let s=t?.timestamp??Number.NEGATIVE_INFINITY,a=!!t&&Math.abs(s-e)<Math.abs(i-e),c=a?t:o,l=a?o:t,u=new VideoFrame(c);return c.close(),l?.close(),u}t?.close(),t=o}}cancel=async()=>await this.reader.cancel()};var fo=class{reader;constructor(e){this.reader=e}async*stream(){for(;;){let{done:e,value:t}=await this.reader.read();if(e)break;yield t}}cancel=async()=>await this.reader.cancel()};var nc=n=>Math.round(n*1e3);function oc(n,e){let t=new Map;async function r(o){let i=t.get(o.id);if(i)return i;let s=e(o.mediaHash),a=n.decodeVideo({source:s}),c=new uo(a.getReader());return t.set(o.id,c),c}return{async video(o,i){let s=await r(o),a=nc(o.start);return{duration:o.duration,visuals:{sampleAt:async c=>{let l=await s.atOrNear(a+nc(c));return l?[{kind:"image",frame:l,matrix:i,id:o.id}]:[]}}}},async audio(o){return{duration:o.duration,audio:{getStream:async function*(){let i=e(o.mediaHash),s=o.start/1e3,a=(o.start+o.duration)/1e3,c=n.decodeAudio({source:i,start:s,end:a});yield*new fo(c.getReader()).stream()}}}},async dispose(){let o=Array.from([...t.values()],i=>i.cancel());t.clear(),await Promise.all(o)}}}var Os=class extends $t{composeAudio_Stack(e){return{getStream:async function*(){for(let t of e)t.audio&&(yield*t.audio.getStream())}}}composeAudio_Sequence(e){return{getStream:async function*(){for(let t of e)t.audio&&(yield*t.audio.getStream())}}}};function sc(n,e,t){return new Os(e,t).build(n)}var mo=class{driver;framerate;resolveMedia;#e;constructor(e,t=30,r=o=>"/assets/temp/gl.mp4"){this.driver=e,this.framerate=t,this.resolveMedia=r,this.#e=oc(this.driver,this.resolveMedia)}async#t(e){let t=new Map(e.items.map(o=>[o.id,o])).get(e.rootId),r=new Map(e.items.map(o=>[o.id,o]));return await sc(t,r,this.#e)}async render(e){let t=await this.#t(e),r=new TransformStream,o=new TransformStream,i=this.driver.encode({video:r.readable,audio:o.readable,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}}),s=r.writable.getWriter(),a=o.writable.getWriter(),c=(async()=>{if(t.audio)for await(let u of t.audio.getStream())await a.write(u);await a.close()})(),l=(async()=>{let u=0,d=1/this.framerate;await Za({fps:this.framerate,duration:t.duration??0},async f=>{let m=await t.visuals?.sampleAt(f)??[],p=await this.driver.composite(m),h=new VideoFrame(p,{timestamp:Math.round(u*d*1e6),duration:Math.round(d*1e6)});await s.write(h),p.close(),u++}),await s.close()})();await c,await l,await i}};var po=class{driver;resources=new Jn;#e;constructor(e){this.driver=e,this.#e=new mo(e)}load=async e=>Object.fromEntries(await Promise.all(Object.entries(e).map(async([t,r])=>[t,await this.resources.store(await r)])));timeline=e=>{let t=new Xt({project:{format:"timeline",info:"https://omniclip.app/",version:0,items:[],rootId:0}}),r=e(t);return t.state.project.rootId=r.id,t.state.project};render=async e=>{await this.#e.render(e)}};var ho=class{data;bytes;hash;nickname;constructor(e,t,r,o){this.data=e,this.bytes=t,this.hash=r,this.nickname=o}static async make(e){let t=new Uint8Array(e),r=new Uint8Array(await crypto.subtle.digest("SHA-256",t)),o=Or.fromBytes(r),i=ti.sigil.fromBytes(r);return new this(e,r,o,i)}};var go=class{url;bytes;blob;filename;checksum;constructor(e,t,r,o,i){this.url=e,this.bytes=t,this.blob=r,this.filename=o,this.checksum=i}static async make(e,t){let r=await e.arrayBuffer(),o=new Uint8Array(r),i=await ho.make(o),s=t??i.nickname,a=URL.createObjectURL(e);return new this(a,o,e,s,i)}static async load(e){}};async function ic(n,e,t){let r=document.querySelector(".play"),o=document.querySelector(".stop"),i=document.querySelector(".seek"),s=new Xt({project:e}),a=await lo.create(n,e,c=>t.resources.require(c).url);document.body.appendChild(a.canvas),r.addEventListener("click",()=>a.play()),o.addEventListener("click",()=>a.pause()),i.addEventListener("change",async c=>{let l=c.target;await a.seek(+l.value)}),a.update(s.state.project)}async function ac(n){let e=document.querySelector(".waveform-demo"),t=document.querySelector(".width"),r=await to.init(n,"/assets/temp/gl.mp4",e);t.addEventListener("change",()=>{let o=+t.value;r.width=o})}async function cc(n,e){let t=new po(n),{videoA:r}=await t.load({videoA:go.make(e)});return{timeline:t.timeline(i=>{let s=i.text("content",{duration:1e3}),a=i.textStyle({fill:"green",fontSize:100});return i.set(s.id,{styleId:a.id}),i.sequence(i.stack(s,i.video(r,{duration:3e3,start:3e3}),i.audio(r,{duration:1e3,start:3e3})),i.gap(500),i.video(r,{duration:7e3,start:5e3}))}),omni:t}}async function lc(n){let e=document.querySelector(".range"),t=document.querySelector(".range-view"),r=document.querySelector(".range-size"),o=document.querySelector(".frequency"),i=document.querySelector(".frequency-view"),s=document.querySelector("#filmstrip"),a=1e3/10/1e3,c=.5,l=await Zn.init(n,{onChange(u){let d=u.sort((f,m)=>f.time-m.time);s.replaceChildren(...d.map(({time:f,canvas:m})=>pl(f,m.canvas)))},frequency:a,canvasSinkOptions:{width:80,height:50,fit:"fill"}});r.addEventListener("change",()=>{c=+r.value;let[u,d]=[+e.value,+e.value+c];l.range=[u,d],t.textContent=`visible time range: [${u}, ${d}]`}),e.addEventListener("change",()=>{let[u,d]=[+e.value,+e.value+c];l.range=[u,d],t.textContent=`visible time range: [${u}, ${d}]`}),o.addEventListener("change",()=>{l.frequency=1e3/+o.value/1e3,i.textContent=`frame every ${l.frequency.toFixed(3)} second (${o.value} frames per second)`}),l.range=[10,10.5]}function pl(n,e){let t=document.createElement("div");t.style.position="relative",t.style.display="inline-block",t.style.marginRight="4px",t.appendChild(e);let r=document.createElement("div");return r.textContent=`${n.toFixed(2)}s`,r.style.position="absolute",r.style.top="2px",r.style.right="4px",r.style.fontSize="10px",r.style.color="white",r.style.background="rgba(0,0,0,0.6)",r.style.padding="2px 4px",r.style.borderRadius="4px",r.style.pointerEvents="none",t.appendChild(r),t}function zs(n,e){let t={width:1920,height:1080},r=document.createElement("canvas");r.width=t.width,r.height=t.height;let o=r.getContext("2d");async function i(){let s=n.decodeVideo({source:e,async onFrame(c){let l=await n.composite([{id:0,kind:"image",frame:c},{id:1,kind:"text",content:"omnitool",style:{fontSize:50,fill:"green"}}]);return c.close(),o?.drawImage(l,0,0),l}}),a=n.decodeAudio({source:e});await n.encode({video:s,audio:a,config:{audio:{codec:"opus",bitrate:128e3},video:{codec:"vp9",bitrate:1e6}}})}return{canvas:r,run:i}}var gt=await Kn.setup({workerUrl:new URL("../driver/driver.worker.bundle.min.js",import.meta.url)}),hl=document.querySelector(".results"),gl=document.querySelector(".fetch"),uc=document.querySelector(".file-input");gl?.addEventListener("click",bl);uc?.addEventListener("input",xl);ac(gt);await gt.thread.work.hello(),gt.machina.count===1?console.log("\u2705 driver works"):console.error("\u274C FAIL driver call didn't work");async function xl(n){let e=uc.files?.[0];if(e){let t=zs(gt,e);await lc(e),dc(t,e.name);let{timeline:r,omni:o}=await cc(gt,e);ic(gt,r,o),Wa(o,r)}}async function bl(){let n=["/assets/temp/gl.mp4"];for(let e of n){let t=zs(gt,"/assets/temp/gl.mp4");dc(t,e)}}async function dc(n,e){let t=document.createElement("div");hl.append(t);let r=document.createElement("p");r.textContent=e,t.append(r),t.append(n.canvas),await n.run()}
2489
2489
  /*! Bundled license information:
2490
2490
 
2491
2491
  mediabunny/dist/modules/src/misc.js: