fix(audio): offline mix limiter -3dBFS, 2-stage normalize (-14 LUFS + hard peak -1 dBTP), OGG export
This commit is contained in:
@@ -1239,9 +1239,9 @@ def render_project(
|
|||||||
):
|
):
|
||||||
enforce_password_changed(current_user)
|
enforce_password_changed(current_user)
|
||||||
engine = PythonRenderEngine()
|
engine = PythonRenderEngine()
|
||||||
# Prevent path traversal: strip any directory components and force .wav.
|
# Prevent path traversal: strip directory components; force .wav/.ogg.
|
||||||
safe_name = os.path.basename((req.output_filename or "render_output.wav").replace("\\", "/"))
|
safe_name = os.path.basename((req.output_filename or "render_output.wav").replace("\\", "/"))
|
||||||
if not safe_name.lower().endswith(".wav"):
|
if not (safe_name.lower().endswith(".wav") or safe_name.lower().endswith(".ogg")):
|
||||||
safe_name += ".wav"
|
safe_name += ".wav"
|
||||||
output_path = os.path.join(settings.PROCESSED_DIR, safe_name)
|
output_path = os.path.join(settings.PROCESSED_DIR, safe_name)
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -223,6 +223,33 @@ def _apply_limiter(buf, params, sr):
|
|||||||
x = np.clip(buf, -1.0, 1.0)
|
x = np.clip(buf, -1.0, 1.0)
|
||||||
return np.tanh(x * k) / tanh_k
|
return np.tanh(x * k) / tanh_k
|
||||||
|
|
||||||
|
def _apply_mix_limiter(buf, sr):
|
||||||
|
"""Mixer summing cap (spec §2): smoothed brickwall -3 dBFS mirror C++
|
||||||
|
realtime (NativeInstrumentEngine.cpp renderAll) — ceiling 0.7071, attack
|
||||||
|
0.1 (~10 samples), release 0.0006, gain chung 2 kênh. Áp cho MASTER CHAIN
|
||||||
|
INPUT offline (realtime đã cap sau khi sum; offline trước đây thiếu).
|
||||||
|
ponytail: loop Python O(n) — thay numba/vectorized khi render >10 phút."""
|
||||||
|
if buf.size == 0:
|
||||||
|
return buf
|
||||||
|
k_ceil = 0.7071
|
||||||
|
k_attack = 0.1
|
||||||
|
k_release = 0.0006
|
||||||
|
eps = 1e-12
|
||||||
|
m_list = np.max(np.abs(buf), axis=0).tolist()
|
||||||
|
n = buf.shape[1]
|
||||||
|
g = 1.0
|
||||||
|
gains = np.empty(n, dtype=np.float32)
|
||||||
|
for i in range(n):
|
||||||
|
t = k_ceil / (m_list[i] + eps)
|
||||||
|
if t > 1.0:
|
||||||
|
t = 1.0
|
||||||
|
if t < g:
|
||||||
|
g += (t - g) * k_attack
|
||||||
|
else:
|
||||||
|
g += (1.0 - g) * k_release
|
||||||
|
gains[i] = g
|
||||||
|
return buf * gains
|
||||||
|
|
||||||
def _apply_exciter(buf, params, sr):
|
def _apply_exciter(buf, params, sr):
|
||||||
params = params or {}
|
params = params or {}
|
||||||
drive = float(params.get("drive", 40) or 40)
|
drive = float(params.get("drive", 40) or 40)
|
||||||
@@ -862,6 +889,11 @@ class PythonRenderEngine:
|
|||||||
_cache={},
|
_cache={},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Mixer summing cap (spec §2): -3 dBFS brickwall mirror C++ realtime —
|
||||||
|
# áp cho MASTER CHAIN INPUT, TRƯỚC master FX chain/volume. Offline
|
||||||
|
# trước đây thiếu cap này (chỉ anti-clip >1.0 sau master chain).
|
||||||
|
master_buffer = _apply_mix_limiter(master_buffer, self.sample_rate)
|
||||||
|
|
||||||
# Masterbus FX chain (VST3 FX / builtin) — render qua native_bridge
|
# Masterbus FX chain (VST3 FX / builtin) — render qua native_bridge
|
||||||
# --render-fx, rồi volume_db master; backward compatible (không có
|
# --render-fx, rồi volume_db master; backward compatible (không có
|
||||||
# master.fx_chain → giữ nguyên luồng cũ).
|
# master.fx_chain → giữ nguyên luồng cũ).
|
||||||
@@ -948,16 +980,29 @@ class PythonRenderEngine:
|
|||||||
if normalize:
|
if normalize:
|
||||||
from app.core import loudness
|
from app.core import loudness
|
||||||
if normalize_target == "-14lufs":
|
if normalize_target == "-14lufs":
|
||||||
|
# Spec: master ra -14 LUFS (scale toàn cục) VÀ hard-peak
|
||||||
|
# <= -1.0 dBTP (chặn peak sau scale, deterministic — peak
|
||||||
|
# cap thắng khi nguồn crest cao, LUFS hạ xuống dưới -14).
|
||||||
|
# ponytail: lookahead limiter khi cần giữ -14 LUFS với
|
||||||
|
# nguồn crest cao (master thật hiếm gặp).
|
||||||
_l = loudness.integrated_lufs(master_buffer, out_sr)
|
_l = loudness.integrated_lufs(master_buffer, out_sr)
|
||||||
if np.isfinite(_l):
|
if np.isfinite(_l):
|
||||||
master_buffer *= 10 ** ((-14.0 - _l) / 20.0)
|
master_buffer *= 10 ** ((-14.0 - _l) / 20.0)
|
||||||
|
_tp = loudness.true_peak_db(master_buffer, out_sr)
|
||||||
|
if np.isfinite(_tp) and _tp > -1.0:
|
||||||
|
master_buffer *= 10 ** ((-1.0 - _tp) / 20.0)
|
||||||
else: # "-1dbtp"
|
else: # "-1dbtp"
|
||||||
_tp = loudness.true_peak_db(master_buffer, out_sr)
|
_tp = loudness.true_peak_db(master_buffer, out_sr)
|
||||||
if np.isfinite(_tp):
|
if np.isfinite(_tp):
|
||||||
master_buffer *= 10 ** ((-1.0 - _tp) / 20.0)
|
master_buffer *= 10 ** ((-1.0 - _tp) / 20.0)
|
||||||
|
|
||||||
# Write final output file (D3: PCM_16/PCM_24 + dither, FLOAT mac dinh)
|
# Write final output file (D3: PCM_16/PCM_24 + dither, FLOAT mac dinh).
|
||||||
if bit_depth == 16:
|
# OGG: Vorbis float lossy — bỏ dither/PCM/BWF (chunk WAV-only).
|
||||||
|
ext = os.path.splitext(output_filepath)[1].lower()
|
||||||
|
if ext == ".ogg":
|
||||||
|
sf.write(output_filepath, master_buffer.T, out_sr,
|
||||||
|
format="OGG", subtype="VORBIS")
|
||||||
|
elif bit_depth == 16:
|
||||||
sf.write(output_filepath, _quantize_pcm(master_buffer, 16, dither).T,
|
sf.write(output_filepath, _quantize_pcm(master_buffer, 16, dither).T,
|
||||||
out_sr, subtype="PCM_16")
|
out_sr, subtype="PCM_16")
|
||||||
elif bit_depth == 24:
|
elif bit_depth == 24:
|
||||||
@@ -967,7 +1012,7 @@ class PythonRenderEngine:
|
|||||||
sf.write(output_filepath, master_buffer.T, out_sr, subtype="FLOAT")
|
sf.write(output_filepath, master_buffer.T, out_sr, subtype="FLOAT")
|
||||||
# Gap 13: BWF/INFO chunks (bext + LIST/INFO title/artist/ISRC) —
|
# Gap 13: BWF/INFO chunks (bext + LIST/INFO title/artist/ISRC) —
|
||||||
# chen sau khi ghi PCM, loi metadata khong lam hong file audio.
|
# chen sau khi ghi PCM, loi metadata khong lam hong file audio.
|
||||||
if metadata:
|
if metadata and ext != ".ogg":
|
||||||
try:
|
try:
|
||||||
from app.core.wav_bwf import patch_bwf_metadata
|
from app.core.wav_bwf import patch_bwf_metadata
|
||||||
patch_bwf_metadata(output_filepath, metadata)
|
patch_bwf_metadata(output_filepath, metadata)
|
||||||
|
|||||||
@@ -18333,8 +18333,8 @@ const App = () => {
|
|||||||
loop: false,
|
loop: false,
|
||||||
loopBars: 4,
|
loopBars: 4,
|
||||||
dither: false,
|
dither: false,
|
||||||
normalize: false,
|
normalize: true,
|
||||||
normalizeTarget: '-1dbtp',
|
normalizeTarget: '-14lufs',
|
||||||
monoCheck: true,
|
monoCheck: true,
|
||||||
// Gap 13: BWF/INFO metadata cho WAV mastering export
|
// Gap 13: BWF/INFO metadata cho WAV mastering export
|
||||||
metaTitle: '',
|
metaTitle: '',
|
||||||
@@ -27969,7 +27969,8 @@ const App = () => {
|
|||||||
try {
|
try {
|
||||||
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 });
|
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 });
|
||||||
const isFloat = exportSettings.bitDepth === 'float';
|
const isFloat = exportSettings.bitDepth === 'float';
|
||||||
const res = await window.SonicAPI.renderProject(schema, 'master_' + Date.now() + '.wav', {
|
const outExt = exportSettings.format === 'ogg' ? 'ogg' : 'wav';
|
||||||
|
const res = await window.SonicAPI.renderProject(schema, 'master_' + Date.now() + '.' + outExt, {
|
||||||
bit_depth: isFloat ? 32 : parseInt(exportSettings.bitDepth) || 16,
|
bit_depth: isFloat ? 32 : parseInt(exportSettings.bitDepth) || 16,
|
||||||
sample_rate: parseInt(exportSettings.sampleRate) || 44100,
|
sample_rate: parseInt(exportSettings.sampleRate) || 44100,
|
||||||
dither: !!exportSettings.dither,
|
dither: !!exportSettings.dither,
|
||||||
@@ -27990,12 +27991,12 @@ const App = () => {
|
|||||||
const br = await fetch(res.url);
|
const br = await fetch(res.url);
|
||||||
if (!br.ok) throw new Error('HTTP ' + br.status);
|
if (!br.ok) throw new Error('HTTP ' + br.status);
|
||||||
const b = await br.blob();
|
const b = await br.blob();
|
||||||
const sp = await saveExportViaDialog((projectName || 'Project') + '_master.wav', b);
|
const sp = await saveExportViaDialog((projectName || 'Project') + '_master.' + outExt, b);
|
||||||
if (sp) showToast(`Đã lưu → ${sp}`, 'success');
|
if (sp) showToast(`Đã lưu → ${sp}`, 'success');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const a = document.createElement('a');
|
const a = document.createElement('a');
|
||||||
a.href = res.url;
|
a.href = res.url;
|
||||||
a.download = 'master.wav';
|
a.download = 'master.' + outExt;
|
||||||
a.click();
|
a.click();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -302,7 +302,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
|
// 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.
|
// 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.
|
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
|
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=202608240831`);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 ->
|
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).
|
// cap nhat delay dry-bypass path (bu latency chain VST3 realtime).
|
||||||
if(typeof ev.data==='string'){try{const d=JSON.parse(ev.data);if(d&&d.cmd==='latency'&&typeof d.total==='number'){fxRt.latencyTotal=d.total;// Chi delay dry path khi crossfade da xong (dry silent) — ap som
|
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
|
||||||
@@ -1176,7 +1176,7 @@ const[masterMuted,setMasterMuted]=useState(false);// MUTE master
|
|||||||
const[masterAutoVol,setMasterAutoVol]=useState([]);// Gap 7: master volume automation [{time s, db}]
|
const[masterAutoVol,setMasterAutoVol]=useState([]);// Gap 7: master volume automation [{time s, db}]
|
||||||
const[masterAutoOn,setMasterAutoOn]=useState(false);// Gap 7: automation active
|
const[masterAutoOn,setMasterAutoOn]=useState(false);// Gap 7: automation active
|
||||||
React.useEffect(()=>{window.__masterAutoVol=masterAutoVol;window.__masterAutoOn=masterAutoOn;},[masterAutoVol,masterAutoOn]);React.useEffect(()=>{if(isPlaying&&typeof applyMasterAutomationSchedule==='function'){try{applyMasterAutomationSchedule(currentTimeRef.current||0);}catch(e){console.warn('[Auto] reschedule error:',e);}}},[masterAutoVol,masterAutoOn,isPlaying]);const[masterVU,setMasterVU]=useState(0);// 0-1
|
React.useEffect(()=>{window.__masterAutoVol=masterAutoVol;window.__masterAutoOn=masterAutoOn;},[masterAutoVol,masterAutoOn]);React.useEffect(()=>{if(isPlaying&&typeof applyMasterAutomationSchedule==='function'){try{applyMasterAutomationSchedule(currentTimeRef.current||0);}catch(e){console.warn('[Auto] reschedule error:',e);}}},[masterAutoVol,masterAutoOn,isPlaying]);const[masterVU,setMasterVU]=useState(0);// 0-1
|
||||||
const[masterMeterPeak,setMasterMeterPeak]=useState(0);const[rightSidebarWidth,setRightSidebarWidth]=useState(320);const[tcpWidth,setTcpWidth]=useState(320);const[mediaExplorerHeight,setMediaExplorerHeight]=useState(50);const[panelPositions,setPanelPositions]=useState({export:'bottom',ai:'right',python_tools:'bottom',selection:'bottom',media_explorer:'bottom',fx_rack:'bottom',midi_events:'bottom'});const[panelDropZone,setPanelDropZone]=useState(null);const[dragGhostPos,setDragGhostPos]=useState(null);const[dragGhostPanel,setDragGhostPanel]=useState(null);const panelDragRef=useRef(null);const trackVuRefs=useRef({});const workspaceRef=useRef(null);const colResizerRef=useRef(null);const rowResizerRef=useRef(null);const[aiConfig,setAiConfig]=useState({baseUrl:localStorage.getItem('ai_base_url')||`${API_BASE_URL}`,apiKey:localStorage.getItem('ai_api_key')||'',model:localStorage.getItem('ai_model')||'deepseek-chat'});const[aiProviders,setAiProviders]=useState([]);useEffect(()=>{(async()=>{try{const data=await window.SonicAPI.getAIConfigs();if(data&&data.providers){setAiProviders(data.providers);const active=data.providers.find(p=>p.is_active)||data.providers[0];if(active)setSelectedProviderId(active.id);}}catch(e){/* server may not have config endpoint */}})();},[]);const[analysisState,setAnalysisState]=useState({status:'Sẵn sàng. Chạy AI để phân tích nhịp.',data:null,isRunning:false});const[aiPrompt,setAiPrompt]=useState('');const[aiComposeMode,setAiComposeMode]=useState('SIMILAR_VARIATION');const[promptHistory,setPromptHistory]=useState([]);const[promptHistIdx,setPromptHistIdx]=useState(-1);const promptHistRef=useRef([]);const aiPromptUndoRef=useRef({stack:[],idx:-1,max:30});const aiPromptUndoPush=text=>{const u=aiPromptUndoRef.current;u.stack.push(text);if(u.stack.length>u.max)u.stack.shift();u.idx=u.stack.length-1;};const[aiProvider,setAiProvider]=useState('OpenAI');const[aiModel,setAiModel]=useState('GPT-4o');const[aiActionLog,setAiActionLog]=useState([]);const actionLogContainerRef=useRef(null);useEffect(()=>{if(actionLogContainerRef.current){actionLogContainerRef.current.scrollTop=actionLogContainerRef.current.scrollHeight;}},[aiActionLog]);const[aiProcessing,setAiProcessing]=useState(false);const[aiSuggestions,setAiSuggestions]=useState([]);const[showAiTypeahead,setShowAiTypeahead]=useState(false);const[showAISuggestions,setShowAISuggestions]=useState(true);const[showAIActionLog,setShowAIActionLog]=useState(false);const aiPromptMgrRef=useRef(null);const aiTypeaheadRef=useRef(null);const[selectedProviderId,setSelectedProviderId]=useState('');const[exportSettings,setExportSettings]=useState({sampleRate:'44100',bitDepth:'float',format:'wav',source:'project',quality:'44khz',channels:'stereo',loop:false,loopBars:4,dither:false,normalize:false,normalizeTarget:'-1dbtp',monoCheck:true,// Gap 13: BWF/INFO metadata cho WAV mastering export
|
const[masterMeterPeak,setMasterMeterPeak]=useState(0);const[rightSidebarWidth,setRightSidebarWidth]=useState(320);const[tcpWidth,setTcpWidth]=useState(320);const[mediaExplorerHeight,setMediaExplorerHeight]=useState(50);const[panelPositions,setPanelPositions]=useState({export:'bottom',ai:'right',python_tools:'bottom',selection:'bottom',media_explorer:'bottom',fx_rack:'bottom',midi_events:'bottom'});const[panelDropZone,setPanelDropZone]=useState(null);const[dragGhostPos,setDragGhostPos]=useState(null);const[dragGhostPanel,setDragGhostPanel]=useState(null);const panelDragRef=useRef(null);const trackVuRefs=useRef({});const workspaceRef=useRef(null);const colResizerRef=useRef(null);const rowResizerRef=useRef(null);const[aiConfig,setAiConfig]=useState({baseUrl:localStorage.getItem('ai_base_url')||`${API_BASE_URL}`,apiKey:localStorage.getItem('ai_api_key')||'',model:localStorage.getItem('ai_model')||'deepseek-chat'});const[aiProviders,setAiProviders]=useState([]);useEffect(()=>{(async()=>{try{const data=await window.SonicAPI.getAIConfigs();if(data&&data.providers){setAiProviders(data.providers);const active=data.providers.find(p=>p.is_active)||data.providers[0];if(active)setSelectedProviderId(active.id);}}catch(e){/* server may not have config endpoint */}})();},[]);const[analysisState,setAnalysisState]=useState({status:'Sẵn sàng. Chạy AI để phân tích nhịp.',data:null,isRunning:false});const[aiPrompt,setAiPrompt]=useState('');const[aiComposeMode,setAiComposeMode]=useState('SIMILAR_VARIATION');const[promptHistory,setPromptHistory]=useState([]);const[promptHistIdx,setPromptHistIdx]=useState(-1);const promptHistRef=useRef([]);const aiPromptUndoRef=useRef({stack:[],idx:-1,max:30});const aiPromptUndoPush=text=>{const u=aiPromptUndoRef.current;u.stack.push(text);if(u.stack.length>u.max)u.stack.shift();u.idx=u.stack.length-1;};const[aiProvider,setAiProvider]=useState('OpenAI');const[aiModel,setAiModel]=useState('GPT-4o');const[aiActionLog,setAiActionLog]=useState([]);const actionLogContainerRef=useRef(null);useEffect(()=>{if(actionLogContainerRef.current){actionLogContainerRef.current.scrollTop=actionLogContainerRef.current.scrollHeight;}},[aiActionLog]);const[aiProcessing,setAiProcessing]=useState(false);const[aiSuggestions,setAiSuggestions]=useState([]);const[showAiTypeahead,setShowAiTypeahead]=useState(false);const[showAISuggestions,setShowAISuggestions]=useState(true);const[showAIActionLog,setShowAIActionLog]=useState(false);const aiPromptMgrRef=useRef(null);const aiTypeaheadRef=useRef(null);const[selectedProviderId,setSelectedProviderId]=useState('');const[exportSettings,setExportSettings]=useState({sampleRate:'44100',bitDepth:'float',format:'wav',source:'project',quality:'44khz',channels:'stereo',loop:false,loopBars:4,dither:false,normalize:true,normalizeTarget:'-14lufs',monoCheck:true,// Gap 13: BWF/INFO metadata cho WAV mastering export
|
||||||
metaTitle:'',metaArtist:'',metaIsrc:''});const[serverStatus,setServerStatus]=useState('checking...');const _lan=window.SonicRuntime&&window.SonicRuntime.capabilities&&window.SonicRuntime.capabilities.lan;const serverAddr=_lan&&_lan.urls&&_lan.urls[0]?function(){try{return new URL(_lan.urls[0]).host;}catch(e){return null;}}():window.location.host;const[menuOpen,setMenuOpen]=useState(null);const[selectedClipId,setSelectedClipId]=useState(null);// { trackId, clipId }
|
metaTitle:'',metaArtist:'',metaIsrc:''});const[serverStatus,setServerStatus]=useState('checking...');const _lan=window.SonicRuntime&&window.SonicRuntime.capabilities&&window.SonicRuntime.capabilities.lan;const serverAddr=_lan&&_lan.urls&&_lan.urls[0]?function(){try{return new URL(_lan.urls[0]).host;}catch(e){return null;}}():window.location.host;const[menuOpen,setMenuOpen]=useState(null);const[selectedClipId,setSelectedClipId]=useState(null);// { trackId, clipId }
|
||||||
const[stretchedClip,setStretchedClip]=useState(null);// { trackId, clipId, originalDuration, startTime, originalSpeed, beforeSnap }
|
const[stretchedClip,setStretchedClip]=useState(null);// { trackId, clipId, originalDuration, startTime, originalSpeed, beforeSnap }
|
||||||
const[draggedSectionItem,setDraggedSectionItem]=useState(null);const[resizedSectionItem,setResizedSectionItem]=useState(null);const[editingTrackName,setEditingTrackName]=useState(null);// trackId being edited
|
const[draggedSectionItem,setDraggedSectionItem]=useState(null);const[resizedSectionItem,setResizedSectionItem]=useState(null);const[editingTrackName,setEditingTrackName]=useState(null);// trackId being edited
|
||||||
@@ -1696,7 +1696,7 @@ fxRtTrackReconcile(trackId,node,track);}catch(e){console.warn('rebuildTrackFxGra
|
|||||||
// Cần activeTrackNodesRef/isPlayingRef. Session giống master (fxRtStart):
|
// Cần activeTrackNodesRef/isPlayingRef. Session giống master (fxRtStart):
|
||||||
// fetch start → AudioWorkletNode 'sf-fx-realtime' → WS; WS open → splice
|
// 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).
|
// 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,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
|
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=202608240831`);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;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==='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.
|
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;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==='set_param'){try{entry.ws.send(JSON.stringify({cmd:'set_param',slot:d.slot,key:d.key,value:d.value}));}catch(e){}return;}if(d.type!=='in')return;// Burst 4 block (1024 mẫu) → tách 4 WS frame 512 floats → bridge batch 4.
|
||||||
// Pace 1 burst/21ms (giống master) — tránh dồn frame sau stall làm tràn ring.
|
// 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){}}}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);fxRtTrackStop(trackId,path,true);}};const fxRtTrackUnsplice=(trackId,path)=>{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
|
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){}}}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);fxRtTrackStop(trackId,path,true);}};const fxRtTrackUnsplice=(trackId,path)=>{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
|
||||||
@@ -2065,7 +2065,7 @@ clientSideExport(exportTracks);}finally{setIsExporting(false);}}else{// Client-s
|
|||||||
clientSideExport(exportTracks,{loopStart,loopDur});}};// ── D4: Mastering render qua engine (D3 export stage) ──
|
clientSideExport(exportTracks,{loopStart,loopDur});}};// ── D4: Mastering render qua engine (D3 export stage) ──
|
||||||
// /api/v1/plugins/render — project schema + mastering chain qua native_bridge
|
// /api/v1/plugins/render — project schema + mastering chain qua native_bridge
|
||||||
// (VST3 masterbus), resample/normalize/dither PCM, mono side/mid check.
|
// (VST3 masterbus), resample/normalize/dither PCM, mono side/mid check.
|
||||||
const renderMasteringExport=async()=>{if(isExporting)return;if(serverStatus!=='connected'){showToast('Cần kết nối server để render mastering.','warning');return;}setIsExporting(true);try{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});const isFloat=exportSettings.bitDepth==='float';const res=await window.SonicAPI.renderProject(schema,'master_'+Date.now()+'.wav',{bit_depth:isFloat?32:parseInt(exportSettings.bitDepth)||16,sample_rate:parseInt(exportSettings.sampleRate)||44100,dither:!!exportSettings.dither,normalize:!!exportSettings.normalize,normalize_target:exportSettings.normalizeTarget||'-1dbtp',mono_check:!!exportSettings.monoCheck,metadata:{title:exportSettings.metaTitle||'',artist:exportSettings.metaArtist||'',isrc:exportSettings.metaIsrc||''}});_lastMasterStats={lufs:res.lufs,true_peak_db:res.true_peak_db};const lufsTxt=res.lufs!==null&&res.lufs!==undefined?res.lufs+' LUFS':'-- LUFS';const tpTxt=res.true_peak_db!==null&&res.true_peak_db!==undefined?res.true_peak_db+' dBTP':'-- dBTP';showToast(`Mastering xong — ${lufsTxt} / ${tpTxt}${res.mono_warning?' • '+res.mono_warning:''}`,'success','Tải về',async()=>{try{const br=await fetch(res.url);if(!br.ok)throw new Error('HTTP '+br.status);const b=await br.blob();const sp=await saveExportViaDialog((projectName||'Project')+'_master.wav',b);if(sp)showToast(`Đã lưu → ${sp}`,'success');}catch(e){const a=document.createElement('a');a.href=res.url;a.download='master.wav';a.click();}});}catch(e){showToast('Render mastering lỗi: '+(e.message||e),'error');}finally{setIsExporting(false);}};// ── Realtime Bounce Export (đầy đủ MIDI + FX Rack + Mastering) ──
|
const renderMasteringExport=async()=>{if(isExporting)return;if(serverStatus!=='connected'){showToast('Cần kết nối server để render mastering.','warning');return;}setIsExporting(true);try{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});const isFloat=exportSettings.bitDepth==='float';const outExt=exportSettings.format==='ogg'?'ogg':'wav';const res=await window.SonicAPI.renderProject(schema,'master_'+Date.now()+'.'+outExt,{bit_depth:isFloat?32:parseInt(exportSettings.bitDepth)||16,sample_rate:parseInt(exportSettings.sampleRate)||44100,dither:!!exportSettings.dither,normalize:!!exportSettings.normalize,normalize_target:exportSettings.normalizeTarget||'-1dbtp',mono_check:!!exportSettings.monoCheck,metadata:{title:exportSettings.metaTitle||'',artist:exportSettings.metaArtist||'',isrc:exportSettings.metaIsrc||''}});_lastMasterStats={lufs:res.lufs,true_peak_db:res.true_peak_db};const lufsTxt=res.lufs!==null&&res.lufs!==undefined?res.lufs+' LUFS':'-- LUFS';const tpTxt=res.true_peak_db!==null&&res.true_peak_db!==undefined?res.true_peak_db+' dBTP':'-- dBTP';showToast(`Mastering xong — ${lufsTxt} / ${tpTxt}${res.mono_warning?' • '+res.mono_warning:''}`,'success','Tải về',async()=>{try{const br=await fetch(res.url);if(!br.ok)throw new Error('HTTP '+br.status);const b=await br.blob();const sp=await saveExportViaDialog((projectName||'Project')+'_master.'+outExt,b);if(sp)showToast(`Đã lưu → ${sp}`,'success');}catch(e){const a=document.createElement('a');a.href=res.url;a.download='master.'+outExt;a.click();}});}catch(e){showToast('Render mastering lỗi: '+(e.message||e),'error');}finally{setIsExporting(false);}};// ── Realtime Bounce Export (đầy đủ MIDI + FX Rack + Mastering) ──
|
||||||
// MIDI/soundfont chạy qua FluidSynth (ScriptProcessor) — không render được
|
// MIDI/soundfont chạy qua FluidSynth (ScriptProcessor) — không render được
|
||||||
// trong OfflineAudioContext. Vì vậy bounce REALTIME: chạy lại toàn bộ project
|
// trong OfflineAudioContext. Vì vậy bounce REALTIME: chạy lại toàn bộ project
|
||||||
// (audio + MIDI + sections qua FX racks + mastering chain, đúng như nghe) và
|
// (audio + MIDI + sections qua FX racks + mastering chain, đúng như nghe) và
|
||||||
|
|||||||
@@ -51,7 +51,7 @@
|
|||||||
<script src="/static/js/services/promptTemplateManager.js?v=202607281039"></script>
|
<script src="/static/js/services/promptTemplateManager.js?v=202607281039"></script>
|
||||||
<script src="/static/js/services/undoRedoEngine.js?v=202607290941"></script>
|
<script src="/static/js/services/undoRedoEngine.js?v=202607290941"></script>
|
||||||
<script src="/static/js/services/chordTheory.js?v=202608211300"></script>
|
<script src="/static/js/services/chordTheory.js?v=202608211300"></script>
|
||||||
<script src="/static/js/app.precompiled.js?v=202608241200" defer></script>
|
<script src="/static/js/app.precompiled.js?v=202608240831" defer></script>
|
||||||
<link rel="stylesheet" href="/static/css/styles.css?v=202607271016">
|
<link rel="stylesheet" href="/static/css/styles.css?v=202607271016">
|
||||||
<style>
|
<style>
|
||||||
:root {
|
:root {
|
||||||
|
|||||||
@@ -1,14 +1,17 @@
|
|||||||
// Rebuild app.precompiled.js from app.jsx using @babel/standalone (avoids the
|
|
||||||
// Babel 8 ESM-only CLI conflict). Mirrors package.json's build script:
|
|
||||||
// babel app/static/js/app.jsx --config-file ./babel.config.json -o app/static/js/app.precompiled.js
|
|
||||||
import * as Babel from '@babel/standalone';
|
import * as Babel from '@babel/standalone';
|
||||||
import { readFileSync, writeFileSync } from 'fs';
|
import { readFileSync, writeFileSync } from 'fs';
|
||||||
|
|
||||||
|
// Cache-buster: argv[2] = 'yyyyMMddHHmm' (build_windows.ps1 truyen); mac dinh
|
||||||
|
// = thoi diem build. Stamp MOI URL asset (?v=) TRONG OUTPUT (khong sua source
|
||||||
|
// app.jsx) -> khong bao gio quen bump version sau khi rebuild bundle.
|
||||||
|
const ver = process.argv[2] || new Date().toISOString().replace(/\D/g, '').slice(0, 12);
|
||||||
|
|
||||||
const src = readFileSync('app/static/js/app.jsx', 'utf8');
|
const src = readFileSync('app/static/js/app.jsx', 'utf8');
|
||||||
const out = Babel.transform(src, {
|
const transformed = Babel.transform(src, {
|
||||||
presets: ['react'],
|
presets: ['react'],
|
||||||
filename: 'app.jsx',
|
filename: 'app.jsx',
|
||||||
sourceType: 'script',
|
sourceType: 'script',
|
||||||
}).code;
|
}).code;
|
||||||
|
const out = transformed.replace(/(sf-fx-realtime\.js\?v=)\d+/g, '$1' + ver);
|
||||||
writeFileSync('app/static/js/app.precompiled.js', out.replace(/\r?\n/g, '\r\n')); // repo CRLF
|
writeFileSync('app/static/js/app.precompiled.js', out.replace(/\r?\n/g, '\r\n')); // repo CRLF
|
||||||
console.log('BUILD OK', out.length, 'bytes');
|
console.log('BUILD OK', 'v=' + ver, out.length, 'bytes');
|
||||||
|
|||||||
+152
-76
@@ -1,95 +1,171 @@
|
|||||||
# build_windows.ps1 - ONE-COMMAND build: daw_engine.exe (PyInstaller) + Tauri v2 (NSIS + MSI)
|
# build_windows.ps1 - ONE-COMMAND build: frontend + native bridge + engine + Tauri (NSIS + MSI)
|
||||||
# Chay tren Windows: powershell -ExecutionPolicy Bypass -File build_windows.ps1
|
#
|
||||||
# LUU Y: file nay chi dung ky tu ASCII (khong dau, khong em-dash) - PowerShell 5.1
|
# powershell -ExecutionPolicy Bypass -File build_windows.ps1 # FULL (tat ca)
|
||||||
# doc .ps1 khong BOM theo ANSI, ky tu Unicode bi hong -> "String is missing terminator".
|
# powershell -ExecutionPolicy Bypass -File build_windows.ps1 -Frontend # chi bundle JS + sync static
|
||||||
|
# powershell -ExecutionPolicy Bypass -File build_windows.ps1 -Bridge # chi build native bridge + sync binaries
|
||||||
|
# powershell -ExecutionPolicy Bypass -File build_windows.ps1 -Engine # chi build engine + sync resources
|
||||||
|
# powershell -ExecutionPolicy Bypass -File build_windows.ps1 -Tauri # chi build installer Tauri
|
||||||
|
# ... -SkipPip -SkipNpm # bo qua cai dependency
|
||||||
|
#
|
||||||
|
# Moi mode TU DONG copy output vao dung vi tri (dist/, src-tauri/resources/,
|
||||||
|
# src-tauri/binaries/) va TU DONG bump cache-buster (?v=) -> khong the miss
|
||||||
|
# buoc copy nao du build theo cach nao. Bridge chi rebuild khi source moi hon.
|
||||||
|
# LUU Y: file nay chi dung ky tu ASCII (khong dau) - PowerShell 5.1 doc an toan.
|
||||||
|
param(
|
||||||
|
[switch]$Frontend,
|
||||||
|
[switch]$Bridge,
|
||||||
|
[switch]$Engine,
|
||||||
|
[switch]$Tauri,
|
||||||
|
[switch]$SkipPip,
|
||||||
|
[switch]$SkipNpm
|
||||||
|
)
|
||||||
|
|
||||||
$ErrorActionPreference = "Stop"
|
$ErrorActionPreference = "Stop"
|
||||||
Set-Location $PSScriptRoot
|
Set-Location $PSScriptRoot
|
||||||
|
|
||||||
# Kill moi daw_engine con song tu build/truoc (windowed, khong console ->
|
$any = $Frontend -or $Bridge -or $Engine -or $Tauri
|
||||||
# de quen -> file exe dang chay bi khoa -> Tauri build loi PermissionDenied
|
$doFrontend = $Frontend -or $Engine -or (-not $any) # Engine can bundle frontend moi truoc
|
||||||
# khi doc externalBin). Stop-Process im lang neu khong co tien trinh nao.
|
$doBridge = $Bridge -or (-not $any)
|
||||||
Write-Host "== [0/6] Kill daw_engine.exe cu (neu dang chay) =="
|
$doEngine = $Engine -or (-not $any)
|
||||||
Get-Process -Name "daw_engine" -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
|
$doTauri = $Tauri -or (-not $any)
|
||||||
Start-Sleep -Milliseconds 500
|
|
||||||
|
|
||||||
Write-Host "== [1/6] Python dependencies =="
|
$Stamp = Get-Date -Format "yyyyMMddHHmm"
|
||||||
python -m pip install --upgrade pip
|
|
||||||
python -m pip install -r requirements.txt pyinstaller pywin32
|
|
||||||
|
|
||||||
Write-Host "== [2/6] Frontend bundle (app.jsx -> app.precompiled.js) =="
|
function Fail([string]$msg) { Write-Host "ERROR: $msg" -ForegroundColor Red; exit 1 }
|
||||||
npm install
|
|
||||||
# Dam bao @babel/standalone co (build.mjs import truc tiep - da gap
|
|
||||||
# ERR_MODULE_NOT_FOUND tren may Windows khi package.json cu thieu dep).
|
|
||||||
if (-not (Test-Path "node_modules\@babel\standalone")) {
|
|
||||||
Write-Host "Thieu @babel/standalone - dang cai them..."
|
|
||||||
npm install @babel/standalone --no-audit --no-fund
|
|
||||||
}
|
|
||||||
if (-not (Test-Path "node_modules\@babel\standalone")) {
|
|
||||||
Write-Host "ERROR: Khong cai duoc @babel/standalone. Kiem tra ket noi npm!" -ForegroundColor Red
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
node build.mjs # @babel/standalone; thay cho 'npm run build' (Babel 8 ESM-only CLI conflict)
|
|
||||||
|
|
||||||
Write-Host "== [3/6] Build daw_engine.exe (PyInstaller) =="
|
if ($doEngine -or $doTauri) {
|
||||||
pyinstaller engine.spec --clean --noconfirm
|
Write-Host "== [0] Kill daw_engine.exe cu (neu dang chay - tranh khoa exe khi build) =="
|
||||||
|
Get-Process -Name "daw_engine" -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
|
||||||
Write-Host "== [3.5/6] Verify bundle contents (app/static, app/templates phai co) =="
|
Start-Sleep -Milliseconds 500
|
||||||
# Bat loi bundle NGAY tai build (da gap 2 lan: chay pyinstaller tu noi khac
|
|
||||||
# -> static/templates thieu -> exe crash 'Directory ...\app\static does not exist').
|
|
||||||
# Dung tools/verify_bundle.py (parse TOC bang ast, chap nhan ca / va \) thay
|
|
||||||
# vi regex thong thuong (TOC Windows co the dung backslash -> false positive).
|
|
||||||
# Truoc tien kiem tra engine.spec phai la ban moi (collect_data_files).
|
|
||||||
$specContent = Get-Content "engine.spec" -Raw -ErrorAction SilentlyContinue
|
|
||||||
if ($specContent -notmatch "collect_data_files\('app'") {
|
|
||||||
Write-Host "ERROR: engine.spec CU (thieu collect_data_files('app')). Pull code moi truoc khi build!" -ForegroundColor Red
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
python tools\verify_bundle.py
|
|
||||||
if ($LASTEXITCODE -ne 0) {
|
|
||||||
Write-Host "ERROR: Bundle thieu asset - dung build, kiem tra engine.spec datas!" -ForegroundColor Red
|
|
||||||
exit 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Write-Host "== [4/6] ONEDIR engine -> src-tauri/resources/daw_engine (Tauri resources) =="
|
# ---- [1] Frontend bundle + sync static -------------------------------------
|
||||||
# ONEDIR: copy ca thu muc dist\daw_engine\ (exe + _internal) vao resources.
|
if ($doFrontend) {
|
||||||
# Tauri bundle resources -> resource_dir()/daw_engine/daw_engine.exe luc runtime.
|
Write-Host "== [1] Frontend bundle (app.jsx -> app.precompiled.js, cache-buster v=$Stamp) =="
|
||||||
if (-not (Test-Path "dist\daw_engine\daw_engine.exe")) {
|
if (-not $SkipNpm) { npm install }
|
||||||
Write-Host "ERROR: dist\daw_engine\daw_engine.exe khong ton tai (onedir build loi?)" -ForegroundColor Red
|
if (-not (Test-Path "node_modules\@babel\standalone")) {
|
||||||
exit 1
|
Write-Host "Thieu @babel/standalone - dang cai them..."
|
||||||
}
|
npm install @babel/standalone --no-audit --no-fund
|
||||||
if (Test-Path "src-tauri\resources\daw_engine") {
|
}
|
||||||
Remove-Item -Recurse -Force "src-tauri\resources\daw_engine"
|
if (-not (Test-Path "node_modules\@babel\standalone")) { Fail "Khong cai duoc @babel/standalone. Kiem tra ket noi npm!" }
|
||||||
}
|
node build.mjs $Stamp
|
||||||
New-Item -ItemType Directory -Force "src-tauri\resources\daw_engine" | Out-Null
|
if ($LASTEXITCODE -ne 0) { Fail "build.mjs that bai" }
|
||||||
Copy-Item "dist\daw_engine\*" "src-tauri\resources\daw_engine\" -Recurse -Force
|
|
||||||
Write-Host "Copied onedir engine -> src-tauri\resources\daw_engine"
|
|
||||||
|
|
||||||
Write-Host "== [5/6] VC++ Redistributable cho hooks.nsh =="
|
# Stamp cache-buster vao index.html source (no-cache HTML, bundle ?v= phai moi)
|
||||||
if (-not (Test-Path src-tauri\vc_redist.x64.exe)) {
|
$idx = "app\templates\index.html"
|
||||||
Invoke-WebRequest -Uri "https://aka.ms/vs/17/release/vc_redist.x64.exe" -OutFile src-tauri\vc_redist.x64.exe
|
$utf8 = New-Object System.Text.UTF8Encoding($false)
|
||||||
|
$html = [IO.File]::ReadAllText($idx, $utf8)
|
||||||
|
[IO.File]::WriteAllText($idx, [regex]::Replace($html, "app\.precompiled\.js\?v=\d+", "app.precompiled.js?v=$Stamp"), $utf8)
|
||||||
|
|
||||||
|
# Sync 3 file static -> dist + src-tauri/resources (ban packaged engine doc tu day)
|
||||||
|
$pairs = @(
|
||||||
|
@("static\js\app.precompiled.js", "_internal\app\static\js\app.precompiled.js"),
|
||||||
|
@("static\js\sf-fx-realtime.js", "_internal\app\static\js\sf-fx-realtime.js"),
|
||||||
|
@("templates\index.html", "_internal\app\templates\index.html")
|
||||||
|
)
|
||||||
|
$roots = @("dist\daw_engine", "src-tauri\resources\daw_engine")
|
||||||
|
foreach ($p in $pairs) {
|
||||||
|
$src = Join-Path "app" $p[0]
|
||||||
|
foreach ($r in $roots) {
|
||||||
|
$dst = Join-Path $r $p[1]
|
||||||
|
New-Item -ItemType Directory -Force (Split-Path $dst) | Out-Null
|
||||||
|
Copy-Item $src $dst -Force
|
||||||
|
}
|
||||||
|
}
|
||||||
|
# Verify hash source == copy (bat loi "copy sai / thieu")
|
||||||
|
foreach ($p in $pairs) {
|
||||||
|
$srcHash = (Get-FileHash (Join-Path "app" $p[0]) -Algorithm SHA256).Hash
|
||||||
|
foreach ($r in $roots) {
|
||||||
|
$dst = Join-Path $r $p[1]
|
||||||
|
if (-not (Test-Path $dst)) { Fail "Thieu file sau sync: $dst" }
|
||||||
|
if ((Get-FileHash $dst -Algorithm SHA256).Hash -ne $srcHash) { Fail "Hash khac nhau sau sync: $dst" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Write-Host "Sync static OK (dist + src-tauri/resources)"
|
||||||
}
|
}
|
||||||
|
|
||||||
Write-Host "== [6/6] Tauri build (NSIS .exe + MSI) =="
|
# ---- [2] Native bridge (MSBuild Release x64) --------------------------------
|
||||||
# Guard: resources/daw_engine PHAI co exe + _internal truoc khi tauri build
|
if ($doBridge) {
|
||||||
# (glob trong tauri.conf.json fail ngay "path not found" neu thieu).
|
Write-Host "== [2] Native bridge (MSBuild Release x64 -> src-tauri/binaries) =="
|
||||||
if (-not (Test-Path "src-tauri\resources\daw_engine\daw_engine.exe")) {
|
$msbuildCandidates = @(
|
||||||
Write-Host "ERROR: src-tauri\resources\daw_engine\daw_engine.exe khong co - buoc [4/6] that bai?" -ForegroundColor Red
|
"${env:ProgramFiles(x86)}\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin\amd64\MSBuild.exe",
|
||||||
exit 1
|
"${env:ProgramFiles(x86)}\Microsoft Visual Studio\2022\BuildTools\MSBuild\Current\Bin\amd64\MSBuild.exe",
|
||||||
|
"${env:ProgramFiles(x86)}\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\amd64\MSBuild.exe",
|
||||||
|
"${env:ProgramFiles(x86)}\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\amd64\MSBuild.exe"
|
||||||
|
)
|
||||||
|
$msbuild = $msbuildCandidates | Where-Object { Test-Path $_ } | Select-Object -First 1
|
||||||
|
if (-not $msbuild) { Fail "Khong tim thay MSBuild.exe. Cai VS Build Tools 2019/2022 (workload C++) va chay CMake native_bridge truoc." }
|
||||||
|
|
||||||
|
foreach ($name in @("daw_vst_bridge", "fx_vst_bridge", "plugin_host")) {
|
||||||
|
$proj = "native_bridge\build\$name.vcxproj"
|
||||||
|
$exe = "native_bridge\build\Release\$name.exe"
|
||||||
|
if (-not (Test-Path $proj)) { Fail "Thieu project: $proj (can CMake native_bridge truoc)" }
|
||||||
|
$newest = Get-ChildItem -Path "native_bridge\src","native_bridge\include" -Recurse -Include *.cpp,*.h,*.hpp -ErrorAction SilentlyContinue |
|
||||||
|
Sort-Object LastWriteTime -Descending | Select-Object -First 1
|
||||||
|
$needBuild = $true
|
||||||
|
if ((Test-Path $exe) -and $newest) { $needBuild = $newest.LastWriteTime -gt (Get-Item $exe).LastWriteTime }
|
||||||
|
if ($needBuild) {
|
||||||
|
Write-Host "Build $name ..."
|
||||||
|
& $msbuild $proj "/p:Configuration=Release" "/p:Platform=x64" "/m" "/nologo" "/v:m"
|
||||||
|
if ($LASTEXITCODE -ne 0) { Fail "MSBuild $name that bai" }
|
||||||
|
} else {
|
||||||
|
Write-Host "Skip $name (exe moi nhat)"
|
||||||
|
}
|
||||||
|
if (-not (Test-Path $exe)) { Fail "Thieu output: $exe" }
|
||||||
|
Copy-Item $exe "src-tauri\binaries\$name.exe" -Force
|
||||||
|
Copy-Item $exe "src-tauri\binaries\$name-x86_64-pc-windows-msvc.exe" -Force
|
||||||
|
}
|
||||||
|
foreach ($dll in @("libfluidsynth-3.dll", "jpeg62.dll")) {
|
||||||
|
if (Test-Path "native_bridge\build\Release\$dll") {
|
||||||
|
Copy-Item "native_bridge\build\Release\$dll" "src-tauri\binaries\$dll" -Force
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Write-Host "Bridge OK -> src-tauri/binaries"
|
||||||
}
|
}
|
||||||
if (-not (Test-Path "src-tauri\resources\daw_engine\_internal")) {
|
|
||||||
Write-Host "ERROR: thieu src-tauri\resources\daw_engine\_internal (onedir khong day du)" -ForegroundColor Red
|
# ---- [3] Engine (PyInstaller) + sync resources ------------------------------
|
||||||
exit 1
|
if ($doEngine) {
|
||||||
|
Write-Host "== [3] Engine (PyInstaller onedir -> src-tauri/resources) =="
|
||||||
|
$specContent = Get-Content "engine.spec" -Raw -ErrorAction SilentlyContinue
|
||||||
|
if ($specContent -notmatch "collect_data_files\('app'") { Fail "engine.spec CU (thieu collect_data_files('app')). Pull code moi truoc khi build!" }
|
||||||
|
if (-not $SkipPip) {
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
python -m pip install -r requirements.txt pyinstaller pywin32
|
||||||
|
}
|
||||||
|
if (Test-Path "dist\daw_engine") { Remove-Item -Recurse -Force "dist\daw_engine" }
|
||||||
|
pyinstaller engine.spec --clean --noconfirm
|
||||||
|
if ($LASTEXITCODE -ne 0) { Fail "pyinstaller that bai" }
|
||||||
|
python tools\verify_bundle.py
|
||||||
|
if ($LASTEXITCODE -ne 0) { Fail "Bundle thieu asset - dung build, kiem tra engine.spec datas" }
|
||||||
|
if (-not (Test-Path "dist\daw_engine\daw_engine.exe")) { Fail "dist\daw_engine\daw_engine.exe khong ton tai (onedir build loi?)" }
|
||||||
|
if (Test-Path "src-tauri\resources\daw_engine") { Remove-Item -Recurse -Force "src-tauri\resources\daw_engine" }
|
||||||
|
New-Item -ItemType Directory -Force "src-tauri\resources\daw_engine" | Out-Null
|
||||||
|
Copy-Item "dist\daw_engine\*" "src-tauri\resources\daw_engine\" -Recurse -Force
|
||||||
|
Write-Host "Engine OK -> src-tauri/resources/daw_engine"
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---- [4] Tauri installer -----------------------------------------------------
|
||||||
|
if ($doTauri) {
|
||||||
|
Write-Host "== [4] VC++ Redistributable (cho hooks.nsh) =="
|
||||||
|
if (-not (Test-Path src-tauri\vc_redist.x64.exe)) {
|
||||||
|
Invoke-WebRequest -Uri "https://aka.ms/vs/17/release/vc_redist.x64.exe" -OutFile src-tauri\vc_redist.x64.exe
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host "== [5] Tauri build (NSIS + MSI) =="
|
||||||
|
if (-not (Test-Path "src-tauri\resources\daw_engine\daw_engine.exe")) { Fail "resources/daw_engine thieu - chay -Engine hoac full truoc" }
|
||||||
|
if (-not (Test-Path "src-tauri\resources\daw_engine\_internal")) { Fail "resources/daw_engine/_internal thieu (onedir khong day du)" }
|
||||||
|
foreach ($name in @("daw_vst_bridge", "fx_vst_bridge", "plugin_host")) {
|
||||||
|
if (-not (Test-Path "src-tauri\binaries\$name-x86_64-pc-windows-msvc.exe")) { Fail "Thieu src-tauri\binaries\$name-x86_64-pc-windows-msvc.exe - chay -Bridge truoc" }
|
||||||
|
}
|
||||||
|
if (-not $SkipNpm) { npm install -D @tauri-apps/cli }
|
||||||
|
npx tauri build
|
||||||
|
if ($LASTEXITCODE -ne 0) { Fail "tauri build that bai" }
|
||||||
}
|
}
|
||||||
npm install -D @tauri-apps/cli
|
|
||||||
npx tauri build
|
|
||||||
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host "== DONE =="
|
Write-Host "== DONE =="
|
||||||
Write-Host " NSIS: src-tauri\target\release\bundle\nsis\SonicForgeDAW_1.0.0_x64-setup.exe"
|
Write-Host " NSIS: src-tauri\target\release\bundle\nsis\SonicForgeDAW_1.0.0_x64-setup.exe"
|
||||||
Write-Host " MSI : src-tauri\target\release\bundle\msi\SonicForgeDAW_1.0.0_x64_en-US.msi"
|
Write-Host " MSI : src-tauri\target\release\bundle\msi\SonicForgeDAW_1.0.0_x64_en-US.msi"
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host "== XAC MINH SAU KHI CAI DAT (quan trong) =="
|
Write-Host "== XAC MINH SAU KHI CAI DAT =="
|
||||||
Write-Host " Mo %APPDATA%\SonicForgeDAW\logs\spawn.log - phai thay:"
|
Write-Host " Mo %APPDATA%\SonicForgeDAW\logs\spawn.log - phai thay [resource_dir/daw_engine (map layout)] ...exists=True"
|
||||||
Write-Host " [resource_dir/daw_engine (map layout)] ...exists=True"
|
|
||||||
Write-Host " Neu exists=False: bundle resources KHONG vao installer (chay lai buoc [4/6])."
|
|
||||||
Write-Host " Engine phai nam o: <thu muc cai dat>\daw_engine\daw_engine.exe"
|
|
||||||
|
|||||||
Reference in New Issue
Block a user