From 36f2cf79b1cc5411561471461963b308b25e85ba Mon Sep 17 00:00:00 2001 From: locphamtran Date: Mon, 31 Aug 2026 12:43:08 +0700 Subject: [PATCH] V45.19: fix Bug 1b (seek#2 + wrap freeze) + Bug 2 (ARM scope theo active tab) v=202608311242 - Bug 1b: worklet clear_queue nho clearMode; dbgPlayFirst post fx_seek_first khi mode=seek -> main snap khong can guard 50ms (seek resume nhanh ~43ms < 50ms). - Bug 1b: loop wrap KHONG freeze playhead nua (chi re-anchor processed) -> het playhead dung ~1.5s sau wrap (truoc day freeze 1500ms fail-safe). - Bug 2: vkbNoteOn chi gom ARM piano roll khi DANG o PIANO_ROLL tab; MAIN/SECTION khong ARM -> targets rong -> preview cam. renderKeybed silent flag tuong tu. - DIAG: preview_diag them trg/prTab (vkb) + sl (keybed). --- app/static/js/app.jsx | 88 ++++++++++++++++++++------------ app/static/js/app.precompiled.js | 32 +++++++----- app/static/js/sf-fx-realtime.js | 5 +- app/templates/index.html | 2 +- 4 files changed, 81 insertions(+), 46 deletions(-) diff --git a/app/static/js/app.jsx b/app/static/js/app.jsx index f61af79..ea63fb4 100644 --- a/app/static/js/app.jsx +++ b/app/static/js/app.jsx @@ -2069,7 +2069,10 @@ async function fxRtStart() { // worklet phát lại OLD TAIL ~5ms → dbgPlayFirst tiêu thụ → trước đây snap // playhead SỚM + calib nhiễu ~50ms → display chạy trước → wrap sớm → vấp // beat 0:0. Pass mới thật ≥ ~80ms → snap/calib chỉ trên event hợp lệ. - if (d.tag === 'fx_play_first' && (_now - _dbgPlayStartMs) >= 50) { + // V45.19 Bug 1b: fx_seek_first (seek resume nhanh ~43ms < 50ms) snap KHONG + // can guard 50ms; fx_play_first giu guard (chan old-tail loop wrap snap som). + const _seekFirst = d.tag === 'fx_seek_first'; + if ((d.tag === 'fx_play_first' || _seekFirst) && (_seekFirst || (_now - _dbgPlayStartMs) >= 50)) { fxRt.pdcCalibMs = Math.max(50, Math.min(3000, _now - _dbgPlayStartMs)); try { if (window.__fxRtSnapPlayhead) window.__fxRtSnapPlayhead(); } catch (e2) {} } @@ -11064,6 +11067,11 @@ const PianoRollTabEditor = ({ st, zoom, bpm, viewportWidth, activeTracks, onClos var kbTrk = activeTracks.find(function(t) { return t.id === st.trackId; }); var kbCtx = resolveTrackInstrumentCtx(kbTrk, activeTracks); ensureSonicInstrument(kbCtx); + // V45.19 Bug 2: keybed chi phat khi DANG o PIANO_ROLL tab hoac track isArmed + // (MAIN/SECTION + ARM off -> cam). NOTE_OFF van gui (vo hai). + const _kbPrTab = (subTabsRef.current || []).find(function (s) { return s.id === activeTabRef.current; }); + const _kbIsPrTab = !!(_kbPrTab && _kbPrTab.type === 'PIANO_ROLL'); + const _kbSilent = !_kbIsPrTab && !(kbTrk && kbTrk.isArmed); const keys = []; for (let pitch = 127; pitch >= PITCH_START; pitch--) { const isBlack = [1, 3, 6, 8, 10].includes(pitch % 12); @@ -11096,34 +11104,37 @@ const PianoRollTabEditor = ({ st, zoom, bpm, viewportWidth, activeTracks, onClos const _pdTab = activeTabRef.current; const _pdSub = subTabsRef.current ? (subTabsRef.current.find(s => s.id === _pdTab) || {}).type : null; const _kbArmedTab = !!(subTabsRef.current || []).some(function (s) { return s.type === 'PIANO_ROLL' && s.isArmed && s.trackId === st.trackId; }); - _dbgLog('preview_diag', 'src=keybed trk=' + st.trackId + ' kbTrk=' + (kbTrk ? kbTrk.id : 'UNDEF') + ' kbArmedTab=' + (_kbArmedTab ? 1 : 0) + ' armedTrk=' + (kbTrk && kbTrk.isArmed ? 1 : 0) + ' tab=' + _pdTab + ' sub=' + (_pdSub || 'none') + ' play=' + (isPlayingRef.current ? 1 : 0) + ' br=' + (window.SonicMidiRouter && window.SonicMidiRouter.isBridgeActive() ? 1 : 0) + ' fxRt=' + (fxRt.active ? 1 : 0) + ' dest=' + _pdDest + ' bd=' + (_pdD ? ('i=' + _pdD.initialized + ' wl=' + _pdD.useWorklet + ' nd=' + _pdD.hasWorkletNode + ' pre=' + _pdD.preBufferLen + ' ch=' + _pdD.chunksLen + ' g=' + _pdD.gain) : 'MISSING') + ' mb=' + (!!masterBus)); + _dbgLog('preview_diag', 'src=keybed trk=' + st.trackId + ' kbTrk=' + (kbTrk ? kbTrk.id : 'UNDEF') + ' kbArmedTab=' + (_kbArmedTab ? 1 : 0) + ' armedTrk=' + (kbTrk && kbTrk.isArmed ? 1 : 0) + ' sl=' + (_kbSilent ? 1 : 0) + ' tab=' + _pdTab + ' sub=' + (_pdSub || 'none') + ' play=' + (isPlayingRef.current ? 1 : 0) + ' br=' + (window.SonicMidiRouter && window.SonicMidiRouter.isBridgeActive() ? 1 : 0) + ' fxRt=' + (fxRt.active ? 1 : 0) + ' dest=' + _pdDest + ' bd=' + (_pdD ? ('i=' + _pdD.initialized + ' wl=' + _pdD.useWorklet + ' nd=' + _pdD.hasWorkletNode + ' pre=' + _pdD.preBufferLen + ' ch=' + _pdD.chunksLen + ' g=' + _pdD.gain) : 'MISSING') + ' mb=' + (!!masterBus)); } catch (e) {} - try { window.__dbgPreviewAudioArmed = { count: 0, nz: 0, t0: performance.now() }; } catch (e) {} - if (window.triggerMidiVuActivity) { - window.triggerMidiVuActivity((st.parent_tab_id && st.parent_tab_id.startsWith('session_') ? '_sess_' : '') + st.trackId, 100); - } - const kbNative = isStandaloneSf() && isSfTrackEngine(kbCtx.synthEngine) && !(window.SonicMidiRouter && window.SonicMidiRouter.isBridgeActive()); - const kbNativeVst = isStandaloneSf() && isVstTrackEngine(kbCtx.synthEngine) && !(window.SonicMidiRouter && window.SonicMidiRouter.isBridgeActive()); - if (kbNative) { - playNativeSfNote(kbTrk, pitch, 100 / 127, 5000, undefined, 'kb_' + st.trackId + '_' + pitch); - } else if (kbNativeVst) { - playNativeVstNote(kbTrk, pitch, 100 / 127, 5000, undefined, 'kb_' + st.trackId + '_' + pitch); - } - if (window.SonicMidiRouter && window.SonicMidiRouter.isBridgeActive()) { - try { if (window.__ensureBridgeProgram) window.__ensureBridgeProgram(kbTrk ? kbTrk.id : 0, kbCtx.program, kbCtx.synthEngine); } catch (er) {} - window.SonicMidiRouter.pushEvent({ cmd: 'NOTE_ON', channel: kbTrk ? kbTrk.id : 0, pitch: pitch, velocity: 100 / 127, percussion: !!(kbCtx && kbCtx.synthEngine && kbCtx.synthEngine.soundfont_bank === 128), live: true }); - } else if (window.SonicSF && !kbNative && !kbNativeVst) { - // ⚠️ FIX: giữ note theo thời gian bấm phím — durationMs lớn (5s) - // chỉ là auto-off phòng hờ; mouseup/mouseleave gọi stopNote dừng - // NGAY (trước đây 500ms → note tự tắt giữa chừng khi giữ phím). - window.SonicSF.playNote(pitch, 100, 5000, undefined, kbCtx.program, null, kbCtx.ch, kbCtx.synthEngine); + // V45.19 Bug 2: _kbSilent -> bo qua phat (MAIN/SECTION + ARM off = cam). + if (!_kbSilent) { + try { window.__dbgPreviewAudioArmed = { count: 0, nz: 0, t0: performance.now() }; } catch (e) {} + if (window.triggerMidiVuActivity) { + window.triggerMidiVuActivity((st.parent_tab_id && st.parent_tab_id.startsWith('session_') ? '_sess_' : '') + st.trackId, 100); + } + const kbNative = isStandaloneSf() && isSfTrackEngine(kbCtx.synthEngine) && !(window.SonicMidiRouter && window.SonicMidiRouter.isBridgeActive()); + const kbNativeVst = isStandaloneSf() && isVstTrackEngine(kbCtx.synthEngine) && !(window.SonicMidiRouter && window.SonicMidiRouter.isBridgeActive()); + if (kbNative) { + playNativeSfNote(kbTrk, pitch, 100 / 127, 5000, undefined, 'kb_' + st.trackId + '_' + pitch); + } else if (kbNativeVst) { + playNativeVstNote(kbTrk, pitch, 100 / 127, 5000, undefined, 'kb_' + st.trackId + '_' + pitch); + } + if (window.SonicMidiRouter && window.SonicMidiRouter.isBridgeActive()) { + try { if (window.__ensureBridgeProgram) window.__ensureBridgeProgram(kbTrk ? kbTrk.id : 0, kbCtx.program, kbCtx.synthEngine); } catch (er) {} + window.SonicMidiRouter.pushEvent({ cmd: 'NOTE_ON', channel: kbTrk ? kbTrk.id : 0, pitch: pitch, velocity: 100 / 127, percussion: !!(kbCtx && kbCtx.synthEngine && kbCtx.synthEngine.soundfont_bank === 128), live: true }); + } else if (window.SonicSF && !kbNative && !kbNativeVst) { + // ⚠️ FIX: giữ note theo thời gian bấm phím — durationMs lớn (5s) + // chỉ là auto-off phòng hờ; mouseup/mouseleave gọi stopNote dừng + // NGAY (trước đây 500ms → note tự tắt giữa chừng khi giữ phím). + window.SonicSF.playNote(pitch, 100, 5000, undefined, kbCtx.program, null, kbCtx.ch, kbCtx.synthEngine); + } } } catch (err) { console.error('playNote error:', err); } }, onMouseEnter: (e) => { - if (keybedMouseDownRef.current) { + if (keybedMouseDownRef.current && !_kbSilent) { try { if (window.triggerMidiVuActivity) { window.triggerMidiVuActivity((st.parent_tab_id && st.parent_tab_id.startsWith('session_') ? '_sess_' : '') + st.trackId, 100); @@ -23862,20 +23873,24 @@ const App = () => { const vkbNoteOn = (pitch, vel) => { try { if (window.__ensureMasteringRouting) window.__ensureMasteringRouting(); } catch (er) {} const allTracks = activeTracksRef.current || []; - // ARM piano roll (sub-tab isArmed, cuc bo) cung tinh nhu ARM track: - // preview note tu piano roll tab phai toi track dang edit du track main - // KHONG ARM (ARM piano roll khong truyen vao MAIN/SECTION). + // V45.19 Bug 2: ARM piano roll chi tac dung khi DANG o PIANO_ROLL tab. O + // MAIN/SECTION chi tinh track isArmed that su; ARM tu piano roll KHONG truyen + // sang. Khong track nao ARM o MAIN/SECTION -> targets rong -> preview cam. + const _prTabNow = (subTabsRef.current || []).find(function (s) { return s.id === activeTabRef.current; }); + const _isPrTabNow = !!(_prTabNow && _prTabNow.type === 'PIANO_ROLL'); const prArmedIds = {}; try { - (subTabsRef.current || []).forEach(function (s) { - if (s.type === 'PIANO_ROLL' && s.isArmed && s.trackId) prArmedIds[s.trackId] = true; - }); + if (_isPrTabNow) { + (subTabsRef.current || []).forEach(function (s) { + if (s.type === 'PIANO_ROLL' && s.isArmed && s.trackId) prArmedIds[s.trackId] = true; + }); + } } catch (e) {} const armed = allTracks.filter(function (t) { return t.isArmed || prArmedIds[t.id]; }); - const targets = armed.length ? armed : allTracks; + const targets = armed.length ? armed : (_isPrTabNow ? allTracks : []); if (!armed.length && !window.__vkbNoArmToast) { window.__vkbNoArmToast = true; - showToast('Không có track nào ARM — chơi vào tất cả track.', 'info'); + showToast(_isPrTabNow ? 'Không có track nào ARM — chơi vào tất cả track.' : 'Không có track nào ARM — preview MIDI câm (MAIN/SECTION).', 'info'); } // DIAG Bug 3/4 (preview khong am): trang thai routing tai note-on. try { @@ -23887,7 +23902,7 @@ const App = () => { const _pdD = window.BridgeAudioNode ? window.BridgeAudioNode.getDiag() : null; const _pdTab = activeTabRef.current; const _pdSub = subTabsRef.current ? (subTabsRef.current.find(s => s.id === _pdTab) || {}).type : null; - _dbgLog('preview_diag', 'armed=' + armed.length + ' tab=' + _pdTab + ' sub=' + (_pdSub || 'none') + ' play=' + (isPlayingRef.current ? 1 : 0) + ' br=' + (window.SonicMidiRouter && window.SonicMidiRouter.isBridgeActive() ? 1 : 0) + ' fxRt=' + (fxRt.active ? 1 : 0) + ' dest=' + _pdDest + ' bd=' + (_pdD ? ('i=' + _pdD.initialized + ' wl=' + _pdD.useWorklet + ' nd=' + _pdD.hasWorkletNode + ' pre=' + _pdD.preBufferLen + ' ch=' + _pdD.chunksLen + ' g=' + _pdD.gain) : 'MISSING') + ' mb=' + (!!masterBus)); + _dbgLog('preview_diag', 'armed=' + armed.length + ' trg=' + targets.length + ' prTab=' + (_isPrTabNow ? 1 : 0) + ' tab=' + _pdTab + ' sub=' + (_pdSub || 'none') + ' play=' + (isPlayingRef.current ? 1 : 0) + ' br=' + (window.SonicMidiRouter && window.SonicMidiRouter.isBridgeActive() ? 1 : 0) + ' fxRt=' + (fxRt.active ? 1 : 0) + ' dest=' + _pdDest + ' bd=' + (_pdD ? ('i=' + _pdD.initialized + ' wl=' + _pdD.useWorklet + ' nd=' + _pdD.hasWorkletNode + ' pre=' + _pdD.preBufferLen + ' ch=' + _pdD.chunksLen + ' g=' + _pdD.gain) : 'MISSING') + ' mb=' + (!!masterBus)); } catch (e) {} // DIAG Bug 3/4: arm bo dem audio frames (500ms sau note-on) de biet // engine co gui audio ve JS khong (tach engine vs JS routing). @@ -25589,7 +25604,16 @@ const App = () => { // V40: real PDC — freeze playhead theo latency FX path; allowCold=true che // cold-start VST pre-roll (playhead không chạy trước khi có tiếng). Bỏ V39 // freeze giả định 0.31s (under-estimate → playhead chạy trước ~0.66s). - try { if (window.__fxRtPlayheadFreeze) window.__fxRtPlayheadFreeze(true); } catch (e) { } + // V45.19 Bug 1b: loop WRAP khong re-buffer (audio lien tuc qua KEEP tail) — chi + // re-anchor processed (playhead theo anchor), KHONG seek-freeze 1500ms (truoc day + // freeze -> playhead dung ~1.5s sau wrap = 'delay kha lau'). Seek/play that freeze. + try { + if (_wrapRestart && fxRt && fxRt.active) { + fxRtAnchorProcessed(); + } else if (window.__fxRtPlayheadFreeze) { + window.__fxRtPlayheadFreeze(true); + } + } catch (e) { } // D2: bridge active -> báo transport PLAY (bridge flush note-off cũ + đồng // bộ timeline; A13 C++ xử lý arg1=playheadSamples sau này). if (window.NativeBridgeService && window.NativeBridgeService.isBridgeConnected) { diff --git a/app/static/js/app.precompiled.js b/app/static/js/app.precompiled.js index 581dd63..f3ae8f8 100644 --- a/app/static/js/app.precompiled.js +++ b/app/static/js/app.precompiled.js @@ -340,7 +340,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=202608311222`);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=202608311242`);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 @@ -382,7 +382,9 @@ const _now=performance.now();// V40: self-calib PDC — fx_play_first = block đ // worklet phát lại OLD TAIL ~5ms → dbgPlayFirst tiêu thụ → trước đây snap // playhead SỚM + calib nhiễu ~50ms → display chạy trước → wrap sớm → vấp // beat 0:0. Pass mới thật ≥ ~80ms → snap/calib chỉ trên event hợp lệ. -if(d.tag==='fx_play_first'&&_now-_dbgPlayStartMs>=50){fxRt.pdcCalibMs=Math.max(50,Math.min(3000,_now-_dbgPlayStartMs));try{if(window.__fxRtSnapPlayhead)window.__fxRtSnapPlayhead();}catch(e2){}}_dbgLog('fx_hop_'+d.tag,'sincePlay='+Math.round(_now-_dbgPlayStartMs)+' sinceClear='+Math.round(_now-_dbgLastClearMs)+' wlT='+d.t+' q='+(d.q!==undefined?d.q:''));return;}if(d.type!=='in')return;// Gửi NGAY, không pace setTimeout: input pacing = đồng hồ audio worklet +// V45.19 Bug 1b: fx_seek_first (seek resume nhanh ~43ms < 50ms) snap KHONG +// can guard 50ms; fx_play_first giu guard (chan old-tail loop wrap snap som). +const _seekFirst=d.tag==='fx_seek_first';if((d.tag==='fx_play_first'||_seekFirst)&&(_seekFirst||_now-_dbgPlayStartMs>=50)){fxRt.pdcCalibMs=Math.max(50,Math.min(3000,_now-_dbgPlayStartMs));try{if(window.__fxRtSnapPlayhead)window.__fxRtSnapPlayhead();}catch(e2){}}_dbgLog('fx_hop_'+d.tag,'sincePlay='+Math.round(_now-_dbgPlayStartMs)+' sinceClear='+Math.round(_now-_dbgLastClearMs)+' wlT='+d.t+' q='+(d.q!==undefined?d.q:''));return;}if(d.type!=='in')return;// Gửi NGAY, không pace setTimeout: input pacing = đồng hồ audio worklet // (1 frame/21.33ms), không phải timer main-thread. Timer bận/trễ → input // gửi trễ → engine/bridge chỉ sản xuất output khi có input → cushion cạn // dần → crackle sau 3-4s (đã xác nhận với chain RỖNG). Burst sau stall: @@ -890,14 +892,17 @@ ccDragRef.current={mode:'cc11',active:true,anchorIdx,gs:g.minS,ge:g.maxE,span:g. const commitCC11Drag=()=>{const drag=ccDragRef.current;if(!drag)return;if(drag.mode==='cc11'&&drag.previewCurve){commitCC11Curve(drag.previewCurve);}ccDragRef.current=null;};const handleCCMouseDown=e=>{if(ccMode==='cc11'){handleCC11MouseDown(e);return;}const canvas=ccCanvasRef.current;if(!canvas)return;const rect=canvas.getBoundingClientRect();const x=e.clientX-rect.left;const y=e.clientY-rect.top;const h=rect.height;const beat=x/pixelsPerBeat-renderBeatOffset;const noteIdx=findCCNoteIndex(beat,y,h);const val=Math.max(0,Math.min(1,(h-y)/h));if(e.ctrlKey){if(selectedNoteIds.length>0){const cursorNoteIdx=findCCNoteIndex(beat,y,h);if(cursorNoteIdx!==-1&&selectedNoteIds.includes(notes[cursorNoteIdx]?notes[cursorNoteIdx].id:-1)){const currentNote=notes[cursorNoteIdx];const currentVal=ccMode==='pan'?(currentNote.pan||0)/2.0+0.5:currentNote.velocity!==undefined?currentNote.velocity:0.8;if(Math.abs(currentVal-val)>0.001){const updatedNotes=notes.map((n,i)=>{if(i!==cursorNoteIdx)return n;if(ccMode==='pan')return{...n,pan:(val-0.5)*2.0};return{...n,velocity:val};});setNotes(updatedNotes);if(isPlaying&&onRescheduleMidi)onRescheduleMidi(updatedNotes);}ccDragRef.current={active:true,lastBeat:beat,selectedMode:true,lastPainted:[cursorNoteIdx]};}else{ccDragRef.current={active:true,lastBeat:beat,selectedMode:true,lastPainted:[]};}}else{// Không chọn notes: vẽ TẤT CẢ notes cùng beat (chord — user 08:25) const idxs=findCCNoteIndicesAtBeat(beat);ccDragRef.current={active:true,lastBeat:beat,lastPainted:idxs};}return;}if(noteIdx!==-1){const currentVal=ccMode==='pan'?(notes[noteIdx].pan||0)/2.0+0.5:notes[noteIdx].velocity!==undefined?notes[noteIdx].velocity:0.8;if(Math.abs(currentVal-val)>0.001){const updatedNotes=notes.map((n,i)=>{if(i!==noteIdx)return n;if(ccMode==='pan')return{...n,pan:(val-0.5)*2.0};return{...n,velocity:val};});setNotes(updatedNotes);if(isPlaying&&onRescheduleMidi)onRescheduleMidi(updatedNotes);}}};const handleCCMouseMove=e=>{if(!ccDragRef.current||!ccDragRef.current.active)return;if(ccDragRef.current.mode==='cc11'){const drag=ccDragRef.current;const canvas=ccCanvasRef.current;if(!canvas)return;const rect=canvas.getBoundingClientRect();const x=e.clientX-rect.left;const y=e.clientY-rect.top;const h=rect.height;const beat=x/pixelsPerBeat-renderBeatOffset;const ratio=Math.max(0,Math.min(1,(beat-drag.gs)/drag.span));const val=Math.max(0,Math.min(127,Math.round((h-y)/h*127)));const curve=(drag.previewCurve||[]).slice();const idx=Math.min(drag.anchorIdx,curve.length-1);const cur=curve[idx]||{position_ratio:ratio,value:val};// Drag node: doi ca ratio+value, clamp giua 2 node lan can let minR=0,maxR=1;for(let i=0;iminR)minR=r;if(r>cur.position_ratio&&r0){const cursorNoteIdx=findCCNoteIndex(beat,y,h);if(cursorNoteIdx!==-1){const cursorNote=notes[cursorNoteIdx];if(cursorNote&&selectedNoteIds.includes(cursorNote.id)&&!painted.includes(cursorNoteIdx)){const currentVal=ccMode==='pan'?(cursorNote.pan||0)/2.0+0.5:cursorNote.velocity!==undefined?cursorNote.velocity:0.8;if(Math.abs(currentVal-val)>0.001){const updatedNotes=notes.map((n,i)=>{if(i!==cursorNoteIdx)return n;if(ccMode==='pan')return{...n,pan:(val-0.5)*2.0};return{...n,velocity:val};});setNotes(updatedNotes);if(isPlaying&&onRescheduleMidi)onRescheduleMidi(updatedNotes);}drag.lastPainted=[...painted,cursorNoteIdx];}}return;}// Vẽ TẤT CẢ notes cùng beat (chord — user 08:25) — trước đây chỉ 1 note -const candidateIdxs=findCCNoteIndicesAtBeat(beat);const unpainted=candidateIdxs.filter(ci=>!painted.includes(ci));if(unpainted.length>0){const updatedNotes=notes.map((n,i)=>{if(!unpainted.includes(i))return n;if(ccMode==='pan')return{...n,pan:(val-0.5)*2.0};return{...n,velocity:val};});setNotes(updatedNotes);if(isPlaying&&onRescheduleMidi)onRescheduleMidi(updatedNotes);drag.lastPainted=[...painted,...unpainted];}};const renderKeybed=()=>{var kbTrk=activeTracks.find(function(t){return t.id===st.trackId;});var kbCtx=resolveTrackInstrumentCtx(kbTrk,activeTracks);ensureSonicInstrument(kbCtx);const keys=[];for(let pitch=127;pitch>=PITCH_START;pitch--){const isBlack=[1,3,6,8,10].includes(pitch%12);const notesArray=['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'];const octave=Math.floor(pitch/12)-1;const label=`${notesArray[pitch%12]}${octave}`;const showLabel=pitch%12===0;keys.push(/*#__PURE__*/React.createElement("div",{key:pitch,style:{height:`${NoteHeight}px`},className:`w-[60px] shrink-0 border-b border-zinc-800 text-[9px] font-bold flex items-center justify-end pr-2 transition cursor-pointer ${activeMidiPitches&&activeMidiPitches.has(pitch)?'bg-emerald-500 text-white border-emerald-400':isBlack?'bg-zinc-950 text-slate-500 border-zinc-900 hover:bg-zinc-800':'bg-white text-zinc-800 border-r border-zinc-400 hover:bg-amber-100'}`,onMouseDown:e=>{e.stopPropagation();keybedMouseDownRef.current=true;try{// Đồng bộ mastering + routing SF NGAY trước khi preview — âm +const candidateIdxs=findCCNoteIndicesAtBeat(beat);const unpainted=candidateIdxs.filter(ci=>!painted.includes(ci));if(unpainted.length>0){const updatedNotes=notes.map((n,i)=>{if(!unpainted.includes(i))return n;if(ccMode==='pan')return{...n,pan:(val-0.5)*2.0};return{...n,velocity:val};});setNotes(updatedNotes);if(isPlaying&&onRescheduleMidi)onRescheduleMidi(updatedNotes);drag.lastPainted=[...painted,...unpainted];}};const renderKeybed=()=>{var kbTrk=activeTracks.find(function(t){return t.id===st.trackId;});var kbCtx=resolveTrackInstrumentCtx(kbTrk,activeTracks);ensureSonicInstrument(kbCtx);// V45.19 Bug 2: keybed chi phat khi DANG o PIANO_ROLL tab hoac track isArmed +// (MAIN/SECTION + ARM off -> cam). NOTE_OFF van gui (vo hai). +const _kbPrTab=(subTabsRef.current||[]).find(function(s){return s.id===activeTabRef.current;});const _kbIsPrTab=!!(_kbPrTab&&_kbPrTab.type==='PIANO_ROLL');const _kbSilent=!_kbIsPrTab&&!(kbTrk&&kbTrk.isArmed);const keys=[];for(let pitch=127;pitch>=PITCH_START;pitch--){const isBlack=[1,3,6,8,10].includes(pitch%12);const notesArray=['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'];const octave=Math.floor(pitch/12)-1;const label=`${notesArray[pitch%12]}${octave}`;const showLabel=pitch%12===0;keys.push(/*#__PURE__*/React.createElement("div",{key:pitch,style:{height:`${NoteHeight}px`},className:`w-[60px] shrink-0 border-b border-zinc-800 text-[9px] font-bold flex items-center justify-end pr-2 transition cursor-pointer ${activeMidiPitches&&activeMidiPitches.has(pitch)?'bg-emerald-500 text-white border-emerald-400':isBlack?'bg-zinc-950 text-slate-500 border-zinc-900 hover:bg-zinc-800':'bg-white text-zinc-800 border-r border-zinc-400 hover:bg-amber-100'}`,onMouseDown:e=>{e.stopPropagation();keybedMouseDownRef.current=true;try{// Đồng bộ mastering + routing SF NGAY trước khi preview — âm // keybed PHẢI qua mastering FX của main out khi chain đang bật // (trước đây phải bật/tắt power mới có tác dụng). try{if(window.__ensureMasteringRouting)window.__ensureMasteringRouting();}catch(er){}// DIAG Bug 2 (keybed ARM khong am): routing + ARM state tai note-on. -try{let _pdDest='none';if(window.AudioRoutingEngine&&window.AudioRoutingEngine._connected){_pdDest=window.AudioRoutingEngine._dest&&window.AudioRoutingEngine._dest.constructor?window.AudioRoutingEngine._dest.constructor.name:'null';_pdDest+='/'+window.AudioRoutingEngine._trackId;}else{_pdDest='NOT_CONNECTED';}const _pdD=window.BridgeAudioNode?window.BridgeAudioNode.getDiag():null;const _pdTab=activeTabRef.current;const _pdSub=subTabsRef.current?(subTabsRef.current.find(s=>s.id===_pdTab)||{}).type:null;const _kbArmedTab=!!(subTabsRef.current||[]).some(function(s){return s.type==='PIANO_ROLL'&&s.isArmed&&s.trackId===st.trackId;});_dbgLog('preview_diag','src=keybed trk='+st.trackId+' kbTrk='+(kbTrk?kbTrk.id:'UNDEF')+' kbArmedTab='+(_kbArmedTab?1:0)+' armedTrk='+(kbTrk&&kbTrk.isArmed?1:0)+' tab='+_pdTab+' sub='+(_pdSub||'none')+' play='+(isPlayingRef.current?1:0)+' br='+(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive()?1:0)+' fxRt='+(fxRt.active?1:0)+' dest='+_pdDest+' bd='+(_pdD?'i='+_pdD.initialized+' wl='+_pdD.useWorklet+' nd='+_pdD.hasWorkletNode+' pre='+_pdD.preBufferLen+' ch='+_pdD.chunksLen+' g='+_pdD.gain:'MISSING')+' mb='+!!masterBus);}catch(e){}try{window.__dbgPreviewAudioArmed={count:0,nz:0,t0:performance.now()};}catch(e){}if(window.triggerMidiVuActivity){window.triggerMidiVuActivity((st.parent_tab_id&&st.parent_tab_id.startsWith('session_')?'_sess_':'')+st.trackId,100);}const kbNative=isStandaloneSf()&&isSfTrackEngine(kbCtx.synthEngine)&&!(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive());const kbNativeVst=isStandaloneSf()&&isVstTrackEngine(kbCtx.synthEngine)&&!(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive());if(kbNative){playNativeSfNote(kbTrk,pitch,100/127,5000,undefined,'kb_'+st.trackId+'_'+pitch);}else if(kbNativeVst){playNativeVstNote(kbTrk,pitch,100/127,5000,undefined,'kb_'+st.trackId+'_'+pitch);}if(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive()){try{if(window.__ensureBridgeProgram)window.__ensureBridgeProgram(kbTrk?kbTrk.id:0,kbCtx.program,kbCtx.synthEngine);}catch(er){}window.SonicMidiRouter.pushEvent({cmd:'NOTE_ON',channel:kbTrk?kbTrk.id:0,pitch:pitch,velocity:100/127,percussion:!!(kbCtx&&kbCtx.synthEngine&&kbCtx.synthEngine.soundfont_bank===128),live:true});}else if(window.SonicSF&&!kbNative&&!kbNativeVst){// ⚠️ FIX: giữ note theo thời gian bấm phím — durationMs lớn (5s) +try{let _pdDest='none';if(window.AudioRoutingEngine&&window.AudioRoutingEngine._connected){_pdDest=window.AudioRoutingEngine._dest&&window.AudioRoutingEngine._dest.constructor?window.AudioRoutingEngine._dest.constructor.name:'null';_pdDest+='/'+window.AudioRoutingEngine._trackId;}else{_pdDest='NOT_CONNECTED';}const _pdD=window.BridgeAudioNode?window.BridgeAudioNode.getDiag():null;const _pdTab=activeTabRef.current;const _pdSub=subTabsRef.current?(subTabsRef.current.find(s=>s.id===_pdTab)||{}).type:null;const _kbArmedTab=!!(subTabsRef.current||[]).some(function(s){return s.type==='PIANO_ROLL'&&s.isArmed&&s.trackId===st.trackId;});_dbgLog('preview_diag','src=keybed trk='+st.trackId+' kbTrk='+(kbTrk?kbTrk.id:'UNDEF')+' kbArmedTab='+(_kbArmedTab?1:0)+' armedTrk='+(kbTrk&&kbTrk.isArmed?1:0)+' sl='+(_kbSilent?1:0)+' tab='+_pdTab+' sub='+(_pdSub||'none')+' play='+(isPlayingRef.current?1:0)+' br='+(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive()?1:0)+' fxRt='+(fxRt.active?1:0)+' dest='+_pdDest+' bd='+(_pdD?'i='+_pdD.initialized+' wl='+_pdD.useWorklet+' nd='+_pdD.hasWorkletNode+' pre='+_pdD.preBufferLen+' ch='+_pdD.chunksLen+' g='+_pdD.gain:'MISSING')+' mb='+!!masterBus);}catch(e){}// V45.19 Bug 2: _kbSilent -> bo qua phat (MAIN/SECTION + ARM off = cam). +if(!_kbSilent){try{window.__dbgPreviewAudioArmed={count:0,nz:0,t0:performance.now()};}catch(e){}if(window.triggerMidiVuActivity){window.triggerMidiVuActivity((st.parent_tab_id&&st.parent_tab_id.startsWith('session_')?'_sess_':'')+st.trackId,100);}const kbNative=isStandaloneSf()&&isSfTrackEngine(kbCtx.synthEngine)&&!(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive());const kbNativeVst=isStandaloneSf()&&isVstTrackEngine(kbCtx.synthEngine)&&!(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive());if(kbNative){playNativeSfNote(kbTrk,pitch,100/127,5000,undefined,'kb_'+st.trackId+'_'+pitch);}else if(kbNativeVst){playNativeVstNote(kbTrk,pitch,100/127,5000,undefined,'kb_'+st.trackId+'_'+pitch);}if(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive()){try{if(window.__ensureBridgeProgram)window.__ensureBridgeProgram(kbTrk?kbTrk.id:0,kbCtx.program,kbCtx.synthEngine);}catch(er){}window.SonicMidiRouter.pushEvent({cmd:'NOTE_ON',channel:kbTrk?kbTrk.id:0,pitch:pitch,velocity:100/127,percussion:!!(kbCtx&&kbCtx.synthEngine&&kbCtx.synthEngine.soundfont_bank===128),live:true});}else if(window.SonicSF&&!kbNative&&!kbNativeVst){// ⚠️ FIX: giữ note theo thời gian bấm phím — durationMs lớn (5s) // chỉ là auto-off phòng hờ; mouseup/mouseleave gọi stopNote dừng // NGAY (trước đây 500ms → note tự tắt giữa chừng khi giữ phím). -window.SonicSF.playNote(pitch,100,5000,undefined,kbCtx.program,null,kbCtx.ch,kbCtx.synthEngine);}}catch(err){console.error('playNote error:',err);}},onMouseEnter:e=>{if(keybedMouseDownRef.current){try{if(window.triggerMidiVuActivity){window.triggerMidiVuActivity((st.parent_tab_id&&st.parent_tab_id.startsWith('session_')?'_sess_':'')+st.trackId,100);}if(isStandaloneSf()&&isSfTrackEngine(kbCtx.synthEngine)&&!(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive())){playNativeSfNote(kbTrk,pitch,100/127,5000,undefined,'kb_'+st.trackId+'_'+pitch);}else if(isStandaloneSf()&&isVstTrackEngine(kbCtx.synthEngine)&&!(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive())){playNativeVstNote(kbTrk,pitch,100/127,5000,undefined,'kb_'+st.trackId+'_'+pitch);}if(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive()){try{if(window.__ensureBridgeProgram)window.__ensureBridgeProgram(kbTrk?kbTrk.id:0,kbCtx.program,kbCtx.synthEngine);}catch(er){}window.SonicMidiRouter.pushEvent({cmd:'NOTE_ON',channel:kbTrk?kbTrk.id:0,pitch:pitch,velocity:100/127,percussion:!!(kbCtx&&kbCtx.synthEngine&&kbCtx.synthEngine.soundfont_bank===128),live:true});}else if(window.SonicSF&&!(isStandaloneSf()&&(isSfTrackEngine(kbCtx.synthEngine)||isVstTrackEngine(kbCtx.synthEngine)))){// giữ note khi kéo qua phím (mouse enter) — dừng bằng mouseup/leave +window.SonicSF.playNote(pitch,100,5000,undefined,kbCtx.program,null,kbCtx.ch,kbCtx.synthEngine);}}}catch(err){console.error('playNote error:',err);}},onMouseEnter:e=>{if(keybedMouseDownRef.current&&!_kbSilent){try{if(window.triggerMidiVuActivity){window.triggerMidiVuActivity((st.parent_tab_id&&st.parent_tab_id.startsWith('session_')?'_sess_':'')+st.trackId,100);}if(isStandaloneSf()&&isSfTrackEngine(kbCtx.synthEngine)&&!(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive())){playNativeSfNote(kbTrk,pitch,100/127,5000,undefined,'kb_'+st.trackId+'_'+pitch);}else if(isStandaloneSf()&&isVstTrackEngine(kbCtx.synthEngine)&&!(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive())){playNativeVstNote(kbTrk,pitch,100/127,5000,undefined,'kb_'+st.trackId+'_'+pitch);}if(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive()){try{if(window.__ensureBridgeProgram)window.__ensureBridgeProgram(kbTrk?kbTrk.id:0,kbCtx.program,kbCtx.synthEngine);}catch(er){}window.SonicMidiRouter.pushEvent({cmd:'NOTE_ON',channel:kbTrk?kbTrk.id:0,pitch:pitch,velocity:100/127,percussion:!!(kbCtx&&kbCtx.synthEngine&&kbCtx.synthEngine.soundfont_bank===128),live:true});}else if(window.SonicSF&&!(isStandaloneSf()&&(isSfTrackEngine(kbCtx.synthEngine)||isVstTrackEngine(kbCtx.synthEngine)))){// giữ note khi kéo qua phím (mouse enter) — dừng bằng mouseup/leave window.SonicSF.playNote(pitch,100,5000,undefined,kbCtx.program,null,kbCtx.ch,kbCtx.synthEngine);}}catch(err){console.error('playNote error:',err);}}},onMouseUp:()=>{keybedMouseDownRef.current=false;// Dừng note khi thả phím — tránh kẹt âm (loop liên tục) với soundfont try{if(isStandaloneSf()){stopNativeSfNote('kb_'+st.trackId+'_'+pitch);stopNativeVstNote('kb_'+st.trackId+'_'+pitch);}if(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive()){window.SonicMidiRouter.pushEvent({cmd:'NOTE_OFF',channel:kbTrk?kbTrk.id:0,pitch:pitch,velocity:0,percussion:!!(kbCtx&&kbCtx.synthEngine&&kbCtx.synthEngine.soundfont_bank===128),live:true});}else if(window.SonicSF&&window.SonicSF.stopNote)window.SonicSF.stopNote(kbCtx.ch,pitch);}catch(e){}},onMouseLeave:()=>{if(!keybedMouseDownRef.current)return;// Kéo chuột ra khỏi phím → dừng note của phím đó try{if(isStandaloneSf()){stopNativeSfNote('kb_'+st.trackId+'_'+pitch);stopNativeVstNote('kb_'+st.trackId+'_'+pitch);}if(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive()){window.SonicMidiRouter.pushEvent({cmd:'NOTE_OFF',channel:kbTrk?kbTrk.id:0,pitch:pitch,velocity:0,percussion:!!(kbCtx&&kbCtx.synthEngine&&kbCtx.synthEngine.soundfont_bank===128),live:true});}else if(window.SonicSF&&window.SonicSF.stopNote)window.SonicSF.stopNote(kbCtx.ch,pitch);}catch(e){}}},showLabel&&label));}return keys;};const handleScroll=e=>{if(keybedRef.current){keybedRef.current.scrollTop=e.currentTarget.scrollTop;}if(rulerScrollRef.current){rulerScrollRef.current.scrollLeft=e.currentTarget.scrollLeft;}if(ccWrapperRef.current){ccWrapperRef.current.scrollLeft=e.currentTarget.scrollLeft;}const el=e.currentTarget;const THRESHOLD=200;if(el.scrollLeft+el.clientWidth>=el.scrollWidth-THRESHOLD){const newBeats=rollBeatsRef.current+16;setRollBeats(newBeats);}};const handleKeybedScroll=e=>{if(gridScrollRef.current){gridScrollRef.current.scrollTop=e.currentTarget.scrollTop;}};const SCALES={"None":null,"Diatonic":{"Major":[0,2,4,5,7,9,11],"Minor":[0,2,3,5,7,8,10],"Dorian":[0,2,3,5,7,9,10],"Phrygian":[0,1,3,5,7,8,10],"Lydian":[0,2,4,6,7,9,11],"Mixolydian":[0,2,4,5,7,9,10],"Locrian":[0,1,3,5,6,8,10]},"Pentatonic":{"Major":[0,2,4,7,9],"Minor":[0,3,5,7,10],"Blues":[0,3,5,6,7,10],"Chinese":[0,2,4,7,9],"Vietnam":[0,2,6,7,10],"India":[0,2,5,7,9],"Japan":[0,2,5,7,9],"Africa":[0,3,5,7,10]},"Church":{"Dorian":[0,2,3,5,7,9,10],"Phrygian":[0,1,3,5,7,8,10],"Lydian":[0,2,4,6,7,9,11],"Mixolydian":[0,2,4,5,7,9,10]},"Jazz":{"Blues":[0,3,5,6,7,10],"Bebop":[0,2,4,5,7,9,10,11],"Diminished":[0,2,3,5,6,8,9,11]},"Asian Traditional":{"Chinese":[0,2,4,7,9],"Vietnam":[0,2,6,7,10],"Japan":[0,2,5,7,9],"India":[0,2,5,7,9],"Gamelan":[0,2,4,7,9],"Korea":[0,2,4,5,7,9]},"Middle Eastern":{"Hijaz":[0,1,4,5,7,8,11],"Nikriz":[0,1,4,5,7,8,10],"Rast":[0,2,4,5,7,8,10],"Saba":[0,1,3,4,7,8,10],"Bayati":[0,2,3,4,7,8,10]}};const[selectedScale,setSelectedScale]=React.useState(null);const selectedScaleRef=React.useRef(null);selectedScaleRef.current=selectedScale;// Root note (0-11 — C..B) — transpose scale highlight + snap (spec 20:12) @@ -1774,11 +1779,11 @@ const showToast=(text,type='info',actionText=null,onActionClick=null)=>{if(toast // NOTE_ON/NOTE_OFF theo pattern attachMidiHandler (hardware MIDI): bridge → // per-track channel alloc; native SF/VST; SonicSF fallback; VU + giữ // counter (heldMidiNotesRef); forward recorder (live record vào midiItems). -const vkbNoteOn=(pitch,vel)=>{try{if(window.__ensureMasteringRouting)window.__ensureMasteringRouting();}catch(er){}const allTracks=activeTracksRef.current||[];// ARM piano roll (sub-tab isArmed, cuc bo) cung tinh nhu ARM track: -// preview note tu piano roll tab phai toi track dang edit du track main -// KHONG ARM (ARM piano roll khong truyen vao MAIN/SECTION). -const prArmedIds={};try{(subTabsRef.current||[]).forEach(function(s){if(s.type==='PIANO_ROLL'&&s.isArmed&&s.trackId)prArmedIds[s.trackId]=true;});}catch(e){}const armed=allTracks.filter(function(t){return t.isArmed||prArmedIds[t.id];});const targets=armed.length?armed:allTracks;if(!armed.length&&!window.__vkbNoArmToast){window.__vkbNoArmToast=true;showToast('Không có track nào ARM — chơi vào tất cả track.','info');}// DIAG Bug 3/4 (preview khong am): trang thai routing tai note-on. -try{let _pdDest='none';if(window.AudioRoutingEngine&&window.AudioRoutingEngine._connected){_pdDest=window.AudioRoutingEngine._dest&&window.AudioRoutingEngine._dest.constructor?window.AudioRoutingEngine._dest.constructor.name:'null';_pdDest+='/'+window.AudioRoutingEngine._trackId;}else{_pdDest='NOT_CONNECTED';}const _pdD=window.BridgeAudioNode?window.BridgeAudioNode.getDiag():null;const _pdTab=activeTabRef.current;const _pdSub=subTabsRef.current?(subTabsRef.current.find(s=>s.id===_pdTab)||{}).type:null;_dbgLog('preview_diag','armed='+armed.length+' tab='+_pdTab+' sub='+(_pdSub||'none')+' play='+(isPlayingRef.current?1:0)+' br='+(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive()?1:0)+' fxRt='+(fxRt.active?1:0)+' dest='+_pdDest+' bd='+(_pdD?'i='+_pdD.initialized+' wl='+_pdD.useWorklet+' nd='+_pdD.hasWorkletNode+' pre='+_pdD.preBufferLen+' ch='+_pdD.chunksLen+' g='+_pdD.gain:'MISSING')+' mb='+!!masterBus);}catch(e){}// DIAG Bug 3/4: arm bo dem audio frames (500ms sau note-on) de biet +const vkbNoteOn=(pitch,vel)=>{try{if(window.__ensureMasteringRouting)window.__ensureMasteringRouting();}catch(er){}const allTracks=activeTracksRef.current||[];// V45.19 Bug 2: ARM piano roll chi tac dung khi DANG o PIANO_ROLL tab. O +// MAIN/SECTION chi tinh track isArmed that su; ARM tu piano roll KHONG truyen +// sang. Khong track nao ARM o MAIN/SECTION -> targets rong -> preview cam. +const _prTabNow=(subTabsRef.current||[]).find(function(s){return s.id===activeTabRef.current;});const _isPrTabNow=!!(_prTabNow&&_prTabNow.type==='PIANO_ROLL');const prArmedIds={};try{if(_isPrTabNow){(subTabsRef.current||[]).forEach(function(s){if(s.type==='PIANO_ROLL'&&s.isArmed&&s.trackId)prArmedIds[s.trackId]=true;});}}catch(e){}const armed=allTracks.filter(function(t){return t.isArmed||prArmedIds[t.id];});const targets=armed.length?armed:_isPrTabNow?allTracks:[];if(!armed.length&&!window.__vkbNoArmToast){window.__vkbNoArmToast=true;showToast(_isPrTabNow?'Không có track nào ARM — chơi vào tất cả track.':'Không có track nào ARM — preview MIDI câm (MAIN/SECTION).','info');}// DIAG Bug 3/4 (preview khong am): trang thai routing tai note-on. +try{let _pdDest='none';if(window.AudioRoutingEngine&&window.AudioRoutingEngine._connected){_pdDest=window.AudioRoutingEngine._dest&&window.AudioRoutingEngine._dest.constructor?window.AudioRoutingEngine._dest.constructor.name:'null';_pdDest+='/'+window.AudioRoutingEngine._trackId;}else{_pdDest='NOT_CONNECTED';}const _pdD=window.BridgeAudioNode?window.BridgeAudioNode.getDiag():null;const _pdTab=activeTabRef.current;const _pdSub=subTabsRef.current?(subTabsRef.current.find(s=>s.id===_pdTab)||{}).type:null;_dbgLog('preview_diag','armed='+armed.length+' trg='+targets.length+' prTab='+(_isPrTabNow?1:0)+' tab='+_pdTab+' sub='+(_pdSub||'none')+' play='+(isPlayingRef.current?1:0)+' br='+(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive()?1:0)+' fxRt='+(fxRt.active?1:0)+' dest='+_pdDest+' bd='+(_pdD?'i='+_pdD.initialized+' wl='+_pdD.useWorklet+' nd='+_pdD.hasWorkletNode+' pre='+_pdD.preBufferLen+' ch='+_pdD.chunksLen+' g='+_pdD.gain:'MISSING')+' mb='+!!masterBus);}catch(e){}// DIAG Bug 3/4: arm bo dem audio frames (500ms sau note-on) de biet // engine co gui audio ve JS khong (tach engine vs JS routing). try{window.__dbgPreviewAudioArmed={count:0,nz:0,t0:performance.now()};}catch(e){}activeMidiPitchesRef.current.add(pitch);setActiveMidiPitches(new Set(activeMidiPitchesRef.current));vkbHeldRef.current.add(pitch);targets.forEach(function(t){const ctx=resolveTrackInstrumentCtx(t,allTracks);ensureSonicInstrument(ctx);if(window.triggerMidiVuActivity)window.triggerMidiVuActivity(t.id,Math.round(vel*127));try{heldMidiNotesRef.current[t.id]=(heldMidiNotesRef.current[t.id]||0)+1;}catch(err){}const percussion=!!(ctx&&ctx.synthEngine&&ctx.synthEngine.soundfont_bank===128);if(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive()){try{if(window.__ensureBridgeProgram)window.__ensureBridgeProgram(t.id,ctx.program,ctx.synthEngine);}catch(er){}try{window.SonicMidiRouter.pushEvent({cmd:'NOTE_ON',channel:t.id,pitch:pitch,velocity:vel,percussion:percussion,live:true});}catch(e){}}else if(isStandaloneSf()&&(isSfTrackEngine(ctx.synthEngine)||isVstTrackEngine(ctx.synthEngine))){if(isSfTrackEngine(ctx.synthEngine))playNativeSfNote(t,pitch,vel,60000,undefined,'vkb_'+t.id+'_'+pitch);else playNativeVstNote(t,pitch,vel,60000,undefined,'vkb_'+t.id+'_'+pitch);}else if(window.SonicSF){const dest=activeTrackNodesRef.current[t.id]&&activeTrackNodesRef.current[t.id].gainNode||null;window.SonicSF.playNote(pitch,Math.max(1,Math.round(vel*127)),60000,undefined,ctx.program,dest,ctx.ch,ctx.synthEngine);}});// Live record: forward tới mọi recorder đang chạy (timeline take / piano roll) if(activeMIDIRecordersRef.current){const msg={data:[0x90,pitch,Math.max(1,Math.round(vel*127))]};for(const trackId in activeMIDIRecordersRef.current){const rec=activeMIDIRecordersRef.current[trackId];if(rec){try{rec.handleMIDIMessage(msg,null);}catch(e){}}}}};const vkbNoteOff=pitch=>{vkbHeldRef.current.delete(pitch);activeMidiPitchesRef.current.delete(pitch);setActiveMidiPitches(new Set(activeMidiPitchesRef.current));const allTracks=activeTracksRef.current||[];allTracks.forEach(function(t){const ctx=resolveTrackInstrumentCtx(t,allTracks);const percussion=!!(ctx&&ctx.synthEngine&&ctx.synthEngine.soundfont_bank===128);if(window.SonicMidiRouter&&window.SonicMidiRouter.isBridgeActive()){try{window.SonicMidiRouter.pushEvent({cmd:'NOTE_OFF',channel:t.id,pitch:pitch,velocity:0,percussion:percussion,live:true});}catch(e){}}else if(window.SonicSF&&window.SonicSF.stopNote){if(isStandaloneSf()){stopNativeSfNote('vkb_'+t.id+'_'+pitch);stopNativeVstNote('vkb_'+t.id+'_'+pitch);}window.SonicSF.stopNote(ctx.ch,pitch);}try{if(heldMidiNotesRef.current[t.id]!==undefined){heldMidiNotesRef.current[t.id]=Math.max(0,heldMidiNotesRef.current[t.id]-1);if(heldMidiNotesRef.current[t.id]===0)delete heldMidiNotesRef.current[t.id];}}catch(err){}});if(activeMIDIRecordersRef.current){const msg={data:[0x80,pitch,0]};for(const trackId in activeMIDIRecordersRef.current){const rec=activeMIDIRecordersRef.current[trackId];if(rec){try{rec.handleMIDIMessage(msg,null);}catch(e){}}}}};vkbNoteOnRef.current=vkbNoteOn;vkbNoteOffRef.current=vkbNoteOff;window.__toggleVkb=function(){setVkbOpen(function(p){const next=!p;if(!next&&vkbHeldRef.current.size){Array.from(vkbHeldRef.current).forEach(function(pitch){try{vkbNoteOffRef.current(pitch);}catch(e){}});}return next;});};window.__toggleChordsPanel=function(){setChordsPanelOpen(function(p){return!p;});};// ── Server-side upload ── @@ -1963,7 +1968,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=202608311222`);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=202608311242`);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 @@ -2108,7 +2113,10 @@ try{if(fxRt&&fxRt.node&&fxRt.node.port)fxRt.node.port.postMessage({type:'clear_q try{fxRtStart();}catch(e){console.warn('[FX RT] start error:',e);}// V40: real PDC — freeze playhead theo latency FX path; allowCold=true che // cold-start VST pre-roll (playhead không chạy trước khi có tiếng). Bỏ V39 // freeze giả định 0.31s (under-estimate → playhead chạy trước ~0.66s). -try{if(window.__fxRtPlayheadFreeze)window.__fxRtPlayheadFreeze(true);}catch(e){}// D2: bridge active -> báo transport PLAY (bridge flush note-off cũ + đồng +// V45.19 Bug 1b: loop WRAP khong re-buffer (audio lien tuc qua KEEP tail) — chi +// re-anchor processed (playhead theo anchor), KHONG seek-freeze 1500ms (truoc day +// freeze -> playhead dung ~1.5s sau wrap = 'delay kha lau'). Seek/play that freeze. +try{if(_wrapRestart&&fxRt&&fxRt.active){fxRtAnchorProcessed();}else if(window.__fxRtPlayheadFreeze){window.__fxRtPlayheadFreeze(true);}}catch(e){}// D2: bridge active -> báo transport PLAY (bridge flush note-off cũ + đồng // bộ timeline; A13 C++ xử lý arg1=playheadSamples sau này). if(window.NativeBridgeService&&window.NativeBridgeService.isBridgeConnected){// V10: loop restart — stopAllPlayback vừa schedule STOP#2 (150ms); hủy // ngay khi PLAY, nếu không STOP#2 đến sau PLAY → bridge drop mọi note-on diff --git a/app/static/js/sf-fx-realtime.js b/app/static/js/sf-fx-realtime.js index 17a1899..325dbe2 100644 --- a/app/static/js/sf-fx-realtime.js +++ b/app/static/js/sf-fx-realtime.js @@ -90,6 +90,7 @@ class SfFxRealtimeProcessor extends AudioWorkletProcessor { return; } if (d && d.type === 'clear_queue') { + this.clearMode = d.mode; // V45.19: nho mode de tag fx_seek_first tai dbgPlayFirst // V34: backlog guard o DAU handler (V33 dat sau mutation -> outQueue.length=0 // chay truoc -> guard luon return, clear van drop queue + fade + re-buffer moi // lan = V31). Queue nho (< FILL 8 block) -> bo qua hoan toan (khong mutation, @@ -354,7 +355,9 @@ class SfFxRealtimeProcessor extends AudioWorkletProcessor { this.wrapMode = false; // V45.3: resume xong — ve che do thuong (underrun sau nay flush nhu cu) if (this.dbgPlayFirst) { this.dbgPlayFirst = false; - this.port.postMessage({ type: 'dbg', tag: 'fx_play_first', t: Math.round(currentTime * 1000), q: this.outQueue.length }); + // V45.19 Bug 1b: seek -> tag fx_seek_first (main thread snap khong can + // guard 50ms — seek resume nhanh ~43ms < 50ms). Wrap/play -> fx_play_first. + this.port.postMessage({ type: 'dbg', tag: (this.clearMode === 'seek' ? 'fx_seek_first' : 'fx_play_first'), t: Math.round(currentTime * 1000), q: this.outQueue.length, m: this.clearMode || '' }); } if (this.resumeFadeIn) { this.resumeFadeIn = false; diff --git a/app/templates/index.html b/app/templates/index.html index 57d217f..79ef358 100644 --- a/app/templates/index.html +++ b/app/templates/index.html @@ -51,7 +51,7 @@ - +