From 662383e5380a96e7e4a5ea95fa045c1c56c7efca Mon Sep 17 00:00:00 2001 From: locphamtran Date: Tue, 25 Aug 2026 08:11:02 +0700 Subject: [PATCH] debug(bounce): EVT_REG/BRIDGE_EVT_RX/WI_QUERY diag + fix PUSH_SENT typo --- app/static/js/app.jsx | 11 +++++++++++ app/static/js/app.precompiled.js | 7 ++++--- app/static/js/services/nativeBridgeService.js | 4 +++- app/templates/index.html | 4 ++-- 4 files changed, 20 insertions(+), 6 deletions(-) diff --git a/app/static/js/app.jsx b/app/static/js/app.jsx index 3c32f00..d5a11bf 100644 --- a/app/static/js/app.jsx +++ b/app/static/js/app.jsx @@ -41,6 +41,17 @@ window.__sfDiagShow = function () { // từ BOUNCE_START. window.__sfHBCount = 0; setInterval(function () { window.__sfHBCount++; if (window.__sfDiag) window.__sfDiag('HB:' + window.__sfHBCount); }, 250); +// WI_QUERY: bridge write_index liveness via proven invoke path (event-free). +window.__sfWICount = 0; +setInterval(function () { + window.__sfWICount++; + if (!window.__TAURI__ || !window.__TAURI__.core) return; + window.__TAURI__.core.invoke('bridge_status').then(function (s) { + if (window.__sfDiag) window.__sfDiag('WI_QUERY#' + window.__sfWICount + ' idx=' + (s && s.write_index) + ' conn=' + (s && s.connected ? 1 : 0)); + }).catch(function (e) { + if (window.__sfDiag) window.__sfDiag('WI_QUERY#' + window.__sfWICount + ' err=' + String(e).slice(0, 80)); + }); +}, 2000); // ── Dedicated per-track MIDI channel allocation ── // FluidSynth has 16 channels; if two tracks share a channel, arming one track diff --git a/app/static/js/app.precompiled.js b/app/static/js/app.precompiled.js index 3520df4..2bf01e5 100644 --- a/app/static/js/app.precompiled.js +++ b/app/static/js/app.precompiled.js @@ -3,7 +3,8 @@ const API_BASE_URL=(window.API_BASE_URL||window.location.origin).replace(/\/+$/, window.__sfDiag=function(){var arr=[];try{var s=localStorage.getItem('__sf_diag');if(s)arr=JSON.parse(s)||[];}catch(e){}return function(msg){try{arr.push(new Date().toISOString().slice(11,23)+' '+msg);if(arr.length>2000)arr=arr.slice(-2000);localStorage.setItem('__sf_diag',JSON.stringify(arr));}catch(e){}};}();window.__sfDiagDump=function(){try{var s=localStorage.getItem('__sf_diag');var arr=s?JSON.parse(s)||[]:[];var idx=-1;for(var i=arr.length-1;i>=0;i--){if(arr[i].indexOf('BOUNCE_START')!==-1){idx=i;break;}}return(idx>=0?arr.slice(idx):arr.slice(-50)).join('\n');}catch(e){return String(e);}};window.__sfDiagShow=function(){try{if(window.__sfDiagDump){var ov=document.createElement('div');ov.style.cssText='position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,.65);display:flex;align-items:center;justify-content:center;font-family:monospace';var box=document.createElement('div');box.style.cssText='background:#fff;color:#111;border-radius:8px;padding:12px;width:min(92vw,900px);max-height:85vh;display:flex;flex-direction:column;box-shadow:0 4px 24px rgba(0,0,0,.5)';var ta=document.createElement('textarea');ta.readOnly=true;ta.value=window.__sfDiagDump();ta.style.cssText='flex:1;min-height:55vh;font-family:monospace;font-size:11px;white-space:pre;resize:none';var bar=document.createElement('div');bar.style.cssText='display:flex;gap:8px;justify-content:flex-end;margin-top:8px';var bCopy=document.createElement('button');bCopy.textContent='Copy';bCopy.onclick=function(){try{ta.focus();ta.select();document.execCommand('copy');bCopy.textContent='Đã copy!';}catch(e){bCopy.textContent='Copy thủ công (Ctrl+C)';}};var bClose=document.createElement('button');bClose.textContent='Đóng';bClose.onclick=function(){document.body.removeChild(ov);};bar.appendChild(bCopy);bar.appendChild(bClose);box.appendChild(ta);box.appendChild(bar);ov.appendChild(box);document.body.appendChild(ov);try{ta.focus();ta.select();}catch(e){}return;}}catch(e){window.alert('DIAG:\n'+(window.__sfDiagDump?window.__sfDiagDump():''));}};// HB: main-thread heartbeat — khoảng cách giữa các HB chứng minh main thread // bị block (timer không fire trong lúc block). Chạy vĩnh viễn; dump chỉ lấy // từ BOUNCE_START. -window.__sfHBCount=0;setInterval(function(){window.__sfHBCount++;if(window.__sfDiag)window.__sfDiag('HB:'+window.__sfHBCount);},250);// ── Dedicated per-track MIDI channel allocation ── +window.__sfHBCount=0;setInterval(function(){window.__sfHBCount++;if(window.__sfDiag)window.__sfDiag('HB:'+window.__sfHBCount);},250);// WI_QUERY: bridge write_index liveness via proven invoke path (event-free). +window.__sfWICount=0;setInterval(function(){window.__sfWICount++;if(!window.__TAURI__||!window.__TAURI__.core)return;window.__TAURI__.core.invoke('bridge_status').then(function(s){if(window.__sfDiag)window.__sfDiag('WI_QUERY#'+window.__sfWICount+' idx='+(s&&s.write_index)+' conn='+(s&&s.connected?1:0));}).catch(function(e){if(window.__sfDiag)window.__sfDiag('WI_QUERY#'+window.__sfWICount+' err='+String(e).slice(0,80));});},2000);// ── Dedicated per-track MIDI channel allocation ── // FluidSynth has 16 channels; if two tracks share a channel, arming one track // re-selects the other track's program and its instrument changes. Every track // gets its own stable, unique channel (0-15, skipping 9 which is the classic @@ -316,7 +317,7 @@ else if(fxRt.chainKey!==ck){fxRtSetChain(chain);fxRt.chainKey=ck;return;}else re // 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=202608250054`);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://';const tok=localStorage.getItem('sonic_token')||'';const wsUrl=`${wsProto}${u.host}${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.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 +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=202608250110`);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://';const tok=localStorage.getItem('sonic_token')||'';const wsUrl=`${wsProto}${u.host}${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.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 try{fxRtPushAllParams();}catch(e){}};ws.onmessage=ev=>{// Gap 8 (PDC realtime): text frame {cmd:'latency', total} tu server -> // cap nhat delay dry-bypass path (bu latency chain VST3 realtime). if(typeof ev.data==='string'){try{const d=JSON.parse(ev.data);if(d&&d.cmd==='latency'&&typeof d.total==='number'){fxRt.latencyTotal=d.total;// Chi delay dry path khi crossfade da xong (dry silent) — ap som @@ -1771,7 +1772,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};fxRtTracks[key]=entry;fxRtGuiPushShm();try{await ctx.audioWorklet.addModule(`${API_BASE_URL}/static/js/sf-fx-realtime.js?v=202608250054`);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://';const tok=localStorage.getItem('sonic_token')||'';const ws=new WebSocket(`${wsProto}${u.host}${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 +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};fxRtTracks[key]=entry;fxRtGuiPushShm();try{await ctx.audioWorklet.addModule(`${API_BASE_URL}/static/js/sf-fx-realtime.js?v=202608250110`);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://';const tok=localStorage.getItem('sonic_token')||'';const ws=new WebSocket(`${wsProto}${u.host}${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(!(ev.data instanceof ArrayBuffer)||!entry.node)return;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==='set_param'){try{entry.ws.send(JSON.stringify({cmd:'set_param',slot:d.slot,key:d.key,value:d.value}));}catch(e){}return;}if(d.type!=='in')return;// Burst 4 block (1024 mẫu) → tách 4 WS frame 512 floats → bridge batch 4. // Pace 1 burst/21ms (giống master) — tránh dồn frame sau stall làm tràn ring. entry.inQueue.push(d);const pump=()=>{if(!entry.inQueue.length)return;const now=Date.now();while(entry.inQueue.length&&now-entry.lastInSent>=FXRT_BURST_MS){entry.lastInSent=now;const dd=entry.inQueue.shift();if(entry.ws&&entry.ws.readyState===1){try{const f=new Float32Array(dd.data);if(f.length>512){for(let i=0;i{const entry=fxRtTracks[trackId+':'+path];if(!entry||!entry.spliced||!entry.node)return;try{entry.node.disconnect();try{entry.spliced.tail.connect(entry.spliced.dest);}catch(e){}entry.spliced=null;}catch(e){console.warn('[FX RT track] unsplice fail',trackId,path,e);}};// Chain đổi trên session ĐANG CHẠY — set_chain KHÔNG restart (bridge swap diff --git a/app/static/js/services/nativeBridgeService.js b/app/static/js/services/nativeBridgeService.js index 092887e..b1e6f54 100644 --- a/app/static/js/services/nativeBridgeService.js +++ b/app/static/js/services/nativeBridgeService.js @@ -54,6 +54,7 @@ var self = this; try { window.__TAURI__.event.listen('bridge-audio', function (e) { + if (!self._evtDiagAt || Date.now() - self._evtDiagAt >= 1000) { self._evtDiagAt = Date.now(); if (window.__sfDiag) window.__sfDiag('BRIDGE_EVT_RX cb=' + (self._audioCb ? 'yes' : 'no') + ' len=' + (e.payload && e.payload.l ? e.payload.l.length : 0)); } // Bridge recovered after bridge-down (or never bootstrapped): // audio frames flow again -> re-establish routing (Fix C). if (!self.isBridgeConnected) self._reconnectIfNeeded(); @@ -71,6 +72,7 @@ if (window.AudioRoutingEngine) window.AudioRoutingEngine.disconnect(); console.warn('[BridgeService] bridge-down event received.'); }); + if (window.__sfDiag) window.__sfDiag('EVT_REG ok'); } catch (e) { console.warn('[BridgeService] event listen failed:', e); } @@ -136,7 +138,7 @@ default: byteCmd = cmd === 'NOTE_ON' ? 0x9 : 0x8; break; } this._pushSent = (this._pushSent || 0) + 1; - if (this.pushSent % 100 === 0 && window.__sfDiag) window.__sfDiag('PUSH_SENT ' + _pushSent); + if (this._pushSent % 100 === 0 && window.__sfDiag) window.__sfDiag('PUSH_SENT ' + this._pushSent); // DIAG: Promise.race 800ms — invoke gửi đi nhưng không settle -> timeout // (phan biet main-thread block vs Rust hang). Promise.race([ diff --git a/app/templates/index.html b/app/templates/index.html index 4487c07..e0e8cd8 100644 --- a/app/templates/index.html +++ b/app/templates/index.html @@ -39,7 +39,7 @@ - + @@ -51,7 +51,7 @@ - +