diff --git a/app/static/js/app.jsx b/app/static/js/app.jsx index 92991ae..848c952 100644 --- a/app/static/js/app.jsx +++ b/app/static/js/app.jsx @@ -2006,13 +2006,34 @@ async function fxRtStart() { fxRt.inQueue = []; fxRt.outL = null; fxRt.outR = null; - // Không clear_queue (hole ~128ms resumeFill=FILL) — chỉ flush engine ring - // (bỏ backlog stale); worklet drop output stale tới flush_done. + // 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 + // khi wet chưa có audio mới → gap → underrun/wobble (log u4-u8). Giờ giống + // cold start: clear_queue mode 'play' (worklet wipe queue + resumeFill=FILL + // + hasStarted=false → gửi 'started' khi đủ FILL block MỚI) → crossfade + + // PDC chỉ khi audio mới thực sự chảy. Engine flush vẫn giữ (bỏ backlog). if (fxRt.ws.readyState === 1) { try { fxRt.ws.send(JSON.stringify({ cmd: 'flush' })); } catch (e) {} } try { fxRtPushAllParams(); } catch (e) {} - fxRt.fadedIn = true; - fxRtCrossfade(true, wToken); - setTimeout(() => { if (wToken === fxRt.startToken) fxRtApplyPdc(); }, 250); + 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; } } diff --git a/app/static/js/app.precompiled.js b/app/static/js/app.precompiled.js index 166bbb5..9c240d9 100644 --- a/app/static/js/app.precompiled.js +++ b/app/static/js/app.precompiled.js @@ -390,9 +390,18 @@ if(!chain.length)return;const wToken=++fxRt.startToken;fxRt.starting=false;fxRt. 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;// Không clear_queue (hole ~128ms resumeFill=FILL) — chỉ flush engine ring -// (bỏ backlog stale); worklet drop output stale tới flush_done. -if(fxRt.ws.readyState===1){try{fxRt.ws.send(JSON.stringify({cmd:'flush'}));}catch(e){}}try{fxRtPushAllParams();}catch(e){}fxRt.fadedIn=true;fxRtCrossfade(true,wToken);setTimeout(()=>{if(wToken===fxRt.startToken)fxRtApplyPdc();},250);return;}}if(!chain.length)return;// C: warm session còn nhưng không wake được (ws đóng/session mất) -> teardown +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 +// 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 +// khi wet chưa có audio mới → gap → underrun/wobble (log u4-u8). Giờ giống +// cold start: clear_queue mode 'play' (worklet wipe queue + resumeFill=FILL +// + hasStarted=false → gửi 'started' khi đủ FILL block MỚI) → crossfade + +// PDC chỉ khi audio mới thực sự chảy. Engine flush vẫn giữ (bỏ backlog). +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)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 @@ -400,7 +409,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=202609062130`);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=202609070853`);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):''}`;const ws=new WebSocket(wsUrl);fxRt.ws=ws;ws.binaryType='arraybuffer';ws.onopen=()=>{if(token!==fxRt.startToken){try{ws.close();}catch(e){}fxRt.starting=false;return;}fxRt.active=true;fxRt.flushing=false;fxRt.starting=false;fxRt.inQueue=[];// bỏ audio stale sản xuất trước khi WS open (~4s load VST) — hết lag khởi đầu @@ -2169,7 +2178,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=202609062130`);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=202609070853`);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 diff --git a/app/static/js/sf-fx-realtime.js b/app/static/js/sf-fx-realtime.js index addc22a..24054ab 100644 --- a/app/static/js/sf-fx-realtime.js +++ b/app/static/js/sf-fx-realtime.js @@ -184,6 +184,12 @@ class SfFxRealtimeProcessor extends AudioWorkletProcessor { // engine ramp/jitter dau play); ARM live note giu RESUME_FILL 8 (~43ms) — preview // nhanh, khong cho FILL 8. this.resumeFill = (d.mode === 'play') ? this.FILL : this.RESUME_FILL; + // M19 Bug A: wake PWR ON sau warm-bypass — worklet rời graph không process + // nên hasStarted còn true từ lần play trước → không bao giờ gửi 'started' + // lại → main không crossfade đúng lúc. Reset ở clear mode 'play' → resume + // sau FILL gửi 'started' lần nữa (giống cold start). Clear 'play' khác khi + // đã active: main fadedIn=true rồi → 'started' thêm bị bỏ qua, vô hại. + if (d.mode === 'play') this.hasStarted = false; this.silenced = false; this.fadeFromL = this.lastOutL; this.fadeFromR = this.lastOutR; diff --git a/app/templates/index.html b/app/templates/index.html index 9fe375d..ad85962 100644 --- a/app/templates/index.html +++ b/app/templates/index.html @@ -51,7 +51,7 @@ - +