V45.38: suppress iZotope 0x7E dialog

- _is_vst2_dll: pure-Python PE export-table check (magic-aware dd offset
  PE32+112) -> IZOzone11Core.dll (runtime lib, no VSTPluginMain) dropped
  from VST2 lists in _scan_plugins and list_scan_all; plugins.py same.
- _hidden_desktop_startupinfo: scan subprocess runs on hidden desktop
  (user32 CreateDesktopW, HDESK restype) -> third-party MessageBox invisible.
- SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX) in all 4
  bridge mains: missing dependency DLL fails silently instead of blocking.
This commit is contained in:
2026-09-01 20:10:33 +07:00
parent aee537a0af
commit 29b5f053a0
14 changed files with 157 additions and 7 deletions
+3 -2
View File
@@ -4,7 +4,7 @@ from fastapi.responses import FileResponse
from pydantic import BaseModel
from typing import Optional, Any
from app.config import settings
from app.core.vst_engine import PluginManager, HAS_PYFLUIDSYNTH, render_soundfont_midi_to_audio, RENDER_LOCK, _render_locked
from app.core.vst_engine import PluginManager, HAS_PYFLUIDSYNTH, render_soundfont_midi_to_audio, RENDER_LOCK, _render_locked, _is_vst2_dll
from app.core.soundfont_inspector import SoundFontInspector
from app.core.soundfont_converter import SoundFontConverter
from app.core.soundfont_scanner import SoundFontAutoScanner
@@ -348,7 +348,8 @@ def _scan_vst_in_dirs(dirs: list) -> list:
"id": name, "name": name, "type": "VST3",
"path": os.path.join(root, f),
}
elif low.endswith(".dll") and not has_vst3_file:
elif (low.endswith(".dll") and not has_vst3_file
and _is_vst2_dll(os.path.join(root, f))):
name = os.path.splitext(f)[0]
if name not in found:
found[name] = {
+135 -2
View File
@@ -7,6 +7,7 @@ import time as _time
import functools
import threading
from ctypes import c_char_p
import struct
import subprocess
@@ -38,6 +39,121 @@ def _ensure_fluidsynth_dll_on_path():
_ensure_fluidsynth_dll_on_path()
def _is_vst2_dll(path: str) -> bool:
"""True nếu .dll export entry VST2 (VSTPluginMain hoặc main) — plugin
VST2 thật (Kong Audio Qin_RV_x64.dll...). Các thư viện runtime đặt cạnh
plugin (vd iZotope Cores/IZOzone11Core.dll — core của Ozone, KHÔNG phải
plugin) không export entry VST2 → loại khỏi danh sách plugin: load chúng
như VST2 gây lỗi dependency 0x7E. Đọc export table PE thuần Python, không
load DLL vào process."""
if not path.lower().endswith(".dll"):
return False
try:
f = open(path, "rb")
except OSError:
return False
try:
head = f.read(0x1000)
if len(head) < 0x40 or head[:2] != b"MZ":
return False
e_lfanew = struct.unpack_from("<I", head, 0x3C)[0]
if e_lfanew + 24 + 120 + 8 > len(head):
return False
if head[e_lfanew:e_lfanew + 4] != b"PE" + bytes(2):
return False
num_sections = struct.unpack_from("<H", head, e_lfanew + 6)[0]
opt_size = struct.unpack_from("<H", head, e_lfanew + 20)[0]
sec_start = e_lfanew + 24 + opt_size
if sec_start + num_sections * 40 > len(head):
return False
# Data directory 0 = export table (RVA, size): PE32 -> opt+96,
# PE32+ (x64) -> opt+112 (magic 0x10B / 0x20B).
magic = struct.unpack_from("<H", head, e_lfanew + 24)[0]
dd = 96 if magic == 0x10B else (112 if magic == 0x20B else 0)
if dd == 0:
return False
exp_rva = struct.unpack_from("<I", head, e_lfanew + 24 + dd)[0]
exp_size = struct.unpack_from("<I", head, e_lfanew + 24 + dd + 4)[0]
if exp_rva == 0 or exp_size == 0:
return False
secs = []
for i in range(num_sections):
off = sec_start + i * 40
va = struct.unpack_from("<I", head, off + 12)[0]
raw_size = struct.unpack_from("<I", head, off + 16)[0]
raw_ptr = struct.unpack_from("<I", head, off + 20)[0]
secs.append((va, raw_size, raw_ptr))
def rva_to_off(rva):
for va, raw_size, raw_ptr in secs:
if va <= rva < va + raw_size:
return raw_ptr + (rva - va)
return None
exp_off = rva_to_off(exp_rva)
if exp_off is None:
return False
f.seek(exp_off)
exp = f.read(40)
if len(exp) < 40:
return False
num_names = struct.unpack_from("<I", exp, 24)[0]
if num_names == 0 or num_names > 65536:
return False
names_off = rva_to_off(struct.unpack_from("<I", exp, 32)[0])
if names_off is None:
return False
f.seek(names_off)
name_ptrs = f.read(num_names * 4)
if len(name_ptrs) < num_names * 4:
return False
for i in range(num_names):
noff = rva_to_off(struct.unpack_from("<I", name_ptrs, i * 4)[0])
if noff is None:
continue
f.seek(noff)
raw = f.read(64)
nm = raw.split(bytes(1), 1)[0].decode("ascii", "replace")
if nm in ("VSTPluginMain", "main"):
return True
return False
except Exception:
return False
finally:
f.close()
def _hidden_desktop_startupinfo():
"""STARTUPINFO cho process con chạy trên DESKTOP ẨN mới tạo: dialog của
plugin bên thứ ba (vd iZotope MessageBox [0x7E] khi core load fail trong
--scan) hiện trên desktop vô hình → user không bị chặn, scan bỏ module sau
timeout 4s như cũ. Trả (startupinfo, desktop_handle) — handle phải đóng
sau khi process con kết thúc; (None, None) khi không tạo được (fallback
desktop thường)."""
if os.name != "nt":
return None, None
try:
import ctypes
from ctypes import wintypes
u32 = ctypes.windll.user32 # CreateDesktopW/CloseDesktop thuộc USER32
u32.CreateDesktopW.restype = ctypes.c_void_p # HDESK 64-bit, không cắt
u32.CreateDesktopW.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR,
wintypes.LPVOID, wintypes.DWORD,
wintypes.DWORD, wintypes.LPVOID]
u32.CloseDesktop.restype = wintypes.BOOL
u32.CloseDesktop.argtypes = [wintypes.HANDLE]
name = "SF_Scan_%d_%d" % (os.getpid(), int(_time.time() * 1000) % 1000000)
# DESKTOP_ALL_ACCESS (0x000F01FF) — handle chỉ để giữ desktop sống.
h = u32.CreateDesktopW(name, None, None, 0, 0x000F01FF, None)
if not h:
return None, None
si = subprocess.STARTUPINFO()
si.lpDesktop = name
return si, h
except Exception:
return None, None
def midi_note_to_freq(note_number: int) -> float:
return 440.0 * (2.0 ** ((note_number - 69) / 12.0))
@@ -378,7 +494,8 @@ class PluginManager:
plugin_name = os.path.splitext(file)[0]
if plugin_name not in plugins:
plugins[plugin_name] = plugin_path
elif low.endswith(".dll") and not has_vst3_file:
elif (low.endswith(".dll") and not has_vst3_file
and _is_vst2_dll(os.path.join(root, file))):
plugin_path = os.path.join(root, file)
plugin_name = os.path.splitext(file)[0]
if plugin_name not in plugins:
@@ -582,12 +699,20 @@ class PluginManager:
if exe:
dirs = [d for d in self._vst_scan_dirs() if d and os.path.isdir(d)]
for d in dirs:
si, hdesk = _hidden_desktop_startupinfo()
try:
r = subprocess.run([exe, "--scan", d], capture_output=True,
creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,
text=True, timeout=300)
text=True, timeout=300, startupinfo=si)
except Exception:
continue
finally:
if hdesk:
try:
import ctypes
ctypes.windll.user32.CloseDesktop(hdesk)
except Exception:
pass
if r.returncode != 0:
continue
try:
@@ -620,6 +745,14 @@ class PluginManager:
continue
seen.add(e["path"])
uniq.append(e)
# Loại .dll KHÔNG phải VST2 thật (không export VSTPluginMain/main —
# vd iZotope Cores/IZOzone11Core.dll là runtime lib, không phải
# plugin): bridge scan emit mọi .dll thành VST2 instrument → load như
# plugin gây 0x7E. Kiểm export table thuần Python, không load DLL.
uniq = [e for e in uniq
if not (e.get("type") == "VST2"
and (e.get("path") or "").lower().endswith(".dll")
and not _is_vst2_dll(e["path"]))]
# Chỉ cache khi bridge tồn tại: kết quả (kể cả rỗng — dir không có
# FX) là đáng tin; khi thiếu bridge thì trả [] nhưng KHÔNG cache.
if exe:
+2 -2
View File
@@ -348,7 +348,7 @@ else if(fxRt.chainKey!==ck){fxRtSetChain(chain);fxRt.chainKey=ck;return;}else re
// node → bypass vô hiệu. Mỗi fxRtStop() bump startToken → mọi checkpoint
// dưới đây thấy mismatch → hủy session vừa tạo, không nối node.
const token=++fxRt.startToken;fxRt.starting=true;const ctx=getAudioContext();if(!ctx||!ctx.audioWorklet||!masterBus||!masterBus.output||!masterBus.analyser||!masterBus.masterFxGain||!masterBus.masterFxDryGain)return;const chainPayload=chain.map(s=>s.type==='vst3'?{type:'vst3',path:s.path,name:s.name||s.path,preset_b64:s.preset_b64||'',bypass:!!s.bypass||!!(window.currentMasteringSettings||{}).vstBypass}:{type:'builtin',id:s.type,params:s.params&&Object.keys(s.params).length?s.params:{},bypass:!!s.bypass});let st;try{st=await window.SonicAPI.fxRealtimeStart({fx_chain:chainPayload,sample_rate:ctx.sampleRate||44100});}catch(e){console.warn('[FX RT] start fail:',e);showToast('Không khởi động VST FX realtime: '+(e.message||e),'warning');fxRt.starting=false;return;}if(token!==fxRt.startToken){// Bypass/stop giữa lúc engine đang load chain — hủy session vừa tạo.
console.warn('[FX RT] start cancelled mid-flight — session stopped');try{window.SonicAPI.fxRealtimeStop({session_id:st.session_id}).catch(()=>{});}catch(e2){}fxRt.starting=false;return;}fxRt.sessionId=st.session_id;fxRtGuiPushShm();try{await ctx.audioWorklet.addModule(`${API_BASE_URL}/static/js/sf-fx-realtime.js?v=202609011809`);if(token!==fxRt.startToken){fxRt.starting=false;return;}fxRt.node=new AudioWorkletNode(ctx,'sf-fx-realtime',{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2]});const u=new URL(API_BASE_URL);const wsProto=u.protocol==='https:'?'wss://':'ws://';// WS to 'localhost' bi tre ~300ms: Chromium thu ::1 truoc (Windows khong
console.warn('[FX RT] start cancelled mid-flight — session stopped');try{window.SonicAPI.fxRealtimeStop({session_id:st.session_id}).catch(()=>{});}catch(e2){}fxRt.starting=false;return;}fxRt.sessionId=st.session_id;fxRtGuiPushShm();try{await ctx.audioWorklet.addModule(`${API_BASE_URL}/static/js/sf-fx-realtime.js?v=202609011947`);if(token!==fxRt.startToken){fxRt.starting=false;return;}fxRt.node=new AudioWorkletNode(ctx,'sf-fx-realtime',{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2]});const u=new URL(API_BASE_URL);const wsProto=u.protocol==='https:'?'wss://':'ws://';// WS to 'localhost' bi tre ~300ms: Chromium thu ::1 truoc (Windows khong
// co listener IPv6 -> SYN hang ~2s) roi moi fallback 127.0.0.1. Dung
// thang 127.0.0.1 (loopback) -> WS open ~5ms. Server chap nhan loopback.
const wsHost=u.hostname==='localhost'||u.hostname==='::1'?'127.0.0.1'+(u.port?':'+u.port:''):u.host;const tok=localStorage.getItem('sonic_token')||'';const wsUrl=`${wsProto}${wsHost}${st.ws_url}${tok?'?token='+encodeURIComponent(tok):''}`;const ws=new WebSocket(wsUrl);fxRt.ws=ws;ws.binaryType='arraybuffer';ws.onopen=()=>{if(token!==fxRt.startToken){try{ws.close();}catch(e){}fxRt.starting=false;return;}fxRt.active=true;fxRt.flushing=false;fxRt.starting=false;fxRt.inQueue=[];// bỏ audio stale sản xuất trước khi WS open (~4s load VST) — hết lag khởi đầu
@@ -2000,7 +2000,7 @@ fxRtTrackReconcile(trackId,node,track);}catch(e){console.warn('rebuildTrackFxGra
// Cần activeTrackNodesRef/isPlayingRef. Session giống master (fxRtStart):
// fetch start → AudioWorkletNode 'sf-fx-realtime' → WS; WS open → splice
// worklet vào chain hiện tại (đọc mods MỚI NHẤT — an toàn với rebuild).
const fxRtTrackStart=async(trackId,track,path)=>{const key=trackId+':'+path;const chain=fxRtTrackChain(track);if(!chain.length)return;if(fxRtTracks[key]){if(!fxRtTracks[key].node||fxRtTracks[key].node.context!==getAudioContext())fxRtTrackStop(trackId,path,true);else return;}const ctx=getAudioContext();if(!ctx||!ctx.audioWorklet)return;const chainPayload=chain.map(s=>s.type==='vst3'?{type:'vst3',path:s.path,name:s.name||s.path,preset_b64:s.preset_b64||'',bypass:!!s.bypass||!!(track&&track.vstFxBypass)}:{type:'builtin',id:s.type,params:s.params&&Object.keys(s.params).length?s.params:{},bypass:!!s.bypass});let st;try{st=await window.SonicAPI.fxRealtimeStart({fx_chain:chainPayload,sample_rate:ctx.sampleRate||44100});}catch(e){console.warn('[FX RT track] start fail',trackId,path,e);return;}const entry={sessionId:st.session_id,ws:null,node:null,ready:false,path,spliced:null,chainKey:fxRtTrackChainKey(chain)+'|vb:'+(track&&track.vstFxBypass?'1':'0'),paramsBySlot:chain.map(s=>fxRtEntryParams(s,null)),inQueue:[],pumpTimer:null,lastInSent:0,flushing:false,flushTimer:null};fxRtTracks[key]=entry;fxRtGuiPushShm();try{await ctx.audioWorklet.addModule(`${API_BASE_URL}/static/js/sf-fx-realtime.js?v=202609011809`);const node=new AudioWorkletNode(ctx,'sf-fx-realtime',{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2]});entry.node=node;const u=new URL(API_BASE_URL);const wsProto=u.protocol==='https:'?'wss://':'ws://';// WS to 'localhost' bi tre ~300ms (Chromium thu ::1 truoc roi fallback) - dung 127.0.0.1
const fxRtTrackStart=async(trackId,track,path)=>{const key=trackId+':'+path;const chain=fxRtTrackChain(track);if(!chain.length)return;if(fxRtTracks[key]){if(!fxRtTracks[key].node||fxRtTracks[key].node.context!==getAudioContext())fxRtTrackStop(trackId,path,true);else return;}const ctx=getAudioContext();if(!ctx||!ctx.audioWorklet)return;const chainPayload=chain.map(s=>s.type==='vst3'?{type:'vst3',path:s.path,name:s.name||s.path,preset_b64:s.preset_b64||'',bypass:!!s.bypass||!!(track&&track.vstFxBypass)}:{type:'builtin',id:s.type,params:s.params&&Object.keys(s.params).length?s.params:{},bypass:!!s.bypass});let st;try{st=await window.SonicAPI.fxRealtimeStart({fx_chain:chainPayload,sample_rate:ctx.sampleRate||44100});}catch(e){console.warn('[FX RT track] start fail',trackId,path,e);return;}const entry={sessionId:st.session_id,ws:null,node:null,ready:false,path,spliced:null,chainKey:fxRtTrackChainKey(chain)+'|vb:'+(track&&track.vstFxBypass?'1':'0'),paramsBySlot:chain.map(s=>fxRtEntryParams(s,null)),inQueue:[],pumpTimer:null,lastInSent:0,flushing:false,flushTimer:null};fxRtTracks[key]=entry;fxRtGuiPushShm();try{await ctx.audioWorklet.addModule(`${API_BASE_URL}/static/js/sf-fx-realtime.js?v=202609011947`);const node=new AudioWorkletNode(ctx,'sf-fx-realtime',{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2]});entry.node=node;const u=new URL(API_BASE_URL);const wsProto=u.protocol==='https:'?'wss://':'ws://';// WS to 'localhost' bi tre ~300ms (Chromium thu ::1 truoc roi fallback) - dung 127.0.0.1
const wsHost=u.hostname==='localhost'||u.hostname==='::1'?'127.0.0.1'+(u.port?':'+u.port:''):u.host;const tok=localStorage.getItem('sonic_token')||'';const ws=new WebSocket(`${wsProto}${wsHost}${st.ws_url}${tok?'?token='+encodeURIComponent(tok):''}`);entry.ws=ws;ws.binaryType='arraybuffer';ws.onopen=()=>{entry.ready=true;entry.inQueue=[];// bỏ audio stale trước khi WS open — hết lag khởi đầu
fxRtTrackSplice(trackId,path);try{(entry.paramsBySlot||[]).forEach((pl,slot)=>pl.forEach(p=>ws.send(JSON.stringify({cmd:'set_param',slot,key:p.key,value:p.value}))));}catch(e){}};ws.onmessage=ev=>{if(typeof ev.data==='string'){try{const d=JSON.parse(ev.data);if(d&&d.cmd==='flush_done'){entry.flushing=false;if(entry.flushTimer){clearTimeout(entry.flushTimer);entry.flushTimer=null;}if(entry.node)entry.node.port.postMessage({type:'flush_done'});}}catch(e){}return;}if(!(ev.data instanceof ArrayBuffer)||!entry.node)return;if(entry.flushing)return;// V24: output stale trong luc flush — drop
const f=new Float32Array(ev.data);const half=f.length/2;const l=new Float32Array(half);const r=new Float32Array(half);for(let i=0;i<half;i++){l[i]=f[i*2];r[i]=f[i*2+1];}entry.node.port.postMessage({type:'out',l,r});};ws.onclose=()=>fxRtTrackStop(trackId,path,true);ws.onerror=()=>{try{ws.close();}catch(e){}};entry.node.port.onmessage=ev=>{const d=ev.data;if(!d||!entry.ws)return;if(d.type==='flush'){// V24: nhu master — worklet underrun-resume → flush engine ring
+1 -1
View File
@@ -51,7 +51,7 @@
<script src="/static/js/services/promptTemplateManager.js?v=202608290945"></script>
<script src="/static/js/services/undoRedoEngine.js?v=202608290945"></script>
<script src="/static/js/services/chordTheory.js?v=202608290945"></script>
<script src="/static/js/app.precompiled.js?v=202609011809" defer></script>
<script src="/static/js/app.precompiled.js?v=202609011947" defer></script>
<link rel="stylesheet" href="/static/css/styles.css?v=202608290945">
<style>
:root {
+4
View File
@@ -106,6 +106,10 @@ public:
};
int main(int argc, char* argv[]) {
#ifdef _WIN32
// Suppress Windows loader error dialogs (0x7E) during probe loads.
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
#endif
if (argc < 2) {
printf("usage: gui_probe <plugin.vst3> [variant] [secs] [hwnd]\n"
"variants: main_own | worker_own_nopump | worker_own_pump | worker_foreign_nopump | worker_foreign_pump | bridge_like | same_thread | two_instances | two_instances_close | close_reopen | bridge_two | shared_worker | ui_thread | two_workers_close\n");
+4
View File
@@ -715,6 +715,10 @@ int main(int argc, char* argv[]) {
SetUnhandledExceptionFilter(CrashDumpHandler);
AddVectoredExceptionHandler(1, VectoredCrashHandler);
#ifdef _WIN32
// Suppress Windows loader error dialogs: a plugin whose dependency DLL is
// missing (LoadLibrary -> 0x7E) must fail silently, not pop a MessageBox
// that blocks the user. Child processes inherit this error mode.
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
// Background daemon: detach the console window unless SF_KEEP_CONSOLE is
// set. Console apps spawned from the GUI (tauri-shell, Popen) flash a
// console window otherwise. Redirected stdio (pipe to bridge.log / the
+3
View File
@@ -106,6 +106,9 @@ int main(int argc, char* argv[]) {
#ifdef _WIN32
SetUnhandledExceptionFilter(FxCrashDumpHandler);
AddVectoredExceptionHandler(1, FxVectoredCrashHandler);
// Suppress Windows loader error dialogs (plugin dependency thiếu -> 0x7E
// phải fail âm thầm, không MessageBox chặn user; child kế thừa error mode).
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
win_daemon_init();
#endif
// stderr, not stdout: stdout is reserved for machine-readable output in
+5
View File
@@ -86,6 +86,11 @@ static HWND make_host_window() {
}
int main(int argc, char* argv[]) {
#ifdef _WIN32
// Suppress Windows loader error dialogs — plugin dependency thiếu (0x7E)
// phải fail âm thầm, không MessageBox chặn user.
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
#endif
std::string shmName, path, presetFile;
double sr = 44100.0;
uint32_t block = AUDIO_BLOCK_SIZE;
Binary file not shown.
Binary file not shown.
Binary file not shown.