@waveform-playlist/browser 9.5.1 → 9.5.2

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/dist/index.js CHANGED
@@ -854,7 +854,7 @@
854
854
  border-top: 1px solid rgba(128, 128, 128, 0.3);
855
855
  margin: 0.35rem 0;
856
856
  `,o0=({items:e})=>{const[t,n]=m.useState(!1),r=m.useCallback(()=>n(!1),[]),s=typeof e=="function"?e(r):e,[a,o]=m.useState({top:0,left:0}),i=m.useRef(null),l=m.useRef(null),c=m.useCallback(()=>{if(!i.current)return;const u=i.current.getBoundingClientRect(),f=window.innerWidth,p=window.innerHeight,d=l.current?.offsetHeight??160;let h=u.right+4;h+gs>f&&(h=u.left-gs-4),h=Math.max(4,Math.min(h,f-gs-4));let v=u.top;v+d>p-4&&(v=Math.max(4,u.bottom-d)),o({top:v,left:h})},[]);return m.useEffect(()=>{if(!t)return;c();const u=requestAnimationFrame(()=>c()),f=()=>c(),p=()=>c();return window.addEventListener("scroll",f,!0),window.addEventListener("resize",p),()=>{cancelAnimationFrame(u),window.removeEventListener("scroll",f,!0),window.removeEventListener("resize",p)}},[t,c]),m.useEffect(()=>{if(!t)return;const u=p=>{const d=p.target;i.current&&!i.current.contains(d)&&l.current&&!l.current.contains(d)&&n(!1)},f=p=>{p.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",u),document.addEventListener("keydown",f),()=>{document.removeEventListener("mousedown",u),document.removeEventListener("keydown",f)}},[t]),C.jsxs(n0,{children:[C.jsx(r0,{ref:i,onClick:u=>{u.stopPropagation(),n(f=>!f)},onMouseDown:u=>u.stopPropagation(),title:"Track menu","aria-label":"Track menu",children:C.jsx(t0,{size:16})}),t&&typeof document<"u"&&mo.createPortal(C.jsx(s0,{ref:l,$top:a.top,$left:a.left,onMouseDown:u=>u.stopPropagation(),children:s.map((u,f)=>C.jsxs(m.Fragment,{children:[f>0&&C.jsx(a0,{}),u.content]},u.id))}),document.body)]})};function yn(e,t){this._waveformData=e,this._channelIndex=t}yn.prototype.min_sample=function(e){var t=(e*this._waveformData.channels+this._channelIndex)*2;return this._waveformData._at(t)};yn.prototype.max_sample=function(e){var t=(e*this._waveformData.channels+this._channelIndex)*2+1;return this._waveformData._at(t)};yn.prototype.set_min_sample=function(e,t){var n=(e*this._waveformData.channels+this._channelIndex)*2;return this._waveformData._set_at(n,t)};yn.prototype.set_max_sample=function(e,t){var n=(e*this._waveformData.channels+this._channelIndex)*2+1;return this._waveformData._set_at(n,t)};yn.prototype.min_array=function(){for(var e=this._waveformData.length,t=[],n=0;n<e;n++)t.push(this.min_sample(n));return t};yn.prototype.max_array=function(){for(var e=this._waveformData.length,t=[],n=0;n<e;n++)t.push(this.max_sample(n));return t};var i0=127,l0=-128,c0=32767,u0=-32768;function d0(e,t){var n=Math.floor(e/t),r=e-n*t;return r>0&&n++,n}function f0(e){for(var t=e.scale,n=e.amplitude_scale,r=e.split_channels,s=e.length,a=e.sample_rate,o=e.channels.map(function(T){return new Float32Array(T)}),i=r?o.length:1,l=24,c=d0(s,t),u=e.bits===8?1:2,f=l+c*2*u*i,p=new ArrayBuffer(f),d=new DataView(p),h=0,v=l,g=new Array(i),y=new Array(i),b=0;b<i;b++)g[b]=1/0,y[b]=-1/0;var w=e.bits===8?l0:u0,_=e.bits===8?i0:c0;d.setInt32(0,2,!0),d.setUint32(4,e.bits===8,!0),d.setInt32(8,a,!0),d.setInt32(12,t,!0),d.setInt32(16,c,!0),d.setInt32(20,i,!0);for(var x=0;x<s;x++){var S=0;if(i===1){for(var k=0;k<o.length;++k)S+=o[k][x];S=Math.floor(_*S*n/o.length),S<g[0]&&(g[0]=S,g[0]<w&&(g[0]=w)),S>y[0]&&(y[0]=S,y[0]>_&&(y[0]=_))}else for(var E=0;E<i;++E)S=Math.floor(_*o[E][x]*n),S<g[E]&&(g[E]=S,g[E]<w&&(g[E]=w)),S>y[E]&&(y[E]=S,y[E]>_&&(y[E]=_));if(++h===t){for(var I=0;I<i;I++)e.bits===8?(d.setInt8(v++,g[I]),d.setInt8(v++,y[I])):(d.setInt16(v,g[I],!0),d.setInt16(v+2,y[I],!0),v+=4),g[I]=1/0,y[I]=-1/0;h=0}}if(h>0)for(var M=0;M<i;M++)e.bits===8?(d.setInt8(v++,g[M]),d.setInt8(v++,y[M])):(d.setInt16(v,g[M],!0),d.setInt16(v+2,y[M],!0));return p}function Ds(e){"@babel/helpers - typeof";return Ds=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ds(e)}function h0(e){return e&&Ds(e)==="object"&&"sample_rate"in e&&"samples_per_pixel"in e&&"bits"in e&&"length"in e&&"data"in e}function p0(e){var t=e&&Ds(e)==="object"&&"byteLength"in e;if(t){var n=new DataView(e),r=n.getInt32(0,!0);if(r!==1&&r!==2)throw new TypeError("WaveformData.create(): This waveform data version not supported")}return t}function m0(e){var t=e.data,n=e.channels||1,r=24,s=e.bits===8?1:2,a=e.length*2*n;if(t.length!==a)throw new Error("WaveformData.create(): Length mismatch in JSON waveform data");var o=r+t.length*s,i=new ArrayBuffer(o),l=new DataView(i);l.setInt32(0,2,!0),l.setUint32(4,e.bits===8,!0),l.setInt32(8,e.sample_rate,!0),l.setInt32(12,e.samples_per_pixel,!0),l.setInt32(16,e.length,!0),l.setInt32(20,n,!0);var c=r;if(e.bits===8)for(var u=0;u<t.length;u++)l.setInt8(c++,t[u],!0);else for(var f=0;f<t.length;f++)l.setInt16(c,t[f],!0),c+=2;return i}function Cn(e){return e==null}function g0(e,t){var n=atob(e);return n}function v0(e,t,n){var r=g0(e),s=r.indexOf(`
857
- `,10)+1,a=r.substring(s)+"",o=new Blob([a],{type:"application/javascript"});return URL.createObjectURL(o)}function y0(e,t,n){var r;return function(a){return r=r||v0(e),new Worker(r,a)}}var b0=y0("Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewogICd1c2Ugc3RyaWN0JzsKCiAgLyoqCiAgICogQXVkaW9CdWZmZXItYmFzZWQgV2F2ZWZvcm1EYXRhIGdlbmVyYXRvcgogICAqCiAgICogQWRhcHRlZCBmcm9tIEJsb2NrRmlsZTo6Q2FsY1N1bW1hcnkgaW4gQXVkYWNpdHksIHdpdGggcGVybWlzc2lvbi4KICAgKiBTZWUgaHR0cHM6Ly9naXRodWIuY29tL2F1ZGFjaXR5L2F1ZGFjaXR5L2Jsb2IvCiAgICogICAxMTA4YzEzNzZjMDkxNjYxNjIzMzVmYWI0NzQzMDA4Y2JhNTdjNGVlL3NyYy9CbG9ja0ZpbGUuY3BwI0wxOTgKICAgKi8KCiAgdmFyIElOVDhfTUFYID0gMTI3OwogIHZhciBJTlQ4X01JTiA9IC0xMjg7CiAgdmFyIElOVDE2X01BWCA9IDMyNzY3OwogIHZhciBJTlQxNl9NSU4gPSAtMzI3Njg7CiAgZnVuY3Rpb24gY2FsY3VsYXRlV2F2ZWZvcm1EYXRhTGVuZ3RoKGF1ZGlvX3NhbXBsZV9jb3VudCwgc2NhbGUpIHsKICAgIHZhciBkYXRhX2xlbmd0aCA9IE1hdGguZmxvb3IoYXVkaW9fc2FtcGxlX2NvdW50IC8gc2NhbGUpOwogICAgdmFyIHNhbXBsZXNfcmVtYWluaW5nID0gYXVkaW9fc2FtcGxlX2NvdW50IC0gZGF0YV9sZW5ndGggKiBzY2FsZTsKICAgIGlmIChzYW1wbGVzX3JlbWFpbmluZyA+IDApIHsKICAgICAgZGF0YV9sZW5ndGgrKzsKICAgIH0KICAgIHJldHVybiBkYXRhX2xlbmd0aDsKICB9CiAgZnVuY3Rpb24gZ2VuZXJhdGVXYXZlZm9ybURhdGEob3B0aW9ucykgewogICAgdmFyIHNjYWxlID0gb3B0aW9ucy5zY2FsZTsKICAgIHZhciBhbXBsaXR1ZGVfc2NhbGUgPSBvcHRpb25zLmFtcGxpdHVkZV9zY2FsZTsKICAgIHZhciBzcGxpdF9jaGFubmVscyA9IG9wdGlvbnMuc3BsaXRfY2hhbm5lbHM7CiAgICB2YXIgbGVuZ3RoID0gb3B0aW9ucy5sZW5ndGg7CiAgICB2YXIgc2FtcGxlX3JhdGUgPSBvcHRpb25zLnNhbXBsZV9yYXRlOwogICAgdmFyIGNoYW5uZWxzID0gb3B0aW9ucy5jaGFubmVscy5tYXAoZnVuY3Rpb24gKGNoYW5uZWwpIHsKICAgICAgcmV0dXJuIG5ldyBGbG9hdDMyQXJyYXkoY2hhbm5lbCk7CiAgICB9KTsKICAgIHZhciBvdXRwdXRfY2hhbm5lbHMgPSBzcGxpdF9jaGFubmVscyA/IGNoYW5uZWxzLmxlbmd0aCA6IDE7CiAgICB2YXIgaGVhZGVyX3NpemUgPSAyNDsKICAgIHZhciBkYXRhX2xlbmd0aCA9IGNhbGN1bGF0ZVdhdmVmb3JtRGF0YUxlbmd0aChsZW5ndGgsIHNjYWxlKTsKICAgIHZhciBieXRlc19wZXJfc2FtcGxlID0gb3B0aW9ucy5iaXRzID09PSA4ID8gMSA6IDI7CiAgICB2YXIgdG90YWxfc2l6ZSA9IGhlYWRlcl9zaXplICsgZGF0YV9sZW5ndGggKiAyICogYnl0ZXNfcGVyX3NhbXBsZSAqIG91dHB1dF9jaGFubmVsczsKICAgIHZhciBidWZmZXIgPSBuZXcgQXJyYXlCdWZmZXIodG90YWxfc2l6ZSk7CiAgICB2YXIgZGF0YV92aWV3ID0gbmV3IERhdGFWaWV3KGJ1ZmZlcik7CiAgICB2YXIgc2NhbGVfY291bnRlciA9IDA7CiAgICB2YXIgb2Zmc2V0ID0gaGVhZGVyX3NpemU7CiAgICB2YXIgbWluX3ZhbHVlID0gbmV3IEFycmF5KG91dHB1dF9jaGFubmVscyk7CiAgICB2YXIgbWF4X3ZhbHVlID0gbmV3IEFycmF5KG91dHB1dF9jaGFubmVscyk7CiAgICBmb3IgKHZhciBjaGFubmVsID0gMDsgY2hhbm5lbCA8IG91dHB1dF9jaGFubmVsczsgY2hhbm5lbCsrKSB7CiAgICAgIG1pbl92YWx1ZVtjaGFubmVsXSA9IEluZmluaXR5OwogICAgICBtYXhfdmFsdWVbY2hhbm5lbF0gPSAtSW5maW5pdHk7CiAgICB9CiAgICB2YXIgcmFuZ2VfbWluID0gb3B0aW9ucy5iaXRzID09PSA4ID8gSU5UOF9NSU4gOiBJTlQxNl9NSU47CiAgICB2YXIgcmFuZ2VfbWF4ID0gb3B0aW9ucy5iaXRzID09PSA4ID8gSU5UOF9NQVggOiBJTlQxNl9NQVg7CiAgICBkYXRhX3ZpZXcuc2V0SW50MzIoMCwgMiwgdHJ1ZSk7IC8vIFZlcnNpb24KICAgIGRhdGFfdmlldy5zZXRVaW50MzIoNCwgb3B0aW9ucy5iaXRzID09PSA4LCB0cnVlKTsgLy8gSXMgOCBiaXQ/CiAgICBkYXRhX3ZpZXcuc2V0SW50MzIoOCwgc2FtcGxlX3JhdGUsIHRydWUpOyAvLyBTYW1wbGUgcmF0ZQogICAgZGF0YV92aWV3LnNldEludDMyKDEyLCBzY2FsZSwgdHJ1ZSk7IC8vIFNjYWxlCiAgICBkYXRhX3ZpZXcuc2V0SW50MzIoMTYsIGRhdGFfbGVuZ3RoLCB0cnVlKTsgLy8gTGVuZ3RoCiAgICBkYXRhX3ZpZXcuc2V0SW50MzIoMjAsIG91dHB1dF9jaGFubmVscywgdHJ1ZSk7CiAgICBmb3IgKHZhciBpID0gMDsgaSA8IGxlbmd0aDsgaSsrKSB7CiAgICAgIHZhciBzYW1wbGUgPSAwOwogICAgICBpZiAob3V0cHV0X2NoYW5uZWxzID09PSAxKSB7CiAgICAgICAgZm9yICh2YXIgX2NoYW5uZWwgPSAwOyBfY2hhbm5lbCA8IGNoYW5uZWxzLmxlbmd0aDsgKytfY2hhbm5lbCkgewogICAgICAgICAgc2FtcGxlICs9IGNoYW5uZWxzW19jaGFubmVsXVtpXTsKICAgICAgICB9CiAgICAgICAgc2FtcGxlID0gTWF0aC5mbG9vcihyYW5nZV9tYXggKiBzYW1wbGUgKiBhbXBsaXR1ZGVfc2NhbGUgLyBjaGFubmVscy5sZW5ndGgpOwogICAgICAgIGlmIChzYW1wbGUgPCBtaW5fdmFsdWVbMF0pIHsKICAgICAgICAgIG1pbl92YWx1ZVswXSA9IHNhbXBsZTsKICAgICAgICAgIGlmIChtaW5fdmFsdWVbMF0gPCByYW5nZV9taW4pIHsKICAgICAgICAgICAgbWluX3ZhbHVlWzBdID0gcmFuZ2VfbWluOwogICAgICAgICAgfQogICAgICAgIH0KICAgICAgICBpZiAoc2FtcGxlID4gbWF4X3ZhbHVlWzBdKSB7CiAgICAgICAgICBtYXhfdmFsdWVbMF0gPSBzYW1wbGU7CiAgICAgICAgICBpZiAobWF4X3ZhbHVlWzBdID4gcmFuZ2VfbWF4KSB7CiAgICAgICAgICAgIG1heF92YWx1ZVswXSA9IHJhbmdlX21heDsKICAgICAgICAgIH0KICAgICAgICB9CiAgICAgIH0gZWxzZSB7CiAgICAgICAgZm9yICh2YXIgX2NoYW5uZWwyID0gMDsgX2NoYW5uZWwyIDwgb3V0cHV0X2NoYW5uZWxzOyArK19jaGFubmVsMikgewogICAgICAgICAgc2FtcGxlID0gTWF0aC5mbG9vcihyYW5nZV9tYXggKiBjaGFubmVsc1tfY2hhbm5lbDJdW2ldICogYW1wbGl0dWRlX3NjYWxlKTsKICAgICAgICAgIGlmIChzYW1wbGUgPCBtaW5fdmFsdWVbX2NoYW5uZWwyXSkgewogICAgICAgICAgICBtaW5fdmFsdWVbX2NoYW5uZWwyXSA9IHNhbXBsZTsKICAgICAgICAgICAgaWYgKG1pbl92YWx1ZVtfY2hhbm5lbDJdIDwgcmFuZ2VfbWluKSB7CiAgICAgICAgICAgICAgbWluX3ZhbHVlW19jaGFubmVsMl0gPSByYW5nZV9taW47CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICAgIGlmIChzYW1wbGUgPiBtYXhfdmFsdWVbX2NoYW5uZWwyXSkgewogICAgICAgICAgICBtYXhfdmFsdWVbX2NoYW5uZWwyXSA9IHNhbXBsZTsKICAgICAgICAgICAgaWYgKG1heF92YWx1ZVtfY2hhbm5lbDJdID4gcmFuZ2VfbWF4KSB7CiAgICAgICAgICAgICAgbWF4X3ZhbHVlW19jaGFubmVsMl0gPSByYW5nZV9tYXg7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICB9CiAgICAgIH0KICAgICAgaWYgKCsrc2NhbGVfY291bnRlciA9PT0gc2NhbGUpIHsKICAgICAgICBmb3IgKHZhciBfY2hhbm5lbDMgPSAwOyBfY2hhbm5lbDMgPCBvdXRwdXRfY2hhbm5lbHM7IF9jaGFubmVsMysrKSB7CiAgICAgICAgICBpZiAob3B0aW9ucy5iaXRzID09PSA4KSB7CiAgICAgICAgICAgIGRhdGFfdmlldy5zZXRJbnQ4KG9mZnNldCsrLCBtaW5fdmFsdWVbX2NoYW5uZWwzXSk7CiAgICAgICAgICAgIGRhdGFfdmlldy5zZXRJbnQ4KG9mZnNldCsrLCBtYXhfdmFsdWVbX2NoYW5uZWwzXSk7CiAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICBkYXRhX3ZpZXcuc2V0SW50MTYob2Zmc2V0LCBtaW5fdmFsdWVbX2NoYW5uZWwzXSwgdHJ1ZSk7CiAgICAgICAgICAgIGRhdGFfdmlldy5zZXRJbnQxNihvZmZzZXQgKyAyLCBtYXhfdmFsdWVbX2NoYW5uZWwzXSwgdHJ1ZSk7CiAgICAgICAgICAgIG9mZnNldCArPSA0OwogICAgICAgICAgfQogICAgICAgICAgbWluX3ZhbHVlW19jaGFubmVsM10gPSBJbmZpbml0eTsKICAgICAgICAgIG1heF92YWx1ZVtfY2hhbm5lbDNdID0gLUluZmluaXR5OwogICAgICAgIH0KICAgICAgICBzY2FsZV9jb3VudGVyID0gMDsKICAgICAgfQogICAgfQogICAgaWYgKHNjYWxlX2NvdW50ZXIgPiAwKSB7CiAgICAgIGZvciAodmFyIF9jaGFubmVsNCA9IDA7IF9jaGFubmVsNCA8IG91dHB1dF9jaGFubmVsczsgX2NoYW5uZWw0KyspIHsKICAgICAgICBpZiAob3B0aW9ucy5iaXRzID09PSA4KSB7CiAgICAgICAgICBkYXRhX3ZpZXcuc2V0SW50OChvZmZzZXQrKywgbWluX3ZhbHVlW19jaGFubmVsNF0pOwogICAgICAgICAgZGF0YV92aWV3LnNldEludDgob2Zmc2V0KyssIG1heF92YWx1ZVtfY2hhbm5lbDRdKTsKICAgICAgICB9IGVsc2UgewogICAgICAgICAgZGF0YV92aWV3LnNldEludDE2KG9mZnNldCwgbWluX3ZhbHVlW19jaGFubmVsNF0sIHRydWUpOwogICAgICAgICAgZGF0YV92aWV3LnNldEludDE2KG9mZnNldCArIDIsIG1heF92YWx1ZVtfY2hhbm5lbDRdLCB0cnVlKTsKICAgICAgICB9CiAgICAgIH0KICAgIH0KICAgIHJldHVybiBidWZmZXI7CiAgfQoKICBvbm1lc3NhZ2UgPSBmdW5jdGlvbiBvbm1lc3NhZ2UoZXZ0KSB7CiAgICB2YXIgYnVmZmVyID0gZ2VuZXJhdGVXYXZlZm9ybURhdGEoZXZ0LmRhdGEpOwoKICAgIC8vIFRyYW5zZmVyIGJ1ZmZlciB0byB0aGUgY2FsbGluZyB0aHJlYWQKICAgIHRoaXMucG9zdE1lc3NhZ2UoYnVmZmVyLCBbYnVmZmVyXSk7CiAgICB0aGlzLmNsb3NlKCk7CiAgfTsKCn0pKCk7Ci8vIyBzb3VyY2VNYXBwaW5nVVJMPXdhdmVmb3JtLWRhdGEtd29ya2VyLmpzLm1hcAoK");function pt(e){if(h0(e)&&(e=m0(e)),p0(e)){this._data=new DataView(e),this._offset=this._version()===2?24:20,this._channels=[];for(var t=0;t<this.channels;t++)this._channels[t]=new yn(this,t)}else throw new TypeError("WaveformData.create(): Unknown data format")}var qn={scale:512,bits:8,amplitude_scale:1,split_channels:!1,disable_worker:!1};function w0(e){var t={scale:e.scale||qn.scale,bits:e.bits||qn.bits,amplitude_scale:e.amplitude_scale||qn.amplitude_scale,split_channels:e.split_channels||qn.split_channels,disable_worker:e.disable_worker||qn.disable_worker};return t}function _0(e){for(var t=[],n=0;n<e.numberOfChannels;++n)t.push(e.getChannelData(n).buffer);return t}function Jd(e,t,n){var r=_0(e);if(t.disable_worker){var s=f0({scale:t.scale,bits:t.bits,amplitude_scale:t.amplitude_scale,split_channels:t.split_channels,length:e.length,sample_rate:e.sampleRate,channels:r});n(void 0,new pt(s),e)}else{var a=new b0;a.onmessage=function(o){n(void 0,new pt(o.data),e)},a.postMessage({scale:t.scale,bits:t.bits,amplitude_scale:t.amplitude_scale,split_channels:t.split_channels,length:e.length,sample_rate:e.sampleRate,channels:r},r)}}function x0(e,t,n,r){function s(o){o||(o=new DOMException("EncodingError")),r(o),r=function(){}}var a=e.decodeAudioData(t,function(o){Jd(o,n,r)},s);a&&a.catch(s)}pt.create=function(t){return new pt(t)};pt.createFromAudio=function(e,t){var n=w0(e);if(e.audio_context&&e.array_buffer)return x0(e.audio_context,e.array_buffer,n,t);if(e.audio_buffer)return Jd(e.audio_buffer,n,t);throw new TypeError("WaveformData.createFromAudio(): Pass either an AudioContext and ArrayBuffer, or an AudioBuffer object")};function Ks(e){this._inputData=e.waveformData,this._output_samples_per_pixel=e.scale,this._scale=this._inputData.scale,this._input_buffer_size=this._inputData.length;var t=this._input_buffer_size*this._inputData.scale,n=Math.ceil(t/this._output_samples_per_pixel),r=24,s=this._inputData.bits===8?1:2,a=r+n*2*this._inputData.channels*s;this._output_data=new ArrayBuffer(a),this.output_dataview=new DataView(this._output_data),this.output_dataview.setInt32(0,2,!0),this.output_dataview.setUint32(4,this._inputData.bits===8,!0),this.output_dataview.setInt32(8,this._inputData.sample_rate,!0),this.output_dataview.setInt32(12,this._output_samples_per_pixel,!0),this.output_dataview.setInt32(16,n,!0),this.output_dataview.setInt32(20,this._inputData.channels,!0),this._outputWaveformData=new pt(this._output_data),this._input_index=0,this._output_index=0;var o=this._inputData.channels;this._min=new Array(o),this._max=new Array(o);for(var i=0;i<o;++i)this._input_buffer_size>0?(this._min[i]=this._inputData.channel(i).min_sample(this._input_index),this._max[i]=this._inputData.channel(i).max_sample(this._input_index)):(this._min[i]=0,this._max[i]=0);this._min_value=this._inputData.bits===8?-128:-32768,this._max_value=this._inputData.bits===8?127:32767,this._where=0,this._prev_where=0,this._stop=0,this._last_input_index=0}Ks.prototype.sample_at_pixel=function(e){return Math.floor(e*this._output_samples_per_pixel)};Ks.prototype.next=function(){for(var e=0,t=1e3,n=this._inputData.channels,r;this._input_index<this._input_buffer_size&&e<t;){for(;Math.floor(this.sample_at_pixel(this._output_index)/this._scale)===this._input_index;){if(this._output_index>0)for(var s=0;s<n;++s)r=this._outputWaveformData.channel(s),r.set_min_sample(this._output_index-1,this._min[s]),r.set_max_sample(this._output_index-1,this._max[s]);if(this._last_input_index=this._input_index,this._output_index++,this._where=this.sample_at_pixel(this._output_index),this._prev_where=this.sample_at_pixel(this._output_index-1),this._where!==this._prev_where)for(var a=0;a<n;++a)this._min[a]=this._max_value,this._max[a]=this._min_value}for(this._where=this.sample_at_pixel(this._output_index),this._stop=Math.floor(this._where/this._scale),this._stop>this._input_buffer_size&&(this._stop=this._input_buffer_size);this._input_index<this._stop;){for(var o=0;o<n;++o){r=this._inputData.channel(o);var i=r.min_sample(this._input_index);i<this._min[o]&&(this._min[o]=i),i=r.max_sample(this._input_index),i>this._max[o]&&(this._max[o]=i)}this._input_index++}e++}if(this._input_index<this._input_buffer_size)return!1;if(this._input_index!==this._last_input_index)for(var l=0;l<n;++l)r=this._outputWaveformData.channel(l),r.set_min_sample(this._output_index-1,this._min[l]),r.set_max_sample(this._output_index-1,this._max[l]);return!0};Ks.prototype.getOutputData=function(){return this._output_data};pt.prototype={_getResampleOptions:function(t){var n={};if(n.scale=t.scale,n.width=t.width,!Cn(n.width)&&(typeof n.width!="number"||n.width<=0))throw new RangeError("WaveformData.resample(): width should be a positive integer value");if(!Cn(n.scale)&&(typeof n.scale!="number"||n.scale<=0))throw new RangeError("WaveformData.resample(): scale should be a positive integer value");if(!n.scale&&!n.width)throw new Error("WaveformData.resample(): Missing scale or width option");if(n.width&&(n.scale=Math.floor(this.duration*this.sample_rate/n.width)),n.scale<this.scale)throw new Error("WaveformData.resample(): Zoom level "+n.scale+" too low, minimum: "+this.scale);return n.abortSignal=t.abortSignal,n},resample:function(t){t=this._getResampleOptions(t),t.waveformData=this;for(var n=new Ks(t);!n.next(););return new pt(n.getOutputData())},concat:function(){var t=this,n=Array.prototype.slice.call(arguments);n.forEach(function(s){if(t.channels!==s.channels||t.sample_rate!==s.sample_rate||t.bits!==s.bits||t.scale!==s.scale)throw new Error("WaveformData.concat(): Waveforms are incompatible")});var r=this._concatBuffers.apply(this,n);return pt.create(r)},_concatBuffers:function(){for(var t=Array.prototype.slice.call(arguments),n=this._offset,r=n,s=0,a=[this].concat(t).map(function(y){return y._data.buffer}),o=0;o<a.length;o++){var i=a[o],l=new DataView(i).getInt32(16,!0);r+=i.byteLength-n,s+=l}for(var c=new ArrayBuffer(r),u=new DataView(a[0]),f=new DataView(c),p=0;p<n;p++)f.setUint8(p,u.getUint8(p));f.setInt32(16,s,!0);for(var d=0,h=new Uint8Array(c,n),v=0;v<a.length;v++){var g=a[v];h.set(new Uint8Array(g,n),d),d+=g.byteLength-n}return c},slice:function(t){var n=0,r=0;if(!Cn(t.startIndex)&&!Cn(t.endIndex)?(n=t.startIndex,r=t.endIndex):!Cn(t.startTime)&&!Cn(t.endTime)&&(n=this.at_time(t.startTime),r=this.at_time(t.endTime)),n<0)throw new RangeError("startIndex or startTime must not be negative");if(r<0)throw new RangeError("endIndex or endTime must not be negative");n>this.length&&(n=this.length),r>this.length&&(r=this.length),n>r&&(n=r);var s=r-n,a=24,o=this.bits===8?1:2,i=a+s*2*this.channels*o,l=new ArrayBuffer(i),c=new DataView(l);c.setInt32(0,2,!0),c.setUint32(4,this.bits===8,!0),c.setInt32(8,this.sample_rate,!0),c.setInt32(12,this.scale,!0),c.setInt32(16,s,!0),c.setInt32(20,this.channels,!0);for(var u=0;u<s*this.channels*2;u++){var f=this._at(n*this.channels*2+u);this.bits===8?c.setInt8(a+u,f):c.setInt16(a+u*2,f,!0)}return new pt(l)},_version:function(){return this._data.getInt32(0,!0)},get length(){return this._data.getUint32(16,!0)},get bits(){var e=!!this._data.getUint32(4,!0);return e?8:16},get duration(){return this.length*this.scale/this.sample_rate},get pixels_per_second(){return this.sample_rate/this.scale},get seconds_per_pixel(){return this.scale/this.sample_rate},get channels(){return this._version()===2?this._data.getInt32(20,!0):1},channel:function(t){if(t>=0&&t<this._channels.length)return this._channels[t];throw new RangeError("Invalid channel: "+t)},get sample_rate(){return this._data.getInt32(8,!0)},get scale(){return this._data.getInt32(12,!0)},_at:function(t){return this.bits===8?this._data.getInt8(this._offset+t):this._data.getInt16(this._offset+t*2,!0)},_set_at:function(t,n){return this.bits===8?this._data.setInt8(this._offset+t,n):this._data.setInt16(this._offset+t*2,n,!0)},at_time:function(t){return Math.floor(t*this.sample_rate/this.scale)},time:function(t){return t*this.scale/this.sample_rate},toJSON:function(){for(var t={version:2,channels:this.channels,sample_rate:this.sample_rate,samples_per_pixel:this.scale,bits:this.bits,length:this.length,data:[]},n=0;n<this.length;n++)for(var r=0;r<this.channels;r++)t.data.push(this.channel(r).min_sample(n)),t.data.push(this.channel(r).max_sample(n));return t},toArrayBuffer:function(){return this._data.buffer}};async function xi(e){const t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch waveform data: ${t.statusText}`);if(e.endsWith(".dat")){const r=await t.arrayBuffer();return pt.create(r)}else{const r=await t.json();return pt.create(r)}}function Qd(e,t=0){const n=e.channel(t),r=e.bits,s=n.min_array(),a=n.max_array(),o=s.length,i=r===8?new Int8Array(o*2):new Int16Array(o*2);for(let l=0;l<o;l++)i[l*2]=s[l],i[l*2+1]=a[l];return{data:i,bits:r,length:o,sampleRate:e.sample_rate}}async function C0(e,t=0){const n=await xi(e);return Qd(n,t)}async function S0(e){const t=await xi(e);return{sampleRate:t.sample_rate,channels:t.channels,duration:t.duration,samplesPerPixel:t.scale,length:t.length,bits:t.bits}}function ef(e,t,n,r){let s=e;if(n!==void 0&&r!==void 0)if(s.scale!==t){const a=e.scale,o=t/a,i=Math.floor(n/t),l=Math.ceil((n+r)/t),c=Math.floor(i*o),u=Math.min(e.length,Math.ceil(l*o));if(c>=u)return null;s=s.slice({startIndex:c,endIndex:u}),s=s.resample({scale:t})}else{const a=Math.floor(n/t),o=Math.ceil((n+r)/t);s=s.slice({startIndex:a,endIndex:o})}else s.scale!==t&&(s=s.resample({scale:t}));return s}function k0(e,t,n=0,r,s){const a=ef(e,t,r,s);if(a===null){const p=e.bits;return{data:p===8?new Int8Array(0):new Int16Array(0),bits:p,length:0}}const o=a.channel(n),i=a.bits,l=o.min_array(),c=o.max_array(),u=l.length,f=i===8?new Int8Array(u*2):new Int16Array(u*2);for(let p=0;p<u;p++)f[p*2]=l[p],f[p*2+1]=c[p];return{data:f,bits:i,length:u}}function Ql(e,t,n,r,s){const a=ef(e,t,r,s);if(a===null){const u=e.bits;return{length:0,data:[],bits:u}}const o=a.channels,i=a.bits,l=[];for(let u=0;u<o;u++){const f=a.channel(u),p=f.min_array(),d=f.max_array(),h=p.length,v=i===8?new Int8Array(h*2):new Int16Array(h*2);for(let g=0;g<h;g++)v[g*2]=p[g],v[g*2+1]=d[g];l.push(v)}if(n&&l.length>1){const u=1/l.length,f=l[0].length/2,p=i===8?new Int8Array(f*2):new Int16Array(f*2);for(let d=0;d<f;d++){let h=0,v=0;for(let g=0;g<l.length;g++)h+=u*l[g][d*2],v+=u*l[g][d*2+1];p[d*2]=h,p[d*2+1]=v}return{length:f,data:[p],bits:i}}return{length:l.length>0?l[0].length/2:0,data:l,bits:i}}function tf(){const[e,t]=m.useState("hh:mm:ss.uuu");return{timeFormat:e,setTimeFormat:t,formatTime:s=>Dn(s,e),parseTime:s=>Hd(s,e)}}function nf({engineRef:e,initialSamplesPerPixel:t}){const[n,r]=m.useState(t),[s,a]=m.useState(!0),[o,i]=m.useState(!0),l=m.useRef(!0),c=m.useRef(!0),u=m.useRef(t),f=m.useCallback(()=>{e.current?.zoomIn()},[e]),p=m.useCallback(()=>{e.current?.zoomOut()},[e]),d=m.useCallback(h=>{h.samplesPerPixel!==u.current&&(u.current=h.samplesPerPixel,m.startTransition(()=>{r(h.samplesPerPixel)})),h.canZoomIn!==l.current&&(l.current=h.canZoomIn,a(h.canZoomIn)),h.canZoomOut!==c.current&&(c.current=h.canZoomOut,i(h.canZoomOut))},[]);return{samplesPerPixel:n,zoomIn:f,zoomOut:p,canZoomIn:s,canZoomOut:o,onEngineState:d}}function rf({engineRef:e,initialVolume:t=1}){const[n,r]=m.useState(t),s=m.useRef(t),a=m.useCallback(i=>{e.current?e.current.setMasterVolume(i):(s.current=i,r(i))},[e]),o=m.useCallback(i=>{i.masterVolume!==s.current&&(s.current=i.masterVolume,r(i.masterVolume))},[]);return{masterVolume:n,setMasterVolume:a,masterVolumeRef:s,onEngineState:o}}function E0({engineRef:e}){const[t,n]=m.useState(0),[r,s]=m.useState(0),a=m.useRef(0),o=m.useRef(0),i=m.useCallback((c,u)=>{e.current?.setSelection(c,u)},[e]),l=m.useCallback(c=>{c.selectionStart!==a.current&&(a.current=c.selectionStart,n(c.selectionStart)),c.selectionEnd!==o.current&&(o.current=c.selectionEnd,s(c.selectionEnd))},[]);return{selectionStart:t,selectionEnd:r,setSelection:i,selectionStartRef:a,selectionEndRef:o,onEngineState:l}}function I0({engineRef:e}){const[t,n]=m.useState(!1),[r,s]=m.useState(0),[a,o]=m.useState(0),i=m.useRef(!1),l=m.useRef(0),c=m.useRef(0),u=m.useCallback(h=>{e.current?.setLoopEnabled(h)},[e]),f=m.useCallback((h,v)=>{e.current?.setLoopRegion(h,v)},[e]),p=m.useCallback(()=>{e.current?.setLoopRegion(0,0)},[e]),d=m.useCallback(h=>{h.isLoopEnabled!==i.current&&(i.current=h.isLoopEnabled,n(h.isLoopEnabled)),h.loopStart!==l.current&&(l.current=h.loopStart,s(h.loopStart)),h.loopEnd!==c.current&&(c.current=h.loopEnd,o(h.loopEnd))},[]);return{isLoopEnabled:t,loopStart:r,loopEnd:a,setLoopEnabled:u,setLoopRegion:f,clearLoopRegion:p,isLoopEnabledRef:i,loopStartRef:l,loopEndRef:c,onEngineState:d}}function M0({engineRef:e}){const[t,n]=m.useState(null),r=m.useRef(null),s=m.useCallback(o=>{e.current?.selectTrack(o)},[e]),a=m.useCallback(o=>{o.selectedTrackId!==r.current&&(r.current=o.selectedTrackId,n(o.selectedTrackId))},[]);return{selectedTrackId:t,setSelectedTrackId:s,onEngineState:a,selectedTrackIdRef:r}}const A0=(e=256)=>{const t=m.useRef(null),n=m.useCallback((r,s,a)=>{const o=new L.Analyser("fft",e);return r.connect(o),r.connect(s),t.current=o,function(){o.dispose(),t.current=null}},[e]);return{analyserRef:t,masterEffects:n}};function ns(e,t,n,r,s=48e3){const a=n??e.audioBuffer,o=a?.sampleRate??e.waveformData?.sample_rate??s,i=a?.duration??e.waveformData?.duration??(e.duration!=null?e.duration+(e.offset??0):void 0);if(i===void 0)return console.warn(`[waveform-playlist] Track ${t+1} ("${e.name??"unnamed"}"): Cannot create track — provide duration, audioBuffer, or waveformData with duration.`),null;const l=uc({audioBuffer:a,sampleRate:o,sourceDuration:i,startTime:e.startTime??0,duration:e.duration??i,offset:e.offset??0,name:e.name||`Track ${t+1}`,fadeIn:e.fadeIn,fadeOut:e.fadeOut,waveformData:e.waveformData});if(isNaN(l.startSample)||isNaN(l.durationSamples)||isNaN(l.offsetSamples))return console.error(`[waveform-playlist] Invalid clip values for track ${t+1} ("${e.name??"unnamed"}"): startSample=${l.startSample}, durationSamples=${l.durationSamples}, offsetSamples=${l.offsetSamples}`),null;const c={...dc({name:e.name||`Track ${t+1}`,clips:[l],muted:e.muted??!1,soloed:e.soloed??!1,volume:e.volume??1,pan:e.pan??0,color:e.color}),effects:e.effects,renderMode:e.renderMode,spectrogramConfig:e.spectrogramConfig,spectrogramColorMap:e.spectrogramColorMap},u=r.get(t);return u?(c.id=u.trackId,c.clips[0]={...c.clips[0],id:u.clipId}):r.set(t,{trackId:c.id,clipId:c.clips[0].id}),c}function T0(e,t={}){const{immediate:n=!1,progressive:r=!1}=t,s=n||r,[a,o]=m.useState(!0),[i,l]=m.useState(null),[c,u]=m.useState(0),f=e.length,[p,d]=m.useState(new Map),h=m.useRef(new Map),v=m.useRef(48e3),g=m.useMemo(()=>{if(!s)return null;const _=[];for(let x=0;x<e.length;x++){const S=ns(e[x],x,p.get(x),h.current,v.current);S&&_.push(S)}return _},[s,e,p]),[y,b]=m.useState(g??[]),w=m.useRef(g);return g!==w.current&&(w.current=g,g&&b(g)),m.useEffect(()=>{if(e.length===0){b([]),o(!1),u(0);return}let _=!1;const x=new AbortController;return(async()=>{try{o(!0),l(null),u(0),s&&d(new Map);const k=cc.getContext().rawContext;v.current=k.sampleRate;const E=e.map(async(M,T)=>{if(M.audioBuffer){if(s&&!_){d(F=>{const O=new Map(F);return O.set(T,M.audioBuffer),O}),u(F=>F+1);return}return ns(M,T,M.audioBuffer,h.current,k.sampleRate)}if(!M.src&&M.waveformData){if(s&&!_){u(F=>F+1);return}return ns(M,T,void 0,h.current,k.sampleRate)}if(!M.src)throw new Error(`Track ${T+1}: Must provide src, audioBuffer, or waveformData`);const A=await fetch(M.src,{signal:x.signal});if(!A.ok)throw new Error(`Failed to fetch ${M.src}: ${A.statusText}`);const $=await A.arrayBuffer(),R=await k.decodeAudioData($);if(!R||!R.sampleRate||!R.duration)throw new Error(`Invalid audio buffer for ${M.src}`);if(s&&!_){d(F=>{const O=new Map(F);return O.set(T,R),O}),u(F=>F+1);return}return ns(M,T,R,h.current,k.sampleRate)}),I=await Promise.all(E);if(!_){if(!s){const M=I.filter(T=>T!=null);b(M),u(M.length)}o(!1)}}catch(k){if(!_){const E=k instanceof Error?k.message:"Unknown error loading audio";l(E),o(!1),console.error(`[waveform-playlist] Error loading audio tracks: ${E}`)}}})(),()=>{_=!0,x.abort()}},[e,s]),{tracks:y,loading:a,error:i,loadedCount:c,totalCount:f}}function $0({originalClip:e,clip:t,pixelDelta:n,samplesPerPixel:r,sampleRate:s,boundary:a,sortedClips:o,sortedIndex:i}){const l=n*r,c=Math.floor(.1*s),u={...t,startSample:e.startSample,offsetSamples:e.offsetSamples,durationSamples:e.durationSamples},f=vc(u,Math.floor(l),a,o,i,c);return a==="left"?{startSample:e.startSample+f,durationSamples:e.durationSamples-f,offsetSamples:e.offsetSamples+f}:{startSample:e.startSample,durationSamples:e.durationSamples+f,offsetSamples:e.offsetSamples}}function sf({tracks:e,onTracksChange:t,samplesPerPixel:n,sampleRate:r,engineRef:s,isDraggingRef:a,snapSamplePosition:o}){const i=m.useRef(o);i.current=o;const l=m.useRef(null),c=m.useRef(0),u=m.useCallback(d=>{const h=d.operation.source?.data;if(!h)return;if(!h.boundary){l.current=null;return}const g=e[h.trackIndex]?.clips[h.clipIndex];g&&(l.current={offsetSamples:g.offsetSamples,durationSamples:g.durationSamples,startSample:g.startSample},a.current=!0)},[e,a]),f=m.useCallback(d=>{const h=d.operation.source?.data;if(!h||!h.boundary||!l.current)return;const{boundary:v,trackIndex:g,clipIndex:y}=h,w=(d.to?.x??d.operation.position.current.x)-d.operation.position.initial.x,_=w*n,x=l.current,S=i.current;let k=_;const E=e.map((I,M)=>{if(M!==g)return I;const T=[...I.clips].sort((R,F)=>R.startSample-F.startSample),A=T.findIndex(R=>R===I.clips[y]),$=I.clips.map((R,F)=>{if(F!==y)return R;let O=$0({originalClip:x,clip:R,pixelDelta:w,samplesPerPixel:n,sampleRate:r,boundary:v,sortedClips:T,sortedIndex:A});if(S)if(v==="left"){const G=S(O.startSample),Q=G-O.startSample;O={startSample:G,durationSamples:O.durationSamples-Q,offsetSamples:O.offsetSamples+Q},k=G-x.startSample}else{const G=O.startSample+O.durationSamples,Q=S(G);O={...O,durationSamples:Q-O.startSample},k=O.durationSamples-x.durationSamples}return{...R,startSample:O.startSample,durationSamples:O.durationSamples,offsetSamples:O.offsetSamples}});return{...I,clips:$}});c.current=k,t(E)},[e,t,n,r]),p=m.useCallback(d=>{if(d.canceled){if(l.current){const _=d.operation.source?.data;if(_){const{trackIndex:x,clipIndex:S}=_,k=l.current,E=e.map((I,M)=>{if(M!==x)return I;const T=I.clips.map((A,$)=>$!==S?A:{...A,offsetSamples:k.offsetSamples,durationSamples:k.durationSamples,startSample:k.startSample});return{...I,clips:T}});t(E)}}a.current=!1,l.current=null,c.current=0;return}const h=d.operation.source?.data;if(!h)return;const{trackIndex:v,clipId:g,boundary:y}=h,b=y?c.current:d.operation.transform.x*n,w=e[v]?.id;if(y){a.current=!1,w?s.current?s.current.trimClip(w,g,y,Math.floor(b)):console.warn("[waveform-playlist] engineRef is null — trim not synced to adapter"):console.warn(`[waveform-playlist] onDragEnd: track at index ${v} not found — trim not synced to adapter`),l.current=null,c.current=0;return}w?s.current?s.current.moveClip(w,g,Math.floor(b)):console.warn("[waveform-playlist] engineRef is null — move not synced to adapter"):console.warn(`[waveform-playlist] onDragEnd: track at index ${v} not found — move not synced to adapter`)},[e,t,n,s,a]);return{onDragStart:u,onDragMove:f,onDragEnd:p}}const ba=.01;function af({annotations:e,onAnnotationsChange:t,samplesPerPixel:n,sampleRate:r,duration:s,linkEndpoints:a}){const o=m.useRef(null),i=m.useCallback(u=>{const f=u.operation.source?.data;if(!f||f.annotationIndex===void 0){o.current=null;return}const p=e[f.annotationIndex];p&&(o.current={start:p.start,end:p.end,annotationIndex:f.annotationIndex})},[e]),l=m.useCallback(u=>{if(!o.current)return;const f=u.operation.source?.data;if(!f)return;const{edge:p,annotationIndex:d}=f,h=o.current,y=((u.to?.x??u.operation.position.current.x)-u.operation.position.initial.x)*n/r,b=p==="start"?h.start+y:h.end+y,w=R0({annotationIndex:d,newTime:b,isDraggingStart:p==="start",annotations:e,duration:s,linkEndpoints:a});t(w)},[e,t,n,r,s,a]),c=m.useCallback(u=>{if(u.canceled&&o.current){const{annotationIndex:f,start:p,end:d}=o.current,h=e.map((v,g)=>g!==f?v:{...v,start:p,end:d});t(h)}o.current=null},[e,t]);return{onDragStart:i,onDragMove:l,onDragEnd:c}}function R0({annotationIndex:e,newTime:t,isDraggingStart:n,annotations:r,duration:s,linkEndpoints:a}){const o=[...r],i=r[e];if(n){const l=Math.min(i.end-.1,Math.max(0,t)),c=l-i.start;if(o[e]={...i,start:l},a&&e>0){const u=o[e-1];Math.abs(u.end-i.start)<ba?o[e-1]={...u,end:Math.max(u.start+.1,u.end+c)}:l<=u.end&&(o[e]={...o[e],start:u.end})}else!a&&e>0&&l<o[e-1].end&&(o[e-1]={...o[e-1],end:l})}else{const l=Math.max(i.start+.1,Math.min(t,s)),c=l-i.end;if(o[e]={...i,end:l},a&&e<o.length-1){const u=o[e+1];if(Math.abs(u.start-i.end)<ba){const f=u.start+c;o[e+1]={...u,start:Math.min(u.end-.1,f)};let p=e+1;for(;p<o.length-1;){const d=o[p],h=o[p+1];if(Math.abs(h.start-d.end)<ba){const v=d.end-r[p].end;o[p+1]={...h,start:Math.min(h.end-.1,h.start+v)},p++}else break}}else l>=u.start&&(o[e]={...o[e],end:u.start})}else if(!a&&e<o.length-1&&l>o[e+1].start){const u=o[e+1];o[e+1]={...u,start:l};let f=e+1;for(;f<o.length-1;){const p=o[f],d=o[f+1];if(p.end>d.start)o[f+1]={...d,start:p.end},f++;else break}}}return o}function of(e={}){const{touchOptimized:t=!1,touchDelay:n=250,touchTolerance:r=5,mouseDistance:s=1}=e;return m.useMemo(()=>t?[ro.configure({activationConstraints(a){return a.pointerType==="touch"?[new Ft.Delay({value:n,tolerance:r})]:[new Ft.Distance({value:s})]}})]:[ro.configure({activationConstraints:[new Ft.Distance({value:s})]})],[t,n,r,s])}const lf=e=>{const{tracks:t,sampleRate:n,engineRef:r}=e,{currentTimeRef:s}=tt(),{selectedTrackId:a}=nt(),o=m.useCallback((l,c,u)=>{const{samplesPerPixel:f}=e,p=t[l];if(!p)return!1;const d=p.clips[c];if(!d)return!1;const h=Math.round(u*n),v=yh(h,f),g=Math.floor(.1*n);if(!yc(d,v,g))return console.warn("Split point is invalid (outside bounds or too close to edge)"),!1;const y=r.current;return y?(y.splitClip(p.id,d.id,v),!0):(console.warn("[waveform-playlist] engineRef is null — split not synced to adapter"),!1)},[t,e,n,r]);return{splitClipAtPlayhead:m.useCallback(()=>{if(!a)return console.warn("[waveform-playlist] No track selected — click a clip to select a track first"),!1;const l=t.findIndex(f=>f.id===a);if(l===-1)return console.warn("Selected track not found"),!1;const c=t[l],u=s.current??0;for(let f=0;f<c.clips.length;f++){const p=c.clips[f],d=p.startSample/n,h=(p.startSample+p.durationSamples)/n;if(u>d&&u<h)return o(l,f,u)}return console.warn(`[waveform-playlist] No clip found at playhead position on track "${c.name}"`),!1},[t,s,a,o,n]),splitClipAt:o}},Ps=e=>{const{shortcuts:t,enabled:n=!0}=e,r=m.useCallback(s=>{if(!n)return;const a=s.target;if(a.tagName==="INPUT"||a.tagName==="TEXTAREA"||a.isContentEditable)return;const o=t.find(i=>{const l=s.key.toLowerCase()===i.key.toLowerCase()||s.key===i.key,c=i.ctrlKey===void 0||s.ctrlKey===i.ctrlKey,u=i.shiftKey===void 0||s.shiftKey===i.shiftKey,f=i.metaKey===void 0||s.metaKey===i.metaKey,p=i.altKey===void 0||s.altKey===i.altKey;return l&&c&&u&&f&&p});o&&(o.preventDefault!==!1&&s.preventDefault(),o.action())},[t,n]);m.useEffect(()=>{if(n)return window.addEventListener("keydown",r),()=>{window.removeEventListener("keydown",r)}},[r,n])},D0=e=>{const t=[],n=typeof navigator<"u"&&navigator.platform.includes("Mac");return e.metaKey&&t.push(n?"Cmd":"Ctrl"),e.ctrlKey&&!e.metaKey&&t.push("Ctrl"),e.altKey&&t.push(n?"Option":"Alt"),e.shiftKey&&t.push("Shift"),t.push(e.key.toUpperCase()),t.join("+")},cf=(e={})=>{const{enabled:t=!0,additionalShortcuts:n=[],shortcuts:r}=e,{isPlaying:s}=tt(),{setCurrentTime:a,play:o,pause:i,stop:l}=Se(),c=m.useCallback(()=>{s?i():o()},[s,o,i]),u=m.useCallback(()=>{l()},[l]),f=m.useCallback(()=>{a(0),s&&o(0)},[s,a,o]),d=r??[...[{key:" ",action:c,description:"Play/Pause",preventDefault:!0},{key:"Escape",action:u,description:"Stop",preventDefault:!0},{key:"0",action:f,description:"Rewind to start",preventDefault:!0}],...n];return Ps({shortcuts:d,enabled:t}),{rewindToStart:f,togglePlayPause:c,stopPlayback:u,shortcuts:d}},wa=.01,rs=.01;function uf({annotations:e,activeAnnotationId:t,onAnnotationsChange:n,onActiveAnnotationChange:r,duration:s,linkEndpoints:a,continuousPlay:o=!1,enabled:i=!0,scrollContainerRef:l,samplesPerPixel:c,sampleRate:u,onPlay:f}){const p=m.useMemo(()=>t?e.findIndex(E=>E.id===t):-1,[e,t]),d=m.useCallback(E=>{if(!l?.current||!c||!u)return;const I=e.find(Q=>Q.id===E);if(!I)return;const M=l.current,T=M.clientWidth,A=I.start*u/c,$=I.end*u/c,R=(A+$)/2,F=M.scrollLeft,O=F,G=F+T;if(A<O||$>G){const Q=Math.max(0,R-T/2);M.scrollTo({left:Q,behavior:"smooth"})}},[e,l,c,u]);m.useEffect(()=>{t&&l?.current&&c&&u&&d(t)},[t,d,l,c,u]);const h=m.useCallback(E=>{if(p<0)return;const I=e[p],M=Math.max(0,Math.min(I.end-.1,I.start+E)),T=M-I.start,A=[...e];if(A[p]={...I,start:M},a&&p>0){const $=A[p-1];Math.abs($.end-I.start)<wa&&(A[p-1]={...$,end:Math.max($.start+.1,$.end+T)})}else if(!a&&p>0){const $=A[p-1];M<$.end&&(A[p-1]={...$,end:M})}n(A)},[e,p,a,n]),v=m.useCallback(E=>{if(p<0)return;const I=e[p],M=Math.max(I.start+.1,Math.min(s,I.end+E)),T=M-I.end,A=[...e];if(A[p]={...I,end:M},a&&p<e.length-1){const $=A[p+1];if(Math.abs($.start-I.end)<wa){const R=Math.min($.end-.1,$.start+T);A[p+1]={...$,start:R};let F=p+1;for(;F<A.length-1;){const O=A[F],G=A[F+1];if(Math.abs(G.start-e[F].end)<wa){const Q=O.end-e[F].end;A[F+1]={...G,start:Math.min(G.end-.1,G.start+Q)},F++}else break}}}else if(!a&&p<e.length-1){const $=A[p+1];if(M>$.start){A[p+1]={...$,start:M};let R=p+1;for(;R<A.length-1;){const F=A[R],O=A[R+1];if(F.end>O.start)A[R+1]={...O,start:F.end},R++;else break}}}n(A)},[e,p,s,a,n]),g=m.useCallback(()=>{!r||e.length===0||(p<=0?r(e[e.length-1].id):r(e[p-1].id))},[e,p,r]),y=m.useCallback(()=>{!r||e.length===0||(p<0||p>=e.length-1?r(e[0].id):r(e[p+1].id))},[e,p,r]),b=m.useCallback(()=>{!r||e.length===0||r(e[0].id)},[e,r]),w=m.useCallback(()=>{!r||e.length===0||r(e[e.length-1].id)},[e,r]),_=m.useCallback(()=>{r&&r(null)},[r]),x=m.useCallback(()=>{if(p<0||!f)return;const E=e[p],I=o?void 0:E.end-E.start;f(E.start,I)},[e,p,o,f]),S=m.useMemo(()=>[{key:"[",action:()=>h(-rs),description:"Move annotation start earlier",preventDefault:!0},{key:"]",action:()=>h(rs),description:"Move annotation start later",preventDefault:!0},{key:"{",shiftKey:!0,action:()=>v(-rs),description:"Move annotation end earlier",preventDefault:!0},{key:"}",shiftKey:!0,action:()=>v(rs),description:"Move annotation end later",preventDefault:!0},{key:"Enter",action:x,description:"Play selected annotation",preventDefault:!0}],[h,v,x]),k=m.useMemo(()=>[{key:"ArrowUp",action:g,description:"Select previous annotation",preventDefault:!0},{key:"ArrowLeft",action:g,description:"Select previous annotation",preventDefault:!0},{key:"ArrowDown",action:y,description:"Select next annotation",preventDefault:!0},{key:"ArrowRight",action:y,description:"Select next annotation",preventDefault:!0},{key:"Home",action:b,description:"Select first annotation",preventDefault:!0},{key:"End",action:w,description:"Select last annotation",preventDefault:!0},{key:"Escape",action:_,description:"Deselect annotation",preventDefault:!0}],[g,y,b,w,_]);return Ps({shortcuts:S,enabled:i&&p>=0}),Ps({shortcuts:k,enabled:i&&e.length>0&&!!r}),{moveStartBoundary:h,moveEndBoundary:v,selectPrevious:g,selectNext:y,selectFirst:b,selectLast:w,clearSelection:_,scrollToAnnotation:d,playActiveAnnotation:x}}const Wr=[{id:"reverb",name:"Reverb",category:"reverb",description:"Simple convolution reverb with adjustable decay time",parameters:[{name:"decay",label:"Decay",type:"number",min:.1,max:10,step:.1,default:1.5,unit:"s"},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:.5}]},{id:"freeverb",name:"Freeverb",category:"reverb",description:"Classic Schroeder/Moorer reverb with room size and dampening",parameters:[{name:"roomSize",label:"Room Size",type:"number",min:0,max:1,step:.01,default:.7},{name:"dampening",label:"Dampening",type:"number",min:0,max:1e4,step:100,default:3e3,unit:"Hz"},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:.5}]},{id:"jcReverb",name:"JC Reverb",category:"reverb",description:"Attempt at Roland JC-120 chorus reverb emulation",parameters:[{name:"roomSize",label:"Room Size",type:"number",min:0,max:1,step:.01,default:.5},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:.5}]},{id:"feedbackDelay",name:"Feedback Delay",category:"delay",description:"Delay line with feedback for echo effects",parameters:[{name:"delayTime",label:"Delay Time",type:"number",min:0,max:1,step:.01,default:.25,unit:"s"},{name:"feedback",label:"Feedback",type:"number",min:0,max:.95,step:.01,default:.5},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:.5}]},{id:"pingPongDelay",name:"Ping Pong Delay",category:"delay",description:"Stereo delay bouncing between left and right channels",parameters:[{name:"delayTime",label:"Delay Time",type:"number",min:0,max:1,step:.01,default:.25,unit:"s"},{name:"feedback",label:"Feedback",type:"number",min:0,max:.95,step:.01,default:.5},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:.5}]},{id:"chorus",name:"Chorus",category:"modulation",description:"Creates thickness by layering detuned copies of the signal",parameters:[{name:"frequency",label:"Rate",type:"number",min:.1,max:10,step:.1,default:1.5,unit:"Hz"},{name:"delayTime",label:"Delay",type:"number",min:0,max:20,step:.5,default:3.5,unit:"ms"},{name:"depth",label:"Depth",type:"number",min:0,max:1,step:.01,default:.7},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:.5}]},{id:"phaser",name:"Phaser",category:"modulation",description:"Classic phaser effect using allpass filters",parameters:[{name:"frequency",label:"Rate",type:"number",min:.1,max:10,step:.1,default:.5,unit:"Hz"},{name:"octaves",label:"Octaves",type:"number",min:1,max:6,step:1,default:3},{name:"baseFrequency",label:"Base Freq",type:"number",min:100,max:2e3,step:10,default:350,unit:"Hz"},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:.5}]},{id:"tremolo",name:"Tremolo",category:"modulation",description:"Rhythmic volume modulation",parameters:[{name:"frequency",label:"Rate",type:"number",min:.1,max:20,step:.1,default:4,unit:"Hz"},{name:"depth",label:"Depth",type:"number",min:0,max:1,step:.01,default:.5},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:1}]},{id:"vibrato",name:"Vibrato",category:"modulation",description:"Pitch modulation effect",parameters:[{name:"frequency",label:"Rate",type:"number",min:.1,max:20,step:.1,default:5,unit:"Hz"},{name:"depth",label:"Depth",type:"number",min:0,max:1,step:.01,default:.1},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:1}]},{id:"autoPanner",name:"Auto Panner",category:"modulation",description:"Automatic left-right panning",parameters:[{name:"frequency",label:"Rate",type:"number",min:.1,max:10,step:.1,default:1,unit:"Hz"},{name:"depth",label:"Depth",type:"number",min:0,max:1,step:.01,default:1},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:1}]},{id:"autoFilter",name:"Auto Filter",category:"filter",description:"Automated filter sweep with LFO",parameters:[{name:"frequency",label:"Rate",type:"number",min:.1,max:10,step:.1,default:1,unit:"Hz"},{name:"baseFrequency",label:"Base Freq",type:"number",min:20,max:2e3,step:10,default:200,unit:"Hz"},{name:"octaves",label:"Octaves",type:"number",min:.5,max:8,step:.5,default:2.6},{name:"depth",label:"Depth",type:"number",min:0,max:1,step:.01,default:1},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:1}]},{id:"autoWah",name:"Auto Wah",category:"filter",description:"Envelope follower filter effect",parameters:[{name:"baseFrequency",label:"Base Freq",type:"number",min:20,max:500,step:10,default:100,unit:"Hz"},{name:"octaves",label:"Octaves",type:"number",min:1,max:8,step:1,default:6},{name:"sensitivity",label:"Sensitivity",type:"number",min:-40,max:0,step:1,default:0,unit:"dB"},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:1}]},{id:"eq3",name:"3-Band EQ",category:"filter",description:"Three band equalizer with low, mid, and high controls",parameters:[{name:"low",label:"Low",type:"number",min:-24,max:24,step:.5,default:0,unit:"dB"},{name:"mid",label:"Mid",type:"number",min:-24,max:24,step:.5,default:0,unit:"dB"},{name:"high",label:"High",type:"number",min:-24,max:24,step:.5,default:0,unit:"dB"},{name:"lowFrequency",label:"Low Freq",type:"number",min:20,max:500,step:10,default:400,unit:"Hz"},{name:"highFrequency",label:"High Freq",type:"number",min:1e3,max:1e4,step:100,default:2500,unit:"Hz"}]},{id:"distortion",name:"Distortion",category:"distortion",description:"Wave shaping distortion effect",parameters:[{name:"distortion",label:"Drive",type:"number",min:0,max:1,step:.01,default:.4},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:1}]},{id:"bitCrusher",name:"Bit Crusher",category:"distortion",description:"Reduces bit depth for lo-fi digital texture",parameters:[{name:"bits",label:"Bits",type:"number",min:1,max:16,step:1,default:4},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:1}]},{id:"chebyshev",name:"Chebyshev",category:"distortion",description:"Waveshaping distortion using Chebyshev polynomials",parameters:[{name:"order",label:"Order",type:"number",min:1,max:100,step:1,default:50},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:1}]},{id:"compressor",name:"Compressor",category:"dynamics",description:"Dynamic range compressor",parameters:[{name:"threshold",label:"Threshold",type:"number",min:-60,max:0,step:1,default:-24,unit:"dB"},{name:"ratio",label:"Ratio",type:"number",min:1,max:20,step:.5,default:4},{name:"attack",label:"Attack",type:"number",min:0,max:1,step:.001,default:.003,unit:"s"},{name:"release",label:"Release",type:"number",min:0,max:1,step:.01,default:.25,unit:"s"},{name:"knee",label:"Knee",type:"number",min:0,max:40,step:1,default:30,unit:"dB"}]},{id:"limiter",name:"Limiter",category:"dynamics",description:"Hard limiter to prevent clipping",parameters:[{name:"threshold",label:"Threshold",type:"number",min:-12,max:0,step:.5,default:-6,unit:"dB"}]},{id:"gate",name:"Gate",category:"dynamics",description:"Noise gate to silence signal below threshold",parameters:[{name:"threshold",label:"Threshold",type:"number",min:-100,max:0,step:1,default:-40,unit:"dB"},{name:"attack",label:"Attack",type:"number",min:0,max:.3,step:.001,default:.001,unit:"s"},{name:"release",label:"Release",type:"number",min:0,max:.5,step:.01,default:.1,unit:"s"}]},{id:"stereoWidener",name:"Stereo Widener",category:"spatial",description:"Expands or narrows the stereo image",parameters:[{name:"width",label:"Width",type:"number",min:0,max:1,step:.01,default:.5}]}],Ci=e=>Wr.find(t=>t.id===e),P0=e=>Wr.filter(t=>t.category===e),F0=[{id:"reverb",name:"Reverb"},{id:"delay",name:"Delay"},{id:"modulation",name:"Modulation"},{id:"filter",name:"Filter"},{id:"distortion",name:"Distortion"},{id:"dynamics",name:"Dynamics"},{id:"spatial",name:"Spatial"}];const O0={reverb:L.Reverb,freeverb:L.Freeverb,jcReverb:L.JCReverb,feedbackDelay:L.FeedbackDelay,pingPongDelay:L.PingPongDelay,chorus:L.Chorus,phaser:L.Phaser,tremolo:L.Tremolo,vibrato:L.Vibrato,autoPanner:L.AutoPanner,autoFilter:L.AutoFilter,autoWah:L.AutoWah,eq3:L.EQ3,distortion:L.Distortion,bitCrusher:L.BitCrusher,chebyshev:L.Chebyshev,compressor:L.Compressor,limiter:L.Limiter,gate:L.Gate,stereoWidener:L.StereoWidener};let L0=0;const B0=()=>`effect_${Date.now()}_${++L0}`;function kr(e,t){const n=O0[e.id];if(!n)throw new Error(`Unknown effect type: ${e.id}`);const r={};e.parameters.forEach(i=>{const l=t?.[i.name]??i.default;r[i.name]=l});const s=new n(r),a=B0(),o=s;return{effect:s,id:e.id,instanceId:a,dispose(){try{s.disconnect(),s.dispose()}catch(i){console.warn(`[waveform-playlist] Error disposing effect "${e.id}" (${a}):`,i)}},setParameter(i,l){const c=o[i];if(i==="wet"){const u=o.wet;if(u&&typeof u=="object"&&"value"in u){u.value=l;return}}c!==void 0&&(c&&typeof c=="object"&&"value"in c?c.value=l:o[i]=l)},getParameter(i){if(i==="wet"){const c=o.wet;if(c&&typeof c=="object"&&"value"in c)return c.value}const l=o[i];if(l!==void 0)return l&&typeof l=="object"&&"value"in l?l.value:l},connect(i){s.connect(i)},disconnect(){try{s.disconnect()}catch(i){console.warn(`[waveform-playlist] Error disconnecting effect "${e.id}" (${a}):`,i)}}}}function W0(e){if(e.length===0)throw new Error("Cannot create effect chain with no effects");for(let t=0;t<e.length-1;t++)e[t].effect.connect(e[t+1].effect);return{input:e[0].effect,output:e[e.length-1].effect,dispose(){e.forEach(t=>t.dispose())}}}function V0(e=256){const[t,n]=m.useState([]),r=m.useRef(t);r.current=t;const s=m.useRef(new Map),a=m.useRef(null),o=m.useRef(null),i=m.useCallback(g=>{const y=o.current;if(!y)return;const{masterGainNode:b,destination:w,analyserNode:_}=y;try{b.disconnect()}catch(S){console.warn("[waveform-playlist] Error disconnecting master effects chain:",S)}const x=g.map(S=>s.current.get(S.instanceId)).filter(S=>S!==void 0);if(x.length===0)b.connect(_),_.connect(w);else{let S=b;x.forEach(k=>{try{k.disconnect()}catch(E){console.warn(`[waveform-playlist] Error disconnecting effect "${k.id}":`,E)}S.connect(k.effect),S=k.effect}),S.connect(_),_.connect(w)}},[]),l=m.useCallback(g=>{const y=Ci(g);if(!y){console.error(`Unknown effect: ${g}`);return}const b={};y.parameters.forEach(x=>{b[x.name]=x.default});const w=kr(y,b);s.current.set(w.instanceId,w);const _={instanceId:w.instanceId,effectId:y.id,definition:y,params:b,bypassed:!1};n(x=>[...x,_])},[]),c=m.useCallback(g=>{const y=s.current.get(g);y&&(y.dispose(),s.current.delete(g)),n(b=>b.filter(w=>w.instanceId!==g))},[]),u=m.useCallback((g,y,b)=>{const w=s.current.get(g);w&&w.setParameter(y,b),n(_=>_.map(x=>x.instanceId===g?{...x,params:{...x.params,[y]:b}}:x))},[]),f=m.useCallback(g=>{const y=r.current.find(_=>_.instanceId===g);if(!y)return;const b=!y.bypassed,w=s.current.get(g);if(w){const _=y.params.wet??1;w.setParameter("wet",b?0:_)}n(_=>_.map(x=>x.instanceId===g?{...x,bypassed:b}:x))},[]),p=m.useCallback((g,y)=>{n(b=>{const w=[...b],[_]=w.splice(g,1);return w.splice(y,0,_),w})},[]),d=m.useCallback(()=>{s.current.forEach(g=>g.dispose()),s.current.clear(),n([])},[]);m.useEffect(()=>{i(t)},[t,i]);const h=m.useCallback((g,y,b)=>{const w=new L.Analyser("fft",e);a.current=w,o.current={masterGainNode:g,destination:y,analyserNode:w};const x=r.current.map(S=>s.current.get(S.instanceId)).filter(S=>S!==void 0);if(x.length===0)g.connect(w),w.connect(y);else{let S=g;x.forEach(k=>{S.connect(k.effect),S=k.effect}),S.connect(w),w.connect(y)}return function(){w.dispose(),a.current=null,o.current=null}},[e]);m.useEffect(()=>{const g=s.current;return()=>{g.forEach(y=>y.dispose()),g.clear()}},[]);const v=m.useCallback(()=>{const g=t.filter(y=>!y.bypassed);if(g.length!==0)return(y,b,w)=>{const _=[];for(const x of g){const S=kr(x.definition,x.params);_.push(S)}if(_.length===0)y.connect(b);else{let x=y;_.forEach(S=>{x.connect(S.effect),x=S.effect}),x.connect(b)}return function(){_.forEach(S=>S.dispose())}}},[t]);return{activeEffects:t,availableEffects:Wr,addEffect:l,removeEffect:c,updateParameter:u,toggleBypass:f,reorderEffects:p,clearAllEffects:d,masterEffects:h,createOfflineEffectsFunction:v,analyserRef:a}}function N0(){const[e,t]=m.useState(new Map),n=m.useRef(new Map),r=m.useRef(new Map),s=m.useCallback((d,h)=>{const v=r.current.get(d);if(!v)return;const{graphEnd:g,masterGainNode:y}=v,b=n.current.get(d);try{g.disconnect()}catch(_){console.warn(`[waveform-playlist] Error disconnecting track "${d}" effect chain:`,_)}const w=h.map(_=>b?.get(_.instanceId)).filter(_=>_!==void 0);if(w.length===0)g.connect(y);else{let _=g;w.forEach(x=>{try{x.disconnect()}catch(S){console.warn(`[waveform-playlist] Error disconnecting effect "${x.id}" on track "${d}":`,S)}_.connect(x.effect),_=x.effect}),_.connect(y)}},[]),a=m.useCallback((d,h)=>{const v=Ci(h);if(!v){console.error(`Unknown effect: ${h}`);return}const g={};v.parameters.forEach(w=>{g[w.name]=w.default});const y=kr(v,g);n.current.has(d)||n.current.set(d,new Map),n.current.get(d).set(y.instanceId,y);const b={instanceId:y.instanceId,effectId:v.id,definition:v,params:g,bypassed:!1};t(w=>{const _=new Map(w),x=_.get(d)||[];return _.set(d,[...x,b]),_})},[]),o=m.useCallback((d,h)=>{const v=n.current.get(d),g=v?.get(h);g&&(g.dispose(),v?.delete(h)),t(y=>{const b=new Map(y),w=b.get(d)||[];return b.set(d,w.filter(_=>_.instanceId!==h)),b})},[]),i=m.useCallback((d,h,v,g)=>{const b=n.current.get(d)?.get(h);b&&b.setParameter(v,g),t(w=>{const _=new Map(w),x=_.get(d)||[];return _.set(d,x.map(S=>S.instanceId===h?{...S,params:{...S.params,[v]:g}}:S)),_})},[]),l=m.useCallback((d,h)=>{const g=(u.current.get(d)||[]).find(_=>_.instanceId===h);if(!g)return;const y=!g.bypassed,w=n.current.get(d)?.get(h);if(w){const _=g.params.wet??1;w.setParameter("wet",y?0:_)}t(_=>{const x=new Map(_),S=x.get(d)||[];return x.set(d,S.map(k=>k.instanceId===h?{...k,bypassed:y}:k)),x})},[]),c=m.useCallback(d=>{const h=n.current.get(d);h&&(h.forEach(v=>v.dispose()),h.clear()),t(v=>{const g=new Map(v);return g.set(d,[]),g})},[]),u=m.useRef(e);u.current=e;const f=m.useCallback(d=>(h,v,g)=>{r.current.set(d,{graphEnd:h,masterGainNode:v});const y=u.current.get(d)||[],b=n.current.get(d),w=y.map(_=>b?.get(_.instanceId)).filter(_=>_!==void 0);if(w.length===0)h.connect(v);else{let _=h;w.forEach(x=>{_.connect(x.effect),_=x.effect}),_.connect(v)}return function(){r.current.delete(d)}},[]);m.useEffect(()=>{e.forEach((d,h)=>{s(h,d)})},[e,s]),m.useEffect(()=>{const d=n.current;return()=>{d.forEach(h=>{h.forEach(v=>v.dispose()),h.clear()}),d.clear()}},[]);const p=m.useCallback(d=>{const v=(e.get(d)||[]).filter(g=>!g.bypassed);if(v.length!==0)return(g,y,b)=>{const w=[];for(const _ of v){const x=kr(_.definition,_.params);w.push(x)}if(w.length===0)g.connect(y);else{let _=g;w.forEach(x=>{_.connect(x.effect),_=x.effect}),_.connect(y)}return function(){w.forEach(x=>x.dispose())}}},[e]);return{trackEffectsState:e,addEffectToTrack:a,removeEffectFromTrack:o,updateTrackEffectParameter:i,toggleBypass:l,clearTrackEffects:c,getTrackEffectsFunction:f,createOfflineTrackEffectsFunction:p,availableEffects:Wr}}function j0(e,t={}){const{bitDepth:n=16}=t,r=e.numberOfChannels,s=e.sampleRate,a=e.length,o=n/8,i=r*o,l=s*i,c=a*i,u=44,f=u+c,p=new ArrayBuffer(f),d=new DataView(p);ss(d,0,"RIFF"),d.setUint32(4,f-8,!0),ss(d,8,"WAVE"),ss(d,12,"fmt "),d.setUint32(16,16,!0),d.setUint16(20,n===32?3:1,!0),d.setUint16(22,r,!0),d.setUint32(24,s,!0),d.setUint32(28,l,!0),d.setUint16(32,i,!0),d.setUint16(34,n,!0),ss(d,36,"data"),d.setUint32(40,c,!0);const h=[];for(let g=0;g<r;g++)h.push(e.getChannelData(g));let v=u;if(n===16)for(let g=0;g<a;g++)for(let y=0;y<r;y++){const b=h[y][g],w=Math.max(-1,Math.min(1,b)),_=w<0?w*32768:w*32767;d.setInt16(v,_,!0),v+=2}else for(let g=0;g<a;g++)for(let y=0;y<r;y++)d.setFloat32(v,h[y][g],!0),v+=4;return new Blob([p],{type:"audio/wav"})}function ss(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}function z0(e,t){const n=URL.createObjectURL(e),r=document.createElement("a");r.href=n,r.download=t,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}function df(){const[e,t]=m.useState(!1),[n,r]=m.useState(0),[s,a]=m.useState(null);return{exportWav:m.useCallback(async(i,l,c={})=>{const{filename:u="export",mode:f="master",trackIndex:p,autoDownload:d=!0,applyEffects:h=!0,effectsFunction:v,createOfflineTrackEffects:g,bitDepth:y=16,onProgress:b}=c;t(!0),r(0),a(null);try{if(i.length===0)throw new Error("No tracks to export");if(f==="individual"&&(p===void 0||p<0||p>=i.length))throw new Error("Invalid track index for individual export");const w=i[0].clips[0]?.sampleRate||44100;let _=0;for(const T of i)for(const A of T.clips){const $=A.startSample+A.durationSamples;_=Math.max(_,$)}_+=Math.round(w*.1);const x=_/w,S=f==="individual"?[{track:i[p],state:l[p],index:p}]:i.map((T,A)=>({track:T,state:l[A],index:A})),k=l.some(T=>T.soloed),E=!!g;let I;if((v||E)&&h)I=await Z0(S,l,k,x,w,v,g,T=>{r(T),b?.(T)});else{const T=new OfflineAudioContext(2,_,w);let A=0;const $=S.reduce((R,{track:F})=>R+F.clips.length,0);for(const{track:R,state:F}of S)if(!(F.muted&&!F.soloed)&&!(k&&!F.soloed))for(const O of R.clips){await G0(T,O,F,w,h),A++;const G=A/$*.5;r(G),b?.(G)}r(.5),b?.(.5),I=await T.startRendering()}r(.9),b?.(.9);const M=j0(I,{bitDepth:y});if(r(1),b?.(1),d){const T=f==="individual"?`${u}_${i[p].name}`:u;z0(M,`${T}.wav`)}return{audioBuffer:I,blob:M,duration:x}}catch(w){const _=w instanceof Error?w.message:"Export failed";throw a(_),w}finally{t(!1)}},[]),isExporting:e,progress:n,error:s}}async function Z0(e,t,n,r,s,a,o,i){const{Offline:l,Volume:c,Gain:u,Panner:f,Player:p,ToneAudioBuffer:d}=await import("tone");i(.1);let h;try{h=await l(async({transport:v,destination:g})=>{const y=new c(0);let b;a?b=a(y,g,!0):y.connect(g);for(const{track:w,state:_}of e){if(_.muted&&!_.soloed||n&&!_.soloed)continue;const x=new c(H0(_.volume)),S=new f(_.pan),k=new u(_.muted?0:1),E=o?.(w.id);E?E(k,y,!0):k.connect(y),S.connect(k),x.connect(S);for(const I of w.clips){const{audioBuffer:M,startSample:T,durationSamples:A,offsetSamples:$,gain:R,fadeIn:F,fadeOut:O}=I,G=T/s,Q=A/s,ee=$/s,ue=new d(M),te=new p(ue),oe=new u(R);if(te.connect(oe),oe.connect(x),F){const se=G,le=G+F.duration,ye=gr(oe.gain);ye&&(ye.setValueAtTime(0,se),ye.linearRampToValueAtTime(R,le))}if(O){const se=G+Q-O.duration,le=G+Q,ye=gr(oe.gain);ye&&(ye.setValueAtTime(R,se),ye.linearRampToValueAtTime(0,le))}te.start(G,ee,Q)}}v.start(0)},r,2,s)}catch(v){throw v instanceof Error?v:new Error(`Tone.Offline rendering failed: ${String(v)}`)}return i(.9),h.get()}function H0(e){return 20*Math.log10(Math.max(e,1e-4))}async function G0(e,t,n,r,s){const{audioBuffer:a,startSample:o,durationSamples:i,offsetSamples:l,gain:c,fadeIn:u,fadeOut:f}=t;if(!a){console.warn(`Skipping clip "${t.name||t.id}" - no audioBuffer for export`);return}const p=o/r,d=i/r,h=l/r,v=e.createBufferSource();v.buffer=a;const g=e.createGain(),y=c*n.volume,b=e.createStereoPanner();if(b.pan.value=n.pan,v.connect(g),g.connect(b),b.connect(e.destination),s){if(u?g.gain.setValueAtTime(0,p):g.gain.setValueAtTime(y,p),u){const w=p,_=p+u.duration;ec(g.gain,w,_,0,y,u.type||"linear")}if(f){const w=p+d-f.duration,_=p+d;(!u||u.duration<d-f.duration)&&g.gain.setValueAtTime(y,w),ec(g.gain,w,_,y,0,f.type||"linear")}}else g.gain.setValueAtTime(y,p);v.start(p,h,d)}function ec(e,t,n,r,s,a){const o=n-t;if(!(o<=0))switch(a){case"linear":e.setValueAtTime(r,t),e.linearRampToValueAtTime(s,n);break;case"exponential":{const i=Math.max(r,1e-4),l=Math.max(s,1e-4);e.setValueAtTime(i,t),e.exponentialRampToValueAtTime(l,n),s===0&&e.setValueAtTime(0,n);break}case"logarithmic":{const i=tc(r,s,256,"logarithmic");e.setValueCurveAtTime(i,t,o);break}case"sCurve":{const i=tc(r,s,256,"sCurve");e.setValueCurveAtTime(i,t,o);break}default:e.setValueAtTime(r,t),e.linearRampToValueAtTime(s,n)}}function tc(e,t,n,r){const s=new Float32Array(n),a=t-e;for(let o=0;o<n;o++){const i=o/(n-1);let l;r==="logarithmic"?a>0?l=Math.log10(1+i*9)/Math.log10(10):l=1-Math.log10(1+(1-i)*9)/Math.log10(10):l=i*i*(3-2*i),s[o]=e+a*l}return s}const ff=()=>{const e=m.useRef(null),t=m.useCallback(()=>{e.current!==null&&(cancelAnimationFrame(e.current),e.current=null)},[]),n=m.useCallback(r=>{t(),e.current=requestAnimationFrame(r)},[t]);return m.useEffect(()=>()=>{t()},[t]),{animationFrameRef:e,startAnimationFrameLoop:n,stopAnimationFrameLoop:t}},U0=`
857
+ `,10)+1,a=r.substring(s)+"",o=new Blob([a],{type:"application/javascript"});return URL.createObjectURL(o)}function y0(e,t,n){var r;return function(a){return r=r||v0(e),new Worker(r,a)}}var b0=y0("Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewogICd1c2Ugc3RyaWN0JzsKCiAgLyoqCiAgICogQXVkaW9CdWZmZXItYmFzZWQgV2F2ZWZvcm1EYXRhIGdlbmVyYXRvcgogICAqCiAgICogQWRhcHRlZCBmcm9tIEJsb2NrRmlsZTo6Q2FsY1N1bW1hcnkgaW4gQXVkYWNpdHksIHdpdGggcGVybWlzc2lvbi4KICAgKiBTZWUgaHR0cHM6Ly9naXRodWIuY29tL2F1ZGFjaXR5L2F1ZGFjaXR5L2Jsb2IvCiAgICogICAxMTA4YzEzNzZjMDkxNjYxNjIzMzVmYWI0NzQzMDA4Y2JhNTdjNGVlL3NyYy9CbG9ja0ZpbGUuY3BwI0wxOTgKICAgKi8KCiAgdmFyIElOVDhfTUFYID0gMTI3OwogIHZhciBJTlQ4X01JTiA9IC0xMjg7CiAgdmFyIElOVDE2X01BWCA9IDMyNzY3OwogIHZhciBJTlQxNl9NSU4gPSAtMzI3Njg7CiAgZnVuY3Rpb24gY2FsY3VsYXRlV2F2ZWZvcm1EYXRhTGVuZ3RoKGF1ZGlvX3NhbXBsZV9jb3VudCwgc2NhbGUpIHsKICAgIHZhciBkYXRhX2xlbmd0aCA9IE1hdGguZmxvb3IoYXVkaW9fc2FtcGxlX2NvdW50IC8gc2NhbGUpOwogICAgdmFyIHNhbXBsZXNfcmVtYWluaW5nID0gYXVkaW9fc2FtcGxlX2NvdW50IC0gZGF0YV9sZW5ndGggKiBzY2FsZTsKICAgIGlmIChzYW1wbGVzX3JlbWFpbmluZyA+IDApIHsKICAgICAgZGF0YV9sZW5ndGgrKzsKICAgIH0KICAgIHJldHVybiBkYXRhX2xlbmd0aDsKICB9CiAgZnVuY3Rpb24gZ2VuZXJhdGVXYXZlZm9ybURhdGEob3B0aW9ucykgewogICAgdmFyIHNjYWxlID0gb3B0aW9ucy5zY2FsZTsKICAgIHZhciBhbXBsaXR1ZGVfc2NhbGUgPSBvcHRpb25zLmFtcGxpdHVkZV9zY2FsZTsKICAgIHZhciBzcGxpdF9jaGFubmVscyA9IG9wdGlvbnMuc3BsaXRfY2hhbm5lbHM7CiAgICB2YXIgbGVuZ3RoID0gb3B0aW9ucy5sZW5ndGg7CiAgICB2YXIgc2FtcGxlX3JhdGUgPSBvcHRpb25zLnNhbXBsZV9yYXRlOwogICAgdmFyIGNoYW5uZWxzID0gb3B0aW9ucy5jaGFubmVscy5tYXAoZnVuY3Rpb24gKGNoYW5uZWwpIHsKICAgICAgcmV0dXJuIG5ldyBGbG9hdDMyQXJyYXkoY2hhbm5lbCk7CiAgICB9KTsKICAgIHZhciBvdXRwdXRfY2hhbm5lbHMgPSBzcGxpdF9jaGFubmVscyA/IGNoYW5uZWxzLmxlbmd0aCA6IDE7CiAgICB2YXIgaGVhZGVyX3NpemUgPSAyNDsKICAgIHZhciBkYXRhX2xlbmd0aCA9IGNhbGN1bGF0ZVdhdmVmb3JtRGF0YUxlbmd0aChsZW5ndGgsIHNjYWxlKTsKICAgIHZhciBieXRlc19wZXJfc2FtcGxlID0gb3B0aW9ucy5iaXRzID09PSA4ID8gMSA6IDI7CiAgICB2YXIgdG90YWxfc2l6ZSA9IGhlYWRlcl9zaXplICsgZGF0YV9sZW5ndGggKiAyICogYnl0ZXNfcGVyX3NhbXBsZSAqIG91dHB1dF9jaGFubmVsczsKICAgIHZhciBidWZmZXIgPSBuZXcgQXJyYXlCdWZmZXIodG90YWxfc2l6ZSk7CiAgICB2YXIgZGF0YV92aWV3ID0gbmV3IERhdGFWaWV3KGJ1ZmZlcik7CiAgICB2YXIgc2NhbGVfY291bnRlciA9IDA7CiAgICB2YXIgb2Zmc2V0ID0gaGVhZGVyX3NpemU7CiAgICB2YXIgbWluX3ZhbHVlID0gbmV3IEFycmF5KG91dHB1dF9jaGFubmVscyk7CiAgICB2YXIgbWF4X3ZhbHVlID0gbmV3IEFycmF5KG91dHB1dF9jaGFubmVscyk7CiAgICBmb3IgKHZhciBjaGFubmVsID0gMDsgY2hhbm5lbCA8IG91dHB1dF9jaGFubmVsczsgY2hhbm5lbCsrKSB7CiAgICAgIG1pbl92YWx1ZVtjaGFubmVsXSA9IEluZmluaXR5OwogICAgICBtYXhfdmFsdWVbY2hhbm5lbF0gPSAtSW5maW5pdHk7CiAgICB9CiAgICB2YXIgcmFuZ2VfbWluID0gb3B0aW9ucy5iaXRzID09PSA4ID8gSU5UOF9NSU4gOiBJTlQxNl9NSU47CiAgICB2YXIgcmFuZ2VfbWF4ID0gb3B0aW9ucy5iaXRzID09PSA4ID8gSU5UOF9NQVggOiBJTlQxNl9NQVg7CiAgICBkYXRhX3ZpZXcuc2V0SW50MzIoMCwgMiwgdHJ1ZSk7IC8vIFZlcnNpb24KICAgIGRhdGFfdmlldy5zZXRVaW50MzIoNCwgb3B0aW9ucy5iaXRzID09PSA4LCB0cnVlKTsgLy8gSXMgOCBiaXQ/CiAgICBkYXRhX3ZpZXcuc2V0SW50MzIoOCwgc2FtcGxlX3JhdGUsIHRydWUpOyAvLyBTYW1wbGUgcmF0ZQogICAgZGF0YV92aWV3LnNldEludDMyKDEyLCBzY2FsZSwgdHJ1ZSk7IC8vIFNjYWxlCiAgICBkYXRhX3ZpZXcuc2V0SW50MzIoMTYsIGRhdGFfbGVuZ3RoLCB0cnVlKTsgLy8gTGVuZ3RoCiAgICBkYXRhX3ZpZXcuc2V0SW50MzIoMjAsIG91dHB1dF9jaGFubmVscywgdHJ1ZSk7CiAgICBmb3IgKHZhciBpID0gMDsgaSA8IGxlbmd0aDsgaSsrKSB7CiAgICAgIHZhciBzYW1wbGUgPSAwOwogICAgICBpZiAob3V0cHV0X2NoYW5uZWxzID09PSAxKSB7CiAgICAgICAgZm9yICh2YXIgX2NoYW5uZWwgPSAwOyBfY2hhbm5lbCA8IGNoYW5uZWxzLmxlbmd0aDsgKytfY2hhbm5lbCkgewogICAgICAgICAgc2FtcGxlICs9IGNoYW5uZWxzW19jaGFubmVsXVtpXTsKICAgICAgICB9CiAgICAgICAgc2FtcGxlID0gTWF0aC5mbG9vcihyYW5nZV9tYXggKiBzYW1wbGUgKiBhbXBsaXR1ZGVfc2NhbGUgLyBjaGFubmVscy5sZW5ndGgpOwogICAgICAgIGlmIChzYW1wbGUgPCBtaW5fdmFsdWVbMF0pIHsKICAgICAgICAgIG1pbl92YWx1ZVswXSA9IHNhbXBsZTsKICAgICAgICAgIGlmIChtaW5fdmFsdWVbMF0gPCByYW5nZV9taW4pIHsKICAgICAgICAgICAgbWluX3ZhbHVlWzBdID0gcmFuZ2VfbWluOwogICAgICAgICAgfQogICAgICAgIH0KICAgICAgICBpZiAoc2FtcGxlID4gbWF4X3ZhbHVlWzBdKSB7CiAgICAgICAgICBtYXhfdmFsdWVbMF0gPSBzYW1wbGU7CiAgICAgICAgICBpZiAobWF4X3ZhbHVlWzBdID4gcmFuZ2VfbWF4KSB7CiAgICAgICAgICAgIG1heF92YWx1ZVswXSA9IHJhbmdlX21heDsKICAgICAgICAgIH0KICAgICAgICB9CiAgICAgIH0gZWxzZSB7CiAgICAgICAgZm9yICh2YXIgX2NoYW5uZWwyID0gMDsgX2NoYW5uZWwyIDwgb3V0cHV0X2NoYW5uZWxzOyArK19jaGFubmVsMikgewogICAgICAgICAgc2FtcGxlID0gTWF0aC5mbG9vcihyYW5nZV9tYXggKiBjaGFubmVsc1tfY2hhbm5lbDJdW2ldICogYW1wbGl0dWRlX3NjYWxlKTsKICAgICAgICAgIGlmIChzYW1wbGUgPCBtaW5fdmFsdWVbX2NoYW5uZWwyXSkgewogICAgICAgICAgICBtaW5fdmFsdWVbX2NoYW5uZWwyXSA9IHNhbXBsZTsKICAgICAgICAgICAgaWYgKG1pbl92YWx1ZVtfY2hhbm5lbDJdIDwgcmFuZ2VfbWluKSB7CiAgICAgICAgICAgICAgbWluX3ZhbHVlW19jaGFubmVsMl0gPSByYW5nZV9taW47CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICAgIGlmIChzYW1wbGUgPiBtYXhfdmFsdWVbX2NoYW5uZWwyXSkgewogICAgICAgICAgICBtYXhfdmFsdWVbX2NoYW5uZWwyXSA9IHNhbXBsZTsKICAgICAgICAgICAgaWYgKG1heF92YWx1ZVtfY2hhbm5lbDJdID4gcmFuZ2VfbWF4KSB7CiAgICAgICAgICAgICAgbWF4X3ZhbHVlW19jaGFubmVsMl0gPSByYW5nZV9tYXg7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICB9CiAgICAgIH0KICAgICAgaWYgKCsrc2NhbGVfY291bnRlciA9PT0gc2NhbGUpIHsKICAgICAgICBmb3IgKHZhciBfY2hhbm5lbDMgPSAwOyBfY2hhbm5lbDMgPCBvdXRwdXRfY2hhbm5lbHM7IF9jaGFubmVsMysrKSB7CiAgICAgICAgICBpZiAob3B0aW9ucy5iaXRzID09PSA4KSB7CiAgICAgICAgICAgIGRhdGFfdmlldy5zZXRJbnQ4KG9mZnNldCsrLCBtaW5fdmFsdWVbX2NoYW5uZWwzXSk7CiAgICAgICAgICAgIGRhdGFfdmlldy5zZXRJbnQ4KG9mZnNldCsrLCBtYXhfdmFsdWVbX2NoYW5uZWwzXSk7CiAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICBkYXRhX3ZpZXcuc2V0SW50MTYob2Zmc2V0LCBtaW5fdmFsdWVbX2NoYW5uZWwzXSwgdHJ1ZSk7CiAgICAgICAgICAgIGRhdGFfdmlldy5zZXRJbnQxNihvZmZzZXQgKyAyLCBtYXhfdmFsdWVbX2NoYW5uZWwzXSwgdHJ1ZSk7CiAgICAgICAgICAgIG9mZnNldCArPSA0OwogICAgICAgICAgfQogICAgICAgICAgbWluX3ZhbHVlW19jaGFubmVsM10gPSBJbmZpbml0eTsKICAgICAgICAgIG1heF92YWx1ZVtfY2hhbm5lbDNdID0gLUluZmluaXR5OwogICAgICAgIH0KICAgICAgICBzY2FsZV9jb3VudGVyID0gMDsKICAgICAgfQogICAgfQogICAgaWYgKHNjYWxlX2NvdW50ZXIgPiAwKSB7CiAgICAgIGZvciAodmFyIF9jaGFubmVsNCA9IDA7IF9jaGFubmVsNCA8IG91dHB1dF9jaGFubmVsczsgX2NoYW5uZWw0KyspIHsKICAgICAgICBpZiAob3B0aW9ucy5iaXRzID09PSA4KSB7CiAgICAgICAgICBkYXRhX3ZpZXcuc2V0SW50OChvZmZzZXQrKywgbWluX3ZhbHVlW19jaGFubmVsNF0pOwogICAgICAgICAgZGF0YV92aWV3LnNldEludDgob2Zmc2V0KyssIG1heF92YWx1ZVtfY2hhbm5lbDRdKTsKICAgICAgICB9IGVsc2UgewogICAgICAgICAgZGF0YV92aWV3LnNldEludDE2KG9mZnNldCwgbWluX3ZhbHVlW19jaGFubmVsNF0sIHRydWUpOwogICAgICAgICAgZGF0YV92aWV3LnNldEludDE2KG9mZnNldCArIDIsIG1heF92YWx1ZVtfY2hhbm5lbDRdLCB0cnVlKTsKICAgICAgICB9CiAgICAgIH0KICAgIH0KICAgIHJldHVybiBidWZmZXI7CiAgfQoKICBvbm1lc3NhZ2UgPSBmdW5jdGlvbiBvbm1lc3NhZ2UoZXZ0KSB7CiAgICB2YXIgYnVmZmVyID0gZ2VuZXJhdGVXYXZlZm9ybURhdGEoZXZ0LmRhdGEpOwoKICAgIC8vIFRyYW5zZmVyIGJ1ZmZlciB0byB0aGUgY2FsbGluZyB0aHJlYWQKICAgIHRoaXMucG9zdE1lc3NhZ2UoYnVmZmVyLCBbYnVmZmVyXSk7CiAgICB0aGlzLmNsb3NlKCk7CiAgfTsKCn0pKCk7Ci8vIyBzb3VyY2VNYXBwaW5nVVJMPXdhdmVmb3JtLWRhdGEtd29ya2VyLmpzLm1hcAoK");function pt(e){if(h0(e)&&(e=m0(e)),p0(e)){this._data=new DataView(e),this._offset=this._version()===2?24:20,this._channels=[];for(var t=0;t<this.channels;t++)this._channels[t]=new yn(this,t)}else throw new TypeError("WaveformData.create(): Unknown data format")}var qn={scale:512,bits:8,amplitude_scale:1,split_channels:!1,disable_worker:!1};function w0(e){var t={scale:e.scale||qn.scale,bits:e.bits||qn.bits,amplitude_scale:e.amplitude_scale||qn.amplitude_scale,split_channels:e.split_channels||qn.split_channels,disable_worker:e.disable_worker||qn.disable_worker};return t}function _0(e){for(var t=[],n=0;n<e.numberOfChannels;++n)t.push(e.getChannelData(n).buffer);return t}function Jd(e,t,n){var r=_0(e);if(t.disable_worker){var s=f0({scale:t.scale,bits:t.bits,amplitude_scale:t.amplitude_scale,split_channels:t.split_channels,length:e.length,sample_rate:e.sampleRate,channels:r});n(void 0,new pt(s),e)}else{var a=new b0;a.onmessage=function(o){n(void 0,new pt(o.data),e)},a.postMessage({scale:t.scale,bits:t.bits,amplitude_scale:t.amplitude_scale,split_channels:t.split_channels,length:e.length,sample_rate:e.sampleRate,channels:r},r)}}function x0(e,t,n,r){function s(o){o||(o=new DOMException("EncodingError")),r(o),r=function(){}}var a=e.decodeAudioData(t,function(o){Jd(o,n,r)},s);a&&a.catch(s)}pt.create=function(t){return new pt(t)};pt.createFromAudio=function(e,t){var n=w0(e);if(e.audio_context&&e.array_buffer)return x0(e.audio_context,e.array_buffer,n,t);if(e.audio_buffer)return Jd(e.audio_buffer,n,t);throw new TypeError("WaveformData.createFromAudio(): Pass either an AudioContext and ArrayBuffer, or an AudioBuffer object")};function Ks(e){this._inputData=e.waveformData,this._output_samples_per_pixel=e.scale,this._scale=this._inputData.scale,this._input_buffer_size=this._inputData.length;var t=this._input_buffer_size*this._inputData.scale,n=Math.ceil(t/this._output_samples_per_pixel),r=24,s=this._inputData.bits===8?1:2,a=r+n*2*this._inputData.channels*s;this._output_data=new ArrayBuffer(a),this.output_dataview=new DataView(this._output_data),this.output_dataview.setInt32(0,2,!0),this.output_dataview.setUint32(4,this._inputData.bits===8,!0),this.output_dataview.setInt32(8,this._inputData.sample_rate,!0),this.output_dataview.setInt32(12,this._output_samples_per_pixel,!0),this.output_dataview.setInt32(16,n,!0),this.output_dataview.setInt32(20,this._inputData.channels,!0),this._outputWaveformData=new pt(this._output_data),this._input_index=0,this._output_index=0;var o=this._inputData.channels;this._min=new Array(o),this._max=new Array(o);for(var i=0;i<o;++i)this._input_buffer_size>0?(this._min[i]=this._inputData.channel(i).min_sample(this._input_index),this._max[i]=this._inputData.channel(i).max_sample(this._input_index)):(this._min[i]=0,this._max[i]=0);this._min_value=this._inputData.bits===8?-128:-32768,this._max_value=this._inputData.bits===8?127:32767,this._where=0,this._prev_where=0,this._stop=0,this._last_input_index=0}Ks.prototype.sample_at_pixel=function(e){return Math.floor(e*this._output_samples_per_pixel)};Ks.prototype.next=function(){for(var e=0,t=1e3,n=this._inputData.channels,r;this._input_index<this._input_buffer_size&&e<t;){for(;Math.floor(this.sample_at_pixel(this._output_index)/this._scale)===this._input_index;){if(this._output_index>0)for(var s=0;s<n;++s)r=this._outputWaveformData.channel(s),r.set_min_sample(this._output_index-1,this._min[s]),r.set_max_sample(this._output_index-1,this._max[s]);if(this._last_input_index=this._input_index,this._output_index++,this._where=this.sample_at_pixel(this._output_index),this._prev_where=this.sample_at_pixel(this._output_index-1),this._where!==this._prev_where)for(var a=0;a<n;++a)this._min[a]=this._max_value,this._max[a]=this._min_value}for(this._where=this.sample_at_pixel(this._output_index),this._stop=Math.floor(this._where/this._scale),this._stop>this._input_buffer_size&&(this._stop=this._input_buffer_size);this._input_index<this._stop;){for(var o=0;o<n;++o){r=this._inputData.channel(o);var i=r.min_sample(this._input_index);i<this._min[o]&&(this._min[o]=i),i=r.max_sample(this._input_index),i>this._max[o]&&(this._max[o]=i)}this._input_index++}e++}if(this._input_index<this._input_buffer_size)return!1;if(this._input_index!==this._last_input_index)for(var l=0;l<n;++l)r=this._outputWaveformData.channel(l),r.set_min_sample(this._output_index-1,this._min[l]),r.set_max_sample(this._output_index-1,this._max[l]);return!0};Ks.prototype.getOutputData=function(){return this._output_data};pt.prototype={_getResampleOptions:function(t){var n={};if(n.scale=t.scale,n.width=t.width,!Cn(n.width)&&(typeof n.width!="number"||n.width<=0))throw new RangeError("WaveformData.resample(): width should be a positive integer value");if(!Cn(n.scale)&&(typeof n.scale!="number"||n.scale<=0))throw new RangeError("WaveformData.resample(): scale should be a positive integer value");if(!n.scale&&!n.width)throw new Error("WaveformData.resample(): Missing scale or width option");if(n.width&&(n.scale=Math.floor(this.duration*this.sample_rate/n.width)),n.scale<this.scale)throw new Error("WaveformData.resample(): Zoom level "+n.scale+" too low, minimum: "+this.scale);return n.abortSignal=t.abortSignal,n},resample:function(t){t=this._getResampleOptions(t),t.waveformData=this;for(var n=new Ks(t);!n.next(););return new pt(n.getOutputData())},concat:function(){var t=this,n=Array.prototype.slice.call(arguments);n.forEach(function(s){if(t.channels!==s.channels||t.sample_rate!==s.sample_rate||t.bits!==s.bits||t.scale!==s.scale)throw new Error("WaveformData.concat(): Waveforms are incompatible")});var r=this._concatBuffers.apply(this,n);return pt.create(r)},_concatBuffers:function(){for(var t=Array.prototype.slice.call(arguments),n=this._offset,r=n,s=0,a=[this].concat(t).map(function(y){return y._data.buffer}),o=0;o<a.length;o++){var i=a[o],l=new DataView(i).getInt32(16,!0);r+=i.byteLength-n,s+=l}for(var c=new ArrayBuffer(r),u=new DataView(a[0]),f=new DataView(c),p=0;p<n;p++)f.setUint8(p,u.getUint8(p));f.setInt32(16,s,!0);for(var d=0,h=new Uint8Array(c,n),v=0;v<a.length;v++){var g=a[v];h.set(new Uint8Array(g,n),d),d+=g.byteLength-n}return c},slice:function(t){var n=0,r=0;if(!Cn(t.startIndex)&&!Cn(t.endIndex)?(n=t.startIndex,r=t.endIndex):!Cn(t.startTime)&&!Cn(t.endTime)&&(n=this.at_time(t.startTime),r=this.at_time(t.endTime)),n<0)throw new RangeError("startIndex or startTime must not be negative");if(r<0)throw new RangeError("endIndex or endTime must not be negative");n>this.length&&(n=this.length),r>this.length&&(r=this.length),n>r&&(n=r);var s=r-n,a=24,o=this.bits===8?1:2,i=a+s*2*this.channels*o,l=new ArrayBuffer(i),c=new DataView(l);c.setInt32(0,2,!0),c.setUint32(4,this.bits===8,!0),c.setInt32(8,this.sample_rate,!0),c.setInt32(12,this.scale,!0),c.setInt32(16,s,!0),c.setInt32(20,this.channels,!0);for(var u=0;u<s*this.channels*2;u++){var f=this._at(n*this.channels*2+u);this.bits===8?c.setInt8(a+u,f):c.setInt16(a+u*2,f,!0)}return new pt(l)},_version:function(){return this._data.getInt32(0,!0)},get length(){return this._data.getUint32(16,!0)},get bits(){var e=!!this._data.getUint32(4,!0);return e?8:16},get duration(){return this.length*this.scale/this.sample_rate},get pixels_per_second(){return this.sample_rate/this.scale},get seconds_per_pixel(){return this.scale/this.sample_rate},get channels(){return this._version()===2?this._data.getInt32(20,!0):1},channel:function(t){if(t>=0&&t<this._channels.length)return this._channels[t];throw new RangeError("Invalid channel: "+t)},get sample_rate(){return this._data.getInt32(8,!0)},get scale(){return this._data.getInt32(12,!0)},_at:function(t){return this.bits===8?this._data.getInt8(this._offset+t):this._data.getInt16(this._offset+t*2,!0)},_set_at:function(t,n){return this.bits===8?this._data.setInt8(this._offset+t,n):this._data.setInt16(this._offset+t*2,n,!0)},at_time:function(t){return Math.floor(t*this.sample_rate/this.scale)},time:function(t){return t*this.scale/this.sample_rate},toJSON:function(){for(var t={version:2,channels:this.channels,sample_rate:this.sample_rate,samples_per_pixel:this.scale,bits:this.bits,length:this.length,data:[]},n=0;n<this.length;n++)for(var r=0;r<this.channels;r++)t.data.push(this.channel(r).min_sample(n)),t.data.push(this.channel(r).max_sample(n));return t},toArrayBuffer:function(){return this._data.buffer}};async function xi(e){const t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch waveform data: ${t.statusText}`);if(e.endsWith(".dat")){const r=await t.arrayBuffer();return pt.create(r)}else{const r=await t.json();return pt.create(r)}}function Qd(e,t=0){const n=e.channel(t),r=e.bits,s=n.min_array(),a=n.max_array(),o=s.length,i=r===8?new Int8Array(o*2):new Int16Array(o*2);for(let l=0;l<o;l++)i[l*2]=s[l],i[l*2+1]=a[l];return{data:i,bits:r,length:o,sampleRate:e.sample_rate}}async function C0(e,t=0){const n=await xi(e);return Qd(n,t)}async function S0(e){const t=await xi(e);return{sampleRate:t.sample_rate,channels:t.channels,duration:t.duration,samplesPerPixel:t.scale,length:t.length,bits:t.bits}}function ef(e,t,n,r){let s=e;if(n!==void 0&&r!==void 0)if(s.scale!==t){const a=e.scale,o=t/a,i=Math.floor(n/t),l=Math.ceil((n+r)/t),c=Math.floor(i*o),u=Math.min(e.length,Math.ceil(l*o));if(c>=u)return null;s=s.slice({startIndex:c,endIndex:u}),s=s.resample({scale:t})}else{const a=Math.floor(n/t),o=Math.ceil((n+r)/t);s=s.slice({startIndex:a,endIndex:o})}else s.scale!==t&&(s=s.resample({scale:t}));return s}function k0(e,t,n=0,r,s){const a=ef(e,t,r,s);if(a===null){const p=e.bits;return{data:p===8?new Int8Array(0):new Int16Array(0),bits:p,length:0}}const o=a.channel(n),i=a.bits,l=o.min_array(),c=o.max_array(),u=l.length,f=i===8?new Int8Array(u*2):new Int16Array(u*2);for(let p=0;p<u;p++)f[p*2]=l[p],f[p*2+1]=c[p];return{data:f,bits:i,length:u}}function Ql(e,t,n,r,s){const a=ef(e,t,r,s);if(a===null){const u=e.bits;return{length:0,data:[],bits:u}}const o=a.channels,i=a.bits,l=[];for(let u=0;u<o;u++){const f=a.channel(u),p=f.min_array(),d=f.max_array(),h=p.length,v=i===8?new Int8Array(h*2):new Int16Array(h*2);for(let g=0;g<h;g++)v[g*2]=p[g],v[g*2+1]=d[g];l.push(v)}if(n&&l.length>1){const u=1/l.length,f=l[0].length/2,p=i===8?new Int8Array(f*2):new Int16Array(f*2);for(let d=0;d<f;d++){let h=0,v=0;for(let g=0;g<l.length;g++)h+=u*l[g][d*2],v+=u*l[g][d*2+1];p[d*2]=h,p[d*2+1]=v}return{length:f,data:[p],bits:i}}return{length:l.length>0?l[0].length/2:0,data:l,bits:i}}function tf(){const[e,t]=m.useState("hh:mm:ss.uuu");return{timeFormat:e,setTimeFormat:t,formatTime:s=>Dn(s,e),parseTime:s=>Hd(s,e)}}function nf({engineRef:e,initialSamplesPerPixel:t}){const[n,r]=m.useState(t),[s,a]=m.useState(!0),[o,i]=m.useState(!0),l=m.useRef(!0),c=m.useRef(!0),u=m.useRef(t),f=m.useCallback(()=>{e.current?.zoomIn()},[e]),p=m.useCallback(()=>{e.current?.zoomOut()},[e]),d=m.useCallback(h=>{h.samplesPerPixel!==u.current&&(u.current=h.samplesPerPixel,m.startTransition(()=>{r(h.samplesPerPixel)})),h.canZoomIn!==l.current&&(l.current=h.canZoomIn,a(h.canZoomIn)),h.canZoomOut!==c.current&&(c.current=h.canZoomOut,i(h.canZoomOut))},[]);return{samplesPerPixel:n,zoomIn:f,zoomOut:p,canZoomIn:s,canZoomOut:o,onEngineState:d}}function rf({engineRef:e,initialVolume:t=1}){const[n,r]=m.useState(t),s=m.useRef(t),a=m.useCallback(i=>{e.current?e.current.setMasterVolume(i):(s.current=i,r(i))},[e]),o=m.useCallback(i=>{i.masterVolume!==s.current&&(s.current=i.masterVolume,r(i.masterVolume))},[]);return{masterVolume:n,setMasterVolume:a,masterVolumeRef:s,onEngineState:o}}function E0({engineRef:e}){const[t,n]=m.useState(0),[r,s]=m.useState(0),a=m.useRef(0),o=m.useRef(0),i=m.useCallback((c,u)=>{e.current?.setSelection(c,u)},[e]),l=m.useCallback(c=>{c.selectionStart!==a.current&&(a.current=c.selectionStart,n(c.selectionStart)),c.selectionEnd!==o.current&&(o.current=c.selectionEnd,s(c.selectionEnd))},[]);return{selectionStart:t,selectionEnd:r,setSelection:i,selectionStartRef:a,selectionEndRef:o,onEngineState:l}}function I0({engineRef:e}){const[t,n]=m.useState(!1),[r,s]=m.useState(0),[a,o]=m.useState(0),i=m.useRef(!1),l=m.useRef(0),c=m.useRef(0),u=m.useCallback(h=>{e.current?.setLoopEnabled(h)},[e]),f=m.useCallback((h,v)=>{e.current?.setLoopRegion(h,v)},[e]),p=m.useCallback(()=>{e.current?.setLoopRegion(0,0)},[e]),d=m.useCallback(h=>{h.isLoopEnabled!==i.current&&(i.current=h.isLoopEnabled,n(h.isLoopEnabled)),h.loopStart!==l.current&&(l.current=h.loopStart,s(h.loopStart)),h.loopEnd!==c.current&&(c.current=h.loopEnd,o(h.loopEnd))},[]);return{isLoopEnabled:t,loopStart:r,loopEnd:a,setLoopEnabled:u,setLoopRegion:f,clearLoopRegion:p,isLoopEnabledRef:i,loopStartRef:l,loopEndRef:c,onEngineState:d}}function M0({engineRef:e}){const[t,n]=m.useState(null),r=m.useRef(null),s=m.useCallback(o=>{e.current?.selectTrack(o)},[e]),a=m.useCallback(o=>{o.selectedTrackId!==r.current&&(r.current=o.selectedTrackId,n(o.selectedTrackId))},[]);return{selectedTrackId:t,setSelectedTrackId:s,onEngineState:a,selectedTrackIdRef:r}}const A0=(e=256)=>{const t=m.useRef(null),n=m.useCallback((r,s,a)=>{const o=new L.Analyser("fft",e);return r.connect(o),r.connect(s),t.current=o,function(){o.dispose(),t.current=null}},[e]);return{analyserRef:t,masterEffects:n}};function ns(e,t,n,r,s=48e3){const a=n??e.audioBuffer,o=a?.sampleRate??e.waveformData?.sample_rate??s,i=a?.duration??e.waveformData?.duration??(e.duration!=null?e.duration+(e.offset??0):void 0);if(i===void 0)return console.warn(`[waveform-playlist] Track ${t+1} ("${e.name??"unnamed"}"): Cannot create track — provide duration, audioBuffer, or waveformData with duration.`),null;const l=uc({audioBuffer:a,sampleRate:o,sourceDuration:i,startTime:e.startTime??0,duration:e.duration??i,offset:e.offset??0,name:e.name||`Track ${t+1}`,fadeIn:e.fadeIn,fadeOut:e.fadeOut,waveformData:e.waveformData});if(isNaN(l.startSample)||isNaN(l.durationSamples)||isNaN(l.offsetSamples))return console.error(`[waveform-playlist] Invalid clip values for track ${t+1} ("${e.name??"unnamed"}"): startSample=${l.startSample}, durationSamples=${l.durationSamples}, offsetSamples=${l.offsetSamples}`),null;const c={...dc({name:e.name||`Track ${t+1}`,clips:[l],muted:e.muted??!1,soloed:e.soloed??!1,volume:e.volume??1,pan:e.pan??0,color:e.color}),effects:e.effects,renderMode:e.renderMode,spectrogramConfig:e.spectrogramConfig,spectrogramColorMap:e.spectrogramColorMap},u=r.get(t);return u?(c.id=u.trackId,c.clips[0]={...c.clips[0],id:u.clipId}):r.set(t,{trackId:c.id,clipId:c.clips[0].id}),c}function T0(e,t={}){const{immediate:n=!1,progressive:r=!1}=t,s=n||r,[a,o]=m.useState(!0),[i,l]=m.useState(null),[c,u]=m.useState(0),f=e.length,[p,d]=m.useState(new Map),h=m.useRef(new Map),v=m.useRef(48e3),g=m.useMemo(()=>{if(!s)return null;const _=[];for(let x=0;x<e.length;x++){const S=ns(e[x],x,p.get(x),h.current,v.current);S&&_.push(S)}return _},[s,e,p]),[y,b]=m.useState(g??[]),w=m.useRef(g);return g!==w.current&&(w.current=g,g&&b(g)),m.useEffect(()=>{if(e.length===0){b([]),o(!1),u(0);return}let _=!1;const x=new AbortController;return(async()=>{try{o(!0),l(null),u(0),s&&d(new Map);const k=cc.getContext().rawContext;v.current=k.sampleRate;const E=e.map(async(M,T)=>{if(M.audioBuffer){if(s&&!_){d(F=>{const O=new Map(F);return O.set(T,M.audioBuffer),O}),u(F=>F+1);return}return ns(M,T,M.audioBuffer,h.current,k.sampleRate)}if(!M.src&&M.waveformData){if(s&&!_){u(F=>F+1);return}return ns(M,T,void 0,h.current,k.sampleRate)}if(!M.src)throw new Error(`Track ${T+1}: Must provide src, audioBuffer, or waveformData`);const A=await fetch(M.src,{signal:x.signal});if(!A.ok)throw new Error(`Failed to fetch ${M.src}: ${A.statusText}`);const $=await A.arrayBuffer(),R=await k.decodeAudioData($);if(!R||!R.sampleRate||!R.duration)throw new Error(`Invalid audio buffer for ${M.src}`);if(s&&!_){d(F=>{const O=new Map(F);return O.set(T,R),O}),u(F=>F+1);return}return ns(M,T,R,h.current,k.sampleRate)}),I=await Promise.all(E);if(!_){if(!s){const M=I.filter(T=>T!=null);b(M),u(M.length)}o(!1)}}catch(k){if(!_){const E=k instanceof Error?k.message:"Unknown error loading audio";l(E),o(!1),console.error(`[waveform-playlist] Error loading audio tracks: ${E}`)}}})(),()=>{_=!0,x.abort()}},[e,s]),{tracks:y,loading:a,error:i,loadedCount:c,totalCount:f}}function $0({originalClip:e,clip:t,pixelDelta:n,samplesPerPixel:r,sampleRate:s,boundary:a,sortedClips:o,sortedIndex:i}){const l=n*r,c=Math.floor(.1*s),u={...t,startSample:e.startSample,offsetSamples:e.offsetSamples,durationSamples:e.durationSamples},f=vc(u,Math.floor(l),a,o,i,c);return a==="left"?{startSample:e.startSample+f,durationSamples:e.durationSamples-f,offsetSamples:e.offsetSamples+f}:{startSample:e.startSample,durationSamples:e.durationSamples+f,offsetSamples:e.offsetSamples}}function sf({tracks:e,onTracksChange:t,samplesPerPixel:n,sampleRate:r,engineRef:s,isDraggingRef:a,snapSamplePosition:o}){const i=m.useRef(o);i.current=o;const l=m.useRef(null),c=m.useRef(0),u=m.useCallback(d=>{const h=d.operation.source?.data;if(!h)return;if(!h.boundary){l.current=null;return}const g=e[h.trackIndex]?.clips[h.clipIndex];g&&(l.current={offsetSamples:g.offsetSamples,durationSamples:g.durationSamples,startSample:g.startSample},a.current=!0)},[e,a]),f=m.useCallback(d=>{const h=d.operation.source?.data;if(!h||!h.boundary||!l.current)return;const{boundary:v,trackIndex:g,clipIndex:y}=h,w=(d.to?.x??d.operation.position.current.x)-d.operation.position.initial.x,_=w*n,x=l.current,S=i.current;let k=_;const E=e.map((I,M)=>{if(M!==g)return I;const T=[...I.clips].sort((R,F)=>R.startSample-F.startSample),A=T.findIndex(R=>R===I.clips[y]),$=I.clips.map((R,F)=>{if(F!==y)return R;let O=$0({originalClip:x,clip:R,pixelDelta:w,samplesPerPixel:n,sampleRate:r,boundary:v,sortedClips:T,sortedIndex:A});if(S)if(v==="left"){const G=S(O.startSample),Q=G-O.startSample;O={startSample:G,durationSamples:O.durationSamples-Q,offsetSamples:O.offsetSamples+Q},k=G-x.startSample}else{const G=O.startSample+O.durationSamples,Q=S(G);O={...O,durationSamples:Q-O.startSample},k=O.durationSamples-x.durationSamples}return{...R,startSample:O.startSample,durationSamples:O.durationSamples,offsetSamples:O.offsetSamples}});return{...I,clips:$}});c.current=k,t(E)},[e,t,n,r]),p=m.useCallback(d=>{if(d.canceled){if(l.current){const _=d.operation.source?.data;if(_){const{trackIndex:x,clipIndex:S}=_,k=l.current,E=e.map((I,M)=>{if(M!==x)return I;const T=I.clips.map((A,$)=>$!==S?A:{...A,offsetSamples:k.offsetSamples,durationSamples:k.durationSamples,startSample:k.startSample});return{...I,clips:T}});t(E)}}a.current=!1,l.current=null,c.current=0;return}const h=d.operation.source?.data;if(!h)return;const{trackIndex:v,clipId:g,boundary:y}=h,b=y?c.current:d.operation.transform.x*n,w=e[v]?.id;if(y){a.current=!1,w?s.current?s.current.trimClip(w,g,y,Math.floor(b)):console.warn("[waveform-playlist] engineRef is null — trim not synced to adapter"):console.warn(`[waveform-playlist] onDragEnd: track at index ${v} not found — trim not synced to adapter`),l.current=null,c.current=0;return}w?s.current?s.current.moveClip(w,g,Math.floor(b)):console.warn("[waveform-playlist] engineRef is null — move not synced to adapter"):console.warn(`[waveform-playlist] onDragEnd: track at index ${v} not found — move not synced to adapter`)},[e,t,n,s,a]);return{onDragStart:u,onDragMove:f,onDragEnd:p}}const ba=.01;function af({annotations:e,onAnnotationsChange:t,samplesPerPixel:n,sampleRate:r,duration:s,linkEndpoints:a}){const o=m.useRef(null),i=m.useCallback(u=>{const f=u.operation.source?.data;if(!f||f.annotationIndex===void 0){o.current=null;return}const p=e[f.annotationIndex];p&&(o.current={start:p.start,end:p.end,annotationIndex:f.annotationIndex})},[e]),l=m.useCallback(u=>{if(!o.current)return;const f=u.operation.source?.data;if(!f)return;const{edge:p,annotationIndex:d}=f,h=o.current,y=((u.to?.x??u.operation.position.current.x)-u.operation.position.initial.x)*n/r,b=p==="start"?h.start+y:h.end+y,w=R0({annotationIndex:d,newTime:b,isDraggingStart:p==="start",annotations:e,duration:s,linkEndpoints:a});t(w)},[e,t,n,r,s,a]),c=m.useCallback(u=>{if(u.canceled&&o.current){const{annotationIndex:f,start:p,end:d}=o.current,h=e.map((v,g)=>g!==f?v:{...v,start:p,end:d});t(h)}o.current=null},[e,t]);return{onDragStart:i,onDragMove:l,onDragEnd:c}}function R0({annotationIndex:e,newTime:t,isDraggingStart:n,annotations:r,duration:s,linkEndpoints:a}){const o=[...r],i=r[e];if(n){const l=Math.min(i.end-.1,Math.max(0,t)),c=l-i.start;if(o[e]={...i,start:l},a&&e>0){const u=o[e-1];Math.abs(u.end-i.start)<ba?o[e-1]={...u,end:Math.max(u.start+.1,u.end+c)}:l<=u.end&&(o[e]={...o[e],start:u.end})}else!a&&e>0&&l<o[e-1].end&&(o[e-1]={...o[e-1],end:l})}else{const l=Math.max(i.start+.1,Math.min(t,s)),c=l-i.end;if(o[e]={...i,end:l},a&&e<o.length-1){const u=o[e+1];if(Math.abs(u.start-i.end)<ba){const f=u.start+c;o[e+1]={...u,start:Math.min(u.end-.1,f)};let p=e+1;for(;p<o.length-1;){const d=o[p],h=o[p+1];if(Math.abs(h.start-d.end)<ba){const v=d.end-r[p].end;o[p+1]={...h,start:Math.min(h.end-.1,h.start+v)},p++}else break}}else l>=u.start&&(o[e]={...o[e],end:u.start})}else if(!a&&e<o.length-1&&l>o[e+1].start){const u=o[e+1];o[e+1]={...u,start:l};let f=e+1;for(;f<o.length-1;){const p=o[f],d=o[f+1];if(p.end>d.start)o[f+1]={...d,start:p.end},f++;else break}}}return o}function of(e={}){const{touchOptimized:t=!1,touchDelay:n=250,touchTolerance:r=5,mouseDistance:s=1}=e;return m.useMemo(()=>t?[ro.configure({activationConstraints(a){return a.pointerType==="touch"?[new Ft.Delay({value:n,tolerance:r})]:[new Ft.Distance({value:s})]}})]:[ro.configure({activationConstraints:[new Ft.Distance({value:s})]})],[t,n,r,s])}const lf=e=>{const{tracks:t,sampleRate:n,engineRef:r}=e,{currentTimeRef:s}=tt(),{selectedTrackId:a}=nt(),o=m.useCallback((l,c,u)=>{const{samplesPerPixel:f}=e,p=t[l];if(!p)return!1;const d=p.clips[c];if(!d)return!1;const h=Math.round(u*n),v=yh(h,f),g=Math.floor(.1*n);if(!yc(d,v,g))return console.warn("Split point is invalid (outside bounds or too close to edge)"),!1;const y=r.current;return y?(y.splitClip(p.id,d.id,v),!0):(console.warn("[waveform-playlist] engineRef is null — split not synced to adapter"),!1)},[t,e,n,r]);return{splitClipAtPlayhead:m.useCallback(()=>{if(!a)return console.warn("[waveform-playlist] No track selected — click a clip to select a track first"),!1;const l=t.findIndex(f=>f.id===a);if(l===-1)return console.warn("Selected track not found"),!1;const c=t[l],u=s.current??0;for(let f=0;f<c.clips.length;f++){const p=c.clips[f],d=p.startSample/n,h=(p.startSample+p.durationSamples)/n;if(u>d&&u<h)return o(l,f,u)}return console.warn(`[waveform-playlist] No clip found at playhead position on track "${c.name}"`),!1},[t,s,a,o,n]),splitClipAt:o}};function D0(e,t,n){if(!n||e.repeat)return;const r=e.target;if(r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.isContentEditable)return;const s=t.find(a=>{const o=e.key.toLowerCase()===a.key.toLowerCase()||e.key===a.key,i=a.ctrlKey===void 0||e.ctrlKey===a.ctrlKey,l=a.shiftKey===void 0||e.shiftKey===a.shiftKey,c=a.metaKey===void 0||e.metaKey===a.metaKey,u=a.altKey===void 0||e.altKey===a.altKey;return o&&i&&l&&c&&u});s&&(s.preventDefault!==!1&&e.preventDefault(),s.action())}const Ps=e=>{const{shortcuts:t,enabled:n=!0}=e,r=m.useCallback(s=>D0(s,t,n),[t,n]);m.useEffect(()=>{if(n)return window.addEventListener("keydown",r),()=>{window.removeEventListener("keydown",r)}},[r,n])},P0=e=>{const t=[],n=typeof navigator<"u"&&navigator.platform.includes("Mac");return e.metaKey&&t.push(n?"Cmd":"Ctrl"),e.ctrlKey&&!e.metaKey&&t.push("Ctrl"),e.altKey&&t.push(n?"Option":"Alt"),e.shiftKey&&t.push("Shift"),t.push(e.key.toUpperCase()),t.join("+")},cf=(e={})=>{const{enabled:t=!0,additionalShortcuts:n=[],shortcuts:r}=e,{isPlaying:s}=tt(),{setCurrentTime:a,play:o,pause:i,stop:l}=Se(),c=m.useCallback(()=>{s?i():o()},[s,o,i]),u=m.useCallback(()=>{l()},[l]),f=m.useCallback(()=>{a(0),s&&o(0)},[s,a,o]),d=r??[...[{key:" ",action:c,description:"Play/Pause",preventDefault:!0},{key:"Escape",action:u,description:"Stop",preventDefault:!0},{key:"0",action:f,description:"Rewind to start",preventDefault:!0}],...n];return Ps({shortcuts:d,enabled:t}),{rewindToStart:f,togglePlayPause:c,stopPlayback:u,shortcuts:d}},wa=.01,rs=.01;function uf({annotations:e,activeAnnotationId:t,onAnnotationsChange:n,onActiveAnnotationChange:r,duration:s,linkEndpoints:a,continuousPlay:o=!1,enabled:i=!0,scrollContainerRef:l,samplesPerPixel:c,sampleRate:u,onPlay:f}){const p=m.useMemo(()=>t?e.findIndex(E=>E.id===t):-1,[e,t]),d=m.useCallback(E=>{if(!l?.current||!c||!u)return;const I=e.find(Q=>Q.id===E);if(!I)return;const M=l.current,T=M.clientWidth,A=I.start*u/c,$=I.end*u/c,R=(A+$)/2,F=M.scrollLeft,O=F,G=F+T;if(A<O||$>G){const Q=Math.max(0,R-T/2);M.scrollTo({left:Q,behavior:"smooth"})}},[e,l,c,u]);m.useEffect(()=>{t&&l?.current&&c&&u&&d(t)},[t,d,l,c,u]);const h=m.useCallback(E=>{if(p<0)return;const I=e[p],M=Math.max(0,Math.min(I.end-.1,I.start+E)),T=M-I.start,A=[...e];if(A[p]={...I,start:M},a&&p>0){const $=A[p-1];Math.abs($.end-I.start)<wa&&(A[p-1]={...$,end:Math.max($.start+.1,$.end+T)})}else if(!a&&p>0){const $=A[p-1];M<$.end&&(A[p-1]={...$,end:M})}n(A)},[e,p,a,n]),v=m.useCallback(E=>{if(p<0)return;const I=e[p],M=Math.max(I.start+.1,Math.min(s,I.end+E)),T=M-I.end,A=[...e];if(A[p]={...I,end:M},a&&p<e.length-1){const $=A[p+1];if(Math.abs($.start-I.end)<wa){const R=Math.min($.end-.1,$.start+T);A[p+1]={...$,start:R};let F=p+1;for(;F<A.length-1;){const O=A[F],G=A[F+1];if(Math.abs(G.start-e[F].end)<wa){const Q=O.end-e[F].end;A[F+1]={...G,start:Math.min(G.end-.1,G.start+Q)},F++}else break}}}else if(!a&&p<e.length-1){const $=A[p+1];if(M>$.start){A[p+1]={...$,start:M};let R=p+1;for(;R<A.length-1;){const F=A[R],O=A[R+1];if(F.end>O.start)A[R+1]={...O,start:F.end},R++;else break}}}n(A)},[e,p,s,a,n]),g=m.useCallback(()=>{!r||e.length===0||(p<=0?r(e[e.length-1].id):r(e[p-1].id))},[e,p,r]),y=m.useCallback(()=>{!r||e.length===0||(p<0||p>=e.length-1?r(e[0].id):r(e[p+1].id))},[e,p,r]),b=m.useCallback(()=>{!r||e.length===0||r(e[0].id)},[e,r]),w=m.useCallback(()=>{!r||e.length===0||r(e[e.length-1].id)},[e,r]),_=m.useCallback(()=>{r&&r(null)},[r]),x=m.useCallback(()=>{if(p<0||!f)return;const E=e[p],I=o?void 0:E.end-E.start;f(E.start,I)},[e,p,o,f]),S=m.useMemo(()=>[{key:"[",action:()=>h(-rs),description:"Move annotation start earlier",preventDefault:!0},{key:"]",action:()=>h(rs),description:"Move annotation start later",preventDefault:!0},{key:"{",shiftKey:!0,action:()=>v(-rs),description:"Move annotation end earlier",preventDefault:!0},{key:"}",shiftKey:!0,action:()=>v(rs),description:"Move annotation end later",preventDefault:!0},{key:"Enter",action:x,description:"Play selected annotation",preventDefault:!0}],[h,v,x]),k=m.useMemo(()=>[{key:"ArrowUp",action:g,description:"Select previous annotation",preventDefault:!0},{key:"ArrowLeft",action:g,description:"Select previous annotation",preventDefault:!0},{key:"ArrowDown",action:y,description:"Select next annotation",preventDefault:!0},{key:"ArrowRight",action:y,description:"Select next annotation",preventDefault:!0},{key:"Home",action:b,description:"Select first annotation",preventDefault:!0},{key:"End",action:w,description:"Select last annotation",preventDefault:!0},{key:"Escape",action:_,description:"Deselect annotation",preventDefault:!0}],[g,y,b,w,_]);return Ps({shortcuts:S,enabled:i&&p>=0}),Ps({shortcuts:k,enabled:i&&e.length>0&&!!r}),{moveStartBoundary:h,moveEndBoundary:v,selectPrevious:g,selectNext:y,selectFirst:b,selectLast:w,clearSelection:_,scrollToAnnotation:d,playActiveAnnotation:x}}const Wr=[{id:"reverb",name:"Reverb",category:"reverb",description:"Simple convolution reverb with adjustable decay time",parameters:[{name:"decay",label:"Decay",type:"number",min:.1,max:10,step:.1,default:1.5,unit:"s"},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:.5}]},{id:"freeverb",name:"Freeverb",category:"reverb",description:"Classic Schroeder/Moorer reverb with room size and dampening",parameters:[{name:"roomSize",label:"Room Size",type:"number",min:0,max:1,step:.01,default:.7},{name:"dampening",label:"Dampening",type:"number",min:0,max:1e4,step:100,default:3e3,unit:"Hz"},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:.5}]},{id:"jcReverb",name:"JC Reverb",category:"reverb",description:"Attempt at Roland JC-120 chorus reverb emulation",parameters:[{name:"roomSize",label:"Room Size",type:"number",min:0,max:1,step:.01,default:.5},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:.5}]},{id:"feedbackDelay",name:"Feedback Delay",category:"delay",description:"Delay line with feedback for echo effects",parameters:[{name:"delayTime",label:"Delay Time",type:"number",min:0,max:1,step:.01,default:.25,unit:"s"},{name:"feedback",label:"Feedback",type:"number",min:0,max:.95,step:.01,default:.5},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:.5}]},{id:"pingPongDelay",name:"Ping Pong Delay",category:"delay",description:"Stereo delay bouncing between left and right channels",parameters:[{name:"delayTime",label:"Delay Time",type:"number",min:0,max:1,step:.01,default:.25,unit:"s"},{name:"feedback",label:"Feedback",type:"number",min:0,max:.95,step:.01,default:.5},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:.5}]},{id:"chorus",name:"Chorus",category:"modulation",description:"Creates thickness by layering detuned copies of the signal",parameters:[{name:"frequency",label:"Rate",type:"number",min:.1,max:10,step:.1,default:1.5,unit:"Hz"},{name:"delayTime",label:"Delay",type:"number",min:0,max:20,step:.5,default:3.5,unit:"ms"},{name:"depth",label:"Depth",type:"number",min:0,max:1,step:.01,default:.7},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:.5}]},{id:"phaser",name:"Phaser",category:"modulation",description:"Classic phaser effect using allpass filters",parameters:[{name:"frequency",label:"Rate",type:"number",min:.1,max:10,step:.1,default:.5,unit:"Hz"},{name:"octaves",label:"Octaves",type:"number",min:1,max:6,step:1,default:3},{name:"baseFrequency",label:"Base Freq",type:"number",min:100,max:2e3,step:10,default:350,unit:"Hz"},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:.5}]},{id:"tremolo",name:"Tremolo",category:"modulation",description:"Rhythmic volume modulation",parameters:[{name:"frequency",label:"Rate",type:"number",min:.1,max:20,step:.1,default:4,unit:"Hz"},{name:"depth",label:"Depth",type:"number",min:0,max:1,step:.01,default:.5},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:1}]},{id:"vibrato",name:"Vibrato",category:"modulation",description:"Pitch modulation effect",parameters:[{name:"frequency",label:"Rate",type:"number",min:.1,max:20,step:.1,default:5,unit:"Hz"},{name:"depth",label:"Depth",type:"number",min:0,max:1,step:.01,default:.1},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:1}]},{id:"autoPanner",name:"Auto Panner",category:"modulation",description:"Automatic left-right panning",parameters:[{name:"frequency",label:"Rate",type:"number",min:.1,max:10,step:.1,default:1,unit:"Hz"},{name:"depth",label:"Depth",type:"number",min:0,max:1,step:.01,default:1},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:1}]},{id:"autoFilter",name:"Auto Filter",category:"filter",description:"Automated filter sweep with LFO",parameters:[{name:"frequency",label:"Rate",type:"number",min:.1,max:10,step:.1,default:1,unit:"Hz"},{name:"baseFrequency",label:"Base Freq",type:"number",min:20,max:2e3,step:10,default:200,unit:"Hz"},{name:"octaves",label:"Octaves",type:"number",min:.5,max:8,step:.5,default:2.6},{name:"depth",label:"Depth",type:"number",min:0,max:1,step:.01,default:1},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:1}]},{id:"autoWah",name:"Auto Wah",category:"filter",description:"Envelope follower filter effect",parameters:[{name:"baseFrequency",label:"Base Freq",type:"number",min:20,max:500,step:10,default:100,unit:"Hz"},{name:"octaves",label:"Octaves",type:"number",min:1,max:8,step:1,default:6},{name:"sensitivity",label:"Sensitivity",type:"number",min:-40,max:0,step:1,default:0,unit:"dB"},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:1}]},{id:"eq3",name:"3-Band EQ",category:"filter",description:"Three band equalizer with low, mid, and high controls",parameters:[{name:"low",label:"Low",type:"number",min:-24,max:24,step:.5,default:0,unit:"dB"},{name:"mid",label:"Mid",type:"number",min:-24,max:24,step:.5,default:0,unit:"dB"},{name:"high",label:"High",type:"number",min:-24,max:24,step:.5,default:0,unit:"dB"},{name:"lowFrequency",label:"Low Freq",type:"number",min:20,max:500,step:10,default:400,unit:"Hz"},{name:"highFrequency",label:"High Freq",type:"number",min:1e3,max:1e4,step:100,default:2500,unit:"Hz"}]},{id:"distortion",name:"Distortion",category:"distortion",description:"Wave shaping distortion effect",parameters:[{name:"distortion",label:"Drive",type:"number",min:0,max:1,step:.01,default:.4},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:1}]},{id:"bitCrusher",name:"Bit Crusher",category:"distortion",description:"Reduces bit depth for lo-fi digital texture",parameters:[{name:"bits",label:"Bits",type:"number",min:1,max:16,step:1,default:4},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:1}]},{id:"chebyshev",name:"Chebyshev",category:"distortion",description:"Waveshaping distortion using Chebyshev polynomials",parameters:[{name:"order",label:"Order",type:"number",min:1,max:100,step:1,default:50},{name:"wet",label:"Mix",type:"number",min:0,max:1,step:.01,default:1}]},{id:"compressor",name:"Compressor",category:"dynamics",description:"Dynamic range compressor",parameters:[{name:"threshold",label:"Threshold",type:"number",min:-60,max:0,step:1,default:-24,unit:"dB"},{name:"ratio",label:"Ratio",type:"number",min:1,max:20,step:.5,default:4},{name:"attack",label:"Attack",type:"number",min:0,max:1,step:.001,default:.003,unit:"s"},{name:"release",label:"Release",type:"number",min:0,max:1,step:.01,default:.25,unit:"s"},{name:"knee",label:"Knee",type:"number",min:0,max:40,step:1,default:30,unit:"dB"}]},{id:"limiter",name:"Limiter",category:"dynamics",description:"Hard limiter to prevent clipping",parameters:[{name:"threshold",label:"Threshold",type:"number",min:-12,max:0,step:.5,default:-6,unit:"dB"}]},{id:"gate",name:"Gate",category:"dynamics",description:"Noise gate to silence signal below threshold",parameters:[{name:"threshold",label:"Threshold",type:"number",min:-100,max:0,step:1,default:-40,unit:"dB"},{name:"attack",label:"Attack",type:"number",min:0,max:.3,step:.001,default:.001,unit:"s"},{name:"release",label:"Release",type:"number",min:0,max:.5,step:.01,default:.1,unit:"s"}]},{id:"stereoWidener",name:"Stereo Widener",category:"spatial",description:"Expands or narrows the stereo image",parameters:[{name:"width",label:"Width",type:"number",min:0,max:1,step:.01,default:.5}]}],Ci=e=>Wr.find(t=>t.id===e),F0=e=>Wr.filter(t=>t.category===e),O0=[{id:"reverb",name:"Reverb"},{id:"delay",name:"Delay"},{id:"modulation",name:"Modulation"},{id:"filter",name:"Filter"},{id:"distortion",name:"Distortion"},{id:"dynamics",name:"Dynamics"},{id:"spatial",name:"Spatial"}];const L0={reverb:L.Reverb,freeverb:L.Freeverb,jcReverb:L.JCReverb,feedbackDelay:L.FeedbackDelay,pingPongDelay:L.PingPongDelay,chorus:L.Chorus,phaser:L.Phaser,tremolo:L.Tremolo,vibrato:L.Vibrato,autoPanner:L.AutoPanner,autoFilter:L.AutoFilter,autoWah:L.AutoWah,eq3:L.EQ3,distortion:L.Distortion,bitCrusher:L.BitCrusher,chebyshev:L.Chebyshev,compressor:L.Compressor,limiter:L.Limiter,gate:L.Gate,stereoWidener:L.StereoWidener};let B0=0;const W0=()=>`effect_${Date.now()}_${++B0}`;function kr(e,t){const n=L0[e.id];if(!n)throw new Error(`Unknown effect type: ${e.id}`);const r={};e.parameters.forEach(i=>{const l=t?.[i.name]??i.default;r[i.name]=l});const s=new n(r),a=W0(),o=s;return{effect:s,id:e.id,instanceId:a,dispose(){try{s.disconnect(),s.dispose()}catch(i){console.warn(`[waveform-playlist] Error disposing effect "${e.id}" (${a}):`,i)}},setParameter(i,l){const c=o[i];if(i==="wet"){const u=o.wet;if(u&&typeof u=="object"&&"value"in u){u.value=l;return}}c!==void 0&&(c&&typeof c=="object"&&"value"in c?c.value=l:o[i]=l)},getParameter(i){if(i==="wet"){const c=o.wet;if(c&&typeof c=="object"&&"value"in c)return c.value}const l=o[i];if(l!==void 0)return l&&typeof l=="object"&&"value"in l?l.value:l},connect(i){s.connect(i)},disconnect(){try{s.disconnect()}catch(i){console.warn(`[waveform-playlist] Error disconnecting effect "${e.id}" (${a}):`,i)}}}}function V0(e){if(e.length===0)throw new Error("Cannot create effect chain with no effects");for(let t=0;t<e.length-1;t++)e[t].effect.connect(e[t+1].effect);return{input:e[0].effect,output:e[e.length-1].effect,dispose(){e.forEach(t=>t.dispose())}}}function N0(e=256){const[t,n]=m.useState([]),r=m.useRef(t);r.current=t;const s=m.useRef(new Map),a=m.useRef(null),o=m.useRef(null),i=m.useCallback(g=>{const y=o.current;if(!y)return;const{masterGainNode:b,destination:w,analyserNode:_}=y;try{b.disconnect()}catch(S){console.warn("[waveform-playlist] Error disconnecting master effects chain:",S)}const x=g.map(S=>s.current.get(S.instanceId)).filter(S=>S!==void 0);if(x.length===0)b.connect(_),_.connect(w);else{let S=b;x.forEach(k=>{try{k.disconnect()}catch(E){console.warn(`[waveform-playlist] Error disconnecting effect "${k.id}":`,E)}S.connect(k.effect),S=k.effect}),S.connect(_),_.connect(w)}},[]),l=m.useCallback(g=>{const y=Ci(g);if(!y){console.error(`Unknown effect: ${g}`);return}const b={};y.parameters.forEach(x=>{b[x.name]=x.default});const w=kr(y,b);s.current.set(w.instanceId,w);const _={instanceId:w.instanceId,effectId:y.id,definition:y,params:b,bypassed:!1};n(x=>[...x,_])},[]),c=m.useCallback(g=>{const y=s.current.get(g);y&&(y.dispose(),s.current.delete(g)),n(b=>b.filter(w=>w.instanceId!==g))},[]),u=m.useCallback((g,y,b)=>{const w=s.current.get(g);w&&w.setParameter(y,b),n(_=>_.map(x=>x.instanceId===g?{...x,params:{...x.params,[y]:b}}:x))},[]),f=m.useCallback(g=>{const y=r.current.find(_=>_.instanceId===g);if(!y)return;const b=!y.bypassed,w=s.current.get(g);if(w){const _=y.params.wet??1;w.setParameter("wet",b?0:_)}n(_=>_.map(x=>x.instanceId===g?{...x,bypassed:b}:x))},[]),p=m.useCallback((g,y)=>{n(b=>{const w=[...b],[_]=w.splice(g,1);return w.splice(y,0,_),w})},[]),d=m.useCallback(()=>{s.current.forEach(g=>g.dispose()),s.current.clear(),n([])},[]);m.useEffect(()=>{i(t)},[t,i]);const h=m.useCallback((g,y,b)=>{const w=new L.Analyser("fft",e);a.current=w,o.current={masterGainNode:g,destination:y,analyserNode:w};const x=r.current.map(S=>s.current.get(S.instanceId)).filter(S=>S!==void 0);if(x.length===0)g.connect(w),w.connect(y);else{let S=g;x.forEach(k=>{S.connect(k.effect),S=k.effect}),S.connect(w),w.connect(y)}return function(){w.dispose(),a.current=null,o.current=null}},[e]);m.useEffect(()=>{const g=s.current;return()=>{g.forEach(y=>y.dispose()),g.clear()}},[]);const v=m.useCallback(()=>{const g=t.filter(y=>!y.bypassed);if(g.length!==0)return(y,b,w)=>{const _=[];for(const x of g){const S=kr(x.definition,x.params);_.push(S)}if(_.length===0)y.connect(b);else{let x=y;_.forEach(S=>{x.connect(S.effect),x=S.effect}),x.connect(b)}return function(){_.forEach(S=>S.dispose())}}},[t]);return{activeEffects:t,availableEffects:Wr,addEffect:l,removeEffect:c,updateParameter:u,toggleBypass:f,reorderEffects:p,clearAllEffects:d,masterEffects:h,createOfflineEffectsFunction:v,analyserRef:a}}function j0(){const[e,t]=m.useState(new Map),n=m.useRef(new Map),r=m.useRef(new Map),s=m.useCallback((d,h)=>{const v=r.current.get(d);if(!v)return;const{graphEnd:g,masterGainNode:y}=v,b=n.current.get(d);try{g.disconnect()}catch(_){console.warn(`[waveform-playlist] Error disconnecting track "${d}" effect chain:`,_)}const w=h.map(_=>b?.get(_.instanceId)).filter(_=>_!==void 0);if(w.length===0)g.connect(y);else{let _=g;w.forEach(x=>{try{x.disconnect()}catch(S){console.warn(`[waveform-playlist] Error disconnecting effect "${x.id}" on track "${d}":`,S)}_.connect(x.effect),_=x.effect}),_.connect(y)}},[]),a=m.useCallback((d,h)=>{const v=Ci(h);if(!v){console.error(`Unknown effect: ${h}`);return}const g={};v.parameters.forEach(w=>{g[w.name]=w.default});const y=kr(v,g);n.current.has(d)||n.current.set(d,new Map),n.current.get(d).set(y.instanceId,y);const b={instanceId:y.instanceId,effectId:v.id,definition:v,params:g,bypassed:!1};t(w=>{const _=new Map(w),x=_.get(d)||[];return _.set(d,[...x,b]),_})},[]),o=m.useCallback((d,h)=>{const v=n.current.get(d),g=v?.get(h);g&&(g.dispose(),v?.delete(h)),t(y=>{const b=new Map(y),w=b.get(d)||[];return b.set(d,w.filter(_=>_.instanceId!==h)),b})},[]),i=m.useCallback((d,h,v,g)=>{const b=n.current.get(d)?.get(h);b&&b.setParameter(v,g),t(w=>{const _=new Map(w),x=_.get(d)||[];return _.set(d,x.map(S=>S.instanceId===h?{...S,params:{...S.params,[v]:g}}:S)),_})},[]),l=m.useCallback((d,h)=>{const g=(u.current.get(d)||[]).find(_=>_.instanceId===h);if(!g)return;const y=!g.bypassed,w=n.current.get(d)?.get(h);if(w){const _=g.params.wet??1;w.setParameter("wet",y?0:_)}t(_=>{const x=new Map(_),S=x.get(d)||[];return x.set(d,S.map(k=>k.instanceId===h?{...k,bypassed:y}:k)),x})},[]),c=m.useCallback(d=>{const h=n.current.get(d);h&&(h.forEach(v=>v.dispose()),h.clear()),t(v=>{const g=new Map(v);return g.set(d,[]),g})},[]),u=m.useRef(e);u.current=e;const f=m.useCallback(d=>(h,v,g)=>{r.current.set(d,{graphEnd:h,masterGainNode:v});const y=u.current.get(d)||[],b=n.current.get(d),w=y.map(_=>b?.get(_.instanceId)).filter(_=>_!==void 0);if(w.length===0)h.connect(v);else{let _=h;w.forEach(x=>{_.connect(x.effect),_=x.effect}),_.connect(v)}return function(){r.current.delete(d)}},[]);m.useEffect(()=>{e.forEach((d,h)=>{s(h,d)})},[e,s]),m.useEffect(()=>{const d=n.current;return()=>{d.forEach(h=>{h.forEach(v=>v.dispose()),h.clear()}),d.clear()}},[]);const p=m.useCallback(d=>{const v=(e.get(d)||[]).filter(g=>!g.bypassed);if(v.length!==0)return(g,y,b)=>{const w=[];for(const _ of v){const x=kr(_.definition,_.params);w.push(x)}if(w.length===0)g.connect(y);else{let _=g;w.forEach(x=>{_.connect(x.effect),_=x.effect}),_.connect(y)}return function(){w.forEach(x=>x.dispose())}}},[e]);return{trackEffectsState:e,addEffectToTrack:a,removeEffectFromTrack:o,updateTrackEffectParameter:i,toggleBypass:l,clearTrackEffects:c,getTrackEffectsFunction:f,createOfflineTrackEffectsFunction:p,availableEffects:Wr}}function z0(e,t={}){const{bitDepth:n=16}=t,r=e.numberOfChannels,s=e.sampleRate,a=e.length,o=n/8,i=r*o,l=s*i,c=a*i,u=44,f=u+c,p=new ArrayBuffer(f),d=new DataView(p);ss(d,0,"RIFF"),d.setUint32(4,f-8,!0),ss(d,8,"WAVE"),ss(d,12,"fmt "),d.setUint32(16,16,!0),d.setUint16(20,n===32?3:1,!0),d.setUint16(22,r,!0),d.setUint32(24,s,!0),d.setUint32(28,l,!0),d.setUint16(32,i,!0),d.setUint16(34,n,!0),ss(d,36,"data"),d.setUint32(40,c,!0);const h=[];for(let g=0;g<r;g++)h.push(e.getChannelData(g));let v=u;if(n===16)for(let g=0;g<a;g++)for(let y=0;y<r;y++){const b=h[y][g],w=Math.max(-1,Math.min(1,b)),_=w<0?w*32768:w*32767;d.setInt16(v,_,!0),v+=2}else for(let g=0;g<a;g++)for(let y=0;y<r;y++)d.setFloat32(v,h[y][g],!0),v+=4;return new Blob([p],{type:"audio/wav"})}function ss(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}function Z0(e,t){const n=URL.createObjectURL(e),r=document.createElement("a");r.href=n,r.download=t,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}function df(){const[e,t]=m.useState(!1),[n,r]=m.useState(0),[s,a]=m.useState(null);return{exportWav:m.useCallback(async(i,l,c={})=>{const{filename:u="export",mode:f="master",trackIndex:p,autoDownload:d=!0,applyEffects:h=!0,effectsFunction:v,createOfflineTrackEffects:g,bitDepth:y=16,onProgress:b}=c;t(!0),r(0),a(null);try{if(i.length===0)throw new Error("No tracks to export");if(f==="individual"&&(p===void 0||p<0||p>=i.length))throw new Error("Invalid track index for individual export");const w=i[0].clips[0]?.sampleRate||44100;let _=0;for(const T of i)for(const A of T.clips){const $=A.startSample+A.durationSamples;_=Math.max(_,$)}_+=Math.round(w*.1);const x=_/w,S=f==="individual"?[{track:i[p],state:l[p],index:p}]:i.map((T,A)=>({track:T,state:l[A],index:A})),k=l.some(T=>T.soloed),E=!!g;let I;if((v||E)&&h)I=await H0(S,l,k,x,w,v,g,T=>{r(T),b?.(T)});else{const T=new OfflineAudioContext(2,_,w);let A=0;const $=S.reduce((R,{track:F})=>R+F.clips.length,0);for(const{track:R,state:F}of S)if(!(F.muted&&!F.soloed)&&!(k&&!F.soloed))for(const O of R.clips){await U0(T,O,F,w,h),A++;const G=A/$*.5;r(G),b?.(G)}r(.5),b?.(.5),I=await T.startRendering()}r(.9),b?.(.9);const M=z0(I,{bitDepth:y});if(r(1),b?.(1),d){const T=f==="individual"?`${u}_${i[p].name}`:u;Z0(M,`${T}.wav`)}return{audioBuffer:I,blob:M,duration:x}}catch(w){const _=w instanceof Error?w.message:"Export failed";throw a(_),w}finally{t(!1)}},[]),isExporting:e,progress:n,error:s}}async function H0(e,t,n,r,s,a,o,i){const{Offline:l,Volume:c,Gain:u,Panner:f,Player:p,ToneAudioBuffer:d}=await import("tone");i(.1);let h;try{h=await l(async({transport:v,destination:g})=>{const y=new c(0);let b;a?b=a(y,g,!0):y.connect(g);for(const{track:w,state:_}of e){if(_.muted&&!_.soloed||n&&!_.soloed)continue;const x=new c(G0(_.volume)),S=new f(_.pan),k=new u(_.muted?0:1),E=o?.(w.id);E?E(k,y,!0):k.connect(y),S.connect(k),x.connect(S);for(const I of w.clips){const{audioBuffer:M,startSample:T,durationSamples:A,offsetSamples:$,gain:R,fadeIn:F,fadeOut:O}=I,G=T/s,Q=A/s,ee=$/s,ue=new d(M),te=new p(ue),oe=new u(R);if(te.connect(oe),oe.connect(x),F){const se=G,le=G+F.duration,ye=gr(oe.gain);ye&&(ye.setValueAtTime(0,se),ye.linearRampToValueAtTime(R,le))}if(O){const se=G+Q-O.duration,le=G+Q,ye=gr(oe.gain);ye&&(ye.setValueAtTime(R,se),ye.linearRampToValueAtTime(0,le))}te.start(G,ee,Q)}}v.start(0)},r,2,s)}catch(v){throw v instanceof Error?v:new Error(`Tone.Offline rendering failed: ${String(v)}`)}return i(.9),h.get()}function G0(e){return 20*Math.log10(Math.max(e,1e-4))}async function U0(e,t,n,r,s){const{audioBuffer:a,startSample:o,durationSamples:i,offsetSamples:l,gain:c,fadeIn:u,fadeOut:f}=t;if(!a){console.warn(`Skipping clip "${t.name||t.id}" - no audioBuffer for export`);return}const p=o/r,d=i/r,h=l/r,v=e.createBufferSource();v.buffer=a;const g=e.createGain(),y=c*n.volume,b=e.createStereoPanner();if(b.pan.value=n.pan,v.connect(g),g.connect(b),b.connect(e.destination),s){if(u?g.gain.setValueAtTime(0,p):g.gain.setValueAtTime(y,p),u){const w=p,_=p+u.duration;ec(g.gain,w,_,0,y,u.type||"linear")}if(f){const w=p+d-f.duration,_=p+d;(!u||u.duration<d-f.duration)&&g.gain.setValueAtTime(y,w),ec(g.gain,w,_,y,0,f.type||"linear")}}else g.gain.setValueAtTime(y,p);v.start(p,h,d)}function ec(e,t,n,r,s,a){const o=n-t;if(!(o<=0))switch(a){case"linear":e.setValueAtTime(r,t),e.linearRampToValueAtTime(s,n);break;case"exponential":{const i=Math.max(r,1e-4),l=Math.max(s,1e-4);e.setValueAtTime(i,t),e.exponentialRampToValueAtTime(l,n),s===0&&e.setValueAtTime(0,n);break}case"logarithmic":{const i=tc(r,s,256,"logarithmic");e.setValueCurveAtTime(i,t,o);break}case"sCurve":{const i=tc(r,s,256,"sCurve");e.setValueCurveAtTime(i,t,o);break}default:e.setValueAtTime(r,t),e.linearRampToValueAtTime(s,n)}}function tc(e,t,n,r){const s=new Float32Array(n),a=t-e;for(let o=0;o<n;o++){const i=o/(n-1);let l;r==="logarithmic"?a>0?l=Math.log10(1+i*9)/Math.log10(10):l=1-Math.log10(1+(1-i)*9)/Math.log10(10):l=i*i*(3-2*i),s[o]=e+a*l}return s}const ff=()=>{const e=m.useRef(null),t=m.useCallback(()=>{e.current!==null&&(cancelAnimationFrame(e.current),e.current=null)},[]),n=m.useCallback(r=>{t(),e.current=requestAnimationFrame(r)},[t]);return m.useEffect(()=>()=>{t()},[t]),{animationFrameRef:e,startAnimationFrameLoop:n,stopAnimationFrameLoop:t}},X0=`
858
858
  "use strict";
859
859
 
860
860
  var INT8_MAX = 127;
@@ -1001,13 +1001,13 @@ self.onmessage = function(e) {
1001
1001
  self.postMessage({ id: msg.id, error: err.message || String(err) });
1002
1002
  }
1003
1003
  };
1004
- `;let X0=0;function Y0(){let e;try{const r=new Blob([U0],{type:"application/javascript"}),s=URL.createObjectURL(r);e=new Worker(s),URL.revokeObjectURL(s)}catch(r){return console.warn("[waveform-playlist] Failed to create peaks worker (CSP restriction?):",r),{generate(){return Promise.reject(new Error("Worker creation failed"))},terminate(){}}}const t=new Map;let n=!1;return e.onmessage=r=>{const s=r.data,a=t.get(s.id);if(a)if(t.delete(s.id),s.error)a.reject(new Error(s.error));else try{const o=pt.create(s.buffer);a.resolve(o)}catch(o){a.reject(o)}},e.onerror=r=>{n=!0,e.terminate();for(const[,s]of t)s.reject(r.error??new Error(r.message));t.clear()},{generate(r){if(n)return Promise.reject(new Error("Worker terminated"));const s=String(++X0);return new Promise((a,o)=>{t.set(s,{resolve:a,reject:o}),e.postMessage({id:s,scale:r.scale,bits:r.bits,amplitude_scale:1,split_channels:r.splitChannels,length:r.length,sample_rate:r.sampleRate,channels:r.channels},r.channels)})},terminate(){n=!0,e.terminate();for(const[,r]of t)r.reject(new Error("Worker terminated"));t.clear()}}}function K0(e,t){const[n,r]=m.useState(()=>new Map),[s,a]=m.useState(!1),o=m.useRef(null),i=m.useRef(new WeakMap),l=m.useRef(new WeakMap),c=m.useRef(new WeakMap),u=m.useRef(0),f=m.useCallback(()=>(o.current||(o.current=Y0()),o.current),[]);return m.useEffect(()=>{let p=!1;const d=i.current,h=l.current,v=c.current,g=[],y=new Map;for(const w of e)for(const _ of w.clips){if(!_.audioBuffer||_.waveformData)continue;const x=d.get(_.audioBuffer);if(x){g.push({clipId:_.id,waveformData:x});continue}if(h.get(_.audioBuffer)){const k=v.get(_.audioBuffer);k?k.add(_.id):v.set(_.audioBuffer,new Set([_.id]));continue}const S=y.get(_.audioBuffer);S?S.add(_.id):y.set(_.audioBuffer,new Set([_.id]))}if(g.length>0&&r(w=>{const _=new Map(w);for(const x of g)_.set(x.clipId,x.waveformData);return _}),y.size===0)return;u.current+=y.size,a(!0);const b=f();for(const[w,_]of y){v.set(w,new Set(_));const x=[];for(let E=0;E<w.numberOfChannels;E++)x.push(w.getChannelData(E).slice().buffer);const S=`buffer-${Math.random().toString(36).slice(2,11)}`,k=b.generate({id:S,channels:x,length:w.length,sampleRate:w.sampleRate,scale:t,bits:16,splitChannels:!0}).then(E=>{d.set(w,E);const I=v.get(w)??new Set;v.delete(w),h.delete(w),!p&&(r(M=>{const T=new Map(M);for(const A of I)T.set(A,E);return T}),u.current--,u.current<=0&&(u.current=0,a(!1)))}).catch(E=>{v.delete(w),h.delete(w),!p&&(console.warn("[waveform-playlist] Worker peak generation failed:",E),u.current--,u.current<=0&&(u.current=0,a(!1)))});h.set(w,k)}return()=>{p=!0,l.current=new WeakMap,c.current=new WeakMap,u.current=0,a(!1)}},[e,t,f]),m.useEffect(()=>()=>{o.current?.terminate(),o.current=null},[]),{cache:n,isGenerating:s}}function uo(e){return e instanceof File?e.name.replace(/\.[^/.]+$/,""):e instanceof Blob?"Untitled":typeof e=="string"?e.split("/").pop()?.replace(/\.[^/.]+$/,"")??"Untitled":e.name??e.src.split("/").pop()?.replace(/\.[^/.]+$/,"")??"Untitled"}async function q0(e,t,n){const r=uo(e);if(e instanceof Blob){const l=await e.arrayBuffer();return n?.throwIfAborted(),{audioBuffer:await t.decodeAudioData(l),name:r}}const s=typeof e=="string"?e:e.src,a=await fetch(s,{signal:n});if(!a.ok)throw new Error(`Failed to fetch ${s}: ${a.statusText}`);const o=await a.arrayBuffer();return n?.throwIfAborted(),{audioBuffer:await t.decodeAudioData(o),name:r}}function J0(){const[e,t]=m.useState([]),[n,r]=m.useState(0),[s,a]=m.useState([]),o=m.useRef(!1),i=m.useRef(new Set),l=m.useRef(new Map);m.useEffect(()=>{const f=l.current;return()=>{o.current=!0;for(const p of f.values())p.abort();f.clear()}},[]);const c=m.useCallback(f=>{if(f.length===0)return;const p=gh(),d=f.map(h=>({track:dc({name:`${uo(h)} (loading...)`,clips:[]}),source:h}));t(h=>[...h,...d.map(v=>v.track)]),r(h=>h+f.length);for(const{track:h,source:v}of d){i.current.add(h.id);const g=new AbortController;l.current.set(h.id,g),(async()=>{try{const{audioBuffer:y,name:b}=await q0(v,p,g.signal),w=uc({audioBuffer:y,startTime:0,duration:y.duration,offset:0,name:b});!o.current&&i.current.has(h.id)&&t(_=>_.map(x=>x.id===h.id?{...x,name:b,clips:[w]}:x))}catch(y){if(y instanceof DOMException&&y.name==="AbortError")return;console.warn("[waveform-playlist] Error loading audio:",y),!o.current&&i.current.has(h.id)&&(t(b=>b.filter(w=>w.id!==h.id)),a(b=>[...b,{name:uo(v),error:y instanceof Error?y:new Error(String(y))}]))}finally{l.current.delete(h.id),!o.current&&i.current.delete(h.id)&&r(y=>y-1)}})()}},[]),u=m.useCallback(f=>{t(d=>d.filter(h=>h.id!==f));const p=l.current.get(f);p&&(p.abort(),l.current.delete(f)),i.current.delete(f)&&r(d=>d-1)},[]);return{tracks:e,addTracks:c,removeTrack:u,loadingCount:n,isLoading:n>0,errors:s}}const hf=m.createContext(null),pf=m.createContext(null),mf=m.createContext(null),gf=m.createContext(null),Q0=({tracks:e,timescale:t=!1,mono:n=!1,waveHeight:r=80,samplesPerPixel:s=1024,zoomLevels:a,automaticScroll:o=!1,theme:i,controls:l={show:!1,width:0},annotationList:c,effects:u,onReady:f,onAnnotationUpdate:p,onAnnotationsChange:d,barWidth:h=1,barGap:v=0,progressBarWidth:g,onTracksChange:y,soundFontCache:b,deferEngineRebuild:w=!1,children:_})=>{const x=g??h+v,S=m.useMemo(()=>a,[a?.join(",")]),k=m.useMemo(()=>{if(!c?.annotations)return[];if(process.env.NODE_ENV!=="production"&&c.annotations.length>0){const V=c.annotations[0];if(typeof V.start!="number"||typeof V.end!="number")return console.error("[waveform-playlist] Annotations must have numeric start/end values. In v6, use parseAeneas() from @waveform-playlist/annotations before passing annotations. Received start type: "+typeof V.start),[]}return c.annotations},[c?.annotations]),E=m.useRef(k);E.current=k;const[I,M]=m.useState(null),[T,A]=m.useState(!1),[$,R]=m.useState(0),[F,O]=m.useState(0),[G,Q]=m.useState([]),[ee,ue]=m.useState([]),[te,oe]=m.useState([]),[se,le]=m.useState(o),[ye,de]=m.useState(c?.isContinuousPlay??!1),[ne,Z]=m.useState(c?.linkEndpoints??!1),[fe,Fe]=m.useState(c?.editable??!1),[ae,Te]=m.useState(!1),B=m.useRef(null),$e=m.useRef(!1),re=m.useRef(!1);re.current=T;const Ve=m.useRef(0),ve=m.useRef(0),Re=m.useRef(e),ct=m.useRef(b);ct.current=b;const xt=m.useRef(te),st=m.useRef(0),je=m.useRef(0),at=m.useRef(null),ut=m.useRef(null),Mt=m.useRef(!1),Ct=m.useRef(c?.isContinuousPlay??!1),j=m.useRef(null),pe=m.useRef(null),ze=m.useRef(0),Ze=m.useRef(!1),q=m.useRef(!1),me=m.useRef(s),He=m.useRef(44100),{timeFormat:St,setTimeFormat:N,formatTime:U}=tf(),H=nf({engineRef:B,initialSamplesPerPixel:s}),{samplesPerPixel:X,onEngineState:ke}=H,Me=rf({engineRef:B,initialVolume:1}),{masterVolume:Y,setMasterVolume:Be,masterVolumeRef:Xe,onEngineState:Ge}=Me,{selectionStart:kt,selectionEnd:Nt,setSelection:wn,selectionStartRef:Dt,selectionEndRef:jr,onEngineState:Mi}=E0({engineRef:B}),{isLoopEnabled:Ai,loopStart:Ti,loopEnd:$i,setLoopEnabled:Ri,setLoopRegion:zr,clearLoopRegion:Di,isLoopEnabledRef:Pi,loopStartRef:Fi,loopEndRef:Oi,onEngineState:Li}=I0({engineRef:B}),{selectedTrackId:Bi,setSelectedTrackId:Wi,onEngineState:Vi,selectedTrackIdRef:Ni}=M0({engineRef:B}),{animationFrameRef:ji,startAnimationFrameLoop:ta,stopAnimationFrameLoop:Zr}=ff(),jf=m.useMemo(()=>Math.min(...S??[256,512,1024,2048,4096,8192]),[S]),{cache:zi}=K0(e,jf),Zi=m.useCallback(V=>{Ct.current=V,de(V)},[]),Pt=m.useCallback(V=>{j.current=V,M(V)},[]),Hi=m.useCallback(()=>{const V=Dt.current??0,z=jr.current??0;V!==z&&z>V&&zr(V,z)},[zr,Dt,jr]);m.useEffect(()=>{Mt.current=se},[se]),m.useEffect(()=>{xt.current=te},[te]),Re.current=e;const na=e===pe.current;Ze.current=na||q.current,m.useEffect(()=>{if(!ut.current||F===0)return;const V=ut.current,z=me.current,he=X;if(z===he)return;const W=V.clientWidth,Ee=V.scrollLeft+W/2,Ce=He.current,oa=Ee*z/Ce*Ce/he,Xr=Math.max(0,oa-W/2);V.scrollLeft=Xr,me.current=he},[X,F]);const Hr=m.useRef(null);m.useEffect(()=>{if(na||q.current){na&&(pe.current=null);let W=0;e.forEach(_e=>{_e.clips.forEach(Ee=>{const Ce=(Ee.startSample+Ee.durationSamples)/Ee.sampleRate;W=Math.max(W,Ce)})}),O(W);return}if(w){let W=0;e.forEach(_e=>{_e.clips.forEach(Ee=>{const Ce=(Ee.startSample+Ee.durationSamples)/Ee.sampleRate;W=Math.max(W,Ce)})}),O(W);return}if(Te(!1),e.length===0){Q([]),O(0),oe([]),ue([]),B.current&&(B.current.dispose(),B.current=null);return}const V=re.current,z=ve.current;return B.current&&V&&(B.current.stop(),Zr(),Hr.current={position:z}),(async()=>{try{const W=[];e.forEach(Ie=>{Ie.clips.length>0&&Ie.clips[0].audioBuffer&&W.push(Ie.clips[0].audioBuffer)});let _e=0;e.forEach(Ie=>{Ie.clips.forEach(ft=>{const jt=ft.sampleRate,Yf=(ft.startSample+ft.durationSamples)/jt;_e=Math.max(_e,Yf)})}),Q(W),O(_e),oe(Ie=>Ie.length===e.length?Ie.map((ft,jt)=>({...ft,name:e[jt].name})):e.map(ft=>({name:ft.name,muted:ft.muted,soloed:ft.soloed,volume:ft.volume,pan:ft.pan}))),B.current&&B.current.dispose(),ze.current=0,pe.current=null,$e.current=!1;const Ee=vh({effects:u,soundFontCache:ct.current}),Ce=new Sh({adapter:Ee,samplesPerPixel:me.current,zoomLevels:S});Ce.setSelection(Dt.current??0,jr.current??0),Ce.setLoopRegion(Fi.current??0,Oi.current??0),Pi.current&&Ce.setLoopEnabled(!0),Ce.setMasterVolume(Xe.current??1),Ni.current&&Ce.selectTrack(Ni.current);const Ur=xt.current,oa=e.map((Ie,ft)=>{const jt=Ur[ft];return{...Ie,volume:jt?.volume??Ie.volume,muted:jt?.muted??Ie.muted,soloed:jt?.soloed??Ie.soloed,pan:jt?.pan??Ie.pan}});let Xr=!0;Ce.on("statechange",Ie=>{Mi(Ie),Li(Ie),Vi(Ie),ke(Ie),Ge(Ie),!Xr&&Ie.tracksVersion!==ze.current&&(ze.current=Ie.tracksVersion,pe.current=Ie.tracks,y?y(Ie.tracks):console.warn("[waveform-playlist] Engine tracks changed but onTracksChange prop is not set — UI will revert on next render. Pass onTracksChange to WaveformPlaylistProvider."))}),Ce.setTracks(oa),Xr=!1,ze.current=Ce.getState().tracksVersion,B.current=Ce,Te(!0);const Xf=new CustomEvent("waveform-playlist:ready",{detail:{trackCount:e.length,duration:_e}});window.dispatchEvent(Xf),f?.()}catch(W){console.error("Error loading audio:",W)}})(),()=>{if(Ze.current){Ze.current=!1;return}Zr(),B.current&&B.current.dispose()}},[e,f,u,Zr,Mi,Li,Vi,ke,Ge,y,Xe,Dt,jr,Fi,Oi,Pi,S,b,w]),m.useEffect(()=>{if(e.length===0)return;const V=e.map(z=>z.clips.map(W=>{let _e;if(W.waveformData)try{_e=Ql(W.waveformData,X,n,W.offsetSamples,W.durationSamples)}catch(Ee){console.warn("[waveform-playlist] Failed to extract peaks from waveformData:",Ee)}if(!_e){const Ee=zi.get(W.id);if(Ee)try{_e=Ql(Ee,X,n,W.offsetSamples,W.durationSamples)}catch(Ce){console.warn("[waveform-playlist] Failed to extract peaks from cache:",Ce)}}if(!_e){!w&&!W.audioBuffer&&!W.waveformData&&!W.midiNotes&&console.warn(`[waveform-playlist] Clip "${W.id}" has no audio data or waveform data`);const Ee=n?1:W.audioBuffer?.numberOfChannels??1,Ce=W.midiNotes?Math.ceil(W.durationSamples/X):0;_e={length:Ce,data:Array.from({length:Ee},()=>new Int16Array(Ce*2)),bits:16}}return{clipId:W.id,trackName:z.name,peaks:_e,startSample:W.startSample,durationSamples:W.durationSamples,fadeIn:W.fadeIn,fadeOut:W.fadeOut,midiNotes:W.midiNotes,sampleRate:W.sampleRate,offsetSamples:W.offsetSamples}}));ue(V)},[e,X,n,zi,w]);const Gi=m.useRef(!1),_n=m.useCallback(()=>{if(B.current)return B.current.getCurrentTime();Gi.current||(Gi.current=!0,console.warn("[waveform-playlist] getPlaybackTime called without engine. Falling back to manual elapsed time (loop wrapping will not work)."));const V=L.getContext().currentTime-(st.current??0);return(je.current??0)+V},[]),Qt=m.useCallback(()=>{const V=()=>{const z=_n();ve.current=z;const he=E.current;if(he.length>0){const W=he.find(_e=>z>=_e.start&&z<_e.end);if(Ct.current)W&&W.id!==j.current?Pt(W.id):!W&&j.current!==null&&Pt(null);else if(j.current){const _e=he.find(Ee=>Ee.id===j.current);if(_e&&z>=_e.end){B.current&&B.current.stop(),A(!1),ve.current=Ve.current,R(Ve.current);return}}else W&&Pt(W.id)}if(Mt.current&&ut.current&&F>0){const W=ut.current,_e=He.current,Ee=z*_e/me.current,Ce=W.clientWidth,Ur=Math.max(0,Ee-Ce/2);W.scrollLeft=Ur}if(at.current!==null&&z>=at.current){B.current&&B.current.stop(),A(!1),ve.current=at.current,R(at.current),at.current=null;return}if(z>=F){B.current&&B.current.stop(),A(!1),ve.current=Ve.current,R(Ve.current),Pt(null);return}ta(V)};ta(V)},[F,Pt,ta,_n]),dt=Zr;m.useEffect(()=>{(async()=>{if(T&&ji.current&&B.current)if(ye){const z=ve.current;B.current.stop(),dt();const W=L.getContext().currentTime;st.current=W,je.current=z,B.current.play(z),Qt()}else dt(),Qt()})().catch(z=>{console.warn("[waveform-playlist] Failed to reschedule playback:",z),A(!1),dt()})},[ye,T,Qt,dt,ji]),m.useEffect(()=>{(async()=>{if(Hr.current&&B.current){const{position:z}=Hr.current;Hr.current=null;const W=L.getContext().currentTime;st.current=W,je.current=z,$e.current||(await B.current.init(),$e.current=!0),B.current.play(z),A(!0),Qt()}})().catch(z=>{console.warn("[waveform-playlist] Failed to resume playback after track change:",z),A(!1),dt()})},[e,Qt,dt]);const Gr=m.useCallback(async(V,z)=>{if(!B.current||F===0)return;const he=V??ve.current;Ve.current=he,ve.current=he,B.current.stop(),B.current.seek(he),dt();const _e=L.getContext().currentTime;st.current=_e,je.current=he,at.current=z!==void 0?he+z:null,$e.current||(await B.current.init(),$e.current=!0);const Ee=z!==void 0?he+z:void 0;try{B.current.play(he,Ee)}catch(Ce){console.warn("[waveform-playlist] Playback failed to start:",Ce),dt();return}A(!0),Qt()},[F,Qt,dt]),Ui=m.useCallback(()=>{if(!B.current)return;const V=_n();B.current.pause(),A(!1),dt(),ve.current=V,R(V)},[dt,_n]),Xi=m.useCallback(()=>{B.current&&(B.current.stop(),A(!1),dt(),ve.current=Ve.current,R(Ve.current),Pt(null))},[dt,Pt]),Yi=m.useCallback(V=>{const z=Math.max(0,Math.min(V,F));ve.current=z,R(z),T&&B.current&&Gr(z)},[F,T,Gr]),Ki=m.useCallback((V,z)=>{const he=Re.current[V]?.id;if(!he)return;const W=[...te];W[V]={...W[V],muted:z},oe(W),B.current&&B.current.setTrackMute(he,z)},[te]),qi=m.useCallback((V,z)=>{const he=Re.current[V]?.id;if(!he)return;const W=[...te];W[V]={...W[V],soloed:z},oe(W),B.current&&B.current.setTrackSolo(he,z)},[te]),Ji=m.useCallback((V,z)=>{const he=Re.current[V]?.id;if(!he)return;const W=[...te];W[V]={...W[V],volume:z},oe(W),B.current&&B.current.setTrackVolume(he,z)},[te]),Qi=m.useCallback((V,z)=>{const he=Re.current[V]?.id;if(!he)return;const W=[...te];W[V]={...W[V],pan:z},oe(W),B.current&&B.current.setTrackPan(he,z)},[te]),el=m.useCallback((V,z)=>{wn(V,z),ve.current=V,R(V),T&&B.current&&(B.current.stop(),B.current.seek(V),B.current.play(V))},[T,wn]),tl=m.useCallback(V=>{ut.current=V},[]),ra=m.useRef(d);ra.current=d;const nl=m.useCallback(V=>{const z=typeof V=="function"?V(E.current):V;if(!ra.current){process.env.NODE_ENV!=="production"&&console.warn("waveform-playlist: setAnnotations was called but no onAnnotationsChange callback is provided. Annotation edits will not persist. Pass onAnnotationsChange to WaveformPlaylistProvider to handle annotation updates.");return}ra.current(z)},[]),sa=G[0]?.sampleRate||e[0]?.clips[0]?.sampleRate||44100;He.current=sa;const aa=t?30:0,rl=e.length*r+aa,zf=m.useMemo(()=>({isPlaying:T,currentTime:$,currentTimeRef:ve,playbackStartTimeRef:st,audioStartPositionRef:je,getPlaybackTime:_n}),[T,$,ve,st,je,_n]),Zf=m.useMemo(()=>({continuousPlay:ye,linkEndpoints:ne,annotationsEditable:fe,isAutomaticScroll:se,isLoopEnabled:Ai,annotations:k,activeAnnotationId:I,selectionStart:kt,selectionEnd:Nt,selectedTrackId:Bi,loopStart:Ti,loopEnd:$i}),[ye,ne,fe,se,Ai,k,I,kt,Nt,Bi,Ti,$i]),sl=m.useCallback(V=>{ve.current=V,R(V)},[ve]),al=m.useCallback(V=>{le(V)},[]),Hf=m.useMemo(()=>({play:Gr,pause:Ui,stop:Xi,seekTo:Yi,setCurrentTime:sl,setTrackMute:Ki,setTrackSolo:qi,setTrackVolume:Ji,setTrackPan:Qi,setSelection:el,setSelectedTrackId:Wi,setTimeFormat:N,formatTime:U,zoomIn:H.zoomIn,zoomOut:H.zoomOut,setMasterVolume:Be,setAutomaticScroll:al,setScrollContainer:tl,scrollContainerRef:ut,setContinuousPlay:Zi,setLinkEndpoints:Z,setAnnotationsEditable:Fe,setAnnotations:nl,setActiveAnnotationId:Pt,setLoopEnabled:Ri,setLoopRegion:zr,setLoopRegionFromSelection:Hi,clearLoopRegion:Di}),[Gr,Ui,Xi,Yi,sl,Ki,qi,Ji,Qi,el,Wi,N,U,H.zoomIn,H.zoomOut,Be,al,tl,ut,Zi,Z,Fe,nl,Pt,Ri,zr,Hi,Di]),Gf=m.useMemo(()=>({duration:F,audioBuffers:G,peaksDataArray:ee,trackStates:te,tracks:e,sampleRate:sa,waveHeight:r,timeScaleHeight:aa,minimumPlaylistHeight:rl,controls:l,playoutRef:B,samplesPerPixel:X,timeFormat:St,masterVolume:Y,canZoomIn:H.canZoomIn,canZoomOut:H.canZoomOut,barWidth:h,barGap:v,progressBarWidth:x,isReady:ae,mono:n,isDraggingRef:q,onTracksChange:y}),[F,G,ee,te,e,sa,r,aa,rl,l,B,X,St,Y,H.canZoomIn,H.canZoomOut,h,v,x,ae,n,q,y]),Uf={...Wd,...i};return C.jsx(P.ThemeProvider,{theme:Uf,children:C.jsx(hf.Provider,{value:zf,children:C.jsx(pf.Provider,{value:Zf,children:C.jsx(mf.Provider,{value:Hf,children:C.jsx(gf.Provider,{value:Gf,children:_})})})})})},tt=()=>{const e=m.useContext(hf);if(!e)throw new Error("usePlaybackAnimation must be used within WaveformPlaylistProvider");return e},nt=()=>{const e=m.useContext(pf);if(!e)throw new Error("usePlaylistState must be used within WaveformPlaylistProvider");return e},Se=()=>{const e=m.useContext(mf);if(!e)throw new Error("usePlaylistControls must be used within WaveformPlaylistProvider");return e},rt=()=>{const e=m.useContext(gf);if(!e)throw new Error("usePlaylistData must be used within WaveformPlaylistProvider");return e};var ey=class{constructor(e){this._playbackRate=1,this.handleEnded=()=>{this.onStopCallback&&this.onStopCallback()},this.handleTimeUpdate=()=>{this.onTimeUpdateCallback&&this.onTimeUpdateCallback(this.audioElement.currentTime)},this._peaks=e.peaks,this._id=e.id??`track-${Date.now()}`,this._name=e.name??"Track",this._playbackRate=e.playbackRate??1,typeof e.source=="string"?(this.audioElement=new Audio(e.source),this.ownsElement=!0):(this.audioElement=e.source,this.ownsElement=!1),this.audioElement.preload="auto",this.audioElement.volume=e.volume??1,this.audioElement.playbackRate=this._playbackRate;const t=this.audioElement;"preservesPitch"in this.audioElement?t.preservesPitch=!0:"mozPreservesPitch"in this.audioElement?t.mozPreservesPitch=!0:"webkitPreservesPitch"in this.audioElement&&(t.webkitPreservesPitch=!0),this.audioElement.addEventListener("ended",this.handleEnded),this.audioElement.addEventListener("timeupdate",this.handleTimeUpdate)}play(e=0){this.audioElement.currentTime=e,this.audioElement.play().catch(t=>{console.warn("MediaElementTrack: play() failed:",t)})}pause(){this.audioElement.pause()}stop(){this.audioElement.pause(),this.audioElement.currentTime=0}seekTo(e){this.audioElement.currentTime=Math.max(0,Math.min(e,this.duration))}setVolume(e){this.audioElement.volume=Math.max(0,Math.min(1,e))}setPlaybackRate(e){const t=Math.max(.5,Math.min(2,e));this._playbackRate=t,this.audioElement.playbackRate=t}setMuted(e){this.audioElement.muted=e}setOnStopCallback(e){this.onStopCallback=e}setOnTimeUpdateCallback(e){this.onTimeUpdateCallback=e}dispose(){this.audioElement.removeEventListener("ended",this.handleEnded),this.audioElement.removeEventListener("timeupdate",this.handleTimeUpdate),this.audioElement.pause(),this.ownsElement&&(this.audioElement.src="",this.audioElement.load())}get id(){return this._id}get name(){return this._name}get peaks(){return this._peaks}get currentTime(){return this.audioElement.currentTime}get duration(){return this.audioElement.duration||this._peaks.duration}get isPlaying(){return!this.audioElement.paused&&!this.audioElement.ended}get volume(){return this.audioElement.volume}get playbackRate(){return this._playbackRate}get muted(){return this.audioElement.muted}get element(){return this.audioElement}},ty=class{constructor(e={}){this.track=null,this._isPlaying=!1,this._masterVolume=e.masterVolume??1,this._playbackRate=e.playbackRate??1}async init(){}addTrack(e){return this.track&&(console.warn("MediaElementPlayout: Only one track is supported. Disposing previous track. For multi-track, use TonePlayout."),this.track.dispose()),this.track=new ey({...e,volume:this._masterVolume*(e.volume??1),playbackRate:this._playbackRate}),this.track.setOnStopCallback(()=>{this._isPlaying=!1,this.onPlaybackCompleteCallback&&this.onPlaybackCompleteCallback()}),this.track}removeTrack(e){this.track&&this.track.id===e&&(this.track.dispose(),this.track=null)}getTrack(e){if(this.track&&this.track.id===e)return this.track}play(e,t,n){if(!this.track){console.warn("MediaElementPlayout: No track to play");return}const r=t??0;if(this._isPlaying=!0,this.track.play(r),n!==void 0){const s=n/this._playbackRate;setTimeout(()=>{this._isPlaying&&(this.pause(),this.onPlaybackCompleteCallback&&this.onPlaybackCompleteCallback())},s*1e3)}}pause(){this.track&&this.track.pause(),this._isPlaying=!1}stop(){this.track&&this.track.stop(),this._isPlaying=!1}seekTo(e){this.track&&this.track.seekTo(e)}getCurrentTime(){return this.track?this.track.currentTime:0}setMasterVolume(e){this._masterVolume=Math.max(0,Math.min(1,e)),this.track&&this.track.setVolume(this._masterVolume)}setPlaybackRate(e){this._playbackRate=Math.max(.5,Math.min(2,e)),this.track&&this.track.setPlaybackRate(this._playbackRate)}setMute(e,t){const n=this.getTrack(e);n&&n.setMuted(t)}setSolo(e,t){console.warn("MediaElementPlayout: Solo is not applicable for single-track playback")}setOnPlaybackComplete(e){this.onPlaybackCompleteCallback=e}dispose(){this.track&&(this.track.dispose(),this.track=null)}get isPlaying(){return this._isPlaying}get masterVolume(){return this._masterVolume}get playbackRate(){return this._playbackRate}get duration(){return this.track?.duration??0}get sampleRate(){return this.track?.peaks.sample_rate??44100}};const vf=m.createContext(null),yf=m.createContext(null),bf=m.createContext(null),wf=m.createContext(null),ny=({track:e,samplesPerPixel:t=1024,waveHeight:n=100,timescale:r=!1,playbackRate:s=1,automaticScroll:a=!1,theme:o,controls:i={show:!1,width:0},annotationList:l,barWidth:c=1,barGap:u=0,progressBarWidth:f,onAnnotationsChange:p,onReady:d,children:h})=>{const v=f??c+u,[g,y]=m.useState(!1),[b,w]=m.useState(0),[_,x]=m.useState(0),[S,k]=m.useState([]),[E,I]=m.useState(s),M=m.useMemo(()=>{if(!l?.annotations)return[];if(process.env.NODE_ENV!=="production"&&l.annotations.length>0){const j=l.annotations[0];if(typeof j.start!="number"||typeof j.end!="number")return console.error("[waveform-playlist] Annotations must have numeric start/end values. In v6, use parseAeneas() from @waveform-playlist/annotations before passing annotations. Received start type: "+typeof j.start),[]}return l.annotations},[l?.annotations]),T=m.useRef(M);T.current=M;const[A,$]=m.useState(null),[R,F]=m.useState(l?.isContinuousPlay??!1),[O]=m.useState(t),[G,Q]=m.useState(a),ee=m.useRef(null),ue=m.useRef(0),te=m.useRef(R),oe=m.useRef(null),se=m.useRef(null),le=m.useRef(a),ye=m.useRef(t),{startAnimationFrameLoop:de,stopAnimationFrameLoop:ne}=ff();m.useEffect(()=>{te.current=R},[R]),m.useEffect(()=>{le.current=G},[G]);const Z=m.useCallback(j=>{oe.current=j,$(j)},[]),fe=m.useCallback(j=>{te.current=j,F(j)},[]),Fe=m.useCallback(j=>{se.current=j},[]),ae=e.waveformData.sample_rate;m.useEffect(()=>{const j=new ty({playbackRate:s});j.addTrack({source:e.source,peaks:e.waveformData,name:e.name});const pe=j.getTrack(j.track?.id??"");return pe&&pe.setOnTimeUpdateCallback(ze=>{ue.current=ze}),j.setOnPlaybackComplete(()=>{ne(),y(!1),Z(null),ue.current=0,w(0)}),ee.current=j,x(e.waveformData.duration),d?.(),()=>{ne(),j.dispose()}},[e.source,e.waveformData,e.name,s,d,ne,Z]),m.useEffect(()=>{try{const j=k0(e.waveformData,O,0,0,Math.ceil(e.waveformData.duration*ae)),pe={clipId:"media-element-clip",trackName:e.name??"Track",peaks:{length:j.length,data:[j.data],bits:j.bits},startSample:0,durationSamples:Math.ceil(e.waveformData.duration*ae)};k([[pe]])}catch(j){console.warn("[waveform-playlist] Failed to extract peaks from waveform data:",j)}},[e.waveformData,e.name,O,ae]);const Te=m.useCallback(()=>{const j=()=>{const pe=ee.current?.getCurrentTime()??0;ue.current=pe;const ze=T.current;if(ze.length>0){const Ze=ze.find(q=>pe>=q.start&&pe<q.end);if(te.current)Ze&&Ze.id!==oe.current?Z(Ze.id):!Ze&&oe.current!==null&&Z(null);else if(oe.current){const q=ze.find(me=>me.id===oe.current);if(q&&pe>=q.end){ee.current?.stop(),y(!1);return}}else Ze&&Z(Ze.id)}if(le.current&&se.current){const Ze=se.current,q=pe*ae/ye.current,me=Ze.clientWidth,He=Math.max(0,q-me/2);Ze.scrollLeft=He}de(j)};de(j)},[Z,ae,de]),B=ne,$e=m.useCallback(j=>{if(!ee.current)return;const pe=j??ue.current;ee.current.play(void 0,pe),y(!0),Te()},[Te]),re=m.useCallback(()=>{ee.current&&(ee.current.pause(),y(!1),B(),w(ee.current.getCurrentTime()))},[B]),Ve=m.useCallback(()=>{ee.current&&(ee.current.stop(),y(!1),B(),ue.current=0,w(0),Z(null))},[B,Z]),ve=m.useCallback(j=>{const pe=Math.max(0,Math.min(j,_));ue.current=pe,w(pe),ee.current&&ee.current.seekTo(pe)},[_]),Re=m.useCallback(j=>{const pe=Math.max(.5,Math.min(2,j));I(pe),ee.current&&ee.current.setPlaybackRate(pe)},[]),ct=r?30:0,xt=m.useMemo(()=>({isPlaying:g,currentTime:b,currentTimeRef:ue}),[g,b]),st=m.useMemo(()=>({continuousPlay:R,annotations:M,activeAnnotationId:A,playbackRate:E,isAutomaticScroll:G}),[R,M,A,E,G]),je=m.useRef(p);je.current=p;const at=m.useCallback(j=>{const pe=typeof j=="function"?j(T.current):j;if(!je.current){process.env.NODE_ENV!=="production"&&console.warn("waveform-playlist: setAnnotations was called but no onAnnotationsChange callback is provided. Annotation edits will not persist. Pass onAnnotationsChange to MediaElementPlaylistProvider to handle annotation updates.");return}je.current(pe)},[]),ut=m.useMemo(()=>({play:$e,pause:re,stop:Ve,seekTo:ve,setPlaybackRate:Re,setContinuousPlay:fe,setAnnotations:at,setActiveAnnotationId:Z,setAutomaticScroll:j=>{Q(j)},setScrollContainer:Fe,scrollContainerRef:se}),[$e,re,Ve,ve,Re,fe,at,Z,Fe]),Mt=m.useMemo(()=>({duration:_,peaksDataArray:S,sampleRate:ae,waveHeight:n,timeScaleHeight:ct,samplesPerPixel:O,playoutRef:ee,controls:i,barWidth:c,barGap:u,progressBarWidth:v}),[_,S,ae,n,ct,O,i,c,u,v]),Ct={...Wd,...o};return C.jsx(P.ThemeProvider,{theme:Ct,children:C.jsx(vf.Provider,{value:xt,children:C.jsx(yf.Provider,{value:st,children:C.jsx(bf.Provider,{value:ut,children:C.jsx(wf.Provider,{value:Mt,children:h})})})})})},Vr=()=>{const e=m.useContext(vf);if(!e)throw new Error("useMediaElementAnimation must be used within MediaElementPlaylistProvider");return e},qs=()=>{const e=m.useContext(yf);if(!e)throw new Error("useMediaElementState must be used within MediaElementPlaylistProvider");return e},Si=()=>{const e=m.useContext(bf);if(!e)throw new Error("useMediaElementControls must be used within MediaElementPlaylistProvider");return e},Js=()=>{const e=m.useContext(wf);if(!e)throw new Error("useMediaElementData must be used within MediaElementPlaylistProvider");return e},ry=({className:e})=>{const{isPlaying:t,currentTimeRef:n}=tt(),{selectionStart:r,selectionEnd:s,isLoopEnabled:a}=nt(),{play:o}=Se(),i=async()=>{if(r!==s&&s>r&&!a){const c=s-r;await o(r,c)}else await o(n.current??0)};return C.jsx(gt,{onClick:i,disabled:t,className:e,children:"Play"})},sy=({className:e})=>{const{isPlaying:t}=tt(),{pause:n}=Se();return C.jsx(gt,{onClick:n,disabled:!t,className:e,children:"Pause"})},ay=({className:e})=>{const{isPlaying:t}=tt(),{stop:n}=Se();return C.jsx(gt,{onClick:n,disabled:!t,className:e,children:"Stop"})},oy=({className:e})=>{const{isPlaying:t}=tt(),{play:n,setCurrentTime:r}=Se(),s=()=>{r(0),t&&n(0)};return C.jsx(gt,{onClick:s,className:e,children:"Rewind"})},iy=({className:e})=>{const{isPlaying:t}=tt(),{play:n,setCurrentTime:r}=Se(),{duration:s}=rt(),a=()=>{r(s),t&&n(s)};return C.jsx(gt,{onClick:a,className:e,children:"Fast Forward"})},ly=({skipAmount:e=5,className:t})=>{const{currentTimeRef:n,isPlaying:r}=tt(),{play:s,setCurrentTime:a}=Se(),o=()=>{const i=Math.max(0,(n.current??0)-e);a(i),r&&s(i)};return C.jsx(gt,{onClick:o,className:t,children:"Skip Backward"})},cy=({skipAmount:e=5,className:t})=>{const{currentTimeRef:n,isPlaying:r}=tt(),{play:s,setCurrentTime:a}=Se(),{duration:o}=rt(),i=()=>{const l=Math.min(o,(n.current??0)+e);a(l),r&&s(l)};return C.jsx(gt,{onClick:i,className:t,children:"Skip Forward"})},uy=({className:e})=>{const{isLoopEnabled:t,loopStart:n,loopEnd:r}=nt(),{setLoopEnabled:s,setLoopRegion:a}=Se(),{duration:o}=rt(),i=n!==r&&r>n,l=()=>{if(!t&&!i){const c=Math.min(10,o*.25);a(0,Math.max(1,c))}s(!t)};return C.jsx(gt,{onClick:l,className:e,title:t?"Disable loop":"Enable loop",children:t?"Loop On":"Loop Off"})},dy=({className:e})=>{const{selectionStart:t,selectionEnd:n,loopStart:r,loopEnd:s}=nt(),{setLoopRegionFromSelection:a,clearLoopRegion:o}=Se(),i=t!==n&&n>t,l=r!==s&&s>r,c=()=>{l?o():a()};return C.jsx(gt,{onClick:c,disabled:!i&&!l,className:e,title:l?"Clear loop region":i?"Set loop region from selection":"Create a selection first",children:l?"Clear Loop":"Set Loop"})},fy=({onClearAll:e,label:t="Clear All",className:n})=>{const{stop:r}=Se(),s=m.useCallback(()=>{r(),e()},[r,e]);return C.jsx(gt,{onClick:s,className:n,title:"Remove all tracks",children:t})},hy=({className:e,disabled:t})=>{const{zoomIn:n}=Se(),{canZoomIn:r}=rt();return C.jsx(gt,{onClick:n,disabled:t||!r,className:e,children:"Zoom In"})},py=({className:e,disabled:t})=>{const{zoomOut:n}=Se(),{canZoomOut:r}=rt();return C.jsx(gt,{onClick:n,disabled:t||!r,className:e,children:"Zoom Out"})},my=({className:e})=>{const{masterVolume:t}=rt(),{setMasterVolume:n}=Se();return C.jsx(lv,{volume:t,onChange:n,className:e})},gy=({className:e})=>{const{timeFormat:t}=rt(),{setTimeFormat:n}=Se();return C.jsx(Hv,{value:t,onChange:n,className:e})},vy=P.span`
1004
+ `;let Y0=0;function K0(){let e;try{const r=new Blob([X0],{type:"application/javascript"}),s=URL.createObjectURL(r);e=new Worker(s),URL.revokeObjectURL(s)}catch(r){return console.warn("[waveform-playlist] Failed to create peaks worker (CSP restriction?):",r),{generate(){return Promise.reject(new Error("Worker creation failed"))},terminate(){}}}const t=new Map;let n=!1;return e.onmessage=r=>{const s=r.data,a=t.get(s.id);if(a)if(t.delete(s.id),s.error)a.reject(new Error(s.error));else try{const o=pt.create(s.buffer);a.resolve(o)}catch(o){a.reject(o)}},e.onerror=r=>{n=!0,e.terminate();for(const[,s]of t)s.reject(r.error??new Error(r.message));t.clear()},{generate(r){if(n)return Promise.reject(new Error("Worker terminated"));const s=String(++Y0);return new Promise((a,o)=>{t.set(s,{resolve:a,reject:o}),e.postMessage({id:s,scale:r.scale,bits:r.bits,amplitude_scale:1,split_channels:r.splitChannels,length:r.length,sample_rate:r.sampleRate,channels:r.channels},r.channels)})},terminate(){n=!0,e.terminate();for(const[,r]of t)r.reject(new Error("Worker terminated"));t.clear()}}}function q0(e,t){const[n,r]=m.useState(()=>new Map),[s,a]=m.useState(!1),o=m.useRef(null),i=m.useRef(new WeakMap),l=m.useRef(new WeakMap),c=m.useRef(new WeakMap),u=m.useRef(0),f=m.useCallback(()=>(o.current||(o.current=K0()),o.current),[]);return m.useEffect(()=>{let p=!1;const d=i.current,h=l.current,v=c.current,g=[],y=new Map;for(const w of e)for(const _ of w.clips){if(!_.audioBuffer||_.waveformData)continue;const x=d.get(_.audioBuffer);if(x){g.push({clipId:_.id,waveformData:x});continue}if(h.get(_.audioBuffer)){const k=v.get(_.audioBuffer);k?k.add(_.id):v.set(_.audioBuffer,new Set([_.id]));continue}const S=y.get(_.audioBuffer);S?S.add(_.id):y.set(_.audioBuffer,new Set([_.id]))}if(g.length>0&&r(w=>{const _=new Map(w);for(const x of g)_.set(x.clipId,x.waveformData);return _}),y.size===0)return;u.current+=y.size,a(!0);const b=f();for(const[w,_]of y){v.set(w,new Set(_));const x=[];for(let E=0;E<w.numberOfChannels;E++)x.push(w.getChannelData(E).slice().buffer);const S=`buffer-${Math.random().toString(36).slice(2,11)}`,k=b.generate({id:S,channels:x,length:w.length,sampleRate:w.sampleRate,scale:t,bits:16,splitChannels:!0}).then(E=>{d.set(w,E);const I=v.get(w)??new Set;v.delete(w),h.delete(w),!p&&(r(M=>{const T=new Map(M);for(const A of I)T.set(A,E);return T}),u.current--,u.current<=0&&(u.current=0,a(!1)))}).catch(E=>{v.delete(w),h.delete(w),!p&&(console.warn("[waveform-playlist] Worker peak generation failed:",E),u.current--,u.current<=0&&(u.current=0,a(!1)))});h.set(w,k)}return()=>{p=!0,l.current=new WeakMap,c.current=new WeakMap,u.current=0,a(!1)}},[e,t,f]),m.useEffect(()=>()=>{o.current?.terminate(),o.current=null},[]),{cache:n,isGenerating:s}}function uo(e){return e instanceof File?e.name.replace(/\.[^/.]+$/,""):e instanceof Blob?"Untitled":typeof e=="string"?e.split("/").pop()?.replace(/\.[^/.]+$/,"")??"Untitled":e.name??e.src.split("/").pop()?.replace(/\.[^/.]+$/,"")??"Untitled"}async function J0(e,t,n){const r=uo(e);if(e instanceof Blob){const l=await e.arrayBuffer();return n?.throwIfAborted(),{audioBuffer:await t.decodeAudioData(l),name:r}}const s=typeof e=="string"?e:e.src,a=await fetch(s,{signal:n});if(!a.ok)throw new Error(`Failed to fetch ${s}: ${a.statusText}`);const o=await a.arrayBuffer();return n?.throwIfAborted(),{audioBuffer:await t.decodeAudioData(o),name:r}}function Q0(){const[e,t]=m.useState([]),[n,r]=m.useState(0),[s,a]=m.useState([]),o=m.useRef(!1),i=m.useRef(new Set),l=m.useRef(new Map);m.useEffect(()=>{const f=l.current;return()=>{o.current=!0;for(const p of f.values())p.abort();f.clear()}},[]);const c=m.useCallback(f=>{if(f.length===0)return;const p=gh(),d=f.map(h=>({track:dc({name:`${uo(h)} (loading...)`,clips:[]}),source:h}));t(h=>[...h,...d.map(v=>v.track)]),r(h=>h+f.length);for(const{track:h,source:v}of d){i.current.add(h.id);const g=new AbortController;l.current.set(h.id,g),(async()=>{try{const{audioBuffer:y,name:b}=await J0(v,p,g.signal),w=uc({audioBuffer:y,startTime:0,duration:y.duration,offset:0,name:b});!o.current&&i.current.has(h.id)&&t(_=>_.map(x=>x.id===h.id?{...x,name:b,clips:[w]}:x))}catch(y){if(y instanceof DOMException&&y.name==="AbortError")return;console.warn("[waveform-playlist] Error loading audio:",y),!o.current&&i.current.has(h.id)&&(t(b=>b.filter(w=>w.id!==h.id)),a(b=>[...b,{name:uo(v),error:y instanceof Error?y:new Error(String(y))}]))}finally{l.current.delete(h.id),!o.current&&i.current.delete(h.id)&&r(y=>y-1)}})()}},[]),u=m.useCallback(f=>{t(d=>d.filter(h=>h.id!==f));const p=l.current.get(f);p&&(p.abort(),l.current.delete(f)),i.current.delete(f)&&r(d=>d-1)},[]);return{tracks:e,addTracks:c,removeTrack:u,loadingCount:n,isLoading:n>0,errors:s}}const hf=m.createContext(null),pf=m.createContext(null),mf=m.createContext(null),gf=m.createContext(null),ey=({tracks:e,timescale:t=!1,mono:n=!1,waveHeight:r=80,samplesPerPixel:s=1024,zoomLevels:a,automaticScroll:o=!1,theme:i,controls:l={show:!1,width:0},annotationList:c,effects:u,onReady:f,onAnnotationUpdate:p,onAnnotationsChange:d,barWidth:h=1,barGap:v=0,progressBarWidth:g,onTracksChange:y,soundFontCache:b,deferEngineRebuild:w=!1,children:_})=>{const x=g??h+v,S=m.useMemo(()=>a,[a?.join(",")]),k=m.useMemo(()=>{if(!c?.annotations)return[];if(process.env.NODE_ENV!=="production"&&c.annotations.length>0){const V=c.annotations[0];if(typeof V.start!="number"||typeof V.end!="number")return console.error("[waveform-playlist] Annotations must have numeric start/end values. In v6, use parseAeneas() from @waveform-playlist/annotations before passing annotations. Received start type: "+typeof V.start),[]}return c.annotations},[c?.annotations]),E=m.useRef(k);E.current=k;const[I,M]=m.useState(null),[T,A]=m.useState(!1),[$,R]=m.useState(0),[F,O]=m.useState(0),[G,Q]=m.useState([]),[ee,ue]=m.useState([]),[te,oe]=m.useState([]),[se,le]=m.useState(o),[ye,de]=m.useState(c?.isContinuousPlay??!1),[ne,Z]=m.useState(c?.linkEndpoints??!1),[fe,Fe]=m.useState(c?.editable??!1),[ae,Te]=m.useState(!1),B=m.useRef(null),$e=m.useRef(!1),re=m.useRef(!1);re.current=T;const Ve=m.useRef(0),ve=m.useRef(0),Re=m.useRef(e),ct=m.useRef(b);ct.current=b;const xt=m.useRef(te),st=m.useRef(0),je=m.useRef(0),at=m.useRef(null),ut=m.useRef(null),Mt=m.useRef(!1),Ct=m.useRef(c?.isContinuousPlay??!1),j=m.useRef(null),pe=m.useRef(null),ze=m.useRef(0),Ze=m.useRef(!1),q=m.useRef(!1),me=m.useRef(s),He=m.useRef(44100),{timeFormat:St,setTimeFormat:N,formatTime:U}=tf(),H=nf({engineRef:B,initialSamplesPerPixel:s}),{samplesPerPixel:X,onEngineState:ke}=H,Me=rf({engineRef:B,initialVolume:1}),{masterVolume:Y,setMasterVolume:Be,masterVolumeRef:Xe,onEngineState:Ge}=Me,{selectionStart:kt,selectionEnd:Nt,setSelection:wn,selectionStartRef:Dt,selectionEndRef:jr,onEngineState:Mi}=E0({engineRef:B}),{isLoopEnabled:Ai,loopStart:Ti,loopEnd:$i,setLoopEnabled:Ri,setLoopRegion:zr,clearLoopRegion:Di,isLoopEnabledRef:Pi,loopStartRef:Fi,loopEndRef:Oi,onEngineState:Li}=I0({engineRef:B}),{selectedTrackId:Bi,setSelectedTrackId:Wi,onEngineState:Vi,selectedTrackIdRef:Ni}=M0({engineRef:B}),{animationFrameRef:ji,startAnimationFrameLoop:ta,stopAnimationFrameLoop:Zr}=ff(),jf=m.useMemo(()=>Math.min(...S??[256,512,1024,2048,4096,8192]),[S]),{cache:zi}=q0(e,jf),Zi=m.useCallback(V=>{Ct.current=V,de(V)},[]),Pt=m.useCallback(V=>{j.current=V,M(V)},[]),Hi=m.useCallback(()=>{const V=Dt.current??0,z=jr.current??0;V!==z&&z>V&&zr(V,z)},[zr,Dt,jr]);m.useEffect(()=>{Mt.current=se},[se]),m.useEffect(()=>{xt.current=te},[te]),Re.current=e;const na=e===pe.current;Ze.current=na||q.current,m.useEffect(()=>{if(!ut.current||F===0)return;const V=ut.current,z=me.current,he=X;if(z===he)return;const W=V.clientWidth,Ee=V.scrollLeft+W/2,Ce=He.current,oa=Ee*z/Ce*Ce/he,Xr=Math.max(0,oa-W/2);V.scrollLeft=Xr,me.current=he},[X,F]);const Hr=m.useRef(null);m.useEffect(()=>{if(na||q.current){na&&(pe.current=null);let W=0;e.forEach(_e=>{_e.clips.forEach(Ee=>{const Ce=(Ee.startSample+Ee.durationSamples)/Ee.sampleRate;W=Math.max(W,Ce)})}),O(W);return}if(w){let W=0;e.forEach(_e=>{_e.clips.forEach(Ee=>{const Ce=(Ee.startSample+Ee.durationSamples)/Ee.sampleRate;W=Math.max(W,Ce)})}),O(W);return}if(Te(!1),e.length===0){Q([]),O(0),oe([]),ue([]),B.current&&(B.current.dispose(),B.current=null);return}const V=re.current,z=ve.current;return B.current&&V&&(B.current.stop(),Zr(),Hr.current={position:z}),(async()=>{try{const W=[];e.forEach(Ie=>{Ie.clips.length>0&&Ie.clips[0].audioBuffer&&W.push(Ie.clips[0].audioBuffer)});let _e=0;e.forEach(Ie=>{Ie.clips.forEach(ft=>{const jt=ft.sampleRate,Yf=(ft.startSample+ft.durationSamples)/jt;_e=Math.max(_e,Yf)})}),Q(W),O(_e),oe(Ie=>Ie.length===e.length?Ie.map((ft,jt)=>({...ft,name:e[jt].name})):e.map(ft=>({name:ft.name,muted:ft.muted,soloed:ft.soloed,volume:ft.volume,pan:ft.pan}))),B.current&&B.current.dispose(),ze.current=0,pe.current=null,$e.current=!1;const Ee=vh({effects:u,soundFontCache:ct.current}),Ce=new Sh({adapter:Ee,samplesPerPixel:me.current,zoomLevels:S});Ce.setSelection(Dt.current??0,jr.current??0),Ce.setLoopRegion(Fi.current??0,Oi.current??0),Pi.current&&Ce.setLoopEnabled(!0),Ce.setMasterVolume(Xe.current??1),Ni.current&&Ce.selectTrack(Ni.current);const Ur=xt.current,oa=e.map((Ie,ft)=>{const jt=Ur[ft];return{...Ie,volume:jt?.volume??Ie.volume,muted:jt?.muted??Ie.muted,soloed:jt?.soloed??Ie.soloed,pan:jt?.pan??Ie.pan}});let Xr=!0;Ce.on("statechange",Ie=>{Mi(Ie),Li(Ie),Vi(Ie),ke(Ie),Ge(Ie),!Xr&&Ie.tracksVersion!==ze.current&&(ze.current=Ie.tracksVersion,pe.current=Ie.tracks,y?y(Ie.tracks):console.warn("[waveform-playlist] Engine tracks changed but onTracksChange prop is not set — UI will revert on next render. Pass onTracksChange to WaveformPlaylistProvider."))}),Ce.setTracks(oa),Xr=!1,ze.current=Ce.getState().tracksVersion,B.current=Ce,Te(!0);const Xf=new CustomEvent("waveform-playlist:ready",{detail:{trackCount:e.length,duration:_e}});window.dispatchEvent(Xf),f?.()}catch(W){console.error("Error loading audio:",W)}})(),()=>{if(Ze.current){Ze.current=!1;return}Zr(),B.current&&B.current.dispose()}},[e,f,u,Zr,Mi,Li,Vi,ke,Ge,y,Xe,Dt,jr,Fi,Oi,Pi,S,b,w]),m.useEffect(()=>{if(e.length===0)return;const V=e.map(z=>z.clips.map(W=>{let _e;if(W.waveformData)try{_e=Ql(W.waveformData,X,n,W.offsetSamples,W.durationSamples)}catch(Ee){console.warn("[waveform-playlist] Failed to extract peaks from waveformData:",Ee)}if(!_e){const Ee=zi.get(W.id);if(Ee)try{_e=Ql(Ee,X,n,W.offsetSamples,W.durationSamples)}catch(Ce){console.warn("[waveform-playlist] Failed to extract peaks from cache:",Ce)}}if(!_e){!w&&!W.audioBuffer&&!W.waveformData&&!W.midiNotes&&console.warn(`[waveform-playlist] Clip "${W.id}" has no audio data or waveform data`);const Ee=n?1:W.audioBuffer?.numberOfChannels??1,Ce=W.midiNotes?Math.ceil(W.durationSamples/X):0;_e={length:Ce,data:Array.from({length:Ee},()=>new Int16Array(Ce*2)),bits:16}}return{clipId:W.id,trackName:z.name,peaks:_e,startSample:W.startSample,durationSamples:W.durationSamples,fadeIn:W.fadeIn,fadeOut:W.fadeOut,midiNotes:W.midiNotes,sampleRate:W.sampleRate,offsetSamples:W.offsetSamples}}));ue(V)},[e,X,n,zi,w]);const Gi=m.useRef(!1),_n=m.useCallback(()=>{if(B.current)return B.current.getCurrentTime();Gi.current||(Gi.current=!0,console.warn("[waveform-playlist] getPlaybackTime called without engine. Falling back to manual elapsed time (loop wrapping will not work)."));const V=L.getContext().currentTime-(st.current??0);return(je.current??0)+V},[]),Qt=m.useCallback(()=>{const V=()=>{const z=_n();ve.current=z;const he=E.current;if(he.length>0){const W=he.find(_e=>z>=_e.start&&z<_e.end);if(Ct.current)W&&W.id!==j.current?Pt(W.id):!W&&j.current!==null&&Pt(null);else if(j.current){const _e=he.find(Ee=>Ee.id===j.current);if(_e&&z>=_e.end){B.current&&B.current.stop(),A(!1),ve.current=Ve.current,R(Ve.current);return}}else W&&Pt(W.id)}if(Mt.current&&ut.current&&F>0){const W=ut.current,_e=He.current,Ee=z*_e/me.current,Ce=W.clientWidth,Ur=Math.max(0,Ee-Ce/2);W.scrollLeft=Ur}if(at.current!==null&&z>=at.current){B.current&&B.current.stop(),A(!1),ve.current=at.current,R(at.current),at.current=null;return}if(z>=F){B.current&&B.current.stop(),A(!1),ve.current=Ve.current,R(Ve.current),Pt(null);return}ta(V)};ta(V)},[F,Pt,ta,_n]),dt=Zr;m.useEffect(()=>{(async()=>{if(T&&ji.current&&B.current)if(ye){const z=ve.current;B.current.stop(),dt();const W=L.getContext().currentTime;st.current=W,je.current=z,B.current.play(z),Qt()}else dt(),Qt()})().catch(z=>{console.warn("[waveform-playlist] Failed to reschedule playback:",z),A(!1),dt()})},[ye,T,Qt,dt,ji]),m.useEffect(()=>{(async()=>{if(Hr.current&&B.current){const{position:z}=Hr.current;Hr.current=null;const W=L.getContext().currentTime;st.current=W,je.current=z,$e.current||(await B.current.init(),$e.current=!0),B.current.play(z),A(!0),Qt()}})().catch(z=>{console.warn("[waveform-playlist] Failed to resume playback after track change:",z),A(!1),dt()})},[e,Qt,dt]);const Gr=m.useCallback(async(V,z)=>{if(!B.current||F===0)return;const he=V??ve.current;Ve.current=he,ve.current=he,B.current.stop(),B.current.seek(he),dt();const _e=L.getContext().currentTime;st.current=_e,je.current=he,at.current=z!==void 0?he+z:null,$e.current||(await B.current.init(),$e.current=!0);const Ee=z!==void 0?he+z:void 0;try{B.current.play(he,Ee)}catch(Ce){console.warn("[waveform-playlist] Playback failed to start:",Ce),dt();return}A(!0),Qt()},[F,Qt,dt]),Ui=m.useCallback(()=>{if(!B.current)return;const V=_n();B.current.pause(),A(!1),dt(),ve.current=V,R(V)},[dt,_n]),Xi=m.useCallback(()=>{B.current&&(B.current.stop(),A(!1),dt(),ve.current=Ve.current,R(Ve.current),Pt(null))},[dt,Pt]),Yi=m.useCallback(V=>{const z=Math.max(0,Math.min(V,F));ve.current=z,R(z),T&&B.current&&Gr(z)},[F,T,Gr]),Ki=m.useCallback((V,z)=>{const he=Re.current[V]?.id;if(!he)return;const W=[...te];W[V]={...W[V],muted:z},oe(W),B.current&&B.current.setTrackMute(he,z)},[te]),qi=m.useCallback((V,z)=>{const he=Re.current[V]?.id;if(!he)return;const W=[...te];W[V]={...W[V],soloed:z},oe(W),B.current&&B.current.setTrackSolo(he,z)},[te]),Ji=m.useCallback((V,z)=>{const he=Re.current[V]?.id;if(!he)return;const W=[...te];W[V]={...W[V],volume:z},oe(W),B.current&&B.current.setTrackVolume(he,z)},[te]),Qi=m.useCallback((V,z)=>{const he=Re.current[V]?.id;if(!he)return;const W=[...te];W[V]={...W[V],pan:z},oe(W),B.current&&B.current.setTrackPan(he,z)},[te]),el=m.useCallback((V,z)=>{wn(V,z),ve.current=V,R(V),T&&B.current&&(B.current.stop(),B.current.seek(V),B.current.play(V))},[T,wn]),tl=m.useCallback(V=>{ut.current=V},[]),ra=m.useRef(d);ra.current=d;const nl=m.useCallback(V=>{const z=typeof V=="function"?V(E.current):V;if(!ra.current){process.env.NODE_ENV!=="production"&&console.warn("waveform-playlist: setAnnotations was called but no onAnnotationsChange callback is provided. Annotation edits will not persist. Pass onAnnotationsChange to WaveformPlaylistProvider to handle annotation updates.");return}ra.current(z)},[]),sa=G[0]?.sampleRate||e[0]?.clips[0]?.sampleRate||44100;He.current=sa;const aa=t?30:0,rl=e.length*r+aa,zf=m.useMemo(()=>({isPlaying:T,currentTime:$,currentTimeRef:ve,playbackStartTimeRef:st,audioStartPositionRef:je,getPlaybackTime:_n}),[T,$,ve,st,je,_n]),Zf=m.useMemo(()=>({continuousPlay:ye,linkEndpoints:ne,annotationsEditable:fe,isAutomaticScroll:se,isLoopEnabled:Ai,annotations:k,activeAnnotationId:I,selectionStart:kt,selectionEnd:Nt,selectedTrackId:Bi,loopStart:Ti,loopEnd:$i}),[ye,ne,fe,se,Ai,k,I,kt,Nt,Bi,Ti,$i]),sl=m.useCallback(V=>{ve.current=V,R(V)},[ve]),al=m.useCallback(V=>{le(V)},[]),Hf=m.useMemo(()=>({play:Gr,pause:Ui,stop:Xi,seekTo:Yi,setCurrentTime:sl,setTrackMute:Ki,setTrackSolo:qi,setTrackVolume:Ji,setTrackPan:Qi,setSelection:el,setSelectedTrackId:Wi,setTimeFormat:N,formatTime:U,zoomIn:H.zoomIn,zoomOut:H.zoomOut,setMasterVolume:Be,setAutomaticScroll:al,setScrollContainer:tl,scrollContainerRef:ut,setContinuousPlay:Zi,setLinkEndpoints:Z,setAnnotationsEditable:Fe,setAnnotations:nl,setActiveAnnotationId:Pt,setLoopEnabled:Ri,setLoopRegion:zr,setLoopRegionFromSelection:Hi,clearLoopRegion:Di}),[Gr,Ui,Xi,Yi,sl,Ki,qi,Ji,Qi,el,Wi,N,U,H.zoomIn,H.zoomOut,Be,al,tl,ut,Zi,Z,Fe,nl,Pt,Ri,zr,Hi,Di]),Gf=m.useMemo(()=>({duration:F,audioBuffers:G,peaksDataArray:ee,trackStates:te,tracks:e,sampleRate:sa,waveHeight:r,timeScaleHeight:aa,minimumPlaylistHeight:rl,controls:l,playoutRef:B,samplesPerPixel:X,timeFormat:St,masterVolume:Y,canZoomIn:H.canZoomIn,canZoomOut:H.canZoomOut,barWidth:h,barGap:v,progressBarWidth:x,isReady:ae,mono:n,isDraggingRef:q,onTracksChange:y}),[F,G,ee,te,e,sa,r,aa,rl,l,B,X,St,Y,H.canZoomIn,H.canZoomOut,h,v,x,ae,n,q,y]),Uf={...Wd,...i};return C.jsx(P.ThemeProvider,{theme:Uf,children:C.jsx(hf.Provider,{value:zf,children:C.jsx(pf.Provider,{value:Zf,children:C.jsx(mf.Provider,{value:Hf,children:C.jsx(gf.Provider,{value:Gf,children:_})})})})})},tt=()=>{const e=m.useContext(hf);if(!e)throw new Error("usePlaybackAnimation must be used within WaveformPlaylistProvider");return e},nt=()=>{const e=m.useContext(pf);if(!e)throw new Error("usePlaylistState must be used within WaveformPlaylistProvider");return e},Se=()=>{const e=m.useContext(mf);if(!e)throw new Error("usePlaylistControls must be used within WaveformPlaylistProvider");return e},rt=()=>{const e=m.useContext(gf);if(!e)throw new Error("usePlaylistData must be used within WaveformPlaylistProvider");return e};var ty=class{constructor(e){this._playbackRate=1,this.handleEnded=()=>{this.onStopCallback&&this.onStopCallback()},this.handleTimeUpdate=()=>{this.onTimeUpdateCallback&&this.onTimeUpdateCallback(this.audioElement.currentTime)},this._peaks=e.peaks,this._id=e.id??`track-${Date.now()}`,this._name=e.name??"Track",this._playbackRate=e.playbackRate??1,typeof e.source=="string"?(this.audioElement=new Audio(e.source),this.ownsElement=!0):(this.audioElement=e.source,this.ownsElement=!1),this.audioElement.preload="auto",this.audioElement.volume=e.volume??1,this.audioElement.playbackRate=this._playbackRate;const t=this.audioElement;"preservesPitch"in this.audioElement?t.preservesPitch=!0:"mozPreservesPitch"in this.audioElement?t.mozPreservesPitch=!0:"webkitPreservesPitch"in this.audioElement&&(t.webkitPreservesPitch=!0),this.audioElement.addEventListener("ended",this.handleEnded),this.audioElement.addEventListener("timeupdate",this.handleTimeUpdate)}play(e=0){this.audioElement.currentTime=e,this.audioElement.play().catch(t=>{console.warn("MediaElementTrack: play() failed:",t)})}pause(){this.audioElement.pause()}stop(){this.audioElement.pause(),this.audioElement.currentTime=0}seekTo(e){this.audioElement.currentTime=Math.max(0,Math.min(e,this.duration))}setVolume(e){this.audioElement.volume=Math.max(0,Math.min(1,e))}setPlaybackRate(e){const t=Math.max(.5,Math.min(2,e));this._playbackRate=t,this.audioElement.playbackRate=t}setMuted(e){this.audioElement.muted=e}setOnStopCallback(e){this.onStopCallback=e}setOnTimeUpdateCallback(e){this.onTimeUpdateCallback=e}dispose(){this.audioElement.removeEventListener("ended",this.handleEnded),this.audioElement.removeEventListener("timeupdate",this.handleTimeUpdate),this.audioElement.pause(),this.ownsElement&&(this.audioElement.src="",this.audioElement.load())}get id(){return this._id}get name(){return this._name}get peaks(){return this._peaks}get currentTime(){return this.audioElement.currentTime}get duration(){return this.audioElement.duration||this._peaks.duration}get isPlaying(){return!this.audioElement.paused&&!this.audioElement.ended}get volume(){return this.audioElement.volume}get playbackRate(){return this._playbackRate}get muted(){return this.audioElement.muted}get element(){return this.audioElement}},ny=class{constructor(e={}){this.track=null,this._isPlaying=!1,this._masterVolume=e.masterVolume??1,this._playbackRate=e.playbackRate??1}async init(){}addTrack(e){return this.track&&(console.warn("MediaElementPlayout: Only one track is supported. Disposing previous track. For multi-track, use TonePlayout."),this.track.dispose()),this.track=new ty({...e,volume:this._masterVolume*(e.volume??1),playbackRate:this._playbackRate}),this.track.setOnStopCallback(()=>{this._isPlaying=!1,this.onPlaybackCompleteCallback&&this.onPlaybackCompleteCallback()}),this.track}removeTrack(e){this.track&&this.track.id===e&&(this.track.dispose(),this.track=null)}getTrack(e){if(this.track&&this.track.id===e)return this.track}play(e,t,n){if(!this.track){console.warn("MediaElementPlayout: No track to play");return}const r=t??0;if(this._isPlaying=!0,this.track.play(r),n!==void 0){const s=n/this._playbackRate;setTimeout(()=>{this._isPlaying&&(this.pause(),this.onPlaybackCompleteCallback&&this.onPlaybackCompleteCallback())},s*1e3)}}pause(){this.track&&this.track.pause(),this._isPlaying=!1}stop(){this.track&&this.track.stop(),this._isPlaying=!1}seekTo(e){this.track&&this.track.seekTo(e)}getCurrentTime(){return this.track?this.track.currentTime:0}setMasterVolume(e){this._masterVolume=Math.max(0,Math.min(1,e)),this.track&&this.track.setVolume(this._masterVolume)}setPlaybackRate(e){this._playbackRate=Math.max(.5,Math.min(2,e)),this.track&&this.track.setPlaybackRate(this._playbackRate)}setMute(e,t){const n=this.getTrack(e);n&&n.setMuted(t)}setSolo(e,t){console.warn("MediaElementPlayout: Solo is not applicable for single-track playback")}setOnPlaybackComplete(e){this.onPlaybackCompleteCallback=e}dispose(){this.track&&(this.track.dispose(),this.track=null)}get isPlaying(){return this._isPlaying}get masterVolume(){return this._masterVolume}get playbackRate(){return this._playbackRate}get duration(){return this.track?.duration??0}get sampleRate(){return this.track?.peaks.sample_rate??44100}};const vf=m.createContext(null),yf=m.createContext(null),bf=m.createContext(null),wf=m.createContext(null),ry=({track:e,samplesPerPixel:t=1024,waveHeight:n=100,timescale:r=!1,playbackRate:s=1,automaticScroll:a=!1,theme:o,controls:i={show:!1,width:0},annotationList:l,barWidth:c=1,barGap:u=0,progressBarWidth:f,onAnnotationsChange:p,onReady:d,children:h})=>{const v=f??c+u,[g,y]=m.useState(!1),[b,w]=m.useState(0),[_,x]=m.useState(0),[S,k]=m.useState([]),[E,I]=m.useState(s),M=m.useMemo(()=>{if(!l?.annotations)return[];if(process.env.NODE_ENV!=="production"&&l.annotations.length>0){const j=l.annotations[0];if(typeof j.start!="number"||typeof j.end!="number")return console.error("[waveform-playlist] Annotations must have numeric start/end values. In v6, use parseAeneas() from @waveform-playlist/annotations before passing annotations. Received start type: "+typeof j.start),[]}return l.annotations},[l?.annotations]),T=m.useRef(M);T.current=M;const[A,$]=m.useState(null),[R,F]=m.useState(l?.isContinuousPlay??!1),[O]=m.useState(t),[G,Q]=m.useState(a),ee=m.useRef(null),ue=m.useRef(0),te=m.useRef(R),oe=m.useRef(null),se=m.useRef(null),le=m.useRef(a),ye=m.useRef(t),{startAnimationFrameLoop:de,stopAnimationFrameLoop:ne}=ff();m.useEffect(()=>{te.current=R},[R]),m.useEffect(()=>{le.current=G},[G]);const Z=m.useCallback(j=>{oe.current=j,$(j)},[]),fe=m.useCallback(j=>{te.current=j,F(j)},[]),Fe=m.useCallback(j=>{se.current=j},[]),ae=e.waveformData.sample_rate;m.useEffect(()=>{const j=new ny({playbackRate:s});j.addTrack({source:e.source,peaks:e.waveformData,name:e.name});const pe=j.getTrack(j.track?.id??"");return pe&&pe.setOnTimeUpdateCallback(ze=>{ue.current=ze}),j.setOnPlaybackComplete(()=>{ne(),y(!1),Z(null),ue.current=0,w(0)}),ee.current=j,x(e.waveformData.duration),d?.(),()=>{ne(),j.dispose()}},[e.source,e.waveformData,e.name,s,d,ne,Z]),m.useEffect(()=>{try{const j=k0(e.waveformData,O,0,0,Math.ceil(e.waveformData.duration*ae)),pe={clipId:"media-element-clip",trackName:e.name??"Track",peaks:{length:j.length,data:[j.data],bits:j.bits},startSample:0,durationSamples:Math.ceil(e.waveformData.duration*ae)};k([[pe]])}catch(j){console.warn("[waveform-playlist] Failed to extract peaks from waveform data:",j)}},[e.waveformData,e.name,O,ae]);const Te=m.useCallback(()=>{const j=()=>{const pe=ee.current?.getCurrentTime()??0;ue.current=pe;const ze=T.current;if(ze.length>0){const Ze=ze.find(q=>pe>=q.start&&pe<q.end);if(te.current)Ze&&Ze.id!==oe.current?Z(Ze.id):!Ze&&oe.current!==null&&Z(null);else if(oe.current){const q=ze.find(me=>me.id===oe.current);if(q&&pe>=q.end){ee.current?.stop(),y(!1);return}}else Ze&&Z(Ze.id)}if(le.current&&se.current){const Ze=se.current,q=pe*ae/ye.current,me=Ze.clientWidth,He=Math.max(0,q-me/2);Ze.scrollLeft=He}de(j)};de(j)},[Z,ae,de]),B=ne,$e=m.useCallback(j=>{if(!ee.current)return;const pe=j??ue.current;ee.current.play(void 0,pe),y(!0),Te()},[Te]),re=m.useCallback(()=>{ee.current&&(ee.current.pause(),y(!1),B(),w(ee.current.getCurrentTime()))},[B]),Ve=m.useCallback(()=>{ee.current&&(ee.current.stop(),y(!1),B(),ue.current=0,w(0),Z(null))},[B,Z]),ve=m.useCallback(j=>{const pe=Math.max(0,Math.min(j,_));ue.current=pe,w(pe),ee.current&&ee.current.seekTo(pe)},[_]),Re=m.useCallback(j=>{const pe=Math.max(.5,Math.min(2,j));I(pe),ee.current&&ee.current.setPlaybackRate(pe)},[]),ct=r?30:0,xt=m.useMemo(()=>({isPlaying:g,currentTime:b,currentTimeRef:ue}),[g,b]),st=m.useMemo(()=>({continuousPlay:R,annotations:M,activeAnnotationId:A,playbackRate:E,isAutomaticScroll:G}),[R,M,A,E,G]),je=m.useRef(p);je.current=p;const at=m.useCallback(j=>{const pe=typeof j=="function"?j(T.current):j;if(!je.current){process.env.NODE_ENV!=="production"&&console.warn("waveform-playlist: setAnnotations was called but no onAnnotationsChange callback is provided. Annotation edits will not persist. Pass onAnnotationsChange to MediaElementPlaylistProvider to handle annotation updates.");return}je.current(pe)},[]),ut=m.useMemo(()=>({play:$e,pause:re,stop:Ve,seekTo:ve,setPlaybackRate:Re,setContinuousPlay:fe,setAnnotations:at,setActiveAnnotationId:Z,setAutomaticScroll:j=>{Q(j)},setScrollContainer:Fe,scrollContainerRef:se}),[$e,re,Ve,ve,Re,fe,at,Z,Fe]),Mt=m.useMemo(()=>({duration:_,peaksDataArray:S,sampleRate:ae,waveHeight:n,timeScaleHeight:ct,samplesPerPixel:O,playoutRef:ee,controls:i,barWidth:c,barGap:u,progressBarWidth:v}),[_,S,ae,n,ct,O,i,c,u,v]),Ct={...Wd,...o};return C.jsx(P.ThemeProvider,{theme:Ct,children:C.jsx(vf.Provider,{value:xt,children:C.jsx(yf.Provider,{value:st,children:C.jsx(bf.Provider,{value:ut,children:C.jsx(wf.Provider,{value:Mt,children:h})})})})})},Vr=()=>{const e=m.useContext(vf);if(!e)throw new Error("useMediaElementAnimation must be used within MediaElementPlaylistProvider");return e},qs=()=>{const e=m.useContext(yf);if(!e)throw new Error("useMediaElementState must be used within MediaElementPlaylistProvider");return e},Si=()=>{const e=m.useContext(bf);if(!e)throw new Error("useMediaElementControls must be used within MediaElementPlaylistProvider");return e},Js=()=>{const e=m.useContext(wf);if(!e)throw new Error("useMediaElementData must be used within MediaElementPlaylistProvider");return e},sy=({className:e})=>{const{isPlaying:t,currentTimeRef:n}=tt(),{selectionStart:r,selectionEnd:s,isLoopEnabled:a}=nt(),{play:o}=Se(),i=async()=>{if(r!==s&&s>r&&!a){const c=s-r;await o(r,c)}else await o(n.current??0)};return C.jsx(gt,{onClick:i,disabled:t,className:e,children:"Play"})},ay=({className:e})=>{const{isPlaying:t}=tt(),{pause:n}=Se();return C.jsx(gt,{onClick:n,disabled:!t,className:e,children:"Pause"})},oy=({className:e})=>{const{isPlaying:t}=tt(),{stop:n}=Se();return C.jsx(gt,{onClick:n,disabled:!t,className:e,children:"Stop"})},iy=({className:e})=>{const{isPlaying:t}=tt(),{play:n,setCurrentTime:r}=Se(),s=()=>{r(0),t&&n(0)};return C.jsx(gt,{onClick:s,className:e,children:"Rewind"})},ly=({className:e})=>{const{isPlaying:t}=tt(),{play:n,setCurrentTime:r}=Se(),{duration:s}=rt(),a=()=>{r(s),t&&n(s)};return C.jsx(gt,{onClick:a,className:e,children:"Fast Forward"})},cy=({skipAmount:e=5,className:t})=>{const{currentTimeRef:n,isPlaying:r}=tt(),{play:s,setCurrentTime:a}=Se(),o=()=>{const i=Math.max(0,(n.current??0)-e);a(i),r&&s(i)};return C.jsx(gt,{onClick:o,className:t,children:"Skip Backward"})},uy=({skipAmount:e=5,className:t})=>{const{currentTimeRef:n,isPlaying:r}=tt(),{play:s,setCurrentTime:a}=Se(),{duration:o}=rt(),i=()=>{const l=Math.min(o,(n.current??0)+e);a(l),r&&s(l)};return C.jsx(gt,{onClick:i,className:t,children:"Skip Forward"})},dy=({className:e})=>{const{isLoopEnabled:t,loopStart:n,loopEnd:r}=nt(),{setLoopEnabled:s,setLoopRegion:a}=Se(),{duration:o}=rt(),i=n!==r&&r>n,l=()=>{if(!t&&!i){const c=Math.min(10,o*.25);a(0,Math.max(1,c))}s(!t)};return C.jsx(gt,{onClick:l,className:e,title:t?"Disable loop":"Enable loop",children:t?"Loop On":"Loop Off"})},fy=({className:e})=>{const{selectionStart:t,selectionEnd:n,loopStart:r,loopEnd:s}=nt(),{setLoopRegionFromSelection:a,clearLoopRegion:o}=Se(),i=t!==n&&n>t,l=r!==s&&s>r,c=()=>{l?o():a()};return C.jsx(gt,{onClick:c,disabled:!i&&!l,className:e,title:l?"Clear loop region":i?"Set loop region from selection":"Create a selection first",children:l?"Clear Loop":"Set Loop"})},hy=({onClearAll:e,label:t="Clear All",className:n})=>{const{stop:r}=Se(),s=m.useCallback(()=>{r(),e()},[r,e]);return C.jsx(gt,{onClick:s,className:n,title:"Remove all tracks",children:t})},py=({className:e,disabled:t})=>{const{zoomIn:n}=Se(),{canZoomIn:r}=rt();return C.jsx(gt,{onClick:n,disabled:t||!r,className:e,children:"Zoom In"})},my=({className:e,disabled:t})=>{const{zoomOut:n}=Se(),{canZoomOut:r}=rt();return C.jsx(gt,{onClick:n,disabled:t||!r,className:e,children:"Zoom Out"})},gy=({className:e})=>{const{masterVolume:t}=rt(),{setMasterVolume:n}=Se();return C.jsx(lv,{volume:t,onChange:n,className:e})},vy=({className:e})=>{const{timeFormat:t}=rt(),{setTimeFormat:n}=Se();return C.jsx(Hv,{value:t,onChange:n,className:e})},yy=P.span`
1005
1005
  font-family: 'Courier New', Monaco, monospace;
1006
1006
  font-size: 1rem;
1007
1007
  font-weight: 600;
1008
1008
  color: ${e=>e.theme?.textColor||"#333"};
1009
1009
  user-select: none;
1010
- `,yy=({className:e})=>{const t=m.useRef(null),n=m.useRef(null),{isPlaying:r,currentTimeRef:s,getPlaybackTime:a}=tt(),{timeFormat:o}=rt();return m.useEffect(()=>{const i=()=>{if(t.current){const l=r?a():s.current??0;t.current.textContent=Dn(l,o)}r&&(n.current=requestAnimationFrame(i))};return r?n.current=requestAnimationFrame(i):i(),()=>{n.current&&(cancelAnimationFrame(n.current),n.current=null)}},[r,o,s,a]),m.useEffect(()=>{!r&&t.current&&(t.current.textContent=Dn(s.current??0,o))}),C.jsx(vy,{ref:t,className:e,"aria-label":"Audio position",children:Dn(s.current??0,o)})},by=({className:e})=>{const{selectionStart:t,selectionEnd:n}=nt(),{setSelection:r}=Se();return C.jsx(kv,{selectionStart:t,selectionEnd:n,onSelectionChange:r,className:e})},wy=({className:e})=>{const{isAutomaticScroll:t}=nt(),{setAutomaticScroll:n}=Se();return C.jsx(Og,{checked:t,onChange:n,className:e})},Qs=m.createContext(null),_y=Qs.Provider;function bn(){const e=m.useContext(Qs);if(!e)throw new Error("useAnnotationIntegration must be used within <AnnotationProvider>. Install @waveform-playlist/annotations and wrap your app with <AnnotationProvider>. See: https://waveform-playlist.naomiaro.com/docs/guides/annotations");return e}const xy=({className:e})=>{const{ContinuousPlayCheckbox:t}=bn(),{continuousPlay:n}=nt(),{setContinuousPlay:r}=Se();return C.jsx(t,{checked:n,onChange:r,className:e})},Cy=({className:e})=>{const{LinkEndpointsCheckbox:t}=bn(),{linkEndpoints:n}=nt(),{setLinkEndpoints:r}=Se();return C.jsx(t,{checked:n,onChange:r,className:e})},Sy=({className:e})=>{const{EditableCheckbox:t}=bn(),{annotationsEditable:n}=nt(),{setAnnotationsEditable:r}=Se();return C.jsx(t,{checked:n,onChange:r,className:e})},ky=({filename:e,className:t})=>{const{DownloadAnnotationsButton:n}=bn(),{annotations:r}=nt();return C.jsx(n,{annotations:r,filename:e,className:t})},Ey=({label:e="Export WAV",filename:t="export",mode:n="master",trackIndex:r,bitDepth:s=16,applyEffects:a=!0,effectsFunction:o,createOfflineTrackEffects:i,className:l,onExportComplete:c,onExportError:u})=>{const{tracks:f,trackStates:p}=rt(),{exportWav:d,isExporting:h,progress:v}=df(),g=async()=>{try{const b=await d(f,p,{filename:t,mode:n,trackIndex:r,bitDepth:s,applyEffects:a,effectsFunction:o,createOfflineTrackEffects:i,autoDownload:!0});c?.(b.blob)}catch(b){u?.(b instanceof Error?b:new Error("Export failed"))}},y=h?`Exporting ${Math.round(v*100)}%`:e;return C.jsx(gt,{onClick:g,disabled:h||f.length===0,className:l,children:y})},_f=m.createContext(!1),Iy=_f.Provider;function xf(){return m.useContext(_f)}const My=P.div.attrs(e=>({style:{width:`${e.$width}px`,background:e.$color}}))`
1010
+ `,by=({className:e})=>{const t=m.useRef(null),n=m.useRef(null),{isPlaying:r,currentTimeRef:s,getPlaybackTime:a}=tt(),{timeFormat:o}=rt();return m.useEffect(()=>{const i=()=>{if(t.current){const l=r?a():s.current??0;t.current.textContent=Dn(l,o)}r&&(n.current=requestAnimationFrame(i))};return r?n.current=requestAnimationFrame(i):i(),()=>{n.current&&(cancelAnimationFrame(n.current),n.current=null)}},[r,o,s,a]),m.useEffect(()=>{!r&&t.current&&(t.current.textContent=Dn(s.current??0,o))}),C.jsx(yy,{ref:t,className:e,"aria-label":"Audio position",children:Dn(s.current??0,o)})},wy=({className:e})=>{const{selectionStart:t,selectionEnd:n}=nt(),{setSelection:r}=Se();return C.jsx(kv,{selectionStart:t,selectionEnd:n,onSelectionChange:r,className:e})},_y=({className:e})=>{const{isAutomaticScroll:t}=nt(),{setAutomaticScroll:n}=Se();return C.jsx(Og,{checked:t,onChange:n,className:e})},Qs=m.createContext(null),xy=Qs.Provider;function bn(){const e=m.useContext(Qs);if(!e)throw new Error("useAnnotationIntegration must be used within <AnnotationProvider>. Install @waveform-playlist/annotations and wrap your app with <AnnotationProvider>. See: https://waveform-playlist.naomiaro.com/docs/guides/annotations");return e}const Cy=({className:e})=>{const{ContinuousPlayCheckbox:t}=bn(),{continuousPlay:n}=nt(),{setContinuousPlay:r}=Se();return C.jsx(t,{checked:n,onChange:r,className:e})},Sy=({className:e})=>{const{LinkEndpointsCheckbox:t}=bn(),{linkEndpoints:n}=nt(),{setLinkEndpoints:r}=Se();return C.jsx(t,{checked:n,onChange:r,className:e})},ky=({className:e})=>{const{EditableCheckbox:t}=bn(),{annotationsEditable:n}=nt(),{setAnnotationsEditable:r}=Se();return C.jsx(t,{checked:n,onChange:r,className:e})},Ey=({filename:e,className:t})=>{const{DownloadAnnotationsButton:n}=bn(),{annotations:r}=nt();return C.jsx(n,{annotations:r,filename:e,className:t})},Iy=({label:e="Export WAV",filename:t="export",mode:n="master",trackIndex:r,bitDepth:s=16,applyEffects:a=!0,effectsFunction:o,createOfflineTrackEffects:i,className:l,onExportComplete:c,onExportError:u})=>{const{tracks:f,trackStates:p}=rt(),{exportWav:d,isExporting:h,progress:v}=df(),g=async()=>{try{const b=await d(f,p,{filename:t,mode:n,trackIndex:r,bitDepth:s,applyEffects:a,effectsFunction:o,createOfflineTrackEffects:i,autoDownload:!0});c?.(b.blob)}catch(b){u?.(b instanceof Error?b:new Error("Export failed"))}},y=h?`Exporting ${Math.round(v*100)}%`:e;return C.jsx(gt,{onClick:g,disabled:h||f.length===0,className:l,children:y})},_f=m.createContext(!1),My=_f.Provider;function xf(){return m.useContext(_f)}const Ay=P.div.attrs(e=>({style:{width:`${e.$width}px`,background:e.$color}}))`
1011
1011
  position: absolute;
1012
1012
  top: 0;
1013
1013
  left: 0;
@@ -1015,7 +1015,7 @@ self.onmessage = function(e) {
1015
1015
  z-index: 100; /* Below sticky controls (z-index: 101) so playhead is hidden when scrolled behind controls */
1016
1016
  pointer-events: none;
1017
1017
  will-change: transform;
1018
- `,Ay=({color:e="#ff0000"})=>{const t=m.useRef(null),n=m.useRef(null),{isPlaying:r,currentTimeRef:s,getPlaybackTime:a}=tt(),{samplesPerPixel:o,sampleRate:i,progressBarWidth:l}=rt();return m.useEffect(()=>{const c=()=>{if(t.current){const f=(r?a():s.current??0)*i/o;t.current.style.transform=`translate3d(${f}px, 0, 0)`}r&&(n.current=requestAnimationFrame(c))};return r?n.current=requestAnimationFrame(c):c(),()=>{n.current&&(cancelAnimationFrame(n.current),n.current=null)}},[r,i,o,s,a]),m.useEffect(()=>{if(!r&&t.current){const u=(s.current??0)*i/o;t.current.style.transform=`translate3d(${u}px, 0, 0)`}}),C.jsx(My,{ref:t,$color:e,$width:l,"data-playhead":!0})},Ty=P.div`
1018
+ `,Ty=({color:e="#ff0000"})=>{const t=m.useRef(null),n=m.useRef(null),{isPlaying:r,currentTimeRef:s,getPlaybackTime:a}=tt(),{samplesPerPixel:o,sampleRate:i,progressBarWidth:l}=rt();return m.useEffect(()=>{const c=()=>{if(t.current){const f=(r?a():s.current??0)*i/o;t.current.style.transform=`translate3d(${f}px, 0, 0)`}r&&(n.current=requestAnimationFrame(c))};return r?n.current=requestAnimationFrame(c):c(),()=>{n.current&&(cancelAnimationFrame(n.current),n.current=null)}},[r,i,o,s,a]),m.useEffect(()=>{if(!r&&t.current){const u=(s.current??0)*i/o;t.current.style.transform=`translate3d(${u}px, 0, 0)`}}),C.jsx(Ay,{ref:t,$color:e,$width:l,"data-playhead":!0})},$y=P.div`
1019
1019
  position: relative;
1020
1020
  `,_a=P.div.attrs(e=>({style:{top:`${e.$top}px`,width:`${e.$width}px`,height:`${e.$height}px`,background:e.$color}}))`
1021
1021
  position: absolute;
@@ -1024,7 +1024,7 @@ self.onmessage = function(e) {
1024
1024
  /* Force GPU compositing layer to prevent gradient flickering during scroll */
1025
1025
  transform: translateZ(0);
1026
1026
  backface-visibility: hidden;
1027
- `,$y=P.div.attrs(e=>({style:{top:`${e.$top}px`,height:`${e.$height}px`,width:`${e.$width}px`,background:e.$color,transform:"scaleX(0)"}}))`
1027
+ `,Ry=P.div.attrs(e=>({style:{top:`${e.$top}px`,height:`${e.$height}px`,width:`${e.$width}px`,background:e.$color,transform:"scaleX(0)"}}))`
1028
1028
  position: absolute;
1029
1029
  left: 0;
1030
1030
  pointer-events: none;
@@ -1032,16 +1032,16 @@ self.onmessage = function(e) {
1032
1032
  transform-origin: left;
1033
1033
  /* scaleX changes are composite-only (GPU) — no layout reflow per frame */
1034
1034
  will-change: transform;
1035
- `,Ry=P.div`
1035
+ `,Dy=P.div`
1036
1036
  position: relative;
1037
1037
  z-index: 2;
1038
- `,nc=({clipStartSample:e,clipDurationSamples:t,midiNotes:n,clipSampleRate:r,clipOffsetSeconds:s,...a})=>{const o=m.useRef(null),i=m.useRef(null),l=Br(),{waveHeight:c}=Ys(),{isPlaying:u,currentTimeRef:f,getPlaybackTime:p}=tt(),{samplesPerPixel:d,sampleRate:h}=rt(),v=l?.waveProgressColor||"rgba(0, 0, 0, 0.1)",g=hc(e,t,d);m.useEffect(()=>{const T=()=>{if(o.current){const $=(u?p():f.current??0)*h,R=e+t;let F=0;$<=e?F=0:$>=R?F=1:F=($-e)/t,o.current.style.transform=`scaleX(${F})`}u&&(i.current=requestAnimationFrame(T))};return u?i.current=requestAnimationFrame(T):T(),()=>{i.current&&(cancelAnimationFrame(i.current),i.current=null)}},[u,h,e,t,g,f,p]),m.useEffect(()=>{if(!u&&o.current){const A=(f.current??0)*h,$=e+t;let R=0;A<=e?R=0:A>=$?R=1:R=(A-e)/t,o.current.style.transform=`scaleX(${R})`}});const y=l?.waveformDrawMode||"inverted";let b;y==="inverted"?b=a.isSelected&&l?l.selectedWaveFillColor:l?.waveFillColor||"white":b=a.isSelected&&l?l.selectedWaveOutlineColor:l?.waveOutlineColor||"grey";const w=a.renderMode==="spectrogram"||a.renderMode==="both",_=a.renderMode==="piano-roll",x=a.renderMode==="both",S=w?"#000":_?l?.pianoRollBackgroundColor||"#1a1a2e":Kt(b),k=Math.floor(c/2),E=c,I=a.index*c,M=Kt(b);return C.jsxs(Ty,{children:[x?C.jsxs(C.Fragment,{children:[C.jsx(_a,{$color:"#000",$height:k,$top:I,$width:a.length}),C.jsx(_a,{$color:M,$height:k,$top:I+k,$width:a.length})]}):C.jsx(_a,{$color:S,$height:E,$top:I,$width:a.length}),!_&&C.jsx($y,{ref:o,$color:v,$height:E,$top:I,$width:g}),C.jsx(Ry,{children:C.jsx(Yd,{...a,transparentBackground:!0,midiNotes:n,sampleRate:r,clipOffsetSeconds:s})})]})},ki=m.createContext(null),Dy=ki.Provider;function Py(){const e=m.useContext(ki);if(!e)throw new Error("useSpectrogramIntegration must be used within <SpectrogramProvider>. Install @waveform-playlist/spectrogram and wrap your app with <SpectrogramProvider>.");return e}const Fy=60,Oy=P.div.attrs(e=>({style:{height:`${e.$height}px`}}))`
1038
+ `,nc=({clipStartSample:e,clipDurationSamples:t,midiNotes:n,clipSampleRate:r,clipOffsetSeconds:s,...a})=>{const o=m.useRef(null),i=m.useRef(null),l=Br(),{waveHeight:c}=Ys(),{isPlaying:u,currentTimeRef:f,getPlaybackTime:p}=tt(),{samplesPerPixel:d,sampleRate:h}=rt(),v=l?.waveProgressColor||"rgba(0, 0, 0, 0.1)",g=hc(e,t,d);m.useEffect(()=>{const T=()=>{if(o.current){const $=(u?p():f.current??0)*h,R=e+t;let F=0;$<=e?F=0:$>=R?F=1:F=($-e)/t,o.current.style.transform=`scaleX(${F})`}u&&(i.current=requestAnimationFrame(T))};return u?i.current=requestAnimationFrame(T):T(),()=>{i.current&&(cancelAnimationFrame(i.current),i.current=null)}},[u,h,e,t,g,f,p]),m.useEffect(()=>{if(!u&&o.current){const A=(f.current??0)*h,$=e+t;let R=0;A<=e?R=0:A>=$?R=1:R=(A-e)/t,o.current.style.transform=`scaleX(${R})`}});const y=l?.waveformDrawMode||"inverted";let b;y==="inverted"?b=a.isSelected&&l?l.selectedWaveFillColor:l?.waveFillColor||"white":b=a.isSelected&&l?l.selectedWaveOutlineColor:l?.waveOutlineColor||"grey";const w=a.renderMode==="spectrogram"||a.renderMode==="both",_=a.renderMode==="piano-roll",x=a.renderMode==="both",S=w?"#000":_?l?.pianoRollBackgroundColor||"#1a1a2e":Kt(b),k=Math.floor(c/2),E=c,I=a.index*c,M=Kt(b);return C.jsxs($y,{children:[x?C.jsxs(C.Fragment,{children:[C.jsx(_a,{$color:"#000",$height:k,$top:I,$width:a.length}),C.jsx(_a,{$color:M,$height:k,$top:I+k,$width:a.length})]}):C.jsx(_a,{$color:S,$height:E,$top:I,$width:a.length}),!_&&C.jsx(Ry,{ref:o,$color:v,$height:E,$top:I,$width:g}),C.jsx(Dy,{children:C.jsx(Yd,{...a,transparentBackground:!0,midiNotes:n,sampleRate:r,clipOffsetSeconds:s})})]})},ki=m.createContext(null),Py=ki.Provider;function Fy(){const e=m.useContext(ki);if(!e)throw new Error("useSpectrogramIntegration must be used within <SpectrogramProvider>. Install @waveform-playlist/spectrogram and wrap your app with <SpectrogramProvider>.");return e}const Oy=60,Ly=P.div.attrs(e=>({style:{height:`${e.$height}px`}}))`
1039
1039
  overflow: hidden;
1040
1040
  pointer-events: auto;
1041
1041
  background: ${e=>e.theme.surfaceColor};
1042
1042
  transition: background 0.15s ease-in-out;
1043
1043
  ${e=>e.$isSelected&&`background: ${e.theme.selectedTrackControlsBackground};`}
1044
- `,Ly=({renderPlayhead:e,color:t,samplesPerPixel:n,sampleRate:r})=>{const{isPlaying:s,currentTimeRef:a,playbackStartTimeRef:o,audioStartPositionRef:i,getPlaybackTime:l}=tt();return e({position:(a.current??0)*r/n,color:t,isPlaying:s,currentTimeRef:a,playbackStartTimeRef:o,audioStartPositionRef:i,samplesPerPixel:n,sampleRate:r,controlsOffset:0,getAudioContextTime:()=>L.getContext().currentTime,getPlaybackTime:l})};function xa(e,t,n,r){const s=e.length>0?Math.max(1,...e.map(o=>o.peaks.data.length)):1,a=t?.isRecording&&t.trackId===n?r?1:t.peaks.length:0;return Math.max(s,a)}const Cf=({renderTrackControls:e,renderTick:t,renderPlayhead:n,annotationControls:r,getAnnotationBoxLabel:s,className:a,showClipHeaders:o=!1,interactiveClips:i=!1,showFades:l=!1,touchOptimized:c=!1,onRemoveTrack:u,recordingState:f})=>{const p=Br(),{isPlaying:d}=tt(),{selectionStart:h,selectionEnd:v,annotations:g,activeAnnotationId:y,annotationsEditable:b,linkEndpoints:w,continuousPlay:_,selectedTrackId:x,loopStart:S,loopEnd:k,isLoopEnabled:E}=nt(),I=m.useContext(Qs),{setAnnotations:M,setActiveAnnotationId:T,setTrackMute:A,setTrackSolo:$,setTrackVolume:R,setTrackPan:F,setSelection:O,play:G,setScrollContainer:Q,setSelectedTrackId:ee,setCurrentTime:ue,setLoopRegion:te}=Se(),{peaksDataArray:oe,trackStates:se,tracks:le,duration:ye,samplesPerPixel:de,sampleRate:ne,waveHeight:Z,timeScaleHeight:fe,controls:Fe,barWidth:ae,barGap:Te,isReady:B,mono:$e}=rt(),re=m.useContext(ki),Ve=m.useMemo(()=>{if(!re)return new Map;const N=new Map;return le.forEach(U=>{if((re.trackSpectrogramOverrides.get(U.id)?.renderMode??U.renderMode??"waveform")==="waveform")return;const X=re.trackSpectrogramOverrides.get(U.id),ke=X?.colorMap??U.spectrogramColorMap??re.spectrogramColorMap??"viridis",Me=X?.config??U.spectrogramConfig??re.spectrogramConfig;N.set(U.id,{colorLUT:re.getColorMap(ke),frequencyScaleFn:re.getFrequencyScale(Me?.frequencyScale??"mel"),config:Me})}),N},[le,re]),ve=m.useMemo(()=>{if(re?.spectrogramWorkerApi)return{registerCanvas:re.spectrogramWorkerApi.registerCanvas.bind(re.spectrogramWorkerApi),unregisterCanvas:re.spectrogramWorkerApi.unregisterCanvas.bind(re.spectrogramWorkerApi)}},[re?.spectrogramWorkerApi]),[Re,ct]=m.useState(null),[xt,st]=m.useState(!1),je=m.useRef(0),at=m.useRef(null),ut=m.useCallback(N=>{at.current=N,Q(N)},[Q]),Mt=le.reduce((N,U)=>U.clips.reduce((H,X)=>{const ke=(X.startSample+X.durationSamples)/X.sampleRate;return Math.max(H,ke)},N),0);let Ct=Mt>0?Mt:ye>0?ye:Fy;if(f?.isRecording){const U=(f.startSample+f.durationSamples)/ne;Ct=Math.max(Ct,U+10)}const j=Math.floor(Ct*ne/de),pe=async N=>{T(N.id);const U=_?void 0:N.end-N.start;try{await G(N.start,U)}catch(H){console.error("waveform-playlist: Failed to start playback for annotation",N.id,H)}},ze=m.useCallback(N=>{if(N>=0&&N<le.length){const U=le[N];ee(U.id)}},[le,ee]),Ze=N=>{const U=N.currentTarget.getBoundingClientRect(),X=(N.clientX-U.left)*de/ne,Me=N.clientY-U.top;let Y=0,Be=-1;for(let Xe=0;Xe<oe.length;Xe++){const Ge=oe[Xe],kt=xa(Ge,f,le[Xe]?.id,$e),Dt=((re?.trackSpectrogramOverrides.get(le[Xe]?.id)?.renderMode??le[Xe]?.renderMode??"waveform")==="both"?kt*2:kt)*Z+(o?22:0);if(Me>=Y&&Me<Y+Dt){Be=Xe;break}Y+=Dt}Be!==-1&&ze(Be),je.current=X,st(!0),ue(X),O(X,X)},q=N=>{if(!xt||d)return;const U=N.currentTarget.getBoundingClientRect(),X=(N.clientX-U.left)*de/ne,ke=Math.min(h,X),Me=Math.max(h,X);O(ke,Me)},me=N=>{if(!xt)return;if(st(!1),d){const Y=Math.max(0,je.current);ue(Y),O(Y,Y),G(Y);return}const U=N.currentTarget.getBoundingClientRect(),X=(N.clientX-U.left)*de/ne,ke=Math.min(h,X),Me=Math.max(h,X);Math.abs(Me-ke)<.1?ue(ke):O(ke,Me)};if(le.some(N=>N.clips.length>0)&&oe.length===0)return C.jsx("div",{className:a,children:"Loading waveform..."});const St=Fe.show?oe.map((N,U)=>{const H=le[U];if(!H)return null;const X=se[U]||{name:`Track ${U+1}`,muted:!1,soloed:!1,volume:1,pan:0},ke=H.clips.some(Ge=>Ge.midiNotes&&Ge.midiNotes.length>0),Me=re?.trackSpectrogramOverrides.get(H.id)?.renderMode??H.renderMode??(ke?"piano-roll":"waveform"),Y=xa(N,f,H.id,$e),Be=Z*Y+(o?bi:0),Xe=e?e(U):C.jsxs(qv,{onClick:()=>ze(U),children:[C.jsxs(Jv,{style:{justifyContent:"center",position:"relative"},children:[u&&C.jsx(Kv,{onClick:Ge=>{Ge.stopPropagation(),u(U)}}),C.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",padding:"0 24px",display:"block"},children:X.name||`Track ${U+1}`}),re?.renderMenuItems&&C.jsx("span",{style:{position:"absolute",right:0,top:0},children:C.jsx(o0,{items:Ge=>re.renderMenuItems({renderMode:Me,onRenderModeChange:kt=>re.setTrackRenderMode(H.id,kt),onOpenSettings:()=>ct(H.id),onClose:Ge})})})]}),C.jsxs(Xv,{children:[C.jsx(Kl,{$variant:X.muted?"danger":"outline",onClick:()=>A(U,!X.muted),children:"Mute"}),C.jsx(Kl,{$variant:X.soloed?"info":"outline",onClick:()=>$(U,!X.soloed),children:"Solo"})]}),C.jsxs(Jl,{children:[C.jsx(Qv,{}),C.jsx(ql,{min:"0",max:"1",step:"0.01",value:X.volume,onChange:Ge=>R(U,parseFloat(Ge.target.value))}),C.jsx(e0,{})]}),C.jsxs(Jl,{children:[C.jsx("span",{children:"L"}),C.jsx(ql,{min:"-1",max:"1",step:"0.01",value:X.pan,onChange:Ge=>F(U,parseFloat(Ge.target.value))}),C.jsx("span",{children:"R"})]})]});return C.jsx(Oy,{$height:Be,$isSelected:H.id===x,children:Xe},H.id)}):void 0;return C.jsxs(Xd,{children:[C.jsx(Lr.Provider,{value:{samplesPerPixel:de,sampleRate:ne,zoomLevels:[de],waveHeight:Z,timeScaleHeight:fe,duration:Ct*1e3,controls:Fe,barWidth:ae,barGap:Te},children:C.jsx(wi,{theme:p,backgroundColor:p.playlistBackgroundColor||Kt(p.waveOutlineColor),timescaleBackgroundColor:p.timescaleBackgroundColor,timescaleWidth:j,tracksWidth:j,controlsWidth:Fe.show?Fe.width:0,onTracksMouseDown:Ze,onTracksMouseMove:q,onTracksMouseUp:me,scrollContainerRef:ut,isSelecting:xt,"data-playlist-state":B?"ready":"loading",trackControlsSlots:St,timescaleGapHeight:fe>0?fe+1:0,timescale:fe>0?C.jsxs(C.Fragment,{children:[C.jsx(Kd,{renderTick:t}),E&&C.jsx(Sv,{startPosition:Math.min(S,k)*ne/de,endPosition:Math.max(S,k)*ne/de,markerColor:p.loopMarkerColor,regionColor:p.loopRegionColor,minPosition:0,maxPosition:j,onLoopRegionChange:(N,U)=>{const H=N*de/ne,X=U*de/ne;te(H,X)}})]}):void 0,children:C.jsxs(C.Fragment,{children:[oe.map((N,U)=>{const H=le[U];if(!H)return null;const X=H.clips.some(Y=>Y.midiNotes&&Y.midiNotes.length>0),ke=re?.trackSpectrogramOverrides.get(H.id)?.renderMode??H.renderMode??(X?"piano-roll":"waveform"),Me=xa(N,f,H.id,$e);return C.jsxs(qd,{numChannels:Me,backgroundColor:ke==="piano-roll"?p.pianoRollBackgroundColor||"#1a1a2e":Kt(p.waveOutlineColor),offset:0,width:j,hasClipHeaders:o,trackId:H.id,isSelected:H.id===x,children:[ke!=="waveform"&&(()=>{const Y=Ve.get(H.id),Be=Y?.config;return!Be?.labels||!Y?null:C.jsx(Ov,{waveHeight:Z,numChannels:Me,frequencyScaleFn:Y.frequencyScaleFn,minFrequency:Be.minFrequency??0,maxFrequency:Be.maxFrequency??ne/2,labelsColor:Be.labelsColor,labelsBackground:Be.labelsBackground,renderMode:ke,hasClipHeaders:o})})(),N.map((Y,Be)=>{const Xe=Y.peaks,Ge=Xe.length;return C.jsx(lo,{clipId:Y.clipId,trackIndex:U,clipIndex:Be,trackName:Y.trackName,startSample:Y.startSample,durationSamples:Y.durationSamples,samplesPerPixel:de,showHeader:o,disableHeaderDrag:!i,isSelected:H.id===x,trackId:H.id,fadeIn:Y.fadeIn,fadeOut:Y.fadeOut,sampleRate:ne,showFades:l,touchOptimized:c,onMouseDown:kt=>{kt.target.closest('[role="button"][aria-roledescription="draggable"]')||ze(U)},children:Xe.data.map((kt,Nt)=>C.jsx(nc,{index:Nt,data:kt,bits:Xe.bits,length:Ge,isSelected:H.id===x,clipStartSample:Y.startSample,clipDurationSamples:Y.durationSamples,renderMode:Y.midiNotes?"piano-roll":ke,midiNotes:Y.midiNotes,clipSampleRate:Y.sampleRate,clipOffsetSeconds:Y.offsetSamples!=null?Y.offsetSamples/(Y.sampleRate||ne):0,samplesPerPixel:de,spectrogramWorkerApi:ve,spectrogramClipId:Y.clipId,spectrogramOnCanvasesReady:re?(wn,Dt)=>{re.registerSpectrogramCanvases(Y.clipId,Nt,wn,Dt)}:void 0},`${Y.clipId}-${Nt}`))},Y.clipId)}),f?.isRecording&&f.trackId===H.id&&f.peaks[0]?.length>0&&C.jsx(lo,{clipId:"recording-preview",trackIndex:U,clipIndex:N.length,trackName:"Recording...",startSample:f.startSample,durationSamples:f.durationSamples,samplesPerPixel:de,showHeader:o,disableHeaderDrag:!0,isSelected:H.id===x,trackId:H.id,children:($e?f.peaks.slice(0,1):f.peaks).map((Y,Be)=>C.jsx(nc,{index:Be,data:Y,bits:f.bits,length:Math.floor(Y.length/2),isSelected:H.id===x,clipStartSample:f.startSample,clipDurationSamples:f.durationSamples},`${H.id}-recording-${Be}`))},`${H.id}-recording`)]},H.id)}),g.length>0&&I&&C.jsx(I.AnnotationBoxesWrapper,{height:30,width:j,children:g.map((N,U)=>{const H=N.start*ne/de,X=N.end*ne/de,ke=s?s(N,U):N.id;return C.jsx(I.AnnotationBox,{annotationId:N.id,annotationIndex:U,startPosition:H,endPosition:X,label:ke,color:"#ff9800",isActive:N.id===y,onClick:()=>pe(N),editable:b},N.id)})}),h!==v&&C.jsx(Zd,{startPosition:Math.min(h,v)*ne/de,endPosition:Math.max(h,v)*ne/de,color:p.selectionColor}),(d||h===v)&&(n?C.jsx(Ly,{renderPlayhead:n,color:p.playheadColor,samplesPerPixel:de,sampleRate:ne}):C.jsx(Ay,{color:p.playheadColor}))]})})}),re?.SettingsModal&&typeof document<"u"&&mo.createPortal(C.jsx(re.SettingsModal,{open:Re!==null,onClose:()=>ct(null),config:Re!==null?re.trackSpectrogramOverrides.get(Re)?.config??le.find(N=>N.id===Re)?.spectrogramConfig??re.spectrogramConfig??{}:{},colorMap:Re!==null?re.trackSpectrogramOverrides.get(Re)?.colorMap??le.find(N=>N.id===Re)?.spectrogramColorMap??re.spectrogramColorMap??"viridis":"viridis",onApply:(N,U)=>{Re!==null&&re.setTrackSpectrogramConfig(Re,N,U)}}),document.body)]})},Sf=({height:e,renderAnnotationItem:t,onAnnotationUpdate:n,controls:r,annotationListConfig:s,scrollActivePosition:a="center",scrollActiveContainer:o="nearest"})=>{const{annotations:i,activeAnnotationId:l,annotationsEditable:c,linkEndpoints:u,continuousPlay:f}=nt(),p=bn(),{setAnnotations:d}=Se(),h=s??{linkEndpoints:u,continuousPlay:f},v=m.useCallback(y=>{d(y),n?.(y)},[d,n]),{AnnotationText:g}=p;return C.jsx(g,{annotations:i,activeAnnotationId:l??void 0,shouldScrollToActive:!0,scrollActivePosition:a,scrollActiveContainer:o,editable:c,controls:c?r:void 0,annotationListConfig:h,height:e,onAnnotationUpdate:v,renderAnnotationItem:t})},By=({renderTrackControls:e,renderTick:t,renderTimestamp:n,renderPlayhead:r,annotationControls:s,annotationListConfig:a,annotationTextHeight:o,renderAnnotationItem:i,getAnnotationBoxLabel:l,scrollActivePosition:c="center",scrollActiveContainer:u="nearest",className:f,showClipHeaders:p=!1,interactiveClips:d=!1,showFades:h=!1,touchOptimized:v=!1,onRemoveTrack:g,recordingState:y})=>{const{annotations:b}=nt(),w=xf(),_=d||w;return C.jsxs(C.Fragment,{children:[C.jsx(Cf,{renderTrackControls:e,renderTick:t??(n?(x,S)=>n(parseFloat(x)||0,S):void 0),renderPlayhead:r,annotationControls:s,getAnnotationBoxLabel:l,className:f,showClipHeaders:p,interactiveClips:_,showFades:h,touchOptimized:v,onRemoveTrack:g,recordingState:y}),b.length>0&&C.jsx(Sf,{height:o,renderAnnotationItem:i,controls:s,annotationListConfig:a,scrollActivePosition:c,scrollActiveContainer:u})]})};var Wy=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",kf=Wy?m.useLayoutEffect:m.useEffect;function Sn(e){const t=m.useRef(e);return kf(()=>{t.current=e},[e]),t}function Ca(e,t,n=m.useEffect,r=Object.is){const s=m.useRef(e);n(()=>{const a=s.current;r(e,a)||(s.current=e,t(e,a))},[t,e])}var rc=Object.getOwnPropertySymbols,Vy=Object.prototype.hasOwnProperty,Ny=Object.prototype.propertyIsEnumerable,jy=(e,t)=>{var n={};for(var r in e)Vy.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&rc)for(var r of rc(e))t.indexOf(r)<0&&Ny.call(e,r)&&(n[r]=e[r]);return n},zy=new ui,Zy=m.createContext(zy),Hy=m.memo(m.forwardRef(({children:e},t)=>{const[n,r]=m.useState(0),s=m.useRef(null),a=m.useRef(null),o=m.useMemo(()=>({renderer:{get rendering(){var i;return(i=s.current)!=null?i:Promise.resolve()}},trackRendering(i){s.current||(s.current=new Promise(l=>{a.current=l})),m.startTransition(()=>{i(),r(l=>l+1)})}}),[]);return kf(()=>{var i;(i=a.current)==null||i.call(a),s.current=null},[e,n]),m.useImperativeHandle(t,()=>o),null})),Sa=[void 0,vr];function Ef(e){var t=e,{children:n,onCollision:r,onBeforeDragStart:s,onDragStart:a,onDragMove:o,onDragOver:i,onDragEnd:l}=t,c=jy(t,["children","onCollision","onBeforeDragStart","onDragStart","onDragMove","onDragOver","onDragEnd"]);const u=m.useRef(null),{plugins:f,modifiers:p,sensors:d}=c,h=Ot(f,Rn.plugins),v=Ot(d,Rn.sensors),g=Ot(p,Rn.modifiers),y=Sn(s),b=Sn(a),w=Sn(i),_=Sn(o),x=Sn(l),S=Sn(r),k=Gy(()=>{var E;return(E=c.manager)!=null?E:new ui(c)});return m.useEffect(()=>{if(!u.current)throw new Error("Renderer not found");const{renderer:E,trackRendering:I}=u.current,{monitor:M}=k;k.renderer=E;const T=[M.addEventListener("beforedragstart",A=>{const $=y.current;$&&I(()=>$(A,k))}),M.addEventListener("dragstart",A=>{var $;return($=b.current)==null?void 0:$.call(b,A,k)}),M.addEventListener("dragover",A=>{const $=w.current;$&&I(()=>$(A,k))}),M.addEventListener("dragmove",A=>{const $=_.current;$&&I(()=>$(A,k))}),M.addEventListener("dragend",A=>{const $=x.current;$&&I(()=>$(A,k))}),M.addEventListener("collision",A=>{var $;return($=S.current)==null?void 0:$.call(S,A,k)})];return()=>T.forEach(A=>A())},[k]),Ca(h,()=>k&&(k.plugins=h),...Sa),Ca(v,()=>k&&(k.sensors=v),...Sa),Ca(g,()=>k&&(k.modifiers=g),...Sa),C.jsxs(Zy.Provider,{value:k,children:[C.jsx(Hy,{ref:u,children:n}),n]})}function Gy(e){const t=m.useRef(null);return t.current||(t.current=e()),m.useInsertionEffect(()=>()=>{var n;return(n=t.current)==null?void 0:n.destroy()},[]),t.current}var Uy=Object.create,If=Object.defineProperty,Xy=Object.getOwnPropertyDescriptor,Mf=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),ea=e=>{throw TypeError(e)},Yy=(e,t,n)=>t in e?If(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ky=e=>{var t;return[,,,Uy((t=e?.[Mf("metadata")])!=null?t:null)]},Af=["class","method","getter","setter","accessor","field","value","get","set"],Tf=e=>e!==void 0&&typeof e!="function"?ea("Function expected"):e,qy=(e,t,n,r,s)=>({kind:Af[e],name:t,metadata:r,addInitializer:a=>n._?ea("Already initialized"):s.push(Tf(a||null))}),Jy=(e,t)=>Yy(t,Mf("metadata"),e[3]),Qy=(e,t,n,r)=>{for(var s=0,a=e[t>>1],o=a&&a.length;s<o;s++)a[s].call(n);return r},$f=(e,t,n,r,s,a)=>{for(var o,i,l,c,u=t&7,f=!1,p=!1,d=2,h=Af[u+5],v=e[d]||(e[d]=[]),g=(s=s.prototype,Xy(s,n)),y=r.length-1;y>=0;y--)l=qy(u,n,i={},e[3],v),l.static=f,l.private=p,c=l.access={has:b=>n in b},c.get=b=>b[n],o=(0,r[y])(g[h],l),i._=1,Tf(o)&&(g[h]=o);return g&&If(s,n,g),s},Rf=(e,t,n)=>t.has(e)||ea("Cannot "+n),eb=(e,t,n)=>(Rf(e,t,"read from private field"),t.get(e)),tb=(e,t,n)=>t.has(e)?ea("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),nb=(e,t,n,r)=>(Rf(e,t,"write to private field"),t.set(e,n),n),Jn=class fo{constructor(t,n){this.x=t,this.y=n}static delta(t,n){return new fo(t.x-n.x,t.y-n.y)}static distance(t,n){return Math.hypot(t.x-n.x,t.y-n.y)}static equals(t,n){return t.x===n.x&&t.y===n.y}static from({x:t,y:n}){return new fo(t,n)}},Df,Pf,ho,vs,Nr,Ei=class extends(ho=qt,Pf=[Ae],Df=[Ae],ho){constructor(e){const t=Jn.from(e);super(t,(n,r)=>Jn.equals(n,r)),Qy(Nr,5,this),tb(this,vs,0),this.velocity={x:0,y:0}}get delta(){return Jn.delta(this.current,this.initial)}get direction(){const{current:e,previous:t}=this;if(!t)return null;const n={x:e.x-t.x,y:e.y-t.y};return!n.x&&!n.y?null:Math.abs(n.x)>Math.abs(n.y)?n.x>0?"right":"left":n.y>0?"down":"up"}get current(){return super.current}set current(e){const{current:t}=this,n=Jn.from(e),r={x:n.x-t.x,y:n.y-t.y},s=Date.now(),a=s-eb(this,vs),o=i=>Math.round(i/a*100);Yt(()=>{nb(this,vs,s),this.velocity={x:o(r.x),y:o(r.y)},super.current=n})}reset(e=this.defaultValue){super.reset(Jn.from(e)),this.velocity={x:0,y:0}}};Nr=Ky(ho);vs=new WeakMap;$f(Nr,2,"delta",Pf,Ei);$f(Nr,2,"direction",Df,Ei);Jy(Nr,Ei);var Ff=(e=>(e.Horizontal="x",e.Vertical="y",e))(Ff||{});Object.values(Ff);var rb=Object.defineProperty,sb=Object.defineProperties,ab=Object.getOwnPropertyDescriptors,sc=Object.getOwnPropertySymbols,ob=Object.prototype.hasOwnProperty,ib=Object.prototype.propertyIsEnumerable,ac=(e,t,n)=>t in e?rb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Of=(e,t)=>{for(var n in t||(t={}))ob.call(t,n)&&ac(e,n,t[n]);if(sc)for(var n of sc(t))ib.call(t,n)&&ac(e,n,t[n]);return e},Lf=(e,t)=>sb(e,ab(t)),po=class extends Fn{apply({transform:t}){if(!this.options)return t;const{axis:n,value:r}=this.options;return Lf(Of({},t),{[n]:r})}};po.configure=pn(po);var Bf=po;Bf.configure({axis:"x",value:0});var Wf=Bf.configure({axis:"y",value:0}),oc=class extends Fn{apply({transform:t}){var n;const{size:r=20}=(n=this.options)!=null?n:{},s=typeof r=="number"?r:r.x,a=typeof r=="number"?r:r.y;return Lf(Of({},t),{x:Math.ceil(t.x/s)*s,y:Math.ceil(t.y/a)*a})}};oc.configure=pn(oc);const Ii=e=>{let t=!1;const n=e.map(r=>r===Qa?(t=!0,Qa.configure({dropAnimation:null})):r);return t||console.warn("[waveform-playlist] noDropAnimationPlugins: Feedback plugin not found in defaults — drop animation may not be disabled. Check @dnd-kit/dom version."),n},lb=P.div`
1044
+ `,By=({renderPlayhead:e,color:t,samplesPerPixel:n,sampleRate:r})=>{const{isPlaying:s,currentTimeRef:a,playbackStartTimeRef:o,audioStartPositionRef:i,getPlaybackTime:l}=tt();return e({position:(a.current??0)*r/n,color:t,isPlaying:s,currentTimeRef:a,playbackStartTimeRef:o,audioStartPositionRef:i,samplesPerPixel:n,sampleRate:r,controlsOffset:0,getAudioContextTime:()=>L.getContext().currentTime,getPlaybackTime:l})};function xa(e,t,n,r){const s=e.length>0?Math.max(1,...e.map(o=>o.peaks.data.length)):1,a=t?.isRecording&&t.trackId===n?r?1:t.peaks.length:0;return Math.max(s,a)}const Cf=({renderTrackControls:e,renderTick:t,renderPlayhead:n,annotationControls:r,getAnnotationBoxLabel:s,className:a,showClipHeaders:o=!1,interactiveClips:i=!1,showFades:l=!1,touchOptimized:c=!1,onRemoveTrack:u,recordingState:f})=>{const p=Br(),{isPlaying:d}=tt(),{selectionStart:h,selectionEnd:v,annotations:g,activeAnnotationId:y,annotationsEditable:b,linkEndpoints:w,continuousPlay:_,selectedTrackId:x,loopStart:S,loopEnd:k,isLoopEnabled:E}=nt(),I=m.useContext(Qs),{setAnnotations:M,setActiveAnnotationId:T,setTrackMute:A,setTrackSolo:$,setTrackVolume:R,setTrackPan:F,setSelection:O,play:G,setScrollContainer:Q,setSelectedTrackId:ee,setCurrentTime:ue,setLoopRegion:te}=Se(),{peaksDataArray:oe,trackStates:se,tracks:le,duration:ye,samplesPerPixel:de,sampleRate:ne,waveHeight:Z,timeScaleHeight:fe,controls:Fe,barWidth:ae,barGap:Te,isReady:B,mono:$e}=rt(),re=m.useContext(ki),Ve=m.useMemo(()=>{if(!re)return new Map;const N=new Map;return le.forEach(U=>{if((re.trackSpectrogramOverrides.get(U.id)?.renderMode??U.renderMode??"waveform")==="waveform")return;const X=re.trackSpectrogramOverrides.get(U.id),ke=X?.colorMap??U.spectrogramColorMap??re.spectrogramColorMap??"viridis",Me=X?.config??U.spectrogramConfig??re.spectrogramConfig;N.set(U.id,{colorLUT:re.getColorMap(ke),frequencyScaleFn:re.getFrequencyScale(Me?.frequencyScale??"mel"),config:Me})}),N},[le,re]),ve=m.useMemo(()=>{if(re?.spectrogramWorkerApi)return{registerCanvas:re.spectrogramWorkerApi.registerCanvas.bind(re.spectrogramWorkerApi),unregisterCanvas:re.spectrogramWorkerApi.unregisterCanvas.bind(re.spectrogramWorkerApi)}},[re?.spectrogramWorkerApi]),[Re,ct]=m.useState(null),[xt,st]=m.useState(!1),je=m.useRef(0),at=m.useRef(null),ut=m.useCallback(N=>{at.current=N,Q(N)},[Q]),Mt=le.reduce((N,U)=>U.clips.reduce((H,X)=>{const ke=(X.startSample+X.durationSamples)/X.sampleRate;return Math.max(H,ke)},N),0);let Ct=Mt>0?Mt:ye>0?ye:Oy;if(f?.isRecording){const U=(f.startSample+f.durationSamples)/ne;Ct=Math.max(Ct,U+10)}const j=Math.floor(Ct*ne/de),pe=async N=>{T(N.id);const U=_?void 0:N.end-N.start;try{await G(N.start,U)}catch(H){console.error("waveform-playlist: Failed to start playback for annotation",N.id,H)}},ze=m.useCallback(N=>{if(N>=0&&N<le.length){const U=le[N];ee(U.id)}},[le,ee]),Ze=N=>{const U=N.currentTarget.getBoundingClientRect(),X=(N.clientX-U.left)*de/ne,Me=N.clientY-U.top;let Y=0,Be=-1;for(let Xe=0;Xe<oe.length;Xe++){const Ge=oe[Xe],kt=xa(Ge,f,le[Xe]?.id,$e),Dt=((re?.trackSpectrogramOverrides.get(le[Xe]?.id)?.renderMode??le[Xe]?.renderMode??"waveform")==="both"?kt*2:kt)*Z+(o?22:0);if(Me>=Y&&Me<Y+Dt){Be=Xe;break}Y+=Dt}Be!==-1&&ze(Be),je.current=X,st(!0),ue(X),O(X,X)},q=N=>{if(!xt||d)return;const U=N.currentTarget.getBoundingClientRect(),X=(N.clientX-U.left)*de/ne,ke=Math.min(h,X),Me=Math.max(h,X);O(ke,Me)},me=N=>{if(!xt)return;if(st(!1),d){const Y=Math.max(0,je.current);ue(Y),O(Y,Y),G(Y);return}const U=N.currentTarget.getBoundingClientRect(),X=(N.clientX-U.left)*de/ne,ke=Math.min(h,X),Me=Math.max(h,X);Math.abs(Me-ke)<.1?ue(ke):O(ke,Me)};if(le.some(N=>N.clips.length>0)&&oe.length===0)return C.jsx("div",{className:a,children:"Loading waveform..."});const St=Fe.show?oe.map((N,U)=>{const H=le[U];if(!H)return null;const X=se[U]||{name:`Track ${U+1}`,muted:!1,soloed:!1,volume:1,pan:0},ke=H.clips.some(Ge=>Ge.midiNotes&&Ge.midiNotes.length>0),Me=re?.trackSpectrogramOverrides.get(H.id)?.renderMode??H.renderMode??(ke?"piano-roll":"waveform"),Y=xa(N,f,H.id,$e),Be=Z*Y+(o?bi:0),Xe=e?e(U):C.jsxs(qv,{onClick:()=>ze(U),children:[C.jsxs(Jv,{style:{justifyContent:"center",position:"relative"},children:[u&&C.jsx(Kv,{onClick:Ge=>{Ge.stopPropagation(),u(U)}}),C.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",padding:"0 24px",display:"block"},children:X.name||`Track ${U+1}`}),re?.renderMenuItems&&C.jsx("span",{style:{position:"absolute",right:0,top:0},children:C.jsx(o0,{items:Ge=>re.renderMenuItems({renderMode:Me,onRenderModeChange:kt=>re.setTrackRenderMode(H.id,kt),onOpenSettings:()=>ct(H.id),onClose:Ge})})})]}),C.jsxs(Xv,{children:[C.jsx(Kl,{$variant:X.muted?"danger":"outline",onClick:()=>A(U,!X.muted),children:"Mute"}),C.jsx(Kl,{$variant:X.soloed?"info":"outline",onClick:()=>$(U,!X.soloed),children:"Solo"})]}),C.jsxs(Jl,{children:[C.jsx(Qv,{}),C.jsx(ql,{min:"0",max:"1",step:"0.01",value:X.volume,onChange:Ge=>R(U,parseFloat(Ge.target.value))}),C.jsx(e0,{})]}),C.jsxs(Jl,{children:[C.jsx("span",{children:"L"}),C.jsx(ql,{min:"-1",max:"1",step:"0.01",value:X.pan,onChange:Ge=>F(U,parseFloat(Ge.target.value))}),C.jsx("span",{children:"R"})]})]});return C.jsx(Ly,{$height:Be,$isSelected:H.id===x,children:Xe},H.id)}):void 0;return C.jsxs(Xd,{children:[C.jsx(Lr.Provider,{value:{samplesPerPixel:de,sampleRate:ne,zoomLevels:[de],waveHeight:Z,timeScaleHeight:fe,duration:Ct*1e3,controls:Fe,barWidth:ae,barGap:Te},children:C.jsx(wi,{theme:p,backgroundColor:p.playlistBackgroundColor||Kt(p.waveOutlineColor),timescaleBackgroundColor:p.timescaleBackgroundColor,timescaleWidth:j,tracksWidth:j,controlsWidth:Fe.show?Fe.width:0,onTracksMouseDown:Ze,onTracksMouseMove:q,onTracksMouseUp:me,scrollContainerRef:ut,isSelecting:xt,"data-playlist-state":B?"ready":"loading",trackControlsSlots:St,timescaleGapHeight:fe>0?fe+1:0,timescale:fe>0?C.jsxs(C.Fragment,{children:[C.jsx(Kd,{renderTick:t}),E&&C.jsx(Sv,{startPosition:Math.min(S,k)*ne/de,endPosition:Math.max(S,k)*ne/de,markerColor:p.loopMarkerColor,regionColor:p.loopRegionColor,minPosition:0,maxPosition:j,onLoopRegionChange:(N,U)=>{const H=N*de/ne,X=U*de/ne;te(H,X)}})]}):void 0,children:C.jsxs(C.Fragment,{children:[oe.map((N,U)=>{const H=le[U];if(!H)return null;const X=H.clips.some(Y=>Y.midiNotes&&Y.midiNotes.length>0),ke=re?.trackSpectrogramOverrides.get(H.id)?.renderMode??H.renderMode??(X?"piano-roll":"waveform"),Me=xa(N,f,H.id,$e);return C.jsxs(qd,{numChannels:Me,backgroundColor:ke==="piano-roll"?p.pianoRollBackgroundColor||"#1a1a2e":Kt(p.waveOutlineColor),offset:0,width:j,hasClipHeaders:o,trackId:H.id,isSelected:H.id===x,children:[ke!=="waveform"&&(()=>{const Y=Ve.get(H.id),Be=Y?.config;return!Be?.labels||!Y?null:C.jsx(Ov,{waveHeight:Z,numChannels:Me,frequencyScaleFn:Y.frequencyScaleFn,minFrequency:Be.minFrequency??0,maxFrequency:Be.maxFrequency??ne/2,labelsColor:Be.labelsColor,labelsBackground:Be.labelsBackground,renderMode:ke,hasClipHeaders:o})})(),N.map((Y,Be)=>{const Xe=Y.peaks,Ge=Xe.length;return C.jsx(lo,{clipId:Y.clipId,trackIndex:U,clipIndex:Be,trackName:Y.trackName,startSample:Y.startSample,durationSamples:Y.durationSamples,samplesPerPixel:de,showHeader:o,disableHeaderDrag:!i,isSelected:H.id===x,trackId:H.id,fadeIn:Y.fadeIn,fadeOut:Y.fadeOut,sampleRate:ne,showFades:l,touchOptimized:c,onMouseDown:kt=>{kt.target.closest('[role="button"][aria-roledescription="draggable"]')||ze(U)},children:Xe.data.map((kt,Nt)=>C.jsx(nc,{index:Nt,data:kt,bits:Xe.bits,length:Ge,isSelected:H.id===x,clipStartSample:Y.startSample,clipDurationSamples:Y.durationSamples,renderMode:Y.midiNotes?"piano-roll":ke,midiNotes:Y.midiNotes,clipSampleRate:Y.sampleRate,clipOffsetSeconds:Y.offsetSamples!=null?Y.offsetSamples/(Y.sampleRate||ne):0,samplesPerPixel:de,spectrogramWorkerApi:ve,spectrogramClipId:Y.clipId,spectrogramOnCanvasesReady:re?(wn,Dt)=>{re.registerSpectrogramCanvases(Y.clipId,Nt,wn,Dt)}:void 0},`${Y.clipId}-${Nt}`))},Y.clipId)}),f?.isRecording&&f.trackId===H.id&&f.peaks[0]?.length>0&&C.jsx(lo,{clipId:"recording-preview",trackIndex:U,clipIndex:N.length,trackName:"Recording...",startSample:f.startSample,durationSamples:f.durationSamples,samplesPerPixel:de,showHeader:o,disableHeaderDrag:!0,isSelected:H.id===x,trackId:H.id,children:($e?f.peaks.slice(0,1):f.peaks).map((Y,Be)=>C.jsx(nc,{index:Be,data:Y,bits:f.bits,length:Math.floor(Y.length/2),isSelected:H.id===x,clipStartSample:f.startSample,clipDurationSamples:f.durationSamples},`${H.id}-recording-${Be}`))},`${H.id}-recording`)]},H.id)}),g.length>0&&I&&C.jsx(I.AnnotationBoxesWrapper,{height:30,width:j,children:g.map((N,U)=>{const H=N.start*ne/de,X=N.end*ne/de,ke=s?s(N,U):N.id;return C.jsx(I.AnnotationBox,{annotationId:N.id,annotationIndex:U,startPosition:H,endPosition:X,label:ke,color:"#ff9800",isActive:N.id===y,onClick:()=>pe(N),editable:b},N.id)})}),h!==v&&C.jsx(Zd,{startPosition:Math.min(h,v)*ne/de,endPosition:Math.max(h,v)*ne/de,color:p.selectionColor}),(d||h===v)&&(n?C.jsx(By,{renderPlayhead:n,color:p.playheadColor,samplesPerPixel:de,sampleRate:ne}):C.jsx(Ty,{color:p.playheadColor}))]})})}),re?.SettingsModal&&typeof document<"u"&&mo.createPortal(C.jsx(re.SettingsModal,{open:Re!==null,onClose:()=>ct(null),config:Re!==null?re.trackSpectrogramOverrides.get(Re)?.config??le.find(N=>N.id===Re)?.spectrogramConfig??re.spectrogramConfig??{}:{},colorMap:Re!==null?re.trackSpectrogramOverrides.get(Re)?.colorMap??le.find(N=>N.id===Re)?.spectrogramColorMap??re.spectrogramColorMap??"viridis":"viridis",onApply:(N,U)=>{Re!==null&&re.setTrackSpectrogramConfig(Re,N,U)}}),document.body)]})},Sf=({height:e,renderAnnotationItem:t,onAnnotationUpdate:n,controls:r,annotationListConfig:s,scrollActivePosition:a="center",scrollActiveContainer:o="nearest"})=>{const{annotations:i,activeAnnotationId:l,annotationsEditable:c,linkEndpoints:u,continuousPlay:f}=nt(),p=bn(),{setAnnotations:d}=Se(),h=s??{linkEndpoints:u,continuousPlay:f},v=m.useCallback(y=>{d(y),n?.(y)},[d,n]),{AnnotationText:g}=p;return C.jsx(g,{annotations:i,activeAnnotationId:l??void 0,shouldScrollToActive:!0,scrollActivePosition:a,scrollActiveContainer:o,editable:c,controls:c?r:void 0,annotationListConfig:h,height:e,onAnnotationUpdate:v,renderAnnotationItem:t})},Wy=({renderTrackControls:e,renderTick:t,renderTimestamp:n,renderPlayhead:r,annotationControls:s,annotationListConfig:a,annotationTextHeight:o,renderAnnotationItem:i,getAnnotationBoxLabel:l,scrollActivePosition:c="center",scrollActiveContainer:u="nearest",className:f,showClipHeaders:p=!1,interactiveClips:d=!1,showFades:h=!1,touchOptimized:v=!1,onRemoveTrack:g,recordingState:y})=>{const{annotations:b}=nt(),w=xf(),_=d||w;return C.jsxs(C.Fragment,{children:[C.jsx(Cf,{renderTrackControls:e,renderTick:t??(n?(x,S)=>n(parseFloat(x)||0,S):void 0),renderPlayhead:r,annotationControls:s,getAnnotationBoxLabel:l,className:f,showClipHeaders:p,interactiveClips:_,showFades:h,touchOptimized:v,onRemoveTrack:g,recordingState:y}),b.length>0&&C.jsx(Sf,{height:o,renderAnnotationItem:i,controls:s,annotationListConfig:a,scrollActivePosition:c,scrollActiveContainer:u})]})};var Vy=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",kf=Vy?m.useLayoutEffect:m.useEffect;function Sn(e){const t=m.useRef(e);return kf(()=>{t.current=e},[e]),t}function Ca(e,t,n=m.useEffect,r=Object.is){const s=m.useRef(e);n(()=>{const a=s.current;r(e,a)||(s.current=e,t(e,a))},[t,e])}var rc=Object.getOwnPropertySymbols,Ny=Object.prototype.hasOwnProperty,jy=Object.prototype.propertyIsEnumerable,zy=(e,t)=>{var n={};for(var r in e)Ny.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&rc)for(var r of rc(e))t.indexOf(r)<0&&jy.call(e,r)&&(n[r]=e[r]);return n},Zy=new ui,Hy=m.createContext(Zy),Gy=m.memo(m.forwardRef(({children:e},t)=>{const[n,r]=m.useState(0),s=m.useRef(null),a=m.useRef(null),o=m.useMemo(()=>({renderer:{get rendering(){var i;return(i=s.current)!=null?i:Promise.resolve()}},trackRendering(i){s.current||(s.current=new Promise(l=>{a.current=l})),m.startTransition(()=>{i(),r(l=>l+1)})}}),[]);return kf(()=>{var i;(i=a.current)==null||i.call(a),s.current=null},[e,n]),m.useImperativeHandle(t,()=>o),null})),Sa=[void 0,vr];function Ef(e){var t=e,{children:n,onCollision:r,onBeforeDragStart:s,onDragStart:a,onDragMove:o,onDragOver:i,onDragEnd:l}=t,c=zy(t,["children","onCollision","onBeforeDragStart","onDragStart","onDragMove","onDragOver","onDragEnd"]);const u=m.useRef(null),{plugins:f,modifiers:p,sensors:d}=c,h=Ot(f,Rn.plugins),v=Ot(d,Rn.sensors),g=Ot(p,Rn.modifiers),y=Sn(s),b=Sn(a),w=Sn(i),_=Sn(o),x=Sn(l),S=Sn(r),k=Uy(()=>{var E;return(E=c.manager)!=null?E:new ui(c)});return m.useEffect(()=>{if(!u.current)throw new Error("Renderer not found");const{renderer:E,trackRendering:I}=u.current,{monitor:M}=k;k.renderer=E;const T=[M.addEventListener("beforedragstart",A=>{const $=y.current;$&&I(()=>$(A,k))}),M.addEventListener("dragstart",A=>{var $;return($=b.current)==null?void 0:$.call(b,A,k)}),M.addEventListener("dragover",A=>{const $=w.current;$&&I(()=>$(A,k))}),M.addEventListener("dragmove",A=>{const $=_.current;$&&I(()=>$(A,k))}),M.addEventListener("dragend",A=>{const $=x.current;$&&I(()=>$(A,k))}),M.addEventListener("collision",A=>{var $;return($=S.current)==null?void 0:$.call(S,A,k)})];return()=>T.forEach(A=>A())},[k]),Ca(h,()=>k&&(k.plugins=h),...Sa),Ca(v,()=>k&&(k.sensors=v),...Sa),Ca(g,()=>k&&(k.modifiers=g),...Sa),C.jsxs(Hy.Provider,{value:k,children:[C.jsx(Gy,{ref:u,children:n}),n]})}function Uy(e){const t=m.useRef(null);return t.current||(t.current=e()),m.useInsertionEffect(()=>()=>{var n;return(n=t.current)==null?void 0:n.destroy()},[]),t.current}var Xy=Object.create,If=Object.defineProperty,Yy=Object.getOwnPropertyDescriptor,Mf=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),ea=e=>{throw TypeError(e)},Ky=(e,t,n)=>t in e?If(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,qy=e=>{var t;return[,,,Xy((t=e?.[Mf("metadata")])!=null?t:null)]},Af=["class","method","getter","setter","accessor","field","value","get","set"],Tf=e=>e!==void 0&&typeof e!="function"?ea("Function expected"):e,Jy=(e,t,n,r,s)=>({kind:Af[e],name:t,metadata:r,addInitializer:a=>n._?ea("Already initialized"):s.push(Tf(a||null))}),Qy=(e,t)=>Ky(t,Mf("metadata"),e[3]),eb=(e,t,n,r)=>{for(var s=0,a=e[t>>1],o=a&&a.length;s<o;s++)a[s].call(n);return r},$f=(e,t,n,r,s,a)=>{for(var o,i,l,c,u=t&7,f=!1,p=!1,d=2,h=Af[u+5],v=e[d]||(e[d]=[]),g=(s=s.prototype,Yy(s,n)),y=r.length-1;y>=0;y--)l=Jy(u,n,i={},e[3],v),l.static=f,l.private=p,c=l.access={has:b=>n in b},c.get=b=>b[n],o=(0,r[y])(g[h],l),i._=1,Tf(o)&&(g[h]=o);return g&&If(s,n,g),s},Rf=(e,t,n)=>t.has(e)||ea("Cannot "+n),tb=(e,t,n)=>(Rf(e,t,"read from private field"),t.get(e)),nb=(e,t,n)=>t.has(e)?ea("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),rb=(e,t,n,r)=>(Rf(e,t,"write to private field"),t.set(e,n),n),Jn=class fo{constructor(t,n){this.x=t,this.y=n}static delta(t,n){return new fo(t.x-n.x,t.y-n.y)}static distance(t,n){return Math.hypot(t.x-n.x,t.y-n.y)}static equals(t,n){return t.x===n.x&&t.y===n.y}static from({x:t,y:n}){return new fo(t,n)}},Df,Pf,ho,vs,Nr,Ei=class extends(ho=qt,Pf=[Ae],Df=[Ae],ho){constructor(e){const t=Jn.from(e);super(t,(n,r)=>Jn.equals(n,r)),eb(Nr,5,this),nb(this,vs,0),this.velocity={x:0,y:0}}get delta(){return Jn.delta(this.current,this.initial)}get direction(){const{current:e,previous:t}=this;if(!t)return null;const n={x:e.x-t.x,y:e.y-t.y};return!n.x&&!n.y?null:Math.abs(n.x)>Math.abs(n.y)?n.x>0?"right":"left":n.y>0?"down":"up"}get current(){return super.current}set current(e){const{current:t}=this,n=Jn.from(e),r={x:n.x-t.x,y:n.y-t.y},s=Date.now(),a=s-tb(this,vs),o=i=>Math.round(i/a*100);Yt(()=>{rb(this,vs,s),this.velocity={x:o(r.x),y:o(r.y)},super.current=n})}reset(e=this.defaultValue){super.reset(Jn.from(e)),this.velocity={x:0,y:0}}};Nr=qy(ho);vs=new WeakMap;$f(Nr,2,"delta",Pf,Ei);$f(Nr,2,"direction",Df,Ei);Qy(Nr,Ei);var Ff=(e=>(e.Horizontal="x",e.Vertical="y",e))(Ff||{});Object.values(Ff);var sb=Object.defineProperty,ab=Object.defineProperties,ob=Object.getOwnPropertyDescriptors,sc=Object.getOwnPropertySymbols,ib=Object.prototype.hasOwnProperty,lb=Object.prototype.propertyIsEnumerable,ac=(e,t,n)=>t in e?sb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Of=(e,t)=>{for(var n in t||(t={}))ib.call(t,n)&&ac(e,n,t[n]);if(sc)for(var n of sc(t))lb.call(t,n)&&ac(e,n,t[n]);return e},Lf=(e,t)=>ab(e,ob(t)),po=class extends Fn{apply({transform:t}){if(!this.options)return t;const{axis:n,value:r}=this.options;return Lf(Of({},t),{[n]:r})}};po.configure=pn(po);var Bf=po;Bf.configure({axis:"x",value:0});var Wf=Bf.configure({axis:"y",value:0}),oc=class extends Fn{apply({transform:t}){var n;const{size:r=20}=(n=this.options)!=null?n:{},s=typeof r=="number"?r:r.x,a=typeof r=="number"?r:r.y;return Lf(Of({},t),{x:Math.ceil(t.x/s)*s,y:Math.ceil(t.y/a)*a})}};oc.configure=pn(oc);const Ii=e=>{let t=!1;const n=e.map(r=>r===Qa?(t=!0,Qa.configure({dropAnimation:null})):r);return t||console.warn("[waveform-playlist] noDropAnimationPlugins: Feedback plugin not found in defaults — drop animation may not be disabled. Check @dnd-kit/dom version."),n},cb=P.div`
1045
1045
  position: absolute;
1046
1046
  top: 0;
1047
1047
  left: 0;
@@ -1051,9 +1051,9 @@ self.onmessage = function(e) {
1051
1051
  z-index: 100;
1052
1052
  pointer-events: none;
1053
1053
  will-change: transform;
1054
- `,cb=({color:e="#ff0000"})=>{const t=m.useRef(null),n=m.useRef(null),{isPlaying:r,currentTimeRef:s}=Vr(),{samplesPerPixel:a,sampleRate:o,progressBarWidth:i}=Js();return m.useEffect(()=>{const l=()=>{if(t.current){const u=(s.current??0)*o/a;t.current.style.transform=`translate3d(${u}px, 0, 0)`}r&&(n.current=requestAnimationFrame(l))};return r?n.current=requestAnimationFrame(l):l(),()=>{n.current&&(cancelAnimationFrame(n.current),n.current=null)}},[r,o,a,s]),m.useEffect(()=>{if(!r&&t.current){const c=(s.current??0)*o/a;t.current.style.transform=`translate3d(${c}px, 0, 0)`}}),C.jsx(lb,{ref:t,$color:e,$width:i,"data-playhead":!0})},ub=P.div`
1054
+ `,ub=({color:e="#ff0000"})=>{const t=m.useRef(null),n=m.useRef(null),{isPlaying:r,currentTimeRef:s}=Vr(),{samplesPerPixel:a,sampleRate:o,progressBarWidth:i}=Js();return m.useEffect(()=>{const l=()=>{if(t.current){const u=(s.current??0)*o/a;t.current.style.transform=`translate3d(${u}px, 0, 0)`}r&&(n.current=requestAnimationFrame(l))};return r?n.current=requestAnimationFrame(l):l(),()=>{n.current&&(cancelAnimationFrame(n.current),n.current=null)}},[r,o,a,s]),m.useEffect(()=>{if(!r&&t.current){const c=(s.current??0)*o/a;t.current.style.transform=`translate3d(${c}px, 0, 0)`}}),C.jsx(cb,{ref:t,$color:e,$width:i,"data-playhead":!0})},db=P.div`
1055
1055
  position: relative;
1056
- `,db=P.div`
1056
+ `,fb=P.div`
1057
1057
  position: absolute;
1058
1058
  top: ${e=>e.$top}px;
1059
1059
  left: 0;
@@ -1063,7 +1063,7 @@ self.onmessage = function(e) {
1063
1063
  z-index: 0;
1064
1064
  transform: translateZ(0);
1065
1065
  backface-visibility: hidden;
1066
- `,fb=P.div`
1066
+ `,hb=P.div`
1067
1067
  position: absolute;
1068
1068
  top: ${e=>e.$top}px;
1069
1069
  left: 0;
@@ -1072,8 +1072,8 @@ self.onmessage = function(e) {
1072
1072
  pointer-events: none;
1073
1073
  z-index: 1;
1074
1074
  will-change: width;
1075
- `,hb=P.div`
1075
+ `,pb=P.div`
1076
1076
  position: relative;
1077
1077
  z-index: 2;
1078
- `,pb=({clipStartSample:e,clipDurationSamples:t,...n})=>{const r=m.useRef(null),s=m.useRef(null),a=Br(),{waveHeight:o}=Ys(),{isPlaying:i,currentTimeRef:l}=Vr(),{samplesPerPixel:c,sampleRate:u}=Js(),f=a?.waveProgressColor||"rgba(0, 0, 0, 0.1)";m.useEffect(()=>{const v=()=>{if(r.current){const y=(l.current??0)*u,b=e+t;let w=0;if(y<=e)w=0;else if(y>=b)w=n.length;else{const _=y-e;w=Math.floor(_/c)}r.current.style.width=`${w}px`}i&&(s.current=requestAnimationFrame(v))};return i?s.current=requestAnimationFrame(v):v(),()=>{s.current&&(cancelAnimationFrame(s.current),s.current=null)}},[i,u,c,e,t,n.length,l]),m.useEffect(()=>{if(!i&&r.current){const g=(l.current??0)*u,y=e+t;let b=0;if(g<=e)b=0;else if(g>=y)b=n.length;else{const w=g-e;b=Math.floor(w/c)}r.current.style.width=`${b}px`}});const p=a?.waveformDrawMode||"inverted";let d;p==="inverted"?d=a?.selectedWaveFillColor||a?.waveFillColor||"white":d=a?.selectedWaveOutlineColor||a?.waveOutlineColor||"grey";const h=Kt(d);return C.jsxs(ub,{children:[C.jsx(db,{$color:h,$height:o,$top:n.index*o,$width:n.length}),C.jsx(fb,{ref:r,$color:f,$height:o,$top:n.index*o}),C.jsx(hb,{children:C.jsx(Yd,{...n,isSelected:!0,transparentBackground:!0})})]})},ic={current:0},mb=({renderPlayhead:e,color:t,samplesPerPixel:n,sampleRate:r})=>{const{isPlaying:s,currentTimeRef:a}=Vr();return e({position:(a.current??0)*r/n,color:t,isPlaying:s,currentTimeRef:a,playbackStartTimeRef:ic,audioStartPositionRef:ic,samplesPerPixel:n,sampleRate:r,controlsOffset:0})},Vf=({getAnnotationBoxLabel:e,editable:t=!1,linkEndpoints:n=!1,onAnnotationUpdate:r,renderPlayhead:s,className:a})=>{const o=Br(),{isPlaying:i}=Vr(),{annotations:l,activeAnnotationId:c}=qs(),u=m.useContext(Qs),{play:f,seekTo:p,setActiveAnnotationId:d,setAnnotations:h,setScrollContainer:v}=Si(),{duration:g,peaksDataArray:y,sampleRate:b,waveHeight:w,timeScaleHeight:_,samplesPerPixel:x,controls:S,playoutRef:k,barWidth:E,barGap:I}=Js(),[M,T]=m.useState(0),[A,$]=m.useState(0),[R,F]=m.useState(!1),O=m.useRef(null),G=m.useCallback(Z=>{O.current=Z,v(Z)},[v]),Q=Math.floor(g*b/x),ee=m.useCallback(async Z=>{d(Z.id);try{await f(Z.start)}catch(fe){console.error("waveform-playlist: Failed to start playback for annotation",Z.id,fe)}},[d,f]),ue=m.useCallback(Z=>{h(Z),r?.(Z)},[h,r]),{onDragStart:te,onDragMove:oe,onDragEnd:se}=af({annotations:l,onAnnotationsChange:ue,samplesPerPixel:x,sampleRate:b,duration:g,linkEndpoints:n}),le=m.useRef(0),ye=m.useCallback(Z=>{const fe=Z.currentTarget.getBoundingClientRect(),ae=(Z.clientX-fe.left)*x/b;le.current=ae,F(!0),T(ae),$(ae)},[x,b]),de=m.useCallback(Z=>{if(!R)return;const fe=Z.currentTarget.getBoundingClientRect(),ae=(Z.clientX-fe.left)*x/b;$(ae)},[R,x,b]),ne=m.useCallback(Z=>{if(!R)return;if(F(!1),i&&k.current){const $e=Math.max(0,le.current);p($e),T($e),$($e),k.current.stop(),f($e);return}const fe=Z.currentTarget.getBoundingClientRect(),ae=(Z.clientX-fe.left)*x/b,Te=Math.min(M,ae),B=Math.max(M,ae);Math.abs(B-Te)<.1?(p(Te),T(Te),$(Te)):(T(Te),$(B))},[R,M,x,b,p,i,k,f]);return y.length===0?C.jsx("div",{className:a,children:"Loading waveform..."}):C.jsx(Xd,{children:C.jsx(Lr.Provider,{value:{samplesPerPixel:x,sampleRate:b,zoomLevels:[x],waveHeight:w,timeScaleHeight:_,duration:g*1e3,controls:S,barWidth:E,barGap:I},children:C.jsx(wi,{theme:o,backgroundColor:Kt(o.waveOutlineColor),timescaleBackgroundColor:o.timescaleBackgroundColor,timescaleWidth:Q,tracksWidth:Q,controlsWidth:S.show?S.width:0,onTracksMouseDown:ye,onTracksMouseMove:de,onTracksMouseUp:ne,scrollContainerRef:G,isSelecting:R,timescale:_>0?C.jsx(Kd,{}):void 0,children:C.jsxs(C.Fragment,{children:[y.map((Z,fe)=>{const Fe=Z.length>0?Math.max(...Z.map(ae=>ae.peaks.data.length)):1;return C.jsx(qd,{numChannels:Fe,backgroundColor:Kt(o.waveOutlineColor),offset:0,width:Q,hasClipHeaders:!1,trackId:`media-element-track-${fe}`,isSelected:!0,children:Z.map((ae,Te)=>{const B=ae.peaks,$e=B.length;return C.jsx(lo,{clipId:ae.clipId,trackIndex:fe,clipIndex:Te,trackName:ae.trackName,startSample:ae.startSample,durationSamples:ae.durationSamples,samplesPerPixel:x,showHeader:!1,disableHeaderDrag:!0,isSelected:!0,trackId:`media-element-track-${fe}`,children:B.data.map((re,Ve)=>C.jsx(pb,{index:Ve,data:re,bits:B.bits,length:$e,clipStartSample:ae.startSample,clipDurationSamples:ae.durationSamples},`${fe}-${Te}-${Ve}`))},`${fe}-${Te}`)})},fe)}),l.length>0&&u&&C.jsx(Ef,{onDragStart:te,onDragMove:oe,onDragEnd:se,modifiers:t?[Wf]:[],plugins:Ii,children:C.jsx(u.AnnotationBoxesWrapper,{height:30,width:Q,children:l.map((Z,fe)=>{const Fe=Z.start*b/x,ae=Z.end*b/x,Te=e?e(Z,fe):Z.id;return C.jsx(u.AnnotationBox,{annotationId:Z.id,annotationIndex:fe,startPosition:Fe,endPosition:ae,label:Te,color:"#ff9800",isActive:Z.id===c,onClick:()=>ee(Z),editable:t},Z.id)})})}),M!==A&&C.jsx(Zd,{startPosition:Math.min(M,A)*b/x,endPosition:Math.max(M,A)*b/x,color:o.selectionColor}),s?C.jsx(mb,{renderPlayhead:s,color:o.playheadColor,samplesPerPixel:x,sampleRate:b}):C.jsx(cb,{color:o.playheadColor})]})})})})},Nf=({height:e,renderAnnotationItem:t,onAnnotationUpdate:n,editable:r=!1,controls:s,annotationListConfig:a,scrollActivePosition:o="center",scrollActiveContainer:i="nearest"})=>{const{annotations:l,activeAnnotationId:c,continuousPlay:u}=qs(),f=bn(),{setAnnotations:p}=Si(),d=a??{linkEndpoints:!1,continuousPlay:u},h=m.useCallback(g=>{p(g),n?.(g)},[p,n]),{AnnotationText:v}=f;return C.jsx(v,{annotations:l,activeAnnotationId:c??void 0,shouldScrollToActive:!0,scrollActivePosition:o,scrollActiveContainer:i,editable:r,controls:r?s:void 0,annotationListConfig:d,height:e,onAnnotationUpdate:h,renderAnnotationItem:t})},gb=({annotationTextHeight:e,getAnnotationBoxLabel:t,renderAnnotationItem:n,editable:r=!1,linkEndpoints:s=!1,onAnnotationUpdate:a,scrollActivePosition:o="center",scrollActiveContainer:i="nearest",renderPlayhead:l,className:c})=>{const{annotations:u}=qs();return C.jsxs(C.Fragment,{children:[C.jsx(Vf,{getAnnotationBoxLabel:t,editable:r,linkEndpoints:s,onAnnotationUpdate:a,renderPlayhead:l,className:c}),u.length>0&&C.jsx(Nf,{height:e,renderAnnotationItem:n,onAnnotationUpdate:a,editable:r,annotationListConfig:{linkEndpoints:s,continuousPlay:!1},scrollActivePosition:o,scrollActiveContainer:i})]})},vb=({playback:e=!1,clipSplitting:t=!1,annotations:n=!1,additionalShortcuts:r=[]})=>{const{tracks:s,samplesPerPixel:a,sampleRate:o,playoutRef:i,duration:l}=rt(),{annotations:c,linkEndpoints:u,activeAnnotationId:f,continuousPlay:p}=nt(),{setAnnotations:d,setActiveAnnotationId:h,scrollContainerRef:v,play:g}=Se(),{splitClipAtPlayhead:y}=lf({tracks:s,sampleRate:o,samplesPerPixel:a,engineRef:i}),b=[];return t&&b.push({key:"s",action:y,description:"Split clip at playhead",preventDefault:!0}),r.length>0&&b.push(...r),cf({enabled:e||b.length>0,...e?{additionalShortcuts:b}:{shortcuts:b}}),uf({annotations:c,activeAnnotationId:f,onAnnotationsChange:d,onActiveAnnotationChange:h,duration:l,linkEndpoints:u,continuousPlay:p,scrollContainerRef:v,samplesPerPixel:a,sampleRate:o,onPlay:g,enabled:n&&c.length>0}),null},Os=class Os extends Fn{apply(t){const{transform:n,source:r}=t;if(!r?.data||!this.options)return n;const{boundary:s,trackIndex:a,clipIndex:o}=r.data;if(s)return{x:0,y:0};const{tracks:i,samplesPerPixel:l}=this.options,c=i[a];if(!c)return n;const u=c.clips[o];if(!u)return n;const f=n.x*l,p=[...c.clips].sort((v,g)=>v.startSample-g.startSample),d=p.findIndex(v=>v.id===u.id);return{x:gc(u,f,p,d)/l,y:0}}};Os.configure=pn(Os);let Fs=Os;const Ls=class Ls extends Fn{apply(t){const{transform:n,source:r}=t;if(!this.options||!r?.data)return n;const{boundary:s,startSample:a}=r.data;if(s)return n;const{samplesPerPixel:o}=this.options;if(this.options.mode==="timescale"){const{gridSamples:g}=this.options;if(a!==void 0){const w=a+n.x*o;return{x:(Math.round(w/g)*g-a)/o,y:0}}const y=n.x*o;return{x:Math.round(y/g)*g/o,y:0}}const{snapTo:i,bpm:l,timeSignature:c,sampleRate:u}=this.options;if(i==="off")return n;const f=i==="bar"?go(c):Bs(c);if(a!==void 0){const g=a+n.x*o,y=Ea(g,l,u),b=Ia(y,f);return{x:($n(b,l,u)-a)/o,y:0}}const p=n.x*o,d=Ea(p,l,u),h=Ia(d,f);return{x:$n(h,l,u)/o,y:0}}};Ls.configure=pn(Ls);let Er=Ls;const yb=()=>{},bb=({snap:e=!1,touchOptimized:t=!1,children:n})=>{const{tracks:r,samplesPerPixel:s,sampleRate:a,playoutRef:o,isDraggingRef:i,onTracksChange:l}=rt(),{setSelectedTrackId:c}=Se(),u=Gd(),f=e&&u!=null&&u.scaleMode==="beats"&&u.snapTo!=="off",p=e&&!f;m.useEffect(()=>{l==null&&console.warn("[waveform-playlist] ClipInteractionProvider: onTracksChange is not set on WaveformPlaylistProvider. Drag and trim edits will not be persisted.")},[l]);const d=m.useMemo(()=>{if(f&&u){const{bpm:_,timeSignature:x,snapTo:S}=u,k=S==="bar"?go(x):Bs(x);return E=>{const I=Ea(E,_,a),M=Ia(I,k);return $n(M,_,a)}}if(p){const _=Math.round(co(s).smallStep/1e3*a);return x=>Math.round(x/_)*_}},[f,p,u,a,s]),h=of({touchOptimized:t}),{onDragStart:v,onDragMove:g,onDragEnd:y}=sf({tracks:r,onTracksChange:l??yb,samplesPerPixel:s,sampleRate:a,engineRef:o,isDraggingRef:i,snapSamplePosition:d}),b=m.useCallback(_=>{const x=_.operation?.source?.data?.trackIndex;x!==void 0&&r[x]&&c(r[x].id),v(_)},[v,r,c]),w=m.useMemo(()=>{const _=[Wf];return f&&u?_.push(Er.configure({mode:"beats",snapTo:u.snapTo,bpm:u.bpm,timeSignature:u.timeSignature,samplesPerPixel:s,sampleRate:a})):p&&_.push(Er.configure({mode:"timescale",gridSamples:Math.round(co(s).smallStep/1e3*a),samplesPerPixel:s})),_.push(Fs.configure({tracks:r,samplesPerPixel:s})),_},[f,p,u,r,s,a]);return C.jsx(Iy,{value:!0,children:C.jsx(Ef,{sensors:h,onDragStart:b,onDragMove:g,onDragEnd:y,modifiers:w,plugins:Ii,children:n})})};exports.Tone=cc;exports.AnnotationIntegrationProvider=_y;exports.AudioPosition=yy;exports.AutomaticScrollCheckbox=wy;exports.ClearAllButton=fy;exports.ClipCollisionModifier=Fs;exports.ClipInteractionProvider=bb;exports.ContinuousPlayCheckbox=xy;exports.DownloadAnnotationsButton=ky;exports.EditableCheckbox=Sy;exports.ExportWavButton=Ey;exports.FastForwardButton=iy;exports.KeyboardShortcuts=vb;exports.LinkEndpointsCheckbox=Cy;exports.LoopButton=uy;exports.MasterVolumeControl=my;exports.MediaElementAnnotationList=Nf;exports.MediaElementPlaylist=Vf;exports.MediaElementPlaylistProvider=ny;exports.MediaElementWaveform=gb;exports.PauseButton=sy;exports.PlayButton=ry;exports.PlaylistAnnotationList=Sf;exports.PlaylistVisualization=Cf;exports.RewindButton=oy;exports.SelectionTimeInputs=by;exports.SetLoopRegionButton=dy;exports.SkipBackwardButton=ly;exports.SkipForwardButton=cy;exports.SnapToGridModifier=Er;exports.SpectrogramIntegrationProvider=Dy;exports.StopButton=ay;exports.TimeFormatSelect=gy;exports.Waveform=By;exports.WaveformPlaylistProvider=Q0;exports.ZoomInButton=hy;exports.ZoomOutButton=py;exports.createEffectChain=W0;exports.createEffectInstance=kr;exports.effectCategories=F0;exports.effectDefinitions=Wr;exports.getEffectDefinition=Ci;exports.getEffectsByCategory=P0;exports.getShortcutLabel=D0;exports.getWaveformDataMetadata=S0;exports.loadPeaksFromWaveformData=C0;exports.loadWaveformData=xi;exports.noDropAnimationPlugins=Ii;exports.useAnnotationDragHandlers=af;exports.useAnnotationIntegration=bn;exports.useAnnotationKeyboardControls=uf;exports.useAudioTracks=T0;exports.useClipDragHandlers=sf;exports.useClipInteractionEnabled=xf;exports.useClipSplitting=lf;exports.useDragSensors=of;exports.useDynamicEffects=V0;exports.useDynamicTracks=J0;exports.useExportWav=df;exports.useKeyboardShortcuts=Ps;exports.useMasterAnalyser=A0;exports.useMasterVolume=rf;exports.useMediaElementAnimation=Vr;exports.useMediaElementControls=Si;exports.useMediaElementData=Js;exports.useMediaElementState=qs;exports.usePlaybackAnimation=tt;exports.usePlaybackShortcuts=cf;exports.usePlaylistControls=Se;exports.usePlaylistData=rt;exports.usePlaylistState=nt;exports.useSpectrogramIntegration=Py;exports.useTimeFormat=tf;exports.useTrackDynamicEffects=N0;exports.useZoomControls=nf;exports.waveformDataToPeaks=Qd;
1078
+ `,mb=({clipStartSample:e,clipDurationSamples:t,...n})=>{const r=m.useRef(null),s=m.useRef(null),a=Br(),{waveHeight:o}=Ys(),{isPlaying:i,currentTimeRef:l}=Vr(),{samplesPerPixel:c,sampleRate:u}=Js(),f=a?.waveProgressColor||"rgba(0, 0, 0, 0.1)";m.useEffect(()=>{const v=()=>{if(r.current){const y=(l.current??0)*u,b=e+t;let w=0;if(y<=e)w=0;else if(y>=b)w=n.length;else{const _=y-e;w=Math.floor(_/c)}r.current.style.width=`${w}px`}i&&(s.current=requestAnimationFrame(v))};return i?s.current=requestAnimationFrame(v):v(),()=>{s.current&&(cancelAnimationFrame(s.current),s.current=null)}},[i,u,c,e,t,n.length,l]),m.useEffect(()=>{if(!i&&r.current){const g=(l.current??0)*u,y=e+t;let b=0;if(g<=e)b=0;else if(g>=y)b=n.length;else{const w=g-e;b=Math.floor(w/c)}r.current.style.width=`${b}px`}});const p=a?.waveformDrawMode||"inverted";let d;p==="inverted"?d=a?.selectedWaveFillColor||a?.waveFillColor||"white":d=a?.selectedWaveOutlineColor||a?.waveOutlineColor||"grey";const h=Kt(d);return C.jsxs(db,{children:[C.jsx(fb,{$color:h,$height:o,$top:n.index*o,$width:n.length}),C.jsx(hb,{ref:r,$color:f,$height:o,$top:n.index*o}),C.jsx(pb,{children:C.jsx(Yd,{...n,isSelected:!0,transparentBackground:!0})})]})},ic={current:0},gb=({renderPlayhead:e,color:t,samplesPerPixel:n,sampleRate:r})=>{const{isPlaying:s,currentTimeRef:a}=Vr();return e({position:(a.current??0)*r/n,color:t,isPlaying:s,currentTimeRef:a,playbackStartTimeRef:ic,audioStartPositionRef:ic,samplesPerPixel:n,sampleRate:r,controlsOffset:0})},Vf=({getAnnotationBoxLabel:e,editable:t=!1,linkEndpoints:n=!1,onAnnotationUpdate:r,renderPlayhead:s,className:a})=>{const o=Br(),{isPlaying:i}=Vr(),{annotations:l,activeAnnotationId:c}=qs(),u=m.useContext(Qs),{play:f,seekTo:p,setActiveAnnotationId:d,setAnnotations:h,setScrollContainer:v}=Si(),{duration:g,peaksDataArray:y,sampleRate:b,waveHeight:w,timeScaleHeight:_,samplesPerPixel:x,controls:S,playoutRef:k,barWidth:E,barGap:I}=Js(),[M,T]=m.useState(0),[A,$]=m.useState(0),[R,F]=m.useState(!1),O=m.useRef(null),G=m.useCallback(Z=>{O.current=Z,v(Z)},[v]),Q=Math.floor(g*b/x),ee=m.useCallback(async Z=>{d(Z.id);try{await f(Z.start)}catch(fe){console.error("waveform-playlist: Failed to start playback for annotation",Z.id,fe)}},[d,f]),ue=m.useCallback(Z=>{h(Z),r?.(Z)},[h,r]),{onDragStart:te,onDragMove:oe,onDragEnd:se}=af({annotations:l,onAnnotationsChange:ue,samplesPerPixel:x,sampleRate:b,duration:g,linkEndpoints:n}),le=m.useRef(0),ye=m.useCallback(Z=>{const fe=Z.currentTarget.getBoundingClientRect(),ae=(Z.clientX-fe.left)*x/b;le.current=ae,F(!0),T(ae),$(ae)},[x,b]),de=m.useCallback(Z=>{if(!R)return;const fe=Z.currentTarget.getBoundingClientRect(),ae=(Z.clientX-fe.left)*x/b;$(ae)},[R,x,b]),ne=m.useCallback(Z=>{if(!R)return;if(F(!1),i&&k.current){const $e=Math.max(0,le.current);p($e),T($e),$($e),k.current.stop(),f($e);return}const fe=Z.currentTarget.getBoundingClientRect(),ae=(Z.clientX-fe.left)*x/b,Te=Math.min(M,ae),B=Math.max(M,ae);Math.abs(B-Te)<.1?(p(Te),T(Te),$(Te)):(T(Te),$(B))},[R,M,x,b,p,i,k,f]);return y.length===0?C.jsx("div",{className:a,children:"Loading waveform..."}):C.jsx(Xd,{children:C.jsx(Lr.Provider,{value:{samplesPerPixel:x,sampleRate:b,zoomLevels:[x],waveHeight:w,timeScaleHeight:_,duration:g*1e3,controls:S,barWidth:E,barGap:I},children:C.jsx(wi,{theme:o,backgroundColor:Kt(o.waveOutlineColor),timescaleBackgroundColor:o.timescaleBackgroundColor,timescaleWidth:Q,tracksWidth:Q,controlsWidth:S.show?S.width:0,onTracksMouseDown:ye,onTracksMouseMove:de,onTracksMouseUp:ne,scrollContainerRef:G,isSelecting:R,timescale:_>0?C.jsx(Kd,{}):void 0,children:C.jsxs(C.Fragment,{children:[y.map((Z,fe)=>{const Fe=Z.length>0?Math.max(...Z.map(ae=>ae.peaks.data.length)):1;return C.jsx(qd,{numChannels:Fe,backgroundColor:Kt(o.waveOutlineColor),offset:0,width:Q,hasClipHeaders:!1,trackId:`media-element-track-${fe}`,isSelected:!0,children:Z.map((ae,Te)=>{const B=ae.peaks,$e=B.length;return C.jsx(lo,{clipId:ae.clipId,trackIndex:fe,clipIndex:Te,trackName:ae.trackName,startSample:ae.startSample,durationSamples:ae.durationSamples,samplesPerPixel:x,showHeader:!1,disableHeaderDrag:!0,isSelected:!0,trackId:`media-element-track-${fe}`,children:B.data.map((re,Ve)=>C.jsx(mb,{index:Ve,data:re,bits:B.bits,length:$e,clipStartSample:ae.startSample,clipDurationSamples:ae.durationSamples},`${fe}-${Te}-${Ve}`))},`${fe}-${Te}`)})},fe)}),l.length>0&&u&&C.jsx(Ef,{onDragStart:te,onDragMove:oe,onDragEnd:se,modifiers:t?[Wf]:[],plugins:Ii,children:C.jsx(u.AnnotationBoxesWrapper,{height:30,width:Q,children:l.map((Z,fe)=>{const Fe=Z.start*b/x,ae=Z.end*b/x,Te=e?e(Z,fe):Z.id;return C.jsx(u.AnnotationBox,{annotationId:Z.id,annotationIndex:fe,startPosition:Fe,endPosition:ae,label:Te,color:"#ff9800",isActive:Z.id===c,onClick:()=>ee(Z),editable:t},Z.id)})})}),M!==A&&C.jsx(Zd,{startPosition:Math.min(M,A)*b/x,endPosition:Math.max(M,A)*b/x,color:o.selectionColor}),s?C.jsx(gb,{renderPlayhead:s,color:o.playheadColor,samplesPerPixel:x,sampleRate:b}):C.jsx(ub,{color:o.playheadColor})]})})})})},Nf=({height:e,renderAnnotationItem:t,onAnnotationUpdate:n,editable:r=!1,controls:s,annotationListConfig:a,scrollActivePosition:o="center",scrollActiveContainer:i="nearest"})=>{const{annotations:l,activeAnnotationId:c,continuousPlay:u}=qs(),f=bn(),{setAnnotations:p}=Si(),d=a??{linkEndpoints:!1,continuousPlay:u},h=m.useCallback(g=>{p(g),n?.(g)},[p,n]),{AnnotationText:v}=f;return C.jsx(v,{annotations:l,activeAnnotationId:c??void 0,shouldScrollToActive:!0,scrollActivePosition:o,scrollActiveContainer:i,editable:r,controls:r?s:void 0,annotationListConfig:d,height:e,onAnnotationUpdate:h,renderAnnotationItem:t})},vb=({annotationTextHeight:e,getAnnotationBoxLabel:t,renderAnnotationItem:n,editable:r=!1,linkEndpoints:s=!1,onAnnotationUpdate:a,scrollActivePosition:o="center",scrollActiveContainer:i="nearest",renderPlayhead:l,className:c})=>{const{annotations:u}=qs();return C.jsxs(C.Fragment,{children:[C.jsx(Vf,{getAnnotationBoxLabel:t,editable:r,linkEndpoints:s,onAnnotationUpdate:a,renderPlayhead:l,className:c}),u.length>0&&C.jsx(Nf,{height:e,renderAnnotationItem:n,onAnnotationUpdate:a,editable:r,annotationListConfig:{linkEndpoints:s,continuousPlay:!1},scrollActivePosition:o,scrollActiveContainer:i})]})},yb=({playback:e=!1,clipSplitting:t=!1,annotations:n=!1,additionalShortcuts:r=[]})=>{const{tracks:s,samplesPerPixel:a,sampleRate:o,playoutRef:i,duration:l}=rt(),{annotations:c,linkEndpoints:u,activeAnnotationId:f,continuousPlay:p}=nt(),{setAnnotations:d,setActiveAnnotationId:h,scrollContainerRef:v,play:g}=Se(),{splitClipAtPlayhead:y}=lf({tracks:s,sampleRate:o,samplesPerPixel:a,engineRef:i}),b=[];return t&&b.push({key:"s",action:y,description:"Split clip at playhead",preventDefault:!0}),r.length>0&&b.push(...r),cf({enabled:e||b.length>0,...e?{additionalShortcuts:b}:{shortcuts:b}}),uf({annotations:c,activeAnnotationId:f,onAnnotationsChange:d,onActiveAnnotationChange:h,duration:l,linkEndpoints:u,continuousPlay:p,scrollContainerRef:v,samplesPerPixel:a,sampleRate:o,onPlay:g,enabled:n&&c.length>0}),null},Os=class Os extends Fn{apply(t){const{transform:n,source:r}=t;if(!r?.data||!this.options)return n;const{boundary:s,trackIndex:a,clipIndex:o}=r.data;if(s)return{x:0,y:0};const{tracks:i,samplesPerPixel:l}=this.options,c=i[a];if(!c)return n;const u=c.clips[o];if(!u)return n;const f=n.x*l,p=[...c.clips].sort((v,g)=>v.startSample-g.startSample),d=p.findIndex(v=>v.id===u.id);return{x:gc(u,f,p,d)/l,y:0}}};Os.configure=pn(Os);let Fs=Os;const Ls=class Ls extends Fn{apply(t){const{transform:n,source:r}=t;if(!this.options||!r?.data)return n;const{boundary:s,startSample:a}=r.data;if(s)return n;const{samplesPerPixel:o}=this.options;if(this.options.mode==="timescale"){const{gridSamples:g}=this.options;if(a!==void 0){const w=a+n.x*o;return{x:(Math.round(w/g)*g-a)/o,y:0}}const y=n.x*o;return{x:Math.round(y/g)*g/o,y:0}}const{snapTo:i,bpm:l,timeSignature:c,sampleRate:u}=this.options;if(i==="off")return n;const f=i==="bar"?go(c):Bs(c);if(a!==void 0){const g=a+n.x*o,y=Ea(g,l,u),b=Ia(y,f);return{x:($n(b,l,u)-a)/o,y:0}}const p=n.x*o,d=Ea(p,l,u),h=Ia(d,f);return{x:$n(h,l,u)/o,y:0}}};Ls.configure=pn(Ls);let Er=Ls;const bb=()=>{},wb=({snap:e=!1,touchOptimized:t=!1,children:n})=>{const{tracks:r,samplesPerPixel:s,sampleRate:a,playoutRef:o,isDraggingRef:i,onTracksChange:l}=rt(),{setSelectedTrackId:c}=Se(),u=Gd(),f=e&&u!=null&&u.scaleMode==="beats"&&u.snapTo!=="off",p=e&&!f;m.useEffect(()=>{l==null&&console.warn("[waveform-playlist] ClipInteractionProvider: onTracksChange is not set on WaveformPlaylistProvider. Drag and trim edits will not be persisted.")},[l]);const d=m.useMemo(()=>{if(f&&u){const{bpm:_,timeSignature:x,snapTo:S}=u,k=S==="bar"?go(x):Bs(x);return E=>{const I=Ea(E,_,a),M=Ia(I,k);return $n(M,_,a)}}if(p){const _=Math.round(co(s).smallStep/1e3*a);return x=>Math.round(x/_)*_}},[f,p,u,a,s]),h=of({touchOptimized:t}),{onDragStart:v,onDragMove:g,onDragEnd:y}=sf({tracks:r,onTracksChange:l??bb,samplesPerPixel:s,sampleRate:a,engineRef:o,isDraggingRef:i,snapSamplePosition:d}),b=m.useCallback(_=>{const x=_.operation?.source?.data?.trackIndex;x!==void 0&&r[x]&&c(r[x].id),v(_)},[v,r,c]),w=m.useMemo(()=>{const _=[Wf];return f&&u?_.push(Er.configure({mode:"beats",snapTo:u.snapTo,bpm:u.bpm,timeSignature:u.timeSignature,samplesPerPixel:s,sampleRate:a})):p&&_.push(Er.configure({mode:"timescale",gridSamples:Math.round(co(s).smallStep/1e3*a),samplesPerPixel:s})),_.push(Fs.configure({tracks:r,samplesPerPixel:s})),_},[f,p,u,r,s,a]);return C.jsx(My,{value:!0,children:C.jsx(Ef,{sensors:h,onDragStart:b,onDragMove:g,onDragEnd:y,modifiers:w,plugins:Ii,children:n})})};exports.Tone=cc;exports.AnnotationIntegrationProvider=xy;exports.AudioPosition=by;exports.AutomaticScrollCheckbox=_y;exports.ClearAllButton=hy;exports.ClipCollisionModifier=Fs;exports.ClipInteractionProvider=wb;exports.ContinuousPlayCheckbox=Cy;exports.DownloadAnnotationsButton=Ey;exports.EditableCheckbox=ky;exports.ExportWavButton=Iy;exports.FastForwardButton=ly;exports.KeyboardShortcuts=yb;exports.LinkEndpointsCheckbox=Sy;exports.LoopButton=dy;exports.MasterVolumeControl=gy;exports.MediaElementAnnotationList=Nf;exports.MediaElementPlaylist=Vf;exports.MediaElementPlaylistProvider=ry;exports.MediaElementWaveform=vb;exports.PauseButton=ay;exports.PlayButton=sy;exports.PlaylistAnnotationList=Sf;exports.PlaylistVisualization=Cf;exports.RewindButton=iy;exports.SelectionTimeInputs=wy;exports.SetLoopRegionButton=fy;exports.SkipBackwardButton=cy;exports.SkipForwardButton=uy;exports.SnapToGridModifier=Er;exports.SpectrogramIntegrationProvider=Py;exports.StopButton=oy;exports.TimeFormatSelect=vy;exports.Waveform=Wy;exports.WaveformPlaylistProvider=ey;exports.ZoomInButton=py;exports.ZoomOutButton=my;exports.createEffectChain=V0;exports.createEffectInstance=kr;exports.effectCategories=O0;exports.effectDefinitions=Wr;exports.getEffectDefinition=Ci;exports.getEffectsByCategory=F0;exports.getShortcutLabel=P0;exports.getWaveformDataMetadata=S0;exports.loadPeaksFromWaveformData=C0;exports.loadWaveformData=xi;exports.noDropAnimationPlugins=Ii;exports.useAnnotationDragHandlers=af;exports.useAnnotationIntegration=bn;exports.useAnnotationKeyboardControls=uf;exports.useAudioTracks=T0;exports.useClipDragHandlers=sf;exports.useClipInteractionEnabled=xf;exports.useClipSplitting=lf;exports.useDragSensors=of;exports.useDynamicEffects=N0;exports.useDynamicTracks=Q0;exports.useExportWav=df;exports.useKeyboardShortcuts=Ps;exports.useMasterAnalyser=A0;exports.useMasterVolume=rf;exports.useMediaElementAnimation=Vr;exports.useMediaElementControls=Si;exports.useMediaElementData=Js;exports.useMediaElementState=qs;exports.usePlaybackAnimation=tt;exports.usePlaybackShortcuts=cf;exports.usePlaylistControls=Se;exports.usePlaylistData=rt;exports.usePlaylistState=nt;exports.useSpectrogramIntegration=Fy;exports.useTimeFormat=tf;exports.useTrackDynamicEffects=j0;exports.useZoomControls=nf;exports.waveformDataToPeaks=Qd;
1079
1079
  //# sourceMappingURL=index.js.map