From 10997a65b9c2a830534a3e3fd0dd0982cc38f4dd Mon Sep 17 00:00:00 2001 From: locphamtran Date: Mon, 24 Aug 2026 07:46:09 +0700 Subject: [PATCH] fix(fx-rt): het crackle master FX - limiter attack smooth + crossfade khi bat/tat chain - NativeInstrumentEngine: kAttack 0.9->0.1 (het zipper khi sum nhieu track) - app.jsx: crossfade masterFxDryGain/masterFxGain thay hard-rewire graph luc activation/deactivation master chain FX; worklet bao 'started' -> ramp dung luc; PDC tre sau khi dry silent (tranh gap 80ms) - sf-fx-realtime.js: fade-in 512 mau luc FILL xong / resume sau underrun - index.html + addModule: cache-buster v=202608241200 - rebuild app.precompiled.js, copy bundle vao dist/ + src-tauri/resources/ - keo dai fix cac round truoc: FILL 16, FXRT_BURST_MS, REBUFFER, pacing, VST GUI click/focus, solo crackle - them harness + plans/patch scripts --- app/api/v1/plugins.py | 26 ++ app/core/fx_realtime.py | 24 ++ app/static/js/app.jsx | 335 ++++++++++++++---- app/static/js/app.precompiled.js | 114 ++++-- app/static/js/services/api.js | 1 + app/static/js/sf-fx-realtime.js | 29 +- app/templates/index.html | 2 +- harness_gui_probe.py | 162 +++++++++ harness_out_glitch.py | 175 +++++++++ harness_setchain_glitch.py | 188 ++++++++++ .../include/NativeInstrumentEngine.h | 5 +- native_bridge/src/FxGuiServer.cpp | 58 +-- native_bridge/src/NativeInstrumentEngine.cpp | 51 ++- native_bridge/src/RealtimeFxLoop.cpp | 41 +++ native_bridge/src/RenderFxJob.cpp | 35 +- plans/patch_attack.py | 22 ++ plans/patch_fx_crossfade.py | 90 +++++ .../daw_vst_bridge-x86_64-pc-windows-msvc.exe | Bin 1796608 -> 1824256 bytes src-tauri/binaries/daw_vst_bridge.exe | Bin 1796608 -> 1824256 bytes .../fx_vst_bridge-x86_64-pc-windows-msvc.exe | Bin 346112 -> 348672 bytes src-tauri/binaries/fx_vst_bridge.exe | Bin 346624 -> 348672 bytes 21 files changed, 1181 insertions(+), 177 deletions(-) create mode 100644 harness_gui_probe.py create mode 100644 harness_out_glitch.py create mode 100644 harness_setchain_glitch.py create mode 100644 plans/patch_attack.py create mode 100644 plans/patch_fx_crossfade.py diff --git a/app/api/v1/plugins.py b/app/api/v1/plugins.py index e19f146..3be15db 100644 --- a/app/api/v1/plugins.py +++ b/app/api/v1/plugins.py @@ -631,6 +631,11 @@ class FxGuiRequest(BaseModel): # mở mapping này để PEEK input ring và chạy processAudio() trên instance # GUI → meter trong plugin nhảy theo âm thật (GUI không consume ring). shm: str = "" + # preset_b64: preset GUI capture mới nhất (bridge state blob hoặc raw + # .vstpreset b64) — bridge áp sau fx->load() để mở GUI với ĐÚNG cài đặt + # đã chỉnh (trước đây GUI mở lại load default → mất settings khi + # hide/show). + preset_b64: str = "" class FxGuiCloseRequest(BaseModel): @@ -682,6 +687,8 @@ async def open_fx_gui(req: FxGuiRequest, current_user: dict = Depends(get_curren job = {"path": plugin_path, "name": req.name or os.path.basename(plugin_path)} if req.shm: job["shm"] = req.shm + if req.preset_b64: + job["preset_b64"] = req.preset_b64 fd, job_path = tempfile.mkstemp(prefix="sf_fx_gui_", suffix=".json", dir=tempfile.gettempdir()) try: with os.fdopen(fd, "w", encoding="utf-8") as f: @@ -1003,6 +1010,10 @@ class FxRealtimeStartRequest(BaseModel): class FxRealtimeStopRequest(BaseModel): session_id: str = "" +class FxRealtimeSetChainRequest(BaseModel): + session_id: str = "" + fx_chain: list = [] + @router.post("/fx-realtime/start") async def fx_realtime_start(req: FxRealtimeStartRequest, current_user: dict = Depends(get_current_user)): @@ -1033,6 +1044,21 @@ async def fx_realtime_stop(req: FxRealtimeStopRequest, ok = fx_realtime.stop_session(req.session_id or "") return {"success": True, "stopped": ok} +@router.post("/fx-realtime/set-chain") +async def fx_realtime_set_chain(req: FxRealtimeSetChainRequest, + current_user: dict = Depends(get_current_user)): + """Cập nhật chain trên session realtime ĐANG CHẠY — KHÔNG restart session. + Engine ghi lại job file (seq++); bridge poll seq → RealtimeFxChain::setChain + (worker load chain mới, swap atomic dưới mutex — audio thread copy + shared_ptr, không dừng) → load/đổi VST FX + đổi preset GUI không ngắt âm/ + crackle. Session/WS/SHM giữ nguyên.""" + enforce_password_changed(current_user) + sess = fx_realtime.get_session(req.session_id or "") + if not sess: + raise HTTPException(status_code=404, detail="Session realtime không tồn tại") + ok = sess.set_chain(req.fx_chain or []) + return {"success": True, "updated": ok} + @router.websocket("/ws/fx-realtime/{session_id}") async def ws_fx_realtime(websocket: WebSocket, session_id: str): """Vòng lặp FX realtime: receive block input → SHM → bridge → SHM → send diff --git a/app/core/fx_realtime.py b/app/core/fx_realtime.py index 5647538..af28825 100644 --- a/app/core/fx_realtime.py +++ b/app/core/fx_realtime.py @@ -120,6 +120,7 @@ class FxRealtimeSession: self._in_pending_t0 = None self.proc = None self._job_path = "" + self._chain_seq = 0 self._started_at = time.time() # Chain hợp nhất (spec PLAN_DAW_A.md Phase 1): giữ đúng thứ tự slot. self.chain = list(self.fx_chain or []) @@ -163,6 +164,7 @@ class FxRealtimeSession: job = { "sample_rate": self.sample_rate, "block_size": self.block_size, + "seq": self._chain_seq, "fx_chain": self._chain_json_for_bridge(), } fd, self._job_path = tempfile.mkstemp(suffix=".json", prefix="fxrt_") @@ -177,6 +179,28 @@ class FxRealtimeSession: creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), ) + def set_chain(self, fx_chain): + """Cập nhật chain trên session ĐANG CHẠY (không restart session): + ghi lại job file seq++ — bridge poll seq mỗi 500ms → setChain async + swap (worker load chain mới, audio giữ chain cũ tới khi swap) → load/ + đổi VST FX + đổi preset GUI không ngắt âm/crackle.""" + self.fx_chain = list(fx_chain or []) + self.chain = self.fx_chain + self._chain_seq += 1 + if not self._job_path or not os.path.exists(self._job_path): + return False + try: + with open(self._job_path, "w", encoding="utf-8") as f: + json.dump({ + "sample_rate": self.sample_rate, + "block_size": self.block_size, + "seq": self._chain_seq, + "fx_chain": self._chain_json_for_bridge(), + }, f) + except Exception: + return False + return True + def wait_ready(self, timeout=30.0): deadline = time.time() + timeout while time.time() < deadline: diff --git a/app/static/js/app.jsx b/app/static/js/app.jsx index a2e17ad..9086787 100644 --- a/app/static/js/app.jsx +++ b/app/static/js/app.jsx @@ -1054,6 +1054,16 @@ function initMasterBus(ctx) { const output = ctx.createGain(); output.gain.value = 1.0; + // Crossfade master-FX activation (het click khi bat/tat master chain FX): + // path mac dinh outputAnalyser -> masterFxDryGain(1) -> pdcDelay -> output; + // nhanh FX noi vao masterFxGain(0) -> output. fxRtStart/fxRtStop ramp 2 gain + // nay thay vi hard-rewire graph (dry path luon noi san — no click, no gap + // trong luc worklet FILL ~86ms). + const masterFxDryGain = ctx.createGain(); + masterFxDryGain.gain.value = 1.0; + const masterFxGain = ctx.createGain(); + masterFxGain.gain.value = 0.0; + // Per-track mastering-bypass dry bus: tracks with bypass ON feed into // dryInput -> dryOutput -> output, skipping the mastering modules // (EQ / Imager / Maximizer) while still passing the master volume fader @@ -1104,6 +1114,8 @@ function initMasterBus(ctx) { compressor: ctx.createDynamicsCompressor(), analyser, output, + masterFxDryGain, + masterFxGain, masteringActive: false, dryInput, dryOutput, @@ -1151,7 +1163,10 @@ function initMasterBus(ctx) { // "state is bad" → CÂM + stuck. Mastering chain có comp/lim module riêng khi bật. masterBus.input.connect(masterBus.inputAnalyser); masterBus.inputAnalyser.connect(masterBus.outputAnalyser); - masterBus.outputAnalyser.connect(masterBus.output); + masterBus.outputAnalyser.connect(masterBus.masterFxDryGain); + masterBus.masterFxDryGain.connect(masterBus.pdcDelay); + masterBus.outputAnalyser.connect(masterBus.masterFxGain); + masterBus.masterFxGain.connect(masterBus.output); masterBus.muteGain.connect(masterBus.analyser); masterBus.muteGain.connect(masterBus.splitter); masterBus.analyser.connect(ctx.destination); @@ -1631,7 +1646,13 @@ function encodeFloatWavBlob(pcm, sampleRate, channels) { // worklet → analyser (sau master fader, trước metering/destination — khớp thứ // tự offline export). Track: mỗi track 1 session/worklet splice vào CẢ 2 đường // chain (audio-clips + MIDI/SF) — mọi luồng track qua bridge trước main out. -const fxRt = { active: false, sessionId: null, ws: null, node: null, inQueue: [], pumpTimer: null, chainKey: null, latencyTotal: 0 }; +const fxRt = { active: false, starting: false, startToken: 0, sessionId: null, ws: null, node: null, inQueue: [], pumpTimer: null, lastInSent: 0, chainKey: null, latencyTotal: 0, fadedIn: false }; +// Pace input realtime: worklet sản xuất đúng realtime, nhưng sau khi main +// thread bị block (solo restart, GUI decode, rAF) các frame 'in' dồn lại — +// gửi 1 loạt làm SHM ring 4-slot tràn → mất block → ngắt quãng. Gửi tối đa 1 +// burst (4 block ~21ms) mỗi 21ms → ring luôn kịp tiêu thụ, audio hồi phục +// trơn sau stall (FILL hấp thụ phần đầu). +const FXRT_BURST_MS = 21; // Signature của chain VST realtime — phát hiện chain ĐỔI (insert/remove/bypass/ // reorder VST) → restart session với chain mới (fxRtStart early-return khi // active, nếu không so chainKey thì VST mới insert không bao giờ được áp). @@ -1688,20 +1709,41 @@ function fxRtPushAllParams() { }); }); } +async function fxRtSetChain(chain) { + const sid = fxRt.sessionId; + if (!sid || !fxRt.ws || fxRt.ws.readyState !== 1) 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: false } + : { type: 'builtin', id: s.type, params: (s.params && Object.keys(s.params).length ? s.params : {}), bypass: false }); + try { + await window.SonicAPI.fxRealtimeSetChain({ session_id: sid, fx_chain: chainPayload }); + try { fxRtPushAllParams(); } catch (e) {} + } catch (e) { + console.warn('[FX RT] set-chain fail:', e); + } +} async function fxRtStart() { const chain = fxRtChain(); const ck = fxRtChainKey(chain); if (fxRt.active) { // masterBus bị rebuild (recovery/export) → node thuộc graph cũ → restart. if (!fxRt.node || fxRt.node.context !== getAudioContext()) fxRtStop(true); - // Chain VST thay đổi (insert/remove/bypass/reorder trong MASTER FX CHAIN) - // → stop + start lại để bridge load đúng chuỗi FX mới. - else if (fxRt.chainKey !== ck) fxRtStop(true); + // Chain thay đổi (insert/remove/bypass/reorder/preset GUI) — KHÔNG restart + // (ngắt âm + crackle): set_chain lên session ĐANG CHẠY → bridge worker + // load chain mới (audio giữ chain cũ tới khi swap) → swap atomic mượt. + else if (fxRt.chainKey !== ck) { fxRtSetChain(chain); fxRt.chainKey = ck; return; } else return; } if (!chain.length) return; + // 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 + // `else if (fxRt.active) fxRtStop()` KHÔNG chạy → start in-flight vẫn nối + // 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) return; + 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: false } : { type: 'builtin', id: s.type, params: (s.params && Object.keys(s.params).length ? s.params : {}), bypass: false }); @@ -1711,12 +1753,21 @@ async function fxRtStart() { } 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=202608212401`); + await ctx.audioWorklet.addModule(`${API_BASE_URL}/static/js/sf-fx-realtime.js?v=202608241200`); + 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://'; @@ -1726,7 +1777,9 @@ async function fxRtStart() { 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) {} }; @@ -1738,7 +1791,9 @@ async function fxRtStart() { const d = JSON.parse(ev.data); if (d && d.cmd === 'latency' && typeof d.total === 'number') { fxRt.latencyTotal = d.total; - fxRtApplyPdc(); + // Chi delay dry path khi crossfade da xong (dry silent) — ap som + // trong luc dry con la path nghe duoc se tao gap ~80ms. + if (fxRt.fadedIn) fxRtApplyPdc(); } } catch (e) {} return; @@ -1753,29 +1808,61 @@ async function fxRtStart() { }; ws.onclose = () => fxRtStop(true); ws.onerror = () => { try { ws.close(); } catch (e) {} }; + // Worklet gom 4 block (1024 mẫu) vào 1 frame → tách 4 WS frame 512 floats + // ở đây. Bridge VST3 nhận input dồn → take=4 → batch 1 call process 1024 + // mẫu (~3.5-4.75ms/block) → đủ 187.5/s (take=1: 5.5ms > budget 5.33ms → + // drop → crackle). KHÔNG dùng f.subarray().buffer — nó gửi cả backing + // buffer 8192B; slice() copy đúng 2048B. + const fxRtSendFrames = (d) => { + if (!fxRt.ws || fxRt.ws.readyState !== 1) return; + try { + const f = new Float32Array(d.data); + if (f.length > 512) { + for (let i = 0; i < f.length; i += 512) fxRt.ws.send(f.slice(i, i + 512).buffer); + } else { + fxRt.ws.send(d.data); + } + } catch (e) {} + }; + const fxRtInPump = () => { + if (!fxRt.inQueue.length) return; + const now = Date.now(); + while (fxRt.inQueue.length && now - fxRt.lastInSent >= FXRT_BURST_MS) { + fxRt.lastInSent = now; + fxRtSendFrames(fxRt.inQueue.shift()); + } + if (fxRt.inQueue.length) { + if (fxRt.pumpTimer) clearTimeout(fxRt.pumpTimer); + fxRt.pumpTimer = setTimeout(fxRtInPump, Math.max(1, FXRT_BURST_MS - (now - fxRt.lastInSent))); + } else if (fxRt.pumpTimer) { + clearTimeout(fxRt.pumpTimer); + fxRt.pumpTimer = null; + } + }; fxRt.node.port.onmessage = (ev) => { const d = ev.data; if (!d || !fxRt.ws) return; + if (d.type === 'started') { + // Worklet bat dau phat (sau FILL) -> crossfade dry->fx muot. Token guard + // chong race: neu stop/restart xay ra trong luc cho, bo qua. + if (fxRt.fadedIn) return; + setTimeout(() => { + if (token !== fxRt.startToken) return; + fxRt.fadedIn = true; + fxRtCrossfade(true, token); + // Dry gan silent (tc 0.025) roi moi tre pdcDelay — tranh gap khi delay + // dang lon dan. + setTimeout(() => fxRtApplyPdc(), 250); + }, 30); + return; + } if (d.type === 'set_param') { try { fxRt.ws.send(JSON.stringify({ cmd: 'set_param', slot: d.slot, key: d.key, value: d.value })); } catch (e) {} return; } if (d.type !== 'in') return; - // Worklet gom 4 block (1024 mẫu) vào 1 frame → tách 4 WS frame 512 floats - // ở đây. Bridge VST3 nhận input dồn → take=4 → batch 1 call process 1024 - // mẫu (~3.5-4.75ms/block) → đủ 187.5/s (take=1: 5.5ms > budget 5.33ms → - // drop → crackle). KHÔNG dùng f.subarray().buffer — nó gửi cả backing - // buffer 8192B; slice() copy đúng 2048B. - if (ws.readyState === 1) { - try { - const f = new Float32Array(d.data); - if (f.length > 512) { - for (let i = 0; i < f.length; i += 512) ws.send(f.slice(i, i + 512).buffer); - } else { - ws.send(d.data); - } - } catch (e) {} - } + fxRt.inQueue.push(d); + fxRtInPump(); }; // Pace input: tối đa 1 block/kỳ (~5.8ms). Gửi dồn theo burst (main thread bị // rAF renderFrame block khi mở MASTERING PANEL) → SHM ring 4-slot tràn → mất @@ -1783,9 +1870,13 @@ async function fxRtStart() { // Phase 4.2: fader SAU worklet — worklet chèn giữa outputAnalyser (chain // output) và output (fader/destination). output → analyser/splitter giữ // nguyên (meter đo âm SAU fader). + // Crossfade activation: KHONG disconnect dry path — outputAnalyser van noi + // masterFxDryGain -> pdcDelay -> output (gain 1); nhanh fx noi masterFxGain + // (gain 0) -> output. Tin hieu 'started' tu worklet -> ramp 2 gain -> switch + // muot, het click hard-rewire. try { masterBus.outputAnalyser.disconnect(masterBus.output); } catch (e) {} masterBus.outputAnalyser.connect(fxRt.node); - fxRt.node.connect(masterBus.output); + fxRt.node.connect(masterBus.masterFxGain); fxRt.chainKey = ck; } catch (e) { console.warn('[FX RT] setup fail:', e); @@ -1793,18 +1884,40 @@ async function fxRtStart() { } } function fxRtStop(silent) { + // Phải bump token TRƯỚC guard early-return: lúc fxRtStart đang in-flight thì + // active/ws/node/sessionId đều chưa có → guard sẽ return, nhưng start vẫn + // phải bị hủy (token mismatch ở checkpoint). + fxRt.startToken++; + fxRt.starting = false; if (fxRt.pumpTimer) { clearInterval(fxRt.pumpTimer); fxRt.pumpTimer = null; } fxRt.inQueue = []; if (!fxRt.active && !fxRt.ws && !fxRt.node && !fxRt.sessionId) return; + let _fxStopNode = null; try { if (fxRt.node) { - fxRt.node.disconnect(); - if (masterBus && masterBus.outputAnalyser && masterBus.output) { - try { masterBus.outputAnalyser.disconnect(masterBus.output); } catch (e) {} - try { masterBus.outputAnalyser.connect(masterBus.output); } catch (e) {} + _fxStopNode = fxRt.node; + if (masterBus && masterBus.masterFxGain && masterBus.masterFxDryGain) { + // Crossfade deactivation: ramp dry 0->1 / fx 1->0 roi MOI disconnect + // (tranh click hard-switch nguoc). Dry path da noi san qua + // masterFxDryGain — khong can reconnect outputAnalyser->output. PDC giam + // ve 0 sau khi dry chiem cho (fx silent). + try { fxRtCrossfade(false); } catch (e) {} + setTimeout(() => { + try { _fxStopNode.disconnect(); } catch (e) {} + _fxStopNode.port.onmessage = null; + if (fxRt.node === _fxStopNode) fxRt.node = null; + fxRt.fadedIn = false; + fxRtApplyPdc(); + }, 180); + } else { + // Fallback graph cu (khong co crossfade gains) — hard switch nhu cu. + try { _fxStopNode.disconnect(); } catch (e) {} + if (masterBus && masterBus.outputAnalyser && masterBus.output) { + try { masterBus.outputAnalyser.connect(masterBus.output); } catch (e) {} + } + _fxStopNode.port.onmessage = null; + if (fxRt.node === _fxStopNode) fxRt.node = null; } - fxRt.node.port.onmessage = null; - fxRt.node = null; } } catch (e) {} try { if (fxRt.ws) { fxRt.ws.onclose = null; fxRt.ws.onmessage = null; try { fxRt.ws.close(); } catch (e) {} fxRt.ws = null; } } catch (e) {} @@ -1814,7 +1927,9 @@ function fxRtStop(silent) { fxRt.active = false; fxRt.chainKey = null; fxRt.latencyTotal = 0; - fxRtApplyPdc(); + // PDC giam ve 0 sau khi dry chiem cho (trong setTimeout cua nhanh crossfade) + // hoac ngay neu khong co node — khong goi tai day de tranh gap 80ms. + if (!_fxStopNode) fxRtApplyPdc(); if (sid) { try { window.SonicAPI.fxRealtimeStop({ session_id: sid }).catch(() => {}); } catch (e) {} } @@ -1837,6 +1952,20 @@ function fxRtApplyPdc() { try { bus.pdcDelay.delayTime.setTargetAtTime(l / (ctx.sampleRate || 44100), ctx.currentTime, 0.05); } catch (e) {} } +// Crossfade master-FX switch: ramp masterFxGain/masterFxDryGain thay vi +// hard-rewire (click). Hai gain nay duoc tao trong initMasterBus. +function fxRtCrossfade(toFx, token) { + const ctx = getAudioContext(); + const bus = masterBus; + if (!ctx || !bus || !bus.masterFxGain || !bus.masterFxDryGain) return; + if (token !== undefined && token !== fxRt.startToken) return; + const tc = 0.025; + try { + bus.masterFxGain.gain.setTargetAtTime(toFx ? 1 : 0, ctx.currentTime, tc); + bus.masterFxDryGain.gain.setTargetAtTime(toFx ? 0 : 1, ctx.currentTime, tc); + } catch (e) {} +} + // ── Realtime VST FX per-track (SHM bridge) — mọi luồng track qua bridge ───── // Mỗi track: session riêng (1 WS/SHM) cho TỪNG đường chain có âm — audio-clips // (path 'audio', splice fxEntry→mods→worklet→fxLegacyIn) và MIDI/SF (path 'sf', @@ -2743,22 +2872,6 @@ const MasterStripConsole = ({ masterVolume, setMasterVolume, masterVolL, setMast React.createElement("div", { className: "flex flex-col items-stretch w-[300px] shrink-0 strip-bg rounded-lg p-2 text-slate-300 select-none shadow-2xl relative overflow-hidden" }, - React.createElement("div", { className: "space-y-1.5 mb-2" }, - React.createElement("button", { - onClick: () => setShowMasteringModal(true), - className: "w-full bg-slate-800 hover:bg-slate-700 text-[10px] font-semibold py-1 rounded border border-slate-700 text-slate-300 tracking-tight" - }, "FX CHAIN"), - React.createElement("button", { - onClick: () => setRefOpen(true), - className: "w-full bg-slate-800 hover:bg-slate-700 text-[10px] font-semibold py-1 rounded border border-slate-700 text-cyan-300 tracking-tight" - }, "A/B REF"), - React.createElement("div", { - className: "flex items-center justify-between bg-slate-950 border border-slate-800 rounded px-1.5 py-0.5 text-[10px] font-mono" - }, - React.createElement("span", { className: "text-slate-400 truncate" }, "Output 1 / Output 2"), - React.createElement("i", { className: "fa-solid fa-circle-notch text-[9px] text-slate-500" }) - ) - ), React.createElement("div", { className: "flex flex-col items-center my-0.5" }, React.createElement("span", { className: "text-[9px] text-slate-400 font-mono" }, panText || 'center'), React.createElement("div", { className: "flex items-center gap-1" }, @@ -12443,7 +12556,7 @@ const ExportModal = ({ open, onClose, exportSettings, setExportSettings, isExpor React.useEffect(() => { deadRef.current = false; setDead(false); - const tick = setInterval(() => { const img = imgRef.current; if (img) img.src = url + '/frame?t=' + Date.now(); }, 100); + const tick = setInterval(() => { const img = imgRef.current; if (img && img.complete) img.src = url + '/frame?t=' + Date.now(); }, 100); const ping = setInterval(() => { fetch(url + '/ping').then(r => { if (!r.ok) throw new Error('bad'); }).catch(() => { if (!deadRef.current) { deadRef.current = true; setDead(true); onDead && onDead(); } @@ -12501,7 +12614,7 @@ const ExportModal = ({ open, onClose, exportSettings, setExportSettings, isExpor } catch (e) {} }; refresh(); - const iv = setInterval(refresh, 500); + const iv = setInterval(refresh, 250); return () => { alive = false; clearInterval(iv); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [url]); @@ -12611,6 +12724,25 @@ let _persistFxGuiTrackId = null; // Latest preset_b64 captured from each plugin's embedded GUI (poll /preset) // - merged into the project on save so knob tweaks survive reload. let _capturedPresetByPath = {}; +// Baseline of each plugin's GUI state at embed-open time. /preset round-trips +// through getState/applyPreset and the blob can differ from the value the +// session started with; restarting the chain on that first difference reloads +// the VST and crackles. First capture after open = baseline (no restart); only +// a CHANGE vs baseline schedules the ~3s restart that syncs realtime to GUI. +let _fxGuiBaselineByPath = {}; +// Debounced restart khi preset GUI đổi (preset poll) — _capturedPresetByPath +// đổi làm chainKey đổi nhưng không ai gọi fxRtStart/reconcile → session +// realtime GIỮ preset cũ (xoay knob trong GUI không đổi âm realtime). Restart +// ~3s sau khi knob DỪNG xoay (không restart mỗi poll 1.5s giữa lúc kéo — load +// VST ~4s ngắt âm). fn tự early-return khi chainKey không đổi. +let _presetRestartTimers = {}; +function _schedulePresetRestart(key, fn, ms) { + if (_presetRestartTimers[key]) clearTimeout(_presetRestartTimers[key]); + _presetRestartTimers[key] = setTimeout(() => { + delete _presetRestartTimers[key]; + try { fn(); } catch (e) {} + }, ms); +} const FXRackModal = ({ track, onUpdateTrack, onClose }) => { const [activeType, setActiveType] = React.useState('eq'); const [addModuleOpen, setAddModuleOpen] = React.useState(false); @@ -12661,16 +12793,25 @@ const FXRackModal = ({ track, onUpdateTrack, onClose }) => { fxGuiOpenRef.current = fxGuiOpen; const closeFxGui = () => { const g = fxGuiOpenRef.current; - if (g) { try { fetch(g.url + '/close', { method: 'POST' }).catch(() => {}); } catch (e) {} } + if (g) { + // Capture preset CUỐI trước khi đóng (poll 1.5s có thể chưa kịp khi chỉnh + // xong đóng ngay) — gọi /preset TRƯỚC /close (close kill process bridge). + try { fetch(g.url + '/preset').then(r => r.json()).then(d => { if (d && d.preset_b64 && g.path) _capturedPresetByPath[g.path] = d.preset_b64; }).catch(() => {}).then(() => { try { fetch(g.url + '/close', { method: 'POST' }).catch(() => {}); } catch (e) {} }); } catch (e) { try { fetch(g.url + '/close', { method: 'POST' }).catch(() => {}); } catch (e2) {} } + } setFxGuiOpen(null); + if (g && g.path) { + const _tk = 'track:' + ((track && track.id) || '') + ':' + g.path; + if (_presetRestartTimers[_tk]) { clearTimeout(_presetRestartTimers[_tk]); delete _presetRestartTimers[_tk]; } + delete _fxGuiBaselineByPath[g.path]; + } if (onUpdateTrack && track) onUpdateTrack(track.id, { vstGuiOpenPath: null, vstGuiOpenName: null }); }; - React.useEffect(() => () => { const g = fxGuiOpenRef.current; if (g) { try { fetch(g.url + '/hide', { method: 'POST' }).catch(() => {}); } catch (e) {} } }, []); + React.useEffect(() => () => { const g = fxGuiOpenRef.current; if (g) { try { fetch(g.url + '/hide', { method: 'POST' }).catch(() => {}); } catch (e) {} const _tk = 'track:' + ((track && track.id) || '') + ':' + g.path; if (_presetRestartTimers[_tk]) { clearTimeout(_presetRestartTimers[_tk]); delete _presetRestartTimers[_tk]; } if (g.path) delete _fxGuiBaselineByPath[g.path]; } }, []); // Capture GUI knob tweaks while the embedded GUI is open (bridge /preset). React.useEffect(() => { if (!fxGuiOpen || !fxGuiOpen.url) return; const iv = setInterval(() => { - fetch(fxGuiOpen.url + '/preset').then(r => r.json()).then(d => { if (d && d.preset_b64) _capturedPresetByPath[fxGuiOpen.path] = d.preset_b64; }).catch(() => {}); + fetch(fxGuiOpen.url + '/preset').then(r => r.json()).then(d => { if (d && d.preset_b64) { const _p = fxGuiOpen.path; const _b = _fxGuiBaselineByPath[_p]; if (_b === undefined) { _fxGuiBaselineByPath[_p] = d.preset_b64; _capturedPresetByPath[_p] = d.preset_b64; return; } if (d.preset_b64 !== _b) { _fxGuiBaselineByPath[_p] = d.preset_b64; _capturedPresetByPath[_p] = d.preset_b64; const _tid = track && track.id; _schedulePresetRestart('track:' + (_tid || '') + ':' + _p, () => { if (_tid && window.__rebuildTrackFxGraph) window.__rebuildTrackFxGraph(_tid, {}); }, 3000); } } }).catch(() => {}); }, 1500); return () => clearInterval(iv); // eslint-disable-next-line react-hooks/exhaustive-deps @@ -12680,7 +12821,7 @@ const FXRackModal = ({ track, onUpdateTrack, onClose }) => { if (!track || !track.vstGuiOpenPath || fxGuiOpen) return; const s = (track.fxChain || []).find(x => x.path === track.vstGuiOpenPath); if (!s || !window.SonicAPI || !window.SonicAPI.openFxGui) return; - window.SonicAPI.openFxGui({ path: s.path, name: s.name || s.path, embed: true, shm: fxRtTrackShmName(track && track.id) }).then(r => { + window.SonicAPI.openFxGui({ path: s.path, name: s.name || s.path, embed: true, shm: fxRtTrackShmName(track && track.id), preset_b64: _capturedPresetByPath[s.path] || s.preset_b64 || '' }).then(r => { if (r && r.embed_url) setFxGuiOpen({ path: s.path, url: r.embed_url }); }).catch(() => {}); // eslint-disable-next-line react-hooks/exhaustive-deps @@ -12688,7 +12829,7 @@ const FXRackModal = ({ track, onUpdateTrack, onClose }) => { const toggleVst = (idx) => setVstChain(vstChain.map((s, i) => i === idx ? { ...s, bypass: !s.bypass } : s)); const removeVst = (idx) => { const rem = vstChain[idx]; if (rem && fxGuiOpen && fxGuiOpen.path === rem.path) closeFxGui(); if (rem) delete _capturedPresetByPath[rem.path]; if (idx === activeVstIdx) setActiveVstIdx(-1); setVstChain(vstChain.filter((_, i) => i !== idx)); }; const moveVst = (idx, dir) => { const j = idx + dir; if (j < 0 || j >= vstChain.length) return; const next = [...vstChain]; const mv = next.splice(idx, 1)[0]; next.splice(j, 0, mv); setVstChain(next); }; - const openVstGui = (s, idx) => { if (!s || !s.path) { window.showToast && window.showToast('Chọn VST FX trước', 'warning'); return; } if (fxGuiOpen) closeFxGui(); if (idx !== undefined) setActiveVstIdx(idx); if (!window.SonicAPI || !window.SonicAPI.openFxGui) { window.showToast && window.showToast('Máy này không hỗ trợ mở GUI VST', 'warning'); return; } window.SonicAPI.openFxGui({ path: s.path, name: s.name || s.path, embed: true, shm: fxRtTrackShmName(track && track.id) }).then(r => { if (r && r.embed_url) { setFxGuiOpen({ path: s.path, url: r.embed_url, name: s.name || s.path }); if (onUpdateTrack && track) onUpdateTrack(track.id, { vstGuiOpenPath: s.path, vstGuiOpenName: s.name || s.path }); } else if (r && r.already_running && r.embed_url) { setFxGuiOpen({ path: s.path, url: r.embed_url, name: s.name || s.path }); if (onUpdateTrack && track) onUpdateTrack(track.id, { vstGuiOpenPath: s.path, vstGuiOpenName: s.name || s.path }); } else if (r && r.already_running) window.showToast && window.showToast('GUI của plugin này đang mở sẵn (cửa sổ ngoài)', 'info'); else window.showToast && window.showToast('Không mở được GUI embed', 'error'); }).catch(err => window.showToast && window.showToast('Lỗi mở GUI: ' + (err.message || err), 'error')); }; + const openVstGui = (s, idx) => { if (!s || !s.path) { window.showToast && window.showToast('Chọn VST FX trước', 'warning'); return; } if (fxGuiOpen) closeFxGui(); if (idx !== undefined) setActiveVstIdx(idx); if (!window.SonicAPI || !window.SonicAPI.openFxGui) { window.showToast && window.showToast('Máy này không hỗ trợ mở GUI VST', 'warning'); return; } window.SonicAPI.openFxGui({ path: s.path, name: s.name || s.path, embed: true, shm: fxRtTrackShmName(track && track.id), preset_b64: _capturedPresetByPath[s.path] || s.preset_b64 || '' }).then(r => { if (r && r.embed_url) { setFxGuiOpen({ path: s.path, url: r.embed_url, name: s.name || s.path }); if (onUpdateTrack && track) onUpdateTrack(track.id, { vstGuiOpenPath: s.path, vstGuiOpenName: s.name || s.path }); } else if (r && r.already_running && r.embed_url) { setFxGuiOpen({ path: s.path, url: r.embed_url, name: s.name || s.path }); if (onUpdateTrack && track) onUpdateTrack(track.id, { vstGuiOpenPath: s.path, vstGuiOpenName: s.name || s.path }); } else if (r && r.already_running) window.showToast && window.showToast('GUI của plugin này đang mở sẵn (cửa sổ ngoài)', 'info'); else window.showToast && window.showToast('Không mở được GUI embed', 'error'); }).catch(err => window.showToast && window.showToast('Lỗi mở GUI: ' + (err.message || err), 'error')); }; const addVst = (path) => { const fx = (fxList || []).find(f => f.path === path); if (!fx) return; const next = [...vstChain, { type: 'vst3', path: fx.path, name: fx.name || fx.id, preset_b64: '', bypass: false }]; setVstChain(next); setActiveVstIdx(next.length - 1); }; const changeVstPlugin = (idx, path) => { const fx = (fxList || []).find(f => f.path === path); delete _capturedPresetByPath[path]; setVstChain(vstChain.map((s, i) => i === idx ? { ...s, path, name: fx ? (fx.name || fx.id) : s.name, preset_b64: '' } : s)); }; const uploadVstPreset = (idx) => { @@ -13244,17 +13385,25 @@ const MasteringModal = ({ isOpen, onClose, masteringSettings, setMasteringSettin masterGuiOpenRef.current = masterGuiOpen; const closeMasterGui = () => { const g = masterGuiOpenRef.current; - if (g) { try { fetch(g.url + '/close', { method: 'POST' }).catch(() => {}); } catch (e) {} } + if (g) { + // Capture preset CUỐI trước khi đóng (giống closeFxGui) — /preset rồi /close. + try { fetch(g.url + '/preset').then(r => r.json()).then(d => { if (d && d.preset_b64 && g.path) _capturedPresetByPath[g.path] = d.preset_b64; }).catch(() => {}).then(() => { try { fetch(g.url + '/close', { method: 'POST' }).catch(() => {}); } catch (e) {} }); } catch (e) { try { fetch(g.url + '/close', { method: 'POST' }).catch(() => {}); } catch (e2) {} } + } setMasterGuiOpen(null); + if (g && g.path) { + const _mk = 'master:' + g.path; + if (_presetRestartTimers[_mk]) { clearTimeout(_presetRestartTimers[_mk]); delete _presetRestartTimers[_mk]; } + delete _fxGuiBaselineByPath[g.path]; + } setActiveMasterVstPath(null); setOzState(prev => { const n = { ...(prev || {}) }; delete n.gui_open_path; delete n.gui_open_name; return n; }); }; - React.useEffect(() => () => { const g = masterGuiOpenRef.current; if (g) { try { fetch(g.url + '/hide', { method: 'POST' }).catch(() => {}); } catch (e) {} } }, []); + React.useEffect(() => () => { const g = masterGuiOpenRef.current; if (g) { try { fetch(g.url + '/hide', { method: 'POST' }).catch(() => {}); } catch (e) {} const _mk = 'master:' + g.path; if (_presetRestartTimers[_mk]) { clearTimeout(_presetRestartTimers[_mk]); delete _presetRestartTimers[_mk]; } if (g.path) delete _fxGuiBaselineByPath[g.path]; } }, []); // Capture GUI knob tweaks while the embedded GUI is open (bridge /preset). React.useEffect(() => { if (!masterGuiOpen || !masterGuiOpen.url) return; const iv = setInterval(() => { - fetch(masterGuiOpen.url + '/preset').then(r => r.json()).then(d => { if (d && d.preset_b64) _capturedPresetByPath[masterGuiOpen.path] = d.preset_b64; }).catch(() => {}); + fetch(masterGuiOpen.url + '/preset').then(r => r.json()).then(d => { if (d && d.preset_b64) { const _p = masterGuiOpen.path; const _b = _fxGuiBaselineByPath[_p]; if (_b === undefined) { _fxGuiBaselineByPath[_p] = d.preset_b64; _capturedPresetByPath[_p] = d.preset_b64; return; } if (d.preset_b64 !== _b) { _fxGuiBaselineByPath[_p] = d.preset_b64; _capturedPresetByPath[_p] = d.preset_b64; _schedulePresetRestart('master:' + _p, () => fxRtStart(), 3000); } } }).catch(() => {}); }, 1500); return () => clearInterval(iv); // eslint-disable-next-line react-hooks/exhaustive-deps @@ -13264,7 +13413,7 @@ const MasteringModal = ({ isOpen, onClose, masteringSettings, setMasteringSettin if (!isOpen || !ozState || !ozState.gui_open_path || masterGuiOpen) return; const s = (ozState.vstFxChain || []).find(x => x.path === ozState.gui_open_path); if (!s || !window.SonicAPI || !window.SonicAPI.openFxGui) return; - window.SonicAPI.openFxGui({ path: s.path, name: ozState.gui_open_name || s.name || s.path, embed: true, shm: fxRt.sessionId || '' }).then(r => { + window.SonicAPI.openFxGui({ path: s.path, name: ozState.gui_open_name || s.name || s.path, embed: true, shm: fxRt.sessionId || '', preset_b64: _capturedPresetByPath[s.path] || s.preset_b64 || '' }).then(r => { if (r && r.embed_url) setMasterGuiOpen({ path: s.path, url: r.embed_url }); }).catch(() => {}); // eslint-disable-next-line react-hooks/exhaustive-deps @@ -13290,7 +13439,7 @@ const MasteringModal = ({ isOpen, onClose, masteringSettings, setMasteringSettin const toggleMasterVst = (idx) => setMasterVstChain(masterVstChain.map((s, i) => i === idx ? { ...s, bypass: !s.bypass } : s)); const removeMasterVst = (idx) => { const rem = masterVstChain[idx]; if (rem) delete _capturedPresetByPath[rem.path]; setMasterVstChain(masterVstChain.filter((_, i) => i !== idx)); }; const moveMasterVst = (idx, dir) => { const j = idx + dir; if (j < 0 || j >= masterVstChain.length) return; const next = [...masterVstChain]; const mv = next.splice(idx, 1)[0]; next.splice(j, 0, mv); setMasterVstChain(next); }; - const openMasterVstGui = (s) => { if (!s || !s.path) { window.showToast && window.showToast('Chọn VST FX trước', 'warning'); return; } if (masterGuiOpen) closeMasterGui(); if (s.path) setActiveMasterVstPath(s.path); if (!window.SonicAPI || !window.SonicAPI.openFxGui) { window.showToast && window.showToast('Máy này không hỗ trợ mở GUI VST', 'warning'); return; } window.SonicAPI.openFxGui({ path: s.path, name: s.name || s.path, embed: true, shm: fxRt.sessionId || '' }).then(r => { if (r && r.embed_url) { setMasterGuiOpen({ path: s.path, url: r.embed_url, name: s.name || s.path }); setOzState(prev => ({ ...(prev || {}), gui_open_path: s.path, gui_open_name: s.name || s.path })); } else if (r && r.already_running && r.embed_url) { setMasterGuiOpen({ path: s.path, url: r.embed_url, name: s.name || s.path }); setOzState(prev => ({ ...(prev || {}), gui_open_path: s.path, gui_open_name: s.name || s.path })); } else if (r && r.already_running) window.showToast && window.showToast('GUI của plugin này đang mở sẵn (cửa sổ ngoài)', 'info'); else window.showToast && window.showToast('Không mở được GUI embed', 'error'); }).catch(err => window.showToast && window.showToast('Lỗi mở GUI: ' + (err.message || err), 'error')); }; + const openMasterVstGui = (s) => { if (!s || !s.path) { window.showToast && window.showToast('Chọn VST FX trước', 'warning'); return; } if (masterGuiOpen) closeMasterGui(); if (s.path) setActiveMasterVstPath(s.path); if (!window.SonicAPI || !window.SonicAPI.openFxGui) { window.showToast && window.showToast('Máy này không hỗ trợ mở GUI VST', 'warning'); return; } window.SonicAPI.openFxGui({ path: s.path, name: s.name || s.path, embed: true, shm: fxRt.sessionId || '', preset_b64: _capturedPresetByPath[s.path] || s.preset_b64 || '' }).then(r => { if (r && r.embed_url) { setMasterGuiOpen({ path: s.path, url: r.embed_url, name: s.name || s.path }); setOzState(prev => ({ ...(prev || {}), gui_open_path: s.path, gui_open_name: s.name || s.path })); } else if (r && r.already_running && r.embed_url) { setMasterGuiOpen({ path: s.path, url: r.embed_url, name: s.name || s.path }); setOzState(prev => ({ ...(prev || {}), gui_open_path: s.path, gui_open_name: s.name || s.path })); } else if (r && r.already_running) window.showToast && window.showToast('GUI của plugin này đang mở sẵn (cửa sổ ngoài)', 'info'); else window.showToast && window.showToast('Không mở được GUI embed', 'error'); }).catch(err => window.showToast && window.showToast('Lỗi mở GUI: ' + (err.message || err), 'error')); }; const addMasterVst = (path) => { const fx = (masterFxList || []).find(f => f.path === path); if (!fx) return; setMasterVstChain([...masterVstChain, { type: 'vst3', path: fx.path, name: fx.name || fx.id, preset_b64: '', bypass: false }]); openMasterVstGui({ path: fx.path, name: fx.name || fx.id }); }; const changeMasterVstPlugin = (idx, path) => { const fx = (masterFxList || []).find(f => f.path === path); delete _capturedPresetByPath[path]; setMasterVstChain(masterVstChain.map((s, i) => i === idx ? { ...s, path, name: fx ? (fx.name || fx.id) : s.name, preset_b64: '' } : s)); }; @@ -19052,7 +19201,7 @@ const App = () => { // masterConnected nhưng fxRt không tự dừng → tắt PWR mà âm không đổi. try { if (fxRtChain().length) { fxRtStart(); } - else if (fxRt.active) { fxRtStop(); } + else if (fxRt.active || fxRt.starting) { fxRtStop(); } } catch (e) { console.warn('[FX RT] resync fail:', e); } // Re-sync live track routes: mastering ON → mọi track qua chain (♪ bị // override bởi effMidiBypass/effAudioBypass) — nút PWR bật/tắt phải áp @@ -23684,11 +23833,11 @@ const App = () => { 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), paramsBySlot: chain.map(s => fxRtEntryParams(s, null)), inQueue: [], pumpTimer: null }; + const entry = { sessionId: st.session_id, ws: null, node: null, ready: false, path, spliced: null, chainKey: fxRtTrackChainKey(chain), 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=202608212401`); + await ctx.audioWorklet.addModule(`${API_BASE_URL}/static/js/sf-fx-realtime.js?v=202608241200`); const node = new AudioWorkletNode(ctx, 'sf-fx-realtime', { numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [2] }); entry.node = node; const u = new URL(API_BASE_URL); @@ -23725,16 +23874,34 @@ const App = () => { } if (d.type !== 'in') return; // Burst 4 block (1024 mẫu) → tách 4 WS frame 512 floats → bridge batch 4. - if (ws.readyState === 1) { - try { - const f = new Float32Array(d.data); - if (f.length > 512) { - for (let i = 0; i < f.length; i += 512) ws.send(f.slice(i, i + 512).buffer); - } else { - ws.send(d.data); + // 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 < f.length; i += 512) entry.ws.send(f.slice(i, i + 512).buffer); + } else { + entry.ws.send(dd.data); + } + } catch (e) {} } - } catch (e) {} - } + } + if (entry.inQueue.length) { + if (entry.pumpTimer) clearTimeout(entry.pumpTimer); + entry.pumpTimer = setTimeout(pump, Math.max(1, FXRT_BURST_MS - (now - entry.lastInSent))); + } else if (entry.pumpTimer) { + clearTimeout(entry.pumpTimer); + entry.pumpTimer = null; + } + }; + pump(); }; } catch (e) { console.warn('[FX RT track] setup fail', trackId, path, e); @@ -23750,6 +23917,23 @@ const App = () => { 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 + // atomic khi worker load xong) → load VST FX / đổi preset GUI không ngắt + // âm/crackle. entry.chainKey cập nhật ngay — reconcile sau đó thấy khớp. + const fxRtTrackSetChain = (trackId, path, track, chainKey) => { + const key = trackId + ':' + path; + const entry = fxRtTracks[key]; + if (!entry || !entry.ws || entry.ws.readyState !== 1) return; + const chain = fxRtTrackChain(track); + if (!chain.length) 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: false } + : { type: 'builtin', id: s.type, params: (s.params && Object.keys(s.params).length ? s.params : {}), bypass: false }); + entry.chainKey = chainKey; + window.SonicAPI.fxRealtimeSetChain({ session_id: entry.sessionId, fx_chain: chainPayload }).then(() => { + try { (entry.paramsBySlot || []).forEach((pl, slot) => pl.forEach(p => { if (entry.ws && entry.ws.readyState === 1) entry.ws.send(JSON.stringify({ cmd: 'set_param', slot, key: p.key, value: p.value })); })); } catch (e) {} + }).catch(e => console.warn('[FX RT track] set-chain fail', trackId, path, e)); + }; const fxRtTrackSplice = (trackId, path) => { const key = trackId + ':' + path; const entry = fxRtTracks[key]; @@ -23800,7 +23984,14 @@ const App = () => { const key = trackId + ':' + p; const entry = fxRtTracks[key]; if (!entry) fxRtTrackStart(trackId, track, p); - else if (entry.chainKey !== chainKey) { fxRtTrackStop(trackId, p, true); fxRtTrackStart(trackId, track, p); } + else if (entry.chainKey !== chainKey) { + // Chain đổi (load/đổi VST FX, preset GUI, bypass slot) — session + // đang chạy → set_chain KHÔNG restart (bridge swap atomic khi load + // xong) → hết crackle khi load VST / chỉnh thông số. Session chưa + // ready (start in-flight) → stop+start lại cho đúng chain. + if (entry.ready) fxRtTrackSetChain(trackId, track, p, chainKey); + else { fxRtTrackStop(trackId, p, true); fxRtTrackStart(trackId, track, p); } + } else if (entry.ready && node) { fxRtTrackUnsplice(trackId, p); // chain mới (sau rebuild) — splice lại đúng mods fxRtTrackSplice(trackId, p); diff --git a/app/static/js/app.precompiled.js b/app/static/js/app.precompiled.js index 4eed221..0c95440 100644 --- a/app/static/js/app.precompiled.js +++ b/app/static/js/app.precompiled.js @@ -189,7 +189,12 @@ const limInput=ctx.createGain();const limNode=ctx.createWaveShaper();limNode.ove const excInput=ctx.createGain();const excHp=ctx.createBiquadFilter();excHp.type='highpass';excHp.frequency.value=clampF(2000);excHp.Q.value=0.7;const excShaper=ctx.createWaveShaper();excShaper.curve=makeDistortionCurve(3);excShaper.oversample='4x';const excDry=ctx.createGain();excDry.gain.value=1.0;const excWet=ctx.createGain();excWet.gain.value=0.0;const excOutput=ctx.createGain();excInput.connect(excDry);excDry.connect(excOutput);excInput.connect(excHp);excHp.connect(excShaper);excShaper.connect(excWet);excWet.connect(excOutput);// ── Master Rebalance module (M/S gains via L/R crossfeed) ── const rebalInput=ctx.createGain();const rebalSplit=ctx.createChannelSplitter(2);const rebalMerge=ctx.createChannelMerger(2);const rebalOutput=ctx.createGain();const gLLr=ctx.createGain();const gRLr=ctx.createGain();const gLRr=ctx.createGain();const gRRr=ctx.createGain();rebalInput.connect(rebalSplit);rebalSplit.connect(gLLr,0);rebalSplit.connect(gRLr,0);rebalSplit.connect(gLRr,1);rebalSplit.connect(gRRr,1);gLLr.connect(rebalMerge,0,0);gRLr.connect(rebalMerge,0,0);gLRr.connect(rebalMerge,0,1);gRRr.connect(rebalMerge,0,1);rebalMerge.connect(rebalOutput);// Setup Analysers const inputAnalyser=ctx.createAnalyser();inputAnalyser.fftSize=2048;const outputAnalyser=ctx.createAnalyser();outputAnalyser.fftSize=2048;// Global fader / output -const output=ctx.createGain();output.gain.value=1.0;// Per-track mastering-bypass dry bus: tracks with bypass ON feed into +const output=ctx.createGain();output.gain.value=1.0;// Crossfade master-FX activation (het click khi bat/tat master chain FX): +// path mac dinh outputAnalyser -> masterFxDryGain(1) -> pdcDelay -> output; +// nhanh FX noi vao masterFxGain(0) -> output. fxRtStart/fxRtStop ramp 2 gain +// nay thay vi hard-rewire graph (dry path luon noi san — no click, no gap +// trong luc worklet FILL ~86ms). +const masterFxDryGain=ctx.createGain();masterFxDryGain.gain.value=1.0;const masterFxGain=ctx.createGain();masterFxGain.gain.value=0.0;// Per-track mastering-bypass dry bus: tracks with bypass ON feed into // dryInput -> dryOutput -> output, skipping the mastering modules // (EQ / Imager / Maximizer) while still passing the master volume fader // and the master output metering. @@ -199,7 +204,7 @@ const dryInput=ctx.createGain();const dryOutput=ctx.createGain();dryInput.connec const pdcDelay=ctx.createDelay(5.0);pdcDelay.delayTime.value=0;dryOutput.connect(pdcDelay);pdcDelay.connect(output);const analyser=ctx.createAnalyser();analyser.fftSize=256;const leftAnalyser=ctx.createAnalyser();leftAnalyser.fftSize=2048;const rightAnalyser=ctx.createAnalyser();rightAnalyser.fftSize=2048;const splitter=ctx.createChannelSplitter(2);splitter.connect(leftAnalyser,0);splitter.connect(rightAnalyser,1);// Master L/R volume + MUTE stage (spec §2: L/R fader + LINK + MUTE master). // output -> volSplit -> volLGain/volRGain -> volMerge -> muteGain -> analyser; // meters (splitter) lay sau muteGain -> MUTE that (VU ve 0). -const volSplit=ctx.createChannelSplitter(2);const volLGain=ctx.createGain();volLGain.gain.value=1.0;const volRGain=ctx.createGain();volRGain.gain.value=1.0;const volMerge=ctx.createChannelMerger(2);const muteGain=ctx.createGain();muteGain.gain.value=1.0;output.connect(volSplit);volSplit.connect(volLGain,0);volSplit.connect(volRGain,1);volLGain.connect(volMerge,0,0);volRGain.connect(volMerge,0,1);volMerge.connect(muteGain);masterBus={input:ctx.createGain(),compressor:ctx.createDynamicsCompressor(),analyser,output,masteringActive:false,dryInput,dryOutput,pdcDelay,splitter,volSplit,volLGain,volRGain,volMerge,muteGain,// Analysers for metering +const volSplit=ctx.createChannelSplitter(2);const volLGain=ctx.createGain();volLGain.gain.value=1.0;const volRGain=ctx.createGain();volRGain.gain.value=1.0;const volMerge=ctx.createChannelMerger(2);const muteGain=ctx.createGain();muteGain.gain.value=1.0;output.connect(volSplit);volSplit.connect(volLGain,0);volSplit.connect(volRGain,1);volLGain.connect(volMerge,0,0);volRGain.connect(volMerge,0,1);volMerge.connect(muteGain);masterBus={input:ctx.createGain(),compressor:ctx.createDynamicsCompressor(),analyser,output,masterFxDryGain,masterFxGain,masteringActive:false,dryInput,dryOutput,pdcDelay,splitter,volSplit,volLGain,volRGain,volMerge,muteGain,// Analysers for metering inputAnalyser,outputAnalyser,leftAnalyser,rightAnalyser,// Mastering nodes eqLowFilter,eqMid1Filter,eqMid2Filter,eqHighFilter,imagerInput,imagerOutput,gainLL1,gainRL1,gainLR1,gainRR1,gainLL2,gainRL2,gainLR2,gainRR2,gainLL3,gainRL3,gainLR3,gainRR3,gainLL4,gainRL4,gainLR4,gainRR4,maximizerBoostGain,maximizerSoftClipper,upwardCompressor,upwardGain,upwardSummingGain,maximizerCompressor,// Extension modules (mastering_expand.md §II.2) compInput,compNode,compMakeup,compOutput,limInput,limNode,limOutput,excInput,excHp,excShaper,excDry,excWet,excOutput,rebalInput,rebalSplit,rebalMerge,gLLr,gRLr,gLRr,gRRr,rebalOutput};// Connect EQ chain (internal — the module BOUNDARIES are wired dynamically @@ -209,7 +214,7 @@ eqLowFilter.connect(eqMid1Filter);eqMid1Filter.connect(eqMid2Filter);eqMid2Filte // Compressor mặc định (ratio 12, threshold -24 — LUÔN-ON) vừa (a) pump-down // tín hiệu → âm nhỏ/méo, vừa (b) phát NaN khi gặp bass transient → 11 biquad // "state is bad" → CÂM + stuck. Mastering chain có comp/lim module riêng khi bật. -masterBus.input.connect(masterBus.inputAnalyser);masterBus.inputAnalyser.connect(masterBus.outputAnalyser);masterBus.outputAnalyser.connect(masterBus.output);masterBus.muteGain.connect(masterBus.analyser);masterBus.muteGain.connect(masterBus.splitter);masterBus.analyser.connect(ctx.destination);window.masterBus=masterBus;// Apply mastering once when the chain is first created (and on the +masterBus.input.connect(masterBus.inputAnalyser);masterBus.inputAnalyser.connect(masterBus.outputAnalyser);masterBus.outputAnalyser.connect(masterBus.masterFxDryGain);masterBus.masterFxDryGain.connect(masterBus.pdcDelay);masterBus.outputAnalyser.connect(masterBus.masterFxGain);masterBus.masterFxGain.connect(masterBus.output);masterBus.muteGain.connect(masterBus.analyser);masterBus.muteGain.connect(masterBus.splitter);masterBus.analyser.connect(ctx.destination);window.masterBus=masterBus;// Apply mastering once when the chain is first created (and on the // masteringSettings effect for subsequent changes — see useEffect). if(window.currentMasteringSettings){try{// Reset sig-cache: chain MỚI (biquad/maximizer node mới) giữ giá trị // INIT (gain 0, width 100…) — applyMasteringSettings early-return vì @@ -273,7 +278,12 @@ const len=Math.floor(pcm.length/channels);const bps=4;const dataBytes=len*bps*ch // worklet → analyser (sau master fader, trước metering/destination — khớp thứ // tự offline export). Track: mỗi track 1 session/worklet splice vào CẢ 2 đường // chain (audio-clips + MIDI/SF) — mọi luồng track qua bridge trước main out. -const fxRt={active:false,sessionId:null,ws:null,node:null,inQueue:[],pumpTimer:null,chainKey:null,latencyTotal:0};// Signature của chain VST realtime — phát hiện chain ĐỔI (insert/remove/bypass/ +const fxRt={active:false,starting:false,startToken:0,sessionId:null,ws:null,node:null,inQueue:[],pumpTimer:null,lastInSent:0,chainKey:null,latencyTotal:0,fadedIn:false};// Pace input realtime: worklet sản xuất đúng realtime, nhưng sau khi main +// thread bị block (solo restart, GUI decode, rAF) các frame 'in' dồn lại — +// gửi 1 loạt làm SHM ring 4-slot tràn → mất block → ngắt quãng. Gửi tối đa 1 +// burst (4 block ~21ms) mỗi 21ms → ring luôn kịp tiêu thụ, audio hồi phục +// trơn sau stall (FILL hấp thụ phần đầu). +const FXRT_BURST_MS=21;// Signature của chain VST realtime — phát hiện chain ĐỔI (insert/remove/bypass/ // reorder VST) → restart session với chain mới (fxRtStart early-return khi // active, nếu không so chainKey thì VST mới insert không bao giờ được áp). function fxRtChainKey(chain){return(chain||[]).map(s=>(s.type||'')+':'+(s.type==='vst3'?(s.path||'')+'#'+(s.preset_b64||'').slice(0,16):s.type||'')).join('|');}function fxRtChain(){const ms=window.currentMasteringSettings;if(!ms||!ms.masterConnected||ms.isBypassed)return[];// Chain hợp nhất (builtin + vst3 theo UI order) — mọi slot active gửi bridge. @@ -282,24 +292,51 @@ function fxRtChainKey(chain){return(chain||[]).map(s=>(s.type||'')+':'+(s.type== // default (passthrough) → power ON nghe như OFF. Merge ở đây làm chainKey đổi // → fxRtStart tự restart session với preset thật. return(ms.chain||[]).filter(s=>s&&s.active!==false&&(s.type!=='vst3'||!ms.vstBypass&&s.path&&!s.bypass)).map(s=>s.type==='vst3'&&_capturedPresetByPath[s.path]?{...s,preset_b64:_capturedPresetByPath[s.path]}:s);}// Param master chain entry → C++ BuiltinFx key (mirror Python _BUILTIN_PARAM_MAP). -const FX_RT_PARAM_MAP={eq:[['g1','eqLowGain'],['g2','eqMid1Gain'],['g3','eqMid2Gain'],['g4','eqHighGain']],compressor:[['threshold','compThreshold'],['ratio','compRatio'],['makeup','compMakeup']],limiter:[['ceiling','limThreshold'],['mode','limMode'],['lookahead_ms','limLookahead']],exciter:[['drive','excDrive']],rebalance:[['mid','rebalMid'],['side','rebalSide']],imager:[['w1','w1'],['w2','w2'],['w3','w3'],['w4','w4']],maximizer:[['boost_db','maxGain'],['soft_clip','maxSoftClip'],['upward','maxUpward'],['ceiling_db','ceiling']]};function fxRtEntryParams(entry,ms){const out=[];if(!entry||entry.type==='vst3')return out;const src=ms||window.currentMasteringSettings||{};const push=(k,v)=>{const n=Number(v);if(isFinite(n))out.push({key:k,value:n});};const map=FX_RT_PARAM_MAP[entry.type]||[];map.forEach(([cppKey,jsKey])=>{if(entry.params&&entry.params[cppKey]!==undefined)push(cppKey,entry.params[cppKey]);else if(entry.params&&entry.params[jsKey]!==undefined)push(jsKey,entry.params[jsKey]);else if(src[jsKey]!==undefined)push(cppKey,src[jsKey]);});if(entry.type==='eqpro'){if(entry.params&&entry.params.amount!==undefined)push('amount',entry.params.amount);const bands=entry.params&&entry.params.bands||[];bands.forEach((b,i)=>{['freq','gain','q'].forEach(k=>{if(b&&b[k]!==undefined)push('band'+i+'_'+k,b[k]);});});}return out;}function fxRtPushAllParams(){if(!fxRt||!fxRt.ws||fxRt.ws.readyState!==1)return;const chain=fxRtChain();chain.forEach((s,i)=>{fxRtEntryParams(s,null).forEach(p=>{try{fxRt.ws.send(JSON.stringify({cmd:'set_param',slot:i,key:p.key,value:p.value}));}catch(e){}});});}async function fxRtStart(){const chain=fxRtChain();const ck=fxRtChainKey(chain);if(fxRt.active){// masterBus bị rebuild (recovery/export) → node thuộc graph cũ → restart. -if(!fxRt.node||fxRt.node.context!==getAudioContext())fxRtStop(true);// Chain VST thay đổi (insert/remove/bypass/reorder trong MASTER FX CHAIN) -// → stop + start lại để bridge load đúng chuỗi FX mới. -else if(fxRt.chainKey!==ck)fxRtStop(true);else return;}if(!chain.length)return;const ctx=getAudioContext();if(!ctx||!ctx.audioWorklet||!masterBus||!masterBus.output||!masterBus.analyser)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:false}:{type:'builtin',id:s.type,params:s.params&&Object.keys(s.params).length?s.params:{},bypass:false});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');return;}fxRt.sessionId=st.session_id;fxRtGuiPushShm();try{await ctx.audioWorklet.addModule(`${API_BASE_URL}/static/js/sf-fx-realtime.js?v=202608212401`);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=()=>{fxRt.active=true;fxRt.inQueue=[];// bỏ audio stale sản xuất trước khi WS open (~4s load VST) — hết lag khởi đầu +const FX_RT_PARAM_MAP={eq:[['g1','eqLowGain'],['g2','eqMid1Gain'],['g3','eqMid2Gain'],['g4','eqHighGain']],compressor:[['threshold','compThreshold'],['ratio','compRatio'],['makeup','compMakeup']],limiter:[['ceiling','limThreshold'],['mode','limMode'],['lookahead_ms','limLookahead']],exciter:[['drive','excDrive']],rebalance:[['mid','rebalMid'],['side','rebalSide']],imager:[['w1','w1'],['w2','w2'],['w3','w3'],['w4','w4']],maximizer:[['boost_db','maxGain'],['soft_clip','maxSoftClip'],['upward','maxUpward'],['ceiling_db','ceiling']]};function fxRtEntryParams(entry,ms){const out=[];if(!entry||entry.type==='vst3')return out;const src=ms||window.currentMasteringSettings||{};const push=(k,v)=>{const n=Number(v);if(isFinite(n))out.push({key:k,value:n});};const map=FX_RT_PARAM_MAP[entry.type]||[];map.forEach(([cppKey,jsKey])=>{if(entry.params&&entry.params[cppKey]!==undefined)push(cppKey,entry.params[cppKey]);else if(entry.params&&entry.params[jsKey]!==undefined)push(jsKey,entry.params[jsKey]);else if(src[jsKey]!==undefined)push(cppKey,src[jsKey]);});if(entry.type==='eqpro'){if(entry.params&&entry.params.amount!==undefined)push('amount',entry.params.amount);const bands=entry.params&&entry.params.bands||[];bands.forEach((b,i)=>{['freq','gain','q'].forEach(k=>{if(b&&b[k]!==undefined)push('band'+i+'_'+k,b[k]);});});}return out;}function fxRtPushAllParams(){if(!fxRt||!fxRt.ws||fxRt.ws.readyState!==1)return;const chain=fxRtChain();chain.forEach((s,i)=>{fxRtEntryParams(s,null).forEach(p=>{try{fxRt.ws.send(JSON.stringify({cmd:'set_param',slot:i,key:p.key,value:p.value}));}catch(e){}});});}async function fxRtSetChain(chain){const sid=fxRt.sessionId;if(!sid||!fxRt.ws||fxRt.ws.readyState!==1)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:false}:{type:'builtin',id:s.type,params:s.params&&Object.keys(s.params).length?s.params:{},bypass:false});try{await window.SonicAPI.fxRealtimeSetChain({session_id:sid,fx_chain:chainPayload});try{fxRtPushAllParams();}catch(e){}}catch(e){console.warn('[FX RT] set-chain fail:',e);}}async function fxRtStart(){const chain=fxRtChain();const ck=fxRtChainKey(chain);if(fxRt.active){// masterBus bị rebuild (recovery/export) → node thuộc graph cũ → restart. +if(!fxRt.node||fxRt.node.context!==getAudioContext())fxRtStop(true);// Chain thay đổi (insert/remove/bypass/reorder/preset GUI) — KHÔNG restart +// (ngắt âm + crackle): set_chain lên session ĐANG CHẠY → bridge worker +// load chain mới (audio giữ chain cũ tới khi swap) → swap atomic mượt. +else if(fxRt.chainKey!==ck){fxRtSetChain(chain);fxRt.chainKey=ck;return;}else return;}if(!chain.length)return;// 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 +// `else if (fxRt.active) fxRtStop()` KHÔNG chạy → start in-flight vẫn nối +// 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:false}:{type:'builtin',id:s.type,params:s.params&&Object.keys(s.params).length?s.params:{},bypass:false});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=202608241200`);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;fxRtApplyPdc();}}catch(e){}return;}if(!(ev.data instanceof ArrayBuffer)||!fxRt.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;ifxRtStop(true);ws.onerror=()=>{try{ws.close();}catch(e){}};fxRt.node.port.onmessage=ev=>{const d=ev.data;if(!d||!fxRt.ws)return;if(d.type==='set_param'){try{fxRt.ws.send(JSON.stringify({cmd:'set_param',slot:d.slot,key:d.key,value:d.value}));}catch(e){}return;}if(d.type!=='in')return;// Worklet gom 4 block (1024 mẫu) vào 1 frame → tách 4 WS frame 512 floats +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 +// trong luc dry con la path nghe duoc se tao gap ~80ms. +if(fxRt.fadedIn)fxRtApplyPdc();}}catch(e){}return;}if(!(ev.data instanceof ArrayBuffer)||!fxRt.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;ifxRtStop(true);ws.onerror=()=>{try{ws.close();}catch(e){}};// Worklet gom 4 block (1024 mẫu) vào 1 frame → tách 4 WS frame 512 floats // ở đây. Bridge VST3 nhận input dồn → take=4 → batch 1 call process 1024 // mẫu (~3.5-4.75ms/block) → đủ 187.5/s (take=1: 5.5ms > budget 5.33ms → // drop → crackle). KHÔNG dùng f.subarray().buffer — nó gửi cả backing // buffer 8192B; slice() copy đúng 2048B. -if(ws.readyState===1){try{const f=new Float32Array(d.data);if(f.length>512){for(let i=0;i{if(!fxRt.ws||fxRt.ws.readyState!==1)return;try{const f=new Float32Array(d.data);if(f.length>512){for(let i=0;i{if(!fxRt.inQueue.length)return;const now=Date.now();while(fxRt.inQueue.length&&now-fxRt.lastInSent>=FXRT_BURST_MS){fxRt.lastInSent=now;fxRtSendFrames(fxRt.inQueue.shift());}if(fxRt.inQueue.length){if(fxRt.pumpTimer)clearTimeout(fxRt.pumpTimer);fxRt.pumpTimer=setTimeout(fxRtInPump,Math.max(1,FXRT_BURST_MS-(now-fxRt.lastInSent)));}else if(fxRt.pumpTimer){clearTimeout(fxRt.pumpTimer);fxRt.pumpTimer=null;}};fxRt.node.port.onmessage=ev=>{const d=ev.data;if(!d||!fxRt.ws)return;if(d.type==='started'){// Worklet bat dau phat (sau FILL) -> crossfade dry->fx muot. Token guard +// chong race: neu stop/restart xay ra trong luc cho, bo qua. +if(fxRt.fadedIn)return;setTimeout(()=>{if(token!==fxRt.startToken)return;fxRt.fadedIn=true;fxRtCrossfade(true,token);// Dry gan silent (tc 0.025) roi moi tre pdcDelay — tranh gap khi delay +// dang lon dan. +setTimeout(()=>fxRtApplyPdc(),250);},30);return;}if(d.type==='set_param'){try{fxRt.ws.send(JSON.stringify({cmd:'set_param',slot:d.slot,key:d.key,value:d.value}));}catch(e){}return;}if(d.type!=='in')return;fxRt.inQueue.push(d);fxRtInPump();};// Pace input: tối đa 1 block/kỳ (~5.8ms). Gửi dồn theo burst (main thread bị // rAF renderFrame block khi mở MASTERING PANEL) → SHM ring 4-slot tràn → mất // block → ngắt quãng. // Phase 4.2: fader SAU worklet — worklet chèn giữa outputAnalyser (chain // output) và output (fader/destination). output → analyser/splitter giữ // nguyên (meter đo âm SAU fader). -try{masterBus.outputAnalyser.disconnect(masterBus.output);}catch(e){}masterBus.outputAnalyser.connect(fxRt.node);fxRt.node.connect(masterBus.output);fxRt.chainKey=ck;}catch(e){console.warn('[FX RT] setup fail:',e);fxRtStop(true);}}function fxRtStop(silent){if(fxRt.pumpTimer){clearInterval(fxRt.pumpTimer);fxRt.pumpTimer=null;}fxRt.inQueue=[];if(!fxRt.active&&!fxRt.ws&&!fxRt.node&&!fxRt.sessionId)return;try{if(fxRt.node){fxRt.node.disconnect();if(masterBus&&masterBus.outputAnalyser&&masterBus.output){try{masterBus.outputAnalyser.disconnect(masterBus.output);}catch(e){}try{masterBus.outputAnalyser.connect(masterBus.output);}catch(e){}}fxRt.node.port.onmessage=null;fxRt.node=null;}}catch(e){}try{if(fxRt.ws){fxRt.ws.onclose=null;fxRt.ws.onmessage=null;try{fxRt.ws.close();}catch(e){}fxRt.ws=null;}}catch(e){}const sid=fxRt.sessionId;fxRt.sessionId=null;fxRtGuiPushShm();fxRt.active=false;fxRt.chainKey=null;fxRt.latencyTotal=0;fxRtApplyPdc();if(sid){try{window.SonicAPI.fxRealtimeStop({session_id:sid}).catch(()=>{});}catch(e){}}}// ── Gap 8: PDC realtime — bù delay dry-bypass path (master chain) ────────── +// Crossfade activation: KHONG disconnect dry path — outputAnalyser van noi +// masterFxDryGain -> pdcDelay -> output (gain 1); nhanh fx noi masterFxGain +// (gain 0) -> output. Tin hieu 'started' tu worklet -> ramp 2 gain -> switch +// muot, het click hard-rewire. +try{masterBus.outputAnalyser.disconnect(masterBus.output);}catch(e){}masterBus.outputAnalyser.connect(fxRt.node);fxRt.node.connect(masterBus.masterFxGain);fxRt.chainKey=ck;}catch(e){console.warn('[FX RT] setup fail:',e);fxRtStop(true);}}function fxRtStop(silent){// Phải bump token TRƯỚC guard early-return: lúc fxRtStart đang in-flight thì +// active/ws/node/sessionId đều chưa có → guard sẽ return, nhưng start vẫn +// phải bị hủy (token mismatch ở checkpoint). +fxRt.startToken++;fxRt.starting=false;if(fxRt.pumpTimer){clearInterval(fxRt.pumpTimer);fxRt.pumpTimer=null;}fxRt.inQueue=[];if(!fxRt.active&&!fxRt.ws&&!fxRt.node&&!fxRt.sessionId)return;let _fxStopNode=null;try{if(fxRt.node){_fxStopNode=fxRt.node;if(masterBus&&masterBus.masterFxGain&&masterBus.masterFxDryGain){// Crossfade deactivation: ramp dry 0->1 / fx 1->0 roi MOI disconnect +// (tranh click hard-switch nguoc). Dry path da noi san qua +// masterFxDryGain — khong can reconnect outputAnalyser->output. PDC giam +// ve 0 sau khi dry chiem cho (fx silent). +try{fxRtCrossfade(false);}catch(e){}setTimeout(()=>{try{_fxStopNode.disconnect();}catch(e){}_fxStopNode.port.onmessage=null;if(fxRt.node===_fxStopNode)fxRt.node=null;fxRt.fadedIn=false;fxRtApplyPdc();},180);}else{// Fallback graph cu (khong co crossfade gains) — hard switch nhu cu. +try{_fxStopNode.disconnect();}catch(e){}if(masterBus&&masterBus.outputAnalyser&&masterBus.output){try{masterBus.outputAnalyser.connect(masterBus.output);}catch(e){}}_fxStopNode.port.onmessage=null;if(fxRt.node===_fxStopNode)fxRt.node=null;}}}catch(e){}try{if(fxRt.ws){fxRt.ws.onclose=null;fxRt.ws.onmessage=null;try{fxRt.ws.close();}catch(e){}fxRt.ws=null;}}catch(e){}const sid=fxRt.sessionId;fxRt.sessionId=null;fxRtGuiPushShm();fxRt.active=false;fxRt.chainKey=null;fxRt.latencyTotal=0;// PDC giam ve 0 sau khi dry chiem cho (trong setTimeout cua nhanh crossfade) +// hoac ngay neu khong co node — khong goi tai day de tranh gap 80ms. +if(!_fxStopNode)fxRtApplyPdc();if(sid){try{window.SonicAPI.fxRealtimeStop({session_id:sid}).catch(()=>{});}catch(e){}}}// ── Gap 8: PDC realtime — bù delay dry-bypass path (master chain) ────────── // Master chain (worklet → bridge VST3) trễ ~2 block round-trip + latency // plugin. Track bypass mastering đi dry path (dryInput→dryOutput→output) KHÔNG // qua worklet → lệch pha với mastered. fxRtApplyPdc trễ dry path đúng lượng @@ -307,7 +344,9 @@ try{masterBus.outputAnalyser.disconnect(masterBus.output);}catch(e){}masterBus.o // (tag seq trên block) khi cần sample-accurate. // RTT = batching 4 block (~7 block @48k ≈ 1792) + FILL buffer 8 block (2048) // — worklet chỉ phát khi queue ≥ FILL → latency tĩnh thêm FILL → 15 block. -const FX_RT_ROUNDTRIP_SAMPLES=3840;function fxRtApplyPdc(){const ctx=getAudioContext();const bus=masterBus;if(!ctx||!bus||!bus.pdcDelay)return;const l=fxRt&&fxRt.active?FX_RT_ROUNDTRIP_SAMPLES+(fxRt.latencyTotal||0):0;try{bus.pdcDelay.delayTime.setTargetAtTime(l/(ctx.sampleRate||44100),ctx.currentTime,0.05);}catch(e){}}// ── Realtime VST FX per-track (SHM bridge) — mọi luồng track qua bridge ───── +const FX_RT_ROUNDTRIP_SAMPLES=3840;function fxRtApplyPdc(){const ctx=getAudioContext();const bus=masterBus;if(!ctx||!bus||!bus.pdcDelay)return;const l=fxRt&&fxRt.active?FX_RT_ROUNDTRIP_SAMPLES+(fxRt.latencyTotal||0):0;try{bus.pdcDelay.delayTime.setTargetAtTime(l/(ctx.sampleRate||44100),ctx.currentTime,0.05);}catch(e){}}// Crossfade master-FX switch: ramp masterFxGain/masterFxDryGain thay vi +// hard-rewire (click). Hai gain nay duoc tao trong initMasterBus. +function fxRtCrossfade(toFx,token){const ctx=getAudioContext();const bus=masterBus;if(!ctx||!bus||!bus.masterFxGain||!bus.masterFxDryGain)return;if(token!==undefined&&token!==fxRt.startToken)return;const tc=0.025;try{bus.masterFxGain.gain.setTargetAtTime(toFx?1:0,ctx.currentTime,tc);bus.masterFxDryGain.gain.setTargetAtTime(toFx?0:1,ctx.currentTime,tc);}catch(e){}}// ── Realtime VST FX per-track (SHM bridge) — mọi luồng track qua bridge ───── // Mỗi track: session riêng (1 WS/SHM) cho TỪNG đường chain có âm — audio-clips // (path 'audio', splice fxEntry→mods→worklet→fxLegacyIn) và MIDI/SF (path 'sf', // splice sfEntry→mods→worklet→sfOut). Track vừa clips vừa MIDI → 2 session @@ -369,7 +408,7 @@ const RefCompareModal=({open,onClose})=>{const[path,setPath]=React.useState(''); // roi play qua blob URL (Audio element khong gui duoc header). const token=localStorage.getItem('sonic_token')||'';const resp=await fetch((window.API_BASE_URL||'')+refStats.url,{headers:token?{'Authorization':'Bearer '+token}:{}});if(!resp.ok)throw new Error('HTTP '+resp.status);const blob=await resp.blob();const objUrl=URL.createObjectURL(blob);const au=new Audio(objUrl);au._objUrl=objUrl;audioRef.current=au;au.loop=true;au.play().then(()=>setAb('B')).catch(()=>{});}catch(e){window.showToast&&window.showToast('Play ref loi: '+(e.message||e),'error');}};const fmt=(v,suf)=>v===null||v===undefined?'--':v+suf;const dlt=(a,b)=>a===null||a===undefined||b===null||b===undefined?'--':(a-b>0?'+':'')+(a-b).toFixed(1);return/*#__PURE__*/React.createElement("div",{className:"fixed inset-0 z-[115] bg-black/70 backdrop-blur-sm flex items-center justify-center p-4",onClick:onClose},/*#__PURE__*/React.createElement("div",{className:"w-full max-w-md bg-slate-900 border border-slate-700 rounded-2xl p-4 space-y-3 shadow-2xl",onClick:e=>e.stopPropagation()},/*#__PURE__*/React.createElement("div",{className:"flex items-center justify-between border-b border-slate-800 pb-2"},/*#__PURE__*/React.createElement("span",{className:"text-xs font-bold text-white tracking-wider"},"A/B REFERENCE"),/*#__PURE__*/React.createElement("button",{onClick:onClose,className:"text-slate-500 hover:text-slate-300"},/*#__PURE__*/React.createElement("i",{"data-lucide":"x",className:"w-4 h-4"}))),/*#__PURE__*/React.createElement("div",{className:"flex gap-1.5"},/*#__PURE__*/React.createElement("input",{value:path,onChange:e=>setPath(e.target.value),placeholder:"Local path (media/browse) hoac file_id",className:"flex-1 bg-[#141414] border border-zinc-800 rounded px-2 py-1 text-xs text-zinc-300 focus:outline-none"}),/*#__PURE__*/React.createElement("button",{onClick:()=>path&&analyze({path}),disabled:busy,className:"px-2 py-1 bg-cyan-700 hover:bg-cyan-600 text-white rounded text-xs font-bold"},busy?'...':'Analyze')),/*#__PURE__*/React.createElement("div",{className:"text-[10px] text-slate-500 text-center"},"- hoac -"),/*#__PURE__*/React.createElement("button",{onClick:()=>fileInputRef.current&&fileInputRef.current.click(),className:"w-full py-1.5 bg-slate-800 hover:bg-slate-700 text-zinc-200 rounded text-xs font-bold border border-slate-700"},"Upload reference file"),/*#__PURE__*/React.createElement("input",{ref:fileInputRef,type:"file",accept:"audio/*,.wav,.mp3,.flac,.ogg,.aiff,.m4a,.aac,.opus",className:"hidden",onChange:e=>{const f=e.target.files&&e.target.files[0];onPickFile(f);e.target.value='';}}),(refStats||masterStats)&&/*#__PURE__*/React.createElement("div",{className:"grid grid-cols-3 gap-1.5 text-[10px] text-center"},/*#__PURE__*/React.createElement("div",{className:"bg-slate-950 border border-slate-800 rounded p-1.5"},/*#__PURE__*/React.createElement("div",{className:"text-slate-500 font-bold mb-1"},"METER"),/*#__PURE__*/React.createElement("div",{className:"text-emerald-400 font-bold"},"LUFS"),/*#__PURE__*/React.createElement("div",{className:"text-slate-300 font-bold"},"dBTP"),/*#__PURE__*/React.createElement("div",{className:"text-slate-400"},"Tone")),/*#__PURE__*/React.createElement("div",{className:"bg-slate-950 border border-slate-800 rounded p-1.5"},/*#__PURE__*/React.createElement("div",{className:"text-slate-500 font-bold mb-1"},"MASTER"),/*#__PURE__*/React.createElement("div",{className:"text-cyan-300 font-bold"},fmt(masterStats&&masterStats.lufs,'')),/*#__PURE__*/React.createElement("div",{className:"text-cyan-300 font-bold"},fmt(masterStats&&masterStats.true_peak_db,'')),/*#__PURE__*/React.createElement("div",{className:"text-slate-400"},"-")),/*#__PURE__*/React.createElement("div",{className:"bg-slate-950 border border-slate-800 rounded p-1.5"},/*#__PURE__*/React.createElement("div",{className:"text-slate-500 font-bold mb-1"},"REF"),/*#__PURE__*/React.createElement("div",{className:"text-fuchsia-300 font-bold"},fmt(refStats&&refStats.lufs,'')),/*#__PURE__*/React.createElement("div",{className:"text-fuchsia-300 font-bold"},fmt(refStats&&refStats.true_peak_db,'')),/*#__PURE__*/React.createElement("div",{className:"text-slate-400"},fmt(refStats&&refStats.centroid_hz,'Hz')))),refStats&&/*#__PURE__*/React.createElement("div",{className:"text-[10px] text-slate-400 text-center"},"Delta: LUFS ",dlt(masterStats&&masterStats.lufs,refStats.lufs)," / dBTP ",dlt(masterStats&&masterStats.true_peak_db,refStats.true_peak_db)," \xA0(+ = master louder)",/*#__PURE__*/React.createElement("div",{className:"text-[9px] text-slate-500"},refStats.filename," \xB7 ",refStats.duration,"s \xB7 ",refStats.sample_rate,"Hz \xB7 ",refStats.channels,"ch")),/*#__PURE__*/React.createElement("div",{className:"grid grid-cols-2 gap-1.5 pt-1"},/*#__PURE__*/React.createElement("button",{onClick:()=>{stopRef();setAb('A');},className:`py-1.5 rounded text-[10px] font-bold border ${ab==='A'?'bg-cyan-600 border-cyan-500 text-white':'bg-slate-800 text-slate-300 border-slate-700'}`},"A \xB7 Master"),/*#__PURE__*/React.createElement("button",{onClick:playB,disabled:!refStats,className:`py-1.5 rounded text-[10px] font-bold border ${ab==='B'?'bg-fuchsia-600 border-fuchsia-500 text-white':'bg-slate-800 text-slate-300 border-slate-700'}`},"B \xB7 Reference"))));};// ── Master Strip Console Component (from md/47_MASTER_STRIP_CONSOLE.md) ── const MasterStripConsole=({masterVolume,setMasterVolume,masterVolL,setMasterVolL,masterVolR,setMasterVolR,masterLink,setMasterLink,masterMuted,setMasterMuted,masterAutoVol,setMasterAutoVol,masterAutoOn,setMasterAutoOn,showMasteringModal,setShowMasteringModal,masteringSettings,setMasteringSettings,isPlaying})=>{const[isTestPlaying,setIsTestPlaying]=React.useState(false);const[isMono,setIsMono]=React.useState(false);const[pan,setPan]=React.useState(0.0);const[panText,setPanText]=React.useState('center');const vuCanvasRef=React.useRef(null);const animFrameRef=React.useRef(null);const rmsValRef=React.useRef(null);const peakLRef=React.useRef(null);const peakRRef=React.useRef(null);const panPointerRef=React.useRef(null);const isMasterActive=masteringSettings?masteringSettings.masterConnected:false;const panStartYRef=React.useRef(0);const startPanValRef=React.useRef(0);const[refOpen,setRefOpen]=React.useState(false);const[autoOpen,setAutoOpen]=React.useState(false);const addAutoPoint=()=>{const pts=(masterAutoVol||[]).slice();pts.push({time:Math.round(pts.reduce((m,p)=>Math.max(m,p.time||0),0)+1),db:0});setMasterAutoVol(pts);};const updAutoPoint=(i,key,val)=>{const pts=(masterAutoVol||[]).slice();pts[i]=Object.assign({},pts[i],{[key]:val});setMasterAutoVol(pts);};const delAutoPoint=i=>setMasterAutoVol((masterAutoVol||[]).filter((p,j)=>j!==i));const ensureAudio=()=>{getAudioContext();};const handleFaderChangeL=val=>{val=Math.max(-60,Math.min(12,val));ensureAudio();setMasterVolL(val);if(masterLink)setMasterVolR(Math.max(-60,Math.min(12,val+(masterVolR-masterVolL))));};const handleFaderChangeR=val=>{val=Math.max(-60,Math.min(12,val));ensureAudio();setMasterVolR(val);if(masterLink)setMasterVolL(Math.max(-60,Math.min(12,val-(masterVolR-masterVolL))));};// Double-click reset: ca 2 ve 0 -const handleFaderChange=val=>{handleFaderChangeL(val);handleFaderChangeR(val);};React.useEffect(()=>{applyMasterVolumesTo(masterBus,masterVolL,masterVolR,masterMuted);},[masterVolL,masterVolR,masterMuted]);const masterVolDisplay=masterLink?masterVolL<=-50?'-inf':(masterVolL>0?'+':'')+masterVolL.toFixed(1):'L'+(masterVolL<=-50?'-inf':masterVolL.toFixed(1))+' R'+(masterVolR<=-50?'-inf':masterVolR.toFixed(1));const handlePanPointerDown=e=>{isPanDraggingRef.current=true;panStartYRef.current=e.clientY;startPanValRef.current=pan;e.currentTarget.setPointerCapture(e.pointerId);};const handlePanPointerMove=e=>{if(!isPanDraggingRef.current)return;const deltaY=panStartYRef.current-e.clientY;let newPan=startPanValRef.current+deltaY/80;newPan=Math.min(1.0,Math.max(-1.0,newPan));setPan(newPan);const angle=newPan*120;if(panPointerRef.current)panPointerRef.current.style.transform=`rotate(${angle}deg)`;if(newPan===0)setPanText('center');else if(newPan<0)setPanText('L'+Math.abs(Math.round(newPan*100)));else setPanText('R'+Math.round(newPan*100));};const handlePanPointerUp=e=>{isPanDraggingRef.current=false;try{e.currentTarget.releasePointerCapture(e.pointerId);}catch(err){}};React.useEffect(()=>{const canvas=vuCanvasRef.current;if(!canvas)return;const ctx=canvas.getContext('2d');function render(){animFrameRef.current=requestAnimationFrame(render);canvas.width=canvas.clientWidth;canvas.height=canvas.clientHeight;const w=canvas.width;const h=canvas.height;ctx.clearRect(0,0,w,h);let levelL=0;let levelR=0;if(masterBus&&masterBus.leftAnalyser&&masterBus.rightAnalyser){const leftData=new Uint8Array(256);const rightData=new Uint8Array(256);masterBus.leftAnalyser.getByteTimeDomainData(leftData);masterBus.rightAnalyser.getByteTimeDomainData(rightData);let peakL=0;let peakR=0;for(let i=0;ipeakL)peakL=v;}for(let i=0;ipeakR)peakR=v;}levelL=peakL;levelR=peakR;}const padding=4;const gap=4;const barW=Math.max(4,(w-padding*2-gap)/2);const grad=ctx.createLinearGradient(0,h,0,0);grad.addColorStop(0,'#10b981');grad.addColorStop(0.7,'#f59e0b');grad.addColorStop(0.95,'#ef4444');ctx.fillStyle=grad;ctx.fillRect(padding,h-levelL*h,barW,levelL*h);ctx.fillRect(padding+barW+gap,h-levelR*h,barW,levelR*h);const maxLevel=Math.max(levelL,levelR);if(rmsValRef.current){rmsValRef.current.innerText=maxLevel>0?(20*Math.log10(maxLevel)-3.2).toFixed(1)+' dB':'-inf';}if(peakLRef.current){peakLRef.current.innerText=levelL>0?(20*Math.log10(levelL)).toFixed(1)+'dB':'-inf';}if(peakRRef.current){peakRRef.current.innerText=levelR>0?(20*Math.log10(levelR)).toFixed(1)+'dB':'-inf';}}render();return()=>{if(animFrameRef.current)cancelAnimationFrame(animFrameRef.current);};},[masterVolL,masterVolR,masterMuted,isMono]);return React.createElement(React.Fragment,null,React.createElement("div",{className:"flex flex-col items-stretch w-[300px] shrink-0 strip-bg rounded-lg p-2 text-slate-300 select-none shadow-2xl relative overflow-hidden"},React.createElement("div",{className:"space-y-1.5 mb-2"},React.createElement("button",{onClick:()=>setShowMasteringModal(true),className:"w-full bg-slate-800 hover:bg-slate-700 text-[10px] font-semibold py-1 rounded border border-slate-700 text-slate-300 tracking-tight"},"FX CHAIN"),React.createElement("button",{onClick:()=>setRefOpen(true),className:"w-full bg-slate-800 hover:bg-slate-700 text-[10px] font-semibold py-1 rounded border border-slate-700 text-cyan-300 tracking-tight"},"A/B REF"),React.createElement("div",{className:"flex items-center justify-between bg-slate-950 border border-slate-800 rounded px-1.5 py-0.5 text-[10px] font-mono"},React.createElement("span",{className:"text-slate-400 truncate"},"Output 1 / Output 2"),React.createElement("i",{className:"fa-solid fa-circle-notch text-[9px] text-slate-500"}))),React.createElement("div",{className:"flex flex-col items-center my-0.5"},React.createElement("span",{className:"text-[9px] text-slate-400 font-mono"},panText||'center'),React.createElement("div",{className:"flex items-center gap-1"},React.createElement("span",{className:"text-[8px] font-mono text-slate-500 w-5 text-right"},pan<0?'L'+Math.abs(Math.round(pan*100)):''),React.createElement("div",{id:"panDial",className:"w-6 h-6 rounded-full bg-slate-800 border-2 border-slate-600 relative flex items-center justify-center shadow-inner cursor-pointer",title:"Kéo chuột để chỉnh Pan (Left/Right)",onPointerDown:handlePanPointerDown,onPointerMove:handlePanPointerMove,onPointerUp:handlePanPointerUp,onWheel:function(e){e.preventDefault();var step=e.deltaY>0?-0.05:0.05;var newPan=Math.max(-1,Math.min(1,pan+step));newPan=Math.round(newPan*100)/100;setPan(newPan);if(panPointerRef.current)panPointerRef.current.style.transform='rotate('+newPan*120+'deg)';if(newPan===0)setPanText('center');else if(newPan<0)setPanText('L'+Math.abs(Math.round(newPan*100)));else setPanText('R'+Math.round(newPan*100));},onDoubleClick:function(){setPan(0);setPanText('center');if(panPointerRef.current)panPointerRef.current.style.transform='rotate(0deg)';}},React.createElement("div",{ref:panPointerRef,id:"panPointer",className:"w-0.5 h-2 bg-slate-200 rounded absolute top-0.5 transition-transform",style:{transform:'rotate('+pan*120+'deg)'}})),React.createElement("span",{className:"text-[8px] font-mono text-slate-500 w-5 text-left"},pan>0?'R'+Math.round(pan*100):''),React.createElement("span",{ref:React.createRef?null:null,className:"text-[10px] font-bold font-mono text-slate-200 ml-8",onDoubleClick:function(){handleFaderChange(0);}},masterVolDisplay))),React.createElement("div",{className:"flex gap-1 my-1 justify-between items-stretch min-h-0",style:{flex:'1 1 0%'}},React.createElement("div",{className:"flex-1 flex flex-col bg-black/80 p-1.5 rounded border border-slate-800/90 relative shadow-inner"},React.createElement("div",{className:"flex-1 flex items-stretch justify-between min-h-0"},React.createElement("div",{className:"flex flex-col h-full text-[8px] font-mono text-slate-400 select-none pr-1 text-right border-r border-slate-800/60 overflow-hidden"},React.createElement("span",{className:"flex-1 flex items-center justify-end"},"+12"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"+6"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"0"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"-6"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"-12"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"-18"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"-24"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"-30"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"-36"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"-42"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"-54")),React.createElement("div",{className:"flex-1 relative bg-slate-950 rounded overflow-hidden mx-1.5 border border-slate-900"},React.createElement("canvas",{ref:vuCanvasRef,className:"w-[100px] h-full block"}),React.createElement("div",{className:"absolute bottom-0.5 inset-x-0 flex justify-around text-[7px] font-mono text-slate-500 font-bold pointer-events-none bg-black/60 py-0.5"},React.createElement("span",null,"L"),React.createElement("span",null,"R"))),React.createElement("div",{className:"flex flex-col h-full text-[8px] font-mono text-slate-400 select-none pl-1 text-left border-l border-slate-800/60 overflow-hidden"},React.createElement("span",{className:"flex-1 flex items-center justify-start"},"+12"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"+6"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"0"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"-6"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"-12"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"-18"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"-24"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"-30"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"-36"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"-42"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"-54"))),React.createElement("div",{className:"flex justify-between text-[9px] font-mono text-slate-400 mt-0.5"},React.createElement("span",{ref:peakLRef},"-inf"),React.createElement("span",{ref:peakRRef},"-inf"))),React.createElement("div",{className:"w-36 flex items-stretch gap-0.5 bg-slate-900/60 p-1 rounded border border-slate-800"},React.createElement("div",{className:"flex-1 flex flex-col items-center justify-center relative fader-track rounded",onWheel:function(e){e.preventDefault();handleFaderChangeL(masterVolL+(e.deltaY>0?-0.5:0.5));}},React.createElement("div",{className:"w-0.5 h-full bg-slate-700 absolute left-1/2 -translate-x-1/2 top-0"}),React.createElement("input",{id:"masterFaderL",type:"range",min:"-60",max:"12",step:"0.5",value:masterVolL,className:"fader-slider w-full z-10",orient:"vertical",onChange:function(e){handleFaderChangeL(parseFloat(e.target.value));},onDoubleClick:function(){handleFaderChangeL(0);}}),React.createElement("span",{className:"text-[7px] font-mono text-slate-500 leading-none mt-0.5"},"L")),React.createElement("div",{className:"relative w-5 text-[7px] font-mono text-slate-500 select-none overflow-hidden"},React.createElement("span",{className:"absolute",style:{top:'0%',right:'2px'}},"+12"),React.createElement("span",{className:"absolute",style:{top:'8.3%',right:'2px'}},"+6"),React.createElement("span",{className:"absolute",style:{top:'16.7%',right:'2px'}},"0"),React.createElement("span",{className:"absolute",style:{top:'25%',right:'2px'}},"-6"),React.createElement("span",{className:"absolute",style:{top:'33.3%',right:'2px'}},"-12"),React.createElement("span",{className:"absolute",style:{top:'50%',right:'2px'}},"-24"),React.createElement("span",{className:"absolute",style:{top:'66.7%',right:'2px'}},"-36"),React.createElement("span",{className:"absolute",style:{top:'91.7%',right:'2px'}},"-54")),React.createElement("div",{className:"flex-1 flex flex-col items-center justify-center relative fader-track rounded",onWheel:function(e){e.preventDefault();handleFaderChangeR(masterVolR+(e.deltaY>0?-0.5:0.5));}},React.createElement("div",{className:"w-0.5 h-full bg-slate-700 absolute left-1/2 -translate-x-1/2 top-0"}),React.createElement("input",{id:"masterFaderR",type:"range",min:"-60",max:"12",step:"0.5",value:masterVolR,className:"fader-slider w-full z-10",orient:"vertical",onChange:function(e){handleFaderChangeR(parseFloat(e.target.value));},onDoubleClick:function(){handleFaderChangeR(0);}}),React.createElement("span",{className:"text-[7px] font-mono text-slate-500 leading-none mt-0.5"},"R"))),React.createElement("div",{className:"w-8 flex flex-col justify-between text-[10px] font-bold"},React.createElement("button",{id:"monoBtn",onClick:function(){setIsMono(function(p){return!p;});},className:"btn-daw h-[18px] rounded flex flex-col items-center justify-center text-[8px]"+(isMono?" btn-mono-active":""),title:"Mono Switch"},React.createElement("i",{className:"fa-solid fa-circle-half-stroke text-[9px]"}),React.createElement("span",null,"MONO")),React.createElement("button",{id:"muteBtn",onClick:function(){setMasterMuted(function(p){return!p;});},className:"btn-daw h-[18px] rounded text-amber-500 font-bold hover:text-amber-400"+(masterMuted?" btn-mute-active":""),title:"Mute Master Output (that: zero output)"},"M"),React.createElement("button",{id:"linkBtn",onClick:function(){setMasterLink(function(p){return!p;});},className:"btn-daw h-[18px] rounded text-xs font-bold"+(masterLink?" btn-teal-active":""),title:"LINK: keo L/R cung luc (giu delta)"},"LK"),React.createElement("button",{className:"btn-daw h-[18px] rounded text-slate-400 hover:text-slate-200",title:"Route Matrix"},React.createElement("i",{className:"fa-solid fa-diagram-project text-[9px]"})),React.createElement("button",{id:"fxBtn",className:"btn-daw h-[18px] rounded font-extrabold text-[10px] transition-all",onClick:function(){setShowMasteringModal(true);},title:"Mở MASTER FX CHAIN để chỉnh sửa"},"FX"),React.createElement("button",{id:"powerBtn",className:"btn-daw h-[18px] rounded text-xs transition-all"+(isMasterActive?" btn-teal-active":""),onClick:function(){if(setMasteringSettings){setMasteringSettings(function(prev){return Object.assign({},prev,{masterConnected:!prev.masterConnected,isBypassed:false});});}},title:"Bật/Tắt MASTER FX CHAIN Bypass"},[React.createElement("i",{className:"fa-solid fa-power-off"+(isMasterActive?" text-emerald-400":" text-slate-500"),key:"ico"}),React.createElement("span",{key:"lbl",className:"text-[7px] font-bold"+(isMasterActive?" text-emerald-300":" text-slate-400")},"PWR")]),React.createElement("button",{className:"btn-daw h-[18px] rounded text-slate-400 text-[8px]",title:"Trim Envelope"},"TRIM"),React.createElement("button",{className:"btn-daw h-[18px] rounded text-slate-400 text-[9px]",title:"Session Info"},React.createElement("i",{className:"fa-solid fa-info"})))),React.createElement("div",{className:"flex flex-col gap-0.5 my-1 shrink-0"},React.createElement("div",{className:"flex items-center justify-between gap-1"},React.createElement("button",{id:"automBtn",onClick:function(){setAutoOpen(function(p){return!p;});},className:"btn-daw rounded px-1 py-0.5 text-[8px] font-bold"+(autoOpen?" btn-teal-active":""),title:"Master Volume Automation (Gap 7)"},"AUTOM"),React.createElement("button",{onClick:function(){setMasterAutoOn(function(p){return!p;});},className:"text-[8px] px-1 py-0.5 rounded font-mono"+(masterAutoOn?" text-emerald-400 bg-emerald-500/10":" text-slate-500"),title:"Bat/tat master volume automation"},masterAutoOn?"ON":"OFF")),autoOpen&&React.createElement("div",{className:"flex flex-col gap-0.5 bg-slate-950 border border-slate-800 rounded p-1 max-h-32 overflow-y-auto"},(masterAutoVol||[]).map(function(pt,i){return React.createElement("div",{key:i,className:"flex items-center gap-1"},React.createElement("input",{type:"number",step:"0.1",min:"0",value:pt.time,onChange:function(e){updAutoPoint(i,'time',parseFloat(e.target.value)||0);},className:"w-12 bg-slate-900 border border-slate-700 rounded px-0.5 text-[8px] font-mono text-slate-200"}),React.createElement("span",{className:"text-[8px] text-slate-500"},"s"),React.createElement("input",{type:"number",step:"0.5",min:"-30",max:"3",value:pt.db,onChange:function(e){updAutoPoint(i,'db',parseFloat(e.target.value)||0);},className:"w-12 bg-slate-900 border border-slate-700 rounded px-0.5 text-[8px] font-mono text-slate-200"}),React.createElement("span",{className:"text-[8px] text-slate-500"},"dB"),React.createElement("button",{onClick:function(){delAutoPoint(i);},className:"text-[8px] text-red-400 hover:text-red-300 ml-auto"},"x"));}),React.createElement("button",{onClick:addAutoPoint,className:"text-[8px] text-cyan-400 hover:text-cyan-300 mt-0.5"},"+ ADD POINT"))),React.createElement("div",{className:"text-center text-[10px] font-bold font-mono text-slate-200 shrink-0"},masterVolDisplay),React.createElement("div",{className:"shrink-0 border-t border-slate-800 flex flex-col items-center"},React.createElement("div",{className:"flex justify-between w-full text-[9px] font-mono py-0.5"},React.createElement("span",{className:"text-emerald-400"},"RMS"),React.createElement("span",{ref:rmsValRef,className:"text-emerald-400 font-bold"},"-inf")),React.createElement("div",{className:"w-full text-center bg-black/80 py-0.5 rounded border border-slate-800 text-[10px] font-extrabold tracking-widest text-slate-100 uppercase"},React.createElement("span",null,"MAIN OUT")))),refOpen&&React.createElement(RefCompareModal,{open:refOpen,onClose:function(){setRefOpen(false);}}));};// ── Track Strip Console Component (from md/48_TRACK_STRIP_COMPONENT.md) ── +const handleFaderChange=val=>{handleFaderChangeL(val);handleFaderChangeR(val);};React.useEffect(()=>{applyMasterVolumesTo(masterBus,masterVolL,masterVolR,masterMuted);},[masterVolL,masterVolR,masterMuted]);const masterVolDisplay=masterLink?masterVolL<=-50?'-inf':(masterVolL>0?'+':'')+masterVolL.toFixed(1):'L'+(masterVolL<=-50?'-inf':masterVolL.toFixed(1))+' R'+(masterVolR<=-50?'-inf':masterVolR.toFixed(1));const handlePanPointerDown=e=>{isPanDraggingRef.current=true;panStartYRef.current=e.clientY;startPanValRef.current=pan;e.currentTarget.setPointerCapture(e.pointerId);};const handlePanPointerMove=e=>{if(!isPanDraggingRef.current)return;const deltaY=panStartYRef.current-e.clientY;let newPan=startPanValRef.current+deltaY/80;newPan=Math.min(1.0,Math.max(-1.0,newPan));setPan(newPan);const angle=newPan*120;if(panPointerRef.current)panPointerRef.current.style.transform=`rotate(${angle}deg)`;if(newPan===0)setPanText('center');else if(newPan<0)setPanText('L'+Math.abs(Math.round(newPan*100)));else setPanText('R'+Math.round(newPan*100));};const handlePanPointerUp=e=>{isPanDraggingRef.current=false;try{e.currentTarget.releasePointerCapture(e.pointerId);}catch(err){}};React.useEffect(()=>{const canvas=vuCanvasRef.current;if(!canvas)return;const ctx=canvas.getContext('2d');function render(){animFrameRef.current=requestAnimationFrame(render);canvas.width=canvas.clientWidth;canvas.height=canvas.clientHeight;const w=canvas.width;const h=canvas.height;ctx.clearRect(0,0,w,h);let levelL=0;let levelR=0;if(masterBus&&masterBus.leftAnalyser&&masterBus.rightAnalyser){const leftData=new Uint8Array(256);const rightData=new Uint8Array(256);masterBus.leftAnalyser.getByteTimeDomainData(leftData);masterBus.rightAnalyser.getByteTimeDomainData(rightData);let peakL=0;let peakR=0;for(let i=0;ipeakL)peakL=v;}for(let i=0;ipeakR)peakR=v;}levelL=peakL;levelR=peakR;}const padding=4;const gap=4;const barW=Math.max(4,(w-padding*2-gap)/2);const grad=ctx.createLinearGradient(0,h,0,0);grad.addColorStop(0,'#10b981');grad.addColorStop(0.7,'#f59e0b');grad.addColorStop(0.95,'#ef4444');ctx.fillStyle=grad;ctx.fillRect(padding,h-levelL*h,barW,levelL*h);ctx.fillRect(padding+barW+gap,h-levelR*h,barW,levelR*h);const maxLevel=Math.max(levelL,levelR);if(rmsValRef.current){rmsValRef.current.innerText=maxLevel>0?(20*Math.log10(maxLevel)-3.2).toFixed(1)+' dB':'-inf';}if(peakLRef.current){peakLRef.current.innerText=levelL>0?(20*Math.log10(levelL)).toFixed(1)+'dB':'-inf';}if(peakRRef.current){peakRRef.current.innerText=levelR>0?(20*Math.log10(levelR)).toFixed(1)+'dB':'-inf';}}render();return()=>{if(animFrameRef.current)cancelAnimationFrame(animFrameRef.current);};},[masterVolL,masterVolR,masterMuted,isMono]);return React.createElement(React.Fragment,null,React.createElement("div",{className:"flex flex-col items-stretch w-[300px] shrink-0 strip-bg rounded-lg p-2 text-slate-300 select-none shadow-2xl relative overflow-hidden"},React.createElement("div",{className:"flex flex-col items-center my-0.5"},React.createElement("span",{className:"text-[9px] text-slate-400 font-mono"},panText||'center'),React.createElement("div",{className:"flex items-center gap-1"},React.createElement("span",{className:"text-[8px] font-mono text-slate-500 w-5 text-right"},pan<0?'L'+Math.abs(Math.round(pan*100)):''),React.createElement("div",{id:"panDial",className:"w-6 h-6 rounded-full bg-slate-800 border-2 border-slate-600 relative flex items-center justify-center shadow-inner cursor-pointer",title:"Kéo chuột để chỉnh Pan (Left/Right)",onPointerDown:handlePanPointerDown,onPointerMove:handlePanPointerMove,onPointerUp:handlePanPointerUp,onWheel:function(e){e.preventDefault();var step=e.deltaY>0?-0.05:0.05;var newPan=Math.max(-1,Math.min(1,pan+step));newPan=Math.round(newPan*100)/100;setPan(newPan);if(panPointerRef.current)panPointerRef.current.style.transform='rotate('+newPan*120+'deg)';if(newPan===0)setPanText('center');else if(newPan<0)setPanText('L'+Math.abs(Math.round(newPan*100)));else setPanText('R'+Math.round(newPan*100));},onDoubleClick:function(){setPan(0);setPanText('center');if(panPointerRef.current)panPointerRef.current.style.transform='rotate(0deg)';}},React.createElement("div",{ref:panPointerRef,id:"panPointer",className:"w-0.5 h-2 bg-slate-200 rounded absolute top-0.5 transition-transform",style:{transform:'rotate('+pan*120+'deg)'}})),React.createElement("span",{className:"text-[8px] font-mono text-slate-500 w-5 text-left"},pan>0?'R'+Math.round(pan*100):''),React.createElement("span",{ref:React.createRef?null:null,className:"text-[10px] font-bold font-mono text-slate-200 ml-8",onDoubleClick:function(){handleFaderChange(0);}},masterVolDisplay))),React.createElement("div",{className:"flex gap-1 my-1 justify-between items-stretch min-h-0",style:{flex:'1 1 0%'}},React.createElement("div",{className:"flex-1 flex flex-col bg-black/80 p-1.5 rounded border border-slate-800/90 relative shadow-inner"},React.createElement("div",{className:"flex-1 flex items-stretch justify-between min-h-0"},React.createElement("div",{className:"flex flex-col h-full text-[8px] font-mono text-slate-400 select-none pr-1 text-right border-r border-slate-800/60 overflow-hidden"},React.createElement("span",{className:"flex-1 flex items-center justify-end"},"+12"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"+6"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"0"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"-6"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"-12"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"-18"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"-24"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"-30"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"-36"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"-42"),React.createElement("span",{className:"flex-1 flex items-center justify-end"},"-54")),React.createElement("div",{className:"flex-1 relative bg-slate-950 rounded overflow-hidden mx-1.5 border border-slate-900"},React.createElement("canvas",{ref:vuCanvasRef,className:"w-[100px] h-full block"}),React.createElement("div",{className:"absolute bottom-0.5 inset-x-0 flex justify-around text-[7px] font-mono text-slate-500 font-bold pointer-events-none bg-black/60 py-0.5"},React.createElement("span",null,"L"),React.createElement("span",null,"R"))),React.createElement("div",{className:"flex flex-col h-full text-[8px] font-mono text-slate-400 select-none pl-1 text-left border-l border-slate-800/60 overflow-hidden"},React.createElement("span",{className:"flex-1 flex items-center justify-start"},"+12"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"+6"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"0"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"-6"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"-12"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"-18"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"-24"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"-30"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"-36"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"-42"),React.createElement("span",{className:"flex-1 flex items-center justify-start"},"-54"))),React.createElement("div",{className:"flex justify-between text-[9px] font-mono text-slate-400 mt-0.5"},React.createElement("span",{ref:peakLRef},"-inf"),React.createElement("span",{ref:peakRRef},"-inf"))),React.createElement("div",{className:"w-36 flex items-stretch gap-0.5 bg-slate-900/60 p-1 rounded border border-slate-800"},React.createElement("div",{className:"flex-1 flex flex-col items-center justify-center relative fader-track rounded",onWheel:function(e){e.preventDefault();handleFaderChangeL(masterVolL+(e.deltaY>0?-0.5:0.5));}},React.createElement("div",{className:"w-0.5 h-full bg-slate-700 absolute left-1/2 -translate-x-1/2 top-0"}),React.createElement("input",{id:"masterFaderL",type:"range",min:"-60",max:"12",step:"0.5",value:masterVolL,className:"fader-slider w-full z-10",orient:"vertical",onChange:function(e){handleFaderChangeL(parseFloat(e.target.value));},onDoubleClick:function(){handleFaderChangeL(0);}}),React.createElement("span",{className:"text-[7px] font-mono text-slate-500 leading-none mt-0.5"},"L")),React.createElement("div",{className:"relative w-5 text-[7px] font-mono text-slate-500 select-none overflow-hidden"},React.createElement("span",{className:"absolute",style:{top:'0%',right:'2px'}},"+12"),React.createElement("span",{className:"absolute",style:{top:'8.3%',right:'2px'}},"+6"),React.createElement("span",{className:"absolute",style:{top:'16.7%',right:'2px'}},"0"),React.createElement("span",{className:"absolute",style:{top:'25%',right:'2px'}},"-6"),React.createElement("span",{className:"absolute",style:{top:'33.3%',right:'2px'}},"-12"),React.createElement("span",{className:"absolute",style:{top:'50%',right:'2px'}},"-24"),React.createElement("span",{className:"absolute",style:{top:'66.7%',right:'2px'}},"-36"),React.createElement("span",{className:"absolute",style:{top:'91.7%',right:'2px'}},"-54")),React.createElement("div",{className:"flex-1 flex flex-col items-center justify-center relative fader-track rounded",onWheel:function(e){e.preventDefault();handleFaderChangeR(masterVolR+(e.deltaY>0?-0.5:0.5));}},React.createElement("div",{className:"w-0.5 h-full bg-slate-700 absolute left-1/2 -translate-x-1/2 top-0"}),React.createElement("input",{id:"masterFaderR",type:"range",min:"-60",max:"12",step:"0.5",value:masterVolR,className:"fader-slider w-full z-10",orient:"vertical",onChange:function(e){handleFaderChangeR(parseFloat(e.target.value));},onDoubleClick:function(){handleFaderChangeR(0);}}),React.createElement("span",{className:"text-[7px] font-mono text-slate-500 leading-none mt-0.5"},"R"))),React.createElement("div",{className:"w-8 flex flex-col justify-between text-[10px] font-bold"},React.createElement("button",{id:"monoBtn",onClick:function(){setIsMono(function(p){return!p;});},className:"btn-daw h-[18px] rounded flex flex-col items-center justify-center text-[8px]"+(isMono?" btn-mono-active":""),title:"Mono Switch"},React.createElement("i",{className:"fa-solid fa-circle-half-stroke text-[9px]"}),React.createElement("span",null,"MONO")),React.createElement("button",{id:"muteBtn",onClick:function(){setMasterMuted(function(p){return!p;});},className:"btn-daw h-[18px] rounded text-amber-500 font-bold hover:text-amber-400"+(masterMuted?" btn-mute-active":""),title:"Mute Master Output (that: zero output)"},"M"),React.createElement("button",{id:"linkBtn",onClick:function(){setMasterLink(function(p){return!p;});},className:"btn-daw h-[18px] rounded text-xs font-bold"+(masterLink?" btn-teal-active":""),title:"LINK: keo L/R cung luc (giu delta)"},"LK"),React.createElement("button",{className:"btn-daw h-[18px] rounded text-slate-400 hover:text-slate-200",title:"Route Matrix"},React.createElement("i",{className:"fa-solid fa-diagram-project text-[9px]"})),React.createElement("button",{id:"fxBtn",className:"btn-daw h-[18px] rounded font-extrabold text-[10px] transition-all",onClick:function(){setShowMasteringModal(true);},title:"Mở MASTER FX CHAIN để chỉnh sửa"},"FX"),React.createElement("button",{id:"powerBtn",className:"btn-daw h-[18px] rounded text-xs transition-all"+(isMasterActive?" btn-teal-active":""),onClick:function(){if(setMasteringSettings){setMasteringSettings(function(prev){return Object.assign({},prev,{masterConnected:!prev.masterConnected,isBypassed:false});});}},title:"Bật/Tắt MASTER FX CHAIN Bypass"},[React.createElement("i",{className:"fa-solid fa-power-off"+(isMasterActive?" text-emerald-400":" text-slate-500"),key:"ico"}),React.createElement("span",{key:"lbl",className:"text-[7px] font-bold"+(isMasterActive?" text-emerald-300":" text-slate-400")},"PWR")]),React.createElement("button",{className:"btn-daw h-[18px] rounded text-slate-400 text-[8px]",title:"Trim Envelope"},"TRIM"),React.createElement("button",{className:"btn-daw h-[18px] rounded text-slate-400 text-[9px]",title:"Session Info"},React.createElement("i",{className:"fa-solid fa-info"})))),React.createElement("div",{className:"flex flex-col gap-0.5 my-1 shrink-0"},React.createElement("div",{className:"flex items-center justify-between gap-1"},React.createElement("button",{id:"automBtn",onClick:function(){setAutoOpen(function(p){return!p;});},className:"btn-daw rounded px-1 py-0.5 text-[8px] font-bold"+(autoOpen?" btn-teal-active":""),title:"Master Volume Automation (Gap 7)"},"AUTOM"),React.createElement("button",{onClick:function(){setMasterAutoOn(function(p){return!p;});},className:"text-[8px] px-1 py-0.5 rounded font-mono"+(masterAutoOn?" text-emerald-400 bg-emerald-500/10":" text-slate-500"),title:"Bat/tat master volume automation"},masterAutoOn?"ON":"OFF")),autoOpen&&React.createElement("div",{className:"flex flex-col gap-0.5 bg-slate-950 border border-slate-800 rounded p-1 max-h-32 overflow-y-auto"},(masterAutoVol||[]).map(function(pt,i){return React.createElement("div",{key:i,className:"flex items-center gap-1"},React.createElement("input",{type:"number",step:"0.1",min:"0",value:pt.time,onChange:function(e){updAutoPoint(i,'time',parseFloat(e.target.value)||0);},className:"w-12 bg-slate-900 border border-slate-700 rounded px-0.5 text-[8px] font-mono text-slate-200"}),React.createElement("span",{className:"text-[8px] text-slate-500"},"s"),React.createElement("input",{type:"number",step:"0.5",min:"-30",max:"3",value:pt.db,onChange:function(e){updAutoPoint(i,'db',parseFloat(e.target.value)||0);},className:"w-12 bg-slate-900 border border-slate-700 rounded px-0.5 text-[8px] font-mono text-slate-200"}),React.createElement("span",{className:"text-[8px] text-slate-500"},"dB"),React.createElement("button",{onClick:function(){delAutoPoint(i);},className:"text-[8px] text-red-400 hover:text-red-300 ml-auto"},"x"));}),React.createElement("button",{onClick:addAutoPoint,className:"text-[8px] text-cyan-400 hover:text-cyan-300 mt-0.5"},"+ ADD POINT"))),React.createElement("div",{className:"text-center text-[10px] font-bold font-mono text-slate-200 shrink-0"},masterVolDisplay),React.createElement("div",{className:"shrink-0 border-t border-slate-800 flex flex-col items-center"},React.createElement("div",{className:"flex justify-between w-full text-[9px] font-mono py-0.5"},React.createElement("span",{className:"text-emerald-400"},"RMS"),React.createElement("span",{ref:rmsValRef,className:"text-emerald-400 font-bold"},"-inf")),React.createElement("div",{className:"w-full text-center bg-black/80 py-0.5 rounded border border-slate-800 text-[10px] font-extrabold tracking-widest text-slate-100 uppercase"},React.createElement("span",null,"MAIN OUT")))),refOpen&&React.createElement(RefCompareModal,{open:refOpen,onClose:function(){setRefOpen(false);}}));};// ── Track Strip Console Component (from md/48_TRACK_STRIP_COMPONENT.md) ── const TrackStripConsole=({track,index,onUpdateTrack,trackVuRefs,style})=>{var vol=track.volumeDb!=null?track.volumeDb:0;var trackColor=track.color||'#06b6d4';var isMuted=track.muted;var isSoloed=track.solo;var isBypassed=!!(track.audioBypass??track.masteringBypass);var isArmed=track.isArmed;var trackName=track.name||'Track '+(index+1);var isMicActive=track.inputSource?.deviceType==='MICROPHONE';const[pan,setPan]=React.useState(0.0);const[panLabel,setPanLabel]=React.useState('center');const[isPhaseInverted,setIsPhaseInverted]=React.useState(false);const panPointerRef=React.useRef(null);const setVuCanvas=React.useCallback(function(el){if(el)trackVuRefs.current[track.id+'_mixer']=el;else delete trackVuRefs.current[track.id+'_mixer'];},[track.id,trackVuRefs]);// Track FX chain editor (mastering_expand.md §II.4): reuse the same module // types as the mastering suite inside this track's FX chain. var FX_MODULE_TYPES=['compressor','limiter','exciter','rebalance','eq'];const updateFxChain=function(nextChain){if(onUpdateTrack)onUpdateTrack(track.id,{fxChain:nextChain});};const handlePanPointerDown=e=>{e.currentTarget._panStartY=e.clientY;e.currentTarget._startPan=pan;e.currentTarget.setPointerCapture(e.pointerId);function onMove(ev){if(!e.currentTarget)return;var deltaY=e.currentTarget._panStartY-ev.clientY;var newPan=Math.min(1.0,Math.max(-1.0,e.currentTarget._startPan+deltaY/80));setPan(newPan);var angle=newPan*120;if(panPointerRef.current)panPointerRef.current.style.transform='rotate('+angle+'deg)';if(newPan===0)setPanLabel('center');else if(newPan<0)setPanLabel('L'+Math.abs(Math.round(newPan*100)));else setPanLabel('R'+Math.round(newPan*100));}function onUp(){document.removeEventListener('pointermove',onMove);document.removeEventListener('pointerup',onUp);}document.addEventListener('pointermove',onMove);document.addEventListener('pointerup',onUp);};return React.createElement("div",{style:style||undefined,className:"flex flex-col items-stretch w-[145px] shrink-0 strip-bg-track rounded-md text-slate-300 select-none shadow-2xl border border-slate-900 overflow-y-auto"},/* 1. Top Track Color Accent Bar */React.createElement("div",{className:"h-1.5 w-full shrink-0 transition-colors",style:{backgroundColor:trackColor}}),/* 2. Pan Rotary Dial Area */React.createElement("div",{className:"h-[46px] shrink-0 py-1 px-2 flex flex-col items-center justify-center border-b border-slate-700/40",style:{backgroundColor:trackColor+'15'}},React.createElement("div",{className:"w-6 h-6 rounded-full bg-slate-800 border-2 border-slate-400 relative flex items-center justify-center cursor-pointer shadow-md",title:"Kéo chuột lên/xuống để chỉnh Pan",onPointerDown:handlePanPointerDown,onDoubleClick:function(){setPan(0);setPanLabel('center');if(panPointerRef.current)panPointerRef.current.style.transform='rotate(0deg)';},onWheel:function(e){e.preventDefault();var step=e.deltaY>0?-0.05:0.05;var newPan=Math.max(-1,Math.min(1,pan+step));newPan=Math.round(newPan*100)/100;setPan(newPan);if(panPointerRef.current)panPointerRef.current.style.transform='rotate('+newPan*120+'deg)';if(newPan===0)setPanLabel('center');else if(newPan<0)setPanLabel('L'+Math.abs(Math.round(newPan*100)));else setPanLabel('R'+Math.round(newPan*100));}},React.createElement("div",{ref:panPointerRef,className:"w-0.5 h-2 rounded absolute top-0.5 transition-transform",style:{backgroundColor:trackColor,transform:'rotate(0deg)'}})),React.createElement("span",{className:"text-[8px] font-mono mt-0.5 font-semibold",style:{color:trackColor}},panLabel)),/* 3. Center Area: Peak dB + Fader + VU + Button Stack */React.createElement("div",{className:"flex-1 p-1 flex gap-1 justify-between items-stretch min-h-[170px]"},/* Left Fader & VU Column */React.createElement("div",{className:"flex-1 flex flex-col justify-between items-center bg-black/60 p-1 rounded border border-slate-800/80"},React.createElement("div",{className:"w-full flex justify-center text-[8px] font-mono text-slate-400 h-4 items-center"},React.createElement("span",null,vol<=-50?'-inf':(vol>0?'+':'')+vol.toFixed(1)+'dB')),React.createElement("div",{className:"flex items-stretch justify-around w-full flex-1 relative py-1"},/* Fader Rail */React.createElement("div",{className:"relative fader-track-bg w-3 flex-1 rounded flex items-center justify-center overflow-hidden"},React.createElement("div",{className:"w-0.5 h-full bg-slate-700 absolute"}),React.createElement("input",{type:"range",min:"-60",max:"12",step:"0.5",value:vol,className:"fader-slider w-full z-10",onChange:function(e){var val=parseFloat(e.target.value);if(onUpdateTrack)onUpdateTrack(track.id,{volumeDb:val});},onWheel:function(e){e.preventDefault();var step=e.deltaY>0?-0.5:0.5;var newVol=Math.max(-60,Math.min(12,vol+step));if(onUpdateTrack)onUpdateTrack(track.id,{volumeDb:newVol});},onDoubleClick:function(){if(onUpdateTrack)onUpdateTrack(track.id,{volumeDb:0});}})),/* VU Meter */React.createElement("div",{className:"w-2.5 flex-1 bg-slate-950 rounded border border-slate-900 overflow-hidden relative",title:"Peak VU Meter"},React.createElement("canvas",{ref:setVuCanvas,className:"w-full h-full block"})))),/* Right Button Stack */React.createElement("div",{className:"w-7 flex flex-col justify-between text-[8px] font-bold shrink-0"},React.createElement("button",{onClick:function(e){e.stopPropagation();var next=!track.muted;if(onUpdateTrack)onUpdateTrack(track.id,{muted:next});if(window.__applyTrackMuteSolo)window.__applyTrackMuteSolo(track.id,{muted:next});},className:"btn-daw h-[24px] rounded text-amber-500 font-extrabold flex items-center justify-center"+(isMuted?" btn-mute-active":""),title:"Mute Track"},"M"),React.createElement("button",{onClick:function(e){e.stopPropagation();var next=!track.solo;if(onUpdateTrack)onUpdateTrack(track.id,{solo:next});if(window.__applyTrackMuteSolo)window.__applyTrackMuteSolo(track.id,{solo:next});},className:"btn-daw h-[24px] rounded text-yellow-400 font-extrabold flex items-center justify-center"+(isSoloed?" btn-solo-active":""),title:"Solo Track"},"S"),React.createElement("button",{onClick:function(e){e.stopPropagation();var next=!(track.audioBypass??track.masteringBypass);if(onUpdateTrack)onUpdateTrack(track.id,{audioBypass:next});// Live re-route: bypassed channel skips FX + mastering chain at Main out. @@ -794,7 +833,7 @@ return{hx:Math.max(0,Math.min((canvasRef.current?canvasRef.current.clientWidth:4 // gửi pointer/key về bridge qua /input. Dùng chung MasteringModal + FXRackModal. // url = embed_url từ API fx-gui open (embed:true); onClose khi user đóng; // onDead khi bridge chết (ping fail) → parent trả graph + toast. -const VstGuiEmbed=({url,onClose,onDead})=>{const imgRef=React.useRef(null);const boxRef=React.useRef(null);const deadRef=React.useRef(false);const screenRectRef=React.useRef(null);const[dead,setDead]=React.useState(false);const post=payload=>{try{fetch(url+'/input',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}).catch(()=>{});}catch(e){}};React.useEffect(()=>{deadRef.current=false;setDead(false);const tick=setInterval(()=>{const img=imgRef.current;if(img)img.src=url+'/frame?t='+Date.now();},100);const ping=setInterval(()=>{fetch(url+'/ping').then(r=>{if(!r.ok)throw new Error('bad');}).catch(()=>{if(!deadRef.current){deadRef.current=true;setDead(true);onDead&&onDead();}});},2000);// Show immediately on mount even before the rect is known: bridge +const VstGuiEmbed=({url,onClose,onDead})=>{const imgRef=React.useRef(null);const boxRef=React.useRef(null);const deadRef=React.useRef(false);const screenRectRef=React.useRef(null);const[dead,setDead]=React.useState(false);const post=payload=>{try{fetch(url+'/input',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}).catch(()=>{});}catch(e){}};React.useEffect(()=>{deadRef.current=false;setDead(false);const tick=setInterval(()=>{const img=imgRef.current;if(img&&img.complete)img.src=url+'/frame?t='+Date.now();},100);const ping=setInterval(()=>{fetch(url+'/ping').then(r=>{if(!r.ok)throw new Error('bad');}).catch(()=>{if(!deadRef.current){deadRef.current=true;setDead(true);onDead&&onDead();}});},2000);// Show immediately on mount even before the rect is known: bridge // re-shows the native window at its last position, and the ~500ms // rect refresh below re-anchors it over the panel. try{fetch(url+'/show',{method:'POST'}).catch(()=>{});}catch(e){}return()=>{clearInterval(tick);clearInterval(ping);// Panel closed -> hide the native window (bridge stays alive so @@ -806,7 +845,7 @@ try{fetch(url+'/hide',{method:'POST'}).catch(()=>{});}catch(e){}};// eslint-disa React.useEffect(()=>{let alive=true;const maybeShow=()=>{const r=screenRectRef.current;if(r&&r.w>=4&&r.h>=4){// Re-POST /show on every refresh (~500ms) so the native window // re-anchors over the panel on scroll/drag/resize. Idempotent: the // bridge skips SetWindowPos/resize when nothing moved. -try{fetch(url+'/show',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({rect:r})}).catch(()=>{});}catch(e){}}};const refresh=()=>{const box=boxRef.current;if(!box)return;const r=box.getBoundingClientRect();if(r.width<4||r.height<4)return;try{const tw=window.__TAURI__&&window.__TAURI__.window;if(tw&&tw.getCurrentWindow){Promise.all([tw.getCurrentWindow().innerPosition(),tw.getCurrentWindow().scaleFactor()]).then(([pos,sf])=>{if(!alive||!boxRef.current)return;const rb=boxRef.current.getBoundingClientRect();screenRectRef.current={x:Math.round(pos.x+rb.left*sf),y:Math.round(pos.y+rb.top*sf),w:Math.round(rb.width*sf),h:Math.round(rb.height*sf)};maybeShow();}).catch(()=>{if(!alive||!boxRef.current)return;const rb=boxRef.current.getBoundingClientRect();screenRectRef.current={x:Math.round((window.screenX||0)+rb.left),y:Math.round((window.screenY||0)+rb.top),w:Math.round(rb.width),h:Math.round(rb.height)};maybeShow();});}else{screenRectRef.current={x:Math.round((window.screenX||0)+r.left),y:Math.round((window.screenY||0)+r.top),w:Math.round(r.width),h:Math.round(r.height)};maybeShow();}}catch(e){}};refresh();const iv=setInterval(refresh,500);return()=>{alive=false;clearInterval(iv);};// eslint-disable-next-line react-hooks/exhaustive-deps +try{fetch(url+'/show',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({rect:r})}).catch(()=>{});}catch(e){}}};const refresh=()=>{const box=boxRef.current;if(!box)return;const r=box.getBoundingClientRect();if(r.width<4||r.height<4)return;try{const tw=window.__TAURI__&&window.__TAURI__.window;if(tw&&tw.getCurrentWindow){Promise.all([tw.getCurrentWindow().innerPosition(),tw.getCurrentWindow().scaleFactor()]).then(([pos,sf])=>{if(!alive||!boxRef.current)return;const rb=boxRef.current.getBoundingClientRect();screenRectRef.current={x:Math.round(pos.x+rb.left*sf),y:Math.round(pos.y+rb.top*sf),w:Math.round(rb.width*sf),h:Math.round(rb.height*sf)};maybeShow();}).catch(()=>{if(!alive||!boxRef.current)return;const rb=boxRef.current.getBoundingClientRect();screenRectRef.current={x:Math.round((window.screenX||0)+rb.left),y:Math.round((window.screenY||0)+rb.top),w:Math.round(rb.width),h:Math.round(rb.height)};maybeShow();});}else{screenRectRef.current={x:Math.round((window.screenX||0)+r.left),y:Math.round((window.screenY||0)+r.top),w:Math.round(r.width),h:Math.round(r.height)};maybeShow();}}catch(e){}};refresh();const iv=setInterval(refresh,250);return()=>{alive=false;clearInterval(iv);};// eslint-disable-next-line react-hooks/exhaustive-deps },[url]);const pt=e=>{const box=boxRef.current,img=imgRef.current;if(!box||!img||!img.naturalWidth||!img.naturalHeight)return null;const r=box.getBoundingClientRect();if(r.width===0||r.height===0)return null;return{x:Math.round((e.clientX-r.left)/r.width*img.naturalWidth),y:Math.round((e.clientY-r.top)/r.height*img.naturalHeight)};};const handle=e=>{const p=pt(e);if(!p)return;post({type:e.type==='mousedown'?'mousedown':e.type==='mouseup'?'mouseup':'mousemove',x:p.x,y:p.y,button:e.button,buttons:e.buttons,rect:screenRectRef.current||undefined});};const close=()=>{try{fetch(url+'/close',{method:'POST'}).catch(()=>{});}catch(e){}onClose&&onClose();};return/*#__PURE__*/React.createElement("div",{className:"relative w-full h-full flex flex-col"},/*#__PURE__*/React.createElement("div",{className:"flex items-center justify-between px-3 py-1.5 bg-slate-900/80 border border-slate-800 rounded-t-lg shrink-0"},/*#__PURE__*/React.createElement("span",{className:"text-[10px] text-violet-300 font-mono"},"VST GUI \u2014 nh\xFAng (frame-capture \xB7 ~10fps)"),/*#__PURE__*/React.createElement("div",{className:"flex items-center gap-2"},dead&&/*#__PURE__*/React.createElement("span",{className:"text-[9px] text-red-400 font-mono"},"bridge m\u1EA5t k\u1EBFt n\u1ED1i"),/*#__PURE__*/React.createElement("button",{onClick:close,className:"px-2 py-0.5 bg-red-900/60 hover:bg-red-800 text-red-100 text-[10px] font-semibold rounded transition",title:"\u0110\xF3ng GUI v\xE0 tr\u1EA3 v\u1EC1 graph"},"\u2715 \u0110\xF3ng GUI"))),/*#__PURE__*/React.createElement("div",{ref:boxRef,tabIndex:0,className:"flex-1 relative bg-slate-950 border border-slate-800 rounded-b-lg overflow-hidden outline-none",onMouseDown:handle,onMouseUp:handle,onMouseMove:handle,onMouseLeave:()=>post({type:'mouseup',x:-1,y:-1,button:0}),onWheel:e=>{const p=pt(e);if(p)post({type:'wheel',x:p.x,y:p.y,deltaY:e.deltaY,rect:screenRectRef.current||undefined});},onKeyDown:e=>{e.preventDefault();post({type:'keydown',keyCode:e.keyCode||e.which});},onKeyUp:e=>{e.preventDefault();post({type:'keyup',keyCode:e.keyCode||e.which});}},/*#__PURE__*/React.createElement("img",{ref:imgRef,alt:"VST GUI",className:"w-full h-full object-contain select-none pointer-events-none",draggable:false})));};const vstRow=(s,idx,toggleV,changeV,uploadV,moveV,removeV,fxl,chainLen,openGui,activeIdx=-1,onSelect=null)=>/*#__PURE__*/React.createElement("div",{key:idx,onClick:()=>onSelect&&onSelect(s,idx),className:`flex items-center gap-2 bg-slate-900/60 border rounded-lg px-2 py-1.5 flex-wrap cursor-pointer transition-all ${activeIdx===idx?'border-teal-400 bg-slate-800/80':'border-slate-800 hover:border-slate-600'}`},/*#__PURE__*/React.createElement("button",{onClick:e=>{e.stopPropagation();toggleV(idx);},className:`w-4 h-4 rounded-full flex items-center justify-center text-[9px] font-bold shrink-0 ${!s.bypass?'bg-teal-500 text-slate-950':'bg-slate-700 text-slate-300'}`,title:s.bypass?'Bypass':'Active'},/*#__PURE__*/React.createElement("i",{"data-lucide":"power",className:"w-2.5 h-2.5"})),/*#__PURE__*/React.createElement("span",{className:"text-[10px] font-bold text-slate-300 font-mono w-6 shrink-0"},idx+1),/*#__PURE__*/React.createElement("select",{value:s.path||'',onClick:e=>e.stopPropagation(),onChange:e=>changeV(idx,e.target.value),className:"flex-1 min-w-[200px] bg-slate-950 border border-slate-700 text-teal-300 rounded px-2 py-1 text-[11px] outline-none focus:border-teal-500"},/*#__PURE__*/React.createElement("option",{value:""},"\u2014 Ch\u1ECDn VST FX \u2014"),(fxl||[]).map(f=>/*#__PURE__*/React.createElement("option",{key:f.path,value:f.path},f.name||f.id))),/*#__PURE__*/React.createElement("span",{className:`text-[9px] font-mono ${s.preset_b64?'text-emerald-400':'text-slate-600'}`},s.preset_b64?'✓ preset':'no preset'),/*#__PURE__*/React.createElement("button",{onClick:e=>{e.stopPropagation();uploadV(idx);},className:"px-2 py-1 bg-slate-800 hover:bg-slate-700 text-slate-300 text-[10px] font-semibold rounded transition",title:"Upload .vstpreset (Save preset)"},"Preset"),openGui&&/*#__PURE__*/React.createElement("button",{onClick:e=>{e.stopPropagation();openGui(s,idx);},disabled:!s.path,className:"px-2 py-1 bg-violet-800 hover:bg-violet-700 disabled:opacity-30 text-violet-100 text-[10px] font-semibold rounded transition",title:"M\u1EDF GUI c\u1EE7a VST (ch\u1EC9nh th\xF4ng s\u1ED1 tr\u1EF1c ti\u1EBFp)"},/*#__PURE__*/React.createElement("i",{"data-lucide":"monitor",className:"w-3 h-3"})," GUI"),/*#__PURE__*/React.createElement("button",{onClick:e=>{e.stopPropagation();moveV(idx,-1);},disabled:idx===0,className:"w-6 h-6 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded text-xs disabled:opacity-30",title:"L\xEAn"},/*#__PURE__*/React.createElement("i",{"data-lucide":"chevron-up",className:"w-3 h-3"})),/*#__PURE__*/React.createElement("button",{onClick:e=>{e.stopPropagation();moveV(idx,1);},disabled:idx===chainLen-1,className:"w-6 h-6 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded text-xs disabled:opacity-30",title:"Xu\u1ED1ng"},/*#__PURE__*/React.createElement("i",{"data-lucide":"chevron-down",className:"w-3 h-3"})),/*#__PURE__*/React.createElement("button",{onClick:e=>{e.stopPropagation();removeV(idx);},className:"text-slate-600 hover:text-red-400 text-xs px-0.5",title:"X\xF3a slot"},/*#__PURE__*/React.createElement("i",{"data-lucide":"x",className:"w-3 h-3"})));// ── VST FX Plugin Picker (spec vst_fx_panel_integration.md §II) ────────── // Modal chọn VST FX theo category (heuristic từ backend list_fx.category). // Dùng chung FXRackModal + MasteringModal: [+] → picker → chèn VST card. @@ -815,17 +854,29 @@ const VST_FX_CATEGORIES=[{id:'all',label:'Tất cả'},{id:'equalizer',label:'Eq let _persistFxGuiOpen=null;// Track id whose rack owns the currently-open embedded GUI (for save). let _persistFxGuiTrackId=null;// Latest preset_b64 captured from each plugin's embedded GUI (poll /preset) // - merged into the project on save so knob tweaks survive reload. -let _capturedPresetByPath={};const FXRackModal=({track,onUpdateTrack,onClose})=>{const[activeType,setActiveType]=React.useState('eq');const[addModuleOpen,setAddModuleOpen]=React.useState(false);const dragChainIndexRef=React.useRef(null);// Wave Observer scope state (unified_fx_rack_panel_update.md §III.3) +let _capturedPresetByPath={};// Baseline of each plugin's GUI state at embed-open time. /preset round-trips +// through getState/applyPreset and the blob can differ from the value the +// session started with; restarting the chain on that first difference reloads +// the VST and crackles. First capture after open = baseline (no restart); only +// a CHANGE vs baseline schedules the ~3s restart that syncs realtime to GUI. +let _fxGuiBaselineByPath={};// Debounced restart khi preset GUI đổi (preset poll) — _capturedPresetByPath +// đổi làm chainKey đổi nhưng không ai gọi fxRtStart/reconcile → session +// realtime GIỮ preset cũ (xoay knob trong GUI không đổi âm realtime). Restart +// ~3s sau khi knob DỪNG xoay (không restart mỗi poll 1.5s giữa lúc kéo — load +// VST ~4s ngắt âm). fn tự early-return khi chainKey không đổi. +let _presetRestartTimers={};function _schedulePresetRestart(key,fn,ms){if(_presetRestartTimers[key])clearTimeout(_presetRestartTimers[key]);_presetRestartTimers[key]=setTimeout(()=>{delete _presetRestartTimers[key];try{fn();}catch(e){}},ms);}const FXRackModal=({track,onUpdateTrack,onClose})=>{const[activeType,setActiveType]=React.useState('eq');const[addModuleOpen,setAddModuleOpen]=React.useState(false);const dragChainIndexRef=React.useRef(null);// Wave Observer scope state (unified_fx_rack_panel_update.md §III.3) const[scopeChannel,setScopeChannel]=React.useState('stereo');const[scopeMode,setScopeMode]=React.useState('waveform');const[scopeDuration,setScopeDuration]=React.useState(2.0);const[scopeZoom,setScopeZoom]=React.useState(0);const[scopePaused,setScopePaused]=React.useState(false);const scopeCanvasRef=React.useRef(null);const scopeMeterLRef=React.useRef(null);const scopeMeterRRef=React.useRef(null);const eqCurveRef=React.useRef(null);const scopeStateRef=React.useRef({L:null,R:null,head:0,len:0,tmpL:null,tmpR:null,freq:null});// VST FX (native_bridge --render-fx) — list VST3 effect plugins + preview const[fxList,setFxList]=React.useState([]);const[fxLoading,setFxLoading]=React.useState(false);React.useEffect(()=>{if(window.SonicAPI&&window.SonicAPI.listFx){setFxLoading(true);window.SonicAPI.listFx().then(d=>setFxList(d&&d.plugins||[])).catch(()=>setFxList([])).finally(()=>setFxLoading(false));}},[track&&track.id]);const previewAudioRef=React.useRef(null);const[vstBypass,setVstBypass]=React.useState(!!(track&&track.vstFxBypass));const[activeVstIdx,setActiveVstIdx]=React.useState(-1);const[vstPickerOpen,setVstPickerOpen]=React.useState(false);if(!track)return null;const chain=track.fxChain||[];// ── VST FX chain (native_bridge --render-fx) — tham chiếu từ unified chain ── const vstChain=chain.filter(m=>m&&m.type==='vst3');// Unified chain strip: builtin DSP + VST FX chung 1 chain (kéo đổi thứ tự giữa cả 2 loại). const unifiedChain=chain.map((m,i)=>({kind:m&&m.type==='vst3'?'vst':'builtin',m,i}));const setVstChain=next=>{const builtin=chain.filter(m=>!m||m.type!=='vst3');const merged=[...builtin,...next.map(s=>({type:'vst3',path:s.path||'',name:s.name||'',preset_b64:s.preset_b64||'',bypass:!!s.bypass}))];if(onUpdateTrack)onUpdateTrack(track.id,{fxChain:merged,vstFxChain:next,vstFxBypass:vstBypass});if(window.__rebuildTrackFxGraph)window.__rebuildTrackFxGraph(track.id,{fxChain:merged,vstFxChain:next,vstFxBypass:vstBypass});};// Embedded VST GUI state (PLAN_MASTERBUS_VST_GUI_EMBED.md Phase 3) const[fxGuiOpen,setFxGuiOpenState]=React.useState(_persistFxGuiOpen);// { path, url } | null -const setFxGuiOpen=v=>{if(_persistFxGuiOpen&&_persistFxGuiOpen.url)_fxGuiUnregisterSource(_persistFxGuiOpen.url);_persistFxGuiOpen=v;_persistFxGuiTrackId=v?track&&track.id:null;if(v&&v.url)_fxGuiRegisterSource(v.url,track&&track.id);setFxGuiOpenState(v);};const fxGuiOpenRef=React.useRef(null);fxGuiOpenRef.current=fxGuiOpen;const closeFxGui=()=>{const g=fxGuiOpenRef.current;if(g){try{fetch(g.url+'/close',{method:'POST'}).catch(()=>{});}catch(e){}}setFxGuiOpen(null);if(onUpdateTrack&&track)onUpdateTrack(track.id,{vstGuiOpenPath:null,vstGuiOpenName:null});};React.useEffect(()=>()=>{const g=fxGuiOpenRef.current;if(g){try{fetch(g.url+'/hide',{method:'POST'}).catch(()=>{});}catch(e){}}},[]);// Capture GUI knob tweaks while the embedded GUI is open (bridge /preset). -React.useEffect(()=>{if(!fxGuiOpen||!fxGuiOpen.url)return;const iv=setInterval(()=>{fetch(fxGuiOpen.url+'/preset').then(r=>r.json()).then(d=>{if(d&&d.preset_b64)_capturedPresetByPath[fxGuiOpen.path]=d.preset_b64;}).catch(()=>{});},1500);return()=>clearInterval(iv);// eslint-disable-next-line react-hooks/exhaustive-deps +const setFxGuiOpen=v=>{if(_persistFxGuiOpen&&_persistFxGuiOpen.url)_fxGuiUnregisterSource(_persistFxGuiOpen.url);_persistFxGuiOpen=v;_persistFxGuiTrackId=v?track&&track.id:null;if(v&&v.url)_fxGuiRegisterSource(v.url,track&&track.id);setFxGuiOpenState(v);};const fxGuiOpenRef=React.useRef(null);fxGuiOpenRef.current=fxGuiOpen;const closeFxGui=()=>{const g=fxGuiOpenRef.current;if(g){// Capture preset CUỐI trước khi đóng (poll 1.5s có thể chưa kịp khi chỉnh +// xong đóng ngay) — gọi /preset TRƯỚC /close (close kill process bridge). +try{fetch(g.url+'/preset').then(r=>r.json()).then(d=>{if(d&&d.preset_b64&&g.path)_capturedPresetByPath[g.path]=d.preset_b64;}).catch(()=>{}).then(()=>{try{fetch(g.url+'/close',{method:'POST'}).catch(()=>{});}catch(e){}});}catch(e){try{fetch(g.url+'/close',{method:'POST'}).catch(()=>{});}catch(e2){}}}setFxGuiOpen(null);if(g&&g.path){const _tk='track:'+(track&&track.id||'')+':'+g.path;if(_presetRestartTimers[_tk]){clearTimeout(_presetRestartTimers[_tk]);delete _presetRestartTimers[_tk];}delete _fxGuiBaselineByPath[g.path];}if(onUpdateTrack&&track)onUpdateTrack(track.id,{vstGuiOpenPath:null,vstGuiOpenName:null});};React.useEffect(()=>()=>{const g=fxGuiOpenRef.current;if(g){try{fetch(g.url+'/hide',{method:'POST'}).catch(()=>{});}catch(e){}const _tk='track:'+(track&&track.id||'')+':'+g.path;if(_presetRestartTimers[_tk]){clearTimeout(_presetRestartTimers[_tk]);delete _presetRestartTimers[_tk];}if(g.path)delete _fxGuiBaselineByPath[g.path];}},[]);// Capture GUI knob tweaks while the embedded GUI is open (bridge /preset). +React.useEffect(()=>{if(!fxGuiOpen||!fxGuiOpen.url)return;const iv=setInterval(()=>{fetch(fxGuiOpen.url+'/preset').then(r=>r.json()).then(d=>{if(d&&d.preset_b64){const _p=fxGuiOpen.path;const _b=_fxGuiBaselineByPath[_p];if(_b===undefined){_fxGuiBaselineByPath[_p]=d.preset_b64;_capturedPresetByPath[_p]=d.preset_b64;return;}if(d.preset_b64!==_b){_fxGuiBaselineByPath[_p]=d.preset_b64;_capturedPresetByPath[_p]=d.preset_b64;const _tid=track&&track.id;_schedulePresetRestart('track:'+(_tid||'')+':'+_p,()=>{if(_tid&&window.__rebuildTrackFxGraph)window.__rebuildTrackFxGraph(_tid,{});},3000);}}}).catch(()=>{});},1500);return()=>clearInterval(iv);// eslint-disable-next-line react-hooks/exhaustive-deps },[fxGuiOpen]);// Reopen the saved GUI when the rack is mounted after a project restore. -React.useEffect(()=>{if(!track||!track.vstGuiOpenPath||fxGuiOpen)return;const s=(track.fxChain||[]).find(x=>x.path===track.vstGuiOpenPath);if(!s||!window.SonicAPI||!window.SonicAPI.openFxGui)return;window.SonicAPI.openFxGui({path:s.path,name:s.name||s.path,embed:true,shm:fxRtTrackShmName(track&&track.id)}).then(r=>{if(r&&r.embed_url)setFxGuiOpen({path:s.path,url:r.embed_url});}).catch(()=>{});// eslint-disable-next-line react-hooks/exhaustive-deps -},[track&&track.id,track&&track.vstGuiOpenPath]);const toggleVst=idx=>setVstChain(vstChain.map((s,i)=>i===idx?{...s,bypass:!s.bypass}:s));const removeVst=idx=>{const rem=vstChain[idx];if(rem&&fxGuiOpen&&fxGuiOpen.path===rem.path)closeFxGui();if(rem)delete _capturedPresetByPath[rem.path];if(idx===activeVstIdx)setActiveVstIdx(-1);setVstChain(vstChain.filter((_,i)=>i!==idx));};const moveVst=(idx,dir)=>{const j=idx+dir;if(j<0||j>=vstChain.length)return;const next=[...vstChain];const mv=next.splice(idx,1)[0];next.splice(j,0,mv);setVstChain(next);};const openVstGui=(s,idx)=>{if(!s||!s.path){window.showToast&&window.showToast('Chọn VST FX trước','warning');return;}if(fxGuiOpen)closeFxGui();if(idx!==undefined)setActiveVstIdx(idx);if(!window.SonicAPI||!window.SonicAPI.openFxGui){window.showToast&&window.showToast('Máy này không hỗ trợ mở GUI VST','warning');return;}window.SonicAPI.openFxGui({path:s.path,name:s.name||s.path,embed:true,shm:fxRtTrackShmName(track&&track.id)}).then(r=>{if(r&&r.embed_url){setFxGuiOpen({path:s.path,url:r.embed_url,name:s.name||s.path});if(onUpdateTrack&&track)onUpdateTrack(track.id,{vstGuiOpenPath:s.path,vstGuiOpenName:s.name||s.path});}else if(r&&r.already_running&&r.embed_url){setFxGuiOpen({path:s.path,url:r.embed_url,name:s.name||s.path});if(onUpdateTrack&&track)onUpdateTrack(track.id,{vstGuiOpenPath:s.path,vstGuiOpenName:s.name||s.path});}else if(r&&r.already_running)window.showToast&&window.showToast('GUI của plugin này đang mở sẵn (cửa sổ ngoài)','info');else window.showToast&&window.showToast('Không mở được GUI embed','error');}).catch(err=>window.showToast&&window.showToast('Lỗi mở GUI: '+(err.message||err),'error'));};const addVst=path=>{const fx=(fxList||[]).find(f=>f.path===path);if(!fx)return;const next=[...vstChain,{type:'vst3',path:fx.path,name:fx.name||fx.id,preset_b64:'',bypass:false}];setVstChain(next);setActiveVstIdx(next.length-1);};const changeVstPlugin=(idx,path)=>{const fx=(fxList||[]).find(f=>f.path===path);delete _capturedPresetByPath[path];setVstChain(vstChain.map((s,i)=>i===idx?{...s,path,name:fx?fx.name||fx.id:s.name,preset_b64:''}:s));};const uploadVstPreset=idx=>{const inp=document.createElement('input');inp.type='file';inp.accept='.vstpreset,.fxp,.fxb,.dspreset';inp.onchange=()=>{const f=inp.files&&inp.files[0];if(!f)return;const reader=new FileReader();reader.onload=()=>{const b64=String(reader.result||'').split(',')[1]||'';setVstChain(vstChain.map((s,i)=>i===idx?{...s,preset_b64:b64}:s));window.showToast&&window.showToast('Đã gắn preset .vstpreset vào slot '+(idx+1),'success');};reader.readAsDataURL(f);};inp.click();};const previewFx=async()=>{try{if(previewAudioRef.current){previewAudioRef.current.pause();previewAudioRef.current=null;}if(!window.__renderProjectPreview){window.showToast&&window.showToast('Không có hàm render preview','warning');return;}window.showToast&&window.showToast('Đang render offline (bridge)...','info');const res=await window.__renderProjectPreview();const au=new Audio((window.API_BASE_URL||'')+res.url);previewAudioRef.current=au;au.onended=()=>{previewAudioRef.current=null;};au.play().then(()=>window.showToast&&window.showToast('Preview offline — âm thật = âm export (VST FX)','success')).catch(()=>{});}catch(e){/* toast ở __renderProjectPreview */}};const setChain=next=>{if(onUpdateTrack)onUpdateTrack(track.id,{fxChain:next});if(window.__rebuildTrackFxGraph)window.__rebuildTrackFxGraph(track.id,{fxChain:next});};const paramsOf=m=>({...(TRACK_FX_DEFAULTS[m.type]||{}),...(m.params||{})});const setParams=(idx,patch)=>{const next=chain.map((m,i)=>i===idx?{...m,params:{...paramsOf(m),...patch}}:m);setChain(next);};const toggleMod=idx=>{const next=chain.map((m,i)=>i===idx?{...m,active:!(m.active!==false)}:m);setChain(next);};const removeMod=idx=>setChain(chain.filter((_,i)=>i!==idx));const addMod=type=>{const def=TRACK_FX_DEFAULTS[type]||{};// Deep-clone default params so each chain entry owns its data (bands array +React.useEffect(()=>{if(!track||!track.vstGuiOpenPath||fxGuiOpen)return;const s=(track.fxChain||[]).find(x=>x.path===track.vstGuiOpenPath);if(!s||!window.SonicAPI||!window.SonicAPI.openFxGui)return;window.SonicAPI.openFxGui({path:s.path,name:s.name||s.path,embed:true,shm:fxRtTrackShmName(track&&track.id),preset_b64:_capturedPresetByPath[s.path]||s.preset_b64||''}).then(r=>{if(r&&r.embed_url)setFxGuiOpen({path:s.path,url:r.embed_url});}).catch(()=>{});// eslint-disable-next-line react-hooks/exhaustive-deps +},[track&&track.id,track&&track.vstGuiOpenPath]);const toggleVst=idx=>setVstChain(vstChain.map((s,i)=>i===idx?{...s,bypass:!s.bypass}:s));const removeVst=idx=>{const rem=vstChain[idx];if(rem&&fxGuiOpen&&fxGuiOpen.path===rem.path)closeFxGui();if(rem)delete _capturedPresetByPath[rem.path];if(idx===activeVstIdx)setActiveVstIdx(-1);setVstChain(vstChain.filter((_,i)=>i!==idx));};const moveVst=(idx,dir)=>{const j=idx+dir;if(j<0||j>=vstChain.length)return;const next=[...vstChain];const mv=next.splice(idx,1)[0];next.splice(j,0,mv);setVstChain(next);};const openVstGui=(s,idx)=>{if(!s||!s.path){window.showToast&&window.showToast('Chọn VST FX trước','warning');return;}if(fxGuiOpen)closeFxGui();if(idx!==undefined)setActiveVstIdx(idx);if(!window.SonicAPI||!window.SonicAPI.openFxGui){window.showToast&&window.showToast('Máy này không hỗ trợ mở GUI VST','warning');return;}window.SonicAPI.openFxGui({path:s.path,name:s.name||s.path,embed:true,shm:fxRtTrackShmName(track&&track.id),preset_b64:_capturedPresetByPath[s.path]||s.preset_b64||''}).then(r=>{if(r&&r.embed_url){setFxGuiOpen({path:s.path,url:r.embed_url,name:s.name||s.path});if(onUpdateTrack&&track)onUpdateTrack(track.id,{vstGuiOpenPath:s.path,vstGuiOpenName:s.name||s.path});}else if(r&&r.already_running&&r.embed_url){setFxGuiOpen({path:s.path,url:r.embed_url,name:s.name||s.path});if(onUpdateTrack&&track)onUpdateTrack(track.id,{vstGuiOpenPath:s.path,vstGuiOpenName:s.name||s.path});}else if(r&&r.already_running)window.showToast&&window.showToast('GUI của plugin này đang mở sẵn (cửa sổ ngoài)','info');else window.showToast&&window.showToast('Không mở được GUI embed','error');}).catch(err=>window.showToast&&window.showToast('Lỗi mở GUI: '+(err.message||err),'error'));};const addVst=path=>{const fx=(fxList||[]).find(f=>f.path===path);if(!fx)return;const next=[...vstChain,{type:'vst3',path:fx.path,name:fx.name||fx.id,preset_b64:'',bypass:false}];setVstChain(next);setActiveVstIdx(next.length-1);};const changeVstPlugin=(idx,path)=>{const fx=(fxList||[]).find(f=>f.path===path);delete _capturedPresetByPath[path];setVstChain(vstChain.map((s,i)=>i===idx?{...s,path,name:fx?fx.name||fx.id:s.name,preset_b64:''}:s));};const uploadVstPreset=idx=>{const inp=document.createElement('input');inp.type='file';inp.accept='.vstpreset,.fxp,.fxb,.dspreset';inp.onchange=()=>{const f=inp.files&&inp.files[0];if(!f)return;const reader=new FileReader();reader.onload=()=>{const b64=String(reader.result||'').split(',')[1]||'';setVstChain(vstChain.map((s,i)=>i===idx?{...s,preset_b64:b64}:s));window.showToast&&window.showToast('Đã gắn preset .vstpreset vào slot '+(idx+1),'success');};reader.readAsDataURL(f);};inp.click();};const previewFx=async()=>{try{if(previewAudioRef.current){previewAudioRef.current.pause();previewAudioRef.current=null;}if(!window.__renderProjectPreview){window.showToast&&window.showToast('Không có hàm render preview','warning');return;}window.showToast&&window.showToast('Đang render offline (bridge)...','info');const res=await window.__renderProjectPreview();const au=new Audio((window.API_BASE_URL||'')+res.url);previewAudioRef.current=au;au.onended=()=>{previewAudioRef.current=null;};au.play().then(()=>window.showToast&&window.showToast('Preview offline — âm thật = âm export (VST FX)','success')).catch(()=>{});}catch(e){/* toast ở __renderProjectPreview */}};const setChain=next=>{if(onUpdateTrack)onUpdateTrack(track.id,{fxChain:next});if(window.__rebuildTrackFxGraph)window.__rebuildTrackFxGraph(track.id,{fxChain:next});};const paramsOf=m=>({...(TRACK_FX_DEFAULTS[m.type]||{}),...(m.params||{})});const setParams=(idx,patch)=>{const next=chain.map((m,i)=>i===idx?{...m,params:{...paramsOf(m),...patch}}:m);setChain(next);};const toggleMod=idx=>{const next=chain.map((m,i)=>i===idx?{...m,active:!(m.active!==false)}:m);setChain(next);};const removeMod=idx=>setChain(chain.filter((_,i)=>i!==idx));const addMod=type=>{const def=TRACK_FX_DEFAULTS[type]||{};// Deep-clone default params so each chain entry owns its data (bands array // especially — shared references would corrupt other modules' state). const params=Array.isArray(def.bands)?{...def,bands:JSON.parse(JSON.stringify(def.bands))}:{...def};setChain([...chain,{type,active:true,params}]);setActiveType(type);setActiveVstIdx(-1);setAddModuleOpen(false);};const applyPreset=key=>{const preset=TRACK_EQ_PRESETS[key];if(!preset)return;const idx=chain.findIndex(m=>m.type==='eq'&&m.active!==false);if(idx>=0)setParams(idx,{g1:preset.g[0],g2:preset.g[1],g3:preset.g[2],g4:preset.g[3]});};const activeMod=chain.find(m=>m.type===activeType)||chain[chain.length-1]||null;const activeIdx=chain.findIndex(m=>m===activeMod);const ap=activeMod?paramsOf(activeMod):{};const slider=(label,val,min,max,step,color,onChange,fmt)=>/*#__PURE__*/React.createElement("div",{className:"flex flex-col gap-1"},/*#__PURE__*/React.createElement("div",{className:"flex justify-between text-[11px] font-mono"},/*#__PURE__*/React.createElement("span",{style:{color,fontWeight:700}},label),/*#__PURE__*/React.createElement("span",{className:"text-slate-300"},fmt?fmt(val):val)),/*#__PURE__*/React.createElement("input",{type:"range",min:min,max:max,step:step||0.1,value:val,onChange:e=>onChange(parseFloat(e.target.value)),className:"w-full h-1 cursor-pointer",style:{accentColor:color}}));// ── Wave Observer real-time scope render loop ── React.useEffect(()=>{const canvas=scopeCanvasRef.current;if(!canvas||!track)return;const st=scopeStateRef.current;let raf=null;const draw=()=>{raf=requestAnimationFrame(draw);const w=canvas.width,h=canvas.height;const ctx=canvas.getContext('2d');ctx.clearRect(0,0,w,h);// Grid @@ -846,15 +897,16 @@ ctx.fillStyle='#475569';ctx.font='9px monospace';ctx.fillText('+12 dB',4,midY-h/ let _persistMasterGuiOpen=null;const MasteringModal=({isOpen,onClose,masteringSettings,setMasteringSettings})=>{const ozState=masteringSettings;const setOzState=setMasteringSettings;const[isPlaying,setIsPlaying]=React.useState(false);const masterConnected=ozState.masterConnected;const setMasterConnected=val=>{setOzState(prev=>({...prev,masterConnected:typeof val==='function'?val(prev.masterConnected):val}));};// ── VST FX masterbus (native_bridge --render-fx, áp dụng khi Export/Offline render) ── const masterVstChain=ozState.vstFxChain||[];// Embedded VST GUI state (PLAN_MASTERBUS_VST_GUI_EMBED.md Phase 2) const[masterGuiOpen,setMasterGuiOpenState]=React.useState(_persistMasterGuiOpen);// { path, url } | null -const setMasterGuiOpen=v=>{if(_persistMasterGuiOpen&&_persistMasterGuiOpen.url)_fxGuiUnregisterSource(_persistMasterGuiOpen.url);_persistMasterGuiOpen=v;if(v&&v.url)_fxGuiRegisterSource(v.url,null);setMasterGuiOpenState(v);};const[activeMasterVstPath,setActiveMasterVstPath]=React.useState(null);const masterGuiOpenRef=React.useRef(null);masterGuiOpenRef.current=masterGuiOpen;const closeMasterGui=()=>{const g=masterGuiOpenRef.current;if(g){try{fetch(g.url+'/close',{method:'POST'}).catch(()=>{});}catch(e){}}setMasterGuiOpen(null);setActiveMasterVstPath(null);setOzState(prev=>{const n={...(prev||{})};delete n.gui_open_path;delete n.gui_open_name;return n;});};React.useEffect(()=>()=>{const g=masterGuiOpenRef.current;if(g){try{fetch(g.url+'/hide',{method:'POST'}).catch(()=>{});}catch(e){}}},[]);// Capture GUI knob tweaks while the embedded GUI is open (bridge /preset). -React.useEffect(()=>{if(!masterGuiOpen||!masterGuiOpen.url)return;const iv=setInterval(()=>{fetch(masterGuiOpen.url+'/preset').then(r=>r.json()).then(d=>{if(d&&d.preset_b64)_capturedPresetByPath[masterGuiOpen.path]=d.preset_b64;}).catch(()=>{});},1500);return()=>clearInterval(iv);// eslint-disable-next-line react-hooks/exhaustive-deps +const setMasterGuiOpen=v=>{if(_persistMasterGuiOpen&&_persistMasterGuiOpen.url)_fxGuiUnregisterSource(_persistMasterGuiOpen.url);_persistMasterGuiOpen=v;if(v&&v.url)_fxGuiRegisterSource(v.url,null);setMasterGuiOpenState(v);};const[activeMasterVstPath,setActiveMasterVstPath]=React.useState(null);const masterGuiOpenRef=React.useRef(null);masterGuiOpenRef.current=masterGuiOpen;const closeMasterGui=()=>{const g=masterGuiOpenRef.current;if(g){// Capture preset CUỐI trước khi đóng (giống closeFxGui) — /preset rồi /close. +try{fetch(g.url+'/preset').then(r=>r.json()).then(d=>{if(d&&d.preset_b64&&g.path)_capturedPresetByPath[g.path]=d.preset_b64;}).catch(()=>{}).then(()=>{try{fetch(g.url+'/close',{method:'POST'}).catch(()=>{});}catch(e){}});}catch(e){try{fetch(g.url+'/close',{method:'POST'}).catch(()=>{});}catch(e2){}}}setMasterGuiOpen(null);if(g&&g.path){const _mk='master:'+g.path;if(_presetRestartTimers[_mk]){clearTimeout(_presetRestartTimers[_mk]);delete _presetRestartTimers[_mk];}delete _fxGuiBaselineByPath[g.path];}setActiveMasterVstPath(null);setOzState(prev=>{const n={...(prev||{})};delete n.gui_open_path;delete n.gui_open_name;return n;});};React.useEffect(()=>()=>{const g=masterGuiOpenRef.current;if(g){try{fetch(g.url+'/hide',{method:'POST'}).catch(()=>{});}catch(e){}const _mk='master:'+g.path;if(_presetRestartTimers[_mk]){clearTimeout(_presetRestartTimers[_mk]);delete _presetRestartTimers[_mk];}if(g.path)delete _fxGuiBaselineByPath[g.path];}},[]);// Capture GUI knob tweaks while the embedded GUI is open (bridge /preset). +React.useEffect(()=>{if(!masterGuiOpen||!masterGuiOpen.url)return;const iv=setInterval(()=>{fetch(masterGuiOpen.url+'/preset').then(r=>r.json()).then(d=>{if(d&&d.preset_b64){const _p=masterGuiOpen.path;const _b=_fxGuiBaselineByPath[_p];if(_b===undefined){_fxGuiBaselineByPath[_p]=d.preset_b64;_capturedPresetByPath[_p]=d.preset_b64;return;}if(d.preset_b64!==_b){_fxGuiBaselineByPath[_p]=d.preset_b64;_capturedPresetByPath[_p]=d.preset_b64;_schedulePresetRestart('master:'+_p,()=>fxRtStart(),3000);}}}).catch(()=>{});},1500);return()=>clearInterval(iv);// eslint-disable-next-line react-hooks/exhaustive-deps },[masterGuiOpen]);// Reopen the saved GUI when the panel is opened after a project restore. -React.useEffect(()=>{if(!isOpen||!ozState||!ozState.gui_open_path||masterGuiOpen)return;const s=(ozState.vstFxChain||[]).find(x=>x.path===ozState.gui_open_path);if(!s||!window.SonicAPI||!window.SonicAPI.openFxGui)return;window.SonicAPI.openFxGui({path:s.path,name:ozState.gui_open_name||s.name||s.path,embed:true,shm:fxRt.sessionId||''}).then(r=>{if(r&&r.embed_url)setMasterGuiOpen({path:s.path,url:r.embed_url});}).catch(()=>{});// eslint-disable-next-line react-hooks/exhaustive-deps +React.useEffect(()=>{if(!isOpen||!ozState||!ozState.gui_open_path||masterGuiOpen)return;const s=(ozState.vstFxChain||[]).find(x=>x.path===ozState.gui_open_path);if(!s||!window.SonicAPI||!window.SonicAPI.openFxGui)return;window.SonicAPI.openFxGui({path:s.path,name:ozState.gui_open_name||s.name||s.path,embed:true,shm:fxRt.sessionId||'',preset_b64:_capturedPresetByPath[s.path]||s.preset_b64||''}).then(r=>{if(r&&r.embed_url)setMasterGuiOpen({path:s.path,url:r.embed_url});}).catch(()=>{});// eslint-disable-next-line react-hooks/exhaustive-deps },[isOpen,ozState&&ozState.gui_open_path]);const setMasterVstChain=next=>setOzState(prev=>{const chain=prev.chain||[];const out=[];let vi=0;const mk=(s,i)=>({id:'mod_vst_'+Date.now()+'_'+i+'_'+Math.random().toString(36).slice(2,8),type:'vst3',path:s.path,name:s.name||'',preset_b64:s.preset_b64||'',bypass:!!s.bypass,active:true});chain.forEach(m=>{if(m.type==='vst3'){const s=next[vi];if(s){out.push(mk(s,vi));vi++;}}else out.push(m);});for(;visetMasterVstChain(masterVstChain.map((s,i)=>i===idx?{...s,bypass:!s.bypass}:s));const removeMasterVst=idx=>{const rem=masterVstChain[idx];if(rem)delete _capturedPresetByPath[rem.path];setMasterVstChain(masterVstChain.filter((_,i)=>i!==idx));};const moveMasterVst=(idx,dir)=>{const j=idx+dir;if(j<0||j>=masterVstChain.length)return;const next=[...masterVstChain];const mv=next.splice(idx,1)[0];next.splice(j,0,mv);setMasterVstChain(next);};const openMasterVstGui=s=>{if(!s||!s.path){window.showToast&&window.showToast('Chọn VST FX trước','warning');return;}if(masterGuiOpen)closeMasterGui();if(s.path)setActiveMasterVstPath(s.path);if(!window.SonicAPI||!window.SonicAPI.openFxGui){window.showToast&&window.showToast('Máy này không hỗ trợ mở GUI VST','warning');return;}window.SonicAPI.openFxGui({path:s.path,name:s.name||s.path,embed:true,shm:fxRt.sessionId||''}).then(r=>{if(r&&r.embed_url){setMasterGuiOpen({path:s.path,url:r.embed_url,name:s.name||s.path});setOzState(prev=>({...(prev||{}),gui_open_path:s.path,gui_open_name:s.name||s.path}));}else if(r&&r.already_running&&r.embed_url){setMasterGuiOpen({path:s.path,url:r.embed_url,name:s.name||s.path});setOzState(prev=>({...(prev||{}),gui_open_path:s.path,gui_open_name:s.name||s.path}));}else if(r&&r.already_running)window.showToast&&window.showToast('GUI của plugin này đang mở sẵn (cửa sổ ngoài)','info');else window.showToast&&window.showToast('Không mở được GUI embed','error');}).catch(err=>window.showToast&&window.showToast('Lỗi mở GUI: '+(err.message||err),'error'));};const addMasterVst=path=>{const fx=(masterFxList||[]).find(f=>f.path===path);if(!fx)return;setMasterVstChain([...masterVstChain,{type:'vst3',path:fx.path,name:fx.name||fx.id,preset_b64:'',bypass:false}]);openMasterVstGui({path:fx.path,name:fx.name||fx.id});};const changeMasterVstPlugin=(idx,path)=>{const fx=(masterFxList||[]).find(f=>f.path===path);delete _capturedPresetByPath[path];setMasterVstChain(masterVstChain.map((s,i)=>i===idx?{...s,path,name:fx?fx.name||fx.id:s.name,preset_b64:''}:s));};const uploadMasterVstPreset=idx=>{const inp=document.createElement('input');inp.type='file';inp.accept='.vstpreset,.fxp,.fxb,.dspreset';inp.onchange=()=>{const f=inp.files&&inp.files[0];if(!f)return;const reader=new FileReader();reader.onload=()=>{const b64=String(reader.result||'').split(',')[1]||'';setMasterVstChain(masterVstChain.map((s,i)=>i===idx?{...s,preset_b64:b64}:s));window.showToast&&window.showToast('Đã gắn preset .vstpreset vào slot '+(idx+1),'success');};reader.readAsDataURL(f);};inp.click();};const previewMasterFx=async()=>{try{if(previewAudioRef.current){previewAudioRef.current.pause();previewAudioRef.current=null;}if(!window.__renderProjectPreview){window.showToast&&window.showToast('Không có hàm render preview','warning');return;}window.showToast&&window.showToast('Đang render offline (bridge)...','info');const res=await window.__renderProjectPreview();const au=new Audio((window.API_BASE_URL||'')+res.url);previewAudioRef.current=au;au.onended=()=>{previewAudioRef.current=null;};au.play().then(()=>window.showToast&&window.showToast('Preview offline — âm thật = âm export (VST FX)','success')).catch(()=>{});}catch(e){/* toast ở __renderProjectPreview */}};const audioRef=React.useRef({source:null});const eqCanvasRef=React.useRef(null);const imagerCanvasRef=React.useRef(null);const inMeterCanvasRef=React.useRef(null);const outMeterCanvasRef=React.useRef(null);const animFrameRef=React.useRef(null);const lufsAccRef=React.useRef([]);const knobsInitializedRef=React.useRef(false);// VST FX masterbus (native_bridge --render-fx) — list VST3 effect plugins + preview +const toggleMasterVst=idx=>setMasterVstChain(masterVstChain.map((s,i)=>i===idx?{...s,bypass:!s.bypass}:s));const removeMasterVst=idx=>{const rem=masterVstChain[idx];if(rem)delete _capturedPresetByPath[rem.path];setMasterVstChain(masterVstChain.filter((_,i)=>i!==idx));};const moveMasterVst=(idx,dir)=>{const j=idx+dir;if(j<0||j>=masterVstChain.length)return;const next=[...masterVstChain];const mv=next.splice(idx,1)[0];next.splice(j,0,mv);setMasterVstChain(next);};const openMasterVstGui=s=>{if(!s||!s.path){window.showToast&&window.showToast('Chọn VST FX trước','warning');return;}if(masterGuiOpen)closeMasterGui();if(s.path)setActiveMasterVstPath(s.path);if(!window.SonicAPI||!window.SonicAPI.openFxGui){window.showToast&&window.showToast('Máy này không hỗ trợ mở GUI VST','warning');return;}window.SonicAPI.openFxGui({path:s.path,name:s.name||s.path,embed:true,shm:fxRt.sessionId||'',preset_b64:_capturedPresetByPath[s.path]||s.preset_b64||''}).then(r=>{if(r&&r.embed_url){setMasterGuiOpen({path:s.path,url:r.embed_url,name:s.name||s.path});setOzState(prev=>({...(prev||{}),gui_open_path:s.path,gui_open_name:s.name||s.path}));}else if(r&&r.already_running&&r.embed_url){setMasterGuiOpen({path:s.path,url:r.embed_url,name:s.name||s.path});setOzState(prev=>({...(prev||{}),gui_open_path:s.path,gui_open_name:s.name||s.path}));}else if(r&&r.already_running)window.showToast&&window.showToast('GUI của plugin này đang mở sẵn (cửa sổ ngoài)','info');else window.showToast&&window.showToast('Không mở được GUI embed','error');}).catch(err=>window.showToast&&window.showToast('Lỗi mở GUI: '+(err.message||err),'error'));};const addMasterVst=path=>{const fx=(masterFxList||[]).find(f=>f.path===path);if(!fx)return;setMasterVstChain([...masterVstChain,{type:'vst3',path:fx.path,name:fx.name||fx.id,preset_b64:'',bypass:false}]);openMasterVstGui({path:fx.path,name:fx.name||fx.id});};const changeMasterVstPlugin=(idx,path)=>{const fx=(masterFxList||[]).find(f=>f.path===path);delete _capturedPresetByPath[path];setMasterVstChain(masterVstChain.map((s,i)=>i===idx?{...s,path,name:fx?fx.name||fx.id:s.name,preset_b64:''}:s));};const uploadMasterVstPreset=idx=>{const inp=document.createElement('input');inp.type='file';inp.accept='.vstpreset,.fxp,.fxb,.dspreset';inp.onchange=()=>{const f=inp.files&&inp.files[0];if(!f)return;const reader=new FileReader();reader.onload=()=>{const b64=String(reader.result||'').split(',')[1]||'';setMasterVstChain(masterVstChain.map((s,i)=>i===idx?{...s,preset_b64:b64}:s));window.showToast&&window.showToast('Đã gắn preset .vstpreset vào slot '+(idx+1),'success');};reader.readAsDataURL(f);};inp.click();};const previewMasterFx=async()=>{try{if(previewAudioRef.current){previewAudioRef.current.pause();previewAudioRef.current=null;}if(!window.__renderProjectPreview){window.showToast&&window.showToast('Không có hàm render preview','warning');return;}window.showToast&&window.showToast('Đang render offline (bridge)...','info');const res=await window.__renderProjectPreview();const au=new Audio((window.API_BASE_URL||'')+res.url);previewAudioRef.current=au;au.onended=()=>{previewAudioRef.current=null;};au.play().then(()=>window.showToast&&window.showToast('Preview offline — âm thật = âm export (VST FX)','success')).catch(()=>{});}catch(e){/* toast ở __renderProjectPreview */}};const audioRef=React.useRef({source:null});const eqCanvasRef=React.useRef(null);const imagerCanvasRef=React.useRef(null);const inMeterCanvasRef=React.useRef(null);const outMeterCanvasRef=React.useRef(null);const animFrameRef=React.useRef(null);const lufsAccRef=React.useRef([]);const knobsInitializedRef=React.useRef(false);// VST FX masterbus (native_bridge --render-fx) — list VST3 effect plugins + preview const[masterFxList,setMasterFxList]=React.useState([]);const[masterFxLoading,setMasterFxLoading]=React.useState(false);React.useEffect(()=>{if(window.SonicAPI&&window.SonicAPI.listFx){setMasterFxLoading(true);window.SonicAPI.listFx().then(d=>setMasterFxList(d&&d.plugins||[])).catch(()=>setMasterFxList([])).finally(()=>setMasterFxLoading(false));}},[isOpen]);const previewAudioRef=React.useRef(null);const[addMasterVstSel,setAddMasterVstSel]=React.useState('');const[masterVstPickerOpen,setMasterVstPickerOpen]=React.useState(false);// Wave Observer Refs & States const woCanvasRef=React.useRef(null);const woLeftHistoryRef=React.useRef(new Float32Array(400).fill(0));const woRightHistoryRef=React.useRef(new Float32Array(400).fill(0));const woLeftMeterRef=React.useRef(null);const woRightMeterRef=React.useRef(null);const[woPaused,setWoPaused]=React.useState(false);const[woChannel,setWoChannel]=React.useState('stereo');const[woMode,setWoMode]=React.useState('waveform');const[woDuration,setWoDuration]=React.useState(2.0);const[woZoom,setWoZoom]=React.useState(0.0);const woPausedRef=React.useRef(woPaused);woPausedRef.current=woPaused;const woChannelRef=React.useRef(woChannel);woChannelRef.current=woChannel;const woModeRef=React.useRef(woMode);woModeRef.current=woMode;const woDurationRef=React.useRef(woDuration);woDurationRef.current=woDuration;const woZoomRef=React.useRef(woZoom);woZoomRef.current=woZoom;const ozStateRef=React.useRef(ozState);ozStateRef.current=ozState;function startAudioDemo(){getAudioContext();const ctx=audioCtx;if(ctx.state==='suspended')ctx.resume();stopAudioDemo();const sampleRate=ctx.sampleRate;const bufferSize=sampleRate*4;const buffer=ctx.createBuffer(2,bufferSize,sampleRate);const left=buffer.getChannelData(0);const right=buffer.getChannelData(1);for(let i=0;i{if(!isOpen)return;getAudioContext();function resizeAll(){const resizeCanvas=ref=>{const el=ref.current;if(el){el.width=el.clientWidth;el.height=el.clientHeight;}};resizeCanvas(eqCanvasRef);resizeCanvas(imagerCanvasRef);resizeCanvas(inMeterCanvasRef);resizeCanvas(outMeterCanvasRef);resizeCanvas(woCanvasRef);}resizeAll();window.addEventListener('resize',resizeAll);const fftData=new Uint8Array(1024);function getPeakLevel(analyser){if(!analyser)return 0;const bufferLength=analyser.fftSize;const dataArray=new Float32Array(bufferLength);analyser.getFloatTimeDomainData(dataArray);let maxVal=0;for(let i=0;imaxVal){maxVal=val;}}return maxVal;}function renderFrame(){animFrameRef.current=requestAnimationFrame(renderFrame);const s=ozStateRef.current;// EQ Spectrum const eqCanvas=eqCanvasRef.current;if(eqCanvas){const w=eqCanvas.width,h=eqCanvas.height;const eqCtx=eqCanvas.getContext('2d');eqCtx.clearRect(0,0,w,h);eqCtx.strokeStyle='rgba(51, 65, 85, 0.3)';eqCtx.lineWidth=1;eqCtx.font='9px JetBrains Mono';eqCtx.fillStyle='#475569';const freqs=[20,50,100,200,500,1000,2000,5000,10000,20000];freqs.forEach(f=>{const x=Math.log10(f/20)/Math.log10(20000/20)*w;eqCtx.beginPath();eqCtx.moveTo(x,0);eqCtx.lineTo(x,h);eqCtx.stroke();if(f>=1000)eqCtx.fillText(`${f/1000}k`,x+3,h-6);else eqCtx.fillText(`${f}`,x+3,h-6);});if(masterBus&&masterBus.outputAnalyser){masterBus.outputAnalyser.getByteFrequencyData(fftData);eqCtx.fillStyle='rgba(56, 189, 248, 0.15)';const barWidth=w/128;for(let i=0;i<128;i++){const val=fftData[i*4]/255;eqCtx.fillRect(i*barWidth,h-val*h,barWidth-1,val*h);}}eqCtx.strokeStyle='#38bdf8';eqCtx.lineWidth=2.5;eqCtx.beginPath();for(let x=0;x{const schema=serializeProjectToSchema(currentProjectId||'temp_project',projectName||'Dự án tạm chưa lưu',bpm,tracks,subTabs,sessionTabs,masteringSettings,masterVolume,{volL:masterVolL,volR:masterVolR,link:masterLink,muted:masterMuted});try{const res=await window.SonicAPI.renderProject(schema,'preview_'+Date.now()+'.wav');_lastMasterStats={lufs:res.lufs,true_peak_db:res.true_peak_db};return res;}catch(e){window.showToast&&window.showToast('Render preview lỗi: '+(e.message||e),'error');throw e;}};const[masteringSettings,setMasteringSettings]=useState({masterConnected:true,// ⚠️ FIX: bật ON mặc định — MIDI item/preview PHẢI được xử lí qua mastering FX ngay khi chạy app (không cần bật/tắt power) activeModule:null,imagerActive:false,maximizerActive:false,eqLowGain:1.5,eqMid1Gain:-1.0,eqMid2Gain:2.0,eqHighGain:1.8,w1:0,w2:115,w3:135,w4:150,imagerScale:'v2',maxGain:5.4,maxUpward:2.0,maxSoftClip:15,maxTransient:25,ceiling:-0.1,isBypassed:false,chain:[],compActive:false,compThreshold:-16,compRatio:3,compMakeup:0,limActive:false,limThreshold:-1.0,limMode:0,limLookahead:2,excActive:false,excDrive:40,rebalActive:false,rebalMid:0,rebalSide:0,vstFxChain:[],vstBypass:false});useEffect(()=>{window.currentMasteringSettings=masteringSettings;if(audioCtx&&masterBus){toggleMasteringOnMaster(masteringSettings.masterConnected,masteringSettings.isBypassed);applyMasteringSettings(masteringSettings);// Đồng bộ realtime VST master với PWR/Bypass: WebAudio graph đã đổi theo // masterConnected nhưng fxRt không tự dừng → tắt PWR mà âm không đổi. -try{if(fxRtChain().length){fxRtStart();}else if(fxRt.active){fxRtStop();}}catch(e){console.warn('[FX RT] resync fail:',e);}// Re-sync live track routes: mastering ON → mọi track qua chain (♪ bị +try{if(fxRtChain().length){fxRtStart();}else if(fxRt.active||fxRt.starting){fxRtStop();}}catch(e){console.warn('[FX RT] resync fail:',e);}// Re-sync live track routes: mastering ON → mọi track qua chain (♪ bị // override bởi effMidiBypass/effAudioBypass) — nút PWR bật/tắt phải áp // ngay lên node đang phát (không chờ tracks effect). try{const _list=activeTracksRef.current&&activeTracksRef.current.length?activeTracksRef.current:tracks;_list.forEach(_t=>{const _n=activeTrackNodesRef.current[_t.id];if(_n){if(_n.sfRouteGain&&_n.sfDryGain){const _b=effMidiBypass(_t);_n.sfRouteGain.gain.value=_b?0:1;_n.sfDryGain.gain.value=_b?1:0;}if(_n.route&&_n.route.routeGain&&_n.route.dryGain){const _ab=routeBypassFor(_t);_n.route.routeGain.gain.value=_ab?0:1;_n.route.dryGain.gain.value=_ab?1:0;}}});// Sub-nodes (section tabs, key '_sub_'): PWR master ON → @@ -1644,9 +1696,17 @@ 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:false}:{type:'builtin',id:s.type,params:s.params&&Object.keys(s.params).length?s.params:{},bypass:false});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),paramsBySlot:chain.map(s=>fxRtEntryParams(s,null)),inQueue:[],pumpTimer:null};fxRtTracks[key]=entry;fxRtGuiPushShm();try{await ctx.audioWorklet.addModule(`${API_BASE_URL}/static/js/sf-fx-realtime.js?v=202608212401`);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:false}:{type:'builtin',id:s.type,params:s.params&&Object.keys(s.params).length?s.params:{},bypass:false});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),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=202608241200`);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. -if(ws.readyState===1){try{const f=new Float32Array(d.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);}};const fxRtTrackSplice=(trackId,path)=>{const key=trackId+':'+path;const entry=fxRtTracks[key];const node=activeTrackNodesRef.current[trackId];if(!entry||!entry.ready||!entry.node||!node||entry.spliced)return;const tail=path==='audio'?node.fxEntry:node.sfEntry;const dest=path==='audio'?node.fxLegacyIn:node.sfOut;if(!tail||!dest)return;try{tail.disconnect(dest);entry.node.connect(dest);tail.connect(entry.node);entry.spliced={tail,dest};console.log('[FX RT track] spliced',trackId,path);}catch(e){console.warn('[FX RT track] splice fail',trackId,path,e);}};const fxRtTrackStop=(trackId,path,silent)=>{const key=trackId+':'+path;const entry=fxRtTracks[key];if(!entry)return;if(entry.pumpTimer){clearInterval(entry.pumpTimer);entry.pumpTimer=null;}entry.inQueue=[];try{fxRtTrackUnsplice(trackId,path);if(entry.node){entry.node.port.onmessage=null;try{entry.node.disconnect();}catch(e){}entry.node=null;}}catch(e){}try{if(entry.ws){entry.ws.onclose=null;entry.ws.onmessage=null;try{entry.ws.close();}catch(e){}entry.ws=null;}}catch(e){}const sid=entry.sessionId;delete fxRtTracks[key];fxRtGuiPushShm();if(sid){try{window.SonicAPI.fxRealtimeStop({session_id:sid}).catch(()=>{});}catch(e){}}};const fxRtTrackReconcile=(trackId,node,track)=>{try{const chain=fxRtTrackChain(track);const chainKey=fxRtTrackChainKey(chain);const wantPaths=chain.length?fxRtTrackPaths(track):[];const prefix=trackId+':';Object.keys(fxRtTracks).forEach(k=>{if(!k.startsWith(prefix))return;const p=k.slice(prefix.length);if(wantPaths.indexOf(p)<0)fxRtTrackStop(trackId,p,true);});if(!isPlayingRef.current)return;wantPaths.forEach(p=>{const key=trackId+':'+p;const entry=fxRtTracks[key];if(!entry)fxRtTrackStart(trackId,track,p);else if(entry.chainKey!==chainKey){fxRtTrackStop(trackId,p,true);fxRtTrackStart(trackId,track,p);}else if(entry.ready&&node){fxRtTrackUnsplice(trackId,p);// chain mới (sau rebuild) — splice lại đúng mods +// 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 +// atomic khi worker load xong) → load VST FX / đổi preset GUI không ngắt +// âm/crackle. entry.chainKey cập nhật ngay — reconcile sau đó thấy khớp. +const fxRtTrackSetChain=(trackId,path,track,chainKey)=>{const key=trackId+':'+path;const entry=fxRtTracks[key];if(!entry||!entry.ws||entry.ws.readyState!==1)return;const chain=fxRtTrackChain(track);if(!chain.length)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:false}:{type:'builtin',id:s.type,params:s.params&&Object.keys(s.params).length?s.params:{},bypass:false});entry.chainKey=chainKey;window.SonicAPI.fxRealtimeSetChain({session_id:entry.sessionId,fx_chain:chainPayload}).then(()=>{try{(entry.paramsBySlot||[]).forEach((pl,slot)=>pl.forEach(p=>{if(entry.ws&&entry.ws.readyState===1)entry.ws.send(JSON.stringify({cmd:'set_param',slot,key:p.key,value:p.value}));}));}catch(e){}}).catch(e=>console.warn('[FX RT track] set-chain fail',trackId,path,e));};const fxRtTrackSplice=(trackId,path)=>{const key=trackId+':'+path;const entry=fxRtTracks[key];const node=activeTrackNodesRef.current[trackId];if(!entry||!entry.ready||!entry.node||!node||entry.spliced)return;const tail=path==='audio'?node.fxEntry:node.sfEntry;const dest=path==='audio'?node.fxLegacyIn:node.sfOut;if(!tail||!dest)return;try{tail.disconnect(dest);entry.node.connect(dest);tail.connect(entry.node);entry.spliced={tail,dest};console.log('[FX RT track] spliced',trackId,path);}catch(e){console.warn('[FX RT track] splice fail',trackId,path,e);}};const fxRtTrackStop=(trackId,path,silent)=>{const key=trackId+':'+path;const entry=fxRtTracks[key];if(!entry)return;if(entry.pumpTimer){clearInterval(entry.pumpTimer);entry.pumpTimer=null;}entry.inQueue=[];try{fxRtTrackUnsplice(trackId,path);if(entry.node){entry.node.port.onmessage=null;try{entry.node.disconnect();}catch(e){}entry.node=null;}}catch(e){}try{if(entry.ws){entry.ws.onclose=null;entry.ws.onmessage=null;try{entry.ws.close();}catch(e){}entry.ws=null;}}catch(e){}const sid=entry.sessionId;delete fxRtTracks[key];fxRtGuiPushShm();if(sid){try{window.SonicAPI.fxRealtimeStop({session_id:sid}).catch(()=>{});}catch(e){}}};const fxRtTrackReconcile=(trackId,node,track)=>{try{const chain=fxRtTrackChain(track);const chainKey=fxRtTrackChainKey(chain);const wantPaths=chain.length?fxRtTrackPaths(track):[];const prefix=trackId+':';Object.keys(fxRtTracks).forEach(k=>{if(!k.startsWith(prefix))return;const p=k.slice(prefix.length);if(wantPaths.indexOf(p)<0)fxRtTrackStop(trackId,p,true);});if(!isPlayingRef.current)return;wantPaths.forEach(p=>{const key=trackId+':'+p;const entry=fxRtTracks[key];if(!entry)fxRtTrackStart(trackId,track,p);else if(entry.chainKey!==chainKey){// Chain đổi (load/đổi VST FX, preset GUI, bypass slot) — session +// đang chạy → set_chain KHÔNG restart (bridge swap atomic khi load +// xong) → hết crackle khi load VST / chỉnh thông số. Session chưa +// ready (start in-flight) → stop+start lại cho đúng chain. +if(entry.ready)fxRtTrackSetChain(trackId,track,p,chainKey);else{fxRtTrackStop(trackId,p,true);fxRtTrackStart(trackId,track,p);}}else if(entry.ready&&node){fxRtTrackUnsplice(trackId,p);// chain mới (sau rebuild) — splice lại đúng mods fxRtTrackSplice(trackId,p);}});}catch(e){console.warn('fxRtTrackReconcile error:',e);}};const fxRtTrackStopAll=()=>{Object.keys(fxRtTracks).forEach(k=>{const i=k.lastIndexOf(':');fxRtTrackStop(k.slice(0,i),k.slice(i+1),true);});};// Route the SHARED FluidSynth output through the gainNode of the single // audible MIDI track so its FX Rack chain / fader / pan affect the soundfont // instrument (unified_fx_rack_panel.md + user request). With more than one diff --git a/app/static/js/services/api.js b/app/static/js/services/api.js index 09895eb..9261c7d 100644 --- a/app/static/js/services/api.js +++ b/app/static/js/services/api.js @@ -87,6 +87,7 @@ window.API_BASE_URL = (window.API_BASE_URL || window.location.origin).replace(/\ // /ws/fx-realtime/{id} đẩy/kéo block audio; stop → tắt bridge. fxRealtimeStart: (payload) => apiRequest('/api/v1/plugins/fx-realtime/start', { method: 'POST', body: JSON.stringify(payload) }), fxRealtimeStop: (payload) => apiRequest('/api/v1/plugins/fx-realtime/stop', { method: 'POST', body: JSON.stringify(payload) }), + fxRealtimeSetChain: (payload) => apiRequest('/api/v1/plugins/fx-realtime/set-chain', { method: 'POST', body: JSON.stringify(payload) }), // Mở native GUI của VST FX (mastering chain / FX rack) qua bridge openFxGui: (payload) => apiRequest('/api/v1/plugins/fx-gui', { method: 'POST', body: JSON.stringify(payload) }), soundfontRender: (payload) => apiRequest('/api/v1/plugins/soundfont-render', { method: 'POST', body: JSON.stringify(payload) }), diff --git a/app/static/js/sf-fx-realtime.js b/app/static/js/sf-fx-realtime.js index c8afa1d..0fdcf24 100644 --- a/app/static/js/sf-fx-realtime.js +++ b/app/static/js/sf-fx-realtime.js @@ -24,7 +24,8 @@ class SfFxRealtimeProcessor extends AudioWorkletProcessor { super(); this.BLOCK = 256; // FXRT_BLOCK this.BURST = 4; // số block gom 1 frame (bridge batch) - this.FILL = 8; // block buffer tối thiểu trước khi phát + this.FILL = 16; // 16 block ~86ms: buffer khởi đầu — hấp thụ jitter main-thread (GUI decode, rAF, solo restart) + this.REBUFFER = 2; // 2 block ~11ms: sau underrun chỉ cần bấy nhiêu để phát lại — gap ngắn, không còn 86ms im lặng this.CAP = 32; // cap queue chặn overflow this.bufLen = this.BLOCK * this.BURST; this.inL = new Float32Array(this.bufLen); @@ -33,6 +34,10 @@ class SfFxRealtimeProcessor extends AudioWorkletProcessor { this.outQueue = []; // [{l: Float32Array, r: Float32Array}] this.outPos = 0; this.playing = false; // false → im lặng (đang chờ đủ FILL) + this.hasStarted = false; // đã phát block đầu chưa — phân biệt FILL khởi đầu vs REBUFFER sau underrun + this.FADE = 512; // fade-in 512 mẫu (~11ms @48k) khi bắt đầu phát/resume — hết click + this.outGain = 0; // gain phát hiện tại (0→1 trong fade) + this.fadeLeft = 0; // số mẫu còn lại của fade this.port.onmessage = (e) => { const d = e.data; if (d && d.type === 'set_param') { this.port.postMessage(d); return; } @@ -76,16 +81,30 @@ class SfFxRealtimeProcessor extends AudioWorkletProcessor { for (let i = 0; i < n; i++) { if (this.playing && this.outQueue.length === 0) this.playing = false; if (!this.playing) { - if (this.outQueue.length >= this.FILL) this.playing = true; - else { + // Khởi đầu: chờ đủ FILL (hấp thụ jitter). Sau underrun: chỉ cần + // REBUFFER (2 block ~11ms) — gap ngắn thay vì 86ms im lặng. + const need = this.hasStarted ? this.REBUFFER : this.FILL; + if (this.outQueue.length >= need) { + this.playing = true; + this.hasStarted = true; + // Fade-in mượt (hết click lúc FILL xong / resume sau underrun); báo + // main thread để crossfade dry→fx đúng thời điểm. + this.outGain = 0; + this.fadeLeft = this.FADE; + this.port.postMessage({ type: 'started' }); + } else { outL[i] = 0; if (outR) outR[i] = 0; continue; } } const blk = this.outQueue[0]; - outL[i] = blk.l[this.outPos]; - if (outR) outR[i] = blk.r[this.outPos]; + if (this.fadeLeft > 0) { + this.outGain = Math.min(1, this.outGain + 1 / this.FADE); + this.fadeLeft--; + } + outL[i] = blk.l[this.outPos] * this.outGain; + if (outR) outR[i] = blk.r[this.outPos] * this.outGain; this.outPos++; if (this.outPos >= this.BLOCK) { this.outQueue.shift(); diff --git a/app/templates/index.html b/app/templates/index.html index a761490..664d9f7 100644 --- a/app/templates/index.html +++ b/app/templates/index.html @@ -51,7 +51,7 @@ - +