V45.12: fix SF preset wrong sau reopen (race C++ restore async ghi de program JS vua gui) - retry FORCE CC0/CC32/PROGRAM sau 1.5s/4s/8s qua cua so restore, bo dedupe v=202608311035
This commit is contained in:
+10
-2
@@ -73,7 +73,7 @@ const resolveTrackInstrumentCtx = (track, tracks) => {
|
||||
// note; reset khi load instrument mới). Dùng chung mọi đường: timeline,
|
||||
// preview, keybed. Trước đây bank hardcode 0 + preview/keybed KHÔNG gửi
|
||||
// program change → SF2 preset ở bank≠0 ra piano sai.
|
||||
window.__ensureBridgeProgram = (trkId, program, synthEngine) => {
|
||||
window.__ensureBridgeProgram = (trkId, program, synthEngine, force) => {
|
||||
try {
|
||||
if (!window.SonicMidiRouter || !window.SonicMidiRouter.isBridgeActive()) return;
|
||||
const _bank = synthEngine && synthEngine.soundfont_bank !== undefined ? synthEngine.soundfont_bank : 0;
|
||||
@@ -83,7 +83,7 @@ window.__ensureBridgeProgram = (trkId, program, synthEngine) => {
|
||||
if (_prog === undefined || _prog === null) return;
|
||||
const _key = trkId + ':' + _bank + ':' + _prog;
|
||||
const _lp = window.__bridgeLastProgram || (window.__bridgeLastProgram = {});
|
||||
if (_lp[_key]) return;
|
||||
if (!force && _lp[_key]) return;
|
||||
_lp[_key] = true;
|
||||
const _isPerc = _bank === 128;
|
||||
window.SonicMidiRouter.pushEvent({ cmd: 'CC', channel: trkId, pitch: 0, velocity: 0, data2: (_bank >> 7) & 0x7F, percussion: _isPerc });
|
||||
@@ -7576,6 +7576,14 @@ const preloadTrackInstruments = async (tracks) => {
|
||||
// __ensureBridgeProgram falls back to synth_engine.soundfont_program.
|
||||
if (typeof inst === 'string' && inst.startsWith('sf_')) {
|
||||
try { if (window.__ensureBridgeProgram) window.__ensureBridgeProgram(t.id || t.trackId, undefined, t.synth_engine); } catch (e) {}
|
||||
// V45.12: C++ restore (bridge_state.json) chạy ASYNC sau preload —
|
||||
// assign() + selectProgram(bank/program CŨ) ghi đè program JS vừa
|
||||
// gửi (race startup). Retry FORCE (bỏ dedupe) sau 1.5s/4s/8s để qua
|
||||
// cửa sổ restore, không spam mỗi note.
|
||||
if (t.synth_engine && t.synth_engine.soundfont_program !== undefined) {
|
||||
const _fire = () => { try { if (window.__ensureBridgeProgram) window.__ensureBridgeProgram(t.id || t.trackId, undefined, t.synth_engine, true); } catch (e) {} };
|
||||
[1500, 4000, 8000].forEach(ms => setTimeout(_fire, ms));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ synthEngine:se,sfId:se.soundfont_id,bank:se.soundfont_bank||0,prog:se.soundfont_
|
||||
// note; reset khi load instrument mới). Dùng chung mọi đường: timeline,
|
||||
// preview, keybed. Trước đây bank hardcode 0 + preview/keybed KHÔNG gửi
|
||||
// program change → SF2 preset ở bank≠0 ra piano sai.
|
||||
window.__ensureBridgeProgram=(trkId,program,synthEngine)=>{try{if(!window.SonicMidiRouter||!window.SonicMidiRouter.isBridgeActive())return;const _bank=synthEngine&&synthEngine.soundfont_bank!==undefined?synthEngine.soundfont_bank:0;const _prog=program!==undefined&&program!==null?program:synthEngine&&synthEngine.soundfont_program!==undefined?synthEngine.soundfont_program:undefined;if(_prog===undefined||_prog===null)return;const _key=trkId+':'+_bank+':'+_prog;const _lp=window.__bridgeLastProgram||(window.__bridgeLastProgram={});if(_lp[_key])return;_lp[_key]=true;const _isPerc=_bank===128;window.SonicMidiRouter.pushEvent({cmd:'CC',channel:trkId,pitch:0,velocity:0,data2:_bank>>7&0x7F,percussion:_isPerc});window.SonicMidiRouter.pushEvent({cmd:'CC',channel:trkId,pitch:32,velocity:0,data2:_bank&0x7F,percussion:_isPerc});window.SonicMidiRouter.pushEvent({cmd:'PROGRAM',channel:trkId,pitch:0,velocity:0,data2:_prog,percussion:_isPerc});}catch(e){console.warn('[Bridge] ensureBridgeProgram error:',e);}};// Đảm bảo FluidSynth channel của track đã select ĐÚNG instrument trước khi
|
||||
window.__ensureBridgeProgram=(trkId,program,synthEngine,force)=>{try{if(!window.SonicMidiRouter||!window.SonicMidiRouter.isBridgeActive())return;const _bank=synthEngine&&synthEngine.soundfont_bank!==undefined?synthEngine.soundfont_bank:0;const _prog=program!==undefined&&program!==null?program:synthEngine&&synthEngine.soundfont_program!==undefined?synthEngine.soundfont_program:undefined;if(_prog===undefined||_prog===null)return;const _key=trkId+':'+_bank+':'+_prog;const _lp=window.__bridgeLastProgram||(window.__bridgeLastProgram={});if(!force&&_lp[_key])return;_lp[_key]=true;const _isPerc=_bank===128;window.SonicMidiRouter.pushEvent({cmd:'CC',channel:trkId,pitch:0,velocity:0,data2:_bank>>7&0x7F,percussion:_isPerc});window.SonicMidiRouter.pushEvent({cmd:'CC',channel:trkId,pitch:32,velocity:0,data2:_bank&0x7F,percussion:_isPerc});window.SonicMidiRouter.pushEvent({cmd:'PROGRAM',channel:trkId,pitch:0,velocity:0,data2:_prog,percussion:_isPerc});}catch(e){console.warn('[Bridge] ensureBridgeProgram error:',e);}};// Đảm bảo FluidSynth channel của track đã select ĐÚNG instrument trước khi
|
||||
// notes bắn. Fire-and-forget: playNote tự load + retry nếu SF chưa load xong
|
||||
// (dedup sẵn trong loadSoundFont) — không chặn, không gây stall khi mở tab.
|
||||
const ensureSonicInstrument=ctx=>{try{if(!window.SonicSF||!window.SonicSF.selectInstrument)return;if(ctx.sfId){window.SonicSF.selectInstrument(ctx.ch,ctx.bank,ctx.prog,ctx.sfId);}else if(ctx.program!==undefined){window.SonicSF.selectInstrument(ctx.ch,0,ctx.program,null);}}catch(e){console.warn('[Instrument] ensureSonicInstrument error:',e);}};// ── MIDI note-off scheduling helper (pending map chống note chồng) ─────────
|
||||
@@ -339,7 +339,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=202608300815`);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=202608311035`);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
|
||||
@@ -752,7 +752,11 @@ for(let i=0;i<list.length;i++){const t=list[i];const inst=t.instrumentId||t.synt
|
||||
// load; preload only loads the SF2 file -> after reopen the SF
|
||||
// preset is wrong (bug: muted SF tracks lost their preset).
|
||||
// __ensureBridgeProgram falls back to synth_engine.soundfont_program.
|
||||
if(typeof inst==='string'&&inst.startsWith('sf_')){try{if(window.__ensureBridgeProgram)window.__ensureBridgeProgram(t.id||t.trackId,undefined,t.synth_engine);}catch(e){}}}}if(window.SonicSF&&window.SonicSF.selectInstrument){for(let i=0;i<list.length;i++){const t=list[i];const se=t.synth_engine;const sfId=se&&se.soundfont_id||t.soundfont_id;if(!sfId)continue;const bank=se?se.soundfont_bank!==undefined?se.soundfont_bank:0:t.soundfont_bank!==undefined?t.soundfont_bank:0;const prog=se?se.soundfont_program!==undefined?se.soundfont_program:0:t.soundfont_program!==undefined?t.soundfont_program:0;const ch=t.midiChannel!==undefined?t.midiChannel:i%16;try{await window.SonicSF.selectInstrument(ch,bank,prog,sfId);}catch(e){}}}};const ProfileModal=({isOpen,onClose,tracks,setTracks,setSelectedTrackId,projectName,setProjectName,currentProjectId,setCurrentProjectId,showToast,loadAudioBuffersForTracks,setAppWarningModal,bpm,setBpm,setMasteringSettings,setSessionTabs,setSubTabs,trackMidiChannelsRef})=>{if(!isOpen)return null;const[activeTab,setActiveTab]=useState('account');const[profile,setProfile]=useState(null);const[oldPassword,setOldPassword]=useState('');const[newPassword,setNewPassword]=useState('');const[msg,setMsg]=useState('');const[error,setError]=useState('');const[loading,setLoading]=useState(false);const[dragOfs,setDragOfs]=useState({x:0,y:0});const dragRef=useRef({active:false,startX:0,startY:0,ofsX:0,ofsY:0});// Projects list state
|
||||
if(typeof inst==='string'&&inst.startsWith('sf_')){try{if(window.__ensureBridgeProgram)window.__ensureBridgeProgram(t.id||t.trackId,undefined,t.synth_engine);}catch(e){}// V45.12: C++ restore (bridge_state.json) chạy ASYNC sau preload —
|
||||
// assign() + selectProgram(bank/program CŨ) ghi đè program JS vừa
|
||||
// gửi (race startup). Retry FORCE (bỏ dedupe) sau 1.5s/4s/8s để qua
|
||||
// cửa sổ restore, không spam mỗi note.
|
||||
if(t.synth_engine&&t.synth_engine.soundfont_program!==undefined){const _fire=()=>{try{if(window.__ensureBridgeProgram)window.__ensureBridgeProgram(t.id||t.trackId,undefined,t.synth_engine,true);}catch(e){}};[1500,4000,8000].forEach(ms=>setTimeout(_fire,ms));}}}}if(window.SonicSF&&window.SonicSF.selectInstrument){for(let i=0;i<list.length;i++){const t=list[i];const se=t.synth_engine;const sfId=se&&se.soundfont_id||t.soundfont_id;if(!sfId)continue;const bank=se?se.soundfont_bank!==undefined?se.soundfont_bank:0:t.soundfont_bank!==undefined?t.soundfont_bank:0;const prog=se?se.soundfont_program!==undefined?se.soundfont_program:0:t.soundfont_program!==undefined?t.soundfont_program:0;const ch=t.midiChannel!==undefined?t.midiChannel:i%16;try{await window.SonicSF.selectInstrument(ch,bank,prog,sfId);}catch(e){}}}};const ProfileModal=({isOpen,onClose,tracks,setTracks,setSelectedTrackId,projectName,setProjectName,currentProjectId,setCurrentProjectId,showToast,loadAudioBuffersForTracks,setAppWarningModal,bpm,setBpm,setMasteringSettings,setSessionTabs,setSubTabs,trackMidiChannelsRef})=>{if(!isOpen)return null;const[activeTab,setActiveTab]=useState('account');const[profile,setProfile]=useState(null);const[oldPassword,setOldPassword]=useState('');const[newPassword,setNewPassword]=useState('');const[msg,setMsg]=useState('');const[error,setError]=useState('');const[loading,setLoading]=useState(false);const[dragOfs,setDragOfs]=useState({x:0,y:0});const dragRef=useRef({active:false,startX:0,startY:0,ofsX:0,ofsY:0});// Projects list state
|
||||
const[projectsList,setProjectsList]=useState([]);const[loadingProjects,setLoadingProjects]=useState(false);// Files list state
|
||||
const[filesList,setFilesList]=useState([]);const[loadingFiles,setLoadingFiles]=useState(false);// Confirmation modal state
|
||||
const[confirmModal,setConfirmModal]=useState(null);// Backup state
|
||||
@@ -1940,7 +1944,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=202608300815`);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=202608311035`);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;i<half;i++){l[i]=f[i*2];r[i]=f[i*2+1];}entry.node.port.postMessage({type:'out',l,r});};ws.onclose=()=>fxRtTrackStop(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
|
||||
|
||||
@@ -51,7 +51,7 @@
|
||||
<script src="/static/js/services/promptTemplateManager.js?v=202608290945"></script>
|
||||
<script src="/static/js/services/undoRedoEngine.js?v=202608290945"></script>
|
||||
<script src="/static/js/services/chordTheory.js?v=202608290945"></script>
|
||||
<script src="/static/js/app.precompiled.js?v=202608300815" defer></script>
|
||||
<script src="/static/js/app.precompiled.js?v=202608311035" defer></script>
|
||||
<link rel="stylesheet" href="/static/css/styles.css?v=202608290945">
|
||||
<style>
|
||||
:root {
|
||||
|
||||
Reference in New Issue
Block a user