UNPKG

audio-inspect

Version:

Lightweight yet powerful audio analysis library

2 lines 67.4 kB
// audio-inspect - Lightweight yet powerful audio analysis library var y=class e extends Error{constructor(n,a,r,s){super(a,{cause:r});this.code=n;this.details=s;this.cause=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}name="AudioInspectError";timestamp=new Date;cause;toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,timestamp:this.timestamp,stack:this.stack,cause:this.cause}}};function Ge(e,t,n){return new y(e,t,void 0,n)}function Ze(e){return e instanceof y}async function Qe(e,t={}){try{if(Ye(e))return await me(e,t);let n=Je(),a=await Xe(e,n),r=fe(a);return await me(r,t)}catch(n){throw new y("DECODE_ERROR",`\u97F3\u58F0\u30C7\u30FC\u30BF\u306E\u8AAD\u307F\u8FBC\u307F\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${n instanceof Error?n.message:"Unknown error"}`,n)}}function Ye(e){return typeof e=="object"&&e!==null&&"sampleRate"in e&&"channelData"in e&&"duration"in e&&"numberOfChannels"in e&&"length"in e}function Je(){if(typeof AudioContext<"u")return new AudioContext;throw new y("UNSUPPORTED_FORMAT","\u3053\u306E\u74B0\u5883\u3067\u306FWeb Audio API\u304C\u5229\u7528\u3067\u304D\u307E\u305B\u3093")}async function Xe(e,t){if(e instanceof AudioBuffer)return e;if(e instanceof ArrayBuffer)return await t.decodeAudioData(e);if(e instanceof Blob||e instanceof File){let n=await e.arrayBuffer();return await t.decodeAudioData(n)}if(typeof e=="string"||e instanceof URL){let n=e instanceof URL?e.href:e,a=await fetch(n);if(!a.ok)throw new y("NETWORK_ERROR",`\u97F3\u58F0\u30D5\u30A1\u30A4\u30EB\u306E\u53D6\u5F97\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${a.status}`);let r=await a.arrayBuffer();return await t.decodeAudioData(r)}throw e instanceof MediaStream?new y("UNSUPPORTED_FORMAT","MediaStream\u306E\u51E6\u7406\u306F\u73FE\u5728\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093"):new y("INVALID_INPUT","\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u306A\u3044\u97F3\u58F0\u30BD\u30FC\u30B9\u3067\u3059")}function fe(e){let t=[];for(let n=0;n<e.numberOfChannels;n++)t.push(e.getChannelData(n));return{sampleRate:e.sampleRate,channelData:t,duration:e.duration,numberOfChannels:e.numberOfChannels,length:e.length}}async function me(e,t){let n=e;if((t.channels==="mono"||t.channels===1)&&(n=tt(n)),t.normalize&&(n=nt(n)),t.sampleRate&&t.sampleRate!==n.sampleRate)try{n=await et(n,t.sampleRate)}catch(a){throw console.warn("\u30B5\u30F3\u30D7\u30EB\u30EC\u30FC\u30C8\u5909\u63DB\u306B\u5931\u6557\u3057\u307E\u3057\u305F:",a),new y("PROCESSING_ERROR",`\u30B5\u30F3\u30D7\u30EB\u30EC\u30FC\u30C8\u5909\u63DB\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${a instanceof Error?a.message:"Unknown error"}`)}return n}async function et(e,t){if(typeof OfflineAudioContext>"u")throw new y("UNSUPPORTED_FORMAT","\u3053\u306E\u74B0\u5883\u3067\u306F\u30B5\u30F3\u30D7\u30EB\u30EC\u30FC\u30C8\u5909\u63DB\u304C\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093");let n=e.sampleRate,a=e.length,r=Math.floor(a*t/n),s=new OfflineAudioContext(e.numberOfChannels,r,t),i=s.createBuffer(e.numberOfChannels,a,n);for(let c=0;c<e.numberOfChannels;c++){let m=e.channelData[c];m&&i.copyToChannel(m,c)}let l=s.createBufferSource();l.buffer=i,l.connect(s.destination),l.start(0);let o=await s.startRendering();return fe(o)}function tt(e){if(e.numberOfChannels===1)return e;let t=new Float32Array(e.length);for(let n=0;n<e.length;n++){let a=0;for(let r=0;r<e.numberOfChannels;r++){let s=e.channelData[r],i=s?.[n];s&&i!==void 0&&(a+=i)}t[n]=a/e.numberOfChannels}return{sampleRate:e.sampleRate,channelData:[t],duration:e.duration,numberOfChannels:1,length:e.length}}function nt(e){let t=0;for(let a of e.channelData)for(let r of a)t=Math.max(t,Math.abs(r));if(t===0)return e;let n=e.channelData.map(a=>{let r=new Float32Array(a.length);for(let s=0;s<a.length;s++){let i=a[s];r[s]=i!==void 0?i/t:0}return r});return{...e,channelData:n}}async function rt(e,t){try{return at(e),await t(e)}catch(n){if(n instanceof y)throw n;let a=n instanceof Error?n.message:"Unknown error";throw new y("PROCESSING_ERROR",`Feature extraction failed: ${a}`,n)}}function at(e){if(!e||typeof e!="object")throw new y("INVALID_INPUT","AudioData is invalid");if(typeof e.sampleRate!="number"||e.sampleRate<=0)throw new y("INVALID_INPUT","Sample rate is invalid");if(!Array.isArray(e.channelData)||e.channelData.length===0)throw new y("INVALID_INPUT","Channel data is invalid");if(typeof e.numberOfChannels!="number"||e.numberOfChannels!==e.channelData.length)throw new y("INVALID_INPUT","Number of channels does not match");if(typeof e.length!="number"||e.length<=0)throw new y("INVALID_INPUT","Data length is invalid");if(typeof e.duration!="number"||e.duration<=0)throw new y("INVALID_INPUT","Audio duration is invalid");let t=e.channelData[0];if(!t)throw new y("INVALID_INPUT","Channel 0 data does not exist");let n=t.length;for(let a=0;a<e.channelData.length;a++){let r=e.channelData[a];if(!(r instanceof Float32Array))throw new y("INVALID_INPUT",`Channel ${a} data is not a Float32Array`);if(r.length!==n)throw new y("INVALID_INPUT",`Channel ${a} data length does not match`)}}var ot=typeof process<"u"?process.env.NODE_ENV!=="production":!1,he=typeof AudioWorkletNode<"u",J=class{numberOfInputs=1;numberOfOutputs=0;channelCount=2;channelCountMode="max";channelInterpretation="speakers";context=null;port={postMessage:()=>{},close:()=>{},onmessage:null};constructor(){}connect(){return this}disconnect(){return this}dispatchEvent(){return!0}addEventListener(){}removeEventListener(){}},W=class extends(he?AudioWorkletNode:J){onresult;onerror;_featureName="getRMS";_featureOptions;_bufferSize=1024;_hopSize=512;_provider;disposed=!1;cleanupInterval;constructor(t,n){if(!he){super(),this._initializeMockMode(n);return}if(!t)throw new y("INITIALIZATION_FAILED","AudioContext is required in browser environment");let a={featureName:"getRMS",bufferSize:1024,hopSize:512,inputChannelCount:1,provider:"native",...n},r={featureName:a.featureName,featureOptions:a.featureOptions,bufferSize:a.bufferSize,hopSize:a.hopSize,inputChannelCount:a.inputChannelCount,provider:a.provider};super(t,"audio-inspect-processor",{processorOptions:r,numberOfInputs:1,numberOfOutputs:0,channelCount:a.inputChannelCount,channelCountMode:"explicit",channelInterpretation:"speakers"}),this._featureName=a.featureName,this._featureOptions=a.featureOptions,this._bufferSize=a.bufferSize,this._hopSize=a.hopSize,this._provider=a.provider,this.setupMessageHandler(),this.setupCleanupInterval()}_initializeMockMode(t){let n={featureName:"getRMS",bufferSize:1024,hopSize:512,provider:"native",...t};this._featureName=n.featureName,this._featureOptions=n.featureOptions,this._bufferSize=n.bufferSize,this._hopSize=n.hopSize,this._provider=n.provider}getPort(){return this.port}setupMessageHandler(){let t=this.getPort();t&&(t.onmessage=this.handleMessage.bind(this))}setupCleanupInterval(){typeof window<"u"&&(this.cleanupInterval=window.setInterval(()=>{if(this.disposed){this.cleanupInterval&&clearInterval(this.cleanupInterval);return}this.performCleanup()},3e4))}performCleanup(){let t=this.getPort();t&&"postMessage"in t&&t.postMessage({type:"cleanup"})}get featureName(){return this._featureName}get featureOptions(){return this._featureOptions}get bufferSize(){return this._bufferSize}get hopSize(){return this._hopSize}get provider(){return this._provider}updateOptions(t){let n={};if(t.featureName!==void 0&&t.featureName!==this._featureName&&(this._featureName=t.featureName,n.featureName=t.featureName),t.featureOptions!==void 0&&(this._featureOptions=t.featureOptions,n.featureOptions=t.featureOptions),t.bufferSize!==void 0&&t.bufferSize!==this._bufferSize&&(this._bufferSize=t.bufferSize,n.bufferSize=t.bufferSize),t.hopSize!==void 0&&t.hopSize!==this._hopSize&&(this._hopSize=t.hopSize,n.hopSize=t.hopSize),t.inputChannelCount!==void 0&&(n.inputChannelCount=t.inputChannelCount),t.provider!==void 0&&t.provider!==this._provider&&(this._provider=t.provider,n.provider=t.provider),Object.keys(n).length>0){let a={type:"updateOptions",payload:n},r=this.getPort();r&&"postMessage"in r&&r.postMessage(a)}}reset(){let t=this.getPort();t&&"postMessage"in t&&t.postMessage({type:"reset"})}dispose(){if(this.disposed)return;this.disposed=!0,this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=void 0),this.disconnect();let t=this.getPort();t&&"close"in t&&t.close()}handleMessage(t){let n=t.data;switch(n.type){case"analysisResult":this.handleAnalysisResult(n);break;case"error":this.handleError(n);break;default:ot&&console.warn("Unknown message type:",n.type)}}handleAnalysisResult(t){let n={data:t.data,timestamp:t.timestamp};this.onresult&&this.onresult(n),"dispatchEvent"in this&&this.dispatchEvent(new CustomEvent("result",{detail:n}))}handleError(t){let n={message:t.message,detail:t.detail};this.onerror&&this.onerror(n),"dispatchEvent"in this&&this.dispatchEvent(new CustomEvent("error",{detail:n}))}};var pe=new WeakSet;function st(e){return pe.has(e)}function it(e){pe.add(e)}async function de(e,t){try{if(e.audioWorklet&&"addModule"in e.audioWorklet)await e.audioWorklet.addModule(t,{credentials:"omit"});else throw new y("WORKLET_NOT_SUPPORTED","AudioWorklet is not supported in this environment");it(e)}catch(n){throw n instanceof Error&&n.message.includes("Failed to load module script")?new y("MODULE_LOAD_FAILED","Failed to load AudioWorklet module. Ensure the processor file is served with correct MIME type (application/javascript)",n):new y("INITIALIZATION_FAILED",`AudioWorklet module registration failed: ${n instanceof Error?n.message:String(n)}`,n)}}var X=class{_paused=!1;inspectNode;sourceNode;constructor(t,n,a,r,s){this.sourceNode=n,this.inspectNode=a,r&&(this.inspectNode.onresult=i=>r(i.data)),s&&(this.inspectNode.onerror=s),this.sourceNode.connect(this.inspectNode)}pause(){this._paused||(this.sourceNode.disconnect(this.inspectNode),this._paused=!0)}resume(){this._paused&&(this.sourceNode.connect(this.inspectNode),this._paused=!1)}stop(){this.sourceNode.disconnect(this.inspectNode),this.inspectNode.dispose(),this._paused=!0}get paused(){return this._paused}};async function ge(e,t,n,a,r){let s=typeof t=="string"?t:t.name;if(!s)throw new y("INVALID_INPUT","\u89E3\u6790\u6A5F\u80FD\u540D\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093");let i,l;if(e instanceof MediaStream)i=new AudioContext,l=i.createMediaStreamSource(e);else if(e instanceof AudioNode)i=e.context,l=e;else if(e instanceof AudioBuffer)i=new AudioContext,l=i.createBufferSource(),l.buffer=e,l.start();else throw new y("UNSUPPORTED_FORMAT","\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u306A\u3044\u97F3\u58F0\u30BD\u30FC\u30B9\u5F62\u5F0F\u3067\u3059");try{await de(i,n.processorModuleUrl);let o={featureName:s,bufferSize:n?.bufferSize||1024,hopSize:n?.hopSize||512,inputChannelCount:1},c=new W(i,o);return new X(i,l,c,a,r)}catch(o){throw new y("INITIALIZATION_FAILED",`\u30B9\u30C8\u30EA\u30FC\u30DF\u30F3\u30B0\u89E3\u6790\u306E\u521D\u671F\u5316\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${o instanceof Error?o.message:String(o)}`)}}function lt(e,t){return new W(e,t)}function be(){return typeof process<"u"&&process.env.NODE_ENV==="development"?"/dist/core/AudioInspectProcessor.js":"/node_modules/audio-inspect/dist/core/AudioInspectProcessor.js"}async function ct(e,t,n){let a=be();st(e)||await de(e,a);let r={featureName:t,bufferSize:1024,hopSize:512,inputChannelCount:1,...n};return new W(e,r)}async function ut(e,t,n,a,r){try{return await ge(e,t,n,a,r)}catch(s){if(n.enableFallback){if(console.warn("Falling back to non-realtime analysis:",s),n.fallbackHandler&&e instanceof AudioBuffer){let i={sampleRate:e.sampleRate,channelData:Array.from({length:e.numberOfChannels},(l,o)=>e.getChannelData(o)),duration:e.duration,numberOfChannels:e.numberOfChannels,length:e.length};n.fallbackHandler(i)}return null}throw s}}var ye=new Map;function mt(e){if(e<=0||!isFinite(e))throw new y("INVALID_INPUT","\u30B5\u30F3\u30D7\u30EB\u30EC\u30FC\u30C8\u306F\u6B63\u306E\u6709\u9650\u5024\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059");if(e<8e3||e>384e3)throw new y("UNSUPPORTED_FORMAT",`\u30B5\u30F3\u30D7\u30EB\u30EC\u30FC\u30C8 ${e}Hz \u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093`)}function Ae(e){mt(e);let t=ye.get(e);if(t)return t;let n=20.598997,a=107.65265,r=737.86223,s=12194.217,i=1.9997,l=[],o=2*e*Math.tan(Math.PI*n/e),c=2*e*Math.tan(Math.PI*a/e),m=2*e*Math.tan(Math.PI*r/e),u=2*e*Math.tan(Math.PI*s/e),f=Math.pow(10,i/20);{let h=o,b=h*h,A=Math.SQRT2,d=4*e*e+2*A*h*e+b,w=2*(b-4*e*e)/d,M=(4*e*e-2*A*h*e+b)/d;l.push({b0:4*e*e*f/d,b1:-8*e*e*f/d,b2:4*e*e*f/d,a0:1,a1:w,a2:M})}{let h=c,b=2*e+h,A=(h-2*e)/b;l.push({b0:2*e/b,b1:-2*e/b,b2:0,a0:1,a1:A,a2:0})}{let h=m,b=2*e+h,A=(h-2*e)/b;l.push({b0:2*e/b,b1:-2*e/b,b2:0,a0:1,a1:A,a2:0})}{let h=u,b=h*h,A=Math.SQRT2,d=4*e*e+2*A*h*e+b,w=2*(b-4*e*e)/d,M=(4*e*e-2*A*h*e+b)/d;l.push({b0:b/d,b1:2*b/d,b2:b/d,a0:1,a1:w,a2:M})}let g=1/we(l,1e3,e).magnitude;return l.forEach(h=>{h.b0*=g,h.b1*=g,h.b2*=g}),ye.set(e,l),l}function we(e,t,n){let a=2*Math.PI*t/n,r=1,s=0;for(let o of e){let c=Math.cos(a),m=Math.sin(a),u=Math.cos(2*a),f=Math.sin(2*a),p=o.b0+o.b1*c+o.b2*u,g=-o.b1*m-o.b2*f,h=o.a0+o.a1*c+o.a2*u,b=-o.a1*m-o.a2*f,A=h*h+b*b;if(A===0)throw new y("INVALID_INPUT","\u5468\u6CE2\u6570\u5FDC\u7B54\u8A08\u7B97\u3067\u30BC\u30ED\u9664\u7B97\u304C\u767A\u751F\u3057\u307E\u3057\u305F");let d=(p*h+g*b)/A,w=(g*h-p*b)/A,M=r*d-s*w,S=r*w+s*d;r=M,s=S}let i=Math.sqrt(r*r+s*s),l=Math.atan2(s,r);return{magnitude:i,phase:l}}function _(){if(typeof performance<"u"&&performance.now)return performance.now();if(typeof process<"u"&&process.hrtime){let[e,t]=process.hrtime();return e*1e3+t/1e6}return Date.now()}function z(e,t=0){if(t===-1){if(e.numberOfChannels===0)throw new y("INVALID_INPUT","No channels available");for(let r=0;r<e.numberOfChannels;r++)if(!e.channelData[r])throw new y("INVALID_INPUT",`Channel ${r} data does not exist for averaging`);let a=new Float32Array(e.length);for(let r=0;r<e.length;r++){let s=0;for(let i=0;i<e.numberOfChannels;i++){let l=e.channelData[i];l&&r<l.length&&(s+=l[r]??0)}a[r]=s/e.numberOfChannels}return a}if(t<-1||t>=e.numberOfChannels)throw new y("INVALID_INPUT",`Invalid channel number: ${t}`);let n=e.channelData[t];if(!n)throw new y("INVALID_INPUT",`Channel ${t} data does not exist`);return n}function Se(e){return e>0&&(e&e-1)===0}function ee(e){if(e<=0||!isFinite(e)||isNaN(e))return 1;if(Se(e))return e;let t=1;for(;t<e&&t<Number.MAX_SAFE_INTEGER;)t*=2;return t}function Me(e,t,n){return t<0||t>=e.length?n:e[t]??n}function H(e){return e==null?!1:!isNaN(e)&&isFinite(e)}function F(e){return e==null||isNaN(e)||!isFinite(e)?0:e}function V(e,t=1){return e<=0||t<=0?-1/0:20*Math.log10(e/t)}function ft(e,t=1){return e===-1/0?0:t*Math.pow(10,e/20)}function ht(e){if(e.numberOfChannels===1)return e;let t=new Float32Array(e.length),n=e.numberOfChannels;for(let a=0;a<e.length;a++){let r=0;for(let s=0;s<n;s++)r+=e.channelData[s]?.[a]??0;t[a]=r/n}return{...e,channelData:[t],numberOfChannels:1}}function pt(e,t,n){if(t<0||n<0||t>=n)throw new y("INVALID_INPUT","\u7121\u52B9\u306A\u6642\u9593\u7BC4\u56F2\u304C\u6307\u5B9A\u3055\u308C\u307E\u3057\u305F",{startTime:t,endTime:n});if(n>e.duration)throw new y("INVALID_INPUT","\u7D42\u4E86\u6642\u9593\u304C\u97F3\u58F0\u306E\u9577\u3055\u3092\u8D85\u3048\u3066\u3044\u307E\u3059",{endTime:n,duration:e.duration});let a=Math.floor(t*e.sampleRate),r=Math.min(Math.floor(n*e.sampleRate),e.length),s=r-a;if(s<=0)throw new y("INSUFFICIENT_DATA","\u30B9\u30E9\u30A4\u30B9\u7BC4\u56F2\u304C\u5C0F\u3055\u3059\u304E\u307E\u3059",{startSample:a,endSample:r,length:s});let i=e.channelData.map(l=>l.slice(a,r));return{...e,channelData:i,duration:n-t,length:s}}function dt(e){let t=0;for(let a of e.channelData)for(let r of a)t=Math.max(t,Math.abs(r));if(t===0||t===1)return e;let n=e.channelData.map(a=>{let r=new Float32Array(a.length);for(let s=0;s<a.length;s++)r[s]=(a[s]??0)/t;return r});return{...e,channelData:n}}function gt(e,t,n={x1:0,x2:0,y1:0,y2:0}){let a=new Float32Array(e.length),{x1:r,x2:s,y1:i,y2:l}=n;for(let o=0;o<e.length;o++){let c=F(e[o]??0),m=t.b0*c+t.b1*r+t.b2*s-t.a1*i-t.a2*l;a[o]=m,s=r,r=c,l=i,i=m}return n.x1=r,n.x2=s,n.y1=i,n.y2=l,a}function te(e,t){let n=Ae(t),a=e;for(let r of n)a=gt(a,r);return a}function Ie(e,t){let n=(e.length-1)*t+1,a=new Float32Array(n);for(let r=0;r<e.length-1;r++){let s=F(e[r]??0),l=(F(e[r+1]??0)-s)/t;for(let o=0;o<t;o++)a[r*t+o]=s+l*o}return e.length>0&&(a[n-1]=F(e[e.length-1]??0)),a}function Fe(e,t){if(e.length<4)return Ie(e,t);let n=(e.length-1)*t+1,a=new Float32Array(n);for(let r=0;r<e.length-1;r++){let s=F(e[Math.max(0,r-1)]??0),i=F(e[r]??0),l=F(e[Math.min(e.length-1,r+1)]??0),o=F(e[Math.min(e.length-1,r+2)]??0);for(let c=0;c<t;c++){let m=c/t,u=m*m,f=u*m,p=.5*(2*i+(-s+l)*m+(2*s-5*i+4*l-o)*u+(-s+3*i-3*l+o)*f);a[r*t+c]=F(p)}}return e.length>0&&(a[n-1]=F(e[e.length-1]??0)),a}function bt(e,t){let n=(e.length-1)*t+1,a=new Float32Array(n),r=s=>{if(Math.abs(s)<1e-10)return 1;let i=Math.PI*s;return Math.abs(s)<3?3*Math.sin(i/3)*Math.sin(i)/(i*i):0};for(let s=0;s<n;s++){let i=s/t,l=0;for(let o=-3;o<=3;o++){let c=Math.floor(i)+o;if(c>=0&&c<e.length){let m=F(e[c]??0),u=r(i-c);l+=m*u}}a[s]=F(l)}return a}function yt(e,t={}){let{factor:n=4,interpolation:a="cubic"}=t;if(n<=1)return e;if(e.length===0)return new Float32Array(0);switch(a){case"linear":return Ie(e,n);case"cubic":return Fe(e,n);case"sinc":return bt(e,n);default:return Fe(e,n)}}function xe(e,t={}){if(e.length===0)return 0;let n=yt(e,t),a=0;for(let r=0;r<n.length;r++){let s=Math.abs(F(n[r]??0));a=Math.max(a,s)}return a}function ve(e,t,n=!1){let a=[],r=e.length;if(r<3)return a;for(let s=1;s<r-1;s++){let i=Math.abs(F(e[s]??0)),l=Math.abs(F(e[s-1]??0)),o=Math.abs(F(e[s+1]??0));if(i>l&&i>o&&i>t){let c={position:s,amplitude:i};n&&(c.prominence=At(e,s,i)),a.push(c)}}return a}function At(e,t,n){let a=n;for(let s=t-1;s>=0;s--){let i=Math.abs(F(e[s]??0));if(i>n)break;a=Math.min(a,i)}let r=n;for(let s=t+1;s<e.length;s++){let i=Math.abs(F(e[s]??0));if(i>n)break;r=Math.min(r,i)}return n-Math.max(a,r)}function wt(e,t={}){let{count:n=100,threshold:a=.1,channel:r=0,minDistance:s=Math.floor(e.sampleRate/100)}=t;if(n<=0)throw new y("INVALID_INPUT","\u30D4\u30FC\u30AF\u6570\u306F\u6B63\u306E\u6574\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059");if(a<0||a>1)throw new y("INVALID_INPUT","\u95BE\u5024\u306F0\u304B\u30891\u306E\u7BC4\u56F2\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059");let i=z(e,r);if(i.length===0)return{peaks:[],maxAmplitude:0,averageAmplitude:0};let l=ve(i,a);if(l.length===0)return{peaks:[],maxAmplitude:0,averageAmplitude:0};l.sort((f,p)=>p.amplitude-f.amplitude);let o=[],c=[];for(let f of l){if(o.length>=n)break;let p=f.position-s,g=f.position+s;c.some(([b,A])=>!(g<b||p>A))||(o.push({position:f.position,time:f.position/e.sampleRate,amplitude:f.amplitude}),c.push([p,g]))}o.sort((f,p)=>f.position-p.position);let m=l.length>0?l[0]?.amplitude??0:0,u=l.length>0?l.reduce((f,p)=>f+p.amplitude,0)/l.length:0;return{peaks:o,maxAmplitude:m,averageAmplitude:u}}var ne=-1/0;function re(e,t={}){let n=typeof t=="number"?{channel:t,asDB:!1,reference:1,truePeak:!1,oversamplingFactor:4,interpolation:"cubic"}:{channel:t.channel??0,asDB:t.asDB??!1,reference:t.reference??1,truePeak:t.truePeak??!1,oversamplingFactor:t.oversamplingFactor??4,interpolation:t.interpolation??"cubic"},a=z(e,n.channel);if(a.length===0)return n.asDB?ne:0;let r=0,s=0;for(let l=0;l<a.length;l++){let o=a[l]??0;H(o)&&(r+=o*o,s++)}if(s===0)return n.asDB?ne:0;let i=Math.sqrt(r/s);return n.asDB?V(i,n.reference):i}function K(e,t={}){let n={channel:t.channel??0,asDB:t.asDB??!1,reference:t.reference??1,truePeak:t.truePeak??!1,oversamplingFactor:t.oversamplingFactor??4,interpolation:t.interpolation??"cubic"},a=z(e,n.channel);if(a.length===0)return n.asDB?ne:0;let r;if(n.truePeak)r=xe(a,{factor:n.oversamplingFactor,interpolation:n.interpolation});else{r=0;for(let s=0;s<a.length;s++){let i=a[s]??0;H(i)&&(r=Math.max(r,Math.abs(i)))}}return n.asDB?V(r,n.reference):r}function Ft(e,t=0){let n=z(e,t);if(n.length<2)return 0;let a=0;for(let r=1;r<n.length;r++){let s=F(n[r-1]??0),i=F(n[r]??0);(s>=0&&i<0||s<0&&i>=0)&&a++}return a/(n.length-1)}function St(e,t={}){let{framesPerSecond:n=60,channel:a=0,method:r="rms"}=t,s=z(e,a),i=Math.ceil(e.duration*n),l=e.length>0?e.length:i>0?1:0,o=Math.min(i,l),c=o>0?Math.max(1,Math.floor(e.length/o)):0,m=[],u=0,f=0;for(let g=0;g<o;g++){let h=g*c,b=Math.min(h+c,s.length);if(b<=h){let M=m.length>0?Me(m,m.length-1,{time:0,amplitude:0}).amplitude:0;m.push({time:(h+c/2)/e.sampleRate,amplitude:M});continue}let A=s.subarray(h,b),d;switch(r){case"peak":d=Re(A);break;case"average":d=Te(A);break;case"rms":default:d=Pe(A);break}let w=(h+(b-h)/2)/e.sampleRate;m.push({time:w,amplitude:d}),u=Math.max(u,d),f+=d}let p=o>0?f/o:0;return{waveform:m,maxAmplitude:u,averageAmplitude:p,frameCount:o,samplesPerFrame:c}}function Pe(e){if(e.length===0)return 0;let t=0;for(let n=0;n<e.length;n++){let a=F(e[n]??0);t+=a*a}return Math.sqrt(t/e.length)}function Re(e){let t=0;for(let n=0;n<e.length;n++){let a=Math.abs(F(e[n]??0));t=Math.max(t,a)}return t}function Te(e){if(e.length===0)return 0;let t=0;for(let n=0;n<e.length;n++)t+=Math.abs(F(e[n]??0));return t/e.length}function G(e,t={}){let n=_(),{framesPerSecond:a=60,channel:r=0,method:s="rms",onProgress:i}=t;i?.(0,"Waveform\u89E3\u6790\u3092\u958B\u59CB");let l=z(e,r),o=Math.ceil(e.duration*a),c=e.length>0?e.length:o>0?1:0,m=Math.min(o,c),u=m>0?Math.max(1,Math.floor(e.length/m)):0;i?.(25,"\u30D5\u30EC\u30FC\u30E0\u8A2D\u5B9A\u5B8C\u4E86");let f=new Float32Array(m),p=new Float32Array(m),g=0,h=0;i?.(50,"\u632F\u5E45\u8A08\u7B97\u3092\u958B\u59CB");for(let d=0;d<m;d++){let w=d*u,M=Math.min(w+u,l.length);if(M<=w){let P=d>0?f[d-1]??0:0;f[d]=P,p[d]=(w+u/2)/e.sampleRate;continue}let S=l.subarray(w,M),I;switch(s){case"peak":I=Re(S);break;case"average":I=Te(S);break;case"rms":default:I=Pe(S);break}if(f[d]=I,p[d]=(w+(M-w)/2)/e.sampleRate,g=Math.max(g,I),h+=I,d%Math.max(1,Math.floor(m/20))===0){let P=50+d/m*45;i?.(Math.round(P),`\u30D5\u30EC\u30FC\u30E0 ${d+1}/${m} \u51E6\u7406\u4E2D`)}}let b=m>0?h/m:0,A=_()-n;return i?.(100,"\u51E6\u7406\u5B8C\u4E86"),{amplitudes:f,timestamps:p,frameCount:m,samplesPerFrame:u,framesPerSecond:a,maxAmplitude:g,averageAmplitude:b,sampleRate:e.sampleRate,duration:e.duration,processingTime:A}}function Z(e,t={}){let n=_(),{count:a=100,threshold:r=.1,channel:s=0,minDistance:i=Math.floor(e.sampleRate/100),onProgress:l}=t;if(l?.(0,"Peaks\u89E3\u6790\u3092\u958B\u59CB"),a<=0)throw new y("INVALID_INPUT","\u30D4\u30FC\u30AF\u6570\u306F\u6B63\u306E\u6574\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059");if(r<0||r>1)throw new y("INVALID_INPUT","\u95BE\u5024\u306F0\u304B\u30891\u306E\u7BC4\u56F2\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059");let o=z(e,s);if(o.length===0)return{positions:new Float32Array(0),amplitudes:new Float32Array(0),times:new Float32Array(0),maxAmplitude:0,averageAmplitude:0,count:0,sampleRate:e.sampleRate,duration:e.duration,processingTime:_()-n};l?.(25,"\u30D4\u30FC\u30AF\u5019\u88DC\u3092\u691C\u51FA\u4E2D");let c=ve(o,r);if(c.length===0)return{positions:new Float32Array(0),amplitudes:new Float32Array(0),times:new Float32Array(0),maxAmplitude:0,averageAmplitude:0,count:0,sampleRate:e.sampleRate,duration:e.duration,processingTime:_()-n};l?.(50,"\u30D4\u30FC\u30AF\u3092\u30BD\u30FC\u30C8\u4E2D"),c.sort((d,w)=>w.amplitude-d.amplitude),l?.(75,"\u30D4\u30FC\u30AF\u3092\u9078\u629E\u4E2D");let m=[],u=[];for(let d of c){if(m.length>=a)break;let w=d.position-i,M=d.position+i;u.some(([I,P])=>!(M<I||w>P))||(m.push({position:d.position,time:d.position/e.sampleRate,amplitude:d.amplitude}),u.push([w,M]))}m.sort((d,w)=>d.position-w.position);let f=new Float32Array(m.length),p=new Float32Array(m.length),g=new Float32Array(m.length);for(let d=0;d<m.length;d++){let w=m[d];w&&(f[d]=w.position,p[d]=w.amplitude,g[d]=w.time)}let h=c.length>0?c[0]?.amplitude??0:0,b=c.length>0?c.reduce((d,w)=>d+w.amplitude,0)/c.length:0,A=_()-n;return l?.(100,"\u51E6\u7406\u5B8C\u4E86"),{positions:f,amplitudes:p,times:g,maxAmplitude:h,averageAmplitude:b,count:m.length,sampleRate:e.sampleRate,duration:e.duration,processingTime:A}}function Q(e,t={}){let n=_(),{channel:a=0,asDB:r=!1,reference:s=1,onProgress:i}=t;i?.(0,"RMS\u89E3\u6790\u3092\u958B\u59CB");let l=z(e,a);if(l.length===0)return{value:r?-1/0:0,channel:a,sampleRate:e.sampleRate,duration:e.duration,processingTime:_()-n};i?.(50,"RMS\u5024\u3092\u8A08\u7B97\u4E2D");let o=0;for(let u=0;u<l.length;u++){let f=l[u]??0;if(H(f)){let p=F(f);o+=p*p}}let c=Math.sqrt(o/l.length),m=_()-n;return i?.(100,"\u51E6\u7406\u5B8C\u4E86"),r?{value:V(c,s),channel:a,sampleRate:e.sampleRate,duration:e.duration,processingTime:m}:{value:c,valueDB:V(c,s),channel:a,sampleRate:e.sampleRate,duration:e.duration,processingTime:m}}var ae=class{constructor(t,n,a=!1){this.size=t;this.sampleRate=n;this.enableProfiling=a;this.initializationPromise=this.initializeWebFFT()}fftInstance=null;initializationPromise=null;get name(){return"WebFFT"}async waitForInitialization(){this.initializationPromise&&await this.initializationPromise}async initializeWebFFT(){try{let n=(await import("webfft")).default;this.fftInstance=new n(this.size),this.enableProfiling&&this.fftInstance?.profile&&await this.fftInstance.profile()}catch(t){throw new y("UNSUPPORTED_FORMAT",`WebFFT\u306E\u521D\u671F\u5316\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${t instanceof Error?t.message:String(t)}`)}}async fft(t){if(this.initializationPromise&&await this.initializationPromise,!this.fftInstance)throw new y("UNSUPPORTED_FORMAT","WebFFT initialization failed");if(t.length!==this.size)throw new y("INVALID_INPUT",`\u5165\u529B\u30B5\u30A4\u30BA\u304C\u4E0D\u6B63\u3067\u3059\u3002\u671F\u5F85\u5024: ${this.size}, \u5B9F\u969B: ${t.length}`);let n=new Float32Array(this.size*2);for(let l=0;l<this.size;l++)n[l*2]=t[l]||0,n[l*2+1]=0;let a=this.fftInstance.fft(n),r=new Float32Array(this.size/2+1),s=new Float32Array(this.size/2+1),i=new Float32Array(this.size/2+1);for(let l=0;l<r.length;l++){let o=a[l*2]||0,c=a[l*2+1]||0;r[l]=Math.sqrt(o*o+c*c),s[l]=Math.atan2(c,o),i[l]=l*this.sampleRate/this.size}return{complex:a,magnitude:r,phase:s,frequencies:i}}async profile(){if(this.initializationPromise&&await this.initializationPromise,!this.fftInstance||!this.fftInstance.profile)throw new y("UNSUPPORTED_FORMAT","WebFFT\u304C\u521D\u671F\u5316\u3055\u308C\u3066\u3044\u307E\u305B\u3093");await this.fftInstance.profile()}dispose(){if(this.fftInstance)try{this.fftInstance.dispose&&this.fftInstance.dispose()}catch(t){console.warn("FFT instance disposal failed:",t)}finally{this.fftInstance=null,this.initializationPromise=null}}},oe=class{constructor(t,n){this.size=t;this.sampleRate=n;if(!this.isPowerOfTwo(t))throw new y("INVALID_INPUT","FFT\u30B5\u30A4\u30BA\u306F2\u306E\u51AA\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059");this.precomputeTables()}bitReversalTable;twiddleFactorsReal;twiddleFactorsImag;get name(){return"Native FFT (Cooley-Tukey)"}isPowerOfTwo(t){return t>0&&(t&t-1)===0}precomputeTables(){this.bitReversalTable=new Uint32Array(this.size);let t=Math.log2(this.size);for(let a=0;a<this.size;a++){let r=0;for(let s=0;s<t;s++)r=r<<1|a>>s&1;this.bitReversalTable[a]=r}let n=this.size/2;this.twiddleFactorsReal=new Float32Array(n),this.twiddleFactorsImag=new Float32Array(n);for(let a=0;a<n;a++){let r=-2*Math.PI*a/this.size;this.twiddleFactorsReal[a]=Math.cos(r),this.twiddleFactorsImag[a]=Math.sin(r)}}fft(t){if(t.length!==this.size)throw new y("INVALID_INPUT",`\u5165\u529B\u30B5\u30A4\u30BA\u304C\u4E0D\u6B63\u3067\u3059\u3002\u671F\u5F85\u5024: ${this.size}, \u5B9F\u969B: ${t.length}`);let n=new Float32Array(this.size),a=new Float32Array(this.size);for(let o=0;o<this.size;o++){let c=this.bitReversalTable[o];c!==void 0&&(n[c]=t[o]||0,a[c]=0)}for(let o=1;o<this.size;o*=2){let c=o*2,m=this.size/c;for(let u=0;u<this.size;u+=c)for(let f=0;f<o;f++){let p=f*m,g=this.twiddleFactorsReal[p]||0,h=this.twiddleFactorsImag[p]||0,b=u+f,A=u+f+o,d=n[b]||0,w=a[b]||0,M=n[A]||0,S=a[A]||0,I=M*g-S*h,P=M*h+S*g;n[b]=d+I,a[b]=w+P,n[A]=d-I,a[A]=w-P}}let r=new Float32Array(this.size*2),s=new Float32Array(this.size/2+1),i=new Float32Array(this.size/2+1),l=new Float32Array(this.size/2+1);for(let o=0;o<this.size;o++)if(r[o*2]=n[o]||0,r[o*2+1]=a[o]||0,o<=this.size/2){let c=n[o]||0,m=a[o]||0;s[o]=Math.sqrt(c*c+m*m),i[o]=Math.atan2(m,c),l[o]=o*this.sampleRate/this.size}return{complex:r,magnitude:s,phase:i,frequencies:l}}dispose(){}},j=class{static async createProvider(t){switch(t.type){case"webfft":{let n=new ae(t.fftSize,t.sampleRate,t.enableProfiling);return await n.waitForInitialization(),n}case"native":return new oe(t.fftSize,t.sampleRate);case"custom":if(!t.customProvider)throw new y("INVALID_INPUT","\u30AB\u30B9\u30BF\u30E0\u30D7\u30ED\u30D0\u30A4\u30C0\u30FC\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093");return t.customProvider;default:{let n=t.type;throw new y("UNSUPPORTED_FORMAT",`\u672A\u5BFE\u5FDC\u306EFFT\u30D7\u30ED\u30D0\u30A4\u30C0\u30FC: ${String(n)}`)}}}static getAvailableProviders(){return["webfft","native"]}};function De(e,t){let n=new Float32Array(e.length),a=e.length;for(let r=0;r<a;r++){let s=1;switch(t){case"hann":s=.5*(1-Math.cos(2*Math.PI*r/(a-1)));break;case"hamming":s=.54-.46*Math.cos(2*Math.PI*r/(a-1));break;case"blackman":s=.42-.5*Math.cos(2*Math.PI*r/(a-1))+.08*Math.cos(4*Math.PI*r/(a-1));break;case"rectangular":default:s=1;break}n[r]=(e[r]||0)*s}return n}function Ce(e,t){if(t===-1){let a=new Float32Array(e.length);for(let r=0;r<e.length;r++){let s=0;for(let i=0;i<e.numberOfChannels;i++){let l=e.channelData[i];l&&r<l.length&&(s+=l[r])}a[r]=s/e.numberOfChannels}return a}if(t<-1||t>=e.numberOfChannels)throw new y("INVALID_INPUT",`Invalid channel number: ${t}`);let n=e.channelData[t];if(!n)throw new y("INVALID_INPUT",`Channel ${t} data does not exist`);return n}async function q(e,t={}){let{fftSize:n=2048,windowFunction:a="hann",channel:r=0,provider:s="native",enableProfiling:i=!1}=t,l=Ce(e,r),o;l.length<n?(o=new Float32Array(n),o.set(l)):o=l.slice(0,n);let c=De(o,a),m=s==="webfft"?["webfft","native"]:[s],u,f=null;for(let p of m)try{f=await j.createProvider({type:p,fftSize:n,sampleRate:e.sampleRate,enableProfiling:i});break}catch(g){if(u=g,p==="webfft"&&m.includes("native"))continue}if(!f)throw u||new y("FFT_PROVIDER_ERROR","Failed to create FFT provider");try{return{...await f.fft(c),fftSize:n,windowFunction:a,providerName:f.name}}finally{f.dispose()}}async function Mt(e,t={}){let{fftSize:n=2048,minFrequency:a=0,maxFrequency:r=e.sampleRate/2,decibels:s=!0,timeFrames:i=1,overlap:l=.5,...o}=t,c=Ce(e,t.channel||0);if(i===1){let m=await q(e,{...o,fftSize:n}),u=It(m,a,r),f={frequencies:u.frequencies,magnitudes:u.magnitude};return s&&(f.decibels=ze(u.magnitude)),f}else{let m=await xt(c,e.sampleRate,n,i,l,{...o,minFrequency:a,maxFrequency:r,decibels:s});return{frequencies:m.frequencies,magnitudes:new Float32Array,spectrogram:m}}}function It(e,t,n){let{frequencies:a,magnitude:r,phase:s,complex:i}=e,l=a.findIndex(m=>m>=t),o=a.findIndex(m=>m>n),c=o===-1?a.length:o;return{frequencies:a.slice(l,c),magnitude:r.slice(l,c),phase:s.slice(l,c),complex:i.slice(l*2,c*2)}}function ze(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;n++){let a=e[n]||0;t[n]=a>0?20*Math.log10(a):-1/0}return t}async function xt(e,t,n,a,r,s){let i=Math.floor(n*(1-r)),l;e.length===0?l=0:e.length<n?l=1:l=Math.floor((e.length-n)/i)+1;let o=Math.min(a,l),c=new Float32Array(o),m=[],u=new Float32Array,f=new Float32Array,p=0,g=0,h=await j.createProvider({type:s.provider||"native",fftSize:n,sampleRate:t,enableProfiling:s.enableProfiling||!1});try{for(let b=0;b<o;b++){let A=b*i,d=new Float32Array(n);for(let T=0;T<n;T++)d[T]=A+T<e.length&&e[A+T]||0;let w=De(d,s.windowFunction||"hann"),M=await h.fft(w);if(b===0){u=M.frequencies;let T=s.minFrequency||0,k=s.maxFrequency||t/2;p=u.findIndex(O=>O>=T),p===-1&&(p=0);let L=u.findIndex(O=>O>k);g=L===-1?u.length:L,f=u.slice(p,g)}let I=M.magnitude.slice(p,g),P=s.decibels?ze(I):I;m.push(P),c[b]=(A+n/2)/t}}finally{h.dispose()}return{times:c,frequencies:f,intensities:m,timeFrames:o,frequencyBins:f.length}}function Oe(e,t,n,a){let r=new Float32Array(a);for(let s=0;s<a&&n+s<e.length;s++){let i=1;switch(t){case"hann":i=.5*(1-Math.cos(2*Math.PI*s/(a-1)));break;case"hamming":i=.54-.46*Math.cos(2*Math.PI*s/(a-1));break;case"rectangular":default:i=1}let l=F(e[n+s]??0);r[s]=l*i}return r}function se(e,t={}){let{frameSize:n=Math.floor(e.sampleRate*.025),hopSize:a=Math.floor(e.sampleRate*.01),channel:r=0,normalized:s=!1,windowFunction:i="rectangular"}=t;if(n<=0||!Number.isInteger(n))throw new y("INVALID_INPUT","frameSize\u306F\u6B63\u306E\u6574\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059");if(a<=0||!Number.isInteger(a))throw new y("INVALID_INPUT","hopSize\u306F\u6B63\u306E\u6574\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059");a>n&&console.warn("[audio-inspect] hopSize\u304CframeSize\u3088\u308A\u5927\u304D\u3044\u305F\u3081\u3001\u30D5\u30EC\u30FC\u30E0\u9593\u306B\u30AE\u30E3\u30C3\u30D7\u304C\u751F\u3058\u307E\u3059");let l=z(e,r),o=l.length;if(o===0)return{times:new Float32Array(0),energies:new Float32Array(0),totalEnergy:0,statistics:{mean:0,std:0,max:0,min:0}};let c=Math.max(0,Math.floor((o-n)/a)+1);if(c===0){let d=vt(l,0,o,i);return{times:new Float32Array([o/2/e.sampleRate]),energies:new Float32Array([d]),totalEnergy:d,statistics:{mean:d,std:0,max:d,min:d}}}let m=new Float32Array(c),u=new Float32Array(c),f=0,p=-1/0,g=1/0;for(let d=0;d<c;d++){let w=d*a,M=Oe(l,i,w,n),S=0;for(let I=0;I<M.length;I++){let P=M[I];P!==void 0&&(S+=P*P)}m[d]=(w+n/2)/e.sampleRate,u[d]=S,f+=S,p=Math.max(p,S),g=Math.min(g,S)}let h=f/c,b=0;for(let d=0;d<c;d++){let w=u[d];if(w!==void 0){let M=w-h;b+=M*M}}let A=Math.sqrt(b/c);if(s&&f>1e-10){for(let d=0;d<u.length;d++){let w=u[d];w!==void 0&&(u[d]=w/f)}return{times:m,energies:u,totalEnergy:1,statistics:{mean:h/f,std:A/f,max:p/f,min:g/f}}}return{times:m,energies:u,totalEnergy:f,statistics:{mean:h,std:A,max:p,min:g}}}function vt(e,t,n,a){let r=Oe(e,a,t,n),s=0;for(let i of r)s+=i*i;return s}async function Pt(e,t){let n=_(),a={processingTime:0},r=[];t.waveform!==void 0&&r.push({name:"waveform",weight:.15,execute:()=>G(e,{...t.waveform,onProgress:(l,o)=>t.onProgress?.(l*.15,`Waveform: ${o}`)})}),t.peaks!==void 0&&r.push({name:"peaks",weight:.2,execute:()=>Z(e,{...t.peaks,onProgress:(l,o)=>t.onProgress?.(l*.2,`Peaks: ${o}`)})}),t.rms!==void 0&&r.push({name:"rms",weight:.1,execute:()=>Q(e,{...t.rms,onProgress:(l,o)=>t.onProgress?.(l*.1,`RMS: ${o}`)})}),t.spectrum!==void 0&&r.push({name:"spectrum",weight:.35,execute:async()=>{let l={};t.spectrum?.fftSize!==void 0&&(l.fftSize=t.spectrum.fftSize),t.spectrum?.channel!==void 0&&(l.channel=t.spectrum.channel),t.spectrum?.windowFunction!==void 0&&(l.windowFunction=t.spectrum.windowFunction==="rectangular"?"none":t.spectrum.windowFunction);let o=await q(e,l);return{frequencies:o.frequencies,magnitudes:o.magnitude,phases:o.phase,fftSize:o.fftSize,windowFunction:o.windowFunction,sampleRate:e.sampleRate,duration:e.duration}}}),t.energy!==void 0&&r.push({name:"energy",weight:.2,execute:()=>{let l=se(e,{...t.energy});return{energies:l.energies,times:l.times,totalEnergy:l.totalEnergy,meanEnergy:l.statistics.mean,maxEnergy:l.statistics.max,minEnergy:l.statistics.min,sampleRate:e.sampleRate,duration:e.duration}}});let s=r.reduce((l,o)=>l+o.weight,0);s>0&&r.forEach(l=>l.weight/=s);let i=0;return await Promise.all(r.map(async l=>{try{let o=await l.execute();switch(l.name){case"waveform":o&&(a.waveform=o);break;case"peaks":o&&(a.peaks=o);break;case"rms":o&&(a.rms=o);break;case"spectrum":o&&(a.spectrum=o);break;case"energy":o&&(a.energy=o);break}i+=l.weight,t.onProgress?.(Math.round(i*100),l.name)}catch(o){console.warn(`Task ${l.name} failed:`,o)}})),a.processingTime=_()-n,a}function Ne(e,t,n={}){let a=new Float32Array(t);switch(e){case"hann":for(let r=0;r<t;r++)a[r]=.5-.5*Math.cos(2*Math.PI*r/(t-1));break;case"hamming":for(let r=0;r<t;r++)a[r]=.54-.46*Math.cos(2*Math.PI*r/(t-1));break;case"blackman":for(let r=0;r<t;r++)a[r]=.42-.5*Math.cos(2*Math.PI*r/(t-1))+.08*Math.cos(4*Math.PI*r/(t-1));break;case"bartlett":for(let r=0;r<t;r++)a[r]=1-Math.abs((r-(t-1)/2)/((t-1)/2));break;case"kaiser":{let r=n.kaiserBeta??8.6,s=ke(r);for(let i=0;i<t;i++){let l=2*i/(t-1)-1;a[i]=ke(r*Math.sqrt(1-l*l))/s}}break;case"tukey":{let r=n.tukeyAlpha??.5,s=Math.floor(r*(t-1)/2);for(let i=0;i<t;i++)i<s?a[i]=.5*(1+Math.cos(Math.PI*(2*i/(r*(t-1))-1))):i>t-1-s?a[i]=.5*(1+Math.cos(Math.PI*(2*i/(r*(t-1))-2/r+1))):a[i]=1}break;case"rectangular":a.fill(1);break;default:throw new y("INVALID_INPUT",`Unknown window type: ${e}`)}return a}function ke(e){let t=1,n=1,a=e*e/4;for(let r=1;r<50&&(n*=a/(r*r),t+=n,!(n<1e-10*t));r++);return t}var ie=class{size;levels;cosTable;sinTable;constructor(t){if(t<=0||(t&t-1)!==0)throw new y("INVALID_INPUT","FFT size must be a power of 2");this.size=t,this.levels=Math.log2(t),this.cosTable=new Float32Array(t/2),this.sinTable=new Float32Array(t/2);for(let n=0;n<t/2;n++){let a=-2*Math.PI*n/t;this.cosTable[n]=Math.cos(a),this.sinTable[n]=Math.sin(a)}}forward(t,n){this.bitReverse(t),this.bitReverse(n);for(let a=1;a<=this.levels;a++){let r=1<<a,s=r>>1;for(let i=0;i<this.size;i+=r)for(let l=0;l<s;l++){let o=i+l,c=o+s,m=l*(this.size/r),u=this.cosTable[m]??0,f=this.sinTable[m]??0,p=(t[c]??0)*u-(n[c]??0)*f,g=(t[c]??0)*f+(n[c]??0)*u;t[c]=(t[o]??0)-p,n[c]=(n[o]??0)-g,t[o]=(t[o]??0)+p,n[o]=(n[o]??0)+g}}}inverse(t,n){for(let r=0;r<this.size;r++)n[r]=-(n[r]??0);this.forward(t,n);let a=1/this.size;for(let r=0;r<this.size;r++)t[r]=(t[r]??0)*a,n[r]=-(n[r]??0)*a}bitReverse(t){let n=this.size,a=0;for(let r=0;r<n-1;r++){if(r<a){let i=t[r]??0;t[r]=t[a]??0,t[a]=i}let s=n>>1;for(;s<=a;)a-=s,s>>=1;a+=s}}},$=class{fft;fftSize;windowSize;hopSize;window;normalize;constructor(t,n={}){if(this.fftSize=n.fftSize??2048,this.windowSize=n.windowSize??this.fftSize,this.hopSize=n.hopSize??Math.floor(this.windowSize/2),this.normalize=n.normalize??"backward",this.fftSize<=0||(this.fftSize&this.fftSize-1)!==0)throw new y("INVALID_INPUT","FFT size must be a power of 2");if(this.windowSize>this.fftSize)throw new y("INVALID_INPUT","Window size cannot be larger than FFT size");this.fft=new ie(this.fftSize);let a=n.windowType??"hann";this.window=Ne(a,this.windowSize,n)}stft(t,n){let a=t.length>=this.windowSize?Math.floor((t.length-this.windowSize)/this.hopSize)+1:0,r=Math.floor(this.fftSize/2)+1,s=[],i=[],l=[],o=new Float32Array(this.fftSize),c=new Float32Array(this.fftSize);for(let f=0;f<a;f++){let p=f*this.hopSize;o.fill(0),c.fill(0);for(let d=0;d<this.windowSize;d++){let w=p+d;w<t.length&&(o[d]=F(t[w]??0)*(this.window[d]??0))}this.fft.forward(o,c);let g=1;this.normalize==="forward"?g=1/this.fftSize:this.normalize==="ortho"&&(g=1/Math.sqrt(this.fftSize));let h=new Float32Array(r*2),b=new Float32Array(r),A=new Float32Array(r);for(let d=0;d<r;d++){let w=(o[d]??0)*g,M=(c[d]??0)*g;h[d*2]=w,h[d*2+1]=M,b[d]=Math.sqrt(w*w+M*M),A[d]=Math.atan2(M,w)}s.push(h),i.push(b),l.push(A)}let m=new Float32Array(a);for(let f=0;f<a;f++)m[f]=f*this.hopSize/n;let u=new Float32Array(r);for(let f=0;f<r;f++)u[f]=f*n/this.fftSize;return{complex:s,magnitude:i,phase:l,frameCount:a,frequencyBins:r,times:m,frequencies:u}}istft(t,n){let{complex:a,frameCount:r,frequencyBins:s}=t,i=n??(r-1)*this.hopSize+this.windowSize,l=new Float32Array(i),o=new Float32Array(i),c=new Float32Array(this.fftSize),m=new Float32Array(this.fftSize);for(let u=0;u<r;u++){let f=u*this.hopSize,p=a[u]??new Float32Array(0);c.fill(0),m.fill(0);for(let h=0;h<s;h++)c[h]=p[h*2]??0,m[h]=p[h*2+1]??0;for(let h=1;h<s-1;h++)c[this.fftSize-h]=c[h]??0,m[this.fftSize-h]=-(m[h]??0);this.fft.inverse(c,m);let g=1;this.normalize==="backward"?g=1:this.normalize==="forward"?g=this.fftSize:this.normalize==="ortho"&&(g=Math.sqrt(this.fftSize));for(let h=0;h<this.windowSize;h++){let b=f+h;if(b<i){let A=(c[h]??0)*g*(this.window[h]??0);l[b]=(l[b]??0)+A,o[b]=(o[b]??0)+(this.window[h]??0)*(this.window[h]??0)}}}for(let u=0;u<i;u++)(o[u]??0)>0&&(l[u]=(l[u]??0)/(o[u]??1));return l}processFrame(t,n){if(t.length!==this.windowSize)throw new y("INVALID_INPUT",`Frame size (${t.length}) must match window size (${this.windowSize})`);let a=new Float32Array(this.fftSize),r=new Float32Array(this.fftSize);for(let u=0;u<this.windowSize;u++)a[u]=F(t[u]??0)*(this.window[u]??0);this.fft.forward(a,r);let s=1;this.normalize==="forward"?s=1/this.fftSize:this.normalize==="ortho"&&(s=1/Math.sqrt(this.fftSize));let i=Math.floor(this.fftSize/2)+1,l=new Float32Array(i*2),o=new Float32Array(i),c=new Float32Array(i),m=new Float32Array(i);for(let u=0;u<i;u++){let f=(a[u]??0)*s,p=(r[u]??0)*s;l[u*2]=f,l[u*2+1]=p,o[u]=Math.sqrt(f*f+p*p),c[u]=Math.atan2(p,f),m[u]=u*n/this.fftSize}return{complex:l,magnitude:o,phase:c,frequencies:m}}getConfig(){return{fftSize:this.fftSize,windowSize:this.windowSize,hopSize:this.hopSize,overlapRatio:1-this.hopSize/this.windowSize}}};function Rt(e,t,n={}){return new $(t,n).stft(e,t)}function Tt(e,t,n={},a){return new $(t,n).istft(e,a)}var le=class{processor;inputBuffer;bufferPosition;windowSize;hopSize;sampleRate;constructor(t,n={}){this.sampleRate=t,this.processor=new $(t,n);let a=this.processor.getConfig();this.windowSize=a.windowSize,this.hopSize=a.hopSize,this.inputBuffer=new Float32Array(this.windowSize),this.bufferPosition=0}process(t,n){let a=[],r=0;for(;r<t.length;){let s=Math.min(t.length-r,this.windowSize-this.bufferPosition);if(this.inputBuffer.set(t.subarray(r,r+s),this.bufferPosition),this.bufferPosition+=s,r+=s,this.bufferPosition>=this.windowSize){let i=this.processor.processFrame(this.inputBuffer,n);a.push({...i,time:a.length*this.hopSize/this.sampleRate}),this.inputBuffer.copyWithin(0,this.hopSize),this.bufferPosition=this.windowSize-this.hopSize}}return{frames:a}}reset(){this.inputBuffer.fill(0),this.bufferPosition=0}getBufferStatus(){return{position:this.bufferPosition,size:this.windowSize}}};function Dt(e,t,n,a){let r=0,s=0;for(let i=0;i<e.length&&i<t.length;i++){let l=t[i],o=e[i];l!==void 0&&o!==void 0&&l>=n&&l<=a&&(r+=l*o,s+=o)}return s>1e-10?r/s:0}function Ct(e,t,n,a,r){let s=0,i=0;for(let l=0;l<e.length&&l<t.length;l++){let o=t[l],c=e[l];if(o!==void 0&&c!==void 0&&o>=a&&o<=r){let m=o-n;s+=m*m*c,i+=c}}return i>1e-10?Math.sqrt(s/i):0}function zt(e,t,n,a,r){let s=0;for(let o=0;o<e.length&&o<t.length;o++){let c=t[o],m=e[o];c!==void 0&&m!==void 0&&c>=a&&c<=r&&(s+=m*m)}let i=s*n,l=0;for(let o=0;o<e.length&&o<t.length;o++){let c=t[o],m=e[o];if(c!==void 0&&m!==void 0&&c>=a&&c<=r&&(l+=m*m,l>=i))return c}return r}function Ot(e,t,n){let a=0,r=0,s=0;for(let i=t;i<=n&&i<e.length;i++){let l=e[i];if(l!==void 0){let o=Math.max(l,1e-10);a+=Math.log(o),r+=o,s++}}return s===0?0:(a=Math.exp(a/s),r=r/s,r>1e-10?a/r:0)}function kt(e){if(e.length<2)return 0;let t=0;for(let n=1;n<e.length;n++){let a=F(e[n-1]??0),r=F(e[n]??0);(a>=0&&r<0||a<0&&r>=0)&&t++}return t/(e.length-1)}function Nt(e,t,n={normalize:!0}){if(!t||t.length===0)return 0;let a=Math.min(e.length,t.length);if(a===0)return 0;let r=e,s=t;if(n.normalize!==!1){let l=0,o=0;for(let u=0;u<a;u++){let f=e[u]??0,p=t[u]??0;l+=f*f,o+=p*p}let c=Math.sqrt(l),m=Math.sqrt(o);if(c>1e-10&&m>1e-10){r=new Float32Array(a),s=new Float32Array(a);for(let u=0;u<a;u++)r[u]=(e[u]??0)/c,s[u]=(t[u]??0)/m}}let i=0;for(let l=0;l<a;l++){let o=(r[l]??0)-(s[l]??0);i+=o*o}return Math.sqrt(i)}async function _e(e,t={}){let{fftSize:n=2048,windowFunction:a="hann",channel:r=0,minFrequency:s=0,maxFrequency:i=e.sampleRate/2,rolloffThreshold:l=.85}=t;if(r>=e.numberOfChannels)throw new y("INVALID_INPUT",`\u7121\u52B9\u306A\u30C1\u30E3\u30F3\u30CD\u30EB\u756A\u53F7: ${r}`);let o=await q(e,{fftSize:n,windowFunction:a,channel:r}),c=Math.max(0,Math.floor(s*n/e.sampleRate)),m=Math.min(o.frequencies.length-1,Math.floor(i*n/e.sampleRate)),u=Dt(o.magnitude,o.frequencies,s,i),f=Ct(o.magnitude,o.frequencies,u,s,i),p=zt(o.magnitude,o.frequencies,l,s,i),g=Ot(o.magnitude,c,m),h=e.channelData[r];if(!h)throw new y("INVALID_INPUT",`\u30C1\u30E3\u30F3\u30CD\u30EB ${r} \u306E\u30C7\u30FC\u30BF\u304C\u5B58\u5728\u3057\u307E\u305B\u3093`);let b=kt(h);return{spectralCentroid:u,spectralBandwidth:f,spectralRolloff:p,spectralFlatness:g,zeroCrossingRate:b,frequencyRange:{min:s,max:i}}}async function Et(e,t={}){let{frameSize:n=2048,hopSize:a=n/2,fftSize:r=n,windowFunction:s="hann",channel:i=0,minFrequency:l=0,maxFrequency:o=e.sampleRate/2,rolloffThreshold:c=.85,numFrames:m}=t;if(i>=e.numberOfChannels)throw new y("INVALID_INPUT",`\u7121\u52B9\u306A\u30C1\u30E3\u30F3\u30CD\u30EB\u756A\u53F7: ${i}`);let u=e.channelData[i];if(!u)throw new y("INVALID_INPUT",`\u30C1\u30E3\u30F3\u30CD\u30EB ${i} \u306E\u30C7\u30FC\u30BF\u304C\u5B58\u5728\u3057\u307E\u305B\u3093`);let f=m||Math.floor((u.length-n)/a)+1;if(f<=0)throw new y("INVALID_INPUT","\u30D5\u30EC\u30FC\u30E0\u6570\u304C\u4E0D\u6B63\u3067\u3059");let p=new Float32Array(f),g=new Float32Array(f),h=new Float32Array(f),b=new Float32Array(f),A=new Float32Array(f),d=new Float32Array(f),w=new Float32Array(f),M;for(let S=0;S<f;S++){let I=S*a,P=Math.min(I+n,u.length);p[S]=I/e.sampleRate;let T=u.subarray(I,P),k=new Float32Array(r),L=Math.min(T.length,r);L>0&&k.set(T.subarray(0,L));let O={channelData:[k],sampleRate:e.sampleRate,numberOfChannels:1,length:r,duration:r/e.sampleRate},E=await _e(O,{fftSize:r,windowFunction:s,channel:0,minFrequency:l,maxFrequency:o,rolloffThreshold:c});g[S]=E.spectralCentroid,h[S]=E.spectralBandwidth,b[S]=E.spectralRolloff,A[S]=E.spectralFlatness,w[S]=E.zeroCrossingRate;let x=await q(O,{fftSize:r,windowFunction:s,channel:0});d[S]=Nt(x.magnitude,M),M=new Float32Array(x.magnitude)}return{times:p,spectralCentroid:g,spectralBandwidth:h,spectralRolloff:b,spectralFlatness:A,spectralFlux:d,zeroCrossingRate:w,frameInfo:{frameSize:n,hopSize:a,numFrames:f}}}function _t(e,t,n){let a=[],r=0;for(let c=t;c<=n&&c<e.length;c++){let m=e[c];if(m!==void 0){let u=m*m;a.push(u),r+=u}}if(a.length===0||r<=1e-10)return{entropy:0,entropyNorm:0};let s=a.map(c=>c/r),i=0;for(let c of s)c>1e-10&&(i-=c*Math.log2(c));let l=Math.log2(a.length),o=l>0?i/l:0;return{entropy:i,entropyNorm:o}}function qt(e,t,n){let a=0,r=0,s=0;for(let o=t;o<=n&&o<e.length;o++){let c=e[o];c!==void 0&&(a=Math.max(a,c),r+=c,s++)}if(s===0)return{crest:0,peak:0,average:0};let i=r/s;return{crest:i>1e-10?a/i:0,peak:a,average:i}}async function Lt(e,t={}){let{fftSize:n=2048,windowFunction:a="hann",channel:r=0,minFrequency:s=0,maxFrequency:i=e.sampleRate/2}=t;if(r>=e.numberOfChannels)throw new y("INVALID_INPUT",`\u7121\u52B9\u306A\u30C1\u30E3\u30F3\u30CD\u30EB\u756A\u53F7: ${r}`);let l=await q(e,{fftSize:n,windowFunction:a,channel:r}),o=Math.max(0,Math.floor(s*n/e.sampleRate)),c=Math.min(l.frequencies.length-1,Math.floor(i*n/e.sampleRate)),{entropy:m,entropyNorm:u}=_t(l.magnitude,o,c);return{entropy:m,entropyNorm:u,frequencyRange:{min:s,max:i}}}async function Bt(e,t={}){let{fftSize:n=2048,windowFunction:a="hann",channel:r=0,minFrequency:s=0,maxFrequency:i=e.sampleRate/2,asDB:l=!1}=t;if(r>=e.numberOfChannels)throw new y("INVALID_INPUT",`\u7121\u52B9\u306A\u30C1\u30E3\u30F3\u30CD\u30EB\u756A\u53F7: ${r}`);let o=await q(e,{fftSize:n,windowFunction:a,channel:r}),c=Math.max(0,Math.floor(s*n/e.sampleRate)),m=Math.min(o.frequencies.length-1,Math.floor(i*n/e.sampleRate)),{crest:u,peak:f,average:p}=qt(o.magnitude,c,m),g={crest:u,peak:f,average:p,frequencyRange:{min:s,max:i}};return l&&(g.crestDB=u>0?20*Math.log10(u):-1/0),g}function Ut(e,t){let n=new Float32Array(t);for(let a=0;a<t;a++)switch(e){case"hann":n[a]=.5-.5*Math.cos(2*Math.PI*a/(t-1));break;case"hamming":n[a]=.54-.46*Math.cos(2*Math.PI*a/(t-1));break;case"blackman":n[a]=.42-.5*Math.cos(2*Math.PI*a/(t-1))+.08*Math.cos(4*Math.PI*a/(t-1));break;case"rectangular":default:n[a]=1;break}return n}function Wt(e,t){let n=Ut(t,e.length),a=new Float32Array(e.length);for(let r=0;r<e.length;r++)a[r]=F(e[r]??0)*(n[r]??0);return a}function Ee(e){return 2595*Math.log10(1+e/700)}function Vt(e){return 700*(Math.pow(10,e/2595)-1)}function jt(e,t,n,a,r){let s=[],i=n/2,l=Math.floor(t/2)+1,o=Ee(a),c=Ee(r),m=new Array(e+2);for(let f=0;f<e+2;f++)m[f]=o+(c-o)*f/(e+1);let u=m.map(f=>{let p=Vt(f);return Math.floor(p/i*(l-1))});for(let f=1;f<=e;f++){let p=new Float32Array(l),g=u[f-1],h=u[f],b=u[f+1];if(!(g===void 0||h===void 0||b===void 0)){for(let A=g;A<=b;A++)A<0||A>=l||A>=p.length||(A<h?h-g>0&&(p[A]=(A-g)/(h-g)):b-h>0&&(p[A]=(b-A)/(b-h)));s.push(p)}}return s}function $t(e,t){let n=e.length,a=new Array(t);for(let r=0;r<t;r++){let s=0;for(let l=0;l<n;l++){let o=e[l];o!==void 0&&(s+=o*Math.cos(Math.PI*r*(l+.5)/n))}let i=Math.sqrt(r===0?1/n:2/n);a[r]=s*i}return a}function Ht(e,t){let n=new Float32Array(e.length);n[0]=F(e[0]??0);for(let a=1;a<e.length;a++){let r=F(e[a]??0),s=F(e[a-1]??0);n[a]=r-t*s}return n}function Kt(e,t){return e.map((n,a)=>{if(t===0)return n;let r=1+t/2*Math.sin(Math.PI*a/t);return n*r})}async function qe(e,t={}){let{frameSizeMs:n=25,hopSizeMs:a=10,windowFunction:r="hamming",channel:s=0,numMelFilters:i=40,numMfccCoeffs:l=13,minFrequency:o=0,maxFrequency:c=e.sampleRate/2,preEmphasis:m=.97,lifterCoeff:u=22}=t;if(s>=e.numberOfChannels)throw new y("INVALID_INPUT",`\u7121\u52B9\u306A\u30C1\u30E3\u30F3\u30CD\u30EB\u756A\u53F7: ${s}`);let f=Math.round(n/1e3*e.sampleRate),p=Math.round(a/1e3*e.sampleRate);if(f<=0||p<=0)throw new y("INVALID_INPUT","\u30D5\u30EC\u30FC\u30E0\u30B5\u30A4\u30BA\u307E\u305F\u306F\u30DB\u30C3\u30D7\u30B5\u30A4\u30BA\u304C\u5C0F\u3055\u3059\u304E\u307E\u3059");let g=t.fftSize??Math.max(1024,ee(f)),h=e.channelData[s];if(!h)throw new y("INVALID_INPUT",`\u30C1\u30E3\u30F3\u30CD\u30EB ${s} \u306E\u30C7\u30FC\u30BF\u304C\u5B58\u5728\u3057\u307E\u305B\u3093`);let b=Ht(h,m),A=Math.floor((b.length-f)/p)+1;if(