diff --git a/app/static/js/app.jsx b/app/static/js/app.jsx index 4346977..0bb240d 100644 --- a/app/static/js/app.jsx +++ b/app/static/js/app.jsx @@ -2149,6 +2149,29 @@ async function fxRtStart() { fxRt.inQueue = []; fxRt.outL = null; fxRt.outR = null; + // M26b diag: PWR ON wake — snap pdcDelay/gains + hoi worklet state luc + // wake, luc 'started' (wet bat dau) + 180/400/800ms sau: do wet-lag that, + // delay node co ve 0 truoc crossfade khong. Bo diag o build fix. + let _m26onWlArmed = false; + const _snapOn = (tag, _sched) => { + let _pd='na',_gd='na',_gw='na',_ps='na',_pa='na'; + const _b=masterBus, _c=getAudioContext(); + try { if(_b&&_b.pdcDelay) _pd=(_b.pdcDelay.delayTime.value*1000).toFixed(1); } catch(e){} + try { if(_b&&_b.masterFxDryGain) _gd=_b.masterFxDryGain.gain.value.toFixed(4); } catch(e){} + try { if(_b&&_b.masterFxGain) _gw=_b.masterFxGain.gain.value.toFixed(4); } catch(e){} + try { _ps=typeof fxRt.processedSamples==='number'?fxRt.processedSamples:'na'; } catch(e){} + try { _pa=typeof fxRt.processedAnchor==='number'?fxRt.processedAnchor:'na'; } catch(e){} + _dbgLog(tag,'pdcMs='+_pd+' gDry='+_gd+' gWet='+_gw+' lat='+(fxRt.latencyTotal||0)+' ps='+_ps+' pa='+_pa+' act='+(fxRt.active?1:0)+' warm='+(fxRt.warm?1:0)+' faded='+(fxRt.fadedIn?1:0)+' ctx='+(_c?_c.currentTime.toFixed(3):'na')); + try { if (fxRt.node && fxRt.node.port) fxRt.node.port.postMessage({ type: 'dbg_state', k: tag }); } catch(e){} + if (_sched && _sched.length) _sched.forEach((_ms,_ix)=>setTimeout(()=>_snapOn('ph_on'+( _ix+1)),_ms)); + }; + try { if (fxRt.node && fxRt.node.port && !_m26onWlArmed) { + _m26onWlArmed = true; + const _wl = (ev) => { try { const d = ev.data; if (d && d.type === 'dbg_state_r') _dbgLog('ph_on_wl','k='+d.k+' t='+d.t+' q='+d.q+' play='+d.playing+' hs='+d.hasStarted+' sil='+d.silenced+' fp='+d.flushPending+' stp='+d.stopped+' wm='+d.wrapMode+' wfb='+d.wrapFadeBlocks+' lat='+d.latencySamples+' rfill='+d.resumeFill+' inC='+d.inCount+' outPos='+d.outPos+' fadeL='+d.fadeLeft+' holdL='+d.holdFadeLeft); } catch(e){} }; + fxRt.node.port.addEventListener('message', _wl); + setTimeout(()=>{ try { if (fxRt.node && fxRt.node.port) fxRt.node.port.removeEventListener('message', _wl); } catch(e){} }, 2600); + } } catch(e){} + _snapOn('ph_on_a', 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 @@ -2169,6 +2192,7 @@ async function fxRtStart() { try { if (ev.data && ev.data.type === 'started' && wToken === fxRt.startToken) { fxRt.fadedIn = true; + try { _snapOn('ph_on_s', [180, 400, 800]); } catch (e) {} fxRtCrossfade(true, wToken); setTimeout(() => { if (wToken === fxRt.startToken) fxRtApplyPdc(); }, 250); } diff --git a/app/static/js/app.precompiled.js b/app/static/js/app.precompiled.js index e32a32b..8f6bc7e 100644 --- a/app/static/js/app.precompiled.js +++ b/app/static/js/app.precompiled.js @@ -390,7 +390,7 @@ 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=202609060930`,{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 +try{if(!fxRtWorkerUrl){const _r=await fetch(`${API_BASE_URL}/static/js/fx-rt-worker.js?v=202609071745`,{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 // (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. @@ -419,7 +419,10 @@ 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;fxRt.inQueue=[];fxRt.outL=null;fxRt.outR=null;// M26b diag: PWR ON wake — snap pdcDelay/gains + hoi worklet state luc +// wake, luc 'started' (wet bat dau) + 180/400/800ms sau: do wet-lag that, +// delay node co ve 0 truoc crossfade khong. Bo diag o build fix. +let _m26onWlArmed=false;const _snapOn=(tag,_sched)=>{let _pd='na',_gd='na',_gw='na',_ps='na',_pa='na';const _b=masterBus,_c=getAudioContext();try{if(_b&&_b.pdcDelay)_pd=(_b.pdcDelay.delayTime.value*1000).toFixed(1);}catch(e){}try{if(_b&&_b.masterFxDryGain)_gd=_b.masterFxDryGain.gain.value.toFixed(4);}catch(e){}try{if(_b&&_b.masterFxGain)_gw=_b.masterFxGain.gain.value.toFixed(4);}catch(e){}try{_ps=typeof fxRt.processedSamples==='number'?fxRt.processedSamples:'na';}catch(e){}try{_pa=typeof fxRt.processedAnchor==='number'?fxRt.processedAnchor:'na';}catch(e){}_dbgLog(tag,'pdcMs='+_pd+' gDry='+_gd+' gWet='+_gw+' lat='+(fxRt.latencyTotal||0)+' ps='+_ps+' pa='+_pa+' act='+(fxRt.active?1:0)+' warm='+(fxRt.warm?1:0)+' faded='+(fxRt.fadedIn?1:0)+' ctx='+(_c?_c.currentTime.toFixed(3):'na'));try{if(fxRt.node&&fxRt.node.port)fxRt.node.port.postMessage({type:'dbg_state',k:tag});}catch(e){}if(_sched&&_sched.length)_sched.forEach((_ms,_ix)=>setTimeout(()=>_snapOn('ph_on'+(_ix+1)),_ms));};try{if(fxRt.node&&fxRt.node.port&&!_m26onWlArmed){_m26onWlArmed=true;const _wl=ev=>{try{const d=ev.data;if(d&&d.type==='dbg_state_r')_dbgLog('ph_on_wl','k='+d.k+' t='+d.t+' q='+d.q+' play='+d.playing+' hs='+d.hasStarted+' sil='+d.silenced+' fp='+d.flushPending+' stp='+d.stopped+' wm='+d.wrapMode+' wfb='+d.wrapFadeBlocks+' lat='+d.latencySamples+' rfill='+d.resumeFill+' inC='+d.inCount+' outPos='+d.outPos+' fadeL='+d.fadeLeft+' holdL='+d.holdFadeLeft);}catch(e){}};fxRt.node.port.addEventListener('message',_wl);setTimeout(()=>{try{if(fxRt.node&&fxRt.node.port)fxRt.node.port.removeEventListener('message',_wl);}catch(e){}},2600);}}catch(e){}_snapOn('ph_on_a',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){fxRt.fadedIn=true;try{_snapOn('ph_on_s',[180,400,800]);}catch(e){}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 // 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=202609060930`);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=202609071745`);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 @@ -2248,7 +2251,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=202609060930`);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=202609071745`);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