From 19c1e032ee9f4649b14cc70910875222e192cb91 Mon Sep 17 00:00:00 2001 From: locphamtran Date: Mon, 7 Sep 2026 20:55:52 +0700 Subject: [PATCH] M26: diag m26d envelope PWR ON (pdc/gains/peak mix+nguon) quanh wake/cold --- app/static/js/app.jsx | 44 ++++++++++++++++++++++++++++++++ app/static/js/app.precompiled.js | 19 ++++++++------ 2 files changed, 55 insertions(+), 8 deletions(-) diff --git a/app/static/js/app.jsx b/app/static/js/app.jsx index dc6f651..938363c 100644 --- a/app/static/js/app.jsx +++ b/app/static/js/app.jsx @@ -2084,6 +2084,44 @@ async function fxRtWsConnect(wsUrl, directPort) { try { shim._worker.postMessage({ kind: 'init', wsUrl, port: directPort || undefined }, directPort ? [directPort] : []); } catch (e) {} return shim; } +// m26d DIAG (tam): do envelope that quanh PWR ON -- pdcDelay samples / masterFx +// gains / peak mix that (masterBus.analyser) + peak nguon pre-FX +// (outputAnalyser). XOA toan bo sau khi co ket luan (M26 fix phase). +function _m26dPeak(an) { + try { + if (!an) return -1; + const _b = new Float32Array(an.fftSize || 2048); + an.getFloatTimeDomainData(_b); + let _m = 0; + for (let _i = 0; _i < _b.length; _i++) { const _v = Math.abs(_b[_i]); if (_v > _m) _m = _v; } + return _m; + } catch (e) { return -2; } +} +function _m26dSnap(tag) { + try { + if (!_phArmed()) return; + const _ctx = getAudioContext(); + const _bus = masterBus; + let _pd = -1, _gx = -1, _gd = -1, _pk = -1, _ps = -1; + try { if (_bus && _bus.pdcDelay && _ctx) _pd = Math.round(_bus.pdcDelay.delayTime.value * _ctx.sampleRate); } catch (e) {} + try { if (_bus && _bus.masterFxGain) _gx = _bus.masterFxGain.gain.value; } catch (e) {} + try { if (_bus && _bus.masterFxDryGain) _gd = _bus.masterFxDryGain.gain.value; } catch (e) {} + try { if (_bus && _bus.analyser) _pk = _m26dPeak(_bus.analyser); } catch (e) {} + try { if (_bus && _bus.outputAnalyser) _ps = _m26dPeak(_bus.outputAnalyser); } catch (e) {} + _dbgLog('m26d_' + tag, 'pdc=' + _pd + ' gx=' + (_gx >= 0 ? _gx.toFixed(4) : 'na') + ' gd=' + (_gd >= 0 ? _gd.toFixed(4) : 'na') + ' pk=' + _pk + ' ps=' + _ps + ' act=' + (fxRt && fxRt.active ? 1 : 0) + ' wrm=' + (fxRt && fxRt.warm ? 1 : 0) + ' fi=' + (fxRt && fxRt.fadedIn ? 1 : 0)); + } catch (e) {} +} +function _m26dSeries(tok, tag) { + const _t = [40, 90, 150, 250, 400, 650, 1000, 1500, 2500]; + for (let _i = 0; _i < _t.length; _i++) { + (function (_ms, _i2) { + setTimeout(function () { + try { if (tok !== fxRt.startToken) return; if (!_phArmed()) return; _m26dSnap(tag + '_' + _i2); } catch (e) {} + }, _ms); + })(_t[_i], _i); + } +} + async function fxRtStart() { // V21: mọi play/chain-change gọi đây — hủy idle timer của lần stop trước // (không để session warm bị teardown giữa lúc đang chơi). @@ -2146,6 +2184,7 @@ async function fxRtStart() { try { if (fxRt.node) fxRt.node.disconnect(masterBus.masterFxGain); } catch (e) {} try { if (fxRt.node) fxRt.node.connect(masterBus.masterFxGain); } catch (e) {} fxRt.active = true; + try { _m26dSnap('wake0'); } catch (e) {} fxRt.inQueue = []; fxRt.outL = null; fxRt.outR = null; @@ -2168,8 +2207,10 @@ async function fxRtStart() { const _wHook = (ev) => { try { if (ev.data && ev.data.type === 'started' && wToken === fxRt.startToken) { + try { _m26dSnap('won_st'); } catch (e) {} fxRt.fadedIn = true; fxRtCrossfade(true, wToken); + try { _m26dSeries(wToken, 'won'); } catch (e) {} setTimeout(() => { if (wToken === fxRt.startToken) fxRtApplyPdc(); }, 250); } } catch (e) {} @@ -2297,8 +2338,10 @@ async function fxRtStart() { if (fxRt.fadedIn) return; setTimeout(() => { if (token !== fxRt.startToken) return; + try { _m26dSnap('con_st'); } catch (e) {} fxRt.fadedIn = true; fxRtCrossfade(true, token); + try { _m26dSeries(token, 'con'); } catch (e) {} // Dry gan silent (tc 0.025) roi moi tre pdcDelay — tranh gap khi delay // dang lon dan. setTimeout(() => fxRtApplyPdc(), 250); @@ -2679,6 +2722,7 @@ function fxRtCrossfade(toFx, token) { const bus = masterBus; if (!ctx || !bus || !bus.masterFxGain || !bus.masterFxDryGain) return; if (token !== undefined && token !== fxRt.startToken) return; + try { _m26dSnap(toFx ? 'xf_on' : 'xf_off'); } catch (e) {} const tc = 0.025; try { bus.masterFxGain.gain.setTargetAtTime(toFx ? 1 : 0, ctx.currentTime, tc); diff --git a/app/static/js/app.precompiled.js b/app/static/js/app.precompiled.js index dab7233..32374e0 100644 --- a/app/static/js/app.precompiled.js +++ b/app/static/js/app.precompiled.js @@ -390,8 +390,11 @@ else if(data instanceof ArrayBuffer)this._worker.postMessage({kind:'send',buf:da // SecurityError -> fxRtStart chet -> master FX khong hoat dong (M24 dung // new WebSocket, khong bi same-origin). Fetch text qua engine (CORS * da bat) // -> Blob URL same-origin -> worker chay duoc ca Tauri lan http dev. -try{if(!fxRtWorkerUrl){const _r=await fetch(`${API_BASE_URL}/static/js/fx-rt-worker.js?v=202609071819`,{cache:'no-store'});if(!_r.ok)throw new Error('fx-rt-worker load '+_r.status);fxRtWorkerUrl=URL.createObjectURL(new Blob([await _r.text()],{type:'text/javascript'}));}shim._worker=new Worker(fxRtWorkerUrl);}catch(e){throw e;}// giong ws constructor that -> caller catch cu giu nguyen -shim._worker.onmessage=ev=>{const d=ev.data;if(!d||shim._closed)return;if(d.kind==='open'){shim.readyState=1;if(shim.onopen){try{shim.onopen();}catch(e){}}return;}if(d.kind==='close'){_fireClose(shim);return;}if(d.kind==='text'){if(shim.onmessage){try{shim.onmessage({data:d.text});}catch(e){}}}};shim._worker.onerror=()=>_fireClose(shim);try{shim._worker.postMessage({kind:'init',wsUrl,port:directPort||undefined},directPort?[directPort]:[]);}catch(e){}return shim;}async function fxRtStart(){// V21: mọi play/chain-change gọi đây — hủy idle timer của lần stop trước +try{if(!fxRtWorkerUrl){const _r=await fetch(`${API_BASE_URL}/static/js/fx-rt-worker.js?v=202609072056`,{cache:'no-store'});if(!_r.ok)throw new Error('fx-rt-worker load '+_r.status);fxRtWorkerUrl=URL.createObjectURL(new Blob([await _r.text()],{type:'text/javascript'}));}shim._worker=new Worker(fxRtWorkerUrl);}catch(e){throw e;}// giong ws constructor that -> caller catch cu giu nguyen +shim._worker.onmessage=ev=>{const d=ev.data;if(!d||shim._closed)return;if(d.kind==='open'){shim.readyState=1;if(shim.onopen){try{shim.onopen();}catch(e){}}return;}if(d.kind==='close'){_fireClose(shim);return;}if(d.kind==='text'){if(shim.onmessage){try{shim.onmessage({data:d.text});}catch(e){}}}};shim._worker.onerror=()=>_fireClose(shim);try{shim._worker.postMessage({kind:'init',wsUrl,port:directPort||undefined},directPort?[directPort]:[]);}catch(e){}return shim;}// m26d DIAG (tam): do envelope that quanh PWR ON -- pdcDelay samples / masterFx +// gains / peak mix that (masterBus.analyser) + peak nguon pre-FX +// (outputAnalyser). XOA toan bo sau khi co ket luan (M26 fix phase). +function _m26dPeak(an){try{if(!an)return-1;const _b=new Float32Array(an.fftSize||2048);an.getFloatTimeDomainData(_b);let _m=0;for(let _i=0;_i<_b.length;_i++){const _v=Math.abs(_b[_i]);if(_v>_m)_m=_v;}return _m;}catch(e){return-2;}}function _m26dSnap(tag){try{if(!_phArmed())return;const _ctx=getAudioContext();const _bus=masterBus;let _pd=-1,_gx=-1,_gd=-1,_pk=-1,_ps=-1;try{if(_bus&&_bus.pdcDelay&&_ctx)_pd=Math.round(_bus.pdcDelay.delayTime.value*_ctx.sampleRate);}catch(e){}try{if(_bus&&_bus.masterFxGain)_gx=_bus.masterFxGain.gain.value;}catch(e){}try{if(_bus&&_bus.masterFxDryGain)_gd=_bus.masterFxDryGain.gain.value;}catch(e){}try{if(_bus&&_bus.analyser)_pk=_m26dPeak(_bus.analyser);}catch(e){}try{if(_bus&&_bus.outputAnalyser)_ps=_m26dPeak(_bus.outputAnalyser);}catch(e){}_dbgLog('m26d_'+tag,'pdc='+_pd+' gx='+(_gx>=0?_gx.toFixed(4):'na')+' gd='+(_gd>=0?_gd.toFixed(4):'na')+' pk='+_pk+' ps='+_ps+' act='+(fxRt&&fxRt.active?1:0)+' wrm='+(fxRt&&fxRt.warm?1:0)+' fi='+(fxRt&&fxRt.fadedIn?1:0));}catch(e){}}function _m26dSeries(tok,tag){const _t=[40,90,150,250,400,650,1000,1500,2500];for(let _i=0;_i<_t.length;_i++){(function(_ms,_i2){setTimeout(function(){try{if(tok!==fxRt.startToken)return;if(!_phArmed())return;_m26dSnap(tag+'_'+_i2);}catch(e){}},_ms);})(_t[_i],_i);}}async function fxRtStart(){// V21: mọi play/chain-change gọi đây — hủy idle timer của lần stop trước // (không để session warm bị teardown giữa lúc đang chơi). if(fxRtWarmIdleTimer){clearTimeout(fxRtWarmIdleTimer);fxRtWarmIdleTimer=null;}const chain=fxRtChain();const ck=fxRtChainKey(chain);const ckStruct=fxRtChainStructKey(chain);if(fxRt.active){// masterBus bị rebuild (recovery/export) → node thuộc graph cũ → restart. if(!fxRt.node||fxRt.node.context!==getAudioContext())fxRtStop(true);// Chain ĐỔI CẤU TRÚC (insert/remove/bypass/reorder/type) — KHÔNG restart @@ -419,7 +422,7 @@ return;}const wToken=++fxRt.startToken;fxRt.starting=false;fxRt.warm=false;// No const _wNodeOk=!!(fxRt.node&&fxRt.node.context===getAudioContext()&&masterBus&&masterBus.outputAnalyser&&masterBus.masterFxGain);if(!_wNodeOk){fxRtStop(true);// fallthrough -> cold start phía dưới (fxRtStop đã bump token) }else{if(fxRt.chainStructKey!==ckStruct){await fxRtSetChain(chain);if(wToken!==fxRt.startToken)return;fxRt.chainStructKey=ckStruct;}fxRt.chainKey=ck;// Reconnect edges: disconnect-then-connect — toggle nhanh <180ms bypass // timer chưa kịp cắt -> disconnect ở đây tránh duplicate edge. -try{if(masterBus&&masterBus.outputAnalyser)masterBus.outputAnalyser.disconnect(fxRt.node);}catch(e){}try{if(masterBus&&masterBus.outputAnalyser)masterBus.outputAnalyser.connect(fxRt.node);}catch(e){}try{if(fxRt.node)fxRt.node.disconnect(masterBus.masterFxGain);}catch(e){}try{if(fxRt.node)fxRt.node.connect(masterBus.masterFxGain);}catch(e){}fxRt.active=true;fxRt.inQueue=[];fxRt.outL=null;fxRt.outR=null;// M19 Bug A fix: wake PWR ON sau warm-bypass. Trước đây chỉ flush engine +try{if(masterBus&&masterBus.outputAnalyser)masterBus.outputAnalyser.disconnect(fxRt.node);}catch(e){}try{if(masterBus&&masterBus.outputAnalyser)masterBus.outputAnalyser.connect(fxRt.node);}catch(e){}try{if(fxRt.node)fxRt.node.disconnect(masterBus.masterFxGain);}catch(e){}try{if(fxRt.node)fxRt.node.connect(masterBus.masterFxGain);}catch(e){}fxRt.active=true;try{_m26dSnap('wake0');}catch(e){}fxRt.inQueue=[];fxRt.outL=null;fxRt.outR=null;// M19 Bug A fix: wake PWR ON sau warm-bypass. Trước đây chỉ flush engine // ring + fadedIn=true NGAY — nhưng worklet lúc bypass rời graph không // process: outQueue còn ~FILL block audio CŨ + hasStarted=true (không gửi // 'started' lại) → reconnect xong phát stale block ngay + crossfade dry→fx @@ -430,7 +433,7 @@ try{if(masterBus&&masterBus.outputAnalyser)masterBus.outputAnalyser.disconnect(f if(fxRt.ws.readyState===1){try{fxRt.ws.send(JSON.stringify({cmd:'flush'}));}catch(e){}}try{fxRtPushAllParams();}catch(e){}try{fxRt.node.port.postMessage({type:'clear_queue',mode:'play'});}catch(e){}fxRt.fadedIn=false;// port.onmessage hiện tại là closure của cold-start cũ — guard 'started' // bằng token CŨ (≠ wToken) nên sẽ bỏ qua. Hook tạm bắt 'started' cho wake // (crossfade + PDC đúng lúc), forward mọi message khác; restore sau 3s. -const _wOld=fxRt.node.port.onmessage;const _wHook=ev=>{try{if(ev.data&&ev.data.type==='started'&&wToken===fxRt.startToken){fxRt.fadedIn=true;fxRtCrossfade(true,wToken);setTimeout(()=>{if(wToken===fxRt.startToken)fxRtApplyPdc();},250);}}catch(e){}try{_wOld(ev);}catch(e){}};fxRt.node.port.onmessage=_wHook;setTimeout(()=>{try{if(fxRt.node&&fxRt.node.port.onmessage===_wHook)fxRt.node.port.onmessage=_wOld;}catch(e){}},3000);return;}}if(!chain.length){fxRtWarmPlayHold=false;try{fxRtApplyPdc();}catch(e){}return;}// C: warm session còn nhưng không wake được (ws đóng/session mất) -> teardown +const _wOld=fxRt.node.port.onmessage;const _wHook=ev=>{try{if(ev.data&&ev.data.type==='started'&&wToken===fxRt.startToken){try{_m26dSnap('won_st');}catch(e){}fxRt.fadedIn=true;fxRtCrossfade(true,wToken);try{_m26dSeries(wToken,'won');}catch(e){}setTimeout(()=>{if(wToken===fxRt.startToken)fxRtApplyPdc();},250);}}catch(e){}try{_wOld(ev);}catch(e){}};fxRt.node.port.onmessage=_wHook;setTimeout(()=>{try{if(fxRt.node&&fxRt.node.port.onmessage===_wHook)fxRt.node.port.onmessage=_wOld;}catch(e){}},3000);return;}}if(!chain.length){fxRtWarmPlayHold=false;try{fxRtApplyPdc();}catch(e){}return;}// C: warm session còn nhưng không wake được (ws đóng/session mất) -> teardown // trước cold-spawn (tránh 2 session song song). if(fxRt.warm)fxRtStop(true);// Token chống race bypass: user bấm PWR/Bypass khi fxRtStart đang chờ // fxRealtimeStart (~4s load VST). Lúc đó fxRt.active vẫn false → effect @@ -438,7 +441,7 @@ if(fxRt.warm)fxRtStop(true);// Token chống race bypass: user bấm PWR/Bypass // node → bypass vô hiệu. Mỗi fxRtStop() bump startToken → mọi checkpoint // dưới đây thấy mismatch → hủy session vừa tạo, không nối node. const token=++fxRt.startToken;fxRt.starting=true;const ctx=getAudioContext();if(!ctx||!ctx.audioWorklet||!masterBus||!masterBus.output||!masterBus.analyser||!masterBus.masterFxGain||!masterBus.masterFxDryGain)return;const chainPayload=chain.map(s=>s.type==='vst3'?{type:'vst3',path:s.path,name:s.name||s.path,preset_b64:s.preset_b64||'',bypass:!!s.bypass||!!(window.currentMasteringSettings||{}).vstBypass}:{type:'builtin',id:s.type,params:s.params&&Object.keys(s.params).length?s.params:{},bypass:!!s.bypass});let st;try{st=await window.SonicAPI.fxRealtimeStart({fx_chain:chainPayload,sample_rate:ctx.sampleRate||44100});}catch(e){console.warn('[FX RT] start fail:',e);showToast('Không khởi động VST FX realtime: '+(e.message||e),'warning');fxRt.starting=false;return;}if(token!==fxRt.startToken){// Bypass/stop giữa lúc engine đang load chain — hủy session vừa tạo. -console.warn('[FX RT] start cancelled mid-flight — session stopped');try{window.SonicAPI.fxRealtimeStop({session_id:st.session_id}).catch(()=>{});}catch(e2){}fxRt.starting=false;return;}fxRt.sessionId=st.session_id;fxRtGuiPushShm();try{await ctx.audioWorklet.addModule(`${API_BASE_URL}/static/js/sf-fx-realtime.js?v=202609071819`);if(token!==fxRt.startToken){fxRt.starting=false;return;}fxRt.node=new AudioWorkletNode(ctx,'sf-fx-realtime',{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2]});const u=new URL(API_BASE_URL);const wsProto=u.protocol==='https:'?'wss://':'ws://';// WS to 'localhost' bi tre ~300ms: Chromium thu ::1 truoc (Windows khong +console.warn('[FX RT] start cancelled mid-flight — session stopped');try{window.SonicAPI.fxRealtimeStop({session_id:st.session_id}).catch(()=>{});}catch(e2){}fxRt.starting=false;return;}fxRt.sessionId=st.session_id;fxRtGuiPushShm();try{await ctx.audioWorklet.addModule(`${API_BASE_URL}/static/js/sf-fx-realtime.js?v=202609072056`);if(token!==fxRt.startToken){fxRt.starting=false;return;}fxRt.node=new AudioWorkletNode(ctx,'sf-fx-realtime',{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2]});const u=new URL(API_BASE_URL);const wsProto=u.protocol==='https:'?'wss://':'ws://';// WS to 'localhost' bi tre ~300ms: Chromium thu ::1 truoc (Windows khong // co listener IPv6 -> SYN hang ~2s) roi moi fallback 127.0.0.1. Dung // thang 127.0.0.1 (loopback) -> WS open ~5ms. Server chap nhan loopback. const wsHost=u.hostname==='localhost'||u.hostname==='::1'?'127.0.0.1'+(u.port?':'+u.port:''):u.host;const tok=localStorage.getItem('sonic_token')||'';const wsUrl=`${wsProto}${wsHost}${st.ws_url}${tok?'?token='+encodeURIComponent(tok):''}`;// M25: WS chay tren Web Worker - binary output/input di THANG @@ -457,7 +460,7 @@ const fxRtChunks=[0,1,2,3].map(()=>new Float32Array(512));const fxRtSendFrames=d // Giữ tham chiếu phòng khi track path còn dùng pattern cũ. const now=Date.now();while(fxRt.inQueue.length&&now-fxRt.lastInSent>=FXRT_BURST_MS){fxRt.lastInSent=now;fxRtSendFrames(fxRt.inQueue.shift());}if(fxRt.inQueue.length){if(fxRt.pumpTimer)clearTimeout(fxRt.pumpTimer);fxRt.pumpTimer=setTimeout(fxRtInPump,Math.max(1,FXRT_BURST_MS-(now-fxRt.lastInSent)));}else if(fxRt.pumpTimer){clearTimeout(fxRt.pumpTimer);fxRt.pumpTimer=null;}};fxRt.node.port.onmessage=ev=>{const d=ev.data;if(!d||!fxRt.ws)return;if(d.type==='started'){// Worklet bat dau phat (sau FILL) -> crossfade dry->fx muot. Token guard // chong race: neu stop/restart xay ra trong luc cho, bo qua. -if(fxRt.fadedIn)return;setTimeout(()=>{if(token!==fxRt.startToken)return;fxRt.fadedIn=true;fxRtCrossfade(true,token);// Dry gan silent (tc 0.025) roi moi tre pdcDelay — tranh gap khi delay +if(fxRt.fadedIn)return;setTimeout(()=>{if(token!==fxRt.startToken)return;try{_m26dSnap('con_st');}catch(e){}fxRt.fadedIn=true;fxRtCrossfade(true,token);try{_m26dSeries(token,'con');}catch(e){}// Dry gan silent (tc 0.025) roi moi tre pdcDelay — tranh gap khi delay // dang lon dan. setTimeout(()=>fxRtApplyPdc(),250);},30);return;}if(d.type==='flush'){// V24: worklet underrun-resume — yeu cau engine flush ring (xoa backlog // stale) → het lag ~1s sau stall. Fallback timer phong ack mat (WS/ @@ -567,7 +570,7 @@ function fxRtAnchorProcessed(){const _phPrevAnchor=fxRt&&fxRt.processedAnchor;if // ponytail: neu content-latency that L>0 -> FX_RT_WET_LAG_SAMPLES + L. const l=fxRt&&fxRt.active?FX_RT_WET_LAG_SAMPLES:0;try{bus.pdcDelay.delayTime.setTargetAtTime(l/(ctx.sampleRate||44100),ctx.currentTime,0.05);}catch(e){}}// Crossfade master-FX switch: ramp masterFxGain/masterFxDryGain thay vi // hard-rewire (click). Hai gain nay duoc tao trong initMasterBus. -function fxRtCrossfade(toFx,token){const ctx=getAudioContext();const bus=masterBus;if(!ctx||!bus||!bus.masterFxGain||!bus.masterFxDryGain)return;if(token!==undefined&&token!==fxRt.startToken)return;const tc=0.025;try{bus.masterFxGain.gain.setTargetAtTime(toFx?1:0,ctx.currentTime,tc);bus.masterFxDryGain.gain.setTargetAtTime(toFx?0:1,ctx.currentTime,tc);}catch(e){}}// ── Realtime VST FX per-track (SHM bridge) — mọi luồng track qua bridge ───── +function fxRtCrossfade(toFx,token){const ctx=getAudioContext();const bus=masterBus;if(!ctx||!bus||!bus.masterFxGain||!bus.masterFxDryGain)return;if(token!==undefined&&token!==fxRt.startToken)return;try{_m26dSnap(toFx?'xf_on':'xf_off');}catch(e){}const tc=0.025;try{bus.masterFxGain.gain.setTargetAtTime(toFx?1:0,ctx.currentTime,tc);bus.masterFxDryGain.gain.setTargetAtTime(toFx?0:1,ctx.currentTime,tc);}catch(e){}}// ── Realtime VST FX per-track (SHM bridge) — mọi luồng track qua bridge ───── // Mỗi track: session riêng (1 WS/SHM) cho TỪNG đường chain có âm — audio-clips // (path 'audio', splice fxEntry→mods→worklet→fxLegacyIn) và MIDI/SF (path 'sf', // splice sfEntry→mods→worklet→sfOut). Track vừa clips vừa MIDI → 2 session @@ -2246,7 +2249,7 @@ fxRtTrackReconcile(trackId,node,track);}catch(e){console.warn('rebuildTrackFxGra // Cần activeTrackNodesRef/isPlayingRef. Session giống master (fxRtStart): // fetch start → AudioWorkletNode 'sf-fx-realtime' → WS; WS open → splice // worklet vào chain hiện tại (đọc mods MỚI NHẤT — an toàn với rebuild). -const fxRtTrackStart=async(trackId,track,path)=>{const key=trackId+':'+path;const chain=fxRtTrackChain(track);if(!chain.length)return;if(fxRtTracks[key]){if(!fxRtTracks[key].node||fxRtTracks[key].node.context!==getAudioContext())fxRtTrackStop(trackId,path,true);else return;}const ctx=getAudioContext();if(!ctx||!ctx.audioWorklet)return;const chainPayload=chain.map(s=>s.type==='vst3'?{type:'vst3',path:s.path,name:s.name||s.path,preset_b64:s.preset_b64||'',bypass:!!s.bypass||!!(track&&track.vstFxBypass)}:{type:'builtin',id:s.type,params:s.params&&Object.keys(s.params).length?s.params:{},bypass:!!s.bypass});let st;try{st=await window.SonicAPI.fxRealtimeStart({fx_chain:chainPayload,sample_rate:ctx.sampleRate||44100});}catch(e){console.warn('[FX RT track] start fail',trackId,path,e);return;}const entry={sessionId:st.session_id,ws:null,node:null,ready:false,path,spliced:null,chainKey:fxRtTrackChainKey(chain)+'|vb:'+(track&&track.vstFxBypass?'1':'0'),paramsBySlot:chain.map(s=>fxRtEntryParams(s,null)),inQueue:[],pumpTimer:null,lastInSent:0,flushing:false,flushTimer:null};fxRtTracks[key]=entry;fxRtGuiPushShm();try{await ctx.audioWorklet.addModule(`${API_BASE_URL}/static/js/sf-fx-realtime.js?v=202609071819`);const node=new AudioWorkletNode(ctx,'sf-fx-realtime',{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2]});entry.node=node;const u=new URL(API_BASE_URL);const wsProto=u.protocol==='https:'?'wss://':'ws://';// WS to 'localhost' bi tre ~300ms (Chromium thu ::1 truoc roi fallback) - dung 127.0.0.1 +const fxRtTrackStart=async(trackId,track,path)=>{const key=trackId+':'+path;const chain=fxRtTrackChain(track);if(!chain.length)return;if(fxRtTracks[key]){if(!fxRtTracks[key].node||fxRtTracks[key].node.context!==getAudioContext())fxRtTrackStop(trackId,path,true);else return;}const ctx=getAudioContext();if(!ctx||!ctx.audioWorklet)return;const chainPayload=chain.map(s=>s.type==='vst3'?{type:'vst3',path:s.path,name:s.name||s.path,preset_b64:s.preset_b64||'',bypass:!!s.bypass||!!(track&&track.vstFxBypass)}:{type:'builtin',id:s.type,params:s.params&&Object.keys(s.params).length?s.params:{},bypass:!!s.bypass});let st;try{st=await window.SonicAPI.fxRealtimeStart({fx_chain:chainPayload,sample_rate:ctx.sampleRate||44100});}catch(e){console.warn('[FX RT track] start fail',trackId,path,e);return;}const entry={sessionId:st.session_id,ws:null,node:null,ready:false,path,spliced:null,chainKey:fxRtTrackChainKey(chain)+'|vb:'+(track&&track.vstFxBypass?'1':'0'),paramsBySlot:chain.map(s=>fxRtEntryParams(s,null)),inQueue:[],pumpTimer:null,lastInSent:0,flushing:false,flushTimer:null};fxRtTracks[key]=entry;fxRtGuiPushShm();try{await ctx.audioWorklet.addModule(`${API_BASE_URL}/static/js/sf-fx-realtime.js?v=202609072056`);const node=new AudioWorkletNode(ctx,'sf-fx-realtime',{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2]});entry.node=node;const u=new URL(API_BASE_URL);const wsProto=u.protocol==='https:'?'wss://':'ws://';// WS to 'localhost' bi tre ~300ms (Chromium thu ::1 truoc roi fallback) - dung 127.0.0.1 const wsHost=u.hostname==='localhost'||u.hostname==='::1'?'127.0.0.1'+(u.port?':'+u.port:''):u.host;const tok=localStorage.getItem('sonic_token')||'';const ws=new WebSocket(`${wsProto}${wsHost}${st.ws_url}${tok?'?token='+encodeURIComponent(tok):''}`);entry.ws=ws;ws.binaryType='arraybuffer';ws.onopen=()=>{entry.ready=true;entry.inQueue=[];// bỏ audio stale trước khi WS open — hết lag khởi đầu fxRtTrackSplice(trackId,path);try{(entry.paramsBySlot||[]).forEach((pl,slot)=>pl.forEach(p=>ws.send(JSON.stringify({cmd:'set_param',slot,key:p.key,value:p.value}))));}catch(e){}};ws.onmessage=ev=>{if(typeof ev.data==='string'){try{const d=JSON.parse(ev.data);if(d&&d.cmd==='flush_done'){entry.flushing=false;if(entry.flushTimer){clearTimeout(entry.flushTimer);entry.flushTimer=null;}if(entry.node)entry.node.port.postMessage({type:'flush_done'});}}catch(e){}return;}if(!(ev.data instanceof ArrayBuffer)||!entry.node)return;if(entry.flushing)return;// V24: output stale trong luc flush — drop const f=new Float32Array(ev.data);const half=f.length/2;const l=new Float32Array(half);const r=new Float32Array(half);for(let i=0;ifxRtTrackStop(trackId,path,true);ws.onerror=()=>{try{ws.close();}catch(e){}};entry.node.port.onmessage=ev=>{const d=ev.data;if(!d||!entry.ws)return;if(d.type==='flush'){// V24: nhu master — worklet underrun-resume → flush engine ring